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

From: Cyrus G. [mailto:[email protected]] :

#---------------------------------------------------------------

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

#---------------------------------------------------------------

test it :slight_smile:

#---------------------------------------------------------------

1. Write a one-line in irb using Range#inject to calculate

20!. Generalize this into a function.

#---------------------------------------------------------------

fri is your friend

C:\Documents and Settings\peñaijm>fri inject
c:0:Warning: require_gem is obsolete. Use gem instead.
------------------------------------------------------ Enumerable#inject
enum.inject(initial) {| memo, obj | block } => obj
enum.inject {| memo, obj | block } => obj

 Combines the elements of _enum_ by applying the block to an
 accumulator value (_memo_) and each element in turn. At each step,
 _memo_ is set to the value returned by the block. The first form
 lets you supply an initial value for _memo_. The second form uses
 the first element of the collection as a the initial value (and
 skips that element while iterating).

    # Sum some numbers
    (5..10).inject {|sum, n| sum + n }              #=> 45
    # Multiply some numbers
    (5..10).inject(1) {|product, n| product * n }   #=> 151200

    # find the longest word
    longest = %w{ cat sheep bear }.inject do |memo,word|
       memo.length > word.length ? memo : word
    end
    longest                                         #=> "sheep"

    # find the length of the longest word
    longest = %w{ cat sheep bear }.inject(0) do |memo,word|
       memo >= word.length ? memo : word.length
    end
    longest                                         #=> 5

#---------------------------------------------------------------

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

of strings.

#---------------------------------------------------------------

fri is your friend

C:\Documents and Settings\peñaijm>fri max
c:0:Warning: require_gem is obsolete. Use gem instead.
------------------------------------------------------ Multiple choices:

 Enumerable#max, SizedQueue#max

C:\Documents and Settings\peñaijm>fri enumerable#max
c:0:Warning: require_gem is obsolete. Use gem instead.
--------------------------------------------------------- Enumerable#max
enum.max => obj
enum.max {|a,b| block } => obj

 Returns the object in _enum_ with the maximum value. The first form
 assumes all objects implement +Comparable+; the second uses the
 block to return _a <=> b_.

    a = %w(albatross dog horse)
    a.max                                  #=> "horse"
    a.max {|a,b| a.length <=> b.length }   #=> "albatross"

C:\Documents and Settings\peñaijm>

#---------------------------------------------------------------

3. Write an iterator function n_times(n) that calls the

given block n times.

#---------------------------------------------------------------

again, fri is your friend

C:\Documents and Settings\peñaijm>fri integer#times
c:0:Warning: require_gem is obsolete. Use gem instead.
---------------------------------------------------------- Integer#times
int.times {|i| block } => int

 Iterates block _int_ times, passing in values from zero to _int_ -
 1.

    5.times do |i|
      print i, " "
    end

 _produces:_

    0 1 2 3 4

C:\Documents and Settings\peñaijm>fri iterator
c:0:Warning: require_gem is obsolete. Use gem instead.
------------------------------------------------------- Kernel#iterator?
block_given? => true or false
iterator? => true or false

 Returns +true+ if +yield+ would execute a block in the current
 context. The +iterator?+ form is mildly deprecated.

    def try
      if block_given?
        yield
      else
        "no block"
      end
    end
    try                  #=> "no block"
    try { "hello" }      #=> "hello"
    try do "hello" end   #=> "hello"

hth.
kind regards -botp

Hi,

Date: Tue, 16 Jan 2007 10:51:18 +0900
Gregory B. wrote in [ruby-talk:234222]:

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

max_by(&:length)

“Sam S.” [email protected] 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

David M. [email protected] writes:

  1. 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.

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

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”

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

On 1/15/07, Cyrus G. [email protected] wrote:

  1. Write an iterator function n_times(n) that calls the given block n
    times.

Thanks.

Cyrus

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

  1. 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)

Cyrus G. 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.

Hi,

At Tue, 16 Jan 2007 13:07:47 +0900,
Peña, Botp [email protected] wrote in [ruby-talk:234253]:

Hi Nobu, will the &: notation/feature be incorporated in 1.8.x series?

I don’t think so, but Symbol#to_proc was incorporated from
ActiveSupport.

On 1/16/07, Sam S. [email protected] 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

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

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

its my self study.

On 1/16/07, Daniel M. [email protected] wrote:

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

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

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

n times.
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 1/15/07, Nobuyoshi N. [email protected] wrote:

Hi,

Date: Tue, 16 Jan 2007 10:51:18 +0900
Gregory B. wrote in [ruby-talk:234222]:

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

max_by(&:length)

Looking forward to 1.9 Nobu! :slight_smile:

On 1/15/07, David M. [email protected] wrote:

[‘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 M. [email protected] wrote:

a.each do |i|
if word.length < i.length
word = i
end
end
word
end

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

From: [email protected] [mailto:[email protected]]:

Gregory B. wrote in [ruby-talk:234222]:

> [‘fodfsafdfsdfso’,‘bar’,‘bazzzzzz’].sort_by { |s| s.length }.pop

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