Day 5/30 Days of CodeWars: JavaScript Edition

nats_tech_notes

Nat's Tech Notes

Posted on July 5, 2022

Day 5/30 Days of CodeWars: JavaScript Edition

I'm back with more CodeWars katas! I took a break to focus on other things for a while, but now my mind is refreshed and ready to solve some more coding challenges.


CodeWars challenges solved
1) Sum of two lowest positive integers (7 kyu)
2) Ones and Zeros (7 kyu)
3) Shortest Word (7 kyu)


Kata 1: Sum of two lowest positive integers

Instructions

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.


Breaking down the problem with P.R.E.P.

Parameters
The function expects one parameter: an array of 4 or more
positive integers.

Returns
The function should return one value: the sum of the 2 lowest numbers in the array.

Examples
The following test cases are provided by CodeWars.

[5, 8, 12, 19, 22], 13
[15, 28, 4, 2, 43], 6
[3, 87, 45, 12, 7], 1
[23, 71, 33, 82, 1], 24
[52, 76, 14, 12, 4], 16
Enter fullscreen mode Exit fullscreen mode

The array is the parameter passed to the function and the number is the integer that should be returned from the function.

Pseudo code
See pseudo code section for each solution


Solution 1: Sorting the array

Pseudo code

1) Create a new array with sorted numbers from smallest to largest.
2) Return the sum of the first two numbers in the array.
Enter fullscreen mode Exit fullscreen mode

Solution

function sumTwoSmallestNumbers(numbers) {  
  const sortedNums = numbers.sort((a, b) => a - b);
  return sortedNums[0] + sortedNums[1];
}
Enter fullscreen mode Exit fullscreen mode

Notes

The .sort() array method - as the name suggests - sorts the elements of the array and returns the sorted array. It can receive an optional comparison function - like in the solution above - to sort the array in a specific manner. In this solution, passing it the comparison function of a - b will sort the numbers from lowest value to highest value.


Solution 2: Using array destructuring

This solution is similar to the one above but uses a different method of selecting the numbers inside the array called array destructuring. When working with arrays, it can be a very useful method to work with the elements inside the array.

function sumTwoSmallestNumbers(numbers) {  
  const [a, b] = numbers.sort((a, b) => a - b);
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Notes

Instead of declaring a variable storing the complete sorted array, a new array is declared holding only two values: a and b, which will automatically hold the values of the first two numbers in the sorted array.


Solution 3: One-liner

The following solution combines the two lines of code from solution 1 into a single line of code.

function sumTwoSmallestNumbers(numbers) {  
  return numbers.sort((a, b) => a - b)[0] + numbers[1];
}
Enter fullscreen mode Exit fullscreen mode

Notes

The .sort() array method does not actually make a copy of the array but mutates the original array. So instead of storing the sorted array in a new variable like in solution 1, the elements can be selected directly from the array passed to the argument once it has been sorted.


Kata 2: Ones and Zeros

Instructions

Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

Examples:

Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11
Enter fullscreen mode Exit fullscreen mode

However, the arrays can have varying lengths, not just limited to 4.


Breaking down the problem with P.R.E.P.

Parameters
The function expects one parameter: an array of ones and zeroes of any given length.

Returns
The function should return one value: the integer representation of the binary inside the array.

Examples
All test cases provided can be found in the instructions.

Pseudo code
See pseudo code section for each solution


Solution 1: Parsing a binary string

Pseudo code

1) Convert array to string.
2) Convert the string to an integer by parsing it.
3) Return the integer.
Enter fullscreen mode Exit fullscreen mode

Solution

const binaryArrayToNumber = arr => parseInt(arr.join(''), 2);
Enter fullscreen mode Exit fullscreen mode

Notes

1) Unlike the solutions from kata 1, all the solutions in this kata use the ES6 arrow function syntax.

2) The .join() array method is used to convert the array into a string. It concatenates the array elements into a string using either commas to separate the array values inside the string (default) or by using the separator specified inside the parenthesis. In this case all the numbers are joined together without a comma or any spaces between the numbers.

3) The parseInt() function receives two parameters: the string to parse and the radix that will be used for parsing - in our case 2 for binary.


Solution 2: Reducing the value with math

Pseudo code

