Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e4875d5

Browse files
author
Sandy
authored
Merge pull request #191 from openset/develop
Add: Fair Candy Swap
2 parents af042da + 5eaa5b8 commit e4875d5

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,19 @@
11
package fair_candy_swap
2+
3+
func fairCandySwap(A []int, B []int) []int {
4+
sA, sB := 0, 0
5+
mB := make(map[int]bool)
6+
for _, v := range A {
7+
sA += v
8+
}
9+
for _, v := range B {
10+
sB += v
11+
mB[v] = true
12+
}
13+
for _, x := range A {
14+
if mB[x+(sB-sA)/2] {
15+
return []int{x, x + (sB-sA)/2}
16+
}
17+
}
18+
return nil
19+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,48 @@
11
package fair_candy_swap
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
a []int
10+
b []int
11+
expected []int
12+
}
13+
14+
func TestFairCandySwap(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
a: []int{1, 1},
18+
b: []int{2, 2},
19+
expected: []int{1, 2},
20+
},
21+
{
22+
a: []int{1, 2},
23+
b: []int{2, 3},
24+
expected: []int{1, 2},
25+
},
26+
{
27+
a: []int{2},
28+
b: []int{1, 3},
29+
expected: []int{2, 3},
30+
},
31+
{
32+
a: []int{1, 2, 5},
33+
b: []int{2, 4},
34+
expected: []int{5, 4},
35+
},
36+
{
37+
a: []int{1, 2, 3},
38+
b: []int{11, 15, 17},
39+
expected: nil,
40+
},
41+
}
42+
for _, tc := range tests {
43+
output := fairCandySwap(tc.a, tc.b)
44+
if !reflect.DeepEqual(output, tc.expected) {
45+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.a, tc.b, output, tc.expected)
46+
}
47+
}
48+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /