Skip to content

Instantly share code, notes, and snippets.

@syntacticsugar
Created March 20, 2013 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syntacticsugar/5202245 to your computer and use it in GitHub Desktop.
Save syntacticsugar/5202245 to your computer and use it in GitHub Desktop.
# goal: get a number like 25164150 # and transform it to: 25,164,150
# goal: get a number like 25164150
# and transform it to: 25,164,150
# =begin
# 1) number.to_s.split("").length
# 2) start from end, count multiples of 3
# 3) insert comma
# 4) turn array back into a string
# .join(",")
# x.unshift(",")unless (x % 3 != 0)
# =end
# number = 11 223 344 556
kazu = [1,1,2,2,3,3,4,4,5,5,6]
# goal = 11,223,344,556
bloated = kazu.reverse.join.split("") # yields array of many strings
threes = 0.upto(kazu.length).find_all { |index| (index % 3).zero? }[1..-1]
# threes --> [3,6,9] # these are the comma-relevent indices
print "the solution is: \n"
puts bloated[threes.last..-1].reverse.join + "," + threes.map { |n| (n-3)..(n-1)}.map {|r| bloated[r]}.map(&:join).join(',').reverse
# STABBY LAMBDA TIME!!!!!!!!!!!
commify = ->(n) {
bloated = n.to_s.reverse.split("")
threes = 0.upto(n.to_s.split("").length).find_all { |index| (index % 3).zero? }[1..-1]
bloated[threes.last..-1].reverse.join + "," + threes.map { |n| (n-3)..(n-1)}.map {|r| bloated[r]}.map(&:join).join(',').reverse
}
puts "\n\nBut the COOL lambda solution is: #{commify[11223344556]}" + " !!!!!"
# 1 + 2
# 1.+(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment