0

I found a problem statement over the internet, was trying to solve it in ruby.

Input and output are self explanatory.

Eg. 1, Input : 2[abc]3[ab]c

Output : abcabcabcababababc

Explanation : 2 times abc and 3 times ab and then c

Eg. 2 Input : 2[3[a]b]

Output : aaabaaab

I tried this, But it doesn't work for multiple level.

num = 1
str = ""
"3[abc]4[ab]2[3[a]b]c".each_char do |ch|
  if ch.to_i != 0
    num = ch
  elsif ch == "["
    next
  elsif ch == "]"
    num.to_i.times { print str }
    str = ""
    num = 1
  else
    str << ch
  end
end

I was looking for recursive call.

2
  • 3
    "I was looking for recursive call" – you usually start with something that you can call like a method or proc. Commented Jan 6, 2021 at 18:04
  • I tried but was unable to find the solution. Commented Jan 7, 2021 at 17:33

1 Answer 1

1
str = "2[abc]3[ab]c2[de]fg"
str.gsub(/(\d+)\[(\p{L}+)\]/) { $2*$1.to_i }  
  #=> "abcabcabababcdedefg"
  #    ^^^^^^
  #          ^^^^^^
  #                 ^^^^

We can write the regular expression in free-spacing mode to make it self-documenting.

/
(\d+)     # match one or more digits, save to capture group 1 
\[        # match '[' 
(\p{L}+)  # match one or more letters, save to capture group 2
\]        # match ']'
/x        # invoke free-spacing regex definition mode

For the first match,

$1 #=> "2"
$2 #=> "abc"

so the block becomes

"abc"*2
  #=> "abcabc"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.