intprog_hackery/sorting_algos.rb

34 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}
pls = sortings.slice(1,sortings.length - 2).map do |ele|
"else if (#{(comp.call ele)[:if]}) {
\t\t\treturn #{(comp.call ele)[:ret]};
\t\t}"
end
"\t\tif (#{(comp.call first)[:if]}) {
\t\t\treturn #{(comp.call first)[:ret]};
\t\t}
\t\t#{pls.join "\n"}
\t\treturn #{(comp.call sortings[sortings.length-1])[:ret]};"
end