Skip to content

Commit b220cdd

Browse files
committed
Solve 'Find the smallest' kata
1 parent f3e4ca4 commit b220cdd

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

src/find-the-smallest/smallest.ts

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* https://www.codewars.com/kata/573992c724fc289553000e95/train/typescript
3+
*/
4+
export function smallest (n: number): number[] {
5+
return Result.potentialResults(n)
6+
.reduce(Result.min)
7+
.toArray()
8+
}
9+
10+
class Result {
11+
private constructor (
12+
private readonly value: number,
13+
private readonly i: number,
14+
private readonly j: number
15+
) {}
16+
17+
toArray (): number[] {
18+
return [this.value, this.i, this.j]
19+
}
20+
21+
static potentialResults (n: number): Result[] {
22+
const size = n.toString().length
23+
24+
return cartesianProduct(size)
25+
.map(({ i, j }) => {
26+
const value = moveDigit(n, i, j)
27+
return new Result(value, i, j)
28+
})
29+
}
30+
31+
static min (a: Result, b: Result): Result {
32+
return a.value <= b.value ? a : b
33+
}
34+
}
35+
36+
function cartesianProduct (a: number, b: number = a): Array<{ i: number, j: number }> {
37+
return intRange(0, a)
38+
.flatMap(i =>
39+
intRange(0, b)
40+
.map(j => ({ i, j }))
41+
)
42+
}
43+
44+
function intRange (start: number, end: number): number[] {
45+
const n = end - start + 1
46+
47+
return Array.from(Array(n).keys())
48+
.map(x => x + start)
49+
}
50+
51+
function moveDigit (n: number, i: number, j: number): number {
52+
const digits = n.toString().split('')
53+
54+
const digit = digits.splice(i, 1)[0]
55+
digits.splice(j, 0, digit)
56+
57+
return Number(digits.join(''))
58+
}
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { smallest } from '../../src/find-the-smallest/smallest'
2+
import chai, { assert } from 'chai'
3+
4+
chai.config.truncateThreshold = 0
5+
6+
describe('Fixed Tests smallest', function () {
7+
it('Basic tests', function () {
8+
assert.deepEqual(smallest(261235), [126235, 2, 0])
9+
assert.deepEqual(smallest(209917), [29917, 0, 1])
10+
assert.deepEqual(smallest(285365), [238565, 3, 1])
11+
assert.deepEqual(smallest(269045), [26945, 3, 0])
12+
assert.deepEqual(smallest(296837), [239687, 4, 1])
13+
})
14+
})

0 commit comments

Comments
 (0)