Skip to content

Instantly share code, notes, and snippets.

@j14159
Created July 13, 2017 21:32
Show Gist options
  • Save j14159/cb6ffa81d013c456c946d979672cb6bf to your computer and use it in GitHub Desktop.
Save j14159/cb6ffa81d013c456c946d979672cb6bf to your computer and use it in GitHub Desktop.
package main
type mesa struct {
height int
width int
}
type position struct {
x int
y int
direction string
}
type rover struct {
p position
}
func (r *rover) Move(m mesa) {
switch r.p.direction {
case "N":
if r.p.y+1 <= m.height {
r.p.y += 1
}
case "S":
if r.p.y-1 >= 0 {
r.p.y -= 1
}
case "E":
if r.p.x+1 <= m.width {
r.p.x += 1
}
case "W":
if r.p.x-1 >= 0 {
r.p.x -= 1
}
default:
break
}
}
package main
import (
"testing"
)
func TestForward(t *testing.T) {
m := mesa{10, 10}
atBottom := rover{position{5, 0, "S"}}
atBottom.Move(m)
if atBottom.p.y < 0 {
t.Error("Fell off the bottom")
}
atTop := rover{position{10, 0, "N"}}
atTop.Move(m)
if atTop.p.y > 10 {
t.Error("Fell of the top")
}
inMiddleE := rover{position{5, 5, "E"}}
inMiddleE.Move(m)
if inMiddleE.p.x != 6 {
t.Error("Why didn't you move East?")
}
inMiddleW := rover{position{5, 5, "W"}}
inMiddleW.Move(m)
if inMiddleW.p.x != 4 {
t.Error("Why didn't you move West? You're at", inMiddleW.p.x, inMiddleW.p.y)
}
}
func TestRepeated(t *testing.T) {
m := mesa{10, 10}
inMiddleE := rover{position{5, 5, "E"}}
moveTimes := func(r rover, times int) rover {
for i := 0; i < times; i++ {
r.Move(m)
}
return r
}
r2 := moveTimes(inMiddleE, 3)
if r2.p.x != 8 {
t.Error("Why didn't you move 3 right?", r2.p.x)
}
if inMiddleE.p.x != 5 {
t.Error("We mutated")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment