Best way to create a checkerboard

I've been contemplating the best way to create a checkerboard pattern, however I think that there may be a better solution (possibly using map or something?) - besides just hardcoding it. Does anyone have ideas?

fn main() {
    let mut out_arr = [[false; 8]; 8];
    for (y, x_arr) in out_arr.iter_mut().enumerate() {
        for (x, v) in x_arr.iter_mut().enumerate() {
            *v = (x+y)%2 != 0;
        }
    }
    println!("Hello, arr: {:#?}", out_arr);
}

Once that’s going to be stabilized, you’d be able to do

let out_arr: [[_; 8]; 8] = array::from_fn(|y| array::from_fn(|x| (x + y) % 2 != 0));

(playground)

2 Likes

If you like that, you could (for an even-sized checkerboard) use something like

let mut state = true;
let out_arr = [[(); 8]; 8].map(|line| {
    line.map(|_| {
        state = !state;
        state
    })
});

(playground)

Edit: For any size (even or odd), something like

let mut outer_state = false;
let out_arr = [[(); WIDTH]; HEIGHT].map(|line| {
    outer_state = !outer_state;
    let mut inner_state = outer_state;
    line.map(|_| {
        inner_state = !inner_state;
        inner_state
    })
});

will work, though that is getting lengthy.

How are we evaluating "best" here? For something like this I'd probably just go with the for-loop version because I feel it is more readable than the fancy version with closures.

That said... In terms of performance all implementations should be equivalent because the optimiser will look at your code, unroll the loops, recognise what you are trying to do, and store it in a hard-coded constant that gets copied into out_arr at runtime.

A common trick is to encode a 8x8 board as a u64, where each bit tells you whether a piece is present or not. In this form, an alternating checkerboard pattern looks like 0xAA55 repeated 4 times and considering it's a special case I'd probably just wrap the hard-coded constant up in a well-named constructor and move on.

This is my over-engineered version.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.