For Loop with Text Array

Hi there,

Am having some trouble figuring this exercise out. It’s a basic grid of text but I want the letters spread out across the rows and columns.

Right now all text from the array appears one on top of each other and not staggered as intended.

Here is the code. Would be really nice if someone could point me in the right direction. Been struggling since a few hours now. Thanks!

String[] myLetters = {"W", "0", "R", "D", "S"};

void setup() {
  size(800, 800);
  background(0);
  smooth();
}

void draw() {
  background(0);
  pushMatrix();
  translate(40, 40); //adjust position
  for (int k = 0; k < myLetters.length; ++k) {
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {        
        if ((i+j)%2==0) {
          fill(255, 0, 0);
        } else {
          fill(0);//fills black over alternating text
        }
        textSize(50);
        textAlign(CENTER, CENTER);
        text(myLetters[k], i*80, j*80);//what am i doing wrong over here??
      }
    }
  }
  popMatrix();
}
1 Like

Think about what these for loops are doing:

for (int k = 0; k < myLetters.length; ++k) {
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {        

You’re looping over every letter in your array, and then looping over every cell in your grid. In other words, you’re drawing every letter inside every cell.

My guess is you probably want to get rid of that first for loop, and calculate k based on the values of i and j for every cell instead.

1 Like

Trying this out as well but to no effect.
I think I’m now setting the cells up first and then drawing the letters to the various cells.
But, the issue persists of the letters not spreading out.

String[] myLetters = {"W", "0", "R", "D", "S"};

void setup() {
  size(800, 800);
  background(0);
  smooth();
}

void draw() {
  background(0);
  pushMatrix();
  translate(40, 40); //adjust position
  for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {        
      if ((i+j)%2==0) {
        fill(255, 0, 0);
      } else {
        fill(0);//fills black over alternating text
      }
      for (int k = 0; k < myLetters.length; ++k) {
        textSize(50);
        textAlign(CENTER, CENTER);
        text(myLetters[k], i*80, j*80);//what am i doing wrong over here??
      }
    }
  }
  popMatrix();
}

I don’t think you want to move the for (int k = 0; k < myLetters.length; ++k) { line to be inside your other for loops. I think you want to get rid of it entirely.

Take a step back and think about how you’d do this without a computer. For a given position i,j, how do you know which letter to draw?

1 Like