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, we'll have a look at our first 7 kyu
kata,
meaning we slightly increase the difficulty.
Source: Codewars
Write a function everyPossibleSum
, that accepts one parameter: myNumber
.
Given a number, e.g. 1234
,
return every possible sum of two digits, e.g. [ 3, 4, 5, 5, 6, 7 ]
.
For this example, we calculate:
[ 1 + 2, 1 + 3, 1 + 4, 2 + 3, 2 + 4, 3 + 4 ]
Input: a number.
Output: an array of numbers.
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:
- Get the single digits of the input number
- Go to the first digit and find all sums with each next digit, starting from the second
- Go to the second digit and find all sums with each next digit, starting from the third
- Do this for every digit
- Return the array with each sum in it
Example:
- Input:
1234
- Go to the first digit and find all sums with each next digit, starting from the second:
1 + 2
,1 + 3
,1 + 4
- Go to the second digit and find all sums with each next digit, starting from the third:
2 + 3
,2 + 4
- Do this for every digit:
3 + 4
- Return the array with each sum in it:
[ 3, 4, 5, 5, 6, 7 ]
- Output:
[ 3, 4, 5, 5, 6, 7 ]
β
Implementation β
function everyPossibleSum(myNumber) {
// split up number into its digits
const split = String(myNumber) // make it a string
.split("") // split it
.map((digit) => Number(digit)); // convert each split char to a number
const sums = [];
// first number: iterate from the first to the last number
for (let first = 0; first < split.length; first++) {
// second number: iterate from the next number after the current first number to the last number
for (let second = first + 1; second < split.length; second++) {
// save the sum in the sums array
sums.push(split[first] + split[second]);
}
}
return sums;
}
Result
console.log(everyPossibleSum(1234));
// [ 3, 4, 5, 5, 6, 7 ] β
console.log(everyPossibleSum(81596));
// [ 9, 13, 17, 14, 6, 10, 7, 14, 11, 15 ] β
Playground β½
You can play around with the code here
Next Part β‘οΈ
Great work!
We learned how to use String
, split
, map
, for
.
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 (0)