Skip to content

Commit

Permalink
polish solution
Browse files Browse the repository at this point in the history
  • Loading branch information
rootulp committed Dec 1, 2023
1 parent 328ca6e commit 8bededb
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions go/queen-attack/queen_attack.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,50 +31,51 @@ func CanQueenAttack(whitePosition, blackPosition string) (bool, error) {
return white.canAttack(black), nil
}

func parse(position string) (location, error) {
func parse(position string) (coordinate, error) {
if len(position) != 2 {
return location{}, errors.New("invalid position")
return coordinate{}, errors.New("invalid position")
}

file := string(position[0])
row, err := strconv.Atoi(position[1:])
if err != nil || !isValidRow(row) || !isValidFile(file) {
return location{}, errors.New("invalid position")
return coordinate{}, errors.New("invalid position")
}
column := fileToColumn[file]

return location{row: row, column: column}, nil
return coordinate{row: row, column: column}, nil
}

func isValidRow(row int) bool {
return row >= 1 && row <= 8
}

func isValidFile(column string) bool {
return column >= "a" && column <= "h"
func isValidFile(file string) bool {
return file >= "a" && file <= "h"
}

type location struct {
type coordinate struct {
row int
column int
}

func (l location) canAttack(other location) bool {
return l.isSameRow(other) || l.isSameColumn(other) || l.isDiagonal(other)
func (c coordinate) canAttack(other coordinate) bool {
return c.isSameRow(other) || c.isSameColumn(other) || c.isDiagonal(other)
}

func (l location) isSameRow(other location) bool {
return l.row == other.row
func (c coordinate) isSameRow(other coordinate) bool {
return c.row == other.row
}

func (l location) isSameColumn(other location) bool {
return l.column == other.column
func (c coordinate) isSameColumn(other coordinate) bool {
return c.column == other.column
}

func (l location) isDiagonal(other location) bool {
return abs(l.row-other.row) == abs(l.column-other.column)
func (c coordinate) isDiagonal(other coordinate) bool {
return abs(c.row-other.row) == abs(c.column-other.column)
}

// abs returns the absolute value of x.
func abs(x int) int {
if x < 0 {
return -x
Expand Down

0 comments on commit 8bededb

Please sign in to comment.