Skip to content

Commit

Permalink
Merge 6bfd7a2 into 42784b0
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 5, 2019
2 parents 42784b0 + 6bfd7a2 commit 17f5d22
Show file tree
Hide file tree
Showing 3 changed files with 57 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)
25 changes: 25 additions & 0 deletions day225/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package day225

import "math/bits"

// JosephusGeneral is the general case solution.
func JosephusGeneral(n, k int) int {
switch {
case n < 1:
return 0
case n == 1:
return 1
case k == 2:
highestBitValue := 1 << uint(bits.Len64(uint64(n))-1)
return 2*(n-highestBitValue) + 1
default:
return josephusGeneral(n, k) + 1
}
}

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

import "testing"

var testcases = []struct {
n, k, survivor int
}{
{5, 2, 3},
{41, 2, 19},
{5, 3, 4},
{1, 100, 1},
{-20, 100, 0},
{0, 100, 0},
}

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 17f5d22

Please sign in to comment.