Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Logic Behind Division Stringified - Ruby
    What's the logic behind the condition: if (i + 1) % 3 == 0 ? Been seeing it in most solutions but I still can't see the logic behind it. I was able to answer this one with gsub but I wanted to understand this approach for future reference. Thanks! def DivisionStringified(n1,n2) n = (n1.to_f/n2.to_f).round arr = n.to_s.split("").reverse return "#{n.to_s}" if arr.length <= 3 n_with_commas = [] arr.each_with_index do |digit,i| n_with_commas << digit if (i + 1) % 3 == 0 n_with_commas << "," end end n_with_commas.reverse.join("") end # keep this function call here puts DivisionStringified(STDIN.gets)
    krissasantos posted this question on 7/15/16 | division, stringified, ruby, logic
    Answers
  • +
  • 2
  • -
  • they messed up my formatting... going to repost with code tags and see if it works. First of all his solution is wrong. It will add a comma at the beginning of any number with a length multiple of 3. e.g. ,100,000,000 or ,100,000 totally wrong.... But i'll explain the ( i + 1 ) % 3 == 0 anyways. So the tricky part about this question is that you need to place a comma every 3 numbers from the end of the number. So you reverse the number and pop in a comma every three places. Number: 100,000,000 or 10,000,000 Reversed Number: 000,000,001 000,000,01 Index: 012 345 678 012 345 67 Index + 1: 123 456 789 123 456 78 Obviously you need to loop through, but how do you place a comma every 3 numbers. If you add 1 to the loop-index of the number you can use the modulo operator to check if you have iterated 3 times. Notice the above shitty matrix. Normally your index is zero-based. But if you add 1, you can now check for multiples of 3. This will execute the if statement every three places. Number (reversed): 000 000 01 Index + 1: 123 456 78 (i+1)%3 == 0 executes: | | Result: 000,000,01 Reverse and return: 10,000,000 But yeah his solution is wrong because it will add a comma at the end if the length is a multiple of 3. Number (reversed): 000 000 001 Index + 1: 123 456 789 (i+1)%3 == 0 executes | | | Result: 000,000,001, Reverse and return: ,100,000,000 you could fix this by adding a conditional If ( i + 1 ) % 3 == 0 && ( i + 1 ) < reversedArray.length
    Log in to write an answer.