1) Start with a sum (accumulator) value of 0.
2) Multiple the accumulator by 2 and add 1 each iteration of the loop.
3) Return the accumulated value.
Enter fullscreen mode Exit fullscreen mode

Solution

const binaryArrayToNumber = arr => {
  return arr.reduce((acc, cur) => acc * 2 + cur, 0);
}
Enter fullscreen mode Exit fullscreen mode

Notes

1) The .reduce() array method is used to "loop over" an array, executing a callback function on each element of the array. The callback function has access to both the current element in the array and the previous value, which is an accumulation of all the executed calculations combined (often called the accumulator). This sum or accumulator value can be passed a default value, which is specified after the comma (in this case the default value is 0).

2) Since the .()reduce method essentially loops over each item in the array, it takes more time to execute than the first solution, which has the same execution time regardless of the array length. While the difference in time will be rather small because of how fast execution time is nowadays, it is still something to take into account, especially when dealing with longer arrays. Solutions that can operate in constant time - meaning independent of the array length - are more favorable than solutions that take more time depending on array length.


No third solution for this kata will be provided. There are technically other ways to solve this challenge, but they are much more difficult to understand and/or have significant downsides, which make them less desirable as a solution.


Kata 3: Shortest Word

Instructions

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.


Breaking down the problem with P.R.E.P.

Parameters
The function expects one parameter: a string of words.

Returns
The function should return one value: the length of the shortest word in the string.

Examples
The following test cases are provided by CodeWars.

("bitcoin take over the world maybe who knows perhaps"), 3
("turns out random test cases are easier than writing basic ones"), 3
("Let's travel abroad shall we"), 2
Enter fullscreen mode Exit fullscreen mode

The string of words between the parenthesis is the string passed to the function, followed by the number that should be returned from the function.

Pseudo code
See pseudo code section for each solution


Solution 1: Using a for loop

Pseudo code

1) Create an array of the words contained in the string.
2) Declare a new variable with a value of the first word's length.
3) Loop over each word in the array. 
4) Check if word's length is smaller than the value of the variable.
5) If it is, set the word's length as the new value of the variable.
6) Return the variable's value.
Enter fullscreen mode Exit fullscreen mode

Solution

function findShort(s){
  const arr = s.split(' ');
  let shortest = arr[0].length;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].length < shortest) {
      shortest = arr[i].length;
    }
  }
  return shortest;
}
Enter fullscreen mode Exit fullscreen mode

Notes

The .split() array method is used to convert the string into an array of words. The string is split into substrings each time a space is encountered, which is not included in the substrings.


Solution 2: Sorting the words by word length

This solution uses a very similar approach as solution 3 of kata 1, except with one extra step (turning the string into an array) and the sorting is done based on word length.

Solution

function findShort(s){
  return s.split(' ')
          .sort((a, b) => a.length - b.length)[0].length;
}
Enter fullscreen mode Exit fullscreen mode

Notes

Just like in the 3rd solution of kata 1, the first element in the array is selected once the array has been sorted. We then get the length of that word since we don't want to return the word itself, but its length.


Solution 3: Finding the min in an array of word lengths

Pseudo code

1) Create an array of the words contained in the string.
2) Create another array containing the length of each word.
3) Find the lowest number in that array.
4) Return it.
Enter fullscreen mode Exit fullscreen mode

Solution

function findShort(s){
  return Math.min(...s.split(' ').map(word => word.length));
}
Enter fullscreen mode Exit fullscreen mode

Notes

1) The .map() array method is used to create a new array by looping over the original array and executing a function on each element inside the array. An arrow function is used in this solution, which can be read as for each word in the array, return the length of the word.

2) The Math.min() function receives numbers as its parameter and returns the number with the lowest value out of those numbers. The numbers passed to it have to be separated by a comma and cannot be contained inside an array.

3) The spread operator (...array) is used to turn the array of numbers into numbers that can be passed to the Math.min() function.


What solution did you implement?
What solution did you find the most elegant?
What solution did you have trouble understanding?

Let me know, I'd love to hear from you!

I hope you found this article helpful.


Connect with me on ...
Twitter
GitHub

💖 💪 🙅 🚩
nats_tech_notes
Nat's Tech Notes

Posted on July 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related