I'm writing a program that requires an array of scrambled numbers that don't repeat when given a maximum value. I've been searching on the internet for hours and every pice of code I find returns some hexidecimal value. Help?
heres some code I wrote after thinking about it more, but it still returns hexidecimal values. (im using xcode fyi) maybe its a problem with my compiler? all of the code makes sence...
The second "piece" (don't know what else to call it) is the condition. If the condition evaluates to true, then the for loop runs again. If it's false, then the for loop terminates and the program's control flow continues.
You want to use the amount of elements in the array (which is 5 in each).
1 2 3 4
for(int i = 0; i < 5; ++i) { // Loops through 5 times (i goes from 0 through 4)
bCheck[i] = false;
}
...
As far as I am aware, the way the loops were previously written, they would just loop on and on until there happens to be a 'zero' in memory location &var+i, i.e. for example this code:
1 2 3
for (int i = 0; bCheck[i]; i++) {
bCheck[i] = false;
}
loops until bCheck[i] is false, which is nothing to do with your program (it means the program will behave differently depending on what happens to be in memory around it...).
The condition that I use in my loops go untill there is an undefined value in the array. It works fine and I use it in my other programs without a problem.
The condition that I use in my loops go untill there is an undefined value in the array
Actually, it loops until you get a zero in the array. There is no "undefined" value. You will just keep going and going. You have loop until you hit whatever size you had for it:
1 2 3
for(unsignedint i = 0; i < array_size; ++i) {
std::cout<<array[i];
}
Thanks for the help on that front, but none of these things would do much to help this program work. Is there anything you guys can do to help? I've made some revisions, but now it returns 15104. I have no Idea why.
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstdlib>
#include <ctime>
// Write out a vector, one line per value.
void print(const std::vector<int>& v)
{
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));
}
// Generate a random sequence based on the size of the supplied vector.
void random_sequence(std::vector<int>& v)
{
// Generate sequence.
for (size_t i = 0; i < v.size(); i++)
{
v[i] = i;
}
// Randomize it.
std::random_shuffle(v.begin(), v.end());
}
int main()
{
std::srand(std::time(0)); // Initialize RNG.
std::vector<int> v(10); // Create a vector of 10 numbers.
random_sequence(v); // Create the random sequence.
print(v); // Write the random sequence.
return EXIT_SUCCESS;
}
If you really need to use arrays instead of vectors, then the code can be easily modified to use them.