|
| 1 | +## [Find Position in Sequence](https://www.codewars.com/kata/660323a44fe3e41cff41e4e9) |
| 2 | + |
| 3 | +- Given an increasing sequence where each element is an integer composed of digits from a given set `t`. |
| 4 | + |
| 5 | +- For example, if `t = { 1, 5 }`, the sequence would be: `1, 5, 11, 15, 51, 55, 111, 115, ...` |
| 6 | + |
| 7 | +- Another example, `if t = { 4, 0, 2 }`, the sequence would be: `0, 2, 4, 20, 22, 24, 40, 42, ...` |
| 8 | + |
| 9 | + |
| 10 | +#### Task |
| 11 | +In this kata, you need to implement a function `findpos(n, t)` that receives a integer `n` and a table/set `t` representing the set of digits, and returns the position of `n` in the sequence. |
| 12 | + |
| 13 | +```js |
| 14 | +findpos(11, { 1 }) --> 2 |
| 15 | +findpos(55, { 1, 5 }) --> 6 |
| 16 | +findpos(42, { 4, 0, 2 }) --> 8 |
| 17 | +findpos(1337, { 1, 3, 7 }) --> 54 |
| 18 | +findpos(123456789, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }) --> 123456790 |
| 19 | +``` |
| 20 | +#### Note |
| 21 | +- The integer `n` will always be in the sequence. |
| 22 | +#### Solution: |
| 23 | + |
| 24 | +```javascript |
| 25 | +function findpos(n, t) { |
| 26 | + // Determine the modifier based on whether 0 is in the set |
| 27 | + const modifier = t.has(0) ? 1 : 0; |
| 28 | + |
| 29 | + // Create a map to store the order of each digit in the set |
| 30 | + const orderMap = new Map([...t].sort((a, b) => a - b).map((number, index) => [number.toString(), index + 1 - modifier])); |
| 31 | + |
| 32 | + // Calculate the position of n in the sequence |
| 33 | + return n.toString() |
| 34 | + .split("") |
| 35 | + .reduceRight((acc, number, place, { length }) => { |
| 36 | + return acc + orderMap.get(number) * t.size ** (length - place - 1); |
| 37 | + }, 0 + modifier); |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +// Examples |
| 42 | +console.log(findpos(11, new Set([1]))); // Output: 2 |
| 43 | +console.log(findpos(55, new Set([1, 5]))); // Output: 6 |
| 44 | + |
| 45 | +``` |
0 commit comments