import java.awt.*;
import javax.swing.*;

class Pendulum extends JPanel implements Runnable {

    private angle = Math.PI / 2;
    private length;

    Pendulum(length) {
        this.length = length;
        setDoubleBuffered(true);
    }

    @Override
    void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);
        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
        def ballX = anchorX + (Math.sin(angle) * length) as int;
        def ballY = anchorY + (Math.cos(angle) * length) as int;
        g.drawLine(anchorX, anchorY, ballX, ballY);
        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
        g.fillOval(ballX - 7, ballY - 7, 14, 14);
    }

    void run() {
        def angleAccel, angleVelocity = 0, dt = 0.1;
        while (true) {
            angleAccel = -9.81 / length * Math.sin(angle);
            angleVelocity += angleAccel * dt;
            angle += angleVelocity * dt;
            repaint();
            try { Thread.sleep(15); } catch (InterruptedException ex) {}
        }
    }

    @Override
    Dimension getPreferredSize() {
        return new Dimension(2 * length + 50, (length / 2 * 3) as int);
    }

    static void main(String[] args) {
        def f = new JFrame("Pendulum");
        def p = new Pendulum(200);
        f.add(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
        new Thread(p).start();
    }
}

simulate a physical system of a simple gravity pendulum and animate it. The Java solution has been converted to Groovy style by removing explicit definitions and converting casts where necessary.


def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText('''
{
    "people":[
        {"name":{"family":"Flintstone","given":"Frederick"},"age":35,"relationships":{"wife":"people[1]","child":"people[4]"}},
        {"name":{"family":"Flintstone","given":"Wilma"},"age":32,"relationships":{"husband":"people[0]","child":"people[4]"}},
        {"name":{"family":"Rubble","given":"Barnard"},"age":30,"relationships":{"wife":"people[3]","child":"people[5]"}},
        {"name":{"family":"Rubble","given":"Elisabeth"},"age":32,"relationships":{"husband":"people[2]","child":"people[5]"}},
        {"name":{"family":"Flintstone","given":"Pebbles"},"age":1,"relationships":{"mother":"people[1]","father":"people[0]"}},
        {"name":{"family":"Rubble","given":"Bam-Bam"},"age":1,"relationships":{"mother":"people[3]","father":"people[2]"}},
    ]
}
''')

result.each { println it.key; it.value.each {person -> println person} }

assert result.people[0].name == [family:'Flintstone', given:'Frederick']
assert result.people[4].age == 1
assert result.people[2].relationships.wife == 'people[3]'
assert result.people[3].name == [family:'Rubble', given:'Elisabeth']
assert Eval.x(result, 'x.' + result.people[2].relationships.wife + '.name') == [family:'Rubble', given:'Elisabeth']
assert Eval.x(result, 'x.' + result.people[1].relationships.husband + '.name') == [family:'Flintstone', given:'Frederick']

"Load a JSON string into a data structure, create a new data structure and serialize it into JSON using Groovy 1.8 or later. The code also ensures the JSON is valid and can handle extra commas in arrays."


import static Constants.tolerance
import static java.math.RoundingMode.HALF_UP

def root(double base, double n) {
    double xOld = 1
    double xNew = 0
    while (true) {
        xNew = ((n - 1) * xOld + base/(xOld)**(n - 1))/n
    if ((xNew - xOld).abs() < tolerance) { break }
        xOld = xNew
    }
    (xNew as BigDecimal).setScale(7, HALF_UP)
}

class Constants {
    static final tolerance = 0.00001
}

print '''
   Base   Power  Calc'd Root  Actual Root
-------  ------  -----------  -----------
'''
def testCases = [
    [b:32.0, n:5.0, r:2.0],
    [b:81.0, n:4.0, r:3.0],
    [b:Math.PI**2, n:4.0, r:Math.PI**(0.5)],
    [b:7.0, n:0.5, r:49.0],
]

testCases.each {
    def r = root(it.b, it.n)
    printf('%7.4f  %6.4f  %11.4f  %11.4f\n',
        it.b, it.n, r, it.r)
    assert (r - it.r).abs() <= tolerance
}

   Base   Power  Calc'd Root  Actual Root
-------  ------  -----------  -----------
32.0000  5.0000       2.0000       2.0000
81.0000  4.0000       3.0000       3.0000
 9.8696  4.0000       1.7725       1.7725
 7.0000  0.5000      49.0000      49.0000

implement the principal nth root computation algorithm for a positive real number A.


"Determines and outputs the hostname of the current system where the routine is running."


Translation of: Ruby

final random = new Random()
final input = new Scanner(System.in)

def evaluate = { expr ->
    if (expr == 'QUIT') {
        return 'QUIT'
    } else {
        try { Eval.me(expr.replaceAll(/(\d)/, '$1.0')) }
        catch (e) { 'syntax error' }
    }
}

def readGuess = { digits ->
    while (true) {
        print "Enter your guess using ${digits} (q to quit): "
        def expr = input.nextLine()

        switch (expr) {
            case ~/^[qQ].*/:
                return 'QUIT'

            case ~/.*[^\d\s\+\*\/\(\)-].*/:
                def badChars = expr.replaceAll(~/[\d\s\+\*\/\(\)-]/, '')
                println "invalid characters in input: ${(badChars as List) as Set}"
                break

            case { (it.replaceAll(~/\D/, '') as List).sort() != ([]+digits).sort() }:
                println '''you didn't use the right digits'''
                break

            case ~/.*\d\d.*/:
                println 'no multi-digit numbers allowed'
                break

            default:
                return expr
        }
    }
}

def digits = (1..4).collect { (random.nextInt(9) + 1) as String }

while (true) {
    def guess = readGuess(digits)
    def result = evaluate(guess)

    switch (result) {
        case 'QUIT':
            println 'Awwww. Maybe next time?'
            return

        case 24:
            println 'Yes! You got it.'
            return

        case 'syntax error':
            println "A ${result} was found in ${guess}"
            break

        default:
            println "Nope: ${guess} == ${result}, not 24"
            println 'One more try, then?'
    }
}

$ groovy TwentyFour.gsh
Enter your guess using [4, 8, 3, 6] (q to quit): 4836
no multi-digit numbers allowed
Enter your guess using [4, 8, 3, 6] (q to quit): 4  ++ ++ 8/ 3-6
A syntax error was found in 4  ++ ++ 8/ 3-6
Enter your guess using [4, 8, 3, 6] (q to quit): btsjsb
invalid characters in input: [t, s, b, j]
Enter your guess using [4, 8, 3, 6] (q to quit): 1+3+2+2
you didn't use the right digits
Enter your guess using [4, 8, 3, 6] (q to quit): q
Awwww. Maybe next time?

$ groovy TwentyFour.gsh
Enter your guess using [6, 3, 2, 6] (q to quit): 6+6+3+2
Nope: 6+6+3+2 == 17.0, not 24
One more try, then?
Enter your guess using [6, 3, 2, 6] (q to quit): (6*3 - 6) * 2
Yes! You got it.

The code implements the 24 Game, where it randomly selects four digits from 1 to 9 and prompts the player to form an arithmetic expression that equals 24 using these digits. The expression can only use each digit once and can include multiplication, division, addition, and subtraction. The code also allows for the use of brackets and floating point division. It does not allow the formation of multiple digit numbers from the provided digits. The game quits if a line starting with "q" is entered.


def rleEncode(text) {
    def encoded = new StringBuilder()
    (text =~ /(([A-Z])\2*)/).each { matcher ->
        encoded.append(matcher[1].size()).append(matcher[2])
    }
    encoded.toString()
}

def rleDecode(text) {
    def decoded = new StringBuilder()
    (text =~ /([0-9]+)([A-Z])/).each { matcher ->
        decoded.append(matcher[2] * Integer.parseInt(matcher[1]))
    }
    decoded.toString()
}

def text = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
def rleEncoded = rleEncode(text)
assert rleEncoded == '12W1B12W3B24W1B14W'
assert text == rleDecode(rleEncoded)

println "Original Text: $text"
println "Encoded Text: $rleEncoded"

Original Text: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Encoded Text: 12W1B12W3B24W1B14W

implement a run-length encoding algorithm that compresses strings of repeated uppercase characters by storing the length of the run. It also provides a function to reverse the compression. The output can be any format that can be used to recreate the original input.


def s = "Greetings "
println s + "Earthlings"

def s1 = s + "Earthlings"
println s1

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


def normal = "http://foo bar/"
def encoded = URLEncoder.encode(normal, "utf-8")
println encoded

provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, "http://foo bar/" is encoded as "http%3A%2F%2Ffoo%20bar%2F".


import static java.math.RoundingMode.*

def knapsackCont = { list, maxWeight = 15.0 ->
    list.sort{ it.weight / it.value }
    def remainder = maxWeight
    List sack = []
    for (item in list) {
        if (item.weight < remainder) {
            sack << [name: item.name, weight: item.weight,
                        value: (item.value as BigDecimal).setScale(2, HALF_UP)]
        } else {
            sack << [name: item.name, weight: remainder,
                        value: (item.value * remainder / item.weight).setScale(2, HALF_UP)]
            break
        }
        remainder -= item.weight
    }
    sack
}

def possibleItems = [
    [name:'beef',    weight:3.8, value:36],
    [name:'pork',    weight:5.4, value:43],
    [name:'ham',     weight:3.6, value:90],
    [name:'greaves', weight:2.4, value:45],
    [name:'flitch',  weight:4.0, value:30],
    [name:'brawn',   weight:2.5, value:56],
    [name:'welt',    weight:3.7, value:67],
    [name:'salami',  weight:3.0, value:95],
    [name:'sausage', weight:5.9, value:98],
]

def contents = knapsackCont(possibleItems)
println "Total Value: ${contents*.value.sum()}"
contents.each {
    printf("    name: %-7s  weight: ${it.weight}  value: ${it.value}\n", it.name)
}

Total Value: 349.38
    name: salami   weight: 3.0  value: 95.00
    name: ham      weight: 3.6  value: 90.00
    name: brawn    weight: 2.5  value: 56.00
    name: greaves  weight: 2.4  value: 45.00
    name: welt     weight: 3.5  value: 63.38

