[QUIZ] One-Liners Mashup (#177 again)

E

Eduard Llull

Too many solvers not providing additional problems!

Here's another... Assuming you have an array of numeric data, write a
method that returns an array of progressive sums. That is:

prog_sum( [1, 5, 13, -6, 20] ) => [1, 6, 19, 13, 33]

def prog_sum(ary)
ary.inject([0, []]) {|(s, a), i| [s+i, a<<(s+i)]}.last
end

And what about
def prog_sum(array)
sum = 0; array.collect { |e| sum+=e }
end
 
T

Todd Benson

Technically not one line, but it's under 80 chars and is recursive...

def f n;self.zip(n==2?self:f(n-1));end;def repeat n;f(n).flatten;end

...doesn't work for n < 2


Offered quiz is a no-brainer; mostly for golfing...

Given an epsilon, compute PI to that precision.

Todd
 
H

Holger Mack

[Note: parts of this message were removed to make it a legal post.]

class Array
def to_s
collect{|x| x.to_s.gsub(/\n/,"\n| ")}.join("\n|-- ")
end
end

puts [:foo, [:bar, [:baz, :quux], :hello, :world], :done].to_s

Works fine for given example but fails for example with
puts [:a, [:b, :c]].to_s

a
|-- b
| |-- c

Still working on this...


-----------------------------------------------------------------------------
New question

Write a oneliner next_fib(n) which gives the smallest Fibonacci number
greater than n
http://en.wikipedia.org/wiki/Fibonacci_number




2008/9/22 Martin DeMello said:
Too many solvers not providing additional problems!

Here's another... Assuming you have an array of numeric data, write a
method that returns an array of progressive sums. That is:

prog_sum( [1, 5, 13, -6, 20] ) => [1, 6, 19, 13, 33]

def prog_sum(ary)
ary.inject([0, []]) {|(s, a), i| [s+i, a<<(s+i)]}.last
end

Followon: Given an s-expression, print it out as a tree, where [:a,
:b, :c, :d] is the node with parent a and children b, c and d

[:foo, [:bar, [:baz, :quux], :hello, :world], :done] #=>

foo
| -- bar
| | -- baz
| | | -- quux
| | -- hello
| | -- world
| -- done

martin
 
K

Ken Bloom

Matthew Moss said:
I was tempted to port the C++ next_permutation code, but then I
realized I have class. :(

I've done it, and posted it here, but It's not one line. I'm not sure
if that's even doable.

What I do know is that most permutation generators in Ruby just look
at positions, not data, and by doing so, they yield identical
permutations in a single iteration when there are indentical data
elements.

--Ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top