From: Joel VanderWerf on 8 Mar 2010 23:49 Prasanth Ravi wrote: > tx for the reply, i originally used > y=0 > gets.split.each{ |x| > z=x.to_i > y+=z if z>0 > } > print y You can save a char by replacing y=0;s.split.each{|x|z=x.to_i;y+=z if z>0} with y=0;s.split.each{|x|y+=x.to_i if /-/!~x} but this is even shorter y=0;s.scan(/ \d+|^\d+/){|x|y+=x.to_i}
From: Aaron D. Gifford on 8 Mar 2010 23:59 Ruby 1.9: 34 characters eval(gets.scan(/(?:^| )(\d+)/)*?+) Aaron out
From: Prasanth Ravi on 9 Mar 2010 00:31 Aaron D. Gifford wrote: > Ruby 1.9: 34 characters > > eval(gets.scan(/(?:^| )(\d+)/)*?+) > > Aaron out edit: y=0 s="" s.scan(/ \d+|^\d+/){|x|y+=x.to_i} puts y i put puts y so i can do it in a script file instead of irb and removed semicolons as ';' counts as a char, 38 char-w/o puts y 43 chars-with puts y this is the shortest i have seen w/o getting into an infinite loop :D,ty -- Posted via http://www.ruby-forum.com/.
From: Prasanth Ravi on 9 Mar 2010 01:55 Aaron D. Gifford wrote: > Ruby 1.9: 34 characters > > eval(gets.scan(/(?:^| )(\d+)/)*?+) > > Aaron out tx aaron this is by far the shortest code ive seen... -- Posted via http://www.ruby-forum.com/.
From: Robert Dober on 9 Mar 2010 02:50 On Mon, Mar 8, 2010 at 10:38 PM, Prasanth Ravi <dare.take(a)gmail.com> wrote: > Robert Dober wrote: >> On Mon, Mar 8, 2010 at 10:10 PM, Prasanth Ravi <dare.take(a)gmail.com> >> wrote: >>> hi i'm a newbie in ruby and was test out some interesting problems in >>> ruby, >>> >>> i came across a small one to print the sum of positive numbers from a >>> list of n numbers... with the shortest code possible.. >>> >>> well the best i could do was, >>> puts gets.split(' ').inject(0){|sum,x| x.to_i>0?sum+x.to_i : sum} >> I am afraid so >> puts gets.split.map(&:to_i).inject(&:+) >> although in Ruby 1.8 you need >> gets.split.inject(0){ |sum, x | sum + x.to_i } >> or >> ... inject{ | sum, x | sum.to_i + x.to_i } >> if you prefer. >> >> What do *you* think is the most readable solution BTW ;)? >> >> Cheers >> Robert >> >> P.S. >> BTW if you meant to not use negative numbers (sorry my English is very >> basic) >> >> map(&:to_i).select{ |x| x > 0 }. ... >> >> would be my choice. >> >> R. > > tx for the reply, i originally used > y=0 > gets.split.each{ |x| > z=x.to_i > y+=z if z>0 > } > print y > > --46 chars > > puts gets.split.map(&:to_i).select{|x| x>0}.inject(&:+) > > --53 chars > I feel that your code has less characters and mine is shorter :) R.
First
|
Prev
|
Next
|
Last
Pages: 1 2 3 4 Prev: Login Prompt - how to? Next: Rufus Sheduler, Dinamic timing changing |