although filling an array with ints is rather easy I am stuck with the following problem:
I would like to fill an array with ints in a certain random range between for example 2-12 but I would also like to have not the same ints for any three successive indexes. So [4,5,4,8,11,5,10] would not be ok.
My current approach works to a certain extend but is not very ellegant and still fails sometimes for obvious reasons. As soon as my array holds more than two ints the if checks if any new int is the same as the two before the new one, if so it just does another Random.Range. Sure I could now just copy past that last if several times, but to my surprise I still sometimes get doublicates.
What am I missing?
Is there a more elegant sollution for a non programmer like me?
void Start() {
for (int i = 0; i < tile_last; i++) {
tile_stream[i] = Random.Range(2,tile_amount);
if (i > 2) {
int g = i - 2;
int h = i - 1;
tile_before_2 = tile_stream[g];
tile_before_1 = tile_stream[h];
tile_current = tile_stream[i];
if (tile_before_2 == tile_current || tile_before_1 == tile_current) {
tile_stream[i] = (Random.Range(1, tile_amount));
print("random_2");
}
if (tile_before_2 == tile_current || tile_before_1 == tile_current) {
tile_stream[i] = (Random.Range(1, tile_amount));
print("random_3");
}
if (tile_before_2 == tile_current || tile_before_1 == tile_current) {
tile_stream[i] = (Random.Range(1, tile_amount));
print("random_4");
}
}
}
}
Thanks Errorsatz and Brathnann for your quick replies.
In the end I went with Brahtnann´s variant, because for me it is easier to read and understand and just three lines Also it works like a charm.
void Start() {
for (int i = 0; i < tile_last; i++) {
tile_stream[i] = Random.Range(2,tile_amount);
if (i > 2) {
int g = i - 2;
int h = i - 1;
tile_before_2 = tile_stream[g];
tile_before_1 = tile_stream[h];
tile_current = tile_stream[i];
while (tile_stream[i] == tile_before_2 || tile_stream[i] == tile_before_1) {
tile_stream[i] = (Random.Range(1, tile_amount));
}
}
}
}