Write Up Code Wars — Word Mesh Solutions JavaScript

Handhika Yanuar Pratama
3 min readFeb 21, 2021

Code Wars is best platform for learning algorithm from programming language, here I want to write the solution for ‘Word Mesh’ challenge using JavaScript. When it was written, the challenge is still in kyu 6.

Question

You will be given an array of strings. The words in the array should mesh together where one or more letters at the end of one word will have the same letters (in the same order) as the next word in the array. But, there are times when all the words won't mesh.Examples of meshed words:"apply" and "plywood""apple" and "each""behemoth" and "mother"Examples of words that do not mesh:"apply" and "playground""apple" and "peggy""behemoth" and "mathematics"If all the words in the given array mesh together, then your code should return the meshed letters in a string. You won't know how many letters the meshed words have in common, but it will be at least one.If all the words don't mesh together, then your code should return "failed to mesh".Input: An array of strings. There will always be at least two words in the input array.Output: Either a string of letters that mesh the words together or the string "failed to mesh".

Example

#1:["allow", "lowering", "ringmaster", "terror"] --> "lowringter"
because:
the letters "low" in the first two words mesh together
the letters "ring" in the second and third word mesh together
the letters "ter" in the third and fourth words mesh together.
#2:["kingdom", "dominator", "notorious", "usual", "allegory"] --> "failed to mesh"
Although the words "dominator" and "notorious" share letters in the same order, the last letters of the first word don't mesh with the first letters of the second word.

This challenge is new type for me. I used to find the solutions first in google. What I found is we can solved this, by using match function. Later, I hope I can make article for that. So here is the solution that I found.

The most tricky part is in this line

let t=(arr[i]+" "+arr[i+1]).match(/(.+) \1/)

As we can see, by using the regular expressions in match. We can got the mesh word from the array. For example, I have an array like this.

console.log(wordMesh(["allow", "lowering", "ringmaster", "terror"]));

The answer is lowringter

To understand how it works, I try to log the output of t, and here is the output.

The match function given an array output. So by taking the first index from all array and concatenate in variable r, we got the answer lowringter . Another solution that I think the most clever is this.

Yeah, exactly I still newbie here and there so much things I don’t know yet. I hope this article can help you and eager you to never stop learning.

Have a Nice Code 😉

--

--