'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:

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 1:[1]

You can find the sum of squared distances (as clarified in the comments) by using sum() and zip():

distance = sum([(elem1 - elem2)**2 for elem1, elem2 in zip(a1, a2)])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BrokenBenchmark