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 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:

inputs = []

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

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

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

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


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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: