#!/usr/bin/env setl
--
-- Median in SETL
--
-- From the {log} (setlog) program
-- http://prmat.math.unipr.it/~gianfr/SETLOG/SamplePrograms/Median.slog
-- """
-- Find the median M of a set S of integer numbers
-- (the median is the unique element M of S such that there are as
-- many elements of S which are smaller than M as there are elements
-- of S which are larger tham M --- if S has an even number of
-- elements, median/2 is assumed to be false
-- """
--
-- This SETL program was created by Hakan Kjellerstrand (hakank@bonetmail.com)
-- Also see my SETL page: http://www.hakank.org/setl/
--
S := {18,5,-3,7,1,7,11,2};
print(median(S));
print(median2(S));
t := time();
setrandom(0); -- indeterministic
S2:=[random 100 : i in [1..1001]];
t1 := time();
print(median(S2));
t2 := time();
print(median2(S2));
t3 := time();
print("Time1: ", (t2 - t1), "ms");
print("Time2: ", (t3 - t2), "ms");
proc median(SS);
if #SS mod 2 = 0 then
return om;
end if;
for m in SS loop
if #{z : z in SS | z < m} = #{z : z in SS | z > m} then
return m;
end if;
end loop;
end proc;
--
-- This version, using exists, is more elegant.
--
proc median2(SS);
if #SS mod 2 = 0 then
return om;
end if;
if exists m in SS | #{z in SS | z < m} = #{z in SS | z > m} then
return m;
end if;
end proc;