intprog_hackery/sorting_algos.rb

36 lines
1.1 KiB
Ruby

# TODO: Make variadic, such that we only need one method
def compare_to(sortings)
first, second, third = *sortings
return_stat = lambda{ |sorting|
if sorting.type == "String"
{:ret => "this.#{sorting.variable}.compareTo(other.#{sorting.variable})"}
else
{:ret => sorting.comparator == ">" ? "this.#{sorting.variable} - other.#{sorting.variable}" : "other.#{sorting.variable} - this.#{sorting.variable}"}
end}
comp = lambda {|sorting|
if sorting.type == "String"
{:if => "!this.#{sorting.variable}.equals(other.#{sorting.variable})",
:ret => (return_stat.call sorting)[:ret]}
else
{:if => "this.#{sorting.variable} != other.#{sorting.variable}",
:ret => (return_stat.call sorting)[:ret]}
end}
if defined? third
"\t\tif (#{(comp.call first)[:if]}) {
\t\t\treturn #{(comp.call first)[:ret]};
\t\t} else if (#{(comp.call second)[:if]}) {
\t\t\treturn #{(comp.call second)[:ret]};
\t\t}
\t\treturn #{(comp.call third)[:ret]};"
else
"\t\tif (#{(comp.call first)[:if]}) {
\t\t\treturn #{(comp.call first)[:ret]};
\t\t}
\t\treturn #{(comp.call second)[:ret]};"
end
end