Skip to content

Commit 1b9c17c

Browse files
feat: add bounce number algorithm
1 parent 5c39e87 commit 1b9c17c

2 files changed

Lines changed: 79 additions & 0 deletions

File tree

‎Maths/BounceNumber.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @function isBounceNumber
3+
* @description A bounce number is a number whose digits are neither
4+
* entirely increasing nor entirely decreasing from left to right.
5+
* For example, 155349 is a bounce number.
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is a bounce number, false otherwise
8+
* @see https://projecteuler.net/problem=112
9+
* @example isBounceNumber(155349) => true
10+
* @example isBounceNumber(1234) => false
11+
* @example isBounceNumber(9876) => false
12+
*/
13+
const isBounceNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
const digits = String(n).split('').map(Number)
18+
if (digits.length === 1) return false
19+
let increasing = false
20+
let decreasing = false
21+
for (let i = 1; i < digits.length; i++) {
22+
if (digits[i] > digits[i - 1]) increasing = true
23+
if (digits[i] < digits[i - 1]) decreasing = true
24+
}
25+
return increasing && decreasing
26+
}
27+
28+
export { isBounceNumber }

‎Maths/test/BounceNumber.test.js‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { isBounceNumber } from '../BounceNumber.js'
2+
3+
describe('isBounceNumber', () => {
4+
test('155349 is a bounce number', () => {
5+
expect(isBounceNumber(155349)).toBe(true)
6+
})
7+
8+
test('121 is a bounce number', () => {
9+
expect(isBounceNumber(121)).toBe(true)
10+
})
11+
12+
test('1234 is NOT a bounce number (increasing)', () => {
13+
expect(isBounceNumber(1234)).toBe(false)
14+
})
15+
16+
test('9876 is NOT a bounce number (decreasing)', () => {
17+
expect(isBounceNumber(9876)).toBe(false)
18+
})
19+
20+
test('1111 is NOT a bounce number (all same)', () => {
21+
expect(isBounceNumber(1111)).toBe(false)
22+
})
23+
24+
test('single digit is NOT a bounce number', () => {
25+
expect(isBounceNumber(5)).toBe(false)
26+
})
27+
28+
test('132 is a bounce number', () => {
29+
expect(isBounceNumber(132)).toBe(true)
30+
})
31+
32+
test('321 is NOT a bounce number (decreasing)', () => {
33+
expect(isBounceNumber(321)).toBe(false)
34+
})
35+
36+
test('123454321 is a bounce number', () => {
37+
expect(isBounceNumber(123454321)).toBe(true)
38+
})
39+
40+
test('throws TypeError for zero', () => {
41+
expect(() => isBounceNumber(0)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for negative input', () => {
45+
expect(() => isBounceNumber(-121)).toThrow(TypeError)
46+
})
47+
48+
test('throws TypeError for float input', () => {
49+
expect(() => isBounceNumber(1.5)).toThrow(TypeError)
50+
})
51+
})

0 commit comments

Comments
 (0)