Last active
July 28, 2022 08:43
-
-
Save LinuxSuRen/415047a7355c8e3bbd24fd0c533a8559 to your computer and use it in GitHub Desktop.
猴子选大王
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
count := 10 | |
fmt.Printf("there are %d monkeys\n", count) | |
index := selectKing(count) | |
fmt.Println("the king is", index) | |
} | |
type monkey struct { | |
id int // the orignal id | |
} | |
func selectKing(count int) (index int) { | |
monkeys := []monkey{} | |
for i := 1; i <= count; i++ { | |
monkeys = append(monkeys, monkey{id: i}) | |
} | |
fmt.Println("start to select") | |
monkey := cutByNumber(3, monkeys) | |
index = monkey.id | |
return | |
} | |
// let's assume the number is 3 | |
func cutByNumber(num int, monkeys []monkey) (m monkey) { | |
number := 1 | |
for i := 0; len(monkeys) > 1; { | |
if i == len(monkeys) { | |
i = 0 | |
} | |
if number == num { | |
number = 1 | |
if i+1 > len(monkeys) { | |
monkeys = monkeys[0:i] | |
} else { | |
monkeys = append(monkeys[0:i], monkeys[i+1:]...) | |
} | |
} else { | |
number = number + 1 | |
i++ | |
} | |
} | |
m = monkeys[0] | |
return | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "testing" | |
func Test_selectKing(t *testing.T) { | |
type args struct { | |
count int | |
} | |
tests := []struct { | |
name string | |
args args | |
wantIndex int | |
}{{ | |
args: args{count: 10}, | |
wantIndex: 4, | |
}, { | |
args: args{count: 8}, | |
wantIndex: 7, | |
}, { | |
args: args{count: 12}, | |
wantIndex: 10, | |
}} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
if gotIndex := selectKing(tt.args.count); gotIndex != tt.wantIndex { | |
t.Errorf("selectKing() = %v, want %v", gotIndex, tt.wantIndex) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment