TPK algorithm: Difference between revisions

Content deleted Content added
The algorithm: insert <source lang="pascal"> tag </source> for ALGOL 60 wiith some pre-ascii characters.
use <code> where proper (<source> doesn't support ALGOL; coloring is wrong for Perl); rm Ruby examples as repetitive
Line 6:
 
==The algorithm==
In [[ALGOL 60]]:
 
<sourcecode lang="pascalalgol">
'''begin integer''' i; '''real''' y; '''real array''' a[0:10];
'''real procedure''' f(t); '''real''' t; '''value''' t;
f := sqrt(abs(t))+5×t↑35*t^3;
'''for''' i := 0 '''step''' 1 '''until''' 10 '''do''' read(a[i]);
'''for''' i := 10 '''step''' -1 '''until''' 0 '''do'''
'''begin''' y := f(a[i]);
'''if''' y > 400 '''then''' write(i, "TOO LARGE")
'''else''' write(i,y);
'''end'''
'''end'''
</sourcecode>
 
The algorithm reads eleven numbers from an input device, stores them in an array, and then processes them in reverse order, applying a user-defined function to each value and reporting either the value of the function or a message to the effect that the value has exceeded some threshold.
Line 28:
The following [[Perl]] implementation is 79 [[byte]]s.
 
<sourcecode lang="perl">
map print(($_>400?"TOO LARGE":$_).$/),reverse map 5*($x=<>)**3+sqrt abs$x,1..11
</sourcecode>
 
==Python version==
Line 46:
else:
print i, y
</source>
 
==Ruby version==
The following Ruby version makes heavy use of blocks / closures, as is common practice in the language:
 
<source lang="ruby">
f = proc { |t| (t.abs + 5 * t ** 3) ** 0.5 }
(1..11).map { f[gets.to_i] }.each_with_index { |t,u| puts u, t > 400 ? "TOO LARGE" : t }
</source>
 
Or, in a slightly longer, but more standard implementation:
 
<source lang="ruby">
a = []
f = lambda { |t| (t.abs + 5 * t ** 3) ** 0.5 }
11.times { a << gets.to_i }.times do |i|
j = f[a.shift]
puts i, j > 400 ? "TOO LARGE" : j
end
</source>