Chess board in one loop



  • Hi everyone, I'm putting some effort making basic exercises more challenging, right now I'm struggling with a chess board, I usually solve this with two loops and conditionals, but my challenge is to do it in one loop and with no conditionals, here is what I've done so far:

    side = 800
    newPage(side, side)
    square = side//8
    with savedState(): fill(1), rect(0, 0, side, side)
    y, advance = 0, 0
    while y < side:
        rect(square * (advance%2), y, square, square)
        rect(square * (advance%2) + square*2, y, square, square)
        rect(square * (advance%2) + square*4, y, square, square)
        rect(square * (advance%2) + square*6, y, square, square)
        y += square
        advance += 1
    

    Do you have any smarter idea to solve this coding challenge?
    Thanks!



  • I like a challenge. I’m not sure this is smarter, but it was fun to find something within your constraints.

    side = 800
    newPage(side, side)
    square = side / 8
    for i in range(64):
        x = i % 8
        y = int(i/8)
        fill((x+y) % 2)
        rect(x * square, y * square, square, square)
    


  • @monomonnik Wow! This is beautiful, thanks for taking your time making an approach, and also for sharing it. It makes sense how you solve it and gives me more ideas to make more challenges like this!



  • @eduairet Thanks, I had fun. Looking forward to more challenges 🙂


  • admin

    you could also use itertools.product to find all combinations of two lists.

    import itertools
    
    count = 10
    w = width() / count
    h = height() / count
    
    for x, y in itertools.product(range(count), range(count)):
        if (x+y) % 2:
            rect(x * w, y * h, w, h)
    


  • @monomonnik
    perfect place to use divmod.
    this:

    x = i % 8
    y = int(i/8)
    

    could be written like:

    x, y = divmod(i, 8)
    

    it will return the quotient (x) and the remainder (y).



  • @jo There’s so much I don’t know. 🙂 Thanks for the tip.



  • @jo Shouldn’t it be the other way around, though?

    y, x = divmod(i, 8)
    


  • @monomonnik
    yes and no.
    in the chessboard examples it does not really matter if you go by columns or by rows.
    but yes the first returned value is the quotient i//n or int(i/n) and the second returned value is the remainder (modulo) i % n.



  • @eduairet It was fun. It looks like there will be more challenges ahead.