-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
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
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
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 | ||
} |
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
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) | ||
} | ||
} | ||
} |