0

For my assignment I have to create the game 'memory'. I keep getting stuck on the part where I randomly give every card a color.

I first created this array

int rectColorArray[] ={BROWN, BROWN,WHITE, WHITE,RED, RED, GREEN, GREEN};

And made a loop in which I hoped it would only pick each color once.

void drawCards(int rectColor){
  int length = 50;
  int xPos =0;
  int yPos =0;
 
  for(int i = 7; i >= 0; i--){
    rectColor = rectColorArray[(int)random(0,rectColorArray.length)];
    fill(rectColor);
   rect(xPos,yPos, length, length); 
   xPos = xPos + length + 10;   
    splice(rectColorArray,i,1);
  }
}

it seems as if 'splice' doesn't do anything, because I keep getting rects that doesn't give the wanted output.

So my final question is: Does anyone know how to fix this problem, or if I should use another technique?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
ItsWard
  • 23
  • 4
  • 1
    This ain't [tag:javascript] and `{BROWN, BROWN,WHITE, WHITE,RED, RED, GREEN, GREEN}` does not create an array, but an object in JS. Is this [tag:java]? – Thomas Jan 02 '20 at 16:40
  • `I keep getting stuck on the part where I randomly give every card a color.` How about a different approach: shuffle the array of colors and then hand out the colors in order. – Thomas Jan 02 '20 at 16:48
  • Sorry, my mistake, I wrongly put the js tag. Retracted it. – Renat Jan 02 '20 at 16:54

1 Answers1

1

A very common solution to this sort of problem is to shuffle the source array, then simply use the shuffled items one at a time sequentially.

How can I shuffle an array?

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41