implement a solution for the continuous knapsack problem. The thief can select and cut items from a butcher's shop to maximize his profit, given a knapsack with a maximum capacity of 15 kg. The items have different weights and prices, and the price after cutting is proportional to the original price by the ratio of masses. The code determines the optimal selection of items to maximize total value without exceeding the knapsack's weight limit.


def words = new URL('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').text.readLines()
def groups = words.groupBy{ it.toList().sort() }
def bigGroupSize = groups.collect{ it.value.size() }.max()
def isBigAnagram = { it.value.size() == bigGroupSize }
println groups.findAll(isBigAnagram).collect{ it.value }.collect{ it.join(' ') }.join('\n')

<output> find the largest sets of anagrams from a given word list located at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.


def base3 = { BigInteger i -> i.toString(3) }

def sierpinskiCarpet = { int order ->
    StringBuffer sb = new StringBuffer()
    def positions = 0..<(3**order)
    def digits = 0..<([order,1].max())

    positions.each { i ->
        String i3 = base3(i).padLeft(order, '0')

        positions.each { j ->
            String j3 = base3(j).padLeft(order, '0')

            sb << (digits.any{ i3[it] == '1' && j3[it] == '1' } ? '  ' : order.toString().padRight(2) )
        }
        sb << '\n'
    }
    sb.toString()
}

(0..4).each { println sierpinskiCarpet(it) }

generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N, using the placement of whitespace and non-whitespace characters. The program uses list-indexing of base 3 string representation to achieve this. The '#' character is used for ASCII art but is not strictly necessary.


import groovy.transform.*

@Canonical
@Sortable(includes = ['freq', 'letter'])
class Node {
    String letter
    int freq
    Node left
    Node right
    boolean isLeaf() { left == null && right == null }
}

Map correspondance(Node n, Map corresp = [:], String prefix = '') {
    if (n.isLeaf()) {
        corresp[n.letter] = prefix ?: '0'
    } else {
        correspondance(n.left,  corresp, prefix + '0')
        correspondance(n.right, corresp, prefix + '1')
    }
    return corresp
}

Map huffmanCode(String message) {
    def queue = message.toList().countBy { it } // char frequencies
        .collect { String letter, int freq ->   // transformed into tree nodes
            new Node(letter, freq)
        } as TreeSet // put in a queue that maintains ordering

    while(queue.size() > 1) {
        def (nodeLeft, nodeRight)  = [queue.pollFirst(), queue.pollFirst()]

        queue << new Node(
            freq:   nodeLeft.freq   + nodeRight.freq,
            letter: nodeLeft.letter + nodeRight.letter,
            left: nodeLeft, right: nodeRight
        )
    }

    return correspondance(queue.pollFirst())
}

String encode(CharSequence msg, Map codeTable) {
    msg.collect { codeTable[it] }.join()
}

String decode(String codedMsg, Map codeTable, String decoded = '') {
    def pair = codeTable.find { k, v -> codedMsg.startsWith(v) }
    pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable)
         : decoded
}

def message = "this is an example for huffman encoding"

def codeTable = huffmanCode(message)
codeTable.each { k, v -> println "$k: $v" }

def encoded = encode(message, codeTable)
println encoded

def decoded = decode(encoded, codeTable)
println decoded

The code implements Huffman encoding algorithm to generate binary codes for each character in a given string based on their frequency of occurrence. It first creates a priority queue with each character as a leaf node. It then constructs a binary tree by continuously removing two nodes with the highest priority (lowest probability) and creating a new internal node with these two nodes as children. The process continues until there's only one node left in the queue, which becomes the root node. The code then traverses the binary tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf form the Huffman encoding for the corresponding character.


import groovy.swing.SwingBuilder

count = 0
new SwingBuilder().edt {
  frame(title:'Click frame', pack: true, show: true) {
    vbox {
      countLabel = label("There have been no clicks yet.")
      button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."})
    }
  }
}

import groovy.swing.SwingBuilder
import groovy.beans.Bindable

@Bindable class Model {
   Integer count = 0
}
model = new Model()
new SwingBuilder().edt {
  frame(title:'Click frame', pack: true, show: true) {
    vbox {
      label(text: bind(source: model, sourceProperty: 'count',
        converter: { v -> !v ? "There have been no clicks yet." : "Clicked ${v} time(s)."}))
      button('Click Me', actionPerformed: {model.count++})
    }
  }
}

"Create a windowed application with a label and a button. The label initially displays 'There have been no clicks yet'. The button, labeled 'click me', updates the label to show the number of times it has been clicked when pressed."


The code performs a countdown from 10 to 0 using a downward for loop.


for(i in (2..9).step(2)) {
    print "${i} "
}
println "Who do we appreciate?"

(2..9).step(2).each {
    print "${it} "
}
println "Who do we appreciate?"

demonstrate a for-loop with a step-value greater than one and also illustrate the use of the "each()" method, which is a preferred alternative to a "for" loop in Groovy programming.


Translation of: JavaScript

def sum = { i, lo, hi, term ->
    (lo..hi).sum { i.value = it; term() }
}
def obj = [:]
println (sum(obj, 1, 100, { 1 / obj.value }))

5.1873775176

The code demonstrates Jensen's Device, a programming technique that uses call by name. It calculates the 100th harmonic number by passing parameters by name to a sum procedure. The procedure re-evaluates the expression in the caller's context every time the parameter's value is required. The first parameter to the sum, representing the "bound" variable of the summation, is also passed by name to make changes visible in the caller's context. The global variable does not have to use the same identifier as the formal parameter.


continuously calculate and display the next decimal digit of Pi. The program runs indefinitely until manually stopped by the user. The output starts with the decimal sequence 3.14159265. The task is specifically about calculating Pi, not using built-in Pi constants.


class CList extends ArrayList implements Comparable {
    CList() { }
    CList(Collection c) { super(c) }
    int compareTo(Object that) {
        assert that instanceof List
        def n = [this.size(), that.size()].min()
        def comp = [this[0..<n], that[0..<n]].transpose().find { it[0] != it[1] }
        comp ? comp[0] <=> comp[1] : this.size() <=> that.size()
    }
}

CList a, b; (a, b) = [[], []]; assert ! (a < b)
b = [1] as CList;              assert   (a < b)
a = [1] as CList;              assert ! (a < b)
b = [2] as CList;              assert   (a < b)
a = [2, -1, 0] as CList;       assert ! (a < b)
b = [2, -1] as CList;          assert ! (a < b)
b = [2, -1, 0] as CList;       assert ! (a < b)
b = [2, -1, 0, -17] as CList;  assert   (a < b)
a = [2,  8, 0] as CList;       assert ! (a < b)

"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise."


def ack ( m, n ) {
    assert m >= 0 && n >= 0 : 'both arguments must be non-negative'
    m == 0 ? n + 1 : n == 0 ? ack(m-1, 1) : ack(m-1, ack(m, n-1))
}

def ackMatrix = (0..3).collect { m -> (0..8).collect { n -> ack(m, n) } }
ackMatrix.each { it.each { elt -> printf "%7d", elt }; println() }

The code is a function that implements the Ackermann function, a non-primitive recursive function. It takes two non-negative arguments and returns their Ackermann value. The function is designed to handle large values due to the rapid growth of the Ackermann function. However, it may cause a stack overflow error for certain inputs.


implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in/library function if available. The Gamma function is computed through numerical integration.


Distinct Solutions[edit]

def listOrder = { a, b ->
    def k = [a.size(), b.size()].min()
    def i = (0..<k).find { a[it] != b[it] }
    (i != null) ? a[i] <=> b[i] : a.size() <=> b.size()
}

def orderedPermutations = { list ->
    def n = list.size()
    (0..<n).permutations().sort(listOrder)
}

def diagonalSafe = { list ->
    def n = list.size()
    n == 1 || (0..<(n-1)).every{ i ->
        ((i+1)..<n).every{ j ->
            !([list[i]+j-i, list[i]+i-j].contains(list[j]))
        }
    }
}

def queensDistinctSolutions = { n ->
    // each permutation is an N-Rooks solution
    orderedPermutations((0..<n)).findAll (diagonalSafe)
}

Unique Solutions[edit]

class Reflect {
    public static final diag = { list ->
        final n = list.size()
        def tList = [0] * n
        (0..<n).each { tList[list[it]] = it }
        tList
    }

    public static final vert = { list ->
        list.reverse()
    }

    public static final horiz = { list ->
        final n = list.size()
        list.collect { n - it - 1 }
    }
}

enum Rotations {
    r0([]),
    r90([Reflect.vert, Reflect.diag]),
    r180([Reflect.vert, Reflect.diag, Reflect.vert, Reflect.diag]),
    r270([Reflect.diag, Reflect.vert]);

    private final List operations

    private Rotations(List ops) {
        operations = ops ?: []
    }

    public static void eliminateDups(primary, solutions) {
        (r0..r270).each { rot -> rot.eliminateDuplicates(primary, solutions) }
    }

    private void eliminateDuplicates(primary, solutions) {
        def rotated = [] + primary
        operations.each { rotated = it(rotated) }
        solutions.removeAll([rotated, Reflect.vert(rotated)])
    }
}

def queensUniqueSolutions = { start ->
    assert start instanceof Number || start instanceof List
    def qus = (start instanceof Number) \
                ? queensDistinctSolutions(start) \
                : [] + start
    for (def i = 0; i < qus.size()-1; i++) {
        Rotations.eliminateDups(qus[i], qus[(i+1)..<(qus.size())])
    }
    qus
}

Test and Results[edit]

(1..9).each { n ->
    def qds = queensDistinctSolutions(n)
    def qus = queensUniqueSolutions(qds)
    println ([boardSize:n, "number of distinct solutions":qds.size(), "number of unique solutions":qus.size()])
    if(n < 9) { qus.each { println it } }
    else { println "first:${qus[0]}"; println "last:${qus[-1]}" }
    println()
}

[1, 3, 0, 2]

row 0 has a queen in column 1
row 1 has a queen in column 3
row 2 has a queen in column 0
row 3 has a queen in column 2

   ---- ---- ---- ----
3 |    |////| ♛ |////|
   ---- ---- ---- ----
