title: Algorithm Challenge number formatting problem
body: <p>Invoice numbers are numeric only with any number of digits. To format one correctly, group the digits in group of three plus a group of any remainder, but never leave one digit by itself, unless it's a one digit number. Eg these are all correct formatting</p>
  <ul>
  <li><p>123</p>
  </li>
  <li><p>12-34</p>
  </li>
  <li><p>6</p>
  </li>
  <li><p>783-907-23-45</p>
  </li>
  </ul>
  <p>And these are not</p>
  <ul>
  <li>123-4</li>
  <li>98-456</li>
  </ul>
  <p>There's one more catch user input is passed directly to the function and you never know what characters users might type. Ignore any part of the input that is not digit</p>
  <p>Invoice.format_number should always return a string</p>
  <pre><code>module Invoice
    def self.format_number(str)
       return &quot;&quot;
    end
  end
  
  puts Invoice.format_number(&quot;ab1234&quot;)
   
  </code></pre>
  <p>What I have tried</p>
  <p>1st approach</p>
  <pre><code>arr = []
  str.chars.each do |elem|
    val = elem =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/
    arr &lt;&lt; elem if val == 0
  end
  
  num_of_digits = arr.length
  pairs_of_two = 0
  pairs_of_three = 0
  
  
  if num_of_digits &gt; 5
    while num_of_digits &gt; 0 do
      break if num_of_digits &lt;= 3
      if num_of_digits &gt;= 3 &amp;&amp; (num_of_digits % 3 == 0  || num_of_digits % 3 == 2)
        pairs_of_three += 1
        num_of_digits -= 3
      elsif num_of_digits % 2 == 0 || num_of_digits % 2 == 1
        pairs_of_two += 1
        num_of_digits -= 2
      end
    end
  end
  </code></pre>
  <p>2nd approach</p>
  <pre><code>arr = []
  str.chars.each do |elem|
    val = elem =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/
    arr &lt;&lt; elem if val == 0
  end
  
  len = arr.length - 1
  
  if arr.length &gt; 4
    str = &quot;&quot;
    i = 0
    while i &lt; len do 
      if arr[i..i+3].length == 4
        str &lt;&lt; arr[i..i+2].join + &quot;-&quot;
        i += 3
      elsif arr[i..i+2].length == 3
        str &lt;&lt; arr[i..i+1].join + &quot;-&quot;
        i += 2
      elsif arr[i..i+1].length == 2
        str &lt;&lt; arr[i..i+1].join
        i += 2
      elsif !arr[i].nil?
        str &lt;&lt; arr[i]
        i += 1
      end
    end
    puts str
  else
    if arr.length &lt;= 3
      puts arr.join
    else
      puts arr[0..1].join + &quot;-&quot; + arr[2..3].join
    end
  end
  </code></pre>
  <p>But none of them is correct</p>