Can anyone try to solve this problems?

Hi to everybody.
   
  I am trying to solve these three problems in Ruby. I do not know if my solutions are really correct. I just wanted to ask help, if somebody can show their solutions. I would appreciated your help.
   
  1. Write a one-line in irb using Range#inject to calculate 20!. Generalize this into a function.
  2. Write a function to find the longest string in an array of strings.
  3. Write an iterator function n_times(n) that calls the given block n times.
   
  Thanks.
   
  Cyrus

···

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com

Please don't post your homework problems on this list. If you are having trouble with a particular part of this, we'd be happy to help.

Brad

···

On Jan 15, 2007, at 1:02 AM, Cyrus Gabilla wrote:

  I am trying to solve these three problems in Ruby. I do not know if my solutions are really correct. I just wanted to ask help, if somebody can show their solutions. I would appreciated your help.

  1. Write a one-line in irb using Range#inject to calculate 20!. Generalize this into a function.
  2. Write a function to find the longest string in an array of strings.
  3. Write an iterator function n_times(n) that calls the given block n times.

Neat! Where are you taking classes on ruby? seriously.

···

On 1/15/07, Cyrus Gabilla <gabilla19992004@yahoo.com> wrote:

Hi to everybody.

I am trying to solve these three problems in Ruby. I do not know if my
solutions are really correct. I just wanted to ask help, if somebody can
show their solutions. I would appreciated your help.

1. Write a one-line in irb using Range#inject to calculate 20!. Generalize
this into a function.
2. Write a function to find the longest string in an array of strings.
3. Write an iterator function n_times(n) that calls the given block n
times.

Thanks.

Cyrus

Cyrus Gabilla wrote:

Hi to everybody.
     I am trying to solve these three problems in Ruby. I do not know if my solutions are really correct. I just wanted to ask help, if somebody can show their solutions. I would appreciated your help.
     1. Write a one-line in irb using Range#inject to calculate 20!. Generalize this into a function.
  2. Write a function to find the longest string in an array of strings.
  3. Write an iterator function n_times(n) that calls the given block n times.
  

You say you have solutions but you don't know if they are correct or not. Perhaps you need to learn how to test correctness. As an example, the calculation of 20 factorial -- does Ruby have a factorial built in? If so, you could compare its results with the results from your code. If not, find another language that does, or borrow someone's engineering calculator to get the (rather large) number.

The other two are easy to test -- factorial is moderately difficult because it's such a common exercise for students that languages tend not to build it in, and because the resulting number gets very large very quickly; unless a language has facilities for computing and printing integers beyond machine precision.

So, courtesy of the Axiom system, here's 20! you can cut and paste into your test driver. I ran off 50! too because ... well, because I can. :slight_smile:

(2) -> factorial(20)
(2) ->
   (2) 2432902008176640000
                                                        Type: PositiveInteger
(3) -> factorial(50)
(3) ->
   (3) 30414093201713378043612608166064768844377641568960512000000000000
                                                        Type: PositiveInteger
(4) ->

···

--
M. Edward (Ed) Borasky, FBG, AB, PTA, PGS, MS, MNLP, NST, ACMC(P)
http://borasky-research.blogspot.com/

If God had meant for carrots to be eaten cooked, He would have given rabbits fire.

  2. Write a function to find the longest string in an array of strings.

Is this from the Brian Schroder Ruby Course PDF?

Here is my function (no doubt a better on exists):

def longest(a)
   word = ''
   a.each do |i|
     if word.length < i.length
       word = i
     end
   end
   word
end

a = ['a', 'fish', 'is', 'messy', 'dog']

puts longest(a)

That is the classic searching algorithm (almost). However there is something more idiomatic.

Here's an example to find the biggest number:
[1, 2, 3].max {|a, b| a <=> b }

Try to adapt the array contents in that and the block to find the longest string.

Dan

David Madden wrote:

···

  2. Write a function to find the longest string in an array of strings.

Is this from the Brian Schroder Ruby Course PDF?

Here is my function (no doubt a better on exists):

def longest(a)
  word = ''
  a.each do |i|
    if word.length < i.length
      word = i
    end
  end
  word
end

a = ['a', 'fish', 'is', 'messy', 'dog']

puts longest(a)

