I’m trying to make a function that returns an array full of 0’s and 1’s. What I have to do is fill the array with zero’s, and then, in chunks of 6, I have to insert a 1, 2 or 3 (randomly chosen) at random locations/indeces in each chunk (so we can assume the length of the array is divisible by 6-no problem there). For example, if I have the array A[12]={0,0,0,0,0,0,0,0,0,0,0,0}, then because I have 12 elements, I have two “6-chunks.” If it was of length 18, I’d have 3 chunks, etc. After running this function, one time I might get A={0,1,0,0,0,0,0,0,0,3,0,0}, another time A={0,0,0,0,0,1,1,0,0,0,0,0}, then A={0,0,0,3,0,0,0,0,2,0,0,0}, etc. Note that the random non-zero number only shows up once in each chunk.
I know how to make an array filled with zero’s, and I know how to generate the numbers 1, 2, and 3 randomly. Here is my code that shows this:
int randNumber;
void setup(){
Serial.begin(9600);
randomSeed(analogRead(0));
generate_random_vector(120); //I want a vector of length 120
}
void loop() {
}
void generate_random_vector(int n){
int vector[n];
int i;
for (i=0; i<n; i++) {
vector[i]=0; //filling the vector with 0's
}
int j;
for (j=0; j<n; j++) {
Serial.println(vector[j]); //printing just to make sure it worked
}
randNumber = random(1, 4); //getting the random 1,2, or 3
Serial.println(randNumber);
}
Here are my problems:
- I cant figure out a way to insert each number at a random location in chunks of six. I also looked and I don’t think Arduino has a built in permutation function.
- The random function doesn’t seem to be generating each number with equal probability-I’m worried that I’m using it wrong.
- I’m having a problem just putting it all together
- I have no idea how to return arrays in Arduino
Can anyone help me make this function?