How to resolve the algorithm Order by pair comparisons step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Order by pair comparisons step by step in the Raku programming language
Table of Contents
Problem Statement
Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: The correct ordering being: Note:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Order by pair comparisons step by step in the Raku programming language
Source code in the raku programming language
my $ask_count = 0;
sub by_asking ( $a, $b ) {
$ask_count++;
constant $fmt = '%2d. Is %-6s [ less than | greater than | equal to ] %-6s? ( < = > ) ';
constant %o = '<' => Order::Less,
'=' => Order::Same,
'>' => Order::More;
loop {
my $input = prompt sprintf $fmt, $ask_count, $a, $b;
return $_ with %o{ $input.trim };
say "Invalid input '$input'";
}
}
my @colors = ;
my @sorted = @colors.sort: &by_asking;
say (:@sorted);
die if @sorted».substr(0,1).join ne 'roygbiv';
my $expected_ask_count = @colors.elems * log(@colors.elems);
warn "Too many questions? ({:$ask_count} > {:$expected_ask_count})" if $ask_count > $expected_ask_count;
You may also check:How to resolve the algorithm Infinity step by step in the Groovy programming language
You may also check:How to resolve the algorithm Delete a file step by step in the Wren programming language
You may also check:How to resolve the algorithm Comments step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Steffensen's method step by step in the ATS programming language
You may also check:How to resolve the algorithm Constrained random points on a circle step by step in the PowerShell programming language