2 |/♛/|    |////|    |
   ---- ---- ---- ----
1 |    |////|    |/♛/|
   ---- ---- ---- ----
0 |////| ♛ |////|    |
   ---- ---- ---- ----
    0    1    2    3

[boardSize:1, number of distinct solutions:1, number of unique solutions:1]
[0]

[boardSize:2, number of distinct solutions:0, number of unique solutions:0]

[boardSize:3, number of distinct solutions:0, number of unique solutions:0]

[boardSize:4, number of distinct solutions:2, number of unique solutions:1]
[1, 3, 0, 2]

[boardSize:5, number of distinct solutions:10, number of unique solutions:2]
[0, 2, 4, 1, 3]
[1, 4, 2, 0, 3]

[boardSize:6, number of distinct solutions:4, number of unique solutions:1]
[1, 3, 5, 0, 2, 4]

[boardSize:7, number of distinct solutions:40, number of unique solutions:6]
[0, 2, 4, 6, 1, 3, 5]
[0, 3, 6, 2, 5, 1, 4]
[1, 3, 0, 6, 4, 2, 5]
[1, 4, 0, 3, 6, 2, 5]
[1, 4, 6, 3, 0, 2, 5]
[1, 5, 2, 6, 3, 0, 4]

[boardSize:8, number of distinct solutions:92, number of unique solutions:12]
[0, 4, 7, 5, 2, 6, 1, 3]
[0, 5, 7, 2, 6, 3, 1, 4]
[1, 3, 5, 7, 2, 0, 6, 4]
[1, 4, 6, 0, 2, 7, 5, 3]
[1, 4, 6, 3, 0, 7, 5, 2]
[1, 5, 0, 6, 3, 7, 2, 4]
[1, 5, 7, 2, 0, 3, 6, 4]
[1, 6, 2, 5, 7, 4, 0, 3]
[1, 6, 4, 7, 0, 3, 5, 2]
[2, 4, 1, 7, 0, 6, 3, 5]
[2, 4, 7, 3, 0, 6, 1, 5]
[2, 5, 1, 4, 7, 0, 6, 3]

[boardSize:9, number of distinct solutions:352, number of unique solutions:46]
first:[0, 2, 5, 7, 1, 3, 8, 6, 4]
last:[3, 1, 6, 8, 0, 7, 4, 2, 5]

"Output: The code solves the N-queens puzzle by generating N! distinct solutions from the N-Rooks problem, then filters out the candidates where all Queens are mutually diagonal-safe. It provides both distinct and unique solutions, accounting for reflections and rotations. The results are presented as a list of N numbers, each representing a column number within the list-indexed row."


def list = [1, 2, 3] + ["Crosby", "Stills", "Nash", "Young"]

println list

demonstrate how to concatenate two arrays.


def totalWeight = { list -> list*.weight.sum() }
def totalValue = { list -> list*.value.sum() }

def knapsack01bf = { possibleItems ->
    possibleItems.subsequences().findAll{ ss ->
        def w = totalWeight(ss)
        350 < w && w < 401
    }.max(totalValue)
}

def knapsack01dp = { possibleItems ->
    def n = possibleItems.size()
    def m = (0..n).collect{ i -> (0..400).collect{ w -> []} }
    (1..400).each { w ->
        (1..n).each { i ->
            def wi = possibleItems[i-1].weight
            m[i][w] = wi > w ? m[i-1][w] : ([m[i-1][w], m[i-1][w-wi] + [possibleItems[i-1]]].max(totalValue))
        }
    }
    m[n][400]
}

def items = [
        [name:"map", weight:9, value:150],
        [name:"compass", weight:13, value:35],
        [name:"water", weight:153, value:200],
        [name:"sandwich", weight:50, value:160],
        [name:"glucose", weight:15, value:60],
        [name:"tin", weight:68, value:45],
        [name:"banana", weight:27, value:60],
        [name:"apple", weight:39, value:40],
        [name:"cheese", weight:23, value:30],
        [name:"beer", weight:52, value:10],
        [name:"suntan cream", weight:11, value:70],
        [name:"camera", weight:32, value:30],
        [name:"t-shirt", weight:24, value:15],
        [name:"trousers", weight:48, value:10],
        [name:"umbrella", weight:73, value:40],
        [name:"waterproof trousers", weight:42, value:70],
        [name:"waterproof overclothes", weight:43, value:75],
        [name:"note-case", weight:22, value:80],
        [name:"sunglasses", weight:7, value:20],
        [name:"towel", weight:18, value:12],
        [name:"socks", weight:4, value:50],
        [name:"book", weight:30, value:10],
]

[knapsack01bf, knapsack01dp].each { knapsack01 ->
    def start = System.currentTimeMillis()
    def packingList = knapsack01(items)
    def elapsed = System.currentTimeMillis() - start

    println "\n\n\nElapsed Time: ${elapsed/1000.0} s"
    println "Total Weight: ${totalWeight(packingList)}"
    println " Total Value: ${totalValue(packingList)}"
    packingList.each {
        printf ("  item: %-25s  weight:%4d  value:%4d\n", it.name, it.weight, it.value)
    }
}

"Output: The code determines the optimal combination of items the tourist can carry in his knapsack, with a maximum weight limit of 4kg, to maximize the total value. It uses brute force and dynamic programming methods to solve the 0-1 Knapsack problem."


Translation of: Java (more or less) Uses explicit maps for preference ranking rather than list position. Uses Man and Woman enumerated types instead of string names, in order to take advantage of compile time type and constant checking to help keep the playas straight without a scorecard.

import static Man.*
import static Woman.*

Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
    Map<Woman,Man> engagedTo = new TreeMap()
    List<Man> freeGuys = (Man.values()).clone()
    while(freeGuys) {
        Man thisGuy = freeGuys[0]
        freeGuys -= thisGuy
        List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
        for(Woman girl in guyChoices) {
            if(! engagedTo[girl]) {
                engagedTo[girl] = thisGuy
                break
            } else {
                Man thatGuy = engagedTo[girl]
                if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
                    engagedTo[girl] = thisGuy
                    freeGuys << thatGuy
                    break
                }
            }
        }
    }
    engagedTo
}

boolean isStable(Map<Woman,Man> matches, Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
    matches.collect{ girl, guy ->
        int guysRank = galsGuyRanking[girl][guy]
        List<Man> sheLikesBetter = Man.values().findAll{ he -> galsGuyRanking[girl][he] > guysRank }
        for(Man otherGuy : sheLikesBetter) {
            Woman otherGuyFiancee = matches.find{ pair -> pair.value == otherGuy }.key
            if(guysGalRanking[otherGuy][girl] > guysGalRanking[otherGuy][otherGuyFiancee]) {
                println """O. M. G. ... ${otherGuy} likes ${girl} better than ${otherGuyFiancee}, and ${girl} likes ${otherGuy} better than ${guy}!
                            I am TOTALLY 'shipping ${girl} and ${otherGuy} now!"""
                return false
            }
        }

        int galsRank = guysGalRanking[guy][girl]
        List<Woman> heLikesBetter = Woman.values().findAll{ she -> guysGalRanking[guy][she] > galsRank }
        for(Woman otherGal : heLikesBetter) {
            Man otherGalFiance = matches[otherGal]
            if(galsGuyRanking[otherGal][guy] > galsGuyRanking[otherGal][otherGalFiance]) {
                println """O. M. G. ... ${otherGal} likes ${guy} better than ${otherGalFiance}, and ${guy} likes ${otherGal} better than ${girl}!
                            I am TOTALLY 'shipping ${guy} and ${otherGal} now!"""
                return false
            }
        }
        true
    }.every()
}

enum Man {
    abe, bob, col, dan, ed, fred, gav, hal, ian, jon
}

enum Woman {
    abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
}

Map<Man,Map<Woman,Integer>> mansWomanRanking = [
    (abe): [(abi):10, (eve):9, (cath):8, (ivy):7, (jan):6, (dee):5, (fay):4, (bea):3, (hope):2, (gay):1],
    (bob): [(cath):10, (hope):9, (abi):8, (dee):7, (eve):6, (fay):5, (bea):4, (jan):3, (ivy):2, (gay):1],
    (col): [(hope):10, (eve):9, (abi):8, (dee):7, (bea):6, (fay):5, (ivy):4, (gay):3, (cath):2, (jan):1],
    (dan): [(ivy):10, (fay):9, (dee):8, (gay):7, (hope):6, (eve):5, (jan):4, (bea):3, (cath):2, (abi):1],
    (ed):  [(jan):10, (dee):9, (bea):8, (cath):7, (fay):6, (eve):5, (abi):4, (ivy):3, (hope):2, (gay):1],
    (fred):[(bea):10, (abi):9, (dee):8, (gay):7, (eve):6, (ivy):5, (cath):4, (jan):3, (hope):2, (fay):1],
    (gav): [(gay):10, (eve):9, (ivy):8, (bea):7, (cath):6, (abi):5, (dee):4, (hope):3, (jan):2, (fay):1],
    (hal): [(abi):10, (eve):9, (hope):8, (fay):7, (ivy):6, (cath):5, (jan):4, (bea):3, (gay):2, (dee):1],
    (ian): [(hope):10, (cath):9, (dee):8, (gay):7, (bea):6, (abi):5, (fay):4, (ivy):3, (jan):2, (eve):1],
    (jon): [(abi):10, (fay):9, (jan):8, (gay):7, (eve):6, (bea):5, (dee):4, (cath):3, (ivy):2, (hope):1],
]

