Skip to content

Instantly share code, notes, and snippets.

@salizzar
Last active August 31, 2015 03:28
Show Gist options
  • Save salizzar/7f5187afb28e70fa1f0d to your computer and use it in GitHub Desktop.
Save salizzar/7f5187afb28e70fa1f0d to your computer and use it in GitHub Desktop.
A little ruby script to get sum of all digits reduced to one, given an array of random numbers between an interval.
random = Random.new
lower = 1000000000
upper = lower * 2 - 1
numbers = 10.times.collect { random.rand(lower..upper) }
summarizer = lambda do |number|
array = number.to_s.split("").collect(&:to_i)
array.inject { |sum, i| sum += i }
end
numbers.each do |number|
sum = total = summarizer.call(number)
stack = []
stack << number
stack << total
if sum < 10
stack << sum
else
new_sum = sum
loop do
new_sum = summarizer.call(new_sum)
stack << new_sum
break if new_sum < 10
end
end
puts stack.join(" - ")
end
@ricardotealdi
Copy link

Brincadeira com Ruby pra aliviar um pouco a correria.
Dá pra melhorar, mas é sexta-feira... dêem um desconto aí

Challenge accepted, lol

summarizer = ->(number) { number.to_s.chars.reduce(0) { |s, i| s + i.to_i } }

lower, upper = 1000000000, lower * 2 - 1

10.times.map { Random.rand(lower..upper) }.each do |number|
  stack = Array(number)
  stack << summarizer.(stack.last) while stack.last > 10
  puts stack.join(' - ')
end

I'm just kidding bro. I've just did it because I like to solve these challenges.

@salizzar
Copy link
Author

Muito bom! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment