|
| 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 | +} |
0 commit comments