Map<Woman,List<Man>> womansManRanking = [
    (abi): [(bob):10, (fred):9, (jon):8, (gav):7, (ian):6, (abe):5, (dan):4, (ed):3, (col):2, (hal):1],
    (bea): [(bob):10, (abe):9, (col):8, (fred):7, (gav):6, (dan):5, (ian):4, (ed):3, (jon):2, (hal):1],
    (cath):[(fred):10, (bob):9, (ed):8, (gav):7, (hal):6, (col):5, (ian):4, (abe):3, (dan):2, (jon):1],
    (dee): [(fred):10, (jon):9, (col):8, (abe):7, (ian):6, (hal):5, (gav):4, (dan):3, (bob):2, (ed):1],
    (eve): [(jon):10, (hal):9, (fred):8, (dan):7, (abe):6, (gav):5, (col):4, (ed):3, (ian):2, (bob):1],
    (fay): [(bob):10, (abe):9, (ed):8, (ian):7, (jon):6, (dan):5, (fred):4, (gav):3, (col):2, (hal):1],
    (gay): [(jon):10, (gav):9, (hal):8, (fred):7, (bob):6, (abe):5, (col):4, (ed):3, (dan):2, (ian):1],
    (hope):[(gav):10, (jon):9, (bob):8, (abe):7, (ian):6, (dan):5, (hal):4, (ed):3, (col):2, (fred):1],
    (ivy): [(ian):10, (col):9, (hal):8, (gav):7, (fred):6, (bob):5, (abe):4, (ed):3, (jon):2, (dan):1],
    (jan): [(ed):10, (hal):9, (gav):8, (abe):7, (bob):6, (jon):5, (col):4, (ian):3, (fred):2, (dan):1],
]

// STABLE test
Map<Woman,Man> matches = match(mansWomanRanking, womansManRanking)
matches.each { w, m ->
    println "${w} (his '${mansWomanRanking[m][w]}' girl) is engaged to ${m} (her '${womansManRanking[w][m]}' guy)"
}
assert matches.keySet() == Woman.values() as Set
assert matches.values() as Set == Man.values() as Set
println ''

assert isStable(matches, mansWomanRanking, womansManRanking)

// PERTURBED test
println 'Swapping partners now ...'
def temp = matches[abi]
matches[abi] = matches[bea]
matches[bea] = temp
matches.each { w, m ->
    println "${w} (his '${mansWomanRanking[m][w]}' girl) is engaged to ${m} (her '${womansManRanking[w][m]}' guy)"
}
println ''

assert ! isStable(matches, mansWomanRanking, womansManRanking)

The code implements the Gale/Shapley algorithm to solve the Stable Marriage problem. It takes as input a list of ten males and ten females with their respective ranked preferences. The code then finds a stable set of engagements where no individual prefers someone else over their current partner. The code also perturbs this stable set to form an unstable set of engagements and checks for its stability.


def f = { println '  AHA!'; it instanceof String }
def g = { printf ('%5d ', it); it > 50 }

println 'bitwise'
assert g(100) & f('sss')
assert g(2) | f('sss')
assert ! (g(1) & f('sss'))
assert g(200) | f('sss')

println '''
logical'''
assert g(100) && f('sss')
assert g(2) || f('sss')
assert ! (g(1) && f('sss'))
assert g(200) || f('sss')

The code defines two functions, a and b, both of which take a boolean value as input, return the same value, and print their names when called. It then calculates the values of two equations, x = a(i) and b(j) and y = a(i) or b(j), using short-circuit evaluation to ensure that function b is only called when necessary. If the programming language does not support short-circuit evaluation, this is achieved using nested if statements. The code is written in Groovy, which supports short-circuiting for logical and (&&) and logical or (||) operations, but not for bitwise and (&) and bitwise or (|) operations.


class ABCSolver {
    def blocks

    ABCSolver(blocks = []) { this.blocks = blocks }

    boolean canMakeWord(rawWord) {
        if (rawWord == '' || rawWord == null) { return true; }
        def word = rawWord.toUpperCase()
        def blocksLeft = [] + blocks
        word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }
    }
}

def a = new ABCSolver(["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
                      "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"])

['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each {
    println "'${it}': ${a.canMakeWord(it)}"
}

The code is a function that checks if a given word can be spelled using a predefined collection of blocks, each with two letters. The blocks can only be used once and the function is case-insensitive. The function is tested with seven different words and returns a boolean value indicating whether or not the word can be spelled with the available blocks.


import java.security.MessageDigest

String.metaClass.md5Checksum = {
    MessageDigest.getInstance('md5').digest(delegate.bytes).collect { String.format("%02x", it) }.join('')
}

assert 'The quick brown fox jumps over the lazy dog'.md5Checksum() == '9e107d9d372bb6826bd81d3542a419d6'

The code implements the MD5 algorithm to encode a string. It optionally validates the implementation using test values from IETF RFC (1321) for MD5. It also includes a warning about MD5's known weaknesses and suggests stronger alternatives for production-grade cryptography. If the solution is a library solution, it refers to MD5/Implementation for a scratch implementation.


s = new java.net.Socket("localhost", 256)
s << "hello socket world"
s.close()

opens a socket to localhost on port 256, sends the message "hello socket world", and then closes the socket.


import javax.mail.*
import javax.mail.internet.*

public static void simpleMail(String from, String password, String to,
    String subject, String body) throws Exception {

    String host = "smtp.gmail.com";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable",true);
    /* mail.smtp.ssl.trust is needed in script to avoid error "Could not convert socket to TLS"  */
    props.setProperty("mail.smtp.ssl.trust", host);
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", "587");

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    InternetAddress toAddress = new InternetAddress(to);

    message.addRecipient(Message.RecipientType.TO, toAddress);

    message.setSubject(subject);
    message.setText(body);

    Transport transport = session.getTransport("smtp");

    transport.connect(host, from, password);

    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

/* Set email address sender */
String s1 = "example@gmail.com";

/* Set password sender */
String s2 = "";

/* Set email address sender */
String s3 = "example@gmail.com"

/*Call function */
simpleMail(s1, s2 , s3, "TITLE", "TEXT");

implement a function to send an email with parameters for setting From, To, Cc addresses, Subject, message text, and optional server name and login details. The function also provides notifications for problems/success and uses libraries or functions from the language, with potential for use of external programs. The solution is portable across different operating systems.


generate a sequential count in octal, starting from zero and incrementing by one on each line, until the program is terminated or the maximum numeric value is reached.


(a, b) = [b, a]

def swap(a, b) {
    [b, a]
}

def (x, y) = swap(1, 3)
assert x == 3
assert y == 1

def listSwap = { a, i, j ->
    assert (0..<(a.size())).containsAll([i,j]);
    a[[j,i]] = a[[i,j]]
}

def list = [2,4,6,8]
listSwap(list, 1, 3)
assert list == [2,8,6,4]

implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. The function also handles the constraints of statically typed languages and dynamically typed languages. It also includes an in-place swap of indexed elements in a list.


Trivial[edit]

def isPalindrome = { String s ->
    s == s?.reverse()
}

println isPalindrome("")
println isPalindrome("a")
println isPalindrome("abcdefgfedcba")
println isPalindrome("abcdeffedcba")
println isPalindrome("abcedfgfedcb")

The code checks if a given sequence of characters is a palindrome, supporting both standard and Unicode characters. It also includes a function to detect inexact palindromes by ignoring white-space, punctuation, and case differences. The code assumes nulls as palindromes but does not handle nulls in the recursive solution. It also includes a feature to reverse a string.


System.getenv().each { property, value -> println "$property = $value"}

"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system."


// version 1.1.2

class Stack<E> {
    private val data = mutableListOf<E>()

    val size get() = data.size

    val empty get() = size == 0

    fun push(element: E) = data.add(element)

    fun pop(): E {
        if (empty) throw RuntimeException("Can't pop elements from an empty stack")
        return data.removeAt(data.lastIndex)
    }

    val top: E
        get() {
            if (empty) throw RuntimeException("Empty stack can't have a top element")
            return data.last()
        }

    fun clear() = data.clear()

    override fun toString() = data.toString()
}

fun main(args: Array<String>) {
    val s = Stack<Int>()
    (1..5).forEach { s.push(it) }
    println(s)
    println("Size of stack = ${s.size}")
    print("Popping: ")
    (1..3).forEach { print("${s.pop()} ") }
    println("\nRemaining on stack: $s")
    println("Top element is now ${s.top}")
    s.clear()
    println("After clearing, stack is ${if(s.empty) "empty" else "not empty"}")
    try {
        s.pop()
    }
    catch (e: Exception) {
        println(e.message)
    }
}

implement a custom Stack class supporting basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack is empty). This Stack class follows the Last In, First Out (LIFO) principle.


enum class Fibonacci {
    ITERATIVE {
        override fun get(n: Int): Long = if (n < 2) {
            n.toLong()
        } else {
            var n1 = 0L
            var n2 = 1L
            repeat(n) {
                val sum = n1 + n2
                n1 = n2
                n2 = sum
            }
            n1
        }
    },
    RECURSIVE {
        override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2]
    },
    CACHING {
        val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)
        override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n)
        private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) }
    },
    ;

    abstract operator fun get(n: Int): Long
}

fun main() {
    val r = 0..30
    for (fib in Fibonacci.values()) {
        print("${fib.name.padEnd(10)}:")
        for (i in r) { print(" " + fib[i]) }
        println()
    }
}

generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.


// version 1.0.5-2

fun main(args: Array<String>) {
    val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
    println(array.joinToString(" "))

    val filteredArray = array.filter{ it % 2 == 0 }
    println(filteredArray.joinToString(" "))

    val mutableList = array.toMutableList()
    mutableList.retainAll { it % 2 == 0 }
    println(mutableList.joinToString(" "))
}

select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.


// version 1.0.6

fun main(args: Array<String>) {
    val s = "0123456789"
    val n = 3
    val m = 4
    val c = '5'
    val z = "12"
    var i: Int
    println(s.substring(n, n + m))
    println(s.substring(n))
    println(s.dropLast(1))
    i = s.indexOf(c)
    println(s.substring(i, i + m))
    i = s.indexOf(z)
    println(s.substring(i, i + m))
}

The code performs the following tasks:
1. Displays a substring starting from 'n' characters in and of 'm' length.
2. Displays a substring starting from 'n' characters in, up to the end of the string.
3. Displays the whole string minus the last character.
4. Displays a substring starting from a known character within the string and of 'm' length.
5. Displays a substring starting from a known substring within the string and of 'm' length.
The code is compatible with any valid Unicode code point in UTF-8 or UTF-16, and references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. The strings in the code are 0-indexed.


fun main(args: Array<String>) {
    println("asdf".reversed())
}

