Mixing elements of array

I am a beginner. Not very much into programming.
I have an array before[]={1000, 0100, 0010, 0001}
I want to mix it in a random sequence each time i restart arduino,
for example {0001, 0100, 1000, 0010}
Can someone please help me?
Thanks in advance.

Are those binary values in that array? If so they will be interpreted as decimal values because you have not used the b prefix.

Look up in the reference the random function and use it to pick what value in the array you want.
Make sure to check out how to seed the random number generator.

2 Likes

Getting Arduino to do anything truly random is a little tricky. The random() function is really "pseudo-random" and will repeat the same sequence every time, unless you give it a randomised "seed".

One way to do that is by reading an unconnected analog pin. Another is, if the user presses a button, you can time the delay before the button is pressed or the length of the press and use that as a seed.

1 Like

If you don't implicitly specify the base (0x for hex, 0b for binary and nothing for decimal), then the elements of your array will be considered as decimal numbers like:

int before[] = {1000, 100, 10, 1};

So, what is the base of your array elements?

2 Likes

Hello
take some time and use a search engine of your choice and ask the WWW for a dice algorithm.

1 Like

Won't those that have a leading zero be interpreted as octal?

3 Likes

One way to randomise the array would be to perform a number of random swaps:

int before[]={1000, 0100, 0010, 0001};
byte lenbefore = sizeof(before)/sizeof(before[0]);
for (int s = 0; s < 100; s++) {
  int i = random(lenbefore);
  int j = random(lenbefore);
  int t = before[i];
  before[i] = before[j];
  before[j] = t;
  }
2 Likes

Meh

1 Like

Or, if you have a board with EEPROM, you could store the seed and increment it on every boot.

1 Like

Yes. The decimal equivalent is:
int before[] = {1000, 64, 8,1};

2 Likes

Thank you everyone

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.