How to resolve the algorithm Order by pair comparisons step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Order by pair comparisons step by step in the Wren 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 Wren programming language

Source code in the wren programming language

import "/ioutil" for Input
import "/fmt" for Fmt

// Inserts item x in list a, and keeps it sorted assuming a is already sorted.
// If x is already in a, inserts it to the right of the rightmost x.
var insortRight = Fn.new{ |a, x, q|
    var lo = 0
    var hi = a.count
    while (lo < hi) {
        var mid = ((lo + hi)/2).floor
        q = q + 1
        var prompt = Fmt.swrite("$2d: Is $6s less than $6s ? y/n: ", q, x, a[mid])
        var less = Input.option(prompt, "yn") == "y"
        if (less) {
            hi = mid
        } else {
            lo = mid + 1
        }
     }
     a.insert(lo, x)
     return q
}

var order = Fn.new { |items|
    var ordered = []
    var q = 0
    for (item in items) {
        q = insortRight.call(ordered, item, q)
    }
    return ordered
}

var items = "violet red green indigo blue yellow orange".split(" ")
var ordered = order.call(items)
System.print("\nThe colors of the rainbow, in sorted order, are:")
System.print(ordered)

  

You may also check:How to resolve the algorithm Pythagorean triples step by step in the ZX Spectrum Basic programming language
You may also check:How to resolve the algorithm Modular exponentiation step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Java programming language
You may also check:How to resolve the algorithm String matching step by step in the C++ programming language
You may also check:How to resolve the algorithm Hilbert curve step by step in the Fōrmulæ programming language