Reverses a given string while preserving Unicode combining characters. For instance, it transforms "asdf" to "fdsa" and "as⃝df̅" to "f̅ds⃝a".


Translation of: FreeBASIC
// version 1.0.5-2

enum class PlayfairOption {
    NO_Q,
    I_EQUALS_J
}

class Playfair(keyword: String, val pfo: PlayfairOption) {
    private val table: Array<CharArray> = Array(5, { CharArray(5) })  // 5 x 5 char array

    init {
        // build table
        val used = BooleanArray(26)  // all elements false
        if (pfo == PlayfairOption.NO_Q)
            used[16] = true  // Q used
        else
            used[9]  = true  // J used
        val alphabet = keyword.toUpperCase() + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        var i = 0
        var j = 0
        var c: Char
        var d: Int
        for (k in 0 until alphabet.length) {
            c = alphabet[k]
            if (c !in 'A'..'Z') continue
            d = c.toInt() - 65
            if (!used[d]) {
                table[i][j] = c
                used[d] = true
                if (++j == 5) {
                    if (++i == 5) break // table has been filled
                    j = 0
                }
            }
        }
    }

    private fun getCleanText(plainText: String): String {
        val plainText2 = plainText.toUpperCase()  // ensure everything is upper case
        // get rid of any non-letters and insert X between duplicate letters
        var cleanText = ""
        var prevChar = '\u0000'  // safe to assume null character won't be present in plainText
        var nextChar: Char
        for (i in 0 until plainText2.length) {
            nextChar = plainText2[i]
            // It appears that Q should be omitted altogether if NO_Q option is specified - we assume so anyway
            if (nextChar !in 'A'..'Z' || (nextChar == 'Q' && pfo == PlayfairOption.NO_Q)) continue
            // If I_EQUALS_J option specified, replace J with I
            if (nextChar == 'J' && pfo == PlayfairOption.I_EQUALS_J) nextChar = 'I'
            if (nextChar != prevChar)
                cleanText += nextChar
            else
                cleanText += "X" + nextChar
            prevChar = nextChar
        }
        val len = cleanText.length
        if (len % 2 == 1)  {  // dangling letter at end so add another letter to complete digram
            if (cleanText[len - 1] != 'X')
                cleanText += 'X'
            else
                cleanText += 'Z'
        }
        return cleanText
    }

    private fun findChar(c: Char): Pair<Int, Int> {
       for (i in 0..4)
           for (j in 0..4)
               if (table[i][j] == c) return Pair(i, j)
       return Pair(-1, -1)
    }

    fun encode(plainText: String): String {
        val cleanText = getCleanText(plainText)
        var cipherText = ""
        val length = cleanText.length
        for (i in 0 until length step 2) {
            val (row1, col1) = findChar(cleanText[i])
            val (row2, col2) = findChar(cleanText[i + 1])
            cipherText += when {
                row1 == row2 -> table[row1][(col1 + 1) % 5].toString() + table[row2][(col2 + 1) % 5]
                col1 == col2 -> table[(row1 + 1) % 5][col1].toString() + table[(row2 + 1) % 5][col2]
                else         -> table[row1][col2].toString() + table[row2][col1]
            }
            if (i < length - 1) cipherText += " "
        }
        return cipherText
    }

    fun decode(cipherText: String): String {
        var decodedText = ""
        val length = cipherText.length
        for (i in 0 until length step 3) {  // cipherText will include spaces so we need to skip them
            val (row1, col1) = findChar(cipherText[i])
            val (row2, col2) = findChar(cipherText[i + 1])
            decodedText += when {
                row1 == row2 -> table[row1][if (col1 > 0) col1 - 1 else 4].toString() + table[row2][if (col2 > 0) col2 - 1 else 4]
                col1 == col2 -> table[if (row1 > 0) row1- 1 else 4][col1].toString() + table[if (row2 > 0) row2 - 1 else 4][col2]
                else         -> table[row1][col2].toString() + table[row2][col1]
            }
            if (i < length - 1) decodedText += " "
        }
        return decodedText
    }

    fun printTable() {
        println("The table to be used is :\n")
        for (i in 0..4) {
            for (j in 0..4) print(table[i][j] + " ")
            println()
        }
    }
}

fun main(args: Array<String>) {
    print("Enter Playfair keyword : ")
    val keyword: String = readLine()!!
    var ignoreQ: String
    do {
         print("Ignore Q when buiding table  y/n : ")
         ignoreQ = readLine()!!.toLowerCase()
    }
    while (ignoreQ != "y" && ignoreQ != "n")
    val pfo = if (ignoreQ == "y") PlayfairOption.NO_Q else PlayfairOption.I_EQUALS_J
    val playfair = Playfair(keyword, pfo)
    playfair.printTable()
    print("\nEnter plain text : ")
    val plainText: String = readLine()!!
    val encodedText = playfair.encode(plainText)
    println("\nEncoded text is : $encodedText")
    val decodedText = playfair.decode(encodedText)
    println("Decoded text is : $decodedText")
}

Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.


Translation of: Java
// version 1.1.51

import java.util.TreeSet

class Edge(val v1: String, val v2: String, val dist: Int)

 /** One vertex of the graph, complete with mappings to neighbouring vertices */
class Vertex(val name: String) : Comparable<Vertex> {

    var dist = Int.MAX_VALUE  // MAX_VALUE assumed to be infinity
    var previous: Vertex? = null
    val neighbours = HashMap<Vertex, Int>()

    fun printPath() {
        if (this == previous) {
            print(name)
        }
        else if (previous == null) {
            print("$name(unreached)")
        }
        else {
            previous!!.printPath()
            print(" -> $name($dist)")
        }
    }

    override fun compareTo(other: Vertex): Int {
        if (dist == other.dist) return name.compareTo(other.name)
        return dist.compareTo(other.dist)
    }

    override fun toString() = "($name, $dist)"
}

class Graph(
    val edges: List<Edge>,
    val directed: Boolean,
    val showAllPaths: Boolean = false
) {
    // mapping of vertex names to Vertex objects, built from a set of Edges
    private val graph = HashMap<String, Vertex>(edges.size)

    init {
        // one pass to find all vertices
        for (e in edges) {
            if (!graph.containsKey(e.v1)) graph.put(e.v1, Vertex(e.v1))
            if (!graph.containsKey(e.v2)) graph.put(e.v2, Vertex(e.v2))
        }

        // another pass to set neighbouring vertices
        for (e in edges) {
            graph[e.v1]!!.neighbours.put(graph[e.v2]!!, e.dist)
            // also do this for an undirected graph if applicable
            if (!directed) graph[e.v2]!!.neighbours.put(graph[e.v1]!!, e.dist)
        }
    }

    /** Runs dijkstra using a specified source vertex */
    fun dijkstra(startName: String) {
        if (!graph.containsKey(startName)) {
            println("Graph doesn't contain start vertex '$startName'")
            return
        }
        val source = graph[startName]
        val q = TreeSet<Vertex>()

        // set-up vertices
        for (v in graph.values) {
            v.previous = if (v == source) source else null
            v.dist = if (v == source)  0 else Int.MAX_VALUE
            q.add(v)
        }

        dijkstra(q)
    }

    /** Implementation of dijkstra's algorithm using a binary heap */
    private fun dijkstra(q: TreeSet<Vertex>) {
        while (!q.isEmpty()) {
            // vertex with shortest distance (first iteration will return source)
            val u = q.pollFirst()
            // if distance is infinite we can ignore 'u' (and any other remaining vertices)
            // since they are unreachable
            if (u.dist == Int.MAX_VALUE) break

            //look at distances to each neighbour
            for (a in u.neighbours) {
                val v = a.key // the neighbour in this iteration

                val alternateDist = u.dist + a.value
                if (alternateDist < v.dist) { // shorter path to neighbour found
                    q.remove(v)
                    v.dist = alternateDist
                    v.previous = u
                    q.add(v)
                }
            }
        }
    }

    /** Prints a path from the source to the specified vertex */
    fun printPath(endName: String) {
        if (!graph.containsKey(endName)) {
            println("Graph doesn't contain end vertex '$endName'")
            return
        }
        print(if (directed) "Directed   : " else "Undirected : ")
        graph[endName]!!.printPath()
        println()
        if (showAllPaths) printAllPaths() else println()
    }

    /** Prints the path from the source to every vertex (output order is not guaranteed) */
    private fun printAllPaths() {
        for (v in graph.values) {
            v.printPath()
            println()
        }
        println()
    }
}

val GRAPH = listOf(
    Edge("a", "b", 7),
    Edge("a", "c", 9),
    Edge("a", "f", 14),
    Edge("b", "c", 10),
    Edge("b", "d", 15),
    Edge("c", "d", 11),
    Edge("c", "f", 2),
    Edge("d", "e", 6),
    Edge("e", "f", 9)
)

const val START = "a"
const val END = "e"

fun main(args: Array<String>) {
    with (Graph(GRAPH, true)) {   // directed
        dijkstra(START)
        printPath(END)
    }
    with (Graph(GRAPH, false)) {  // undirected
        dijkstra(START)
        printPath(END)
    }
}

Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.


Translation of: Java
class AvlTree {
    private var root: Node? = null

    private class Node(var key: Int, var parent: Node?) {
        var balance: Int = 0
        var left : Node? = null
        var right: Node? = null
    }

    fun insert(key: Int): Boolean {
        if (root == null)
            root = Node(key, null)
        else {
            var n: Node? = root
            var parent: Node
            while (true) {
                if (n!!.key == key) return false
                parent = n
                val goLeft = n.key > key
                n = if (goLeft) n.left else n.right
                if (n == null) {
                    if (goLeft)
                        parent.left  = Node(key, parent)
                    else
                        parent.right = Node(key, parent)
                    rebalance(parent)
                    break
                }
            }
        }
        return true
    }

