Иван обнови решението на 20.01.2014 06:15 (преди над 4 години)
+package main
+
+import "sync"
+
+type Mall struct {
+ table [4][4]rune
+ m sync.Mutex
+ log [][2][2]int
+}
+
+var wg sync.WaitGroup
+var currState Mall
+
+func playMall(mall [4][4]rune) [][2][2]int {
+ currState.log = [][2][2]int{}
+ currState.table = mall
+ for i := range currState.table {
+ for j := range currState.table[i] {
+ if currState.table[i][j] == 'X' {
+ wg.Add(1)
+ go goAround([2]int{i, j})
+ }
+ }
+ }
+ wg.Wait()
+ return currState.log
+}
+
+func abs(n int) int {
+ if n > 0 {
+ return n
+ } else {
+ return 4 + n
+ }
+}
+
+func goAround(person [2]int) {
+ var step [2][2]int
+ defer func() {
+ wg.Done()
+ }()
+ for i := 0; i < 100; i++ {
+ currState.m.Lock()
+ step[0] = person
+ if currState.table[abs(person[0]-1)%4][abs(person[1]-1)%4] == '-' {
+ currState.table[abs(person[0]-1)%4][abs(person[1]-1)%4] = 'X'
+ currState.table[person[0]][person[1]] = '-'
+ person[0] = abs(person[0]-1) % 4
+ person[1] = abs(person[1]-1) % 4
+ step[1] = person
+ } else if currState.table[(person[0]+1)%4][(person[1]+1)%4] == '-' {
+ currState.table[(person[0]+1)%4][(person[1]+1)%4] = 'X'
+ currState.table[person[0]][person[1]] = '-'
+ person[0] = (person[0] + 1) % 4
+ person[1] = (person[1] + 1) % 4
+ step[1] = person
+ } else if currState.table[(person[0]+1)%4][abs(person[1]-1)%4] == '-' {
+ currState.table[(person[0]+1)%4][abs(person[1]-1)%4] = 'X'
+ currState.table[person[0]][person[1]] = '-'
+ person[0] = (person[0] + 1) % 4
+ person[1] = abs(person[1]-1) % 4
+ step[1] = person
+ } else if currState.table[(person[0]+1)%4][abs(person[1]-1)%4] == '-' {
+ currState.table[abs(person[0]-1)%4][(person[1]+1)%4] = 'X'
+ currState.table[person[0]][person[1]] = '-'
+ person[0] = abs(person[0]-1) % 4
+ person[1] = (person[1] + 1) % 4
+ step[1] = person
+ } else {
+ step[1] = [2]int{-2, -2}
+ currState.log = append(currState.log, step)
+ currState.m.Unlock()
+ return
+ }
+ currState.log = append(currState.log, step)
+ currState.m.Unlock()
+ }
+ step[0] = person
+ step[1] = [2]int{-1, -1}
+ currState.m.Lock()
+ currState.log = append(currState.log, step)
+ currState.m.Unlock()
+}
Сериозно!? Четири еднакви блока код и бъг в един от тях по невнимание. Fix that :P