Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading