Skip to content

Commit cc16cbd

Browse files
authored
Added JugglerSequence.js (TheAlgorithms#1075)
1 parent a9e65cd commit cc16cbd

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Maths/JugglerSequence.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* Juggler Sequence: https://en.wikipedia.org/wiki/Juggler_sequence
3+
* function jugglerSequence
4+
* Juggler Sequence is a series of integer number in which the first term starts with a positive integer number n
5+
* and the remaining terms are generated from the immediate previous term using the recurrence relation
6+
* Produce Juggler Sequence using number n as the first term of the sequence and store in an array
7+
* Reference: https://www.geeksforgeeks.org/juggler-sequence/
8+
* jugglerSequence(3) // returns [3, 5, 11, 36, 6, 2, 1 ]
9+
* jugglerSequence(9) // returns [9, 27, 140, 11, 36, 6, 2, 1]
10+
* jugglerSequence(15) // returns [15, 58, 7, 18, 4, 2, 1]
11+
*/
12+
13+
function jugglerSequence (n) {
14+
const sequence = []
15+
sequence.push(n)
16+
// Calculate terms until last term is not 1
17+
while (n !== 1) {
18+
n = Math.floor(n ** ((n % 2) + 0.5))
19+
sequence.push(n)
20+
}
21+
return sequence
22+
}
23+
24+
export { jugglerSequence }

Maths/test/JugglerSequence.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { jugglerSequence } from '../JugglerSequence'
2+
3+
describe('Testing jugglerSequence function', () => {
4+
it('should return [3, 5, 11, 36, 6, 2, 1 ] if the number is 3', () => {
5+
expect(jugglerSequence(3)).toEqual(
6+
expect.arrayContaining([3, 5, 11, 36, 6, 2, 1])
7+
)
8+
})
9+
10+
it('should return [9, 27, 140, 11, 36, 6, 2, 1] if the number is 9', () => {
11+
expect(jugglerSequence(9)).toEqual(
12+
expect.arrayContaining([9, 27, 140, 11, 36, 6, 2, 1])
13+
)
14+
})
15+
16+
it('should return [15, 58, 7, 18, 4, 2, 1] if the number is 15', () => {
17+
expect(jugglerSequence(15)).toEqual(
18+
expect.arrayContaining([15, 58, 7, 18, 4, 2, 1])
19+
)
20+
})
21+
})

0 commit comments

Comments
 (0)