Skip to content

Commit 483f181

Browse files
committed
feat: add new Josephus file in Recursive directory
1 parent ff314a2 commit 483f181

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

Diff for: Recursive/Josephus.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function Josephus
3+
* @description recursive implementation of the Josephus function.
4+
* @param {Integer[]} collection - The integer array.
5+
* @param {Integer} - The step size.
6+
* @return {Integer} - The last integer in the list.
7+
* @see [JosephusProblem](https://en.wikipedia.org/wiki/Josephus_problem)
8+
* @example [1,2,3,4,5,6,7] with step 3 = 4
9+
*/
10+
11+
const josephus = (collection, step) => {
12+
// return null for invalid steps that are less than or equal to 0
13+
if (step <= 0 || collection.length === 0) {
14+
return null
15+
}
16+
if (collection.length === 1) {
17+
return collection[0]
18+
} else {
19+
step = (step - 1) % collection.length
20+
collection.splice(step, 1)
21+
return josephus(collection, step + collection.length)
22+
}
23+
}
24+
25+
export { josephus }

Diff for: Recursive/test/Josephus.test.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { josephus } from '../Josephus'
2+
3+
describe('Josephus', () => {
4+
const collection = [1, 2, 3, 4, 5, 6, 7]
5+
const collection1 = [1]
6+
const collection2 = []
7+
8+
it('should return 4 for step size of 3', () => {
9+
const step = 3
10+
expect(josephus([...collection], step)).toBe(4)
11+
})
12+
13+
it('should return 4 for a step size of 10', () => {
14+
const step = 10
15+
expect(josephus([...collection], step)).toBe(4)
16+
})
17+
18+
it('should return null for a step size of 0 as it is invalid', () => {
19+
const step = 0
20+
expect(josephus([...collection], step)).toBeNull()
21+
})
22+
23+
it('should return 7 for a step size of 1000', () => {
24+
const step = 1000
25+
expect(josephus([...collection], step)).toBe(7)
26+
})
27+
28+
it('should return null for a step size of -1 as it is invalid', () => {
29+
const step = -1
30+
expect(josephus([...collection], step)).toBeNull()
31+
})
32+
it('should return 1 for a collection with just 1', () => {
33+
const step = 2
34+
expect(josephus([...collection1], step)).toBe(1)
35+
})
36+
it('should return null for an empty collection as it is invalid', () => {
37+
const step = 3
38+
expect(josephus([...collection2], step)).toBeNull()
39+
})
40+
})

0 commit comments

Comments
 (0)