0
\$\begingroup\$

I have written a function for producing a 16 step array (note[16]), intended to generate two numbers (in this example 1 and 2) with the following conditions:

  • Any of the numbers can only be repeated once
  • The sequence is meant to wrap around, meaning that the above applies to the first and last number of the 16 elements

Here is the code, which works to the best of my knowledge:

void generateLoop() {
  //1. Replace numbers with 0 to indicate unfinished array
  for (int i = 0; i < 16; i++) {
    note[i] = 0;
  }

  //2. generate a 3 number sequence to make sure conditions are met
  for (int i = 0; i < 3; i++) {
    do {
      note[i] = random(1, 3);
    } while (i == 2 &&
         note[2] == note[1] &&
         note[2] == note[0]);
  }

  //3. shift every element right for as long as exclusion criteria are met
  while ((note[15] == 0 ||
         (note[15] == note[0] &&
          note[0] == note[1]))

         ||

         (note[15] == 0 ||
         (note[15] == note[14] &&
          note[15] == note[0]))) {

    for (int i = 15; 0 < i; i--) {
      note[i] = note[i - 1];
    }

    //4. Randomize new value to enter the number series, according to conditions for repetition
    do {
      note[0] = random(1, 3);
    } while (note[0] == note[1] &&
             note[0] == note[2]);
  }
}

I hope the code is fairly readable :). My question is, what code improvements do you see?

\$\endgroup\$
  • \$\begingroup\$ The code is very hard to read because it isn't indented correctly. \$\endgroup\$ – pacmaninbw Dec 9 '19 at 13:18
  • \$\begingroup\$ I'll see what i can do \$\endgroup\$ – Erik Dec 9 '19 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.