['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop

···

On 1/15/07, David Madden <moose56@gmail.com> wrote:

> 2. Write a function to find the longest string in an array of
> strings.
>
Is this from the Brian Schroder Ruby Course PDF?

Here is my function (no doubt a better on exists):

def longest(a)
   word = ''
   a.each do |i|
     if word.length < i.length
       word = i
     end
   end
   word
end

David Madden <moose56@gmail.com> writes:

  2. Write a function to find the longest string in an array of
strings.

Is this from the Brian Schroder Ruby Course PDF?

Here is my function (no doubt a better on exists):

Well, okay, we've heard from folks with their fancy 1.9 ruby with
max_by and that &:sym notation. However, I'm a little bit surprised
that this one-liner with inject didn't pop up:

def longest(a)
  a.inject { |x,y| x.length < y.length ? y : x }
end

ObQuickIRBSanityCheck:

irb(main):001:0> def longest(a)
irb(main):002:1> a.inject { |x,y| x.length < y.length ? y : x }
irb(main):003:1> end
=> nil
irb(main):004:0> longest(%w[a bc de fgh ijkl mnopq rstu vwxyz])
=> "mnopq"

foldr is your friend.

···

--
s=%q( Daniel Martin -- martin@snowplow.org
       puts "s=%q(#{s})",s.map{|i|i}[1] )
       puts "s=%q(#{s})",s.map{|i|i}[1]

Neat! Where are you taking classes on ruby? seriously.

its my self study.

···

---------------------------------
Bored stiff? Loosen up...
Download and play hundreds of games for free on Yahoo! Games.

Hi,

Gregory Brown wrote in [ruby-talk:234222]:

['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop

max_by(&:length)

···

Date: Tue, 16 Jan 2007 10:51:18 +0900

--
Nobu Nakada

def longest(a)
   word = ''
   a.each do |i|
     if word.length < i.length
       word = i
     end
   end
   word
end

['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop

The beauty of a one line solution :slight_smile:

also...what is this about:

max_by(&:length)

Dave.

Daniel, this is a much better solution than my sort_by one. So good work! :slight_smile:

···

On 1/16/07, Daniel Martin <martin@snowplow.org> wrote:

David Madden <moose56@gmail.com> writes:

>> 2. Write a function to find the longest string in an array of
>> strings.
>>
> Is this from the Brian Schroder Ruby Course PDF?
>
> Here is my function (no doubt a better on exists):

Well, okay, we've heard from folks with their fancy 1.9 ruby with
max_by and that &:sym notation. However, I'm a little bit surprised
that this one-liner with inject didn't pop up:

def longest(a)
  a.inject { |x,y| x.length < y.length ? y : x }
end

Here's my try at a Ruby 1.8 implementation of the Enumerable#max_by:

a = %w{ one two three four }

def a.max_by
  pairs = inject({}) do |hash, obj|
    hash[yield obj] = obj; hash
  end
  pairs[pairs.keys.max]
end

require 'facet/symbol/to_proc'
a.max_by &:size

=> "three"

# Gregory Brown wrote in [ruby-talk:234222]:
# > ['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop

···

From: nobu.nakada@gmail.com [mailto:nobu.nakada@gmail.com]:
#
# max_by(&:length)

Hi Nobu, will the &: notation/feature be incorporated in 1.8.x series?
btw, i'd prefer max(&:length) over max_by..

kind regards -botp

Looking forward to 1.9 Nobu! :slight_smile:

···

On 1/15/07, Nobuyoshi Nakada <nobu@ruby-lang.org> wrote:

Hi,

Date: Tue, 16 Jan 2007 10:51:18 +0900
Gregory Brown wrote in [ruby-talk:234222]:
> ['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop

max_by(&:length)

>>
>> def longest(a)
>> word = ''
>> a.each do |i|
>> if word.length < i.length
>> word = i
>> end
>> end
>> word
>> end
>
> ['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop
>

The beauty of a one line solution :slight_smile:

also...what is this about:

max_by(&:length)

This is an Enumerable method from 1.9
http://ruby-doc.org/core-1.9/classes/Enumerable.html

It is a much better solution than what I offered, since it doesn't
sort the list first.
The actual method is implemented in C, but here is one way of doing it
in Ruby, to help you understand what's going on (maybe :slight_smile: )

seltzer:~ sandal$ irb
module Enumerable
  def max_by
    m={}
    each { |e|

?> v = yield(e)

       m[:value] ||= v
       if v > m[:value]
         m[:obj] = e; m[:value] = v;

?> end

    }
    m[:obj]
  end
end

=> nil

['foo','bartdfaggdgs','afdfd'].max_by { |e| e.length }

=> "bartdfaggdgs"

class Symbol
  def to_proc
    lambda { |x| x.send(self) }
  end
end

=> nil

['foo','bartdfaggdgs','afdfd'].max_by &:length

=> "bartdfaggdgs"

···

On 1/15/07, David Madden <moose56@gmail.com> wrote:

Yep, this is smarter than my ruby attempt :slight_smile:

Avoid the dependency on facets, Symbol#to_proc is the easiest thing in
the world to write

class Symbol
  def to_proc
      lambda { |x| x.send(self) }
  end
end

···

On 1/16/07, Sam Smoot <ssmoot@gmail.com> wrote:

Here's my try at a Ruby 1.8 implementation of the Enumerable#max_by:

> a = %w{ one two three four }

> def a.max_by
> pairs = inject({}) do |hash, obj|
> hash[yield obj] = obj; hash
> end
> pairs[pairs.keys.max]
> end

"Sam Smoot" <ssmoot@gmail.com> writes:

Here's my try at a Ruby 1.8 implementation of the Enumerable#max_by:

Why build up a separate hash structure?

def Enumerable.max_by
  ps = nil
  inject do |pmax, a|
    s = yield a
    if (ps == nil or s > ps) then
      ps = s
      a
    else
      pmax
    end
  end
end

···

--
s=%q( Daniel Martin -- martin@snowplow.org
       puts "s=%q(#{s})",s.map{|i|i}[1] )
       puts "s=%q(#{s})",s.map{|i|i}[1]

Peña, Botp:

btw, i'd prefer max(&:length) over max_by..

Note the difference in using sort and sort_by, or max and max_by:

enum.max { |x,y| x.length <=> y.length }
enum.max_by { |x| x.length } # 1.9

Kalman