Skip to content

Commit 030892d

Browse files
committed
findpos
1 parent 257968e commit 030892d

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

5_kyu/findpos.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
```

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ Solutions to CodeWars programming tasks. I try to update every day
165165
<td><a href=" "> </a></td>
166166
<td><a href="https://github.com/esadakman/javaScript-coding-challenges/blob/master/7_kyu/hasSurvived.md">hasSurvived</a></td>
167167
<td><a href="https://github.com/esadakman/javaScript-coding-challenges/blob/master/6_kyu/areaOfPolygonInsideCircle.md">areaOfPolygonInsideCircle</a></td>
168-
<td><a href="5 kyu "> </a></td>
168+
<td><a href="https://github.com/esadakman/javaScript-coding-challenges/blob/master/5_kyu/findpos.md">findpos</a></td>
169169
<td><a href="others "></a></td>
170170
</tr>
171171
<tr>

0 commit comments

Comments
 (0)