Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Ruby: TPK Algorithm in Different Programming Languages

leave a comment »

I was looking for some exercise problems for a programming class I am teaching and encountered Knuth’s TPK problem on http://cs.fit.edu/~ryan/compare/ comparing solutions in different languages but did not find my favorite language and thought I would do it in Ruby and may be submit for inclusion there.

The TPK algorithm reads in an array of 11 values, applies a particular function to each value, and then writes the result in reverse order. It serves just to illustrate some of the usual actions that an imperative programming language must perform.

Here is my quick solution:

#
# http://cs.fit.edu/~ryan/compare/
#
inputs = []

def f(x)
  Math.sqrt(x.abs) + (5 * x ** 3)
end

11.times do
  inputs << gets.chomp.to_f
end

inputs.reverse.each_with_index do |num, index|
  fn = f(num)
  if fn < 400
    puts "#{10 - index} #{fn}"
  else
    puts "#{10 - index} #{fn} TOO LARGE"
  end
end

I think it could be done better but just wanted to have something out there.

Advertisements

Written by imsaar

August 28, 2013 at 2:33 pm

Posted in ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: