The solution of the chessboard problem

Hello my name is Igor! I'm a beginner developer and began to study the swift, I recently solved the problem of the chessboard. The task condition is - (Chessboard 8x8, each value in the range 1 ... 8. For two given values for vertical and horizontal, define the color of the field.If you want to complicate the task, then instead of digits on the horizontal axis, use the letters a, b, c, d, e, f, g, x). If it's not hard to see my code that I wrote and tell me correctly, I did and how can I reduce or improve it?


let a = 1

let b = 2

let c = 3

let d = 4

let e = 5

let f = 6

let g = 7

let h = 8



let x = d

let y = 4

let cellNumber = (y * x) // Calculate the cell number and color

let colorBlack = cellNumber



if cellNumber >= 1 && cellNumber <= 64 && colorBlack == cellNumber {

print("Cell color black")

} else {

print("Cell color white")

}

This does not work, it will always give "Cell color black":

let colorBlack = cellNumber

sets colorBlack to cellNumber


so when you test

if cellNumber >= 1 && cellNumber <= 64 && colorBlack == cellNumber

colorBlack == cellNumber is alsways true : you just test if cellNumber >= 1 && cellNumber <= 64


Your computation of cell number is wrong : for instance A2 and B1 are both cellnumber 2, but they are different cells.

A correct cell number is x + (y-1)*8

if the cell number is even (2, 4, 6, 8, 10, 12, 14, 16, 18…), it is a black cell, otherwise a white one (or the reverse, depending how you have set the checkboard)


I suppose you test in playground ?

A correct code should be:

        let x = 4
        let y = 4
        if x < 1 || x > 8 {
            print("wrong row")
        } else {
            if y < 1 || y > 8 {
                print("wrong column")
            } else {
                let cellNumber = x + (y-1)*8 
               
                if cellNumber % 2 == 0 {
                    print("Cell color black")
                } else {
                    print("Cell color white")
                }
            }
        }

For the fun, you could ask user to enter row and colum as C3 ; in your app, you should find the row (C) and colum (3), check they are

in correct range before finding the color.

Yes, I'm training in a playground. Thanks for the reply

Did this solve your problem ? If yes, don't forget to mark the thread as closed by clicking correct answer on the post with the solution.

The solution of the chessboard problem
 
 
Q