mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 21:14:43 +01:00
20201110: find lost number
This commit is contained in:
38
20201110_find_lost_number/main.go
Normal file
38
20201110_find_lost_number/main.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := rand.Intn(100)
|
||||
fmt.Println("r:", r)
|
||||
var src []int
|
||||
for i := 0; i < 100; i++ {
|
||||
if i == r {
|
||||
continue
|
||||
}
|
||||
src = append(src, i)
|
||||
}
|
||||
fmt.Println("lost number:", findLostNumber(src))
|
||||
fmt.Println("lost number2:", findLostNumber2(src))
|
||||
}
|
||||
|
||||
func findLostNumber(nums []int) int {
|
||||
sum := 0
|
||||
for _, n := range nums {
|
||||
sum += n
|
||||
}
|
||||
n := len(nums)
|
||||
return n*(n+1)/2 - sum
|
||||
}
|
||||
|
||||
func findLostNumber2(nums []int) int {
|
||||
res := 0
|
||||
for i, n := range nums {
|
||||
res = res ^ i ^ n
|
||||
}
|
||||
res = res ^ len(nums)
|
||||
return res
|
||||
}
|
||||
63
20201110_find_lost_number/main_test.go
Normal file
63
20201110_find_lost_number/main_test.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_findLostNumber(t *testing.T) {
|
||||
type args struct {
|
||||
nums []int
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want int
|
||||
}{
|
||||
{
|
||||
"example_1",
|
||||
args{[]int{3, 0, 1}},
|
||||
2,
|
||||
},
|
||||
{
|
||||
"example_2",
|
||||
args{[]int{9, 6, 4, 2, 3, 5, 7, 0, 1}},
|
||||
8,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := findLostNumber(tt.args.nums); got != tt.want {
|
||||
t.Errorf("findLostNumber() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_findLostNumber2(t *testing.T) {
|
||||
type args struct {
|
||||
nums []int
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want int
|
||||
}{
|
||||
{
|
||||
"example_1",
|
||||
args{[]int{3, 0, 1}},
|
||||
2,
|
||||
},
|
||||
{
|
||||
"example_2",
|
||||
args{[]int{9, 6, 4, 2, 3, 5, 7, 0, 1}},
|
||||
8,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := findLostNumber2(tt.args.nums); got != tt.want {
|
||||
t.Errorf("findLostNumber2() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user