From 2c35054f652f2d4bbf09867a871096f48e5c7af8 Mon Sep 17 00:00:00 2001 From: Scott Worley Date: Mon, 28 Dec 2015 17:35:41 -0800 Subject: [PATCH 1/1] Adjacent spaces --- sliding_tile.go | 30 +++++++++++++++++++++++++++++- sliding_tile_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/sliding_tile.go b/sliding_tile.go index 32bccae..96e00dc 100644 --- a/sliding_tile.go +++ b/sliding_tile.go @@ -5,11 +5,19 @@ import "os" import "strconv" const HOLE = 0 -const BOARD_SIZE = 16 +const BOARD_DIM = 4 +const BOARD_SIZE = BOARD_DIM * BOARD_DIM type Space int8 type Board [BOARD_SIZE]Space +const ( + LEFT = -1 + RIGHT = +1 + UP = -BOARD_DIM + DOWN = +BOARD_DIM +) + func read_board_from_strings(in []string) (*Board, error) { if len(in) != BOARD_SIZE { return nil, fmt.Errorf("Please provide %d values", BOARD_SIZE) @@ -25,6 +33,26 @@ func read_board_from_strings(in []string) (*Board, error) { return &b, nil } +func adjacent_spaces(s Space) []Space { + if s < 0 || s >= BOARD_SIZE { + panic("Invalid space") + } + var adjacent []Space + if s >= BOARD_DIM { + adjacent = append(adjacent, s+UP) + } + if s < BOARD_SIZE-BOARD_DIM { + adjacent = append(adjacent, s+DOWN) + } + if s%BOARD_DIM != 0 { + adjacent = append(adjacent, s+LEFT) + } + if s%BOARD_DIM != BOARD_DIM-1 { + adjacent = append(adjacent, s+RIGHT) + } + return adjacent +} + func main() { start, err := read_board_from_strings(os.Args[1:]) if err != nil { diff --git a/sliding_tile_test.go b/sliding_tile_test.go index 28392ee..34f3fcc 100644 --- a/sliding_tile_test.go +++ b/sliding_tile_test.go @@ -1,5 +1,7 @@ package main +import "reflect" +import "sort" import "testing" func Test_read_board_from_strings(t *testing.T) { @@ -26,3 +28,43 @@ func Test_read_board_from_strings(t *testing.T) { t.Fail() } } + +// For sorting, for unordered equality testing +type Spaces []Space + +func (s Spaces) Len() int { return len(s) } +func (s Spaces) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s Spaces) Less(i, j int) bool { return s[i] < s[j] } + +func Test_adjacent_spaces(t *testing.T) { + type TestCase struct { + s Space + expected Spaces + } + cases := []TestCase{ + {0, []Space{1, 4}}, + {1, []Space{0, 2, 5}}, + {2, []Space{1, 3, 6}}, + {3, []Space{2, 7}}, + {4, []Space{0, 5, 8}}, + {5, []Space{1, 4, 6, 9}}, + {6, []Space{2, 5, 7, 10}}, + {7, []Space{3, 6, 11}}, + {8, []Space{4, 9, 12}}, + {9, []Space{5, 8, 10, 13}}, + {10, []Space{6, 9, 11, 14}}, + {11, []Space{7, 10, 15}}, + {12, []Space{8, 13}}, + {13, []Space{9, 12, 14}}, + {14, []Space{10, 13, 15}}, + {15, []Space{11, 14}}, + } + for i, c := range cases { + var actual Spaces = adjacent_spaces(c.s) + sort.Sort(c.expected) + sort.Sort(actual) + if !reflect.DeepEqual(c.expected, actual) { + t.Error(i, c.expected, actual) + } + } +} -- 2.44.1