DEV Community

Cover image for JavaScript Katas: Letterbox Paint Squad
miku86
miku86

Posted on

JavaScript Katas: Letterbox Paint Squad

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.


Today's exercise

Today, another 7 kyu kata,
meaning we slightly increase the difficulty.

Source: Codewars

You and a group of friends are earning some extra money by re-painting the numbers on people's letterboxes for a small fee.

Since there are 10 of you in the group, each person just paints one digit, e.g. somebody will paint only the 1's, somebody else will paint only the 2's and so on...

At the end of the day you realise not everybody did the same amount of work.

To avoid any fights you need to distribute the money fairly. That's where this Kata comes in.

Write a function paintLetterboxes, that accepts two parameter: start and end.

Given a start number, e.g. 125,
and an end number, e.g. 132,
return the frequency of all 10 digits painted,
e.g. [1, 9, 6, 3, 0, 1, 1, 1, 1, 1].

125: 1 x 1, 1 x 2, 1 x 5
126: 1 x 1, 1 x 2, 1 x 6
...
132: 1 x 1, 1 x 3, 1 x 2
Enter fullscreen mode Exit fullscreen mode

Input: two numbers.

Output: an array of numbers.


Thinking about the Solution 💭

First, we need to understand the exercise! If we don't understand it, we can't solve it!.

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:

  1. Create array with the number of every number between start and end
  2. Map each number into its split digits
  3. Reduce every number into one big array
  4. Create object with all numbers from 0 to 9
  5. Count every digit
  6. Return as array

Example:

  • Input: 125, 132
  • Create array with the number of every number between start and end: [125, 126, 127, 128, 129, 130, 131, 132]
  • Map each number into its split digits: [ [ '1', '2', '5' ], [ '1', '2', '6' ], ..., [ '1', '3', '2' ] ]
  • Reduce every number into one big array: [ '1', '2', '5', '1', '2', '6', ..., '1', '3', '2' ]
  • Create object with all numbers from 0 to 9: { '0': 0, '1': 0, ... , '9': 0 }
  • Count every digit: { '0': 1, '1': 9, ... , '9': 1 }
  • Return as array: [ 1, 9, 6, 3, 0, 1, 1, 1, 1, 1 ]
  • Output: [ 1, 9, 6, 3, 0, 1, 1, 1, 1, 1 ]

🥵


Implementation (Explicit) ⛑

function paintLetterboxes(start, end) {
  // create array with the number of every number between start and end
  // const array = [...Array(end - start + 1).keys()].map(i => i + start);
  const allNumbers = [...Array(end + 1).keys()].slice(start);

  // map each number into its split digits
  const splitIntoDigits = allNumbers.map((num) => String(num).split(""));

  // reduce every number into one big array
  // const allDigits = splitIntoDigits.reduce((acc, cur) => acc.concat(cur), []); // node < 11
  const allDigits = splitIntoDigits.flat();

  // create object with all numbers from 0 to 9
  const startObject = [...Array(10).keys()].reduce(
    (acc, cur) => ({ ...acc, [cur]: 0 }),
    {}
  );

  // count every digit
  const counted = allDigits.reduce(
    (acc, cur) => ({ ...acc, [cur]: acc[cur] + 1 }),
    startObject
  );

  // return as array
  const result = Object.entries(counted).reduce(
    (acc, cur) => [...acc, cur[1]],
    []
  );

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(paintLetterboxes(125, 132));
// [ 1, 9, 6, 3, 0, 1, 1, 1, 1, 1 ] ✅

console.log(paintLetterboxes(2, 4));
// [ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 ] ✅
Enter fullscreen mode Exit fullscreen mode

Implementation (Implicit) ⛑

function paintLetterboxes(start, end) {
  const startObject = [...Array(10).keys()].reduce(
    (acc, cur) => ({ ...acc, [cur]: 0 }),
    {}
  );
  const counted = [...Array(end + 1).keys()]
    .slice(start)
    .map((num) => String(num).split(""))
    .flat()
    .reduce((acc, cur) => ({ ...acc, [cur]: acc[cur] + 1 }), startObject);
  return Object.entries(counted).reduce((acc, cur) => [...acc, cur[1]], []);
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(paintLetterboxes(125, 132));
// [ 1, 9, 6, 3, 0, 1, 1, 1, 1, 1 ] ✅

console.log(paintLetterboxes(2, 4));
// [ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 ] ✅
Enter fullscreen mode Exit fullscreen mode

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work!

Probably, this solution is way too complicated, but it was fun!

We learned how to use ..., Array, keys, entries, slice, flat, map, reduce.

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 (3)

Collapse
 
kosich profile image
Kostia Palchyk • Edited

My turned-out-to-be-similar solution:

const paintLetterboxes = (start, end) =>
  Array(1 + end - start)
  .fill()
  .map((_, i) => start + i)
  .flatMap(n => n.toString().split(''))
  .reduce((a, c) => (a[c] += 1, a), Array(10).fill(0))

First time I actually used flatMap :)

-

Btw, IMHO, kata description in a code-box is not the best UX-wise because of additional scrolling...

maybe quotes would fit better?


or separators?


Collapse
 
miku86 profile image
miku86 • Edited

Hey Kostia,

yes, you are right,
will search for a better solution, thanks!

Collapse
 
lbermudez profile image
lbermudez

In my opinion the solutions proposes for wide ranges have a low performance respect to occupied memory in this steps:

[...Array(end + 1).keys()]
or
[...Array(end + 1)

Although the array is sliced after, but with this algorithms the memory is occupied unnecessarily. I think is better iterating with simple loop (start to end):

const paintLetterboxes = (start, end) => {
    const digits = Array(10).fill(0);
    for (let num = start; num <= end; num++)  {
        for (const d of String(num)) {
            digits[d] += 1;
        }
    }
    return digits;
}
Enter fullscreen mode Exit fullscreen mode

This with generator (only to freak out):

function* gen(start, end) {
    for (let num = start; num <= end; num++) yield num;
};

const paintLetterboxes = (start, end) => {
    const digits = Array(10).fill(0);
    for (const num of gen(start, end)) {
        for (const d of String(num)) {
            digits[d]++;
        }
    }
    return digits;
};
Enter fullscreen mode Exit fullscreen mode

In my opinion use functional programming to solve problems must be evaluated in performance terms because the abstraction can be hide low time or memory performance.