Home > Software design >  How do I print a shuffled order of strings that never repeat? ARDUINO
How do I print a shuffled order of strings that never repeat? ARDUINO

Time:07-28

I'm trying to make a scramble generator for the rubik's cube, every letter corresponds to a move on the cube, but I don't want that two moves get printed next to each other, for example " R R U U2 L' " because that would make quite inefficient that scramble. I'll paste part of the code down below:

char a0[] = "R ";
char a1[] = "L' ";
char a2[] = "B' ";
char a3[] = "D2 ";
char a4[] = "F ";
char a5[] = "U2 ";
int moveA;

for (int i=0; i < 6; i  )
{
  moveA = random(0,5);
  if (moveA == 0)
    Serial.print(a0);
  else if (moveA == 1)
    Serial.print(a1);
  else if (moveA == 2)
    Serial.print(a2);
  else if (moveA == 3)
    Serial.print(a3);
  else if (moveA == 4)
    Serial.print(a4);
  else if (moveA == 5)
    Serial.print(a5);
  delay(200);

The output is usually something like

B' F D2 D2 R B' 
F2 D' D' F2 R2 R2 

CodePudding user response:

You can put the moves in an array and then shuffle the array:

const char *moves[] = {"R ", "L' ", "B' ", "D2 ", "F ", "U2 "};
const int num_moves = sizeof(moves) / sizeof(moves[0]);

// Shuffle
for (int i = num_moves - 1; i > 0; i--)
{
    // Random index 0 ≤ j ≤ i
    int j = random(0, i   1);
    // Swap
    const char *tmp = moves[i];
    moves[i] = moves[j];
    moves[j] = tmp;
}
for (int i = 0; i < num_moves; i  )
{
  Serial.print(moves[i]);
  delay(200);
}

See: Fisher–Yates shuffle

  • Related