1
0
Fork 0

First five problems in Ruby and (mostly) simplified to one-liners.

This commit is contained in:
Andrew Tomaka 2012-04-05 08:10:04 -04:00
parent 2ed479ddb7
commit 68062715c0
9 changed files with 63 additions and 0 deletions

10
Ruby/1-a.rb Executable file
View File

@ -0,0 +1,10 @@
#!/usr/bin/env ruby
sum = 0;
(1..999).each do |i|
if(i % 3 == 0 || i % 5 == 0) then
sum += i
end
end
puts sum

6
Ruby/1-b.rb Executable file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env ruby
sum = 0;
(1..999).each { |i| sum += i if (i % 3 == 0 || i % 5 == 0) }
puts sum

3
Ruby/1-c.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
puts (1...1000).select{ |i| i % 3 == 0 || i % 5 == 0 }.inject(:+)

11
Ruby/2-a.rb Executable file
View File

@ -0,0 +1,11 @@
#!/usr/bin/env ruby
sum = 0
i = j = 1
until (i >= 4000000)
i, j = j, i + j
sum += i if(i.even?)
end
puts sum

3
Ruby/2-conrad.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
puts Enumerator.new { |yielder| i, j = 0, 1; loop {i, j = j, i + j; yielder.yield i} }.take_while { |n| n <= 4E6}.select { |i| i.even? }.inject(:+)

4
Ruby/3-a.rb Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env ruby
require 'prime'
puts Prime.prime_division(600851475143).last[0]

3
Ruby/4-a.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
p (100...1000).to_a.map{ |i| (100...1000).to_a.map{ |j| i *j } }.flatten(1).select { |i| i.to_s == i.to_s.reverse }.sort.last

20
Ruby/5-a.rb Executable file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env ruby
i = 20
while true do
20.downto(1) { |j|
break if i % j != 0
@done = true if j == 1
}
break if @done
if i > 232792560 then
puts 'fail'
break
end
i += 20
end
puts i

3
Ruby/5-b.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
puts (1..20).inject(1) { |lcm, n| lcm.lcm(n) }