Generate random enum without consecutive repetition - c++

How do I generate random enum values without consecutive repetition?
enum keycode {
VK_LEFT = 75,
VK_UP = 72,
VK_RIGHT = 77,
VK_DOWN = 80
};
VK_LEFT, VK_DOWN, VK_UP, VK_RIGHT, VK_DOWN ...
and not
VK_LEFT, VK_DOWN, VK_UP, VK_UP, VK_RIGHT ...

Let's say your four values are 0, 1, 2, and 3.
Pick a random number N0 in {0, 1, 2, 3}.
Pick a random number N1 in {0, 1, 2, 3} \ {N0}.
Pick a random number N2 in {0, 1, 2, 3} \ {N1}.
Pick a random number N3 in {0, 1, 2, 3} \ {N2}.
And so on...

When you call the code that generates the random value from your enum, have it check the new random value against the last value selected. If they're equal, select another value.
This could be done in a while loop. Pseudocode:
keycode value;
while (value != lastChosen)
value = keycode[random.next];
lastChosen = value;
where lastChosen is the last selected value.

this will generate K non-repeating numbers between 1 and N:
vector<int> non_repeat(int K, int N)
{
vector<int> res;
int last = 1 + rand() % N;
res.push_back(last);
for(int i=1;i<K;++i)
{
int r = 1 + rand() % (N-1);
if(r>=last) ++r;
res.push_back(r);
last = r;
}
return res;
}
should be fairly easy to adopt to your need

Related

find minimum sum of non-neighbouring K entries inside an array

Given an integer array A of size N, find minimum sum of K non-neighboring entries (entries cant be adjacent to one another, for example, if K was 2, you cant add A[2], A[3] and call it minimum sum, even if it was, because those are adjacent/neighboring to one another), example:
A[] = {355, 46, 203, 140, 28}, k = 2, result would be 74 (46 + 28)
A[] = {9, 4, 0, 9, 14, 7, 1}, k = 3, result would be 10 (9 + 0 + 1)
The problem is somewhat similar to House Robber on leetcode, except instead of finding maximum sum of non-adjacent entries, we are tasked to find the minimum sum and with constraint K entries.
From my prespective, this is clearly a dynamic programming problem, so i tried to break down the problem recursively and implemented something like this:
#include <vector>
#include <iostream>
using namespace std;
int minimal_k(vector<int>& nums, int i, int k)
{
if (i == 0) return nums[0];
if (i < 0 || !k) return 0;
return min(minimal_k(nums, i - 2, k - 1) + nums[i], minimal_k(nums, i - 1, k));
}
int main()
{
// example above
vector<int> nums{9, 4, 0, 9, 14, 7, 1};
cout << minimal_k(nums, nums.size() - 1, 3);
// output is 4, wrong answer
}
This was my attempt at the solution, I have played around a lot with this but no luck, so what would be a solution to this problem?
This line:
if (i < 0 || !k) return 0;
If k is 0, you should probably return return 0. But if i < 0 or if the effective length of the array is less than k, you probably need to return a VERY LARGE value such that the summed result goes higher than any valid solution.
In my solution, I have the recursion return INT_MAX as a long long when recursing into an invalid subset or when k exceeds the remaining length.
And as with any of these dynamic programming and recursion problems, a cache of results so that you don't repeat the same recursive search will help out a bunch. This will speed things up by several orders of magnitude for very large input sets.
Here's my solution.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
// the "cache" is a map from offset to another map
// that tracks k to a final result.
typedef unordered_map<size_t, unordered_map<size_t, long long>> CACHE_MAP;
bool get_cache_result(const CACHE_MAP& cache, size_t offset, size_t k, long long& result);
void insert_into_cache(CACHE_MAP& cache, size_t offset, size_t k, long long result);
long long minimal_k_impl(const vector<int>& nums, size_t offset, size_t k, CACHE_MAP& cache)
{
long long result = INT_MAX;
size_t len = nums.size();
if (k == 0)
{
return 0;
}
if (offset >= len)
{
return INT_MAX; // exceeded array boundary, return INT_MAX
}
size_t effective_length = len - offset;
// If we have more k than remaining elements, return INT_MAX to indicate
// that this recursion is invalid
// you might be able to reduce to checking (effective_length/2+1 < k)
if ( (effective_length < k) || ((effective_length == k) && (k != 1)) )
{
return INT_MAX;
}
if (get_cache_result(cache, offset, k, result))
{
return result;
}
long long sum1 = nums[offset] + minimal_k_impl(nums, offset + 2, k - 1, cache);
long long sum2 = minimal_k_impl(nums, offset + 1, k, cache);
result = std::min(sum1, sum2);
insert_into_cache(cache, offset, k, result);
return result;
}
long long minimal_k(const vector<int>& nums, size_t k)
{
CACHE_MAP cache;
return minimal_k_impl(nums, 0, k, cache);
}
bool get_cache_result(const CACHE_MAP& cache, size_t offset, size_t k, long long& result)
{
// effectively this code does this:
// result = cache[offset][k]
bool ret = false;
auto itor1 = cache.find(offset);
if (itor1 != cache.end())
{
auto& inner_map = itor1->second;
auto itor2 = inner_map.find(k);
if (itor2 != inner_map.end())
{
ret = true;
result = itor2->second;
}
}
return ret;
}
void insert_into_cache(CACHE_MAP& cache, size_t offset, size_t k, long long result)
{
cache[offset][k] = result;
}
int main()
{
vector<int> nums1{ 355, 46, 203, 140, 28 };
vector<int> nums2{ 9, 4, 0, 9, 14, 7, 1 };
vector<int> nums3{8,6,7,5,3,0,9,5,5,5,1,2,9,-10};
long long result = minimal_k(nums1, 2);
std::cout << result << std::endl;
result = minimal_k(nums2, 3);
std::cout << result << std::endl;
result = minimal_k(nums3, 3);
std::cout << result << std::endl;
return 0;
}
It is core sorting related problem. To find sum of minimum k non adjacent elements requires minimum value elements to bring next to each other by sorting. Let's see this sorting approach,
Given input array = [9, 4, 0, 9, 14, 7, 1] and k = 3
Create another array which contains elements of input array with indexes as showed below,
[9, 0], [4, 1], [0, 2], [9, 3], [14, 4], [7, 5], [1, 6]
then sort this array.
Motive behind this element and index array is, after sorting information of index of each element will not be lost.
One more array is required to keep record of used indexes, so initial view of information after sorting is as showed below,
Element and Index array
..............................
| 0 | 1 | 4 | 7 | 9 | 9 | 14 |
..............................
2 6 1 5 3 0 4 <-- Index
Used index record array
..............................
| 0 | 0 | 0 | 0 | 0 | 0 | 0 |
..............................
0 1 2 3 4 5 6 <-- Index
In used index record array 0 (false) means element at this index is not included yet in minimum sum.
Front element of sorted array is minimum value element and we include it for minimum sum and update used index record array to indicate that this element is used, as showed below,
font element is 0 at index 2 and due to this set 1(true) at index 2 of used index record array showed below,
min sum = 0
Used index record array
..............................
| 0 | 0 | 1 | 0 | 0 | 0 | 0 |
..............................
0 1 2 3 4 5 6
iterate to next element in sorted array and as you can see above it is 1 and have index 6. To include 1 in minimum sum we have to find, is left or right adjacent element of 1 already used or not, so 1 has index 6 and it is last element in input array it means we only have to check if value of index 5 is already used or not, and this can be done by looking at used index record array, and as showed above usedIndexRerocd[5] = 0 so 1 can be considered for minimum sum. After using 1, state updated to following,
min sum = 0 + 1
Used index record array
..............................
| 0 | 0 | 1 | 0 | 0 | 0 | 1 |
..............................
0 1 2 3 4 5 6
than iterate to next element which is 4 at index 1 but this can not be considered because element at index 0 is already used, same happen with elements 7, 9 because these are at index 5, 3 respectively and adjacent to used elements.
Finally iterating to 9 at index = 0 and by looking at used index record array usedIndexRecordArray[1] = 0 and that's why 9 can be included in minimum sum and final state reached to following,
min sum = 0 + 1 + 9
Used index record array
..............................
| 1 | 0 | 1 | 0 | 0 | 0 | 1 |
..............................
0 1 2 3 4 5 6
Finally minimum sum = 10,
One of the Worst case scenario when input array is already sorted then at least 2*k - 1 elements have to be iterated to find minimum sum of non adjacent k elements as showed below
input array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and k = 4 then following highlighted elements shall be considered for minimum sum,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note: You have to include all input validation, like one of the validation is, if you want to find minimum sum of k non adjacent elements then input should have at least 2*k - 1 elements. I am not including these validations because i am aware of all input constraints of problem.
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
long minSumOfNonAdjacentKEntries(std::size_t k, const std::vector<int>& arr){
if(arr.size() < 2){
return 0;
}
std::vector<std::pair<int, std::size_t>> numIndexArr;
numIndexArr.reserve(arr.size());
for(std::size_t i = 0, arrSize = arr.size(); i < arrSize; ++i){
numIndexArr.emplace_back(arr[i], i);
}
std::sort(numIndexArr.begin(), numIndexArr.end(), [](const std::pair<int, std::size_t>& a,
const std::pair<int, std::size_t>& b){return a.first < b.first;});
long minSum = numIndexArr.front().first;
std::size_t elementCount = 1;
std::size_t lastIndex = arr.size() - 1;
std::vector<bool> usedIndexRecord(arr.size(), false);
usedIndexRecord[numIndexArr.front().second] = true;
for(std::vector<std::pair<int, std::size_t>>::const_iterator it = numIndexArr.cbegin() + 1,
endIt = numIndexArr.cend(); elementCount < k && endIt != it; ++it){
bool leftAdjacentElementUsed = (0 == it->second) ? false : usedIndexRecord[it->second - 1];
bool rightAdjacentElementUsed = (lastIndex == it->second) ? false : usedIndexRecord[it->second + 1];
if(!leftAdjacentElementUsed && !rightAdjacentElementUsed){
minSum += it->first;
++elementCount;
usedIndexRecord[it->second] = true;
}
}
return minSum;
}
int main(){
cout<< "k = 2, [355, 46, 203, 140, 28], min sum = "<< minSumOfNonAdjacentKEntries(2, {355, 46, 203, 140, 28})
<< '\n';
cout<< "k = 3, [9, 4, 0, 9, 14, 7, 1], min sum = "<< minSumOfNonAdjacentKEntries(3, {9, 4, 0, 9, 14, 7, 1})
<< '\n';
}
Output:
k = 2, [355, 46, 203, 140, 28], min sum = 74
k = 3, [9, 4, 0, 9, 14, 7, 1], min sum = 10

Remove the first smallest number in a vector in C++ (and keep the order)

I have an vector<int> number_vector that contains {1, 0, 0, 0, 0, 0 ,0}. I need to iterate over this number_vector, e.g 4 times, and remove the first smallest number at each iteration, i.e at the first iteration I will remove the value 0 at the index 1, at the next iteration I will remove the 0 that is at the index 1, etc. I'm doing this right now the following way:
int n = 7;
int d = 4;
vector<int> number_vector{1, 0, 0, 0, 0, 0 ,0};
for (int counter = 0; counter < n - d; counter++)
{
int index = distance(number_vector.begin(), min_element(number_vector.begin(), number_vector.end()));
if (index != number_vector.size() - 1)
{
number_vector[index] = move(number_vector.back());
}
number_vector.pop_back();
// number_vector.erase(number_vector.begin() + index);
}
The problem it's that if I run the code above, at the end number_vector has {1, 0, 0, 0} while it should have {1, 0, 0}, and for other cases like n = 4, d = 2 and number_vector{3, 7, 5, 9}, the final number_vector has the right value, that is 79. Some tips?
First of all you're iterating three times, not four. Secondly, if the vector isn't required, you can just use a map and pop the front iterator since it will always be the lowest value. Finally, there is no need for a swap or distance, just erase the result of min_element if it's not invalid.
When you iterate from 0 to n-d, with n=7 and d=4. you will iterate from counter=0 to counter < 7-4, i.e., 3. So your loop will iterate 3 times with values 0, 1 and 2. This will remove three zeros from number_vector. So your code is behaving as expected.
I think what you want is to iterate from 0 to d. Also you are unnecessarily complicating the code by using index. You can use the iterator directly like below.
for (int counter = 0; counter < d; counter++)
{
*min_element(number_vector.begin(), number_vector.end()) = *number_vector.rbegin();
number_vector.pop_back();
}
Is your d represents the times of pop minimum number from vector?
Then modify counter < n - d to counter < d, it will have {1, 0, 0}
11.04
if you want to keep the order,you can modify
for (int counter = 0; counter < d; ++counter)
{
auto iter = min_element(number_vector.begin(), number_vector.end());
number_vector.erase(iter);
}
PS:std::list maybe a better choice?

Max subarray with start and end index

I'm trying to find the maximum contiguous subarray with start and end index. The method I've adopted is divide-and-conquer, with O(nlogn) time complexity.
I have tested with several test cases, and the start and end index always work correctly. However, I found that if the array contains an odd-numbered of elements, the maximum sum is sometimes correct, sometimes incorrect(seemingly random). But for even cases, it is always correct. Here is my code:
int maxSubSeq(int A[], int n, int &s, int &e)
{
// s and e stands for start and end index respectively,
// and both are passed by reference
if(n == 1){
return A[0];
}
int sum = 0;
int midIndex = n / 2;
int maxLeftIndex = midIndex - 1;
int maxRightIndex = midIndex;
int leftMaxSubSeq = A[maxLeftIndex];
int rightMaxSubSeq = A[maxRightIndex];
int left = maxSubSeq(A, midIndex, s, e);
int right = maxSubSeq(A + midIndex, n - midIndex, s, e);
for(int i = midIndex - 1; i >= 0; i--){
sum += A[i];
if(sum > leftMaxSubSeq){
leftMaxSubSeq = sum;
s = i;
}
}
sum = 0;
for(int i = midIndex; i < n; i++){
sum += A[i];
if(sum > rightMaxSubSeq){
rightMaxSubSeq = sum;
e = i;
}
}
return max(max(leftMaxSubSeq + rightMaxSubSeq, left),right);
}
Below is two of the test cases I was working with, one has odd-numbered elements, one has even-numbered elements.
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
Edit: The following are the 2 kinds of outputs:
// TEST 1
Test file : T2-Data-1.txt
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
maxSubSeq : A[3..7] = 32769 // Index is correct, but sum should be 20
Test file : T2-Data-2.txt
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
maxSubSeq : A[9..17] = 39 // correct
// TEST 2
Test file : T2-Data-1.txt
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
maxSubSeq : A[3..7] = 20
Test file : T2-Data-2.txt
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
maxSubSeq : A[9..17] = 39
Can anyone point out why this is occurring? Thanks in advance!
Assuming that n is the correct size of your array (we see it being passed in as a parameter and later used to initialize midIndexbut we do not see its actual invocation and so must assume you're doing it correctly), the issue lies here:
int midIndex = n / 2;
In the case that your array has an odd number of elements, which we can represented as
n = 2k + 1
we can find that your middle index will always equate to
(2k + 1) / 2 = k + (1/2)
which means that for every integer, k, you'll always have half of an integer number added to k.
C++ doesn't round integers that receive floating-point numbers; it truncates. So while you'd expect k + 0.5 to round to k+1, you actually get k after truncation.
This means that, for example, when your array size is 11, midIndex is defined to be 5. Therefore, you need to adjust your code accordingly.

How can I order an array with duplicate values?

I want to order an array of stuffs that may have duplicates. For example:
int values[5] = {4, 5, 2, 5, -1};
int expected[5] = {1, 2, 0, 2, -1};
Here 2 is the smallest element so its order is 0. 4 is the 2nd smallest so its order is 1. 5 is the 3rd smallest and I want both of them have the order 2. I want to skip over certain elements (-1 in the above example) so these elements will have order -1.
How do I do this in C++ or describe an algorithm ?
Thanks
Just sort the array, then assign each element its rank:
vector<int> v(values, values + 5);
v.push_back(-1);
sort(begin(v), end(v));
v.resize(unique(begin(v), end(v)) - begin(v));
for (int i = 0; i < 5; ++i)
expected[i] = lower_bound(begin(v), end(v), values[i]) - begin(v) - 1;
This assumes that all the elements are non-negative or -1. If there are negative elements that are smaller than -1, you need to special case the -1.

Fill vector with random unique integers from a fixed pool of numbers

I want to fill a vector with random integers but there can't be duplicates in it.
First off, I have this code to put numberOfSlots random integers between 0 and 7 in the vector (numberOfSlots can be 2 to 20):
srand((unsigned int)time(NULL));
unsigned int min = 0;
unsigned int max = 7;
std::vector<unsigned int> v;
for (int i = 0; i < numberOfSlots; i++) {
unsigned int rdm = std::rand() % (max - min + 1) + min;
v.push_back(rdm);
}
This is the code for when duplicate integers are allowed. This is working fine!
Now I want to the change that code so that from the same random pool of possible integers (min to max) the generated random integer is only added if it's not already in the vector.
So if for example numberOfSlots is 5, then the vector will have 5 entries that were randomly chosen from the pool but are not the same, e.g. 7, 1, 3, 5, 0. If numberOfSlots is 8, the vector will be for example 3, 1, 2, 7, 6, 0, 4, 5.
I know how to shuffle the vector and stuff but I am not able to get this working. I think I have to use a while loop and check all already existing integers in the vector against the new random to be added number and if it's already in there generate a new random number and check again, etc. but I don't know
I am a beginner and this is really hard. Can someone maybe give me a hint? I would appreciate it... thank you so much
You can populate your vector with values 0..N-1 (or your pool values), and thereafter shuffle it. See example:
// Initialize
for(i = 0; i < N; i++)
arr[i] = i;
// shuffle
for(i = N - 1; i > 0; i--) {
j = rand() % i;
swap(arr[i], arr[j]);
}
I think your best bet is to create a vector to store the unrandomized integers, then another vector to store a randomized subset.
randomly chooose a number from your unrandomized integer vector, add that number to the randomized subset vector, then remove it from your unrandomized integer vector.
Now your unrandomized integer vector is one smaller, so randomly choose a number on the new smaller vector, add it to the randomized subset vector, and remove it from the unrandomized vector. Repeat.
Here's what it might look like
Unrandomized
{0, 1, 2, 3, 4, 5, 6, 7}
Randomized
{}
Choose random index: 5
Yields =>
Unrandomized
{0, 1, 2, 3, 5, 6, 7} //Removed 4 because it was at index #5
Randomized
{5}
Choose Random Index: 0
Yields =>
Unrandomized
{1, 2, 3, 5, 6, 7}
Randomized
{5, 0}
Choose Random Index: 6
Yields=>
Unrandommized
{1, 2, 3, 5, 6} // 7 removed at index #6
Randomized
{5, 0, 7}
And say you only have to pick do 3 random values here so you end up with 5, 0, 7. This method ensures no duplicates. I think there is an easier way using an inline function but I don't know it and the above should suffice.