Skip to content

Commit

Permalink
Merge 0a516b6 into 42784b0
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 4, 2019
2 parents 42784b0 + 0a516b6 commit 35a56ad
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,4 @@ problems from
* [Day 222](https://github.com/vaskoz/dailycodingproblem-go/issues/458)
* [Day 223](https://github.com/vaskoz/dailycodingproblem-go/issues/460)
* [Day 224](https://github.com/vaskoz/dailycodingproblem-go/issues/462)
* [Day 225](https://github.com/vaskoz/dailycodingproblem-go/issues/465)
24 changes: 24 additions & 0 deletions day225/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package day225

import "math/bits"

// JosephusGeneral is the general case solution.
func JosephusGeneral(n, k int) int {
if k == 2 {
return josephusGeneralK2(n)
}
return josephusGeneral(n, k) + 1
}

func josephusGeneralK2(n int) int {
highestBit := bits.Len64(uint64(n))
highestBit = 1 << uint(highestBit-1)
return 2*(n-highestBit) + 1
}

func josephusGeneral(n, k int) int {
if n == 1 {
return 0
}
return (josephusGeneral(n-1, k) + k) % n
}
28 changes: 28 additions & 0 deletions day225/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day225

import "testing"

var testcases = []struct {
n, k, survivor int
}{
{5, 2, 3},
{41, 2, 19},
{5, 3, 4},
}

func TestJosephusGeneral(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if survivor := JosephusGeneral(tc.n, tc.k); survivor != tc.survivor {
t.Errorf("Given N=%d, k=%d, expected %d, got %d", tc.n, tc.k, tc.survivor, survivor)
}
}
}

func BenchmarkJosephusGeneral(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
JosephusGeneral(tc.n, tc.k)
}
}
}

0 comments on commit 35a56ad

Please sign in to comment.