Search code examples
javascriptarraysstringalgorithmrun-length-encoding

I have a string with counts and alphabets in ordered manner i have to print the alphabets according to their count


var input = `2
6
z2k1o2
6
m2v1p2`

var newInput = input.split("\n")
//console.log(newInput.length)
var input_arr = input.trim().split("\n")
var n = Number(input_arr[0])
//console.log(input_arr)

for (var i = 1; i < input_arr.length; i = i + 2) {
  var length = Number(input_arr[i])
  var string = input_arr[i + 1].trim()

}
//console.log(string)

var newstring = string
//console.log(newstring)
var alpha = []
var num = []
for (i = 1; i < string.length; i += 2) {
  num.push(string[i])
}
var newnum = num.map(Number)
//console.log(newnum)

for (i = 0; i < string.length; i += 2) {
  alpha.push(string[i])
}
var newalpha = (alpha)
//console.log(newalpha)
var answer = []
for (i = 0; i < newnum.length; i++) {

  for (j = 0; j < newnum[i]; j++) {
    answer.push(newalpha[i])
  }
}

console.log(answer.join(""))

Here I'm getting only one output can you please explain why And do you like share any other approach for this problem.

This is the input z2k1o2 and the output should be zzkoo The input will follow this patter of alphabets ans counts..


Solution

  • I'd do this with a regular expression that captures pairs of (character, number) and uses the function-replacement mode of .replace() to generate the replacement string.

    > "a2b1c2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
    "aabcc"
    
    >"pos2es2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
    "possess"