    fun delete(delKey: Int) {
        if (root == null) return
        var n:       Node? = root
        var parent:  Node? = root
        var delNode: Node? = null
        var child:   Node? = root
        while (child != null) {
            parent = n
            n = child
            child = if (delKey >= n.key) n.right else n.left
            if (delKey == n.key) delNode = n
        }
        if (delNode != null) {
            delNode.key = n!!.key
            child = if (n.left != null) n.left else n.right
            if (0 == root!!.key.compareTo(delKey)) {
                root = child

                if (null != root) {
                    root!!.parent = null
                }

            } else {
                if (parent!!.left == n)
                    parent.left = child
                else
                    parent.right = child

                if (null != child) {
                    child.parent = parent
                }

                rebalance(parent)
            }
    }

    private fun rebalance(n: Node) {
        setBalance(n)
        var nn = n
        if (nn.balance == -2)
            if (height(nn.left!!.left) >= height(nn.left!!.right))
                nn = rotateRight(nn)
            else
                nn = rotateLeftThenRight(nn)
        else if (nn.balance == 2)
            if (height(nn.right!!.right) >= height(nn.right!!.left))
                nn = rotateLeft(nn)
            else
                nn = rotateRightThenLeft(nn)
        if (nn.parent != null) rebalance(nn.parent!!)
        else root = nn
    }

    private fun rotateLeft(a: Node): Node {
        val b: Node? = a.right
        b!!.parent = a.parent
        a.right = b.left
        if (a.right != null) a.right!!.parent = a
        b.left = a
        a.parent = b
        if (b.parent != null) {
            if (b.parent!!.right == a)
                b.parent!!.right = b
            else
                b.parent!!.left = b
        }
        setBalance(a, b)
        return b
    }

    private fun rotateRight(a: Node): Node {
        val b: Node? = a.left
        b!!.parent = a.parent
        a.left = b.right
        if (a.left != null) a.left!!.parent = a
        b.right = a
        a.parent = b
        if (b.parent != null) {
            if (b.parent!!.right == a)
                b.parent!!.right = b
            else
                b.parent!!.left = b
        }
        setBalance(a, b)
        return b
    }

    private fun rotateLeftThenRight(n: Node): Node {
        n.left = rotateLeft(n.left!!)
        return rotateRight(n)
    }

    private fun rotateRightThenLeft(n: Node): Node {
        n.right = rotateRight(n.right!!)
        return rotateLeft(n)
    }

    private fun height(n: Node?): Int {
        if (n == null) return -1
        return 1 + Math.max(height(n.left), height(n.right))
    }

    private fun setBalance(vararg nodes: Node) {
        for (n in nodes) n.balance = height(n.right) - height(n.left)
    }

    fun printKey() {
        printKey(root)
        println()
    }

    private fun printKey(n: Node?) {
        if (n != null) {
            printKey(n.left)
            print("${n.key} ")
            printKey(n.right)
        }
    }

    fun printBalance() {
        printBalance(root)
        println()
    }

    private fun printBalance(n: Node?) {
        if (n != null) {
            printBalance(n.left)
            print("${n.balance} ")
            printBalance(n.right)
        }
    }
}

fun main(args: Array<String>) {
    val tree = AvlTree()
    println("Inserting values 1 to 10")
    for (i in 1..10) tree.insert(i)
    print("Printing key     : ")
    tree.printKey()
    print("Printing balance : ")
    tree.printBalance()
}

implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.


// version 1.1.51

typealias IAE = IllegalArgumentException

class Point(val x: Double, val y: Double) {
    fun distanceFrom(other: Point): Double {
        val dx = x - other.x
        val dy = y - other.y
        return Math.sqrt(dx * dx + dy * dy )
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || other !is Point) return false
        return (x == other.x && y == other.y)
    }

    override fun toString() = "(%.4f, %.4f)".format(x, y)
}

fun findCircles(p1: Point, p2: Point, r: Double): Pair<Point, Point> {
    if (r < 0.0) throw IAE("the radius can't be negative")
    if (r == 0.0 && p1 != p2) throw IAE("no circles can ever be drawn")
    if (r == 0.0) return p1 to p1
    if (p1 == p2) throw IAE("an infinite number of circles can be drawn")
    val distance = p1.distanceFrom(p2)
    val diameter = 2.0 * r
    if (distance > diameter) throw IAE("the points are too far apart to draw a circle")
    val center = Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0)
    if (distance == diameter) return center to center
    val mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0)
    val dx =  (p2.x - p1.x) * mirrorDistance / distance
    val dy =  (p2.y - p1.y) * mirrorDistance / distance
    return Point(center.x - dy, center.y + dx) to
           Point(center.x + dy, center.y - dx)
}

fun main(args: Array<String>) {
    val p = arrayOf(
        Point(0.1234, 0.9876),
        Point(0.8765, 0.2345),
        Point(0.0000, 2.0000),
        Point(0.0000, 0.0000)
    )
    val points = arrayOf(
        p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0]
    )
    val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0)
    for (i in 0..4) {
        try {
            val (p1, p2) = points[i]
            val r  = radii[i]
            println("For points $p1 and $p2 with radius $r")
            val (c1, c2) = findCircles(p1, p2, r)
            if (c1 == c2)
                println("there is just one circle with center at $c1")
            else
                println("there are two circles with centers at $c1 and $c2")
        }
        catch(ex: IllegalArgumentException) {
            println(ex.message)
        }
        println()
    }
}

"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned."


Translation of: Go
// version 1.1.4-3

fun Byte.toUInt()  = java.lang.Byte.toUnsignedInt(this)

fun Byte.toULong() = java.lang.Byte.toUnsignedLong(this)

fun Int.toULong()  = java.lang.Integer.toUnsignedLong(this)

val s = arrayOf(
    byteArrayOf( 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3),
    byteArrayOf(14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9),
    byteArrayOf( 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11),
    byteArrayOf( 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3),
    byteArrayOf( 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2),
    byteArrayOf( 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14),
    byteArrayOf(13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12),
    byteArrayOf( 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12)
)

class Gost(val sBox: Array<ByteArray>) {

    val k87 = ByteArray(256)
    val k65 = ByteArray(256)
    val k43 = ByteArray(256)
    val k21 = ByteArray(256)
    val enc = ByteArray(8)

    init {
        for (i in 0 until 256) {
            val j = i ushr 4
            val k = i and 15
            k87[i] = ((sBox[7][j].toUInt() shl 4) or sBox[6][k].toUInt()).toByte()
            k65[i] = ((sBox[5][j].toUInt() shl 4) or sBox[4][k].toUInt()).toByte()
            k43[i] = ((sBox[3][j].toUInt() shl 4) or sBox[2][k].toUInt()).toByte()
            k21[i] = ((sBox[1][j].toUInt() shl 4) or sBox[0][k].toUInt()).toByte()
        }
    }

    fun f(x: Int): Int {
        val y = (k87[(x ushr 24) and 255].toULong() shl 24) or
                (k65[(x ushr 16) and 255].toULong() shl 16) or
                (k43[(x ushr  8) and 255].toULong() shl  8) or
                (k21[ x and 255].toULong())
        return ((y shl 11) or (y ushr 21)).toInt()
    }

    fun u32(ba: ByteArray): Int =
        (ba[0].toULong() or
        (ba[1].toULong() shl 8) or
        (ba[2].toULong() shl 16) or
        (ba[3].toULong() shl 24)).toInt()

    fun b4(u: Int) {
        enc[0] = u.toByte()
        enc[1] = (u ushr  8).toByte()
        enc[2] = (u ushr 16).toByte()
        enc[3] = (u ushr 24).toByte()
    }

    fun mainStep(input: ByteArray, key: ByteArray) {
        val key32  = u32(key)
        val input1 = u32(input.sliceArray(0..3))
        val input2 = u32(input.sliceArray(4..7))
        val temp   = (key32.toULong() + input1.toULong()).toInt()
        b4(f(temp) xor input2)
        for (i in 0..3) enc[4 + i] = input[i]
    }
}

fun main(args: Array<String>) {
    val input = byteArrayOf(0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04)
    val key = byteArrayOf(0xF9.toByte(), 0x04, 0xC1.toByte(), 0xE2.toByte())
    val g = Gost(s)
    g.mainStep(input, key)
    for (b in g.enc) print("[%02X]".format(b))
    println()
}

Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.


import kotlin.random.Random

fun main() {
    while (true) {
        val a = Random.nextInt(20)
        println(a)
        if (a == 10) break
        println(Random.nextInt(20))
    }
}

import kotlin.random.Random

fun main() {
    while (Random.nextInt(20).also { println(it) } != 10)
        println(Random.nextInt(20))
}

generates and prints random numbers from 0 to 19. If the number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


Translation of: C
// version 1.0.6

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun main(args: Array<String>) {
    // test 929 plus all prime numbers below 100 which are known not to be Mersenne primes
    val q = intArrayOf(11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929)
    for (k in 0 until q.size) {
        if (isPrime(q[k])) {
            var i: Long
            var d: Int
            var p: Int
            var r: Int = q[k]
            while (r > 0) r = r shl 1
            d = 2 * q[k] + 1
            while (true) {
                i = 1L
                p = r
                while (p != 0) {
                    i = (i * i) % d
                    if (p < 0) i *= 2
                    if (i > d) i -= d
                    p = p shl 1
                }
                if (i != 1L)
                    d += 2 * q[k]
                else
                    break
            }
            println("2^${"%3d".format(q[k])} - 1 = 0 (mod $d)")
        } else {
            println("${q[k]} is not prime")
        }
    }
}

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


// version 1.1.3

import javax.xml.parsers.DocumentBuilderFactory
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.xpath.XPathFactory
import javax.xml.xpath.XPathConstants
import org.w3c.dom.Node
import org.w3c.dom.NodeList

val xml =
"""
<inventory title="OmniCorp Store #45x10^3">

    <item upc="123456789" stock="12">
      <name>Invisibility Cream</name>
      <price>14.50</price>
      <description>Makes you invisible</description>
    </item>
    <item upc="445322344" stock="18">
      <name>Levitation Salve</name>
      <price>23.99</price>
      <description>Levitate yourself for up to 3 hours per application</description>
    </item>

    <item upc="485672034" stock="653">
      <name>Blork and Freen Instameal</name>
      <price>4.95</price>
      <description>A tasty meal in a tablet; just add water</description>
    </item>
    <item upc="132957764" stock="44">
      <name>Grob winglets</name>
      <price>3.56</price>
      <description>Tender winglets of Grob. Just add water</description>
    </item>

</inventory>
"""

