Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Count the occurence of an interger in a string

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 334
    Comment on it

    Description:

    Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer.

    Example: countMe('1123') (count_me in Ruby)

    • Here 1 comes twice so <count><integer> will be "21"
    • then 2 comes once so <count><integer> will be "12"
    • then 3 comes once so <count><integer> will be "13"

    hence output string will be "211213".

    Similarly countMe('211213') will return '1221121113' (1 time 2, 2 times 1, 1 time 2, 1 time 1, 1 time 3)

    Return "" for empty, nil or non numeric strings

     

     

    Test Case:

    Test.expect(count_me('1123') == '211213')
    Test.expect(count_me('1') == '11')
    Test.expect(count_me('211213') == '1221121113')
    Test.expect(count_me('a123') == '')

     

    Solution:

    def count_me(data)
      return '' if data.to_i.to_s != data
      data_s = data.to_s
      count = 1
      output = ""
      
      i = 0
      while i < data_s.length - 1
        if data_s[i] == data_s[i + 1]
          count += 1
        else 
          output << count.to_s << data_s[i]
          count = 1
        end
        
        i += 1
      end
      
       output << count.to_s << data_s[i]
    end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: