Home > Enterprise >  Checkerboard pattern without x and y (purely based on index)
Checkerboard pattern without x and y (purely based on index)

Time:05-20

Is there a way to generate a checkerboard pattern without using nested for loops and without using x and y?

I'm sure this has already been done before, but I couldn't find it in the ~15mins I was looking for it.

Currently I have this function that generates the pattern first extracting x and y:

fn get_bg_color_of(idx: usize) -> &'static str {
    const BG_BLACK: &str = "\u{001b}[48;5;126m";
    const BG_WHITE: &str = "\u{001b}[48;5;145m";

    let x = idx % Board::WIDTH;
    let y = idx / Board::WIDTH;

    let is_even_row = y % 2 == 0;
    let is_even_column = x % 2 == 0;

    if is_even_row && is_even_column || !is_even_row && !is_even_column {
        return BG_WHITE;
    }

    BG_BLACK
}

Is there a simpler way to do this? If yes, please also explain how and why, I like to know what's happening in my code :)

CodePudding user response:

If WIDTH is even, then you need to separate x and y. You can write that shorter, though:

fn get_bg_color_of(idx: usize) -> &'static str {
    const BG_BLACK: &str = "\u{001b}[48;5;126m";
    const BG_WHITE: &str = "\u{001b}[48;5;145m";

    if ( (idx   (idx/Board::WIDTH)) % 2 == 0 ) {
        return BG_WHITE;
    }
    return BG_BLACK;
}

Note that this doesn't work if WIDTH is odd. In that case, you can just do:

    if ( idx % 2 == 0 ) {
        return BG_WHITE;
    }
}

If you need to handle both cases, then:

    if ( ((idx%Board::WIDTH)   (idx/Board::WIDTH)) % 2 == 0 ) {
        return BG_WHITE;
    }
  • Related