fun main(args: Array<String>) {
    val dbFactory = DocumentBuilderFactory.newInstance()
    val dBuilder  = dbFactory.newDocumentBuilder()
    val xmlInput = InputSource(StringReader(xml))
    val doc = dBuilder.parse(xmlInput)
    val xpFactory = XPathFactory.newInstance()
    val xPath = xpFactory.newXPath()

    val qNode = xPath.evaluate("/inventory/section/item[1]", doc, XPathConstants.NODE) as Node
    val upc = qNode.attributes.getNamedItem("upc")
    val stock = qNode.attributes.getNamedItem("stock")
    println("For the first item :  upc = ${upc.textContent} and stock = ${stock.textContent}")

    val qNodes = xPath.evaluate("/inventory/section/item/price", doc, XPathConstants.NODESET) as NodeList
    print("\nThe prices of each item are : ")
    for (i in 0 until qNodes.length) print("${qNodes.item(i).textContent}  ")
    println()

    val qNodes2 = xPath.evaluate("/inventory/section/item/name", doc, XPathConstants.NODESET) as NodeList
    val names = Array<String>(qNodes2.length) { qNodes2.item(it).textContent }
    println("\nThe names of each item are as follows :")
    println("  ${names.joinToString("\n  ")}")
}

1. Retrieves the first "item" element from the XML document.
2. Prints out each "price" element from the XML document.
3. Gets an array of all the "name" elements from the XML document.


// version 1.0.6

fun main(args: Array<String>) {
   val fruits  = setOf("apple", "pear", "orange", "banana")
   println("fruits  : $fruits")
   val fruits2 = setOf("melon", "orange", "lemon", "gooseberry")
   println("fruits2 : $fruits2\n")

   println("fruits  contains 'banana'     : ${"banana" in fruits}")
   println("fruits2 contains 'elderberry' : ${"elderbury" in fruits2}\n")

   println("Union        : ${fruits.union(fruits2)}")
   println("Intersection : ${fruits.intersect(fruits2)}")
   println("Difference   : ${fruits.minus(fruits2)}\n")

   println("fruits2 is a subset of fruits : ${fruits.containsAll(fruits2)}\n")
   val fruits3 = fruits
   println("fruits3 : $fruits3\n")
   var areEqual = fruits.containsAll(fruits2) && fruits3.containsAll(fruits)
   println("fruits2 and fruits are equal  : $areEqual")
   areEqual = fruits.containsAll(fruits3) && fruits3.containsAll(fruits)
   println("fruits3 and fruits are equal  : $areEqual\n")

   val fruits4 = setOf("apple", "orange")
   println("fruits4 : $fruits4\n")
   var isProperSubset = fruits.containsAll(fruits3) && !fruits3.containsAll(fruits)
   println("fruits3 is a proper subset of fruits : $isProperSubset")
   isProperSubset = fruits.containsAll(fruits4) && !fruits4.containsAll(fruits)
   println("fruits4 is a proper subset of fruits : $isProperSubset\n")

   val fruits5 = mutableSetOf("cherry", "blueberry", "raspberry")
   println("fruits5 : $fruits5\n")
   fruits5 += "guava"
   println("fruits5 + 'guava'  : $fruits5")
   println("fruits5 - 'cherry' : ${fruits5 - "cherry"}")
}

demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.


// version 1.0.6

import java.util.*

fun main(args: Array<String>) {
    println("Christmas day in the following years falls on a Sunday:\n")
    val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25)
    for (year in 2008..2121) {
        if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year)
        calendar.add(Calendar.YEAR, 1)
    }
}

The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date/time representation, such as overflow issues similar to y2k problems.


Translation of: Java
fun main(args: Array<String>) {
    val data = listOf(1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d")
    val set = data.distinct()

    println(data)
    println(set)
}

implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.


fun <E : Comparable<E>> List<E>.qsort(): List<E> =
        if (size < 2) this
        else filter { it < first() }.qsort() +
                filter { it == first() } +
                filter { it > first() }.qsort()

fun <E : Comparable<E>> List<E>.qsort(): List<E> =
        if (size < 2) this
        else {
            val (less, high) = subList(1, size).partition { it < first() }
            less.qsort() + first() + high.qsort()
        }

implement the quicksort algorithm to sort an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and combines them with the pivot to get the sorted array. The codes also include two versions of the quicksort algorithm, one that creates new arrays for the partitions and another that sorts the array in place to save memory. The pivot selection method is not specified.


// version 1.0.6

import java.util.GregorianCalendar

fun main(args: Array<String>) {
    val now = GregorianCalendar()
    println("%tF".format(now))
    println("%tA, %1\$tB %1\$te, %1\$tY".format(now))
}

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


// purely functional & lazy version, leveraging recursion and Sequences (a.k.a. streams)
fun <T> Set<T>.subsets(): Sequence<Set<T>> =
    when (size) {
        0 -> sequenceOf(emptySet())
        else -> {
            val head = first()
            val tail = this - head
            tail.subsets() + tail.subsets().map { setOf(head) + it }
        }
    }

// if recursion is an issue, you may change it this way:

fun <T> Set<T>.subsets(): Sequence<Set<T>> = sequence {
    when (size) {
        0 -> yield(emptySet<T>())
        else -> {
            val head = first()
            val tail = this@subsets - head
            yieldAll(tail.subsets())
            for (subset in tail.subsets()) {
                yield(setOf(head) + subset)
            }
        }
    }
}

implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.


val romanNumerals = mapOf(
    1000 to "M",
    900 to "CM",
    500 to "D",
    400 to "CD",
    100 to "C",
    90 to "XC",
    50 to "L",
    40 to "XL",
    10 to "X",
    9 to "IX",
    5 to "V",
    4 to "IV",
    1 to "I"
)

fun encode(number: Int): String? {
    if (number > 5000 || number < 1) {
        return null
    }
    var num = number
    var result = ""
    for ((multiple, numeral) in romanNumerals.entries) {
        while (num >= multiple) {
            num -= multiple
            result += numeral
        }
    }
    return result
}

fun main(args: Array<String>) {
    println(encode(1990))
    println(encode(1666))
    println(encode(2008))
}

implement a function that converts a positive integer into its equivalent Roman numeral representation. The function works by expressing each digit separately, starting from the leftmost digit and ignoring any digit with a value of zero.


fun main(x: Array<String>) {
    var a = arrayOf(1, 2, 3, 4)
    println(a.asList())
    a += 5
    println(a.asList())
    println(a.reversedArray().asList())
}

demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    val text = File("input.txt").readText()
    File("output.txt").writeText(text)
}

demonstrate reading the contents of "input.txt" file into a variable and then writing this variable's contents into a new file called "output.txt".


// version 1.0.6

fun main(args: Array<String>) {
    val s = "alphaBETA"
    println(s.toUpperCase())
    println(s.toLowerCase())
    println(s.capitalize())
    println(s.decapitalize())
}

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.


// version 1.1.2

typealias Point = Pair<Double, Double>

fun distance(p1: Point, p2: Point) = Math.hypot(p1.first- p2.first, p1.second - p2.second)

fun bruteForceClosestPair(p: List<Point>): Pair<Double, Pair<Point, Point>> {
    val n = p.size
    if (n < 2) throw IllegalArgumentException("Must be at least two points")
    var minPoints = p[0] to p[1]
    var minDistance = distance(p[0], p[1])
    for (i in 0 until n - 1)
        for (j in i + 1 until n) {
            val dist = distance(p[i], p[j])
            if (dist < minDistance) {
                minDistance = dist
                minPoints = p[i] to p[j]
            }
        }
    return minDistance to Pair(minPoints.first, minPoints.second)
}

fun optimizedClosestPair(xP: List<Point>, yP: List<Point>): Pair<Double, Pair<Point, Point>> {
    val n = xP.size
    if (n <= 3) return bruteForceClosestPair(xP)
    val xL = xP.take(n / 2)
    val xR = xP.drop(n / 2)
    val xm = xP[n / 2 - 1].first
    val yL = yP.filter { it.first <= xm }
    val yR = yP.filter { it.first >  xm }
    val (dL, pairL) = optimizedClosestPair(xL, yL)
    val (dR, pairR) = optimizedClosestPair(xR, yR)
    var dmin = dR
    var pairMin = pairR
    if (dL < dR) {
        dmin = dL
        pairMin = pairL
    }
    val yS = yP.filter { Math.abs(xm - it.first) < dmin }
    val nS = yS.size
    var closest = dmin
    var closestPair = pairMin
    for (i in 0 until nS - 1) {
        var k = i + 1
        while (k < nS && (yS[k].second - yS[i].second < dmin)) {
            val dist = distance(yS[k], yS[i])
            if (dist < closest) {
                closest = dist
                closestPair = Pair(yS[k], yS[i])
            }
            k++
        }
    }
    return closest to closestPair
}

fun main(args: Array<String>) {
    val points = listOf(
        listOf(
            5.0 to  9.0, 9.0 to 3.0,  2.0 to 0.0, 8.0 to  4.0, 7.0 to 4.0,
            9.0 to 10.0, 1.0 to 9.0,  8.0 to 2.0, 0.0 to 10.0, 9.0 to 6.0
        ),
        listOf(
            0.654682 to 0.925557, 0.409382 to 0.619391, 0.891663 to 0.888594,
            0.716629 to 0.996200, 0.477721 to 0.946355, 0.925092 to 0.818220,
            0.624291 to 0.142924, 0.211332 to 0.221507, 0.293786 to 0.691701,
            0.839186 to 0.728260
        )
    )
    for (p in points) {
        val (dist, pair) = bruteForceClosestPair(p)
        println("Closest pair (brute force) is ${pair.first} and ${pair.second}, distance $dist")
        val xP = p.sortedBy { it.first }
        val yP = p.sortedBy { it.second }
        val (dist2, pair2) = optimizedClosestPair(xP, yP)
        println("Closest pair (optimized)   is ${pair2.first} and ${pair2.second}, distance $dist2\n")
    }
}

provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.


import java.util.PriorityQueue

