Given a list lst and a number N, create a new list that contains each number in lst at most N times without reordering.
For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], skip the next 1 and 2 because this would lead to those numbers being in the result more than N times. Finally, take 3, which leads to [1,2,3,1,2,3].
deleteNth([1,1,1,1],2) // return [1,1]
deleteNth([20,37,20,21],1) // return [20,37,21]
Tests
deleteNth([20,37,20,21], 1)
deleteNth([1,1,3,3,7,2,2,2,2], 3)
Good luck!
This challenge comes from JustyFY on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (12)
Just joined the community! I guess reducer is overkill here but still 🤷
Hmm... I wonder what happens if
deleteNthis invoked more than once :Phaha, you re right! Missed that one. Moved the obj initialisation inside the func.
JavaScript
Scala
Javascript Map:
Haskell:
Clojure
recur-based version, for comparison's sake:Java
JS solution
C++
std::vector deleteNth(const std::vector& lst, int n)
{
std::vector out;
std::map count;
for(auto i : lst)
{
if(count[i] < n)
{
count[i] = count[i] + 1;
out.push_pack(i);
}
}
return out;
}
TypeScript