Intro 🌐
Problem solving is an important skill, for your career and your life in general.
That's why I take interesting katas of all levels, customize them and explain how to solve them.
Understanding the Exercise❗
First, we need to understand the exercise!
If you don't understand it, you can't solve it!.
My personal method:
- Input: What do I put in?
- Output: What do I want to get out?
Today's exercise
Today, another 7 kyu
kata,
meaning we slightly increase the difficulty.
Source: Codewars
Write a function missingValues
, that accepts one parameter: myArray
.
Given an array of number, e.g. [1, 1, 1, 2, 2, 3]
,
find:
- the number
x
, that appears once, e.g.3
- the number
y
, that appears twice, e.g.2
and return the product x * x * y
, e.g. 18
(=> 3 x 3 x 2
).
Input: an array of numbers.
Output: a number.
Thinking about the Solution 💭
I think I understand the exercise (= what I put into the function and what I want to get out of it).
Now, I need the specific steps to get from input to output.
I try to do this in small baby steps:
- Find the number that appears once,
x
- Find the number that appears twice,
y
- Return the product of
x * x * y
Example:
- Input:
[1, 1, 1, 2, 2, 3]
- Find the number that appears once,
x
:3
- Find the number that appears twice,
y
:2
- Return the product of
x * x * y
:18
(=>3 x 3 x 2
) - Output:
18
✅
Implementation ⛑
function missingValues(myArray) { // count amount of each number const count = myArray.reduce( (acc, cur) => acc.hasOwnProperty(cur) ? { ...acc, [cur]: acc[cur] + 1 } : { ...acc, [cur]: 1 }, {} ); // helper function to find the object key (= our number) that appears [amount] times const appears = (amount) => Object.entries(count) .filter(([key, value]) => value === amount) .map((entry) => entry[0]); return appears(1) * appears(1) * appears(2); }
Result
console.log([1, 1, 1, 2, 2, 3]); // 18 ✅ console.log([6, 5, 4, 100, 6, 5, 4, 100, 6, 5, 4, 200]); // 4000000 ✅
Playground ⚽
You can play around with the code here
Next Part ➡️
Great work!
We learned how to use reduce
, filter
, map
, hasOwnProperty
, Object.entries
.
I hope you can use your new learnings to solve problems more easily!
Next time, we'll solve another interesting kata. Stay tuned!
If I should solve a specific kata, shoot me a message here.
If you want to read my latest stuff, get in touch with me!
Further Reading 📖
Questions ❔
- How often do you do katas?
- Which implementation do you like more? Why?
- Any alternative solution?
Top comments (1)
This doesn't look like a very reasonable use of reduce.
I'd suggest starting with something like this.