fun main(args: Array<String>) {
    // generic array
    val ga = arrayOf(1, 2, 3)
    println(ga.joinToString(prefix = "[", postfix = "]"))

    // specialized array (one for each primitive type)
    val da = doubleArrayOf(4.0, 5.0, 6.0)
    println(da.joinToString(prefix = "[", postfix = "]"))

    // immutable list
    val li = listOf<Byte>(7, 8, 9)
    println(li)

    // mutable list
    val ml = mutableListOf<Short>()
    ml.add(10); ml.add(11); ml.add(12)
    println(ml)

    // immutable map
    val hm = mapOf('a' to 97, 'b' to 98, 'c' to 99)
    println(hm)

    // mutable map
    val mm = mutableMapOf<Char, Int>()
    mm.put('d', 100); mm.put('e', 101); mm.put('f', 102)
    println(mm)

    // immutable set (duplicates not allowed)
    val se = setOf(1, 2, 3)
    println(se)

    // mutable set (duplicates not allowed)
    val ms = mutableSetOf<Long>()
    ms.add(4L); ms.add(5L); ms.add(6L)
    println(ms)

    // priority queue (imported from Java)
    val pq = PriorityQueue<String>()
    pq.add("First"); pq.add("Second"); pq.add("Third")
    println(pq)
}

demonstrate the creation of a collection in a statically-typed language, with the addition of a few values. The code also highlights the distinction between mutable and immutable collection types in Kotlin, including arrays. It also showcases how Kotlin can access other Java collection types such as LinkedList, Queue, Deque, and Stack.


Translation of: C

// version 1.1.2

data class Item(val name: String, val value: Double, val weight: Double, val volume: Double)

val items = listOf(
    Item("panacea", 3000.0, 0.3, 0.025),
    Item("ichor", 1800.0, 0.2, 0.015),
    Item("gold", 2500.0, 2.0, 0.002)
)

val n = items.size
val count = IntArray(n)
val best  = IntArray(n)
var bestValue = 0.0

const val MAX_WEIGHT = 25.0
const val MAX_VOLUME = 0.25

fun knapsack(i: Int, value: Double, weight: Double, volume: Double) {
    if (i == n) {
        if (value > bestValue) {
            bestValue = value
            for (j in 0 until n) best[j] = count[j]
        }
        return
    }
    val m1 = Math.floor(weight / items[i].weight).toInt()
    val m2 = Math.floor(volume / items[i].volume).toInt()
    val m  = minOf(m1, m2)
    count[i] = m
    while (count[i] >= 0) {
        knapsack(
            i + 1,
            value  + count[i] * items[i].value,
            weight - count[i] * items[i].weight,
            volume - count[i] * items[i].volume
        )
        count[i]--
    }
}

fun main(args: Array<String>) {
    knapsack(0, 0.0, MAX_WEIGHT, MAX_VOLUME)
    println("Item Chosen  Number Value  Weight  Volume")
    println("-----------  ------ -----  ------  ------")
    var itemCount = 0
    var sumNumber = 0
    var sumWeight = 0.0
    var sumVolume = 0.0
    for (i in 0 until n) {
        if (best[i] == 0) continue
        itemCount++
        val name   = items[i].name
        val number = best[i]
        val value  = items[i].value  * number
        val weight = items[i].weight * number
        val volume = items[i].volume * number
        sumNumber += number
        sumWeight += weight
        sumVolume += volume
        print("${name.padEnd(11)}   ${"%2d".format(number)}    ${"%5.0f".format(value)}   ${"%4.1f".format(weight)}")
        println("    ${"%4.2f".format(volume)}")
    }
    println("-----------  ------ -----  ------  ------")
    print("${itemCount} items       ${"%2d".format(sumNumber)}    ${"%5.0f".format(bestValue)}   ${"%4.1f".format(sumWeight)}")
    println("    ${"%4.2f".format(sumVolume)}")
}

"Output: The code implements a solution to the unbounded Knapsack problem. It calculates the maximum value a traveler can carry from Shangri La, given a weight limit of 25 and volume limit of 0.25. The code considers the weight, volume, and value of each item (panacea, ichor, gold) and returns the optimal quantity of each item to maximize the total value. It uses a recursive brute force approach and only needs to provide one of the four possible solutions."


// version 1.0.6

fun main(args: Array<String>) {
    for (i in 1 .. 10) {
        print(i)
        if (i < 10) print(", ")
    }
}

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


Translation of: Java
// version 1.1.51

val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
        "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"

val deps = mutableListOf(
     2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
     3 to 1, 3 to 10, 3 to 11,
     4 to 1, 4 to 10,
     5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
     6 to 1, 6 to 3, 6 to 10, 6 to 11,
     7 to 1, 7 to 10,
     8 to 1, 8 to 10,
     9 to 1, 9 to 10,
     10 to 1,
     11 to 1,
     12 to 0, 12 to 1,
     13 to 1
)

class Graph(s: String, edges: List<Pair<Int,Int>>) {

    val vertices = s.split(", ")
    val numVertices = vertices.size
    val adjacency = List(numVertices) { BooleanArray(numVertices) }

    init {
        for (edge in edges) adjacency[edge.first][edge.second] = true
    }

    fun hasDependency(r: Int, todo: List<Int>): Boolean {
        return todo.any { adjacency[r][it] }
    }

    fun topoSort(): List<String>? {
        val result = mutableListOf<String>()
        val todo = MutableList<Int>(numVertices) { it }
        try {
            outer@ while(!todo.isEmpty()) {
                for ((i, r) in todo.withIndex()) {
                    if (!hasDependency(r, todo)) {
                        todo.removeAt(i)
                        result.add(vertices[r])
                        continue@outer
                     }
                }
                throw Exception("Graph has cycles")
            }
        }
        catch (e: Exception) {
            println(e)
            return null
        }
        return result
    }
}

fun main(args: Array<String>) {
    val g = Graph(s, deps)
    println("Topologically sorted order:")
    println(g.topoSort())
    println()
    // now insert 3 to 6 at index 10 of deps
    deps.add(10, 3 to 6)
    val g2 = Graph(s, deps)
    println("Following the addition of dw04 to the dependencies of dw01:")
    println(g2.topoSort())
}

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


fun main() {
    val s1 = "abracadabra"
    val s2 = "abra"
    println("$s1 begins with $s2: ${s1.startsWith(s2)}")
    println("$s1 ends with $s2: ${s1.endsWith(s2)}")
    val b = s2 in s1
    if (b) {
        print("$s1 contains $s2 at these indices: ")
        // can use indexOf to get first index or lastIndexOf to get last index
        // to get ALL indices, use a for loop or Regex
        println(
            s2.toRegex(RegexOption.LITERAL).findAll(s1).joinToString { it.range.start.toString() }
        )
    }
    else println("$s1 does not contain $2.")
}

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


Translation of: C
// version 1.1.2

class FourSquares(
    private val lo: Int,
    private val hi: Int,
    private val unique: Boolean,
    private val show: Boolean
) {
    private var a = 0
    private var b = 0
    private var c = 0
    private var d = 0
    private var e = 0
    private var f = 0
    private var g = 0
    private var s = 0

    init {
        println()
        if (show) {
            println("a b c d e f g")
            println("-------------")
        }
        acd()
        println("\n$s ${if (unique) "unique" else "non-unique"} solutions in $lo to $hi")
    }

    private fun acd() {
        c = lo
        while (c <= hi) {
            d = lo
            while (d <= hi) {
                if (!unique || c != d) {
                    a = c + d
                    if ((a in lo..hi) && (!unique || (c != 0 && d!= 0))) ge()
                }
                d++
            }
            c++
        }
    }

    private fun bf() {
        f = lo
        while (f <= hi) {
            if (!unique || (f != a && f != c && f != d && f != e && f!= g)) {
                b = e + f - c
                if ((b in lo..hi) && (!unique || (b != a && b != c && b != d && b != e && b != f && b!= g))) {
                    s++
                    if (show) println("$a $b $c $d $e $f $g")
                }
            }
            f++
        }
    }

    private fun ge() {
        e = lo
        while (e <= hi) {
            if (!unique || (e != a && e != c && e != d)) {
                g = d + e
                if ((g in lo..hi) && (!unique || (g != a && g != c && g != d && g != e))) bf()
            }
            e++
        }
    }
}

fun main(args: Array<String>) {
    FourSquares(1, 7, true, true)
    FourSquares(3, 9, true, true)
    FourSquares(0, 9, false, false)
}

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.


Translation of: Java
// version 1.1

import java.awt.*
import java.time.LocalTime
import javax.swing.*

class Clock : JPanel() {
    private val degrees06: Float = (Math.PI / 30.0).toFloat()
    private val degrees30: Float = degrees06 * 5.0f
    private val degrees90: Float =  degrees30 * 3.0f
    private val size = 590
    private val spacing = 40
    private val diameter = size - 2 * spacing
    private val cx = diameter / 2 + spacing
    private val cy = cx

    init {
        preferredSize = Dimension(size, size)
        background =  Color.white
        Timer(1000) {
            repaint()
        }.start()
    }

    override public fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawFace(g)
        val time  = LocalTime.now()
        val hour = time.hour
        val minute = time.minute
        val second = time.second
        var angle: Float = degrees90 - degrees06 * second
        drawHand(g, angle, diameter / 2 - 30, Color.red)
        val minsecs: Float = minute + second / 60.0f
        angle = degrees90 - degrees06 * minsecs
        drawHand(g, angle, diameter / 3 + 10, Color.black)
        val hourmins: Float = hour + minsecs / 60.0f
        angle = degrees90 - degrees30 * hourmins
        drawHand(g, angle, diameter / 4 + 10, Color.black)
    }

    private fun drawFace(g: Graphics2D) {
        g.stroke = BasicStroke(2.0f)
        g.color = Color.yellow
        g.fillOval(spacing, spacing, diameter, diameter)
        g.color = Color.black
        g.drawOval(spacing, spacing, diameter, diameter)
    }

    private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) {
        val x: Int  = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt()
        val y: Int =  cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt()
        g.color = color
        g.drawLine(cx, cy, x, y)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        f.title = "Clock"
        f.isResizable = false
        f.add(Clock(), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.isVisible = true
    }
}

illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.