DEV Community

Cesar Del rio
Cesar Del rio

Posted on

#38 - Assemble string CodeWars Kata (6 kyu)

Instructions

Task
In this task, you need to restore a string from a list of its copies.

You will receive an array of strings. All of them are supposed to be the same as the original but, unfortunately, they were corrupted which means some of the characters were replaced with asterisks ("*").

You have to restore the original string based on non-corrupted information you have. If in some cases it is not possible to determine what the original character was, use "#" character as a special marker for that.

If the array is empty, then return an empty string.

Examples:

input = [
  "a*cde",
  "*bcde",
  "abc*e"
]
result = "abcde"


input = [
  "a*c**",
  "**cd*",
  "a*cd*"
]
result = "a#cd#"
Enter fullscreen mode Exit fullscreen mode

My solution:

function assembleString(arr){
  let r = []
  for(let i = 0; i<arr.length; i++){
    for(let j = 0; j<arr[i].length; j++){
      if(i==0) r.push(arr[i][j])
      if(r[j] == '*' || arr[i][j] !== '*') r[j] = arr[i][j]
    }
  }
  return r.map(x=>x=='*' ? '#' : x).join('')
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I made an empty array in the variable "r"

let r = []

Enter fullscreen mode Exit fullscreen mode

After that I used 2 for loops, the first one to iterate through arr, and then the other to iterate into every array inside of it that contained a word, inside of the second loop, first I checked if it is the first word array, I will push it as it is, so I can get it as a base for the other iterations, and I can start from something.

for(let i = 0; i<arr.length; i++){
    for(let j = 0; j<arr[i].length; j++){
      if(i==0) r.push(arr[i][j])
Enter fullscreen mode Exit fullscreen mode

After that I used another conditional that checked if the the element in "r" that is in the same index position we are iterating is a "" and the character that I'm iterating isn't a '' it means that we discovered another character, so I just change "*" to the correct character

if(r[j] == '*' || arr[i][j] !== '*') r[j] = arr[i][j]
Enter fullscreen mode Exit fullscreen mode

At the end I just returned the "r" array, that contained the last result, but first I mapped it to change every "*" to a "#" and to join it into an array

return r.map(x=>x=='*' ? '#' : x).join('')
Enter fullscreen mode Exit fullscreen mode

What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Discussion (0)