int[] Josephus (int size, int kill, int survivors) {
    // init user pool
    def users = new int[size];

    // give initial values such that [0] = 1 (first person) [1] = 2 (second person) etc
    users.eachWithIndex() {obj, i -> users[i] = i + 1};

    // keep track of which person we are on (ranging from 1 to kill)
    def person = 1;

    // keep going until we have the desired number of survivors
    while (users.size() > survivors)
    {
        // for each person, if they are the kill'th person, set them to -1 to show eliminated
        users.eachWithIndex() {obj, i ->
            if (person++ % kill == 0) {
                users[i] = -1;
            }

            // if person overflowed kill then reset back to 1
            if (person > kill) {person = 1;}
        }

        // clear out all eliminated persons
        users = users.findAll{w -> w >= 0};
    }

    // resulting set is the safe positions
    return users;
}

// Run some test cases

println "Final survivor for n = 10201 and k = 17: " + Josephus(10201,17,1)[0];

println "4 safe spots for n = 10201 and k = 17: " + Josephus(10201,17,4);


import Data.List ((\\))
import System.Environment (getArgs)

prisoners :: Int -> [Int]
prisoners n = [0 .. n - 1]

counter :: Int -> [Int]
counter k = cycle [k, k-1 .. 1]

killList :: [Int] -> [Int] -> ([Int], [Int], [Int])
killList xs cs = (killed, survivors, newCs)
    where
        (killed, newCs) = kill xs cs []
        survivors = xs \\ killed
        kill [] cs rs = (rs, cs)
        kill (x:xs) (c:cs) rs
            | c == 1 =
                let ts = rs ++ [x]
                in  kill xs cs ts
            | otherwise =
                kill xs cs rs

killRecursive :: [Int] -> [Int] -> Int -> ([Int], [Int])
killRecursive xs cs m = killR ([], xs, cs)
    where
        killR (killed, remaining, counter)
            | length remaining <= m = (killed, remaining)
            | otherwise =
                let (newKilled, newRemaining, newCounter) =
                        killList remaining counter
                    allKilled = killed ++ newKilled
                in  killR (allKilled, newRemaining, newCounter)

main :: IO ()
main = do
    args <- getArgs
    case args of
        [n, k, m] -> print $ snd $ killRecursive (prisoners (read n))
                        (counter (read k)) (read m)
        _         -> print $ snd $ killRecursive (prisoners 41) (counter 3) 1


'Knapsack problem/0-1 - 12/02/2017
Option Explicit
Const maxWeight = 400
Dim DataList As Variant
Dim xList(64, 3) As Variant
Dim nItems As Integer
Dim s  As String, xss As String
Dim xwei As Integer, xval As Integer, nn As Integer

Private Sub Form_Load()
    Dim i As Integer, j As Integer
    DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _
           "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _
           "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _
           "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _
           "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _
           "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50)
    nItems = (UBound(DataList) + 1) / 3
    j = 0
    For i = 1 To nItems
        xList(i, 1) = DataList(j)
        xList(i, 2) = DataList(j + 1)
        xList(i, 3) = DataList(j + 2)
        j = j + 3
    Next i
    For i = 1 To nItems
        xListBox.AddItem xList(i, 1)
    Next i
End Sub

Private Sub cmdOK_Click()
    Dim i As Integer, j As Integer
    For i = 1 To xListBox.ListCount
        xListBox.RemoveItem 0
    Next i
    s = ""
    For i = 1 To nItems
        s = s & Chr(i)
    Next
    nn = 0
    Call ChoiceBin(1, "")
    For i = 1 To Len(xss)
        j = Asc(Mid(xss, i, 1))
        xListBox.AddItem xList(j, 1)
    Next i
    xListBox.AddItem "*Total* " & xwei & " " & xval
End Sub

Private Sub ChoiceBin(n As String, ss As String)
    Dim r As String
    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer
    Dim ipct As Integer
    If n = Len(s) + 1 Then
        iwei = 0: ival = 0
        For i = 1 To Len(ss)
            j = Asc(Mid(ss, i, 1))
            iwei = iwei + xList(j, 2)
            ival = ival + xList(j, 3)
        Next
        If iwei <= maxWeight And ival > xval Then
            xss = ss: xwei = iwei: xval = ival
        End If
    Else
        r = Mid(s, n, 1)
        Call ChoiceBin(n + 1, ss & r)
        Call ChoiceBin(n + 1, ss)
    End If
End Sub 'ChoiceBin


procedure main(A)
   m := integer(A[1]) | 41
   c := integer(A[2]) | 3
   write("With ",m," men, counting to ",c," last position is: ", j(m,c))
end

procedure j(m,c)
   return if m==1 then 0 else (j(m-1,c)+c)%m
end


'Knapsack problem/0-1 - 12/02/2017
Public Class KnapsackBin
    Const knam = 0, kwei = 1, kval = 2
    Const maxWeight = 400
    Dim xList(,) As Object = { _
            {"map", 9, 150}, _
            {"compass", 13, 35}, _
            {"water", 153, 200}, _
            {"sandwich", 50, 160}, _
            {"glucose", 15, 60}, _
            {"tin", 68, 45}, _
            {"banana", 27, 60}, _
            {"ChoiceBinle", 39, 40}, _
            {"cheese", 23, 30}, _
            {"beer", 52, 10}, _
            {"suntan cream", 11, 70}, _
            {"camera", 32, 30}, _
            {"T-shirt", 24, 15}, _
            {"trousers", 48, 10}, _
            {"umbrella", 73, 40}, _
            {"waterproof trousers", 42, 70}, _
            {"waterproof overclothes", 43, 75}, _
            {"note-case", 22, 80}, _
            {"sunglasses", 7, 20}, _
            {"towel", 18, 12}, _
            {"socks", 4, 50}, _
            {"book", 30, 10}}
    Dim s, xss As String, xwei, xval, nn As Integer

    Private Sub KnapsackBin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim i As Integer
        xListView.View = View.Details
        xListView.Columns.Add("item", 120, HorizontalAlignment.Left)
        xListView.Columns.Add("weight", 50, HorizontalAlignment.Right)
        xListView.Columns.Add("value", 50, HorizontalAlignment.Right)
        For i = 0 To UBound(xList, 1)
            xListView.Items.Add(New ListViewItem(New String() {xList(i, 0), _
                                xList(i, 1).ToString, xList(i, 2).ToString}))
        Next i
    End Sub 'KnapsackBin_Load

    Private Sub cmdOK_Click(sender As Object, e As EventArgs) Handles cmdOK.Click
        Dim i, j, nItems As Integer
        For i = xListView.Items.Count - 1 To 0 Step -1
            xListView.Items.RemoveAt(i)
        Next i
        Me.Refresh()
        nItems = UBound(xList, 1) + 1
        s = ""
        For i = 1 To nItems
            s = s & Chr(i - 1)
        Next
        nn = 0
        Call ChoiceBin(1, "")
        For i = 1 To Len(xss)
            j = Asc(Mid(xss, i, 1))
            xListView.Items.Add(New ListViewItem(New String() {xList(j, 0), _
                                xList(j, 1).ToString, xList(j, 2).ToString}))
        Next i
        xListView.Items.Add(New ListViewItem(New String() {"*Total*", xwei, xval}))
    End Sub 'cmdOK_Click

    Private Sub ChoiceBin(n As String, ss As String)
        Dim r As String, i, j, iwei, ival As Integer
        Dim ipct As Integer
        If n = Len(s) + 1 Then
            iwei = 0 : ival = 0
            For i = 1 To Len(ss)
                j = Asc(Mid(ss, i, 1))
                iwei = iwei + xList(j, 1)
                ival = ival + xList(j, 2)
            Next
            If iwei <= maxWeight And ival > xval Then
                xss = ss : xwei = iwei : xval = ival
            End If
        Else
            r = Mid(s, n, 1)
            Call ChoiceBin(n + 1, ss & r)
            Call ChoiceBin(n + 1, ss)
        End If
    End Sub 'ChoiceBin

End Class 'KnapsackBin


import java.util.ArrayList;

public class Josephus {
    public static int execute(int n, int k){
        int killIdx = 0;
        ArrayList<Integer> prisoners = new ArrayList<Integer>(n);
        for(int i = 0;i < n;i++){
            prisoners.add(i);
        }
        System.out.println("Prisoners executed in order:");
        while(prisoners.size() > 1){
            killIdx = (killIdx + k - 1) % prisoners.size();
            System.out.print(prisoners.get(killIdx) + " ");
            prisoners.remove(killIdx);
        }
        System.out.println();
        return prisoners.get(0);
    }

    public static ArrayList<Integer> executeAllButM(int n, int k, int m){
        int killIdx = 0;
        ArrayList<Integer> prisoners = new ArrayList<Integer>(n);
        for(int i = 0;i < n;i++){
            prisoners.add(i);
        }
        System.out.println("Prisoners executed in order:");
        while(prisoners.size() > m){
            killIdx = (killIdx + k - 1) % prisoners.size();
            System.out.print(prisoners.get(killIdx) + " ");
            prisoners.remove(killIdx);
        }
        System.out.println();
        return prisoners;
    }

    public static void main(String[] args){
        System.out.println("Survivor: " + execute(41, 3));
        System.out.println("Survivors: " + executeAllButM(41, 3, 3));
    }
}


struct Item {
    name string
    w int
    v int
}

const wants = [
        Item{'map', 9, 150},
        Item{'compass', 13, 35},
        Item{'water', 153, 200},
        Item{'sandwich', 50, 60},
        Item{'glucose', 15, 60},
        Item{'tin', 68, 45},
        Item{'banana', 27, 60},
        Item{'apple', 39, 40},
        Item{'cheese', 23, 30},
        Item{'beer', 52, 10},
        Item{'suntancream', 11, 70},
        Item{'camera', 32, 30},
        Item{'T-shirt', 24, 15},
        Item{'trousers', 48, 10},
        Item{'umbrella', 73, 40},
        Item{'w-trousers', 42, 70},
        Item{'w-overclothes', 43, 75},
        Item{'note-case', 22, 80},
        Item{'sunglasses', 7, 20},
        Item{'towel', 18, 12},
        Item{'socks', 4, 50},
        Item{'book', 30, 10}
    ]
const max_wt = 400

fn main(){
    items, w, v := m(wants.len-1, max_wt)

    println(items)
    println('weight: $w')
    println('value: $v')
}

fn m(i int, w int) ([]string, int, int) {
    if i<0 || w==0{
        return []string{}, 0, 0
    } else if wants[i].w > w {
        return m(i-1, w)
    }
    i0, w0, v0 := m(i-1, w)
    mut i1, w1, mut v1 := m(i-1, w-wants[i].w)
    v1 += wants[i].v
    if v1 > v0 {
        i1 << wants[i].name
        return i1, w1+wants[i].w, v1
    }
    return i0, w0, v0
}


V WORDS = File(‘linuxwords.txt’).read_lines()
V MISSPELLINGS = [‘accomodate’,
                  ‘definately’,
                  ‘goverment’]

F jaro_winkler_distance(=st1, =st2)
   I st1.len < st2.len
      (st1, st2) = (st2, st1)
   V len1 = st1.len
   V len2 = st2.len
   I len2 == 0
      R 0.0
   V delta = max(0, len2 I/ 2 - 1)
   V flag = (0 .< len2).map(_ -> 0B)
   [Char] ch1_match
   L(ch1) st1
      V idx1 = L.index
      L(ch2) st2
         V idx2 = L.index
         I idx2 <= idx1 + delta & idx2 >= idx1 - delta & ch1 == ch2 & !(flag[idx2])
            flag[idx2] = 1B
            ch1_match.append(ch1)
            L.break
   V matches = ch1_match.len
   I matches == 0
      R 1.0
   V transpositions = 0
   V idx1 = 0
   L(ch2) st2
      V idx2 = L.index
      I flag[idx2]
         transpositions += (ch2 != ch1_match[idx1])
         idx1++
   V jaro = (Float(matches) / len1 + Float(matches) / len2 + (matches - transpositions / 2) / matches) / 3.0
   V commonprefix = 0
   L(i) 0 .< min(4, len2)
      commonprefix += (st1[i] == st2[i])
   R 1.0 - (jaro + commonprefix * 0.1 * (1 - jaro))

F within_distance(maxdistance, stri, maxtoreturn)
   V arr = :WORDS.filter(w -> jaro_winkler_distance(@stri, w) <= @maxdistance)
   arr.sort(key' x -> jaro_winkler_distance(@stri, x))
   R I arr.len <= maxtoreturn {arr} E arr[0 .< maxtoreturn]

L(STR) MISSPELLINGS
   print("\nClose dictionary words ( distance < 0.15 using Jaro-Winkler distance) to \" "STR" \" are:\n        Word   | Distance")
   L(w) within_distance(0.15, STR, 5)
      print(‘#14 | #.4’.format(w, jaro_winkler_distance(STR, w)))


var Josephus = {
  init: function(n) {
    this.head = {};
    var current = this.head;
    for (var i = 0; i < n-1; i++) {
      current.label = i+1;
      current.next = {prev: current};
      current = current.next;
    }
    current.label = n;
    current.next = this.head;
    this.head.prev = current;
    return this;
  },
  kill: function(spacing) {
    var current = this.head;
    while (current.next !== current) {
      for (var i = 0; i < spacing-1; i++) {
        current = current.next;
      }
      current.prev.next = current.next;
      current.next.prev = current.prev;
      current = current.next;
    }
    return current.label;
  }
}


# A control structure, for convenience:
# as soon as "condition" is true, then emit . and stop:
def do_until(condition; next):
  def u: if condition then . else (next|u) end;
  u;

# n is the initial number; every k-th prisoner is removed until m remain.
# Solution by simulation
def josephus(n;k;m):
    reduce range(0;n) as $i ([]; . + [$i])    # Number the prisoners from 0 to (n-1)
    | do_until( length < k or length <= m; .[k:] + .[0:k-1] )
    | do_until( length <= m; (k % length) as $i | .[$i:] + .[0:$i-1] );


import "/fmt" for Fmt

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

var m
m = Fn.new { |i, w|
    if (i < 0 || w == 0) return [[], 0, 0]
    if (wants[i][1] > w) return m.call(i-1, w)
    System.write("") // guard against VM recursion bug
    var res = m.call(i-1, w)
    var i0 = res[0]
    var w0 = res[1]
    var v0 = res[2]
    res = m.call(i-1, w - wants[i][1])
    var i1 = res[0]
    var w1 = res[1]
    var v1 = res[2] + wants[i][2]
    if (v1 > v0) {
        i1.add(wants[i])
        return [i1, w1 + wants[i][1], v1]
    }
    return [i0, w0, v0]
}

var maxWt = 400
var res = m.call(wants.count-1, maxWt)
var items = res[0]
var tw = res[1]
var tv = res[2]
System.print("Max weight: %(maxWt)\n")
System.print("Item                  Weight   Value")
System.print("------------------------------------")
for (i in 0...items.count) {
    Fmt.print("$-22s  $3d     $4s", items[i][0], items[i][1], items[i][2])
}
System.print("                        ---     ----")
Fmt.print("totals                  $3d     $4d", tw, tv)


module JaroWinkler exposing (similarity)

commonPrefixLength : List a -> List a -> Int -> Int
commonPrefixLength xs ys counter =
    case ( xs, ys ) of
        ( x :: xs_, y :: ys_ ) ->
            if x == y then
                commonPrefixLength xs_ ys_ (counter + 1)

            else
                counter

        _ ->
            counter

similarity : String -> String -> Float
similarity s1 s2 =
    let
        chars1 =
            String.toList s1

        chars2 =
            String.toList s2

        jaroScore =
            jaro chars1 chars2

        l =
            toFloat <| min (commonPrefixLength chars1 chars2 0) 4

        p =
            0.1
    in
    jaroScore + (l * p * (1.0 - jaroScore))

containtsInNextN : Int -> a -> List a -> Bool
containtsInNextN i a items =
    case ( i, items ) of
        ( 0, _ ) ->
            False

        ( _, [] ) ->
            False

        ( _, item :: rest ) ->
            if item == a then
                True

            else
                containtsInNextN (i - 1) a rest

exists : Int -> Int -> List a -> a -> Bool
exists startAt endAt items i =
    if endAt < startAt then
        False

    else if startAt == 0 then
        case items of
            first :: rest ->
                if i == first then
                    True

                else
                    exists 0 (endAt - 1) rest i

            [] ->
                False

    else
        exists 0 (endAt - startAt) (List.drop startAt items) i

existsInWindow : a -> List a -> Int -> Int -> Bool
existsInWindow item items offset radius =
    let
        startAt =
            max 0 (offset - radius)

        endAt =
            min (offset + radius) (List.length items - 1)
    in
    exists startAt endAt items item

transpositions : List a -> List a -> Int -> Int
transpositions xs ys counter =
    case ( xs, ys ) of
        ( [], _ ) ->
            counter

        ( _, [] ) ->
            counter

        ( x :: xs_, y :: ys_ ) ->
            if x /= y then
                transpositions xs_ ys_ (counter + 1)

            else
                transpositions xs_ ys_ counter

commonItems : List a -> List a -> Int -> List a
commonItems items1 items2 radius =
    items1
        |> List.indexedMap
            (\index item ->
                if existsInWindow item items2 index radius then
                    [ item ]

                else
                    []
            )
        |> List.concat

jaro : List Char -> List Char -> Float
jaro chars1 chars2 =
    let
        minLenth =
            min (List.length chars1) (List.length chars2)

        matchRadius =
            minLenth // 2 + (minLenth |> modBy 2)

        c1 =
            commonItems chars1 chars2 matchRadius

        c2 =
            commonItems chars2 chars1 matchRadius

        c1length =
            toFloat (List.length c1)

        c2length =
            toFloat (List.length c2)

        mismatches =
            transpositions c1 c2 0

        transpositionScore =
            (toFloat mismatches + abs (c1length - c2length)) / 2.0

        s1length =
            toFloat (List.length chars1)

        s2length =
            toFloat (List.length chars2)

        tLength =
            max c1length c2length

        result =
            (c1length / s1length + c2length / s2length + (tLength - transpositionScore) / tLength) / 3.0
    in
    if isNaN result then
        0.0

    else
        result


PROC jaro sim = ( STRING sp1, sp2 )REAL:
     IF   STRING s1 = sp1[ AT 0 ];
          STRING s2 = sp2[ AT 0 ];
          INT le1   = ( UPB s1 - LWB s1 ) + 1;
          INT le2   = ( UPB s2 - LWB s2 ) + 1;
          le1 < 1 AND le2 < 1
     THEN # both strings are empty #         1
     ELIF le1 < 1 OR  le2 < 1
     THEN # one of the strings is empty #    0
     ELSE # both strings are non-empty #
        INT dist := IF le2 > le1 THEN le2 ELSE le1 FI;
        dist OVERAB 2 -:= 1;
        [ 0 : le1 ]BOOL matches1; FOR i FROM LWB matches1 TO UPB matches1 DO matches1[ i ] := FALSE OD;
        [ 0 : le2 ]BOOL matches2; FOR i FROM LWB matches2 TO UPB matches2 DO matches2[ i ] := FALSE OD;
        INT matches  := 0;
        INT transpos := 0;
        FOR i FROM LWB s1 TO UPB s1 DO
            INT start := i - dist;
            IF  start < 0 THEN start := 0 FI;
            INT end   := i + dist + 1;
            IF  end > le2 THEN end := le2 FI;
            FOR k FROM start TO end - 1
            WHILE IF matches2[ k ]
                  THEN TRUE
                  ELIF s1[ i ] /= s2[ k ]
                  THEN TRUE
                  ELSE
                      matches2[ k ] := matches1[ i ] := TRUE;
                      matches +:= 1;
                      FALSE
                  FI
            DO SKIP OD
        OD;
        IF matches = 0
        THEN 0
        ELSE
            INT k := 0;
            FOR i FROM LWB s1 TO UPB s1 DO
                IF matches1[ i ] THEN
                    WHILE NOT matches2[ k ] DO k +:= 1 OD;
                    IF s1[ i ] /= s2[ k ] THEN transpos +:= 1 FI;
                    k +:= 1
                FI
            OD;
            transpos OVERAB 2;
            ( ( matches / le1 )
            + ( matches / le2 )
            + ( ( matches - transpos ) / matches )
            ) / 3
        FI
     FI # jaro sim # ;
PROC jaro winkler dist = ( STRING sp, tp )REAL:
     BEGIN
        STRING s  = sp[ AT 0 ];
        STRING t  = tp[ AT 0 ];
        INT  ls = ( UPB s - LWB s ) + 1;
        INT  lt = ( UPB t - LWB t ) + 1;
        INT  l max := IF ls < lt THEN ls ELSE lt FI;
        IF   l max > 4 THEN l max := 4 FI;
        INT  l := 0;
        FOR  i FROM 0 TO l max - 1 DO IF s[ i ] = t[ i ] THEN l +:= 1 FI OD;
        REAL js = jaro sim( s, t );
        REAL p  = 0.1;
        REAL ws = js + ( l * p * ( 1 - js ) );
        1 - ws
     END # jaro winkler dist # ;
# include the Associative Array code #
PR read "aArray.a68" PR
# test cases #
[]STRING misspelt = ( "accomodate", "definately", "goverment", "occured", "publically", "recieve", "seperate", "untill", "wich" );
IF  FILE input file;
    STRING file name = "unixdict.txt";
    open( input file, file name, stand in channel ) /= 0
THEN
    # failed to open the file #
    print( ( "Unable to open """ + file name + """", newline ) )
ELSE
    # file opened OK #
    BOOL at eof := FALSE;
    # set the EOF handler for the file #
    on logical file end( input file, ( REF FILE f )BOOL:
                                     BEGIN
                                         # note that we reached EOF on the #
                                         # latest read #
                                         at eof := TRUE;
                                         # return TRUE so processing can continue #
                                         TRUE
                                     END
                       );
    REF AARRAY words := INIT LOC AARRAY;
    STRING word;
    WHILE NOT at eof
    DO
        STRING word;
        get( input file, ( word, newline ) );
        words // word := ""
    OD;
    # close the file #
    close( input file );
    # look for near matches to the misspelt words #
    INT max closest = 6; # max number of closest matches to show #
    FOR m pos FROM LWB misspelt TO UPB misspelt DO
        [ max closest ]STRING closest word;
        [ max closest ]REAL   closest jwd;
        FOR i TO max closest DO closest word[ i ] := ""; closest jwd[ i ] := 999 999 999 OD;
        REF AAELEMENT e := FIRST words;
        WHILE e ISNT nil element DO
            STRING word = key OF e;
            REAL jwd = jaro winkler dist( misspelt[ m pos ], word );
            BOOL found better match := FALSE;
            FOR i TO max closest WHILE NOT found better match DO
                IF jwd <= closest jwd[ i ] THEN
                    # found a new closer match #
                    found better match := TRUE;
                    # shuffle the others down 1 and insert the new match #
                    FOR j FROM max closest BY - 1 TO i + 1 DO
                        closest word[ j ] := closest word[ j - 1 ];
                        closest jwd[  j ] := closest jwd[  j - 1 ]
                    OD;
                    closest word[ i ] := word;
                    closest jwd[  i ] := jwd
                FI
            OD;
            e := NEXT words
        OD;
        print( ( "Misspelt word: ", misspelt[ m pos ], ":", newline ) );
        FOR i TO max closest DO
            print( ( fixed( closest jwd[ i ], -8, 4 ), " ", closest word[ i ], newline ) )
        OD;
        print( ( newline ) )
    OD
FI


using Memoize
@memoize josephus(n::Integer, k::Integer, m::Integer=1) = n == m ? collect(0:m .- 1) : mod.(josephus(n - 1, k, m) + k, n)

@show josephus(41, 3)
@show josephus(41, 3, 5)


// version 1.1.3

fun josephus(n: Int, k: Int, m: Int): Pair<List<Int>, List<Int>> {
    require(k > 0 && m > 0 && n > k && n > m)
    val killed = mutableListOf<Int>()
    val survived = MutableList(n) { it }
    var start = k - 1
    outer@ while (true) {
        val end = survived.size - 1
        var i = start
        var deleted = 0
        while (i <= end) {
            killed.add(survived.removeAt(i - deleted))
            if (survived.size == m) break@outer
            deleted++
            i += k
        }
        start = i - end - 1
    }
    return Pair(survived, killed)
}

fun main(args: Array<String>) {
    val triples = listOf(Triple(5, 2, 1), Triple(41, 3, 1), Triple(41, 3, 3))
    for (triple in triples) {
        val(n, k, m) = triple
        println("Prisoners = $n, Step = $m, Survivors = $m")
        val (survived, killed)  = josephus(n, k, m)
        println("Survived   : $survived")
        println("Kill order : $killed")
        println()
    }
}


include c:\cxpl\codes;  \include 'code' declarations

int     Item, Items, Weights, Values,
        BestItems, BestValues,
        I, W, V, N;
def     Tab=9;
def     Name,                   Weight, Value;
[Item:= [["map                  ",   9, 150],
        ["compass               ",  13,  35],
        ["water                 ", 153, 200],
        ["sandwich              ",  50, 160],
        ["glucose               ",  15,  60],
        ["tin                   ",  68,  45],
        ["banana                ",  27,  60],
        ["apple                 ",  39,  40],
        ["cheese                ",  23,  30],
        ["beer                  ",  52,  10],
        ["suntan cream          ",  11,  70],
        ["camera                ",  32,  30],
        ["T-shirt               ",  24,  15],
        ["trousers              ",  48,  10],
        ["umbrella              ",  73,  40],
        ["waterproof trousers   ",  42,  70],
        ["waterproof overclothes",  43,  75],
        ["note-case             ",  22,  80],
        ["sunglasses            ",   7,  20],
        ["towel                 ",  18,  12],
        ["socks                 ",   4,  50],
        ["book                  ",  30,  10]];

BestValues:= 0;
for Items:= 0 to 1<<22-1 do     \for all possible combinations of Items...
        [I:= Items;  W:= 0;  V:= 0;  N:= 0;
        while I do              \add weights and values for each item (bit in I)
                [if I&1 then
                        [W:= W + Item(N,Weight);  V:= V + Item(N,Value)];
                I:= I>>1;  N:= N+1;
                ];
        if V>BestValues & W<=400 then   \save best combination found so far
                [BestValues:= V;  BestItems:= Items];
        ];

I:= BestItems;  W:= 0;  V:= 0;  N:= 0;          \show best combination of items
while I do
        [if I&1 then
                [Text(0, "  ");  Text(0, Item(N,Name));  ChOut(0, Tab);
                IntOut(0, Item(N,Weight));  ChOut(0, Tab);
                IntOut(0, Item(N,Value));  CrLf(0);
                W:= W + Item(N,Weight);
                V:= V + Item(N,Value);
                ];
        I:= I>>1;  N:= N+1;
        ];
Text(0, "Totals:                                ");
IntOut(0, W);  ChOut(0, Tab);
IntOut(0, V);  CrLf(0);
]


fcn addItem(pairs,it){   // pairs is list of (cost of:,names), it is (name,w,v)
   w,left,right:=it[1],pairs[0,w],pairs[w,*];
   left.extend(right.zipWith(
      fcn([(t1,_)]a,[(t2,_)]b){ t1>t2 and a or b  },
      pairs.apply('wrap([(tot,names)]){ T(tot + it[2], names + it[0]) })))
}//--> new list of pairs


#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

auto load_dictionary(const std::string& path) {
    std::ifstream in(path);
    if (!in)
        throw std::runtime_error("Cannot open file " + path);
    std::string line;
    std::vector<std::string> words;
    while (getline(in, line))
        words.push_back(line);
    return words;
}

double jaro_winkler_distance(std::string str1, std::string str2) {
    size_t len1 = str1.size();
    size_t len2 = str2.size();
    if (len1 < len2) {
        std::swap(str1, str2);
        std::swap(len1, len2);
    }
    if (len2 == 0)
        return len1 == 0 ? 0.0 : 1.0;
    size_t delta = std::max(size_t(1), len1/2) - 1;
    std::vector<bool> flag(len2, false);
    std::vector<char> ch1_match;
    ch1_match.reserve(len1);
    for (size_t idx1 = 0; idx1 < len1; ++idx1) {
        char ch1 = str1[idx1];
        for (size_t idx2 = 0; idx2 < len2; ++idx2) {
            char ch2 = str2[idx2];
            if (idx2 <= idx1 + delta && idx2 + delta >= idx1
                && ch1 == ch2 && !flag[idx2]) {
                flag[idx2] = true;
                ch1_match.push_back(ch1);
                break;
            }
        }
    }
    size_t matches = ch1_match.size();
    if (matches == 0)
        return 1.0;
    size_t transpositions = 0;
    for (size_t idx1 = 0, idx2 = 0; idx2 < len2; ++idx2) {
        if (flag[idx2]) {
            if (str2[idx2] != ch1_match[idx1])
                ++transpositions;
            ++idx1;
        }
    }
    double m = matches;
    double jaro = (m/len1 + m/len2 + (m - transpositions/2.0)/m)/3.0;
    size_t common_prefix = 0;
    len2 = std::min(size_t(4), len2);
    for (size_t i = 0; i < len2; ++i) {
        if (str1[i] == str2[i])
            ++common_prefix;
    }
    return 1.0 - (jaro + common_prefix * 0.1 * (1.0 - jaro));
}

auto within_distance(const std::vector<std::string>& words,
                     double max_distance, const std::string& str,
                     size_t max_to_return) {
    using pair = std::pair<std::string, double>;
    std::vector<pair> result;
    for (const auto& word : words) {
        double jaro = jaro_winkler_distance(word, str);
        if (jaro <= max_distance)
            result.emplace_back(word, jaro);
    }
    std::stable_sort(result.begin(), result.end(),
        [](const pair& p1, const pair& p2) { return p1.second < p2.second; });
    if (result.size() > max_to_return)
        result.resize(max_to_return);
    return result;
}

int main() {
    try {
        auto words(load_dictionary("linuxwords.txt"));
        std::cout << std::fixed << std::setprecision(4);
        for (auto str : {"accomodate", "definately", "goverment",
                            "occured", "publically", "recieve",
                            "seperate", "untill", "wich"}) {
            std::cout << "Close dictionary words (distance < 0.15 using Jaro-Winkler distance) to '"
                << str << "' are:\n        Word   |  Distance\n";
            for (const auto& pair : within_distance(words, 0.15, str, 5)) {
                std::cout << std::setw(14) << pair.first << " | "
                    << std::setw(6) << pair.second << '\n';
            }
            std::cout << '\n';
        }
    } catch (const std::exception& ex) {
        std::cerr << ex.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}


function josephus(n, k, m)
    local positions={}
    for i=1,n do
        table.insert(positions, i-1)
    end
    local i,j=1,1
    local s='Execution order: '
    while #positions>m do
        if j==k then
            s=s .. positions[i] .. ', '
            table.remove(positions, i)
            i=i-1
        end
        i=i+1
        j=j+1
        if i>#positions then i=1 end
        if j>k then j=1 end
    end
    print(s:sub(1,#s-2) .. '.')
    local s='Survivors: '
    for _,v in pairs(positions) do s=s .. v .. ', ' end
    print(s:sub(1,#s-2) .. '.')
end
josephus(41,3, 1)


survivor[n_, k_] := Nest[Most[RotateLeft[#, k]] &, Range[0, n - 1], n - 1]
survivor[41, 3]


// Calculate Jaro-Winkler Similarity of 2 Strings. Nigel Galloway: August 7th., 2020
let Jw P n g=let L=float(let i=Seq.map2(fun n g->n=g) n g in (if Seq.length i>4 then i|>Seq.take 4 else i)|>Seq.takeWhile id|>Seq.length)
             let J=J n g in J+P*L*(1.0-J)

let dict=System.IO.File.ReadAllLines("linuxwords.txt")
let fN g=let N=Jw 0.1 g in dict|>Array.map(fun n->(n,1.0-(N n)))|>Array.sortBy snd
["accomodate";"definately";"goverment";"occured";"publically";"recieve";"seperate";"untill";"wich"]|>
  List.iter(fun n->printfn "%s" n;fN n|>Array.take 5|>Array.iter(fun n->printf "%A" n);printfn "\n")


package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "sort"
)

func jaroSim(str1, str2 string) float64 {
    if len(str1) == 0 && len(str2) == 0 {
        return 1
    }
    if len(str1) == 0 || len(str2) == 0 {
        return 0
    }
    match_distance := len(str1)
    if len(str2) > match_distance {
        match_distance = len(str2)
    }
    match_distance = match_distance/2 - 1
    str1_matches := make([]bool, len(str1))
    str2_matches := make([]bool, len(str2))
    matches := 0.
    transpositions := 0.
    for i := range str1 {
        start := i - match_distance
        if start < 0 {
            start = 0
        }
        end := i + match_distance + 1
        if end > len(str2) {
            end = len(str2)
        }
        for k := start; k < end; k++ {
            if str2_matches[k] {
                continue
            }
            if str1[i] != str2[k] {
                continue
            }
            str1_matches[i] = true
            str2_matches[k] = true
            matches++
            break
        }
    }
    if matches == 0 {
        return 0
    }
    k := 0
    for i := range str1 {
        if !str1_matches[i] {
            continue
        }
        for !str2_matches[k] {
            k++
        }
        if str1[i] != str2[k] {
            transpositions++
        }
        k++
    }
    transpositions /= 2
    return (matches/float64(len(str1)) +
        matches/float64(len(str2)) +
        (matches-transpositions)/matches) / 3
}

func jaroWinklerDist(s, t string) float64 {
    ls := len(s)
    lt := len(t)
    lmax := lt
    if ls < lt {
        lmax = ls
    }
    if lmax > 4 {
        lmax = 4
    }
    l := 0
    for i := 0; i < lmax; i++ {
        if s[i] == t[i] {
            l++
        }
    }
    js := jaroSim(s, t)
    p := 0.1
    ws := js + float64(l)*p*(1-js)
    return 1 - ws
}

type wd struct {
    word string
    dist float64
}

func main() {
    misspelt := []string{
        "accomodate", "definately", "goverment", "occured", "publically",
        "recieve", "seperate", "untill", "wich",
    }
    b, err := ioutil.ReadFile("unixdict.txt")
    if err != nil {
        log.Fatal("Error reading file")
    }
    words := bytes.Fields(b)
    for _, ms := range misspelt {
        var closest []wd
        for _, w := range words {
            word := string(w)
            if word == "" {
                continue
            }
            jwd := jaroWinklerDist(ms, word)
            if jwd < 0.15 {
                closest = append(closest, wd{word, jwd})
            }
        }
        fmt.Println("Misspelt word:", ms, ":")
        sort.Slice(closest, func(i, j int) bool { return closest[i].dist < closest[j].dist })
        for i, c := range closest {
            fmt.Printf("%0.4f %s\n", c.dist, c.word)
            if i == 5 {
                break
            }
        }
        fmt.Println()
    }
}


function [indAlive] = josephus(numPeople,count)
% Josephus: Given a circle of numPeople individuals, with a count of count,
% find the index (starting at 1) of the survivor [see Josephus Problem]

%% Definitions:
%   0 = dead position
%   1 = alive position
%   index = # of person

%% Setting up
arrPeople = ones(1, numPeople);
currInd = 0;

%% Counting
while (length(arrPeople(arrPeople == 1)) > 1)     % While more than 1 person is alive
    counter = 0;
    while counter ~= count                       % Counting until we hit the count
        currInd = currInd + 1;                  % Move to the next person

        if currInd > numPeople                  % If overflow, wraparound
            currInd = currInd - numPeople;
        end

        if arrPeople(currInd)                   % If the current person is alive
            counter = counter + 1;                % Add 1 person to the count
            %fprintf("Index: %d \t| Counter: %d\n", currInd, counter)           % Uncomment to display index and counter location
        end

    end

    arrPeople(currInd) = 0;                     % Kill the person we reached
    %fprintf("Killed person %d \n", currInd)                                   % Uncomment to display order of killing
    %disp(arrPeople)                                                           % Uncomment to display current status of people
end

indAlive = find(arrPeople);

end


MODULE Josephus;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE Josephus(n,k : INTEGER) : INTEGER;
VAR a,m : INTEGER;
BEGIN
    m := 0;
    FOR a:=1 TO n DO
        m := (m + k) MOD a;
    END;
    RETURN m
END Josephus;

VAR
    buf : ARRAY[0..63] OF CHAR;
    n,k,i : INTEGER;
    nl,kl,il : LONGCARD;
BEGIN
    n := 41;
    k := 3;
    FormatString("n = %i, k = %i, final survivor: %i\n", buf, n, k, Josephus(n, k));
    WriteString(buf);

    ReadChar
END Josephus.


import java.io.*;
import java.util.*;

public class JaroWinkler {
    public static void main(String[] args) {
        try {
            List<String> words = loadDictionary("linuxwords.txt");
            String[] strings = {
                "accomodate", "definately", "goverment", "occured",
                "publically", "recieve", "seperate", "untill", "wich"
            };
            for (String string : strings) {
                System.out.printf("Close dictionary words (distance < 0.15 using Jaro-Winkler distance) to '%s' are:\n"
                                    + "        Word   |  Distance\n", string);
                for (StringDistance s : withinDistance(words, 0.15, string, 5)) {
                    System.out.printf("%14s | %.4f\n", s.word, s.distance);
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class StringDistance implements Comparable<StringDistance> {
        private StringDistance(String word, double distance) {
            this.word = word;
            this.distance = distance;
        }
        public int compareTo(StringDistance s) {
            return Double.compare(distance, s.distance);
        }
        private String word;
        private double distance;
    }

    private static List<StringDistance> withinDistance(List<String> words,
                        double maxDistance, String string, int max) {
        List<StringDistance> result = new ArrayList<>();
        for (String word : words) {
            double distance = jaroWinklerDistance(word, string);
            if (distance <= maxDistance)
                result.add(new StringDistance(word, distance));
        }
        Collections.sort(result);
        if (result.size() > max)
            result = result.subList(0, max);
        return result;
    }

    private static double jaroWinklerDistance(String string1, String string2) {
        int len1 = string1.length();
        int len2 = string2.length();
        if (len1 < len2) {
            String s = string1;
            string1 = string2;
            string2 = s;
            int tmp = len1;
            len1 = len2;
            len2 = tmp;
        }
        if (len2 == 0)
            return len1 == 0 ? 0.0 : 1.0;
        int delta = Math.max(1, len1 / 2) - 1;
        boolean[] flag = new boolean[len2];
        Arrays.fill(flag, false);
        char[] ch1Match = new char[len1];
        int matches = 0;
        for (int i = 0; i < len1; ++i) {
            char ch1 = string1.charAt(i);
            for (int j = 0; j < len2; ++j) {
                char ch2 = string2.charAt(j);
                if (j <= i + delta && j + delta >= i && ch1 == ch2 && !flag[j]) {
                    flag[j] = true;
                    ch1Match[matches++] = ch1;
                    break;
                }
            }
        }
        if (matches == 0)
            return 1.0;
        int transpositions = 0;
        for (int i = 0, j = 0; j < len2; ++j) {
            if (flag[j]) {
                if (string2.charAt(j) != ch1Match[i])
                    ++transpositions;
                ++i;
            }
        }
        double m = matches;
        double jaro = (m / len1 + m / len2 + (m - transpositions / 2.0) / m) / 3.0;
        int commonPrefix = 0;
        len2 = Math.min(4, len2);
        for (int i = 0; i < len2; ++i) {
            if (string1.charAt(i) == string2.charAt(i))
                ++commonPrefix;
        }
        return 1.0 - (jaro + commonPrefix * 0.1 * (1.0 - jaro));
    }

    private static List<String> loadDictionary(String path) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            List<String> words = new ArrayList<>();
            String word;
            while ((word = reader.readLine()) != null)
                words.add(word);
            return words;
        }
    }
}


def j(n, k)
        p = list(range(0, n-1))
        i = 0
        seq = {}
        while len(p) > 0
                i = (i+k-1) % len(p)
                seq.append(p[i])
                p.remove(i)
        end
        sur = seq[len(seq) - 1]; seq.remove(len(seq) - 1)
        return format("Prisoner killing order: %s\nSurvivor: %d", seq, sur)
end

println j(5,2)
println
println j(41,3)


/* NetRexx */
options replace format comments java crossref symbols nobinary

/* REXX **************************************************************
* 15.11.2012 Walter Pachl - my own solution
* 16.11.2012 Walter Pachl generalized n prisoners + w killing distance
*                         and s=number of survivors
**********************************************************************/
dead = 0                               /* nobody's dead yet          */
n = 41                                 /* number of alive prisoners  */
nn = n                                 /* wrap around boundary       */
w = 3                                  /* killing count              */
s = 1                                  /* nuber of survivors         */
p = -1                                 /* start here                 */
killed = ''                            /* output of killings         */
Loop until n = s                       /* until one alive prisoner   */
  found = 0                            /* start looking              */
  Loop Until found = w                 /* until we have the third    */
    p = p + 1                          /* next position              */
    If p = nn Then p = 0               /* wrap around                */
    If dead[p] = 0 Then                /* a prisoner who is alive    */
      found = found + 1                /* increment found count      */
    End
  dead[p] = 1
  n = n - 1                            /* shoot the one on this pos. */
  killed = killed p                    /* add to output              */
  End                                  /* End of main loop           */
Say 'killed:'killed.subword(1, 20)     /* output killing sequence    */
Say '       'killed.subword(21)        /* output killing sequence    */
Say 'Survivor(s):'                     /* show                       */
Loop i = 0 To 40                       /* look for the surviving p's */
  If dead[i] = 0 Then Say i            /* found one                  */
  End


import sequtils, strutils, sugar

proc j(n, k: int): string =
  var
    p = toSeq(0 ..< n)
    i = 0
    s = newSeq[int]()

  while p.len > 0:
    i = (i + k - 1) mod p.len
    s.add p[i]
    system.delete(p, i)

  result = "Prisoner killing order: "
  result.add s.map((x: int) => $x).join(", ")
  result.add ".\nSurvivor: "
  result.add($s[s.high])

echo j(5,2)
echo j(41,3)


# See [[Jaro_similarity#jq]] for the implementation of jaro/2

def length_of_common_prefix($s1; $s2):
  if ($s1|length) > ($s2|length) then length_of_common_prefix($s2; $s1)
  else ($s1|explode) as $x1
  | ($s2|explode) as $x2
  | first( range(0;$x1|length) | select( $x1[.] != $x2[.] )) // ($x1|length)
  end;

# Output: the Jaro-WInkler distance using 0.1 as the common-prefix multiplier
def jaro_winkler($s1; $s2):
  if $s1 == $s2 then 0
  else jaro($s1; $s2) as $j
  | length_of_common_prefix($s1[:4]; $s2[:4]) as $l
  | 1 - ($j + 0.1 * $l * (1 - $j))
  end ;

# Input: an array of words
# Output: [[match, distance] ...]
def candidates($word; $threshold):
  map(jaro_winkler($word; . ) as $x | select($x <= $threshold) | [., $x] );

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

def task:
  [inputs] # the dictionary
  | ("accomodate", "definately", "goverment", "occured", "publically", "recieve", "seperate", "untill", "wich") as $word
  | candidates($word; 0.15) | sort_by(.[-1]) | .[:5]
  | "Matches for \($word|lpad(10)): Distance",
    (.[] | "\(.[0] | lpad(21)) : \(.[-1] * 1000 | round / 1000)") ;

task


# download("http://users.cs.duke.edu/~ola/ap/linuxwords", "linuxwords.txt")
const words = read("linuxwords.txt", String) |> split .|> strip

function jarowinklerdistance(s1, s2)
    if length(s1) < length(s2)
        s1, s2 = s2, s1
    end
    len1, len2 = length(s1), length(s2)
    len2 == 0 && return 0.0
    delta = max(0, len2 ÷ 2 - 1)
    flag = zeros(Bool, len2)  # flags for possible transpositions, begin as false
    ch1_match = eltype(s1)[]
    for (i, ch1) in enumerate(s1)
        for (j, ch2) in enumerate(s2)
            if (j <= i + delta) && (j >= i - delta) && (ch1 == ch2) && !flag[j]
                flag[j] = true
                push!(ch1_match, ch1)
                break
            end
        end
    end
    matches = length(ch1_match)
    matches == 0 && return 1.0
    transpositions, i = 0, 0
    for (j, ch2) in enumerate(s2)
        if flag[j]
            i += 1
            transpositions += (ch2 != ch1_match[i])
        end
    end
    jaro = (matches / len1 + matches / len2 + (matches - transpositions/2) / matches) / 3.0
    commonprefix = count(i -> s1[i] == s2[i], 1:min(len2, 4))
    return 1 - (jaro + commonprefix * 0.1 * (1 - jaro))
end

function closewords(s, maxdistance, maxtoreturn)
    jw = 0.0
    arr = [(w, jw) for w in words if (jw = jarowinklerdistance(s, w)) <= maxdistance]
    sort!(arr, lt=(x, y) -> x[2] < y[2])
    return length(arr) <= maxtoreturn ? arr : arr[1:maxtoreturn]
end

for s in ["accomodate", "definately", "goverment", "occured", "publically",
    "recieve", "seperate", "untill", "wich"]
    println("\nClose dictionary words ( distance < 0.15 using Jaro-Winkler distance) to '$s' are:")
    println("    Word      |  Distance")
    for (w, jw) in closewords(s, 0.15, 5)
        println(rpad(w, 14), "| ", Float16(jw))
    end
end


import lenientops

func jaroSim(s1, s2: string): float =

  if s1.len == 0 and s2.len == 0: return 1
  if s1.len == 0 or s2.len == 0: return 0

  let matchDistance = max(s1.len, s2.len) div 2 - 1
  var s1Matches = newSeq[bool](s1.len)
  var s2Matches = newSeq[bool](s2.len)
  var matches = 0
  for i in 0..s1.high:
    for j in max(0, i - matchDistance)..min(i + matchDistance, s2.high):
      if not s2Matches[j] and s1[i] == s2[j]:
        s1Matches[i] = true
        s2Matches[j] = true
        inc matches
        break
  if matches == 0: return 0

  var transpositions = 0.0
  var k = 0
  for i in ..s1.high:
    if not s1Matches[i]: continue
    while not s2Matches[k]: inc k
    if s1[i] != s2[k]: transpositions += 0.5
    inc k

  result = (matches / s1.len + matches / s2.len + (matches - transpositions) / matches) / 3

func jaroWinklerDist(s, t: string): float =
  let ls = s.len
  let lt = t.len
  var lmax = if ls < lt: ls else: lt
  if lmax > 4: lmax = 4
  var l = 0
  for i in 0..<lmax:
    if s[i] == t[i]: inc l
  let js = jaroSim(s, t)
  let p = 0.1
  let ws = js + float(l) * p * (1 - js)
  result = 1 - ws

when isMainModule:

  import algorithm, sequtils, strformat

  type Wd = tuple[word: string; dist: float]

  func `<`(w1, w2: Wd): bool =
    if w1.dist < w2.dist: true
    elif w1.dist == w2.dist: w1.word < w2.word
    else: false

  const Misspelt = ["accomodate", "definately", "goverment", "occured",
                    "publically", "recieve", "seperate", "untill", "wich"]

  let words = toSeq("unixdict.txt".lines)
  for ms in Misspelt:
    var closest: seq[Wd]
    for word in words:
      if word.len == 0: continue
      let jwd = jaroWinklerDist(ms, word)
      if jwd < 0.15:
        closest.add (word, jwd)
    echo "Misspelt word: ", ms, ":"
    closest.sort()
    for i, c in closest:
      echo &"{c.dist:0.4f} {c.word}"
      if i == 5: break
    echo()


use strict;
use warnings;
use List::Util qw(min max head);

sub jaro_winkler {
    my($s, $t) = @_;
    my(@s_matches, @t_matches, $matches);

    return 0 if $s eq $t;

    my $s_len = length $s; my @s = split //, $s;
    my $t_len = length $t; my @t = split //, $t;

    my $match_distance = int (max($s_len,$t_len)/2) - 1;

    for my $i (0 .. $#s) {
        my $start = max(0, $i - $match_distance);
        my $end   = min($i + $match_distance, $t_len - 1);
        for my $j ($start .. $end) {
            next if $t_matches[$j] or $s[$i] ne $t[$j];
            ($s_matches[$i], $t_matches[$j]) = (1, 1);
            $matches++ and last;
        }
    }
    return 1 unless $matches;

    my($k, $transpositions) = (0, 0);

    for my $i (0 .. $#s) {
        next unless $s_matches[$i];
        $k++ until  $t_matches[$k];
        $transpositions++ if $s[$i] ne $t[$k];
        $k++;
    }

    my $prefix = 0;
    $s[$_] eq $t[$_] and ++$prefix for 0 .. -1 + min 5, $s_len, $t_len;

    my $jaro = ($matches / $s_len + $matches / $t_len +
        (($matches - $transpositions / 2) / $matches)) / 3;

    1 - ($jaro + $prefix * .1 * ( 1 - $jaro) )
}

my @words = split /\n/, `cat ./unixdict.txt`;

for my $word (<accomodate definately goverment occured publically recieve seperate untill wich>) {
    my %J;
    $J{$_} = jaro_winkler($word, $_) for @words;
    print "\nClosest 5 dictionary words with a Jaro-Winkler distance < .15 from '$word':\n";
    printf "%15s : %0.4f\n", $_, $J{$_}
         for head 5, sort { $J{$a} <=> $J{$b} or $a cmp $b } grep { $J{$_} < 0.15 } keys %J;
}


class Josephus {
  function : Execute(n : Int, k : Int) ~ Int {
    killIdx := 0;
    prisoners := Collection.IntVector->New();
    for(i := 0;i < n;i+=1;){
      prisoners->AddBack(i);
    };

    "Prisoners executed in order:"->PrintLine();
    while(prisoners->Size() > 1){
      killIdx := (killIdx + k - 1) % prisoners->Size();
      executed := prisoners->Get(killIdx);
      "{$executed} "->Print();
      prisoners->Remove(killIdx);
    };
    '\n'->Print();
    return prisoners->Get(0);
  }

  function : ExecuteAllButM(n : Int, k : Int, m : Int) ~ Collection.IntVector {
    killIdx := 0;
    prisoners := Collection.IntVector->New();
    for(i := 0;i < n;i+=1;){
      prisoners->AddBack(i);
    };
    "Prisoners executed in order:"->PrintLine();
    while(prisoners->Size() > m){
      killIdx := (killIdx + k - 1) % prisoners->Size();
      executed := prisoners->Get(killIdx);
      "{$executed} "->Print();
      prisoners->Remove(killIdx);
    };
    '\n'->Print();
    return prisoners;
  }

  function : Main(args : String[]) ~ Nil {
    result := Execute(41, 3);
    "Survivor: {$result}"->PrintLine();

    results := ExecuteAllButM(41, 3, 3);
    "Survivors: "->Print();
    each(i : results) {
    results->Get(i)->Print();
      if(i + 1 < results->Size()) {
        ' '->Print();
      };
    };
  }
}


function jaro(string str1, str2)
    str1 = trim(upper(str1))
    str2 = trim(upper(str2))
    integer len1 = length(str1),
            len2 = length(str2),
            match_distance = floor(max(len1,len2)/2)-1,
            match_count = 0,
            half_transposed = 0

    if len1==0 then return len2==0 end if

    -- count the number of matches
    sequence m1 = repeat(false,len1),
             m2 = repeat(false,len2)
    for i=1 to len1 do
        for k=max(1,i-match_distance)
           to min(len2,i+match_distance) do
            if not m2[k] then
                if str1[i]=str2[k] then
                    m1[i] = true
                    m2[k] = true
                    match_count += 1
                    exit
                end if
            end if
        end for
    end for

    if match_count==0 then return 0 end if

    -- count the number of half-transpositions
    integer k = 1
    for i=1 to len1 do
        if m1[i] then
            while not m2[k] do k += 1 end while
            half_transposed += (str1[i]!=str2[k])
            k += 1
        end if
    end for
    integer transpositions = floor(half_transposed/2),
            not_transposed = match_count - transpositions
    --
    -- return the average of:
    --   percentage/fraction of the first string matched,
    --   percentage/fraction of the second string matched, and
    --   percentage/fraction of matches that were not transposed.
    --
    return (match_count/len1 +
            match_count/len2 +
            not_transposed/match_count)/3
end function

with javascript_semantics
function jaroWinklerDist(string s, t)
    integer lm = min({length(s),length(t),4}),
            l = sum(sq_eq(s[1..lm],t[1..lm]))
    return (1-jaro(s, t))*(1-l*0.1)
end function

constant mispelt = {"accomodate", "definately", "goverment", "occured",
                    "publically", "recieve", "seperate", "untill", "wich"},
         words = unix_dict()
sequence jwds = repeat(0,length(words))
for m=1 to length(mispelt) do
    string ms = mispelt[m]
    printf(1,"\nMisspelt word: %s :\n", ms)
    for w=1 to length(words) do
        jwds[w] = jaroWinklerDist(ms,words[w])
    end for
    sequence tags = custom_sort(jwds,tagset(length(words)))
    for j=1 to 6 do
        integer tj = tags[j]
--      if jwds[tj]>0.15 then exit end if
        printf(1,"%0.4f %s\n", {jwds[tj], words[tj]})
    end for
end for


: josephus(n, k)
| prisoners killed i |
   n seq asListBuffer ->prisoners
   ListBuffer newSize(n) ->killed

   0 n 1- loop: i [
      k 1- + prisoners size mod dup 1+ prisoners removeAt
      killed add
      ] drop

   System.Out "Killed : " << killed << "\nSurvivor : " << prisoners << cr
;


declare
fun {Pipe Xs L H F}
   if L=<H then {Pipe {F Xs L} L+1 H F} else Xs end
end
fun {Josephus N K}
   fun {Victim Xs I}
      case Xs of kill(X S)|Xr then
	 if S==1 then Last=I nil
	 elseif X mod K==0 then
	    Killed:=I-1|@Killed
	    kill(X+1 S-1)|Xr
	 else
	    kill(X+1 S)|{Victim Xr I}
	 end
      [] nil then nil end
   end
   Last Zs Killed={NewCell nil}
in
   Zs={Pipe kill(1 N)|Zs 1 N
       fun {$ Is I} thread {Victim Is I} end end}
   result(survivor: Last-1 killed: {Reverse @Killed})
end
{Show {Josephus 41 3}}


Josephus(n, k)=if(n<2, n>0, my(t=(Josephus(n-1, k)+k)%n); if(t, t, n))


"""
Test Jaro-Winkler distance metric.
linuxwords.txt is from http://users.cs.duke.edu/~ola/ap/linuxwords
"""

WORDS = [s.strip() for s in open("linuxwords.txt").read().split()]
MISSPELLINGS = [
    "accomodate",
    "definately",
    "goverment",
    "occured",
    "publically",
    "recieve",
    "seperate",
    "untill",
    "wich",
]

def jaro_winkler_distance(st1, st2):
    """
    Compute Jaro-Winkler distance between two strings.
    """
    if len(st1) < len(st2):
        st1, st2 = st2, st1
    len1, len2 = len(st1), len(st2)
    if len2 == 0:
        return 0.0
    delta = max(0, len2 // 2 - 1)
    flag = [False for _ in range(len2)]  # flags for possible transpositions
    ch1_match = []
    for idx1, ch1 in enumerate(st1):
        for idx2, ch2 in enumerate(st2):
            if idx2 <= idx1 + delta and idx2 >= idx1 - delta and ch1 == ch2 and not flag[idx2]:
                flag[idx2] = True
                ch1_match.append(ch1)
                break

    matches = len(ch1_match)
    if matches == 0:
        return 1.0
    transpositions, idx1 = 0, 0
    for idx2, ch2 in enumerate(st2):
        if flag[idx2]:
            transpositions += (ch2 != ch1_match[idx1])
            idx1 += 1

    jaro = (matches / len1 + matches / len2 + (matches - transpositions/2) / matches) / 3.0
    commonprefix = 0
    for i in range(min(4, len2)):
        commonprefix += (st1[i] == st2[i])

    return 1.0 - (jaro + commonprefix * 0.1 * (1 - jaro))

def within_distance(maxdistance, stri, maxtoreturn):
    """
    Find words in WORDS of closeness to stri within maxdistance, return up to maxreturn of them.
    """
    arr = [w for w in WORDS if jaro_winkler_distance(stri, w) <= maxdistance]
    arr.sort(key=lambda x: jaro_winkler_distance(stri, x))
    return arr if len(arr) <= maxtoreturn else arr[:maxtoreturn]

for STR in MISSPELLINGS:
    print('\nClose dictionary words ( distance < 0.15 using Jaro-Winkler distance) to "',
          STR, '" are:\n        Word   |  Distance')
    for w in within_distance(0.15, STR, 5):
        print('{:>14} | {:6.4f}'.format(w, jaro_winkler_distance(STR, w)))


sub jaro-winkler ($s, $t) {

    return 0 if $s eq $t;

    my $s_len = + my @s = $s.comb;
    my $t_len = + my @t = $t.comb;

    my $match_distance = ($s_len max $t_len) div 2 - 1;

    my @s_matches;
    my @t_matches;
    my $matches = 0;

    for ^@s -> $i {

        my $start = 0 max $i - $match_distance;
        my $end = $i + $match_distance min ($t_len - 1);

        for $start .. $end -> $j {
            @t_matches[$j] and next;
            @s[$i] eq @t[$j] or next;
            @s_matches[$i] = 1;
            @t_matches[$j] = 1;
            $matches++;
            last;
        }
    }

    return 1 if $matches == 0;

    my $k              = 0;
    my $transpositions = 0;

    for ^@s -> $i {
        @s_matches[$i] or next;
        until @t_matches[$k] { ++$k }
        @s[$i] eq @t[$k] or ++$transpositions;
        ++$k;
    }

    my $prefix = 0;

    ++$prefix if @s[$_] eq @t[$_] for ^(min 4, $s_len, $t_len);

    my $jaro = ($matches / $s_len + $matches / $t_len +
        (($matches - $transpositions / 2) / $matches)) / 3;

    1 - ($jaro + $prefix * .1 * ( 1 - $jaro) )
}

my @words =  './unixdict.txt'.IO.slurp.words;

for <accomodate definately goverment occured publically recieve seperate untill wich>
   -> $word {

   my %result = @words.race.map: { $_ => jaro-winkler($word, $_) };

   say "\nClosest 5 dictionary words with a Jaro-Winkler distance < .15 from $word:";

   printf "%15s : %0.4f\n", .key, .value for %result.grep({ .value < .15 }).sort({+.value, ~.key}).head(5);
}


F jacobi(=a, =n)
   I n <= 0
      X ValueError(‘'n' must be a positive integer.’)
   I n % 2 == 0
      X ValueError(‘'n' must be odd.’)
   a %= n
   V result = 1
   L a != 0
      L a % 2 == 0
         a /= 2
         V n_mod_8 = n % 8
         I n_mod_8 C (3, 5)
            result = -result
      (a, n) = (n, a)
      I a % 4 == 3 & n % 4 == 3
         result = -result
      a %= n
   I n == 1
      R result
   E
      R 0

print(‘n\k|’, end' ‘’)
V kmax = 20
L(k) 0..kmax
   print(‘#3’.format(k), end' ‘’)
print("\n----", end' ‘’)
L(k) 0..kmax
   print(end' ‘---’)
print()
L(n) (1..21).step(2)
   print(‘#<2 |’.format(n), end' ‘’)
   L(k) 0..kmax
      print(‘#3’.format(jacobi(k, n)), end' ‘’)
   print()


my @prisoner = 0 .. 40;
my $k = 3;
until (@prisoner == 1) {
    push @prisoner, shift @prisoner for 1 .. $k-1;
    shift @prisoner;
}

print "Prisoner @prisoner survived.\n"


function skipping(sequence prisoners, integer step, survivors=1)
    integer n = length(prisoners), nn = n, p = 0
    while n>survivors do
        integer found = 0
        while found<step do
            p = iff(p=nn?1:p+1)
            found += prisoners[p]!=-1
        end while
        prisoners[p] = -1
        n -= 1
    end while
    return remove_all(-1,prisoners)
end function
--?skipping({"Joe","Jack","William","John","James"},2,1) --> {"William"}


use std::fs::File;
use std::io::{self, BufRead};

fn load_dictionary(filename: &str) -> std::io::Result<Vec<String>> {
    let file = File::open(filename)?;
    let mut dict = Vec::new();
    for line in io::BufReader::new(file).lines() {
        dict.push(line?);
    }
    Ok(dict)
}

fn jaro_winkler_distance(string1: &str, string2: &str) -> f64 {
    let mut st1 = string1;
    let mut st2 = string2;
    let mut len1 = st1.chars().count();
    let mut len2 = st2.chars().count();
    if len1 < len2 {
        std::mem::swap(&mut st1, &mut st2);
        std::mem::swap(&mut len1, &mut len2);
    }
    if len2 == 0 {
        return if len1 == 0 { 0.0 } else { 1.0 };
    }
    let delta = std::cmp::max(1, len1 / 2) - 1;
    let mut flag = vec![false; len2];
    let mut ch1_match = vec![];
    for (idx1, ch1) in st1.chars().enumerate() {
        for (idx2, ch2) in st2.chars().enumerate() {
            if idx2 <= idx1 + delta && idx2 + delta >= idx1 && ch1 == ch2 && !flag[idx2] {
                flag[idx2] = true;
                ch1_match.push(ch1);
                break;
            }
        }
    }
    let matches = ch1_match.len();
    if matches == 0 {
        return 1.0;
    }
    let mut transpositions = 0;
    let mut idx1 = 0;
    for (idx2, ch2) in st2.chars().enumerate() {
        if flag[idx2] {
            transpositions += (ch2 != ch1_match[idx1]) as i32;
            idx1 += 1;
        }
    }
    let m = matches as f64;
    let jaro =
        (m / (len1 as f64) + m / (len2 as f64) + (m - (transpositions as f64) / 2.0) / m) / 3.0;
    let mut commonprefix = 0;
    for (c1, c2) in st1.chars().zip(st2.chars()).take(std::cmp::min(4, len2)) {
        commonprefix += (c1 == c2) as i32;
    }
    1.0 - (jaro + commonprefix as f64 * 0.1 * (1.0 - jaro))
}

fn within_distance<'a>(
    dict: &'a Vec<String>,
    max_distance: f64,
    stri: &str,
    max_to_return: usize,
) -> Vec<(&'a String, f64)> {
    let mut arr: Vec<(&String, f64)> = dict
        .iter()
        .map(|w| (w, jaro_winkler_distance(stri, w)))
        .filter(|x| x.1 <= max_distance)
        .collect();
    // The trait std::cmp::Ord is not implemented for f64, otherwise
    // we could just do this:
    // arr.sort_by_key(|x| x.1);
    let compare_distance = |d1, d2| {
        use std::cmp::Ordering;
        if d1 < d2 {
            Ordering::Less
        } else if d1 > d2 {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    };
    arr.sort_by(|x, y| compare_distance(x.1, y.1));
    arr[0..std::cmp::min(max_to_return, arr.len())].to_vec()
}

fn main() {
    match load_dictionary("linuxwords.txt") {
        Ok(dict) => {
            for word in &[
                "accomodate",
                "definately",
                "goverment",
                "occured",
                "publically",
                "recieve",
                "seperate",
                "untill",
                "wich",
            ] {
                println!("Close dictionary words (distance < 0.15 using Jaro-Winkler distance) to '{}' are:", word);
                println!("        Word   |  Distance");
                for (w, dist) in within_distance(&dict, 0.15, word, 5) {
                    println!("{:>14} | {:6.4}", w, dist)
                }
                println!();
            }
        }
        Err(error) => eprintln!("{}", error),
    }
}


import Foundation

func loadDictionary(_ path: String) throws -> [String] {
    let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
    return contents.components(separatedBy: "\n")
}

func jaroWinklerDistance(string1: String, string2: String) -> Double {
    var st1 = Array(string1)
    var st2 = Array(string2)
    var len1 = st1.count
    var len2 = st2.count
    if len1 < len2 {
        swap(&st1, &st2)
        swap(&len1, &len2)
    }
    if len2 == 0 {
        return len1 == 0 ? 0.0 : 1.0
    }
    let delta = max(1, len1 / 2) - 1
    var flag = Array(repeating: false, count: len2)
    var ch1Match: [Character] = []
    ch1Match.reserveCapacity(len1)
    for idx1 in 0..<len1 {
        let ch1 = st1[idx1]
        for idx2 in 0..<len2 {
            let ch2 = st2[idx2]
            if idx2 <= idx1 + delta && idx2 + delta >= idx1 && ch1 == ch2 && !flag[idx2] {
                flag[idx2] = true
                ch1Match.append(ch1)
                break
            }
        }
    }
    let matches = ch1Match.count
    if matches == 0 {
        return 1.0
    }
    var transpositions = 0
    var idx1 = 0
    for idx2 in 0..<len2 {
        if flag[idx2] {
            if st2[idx2] != ch1Match[idx1] {
                transpositions += 1
            }
            idx1 += 1
        }
    }
    let m = Double(matches)
    let jaro =
        (m / Double(len1) + m / Double(len2) + (m - Double(transpositions) / 2.0) / m) / 3.0
    var commonPrefix = 0
    for i in 0..<min(4, len2) {
        if st1[i] == st2[i] {
            commonPrefix += 1
        }
    }
    return 1.0 - (jaro + Double(commonPrefix) * 0.1 * (1.0 - jaro))
}

func withinDistance(words: [String], maxDistance: Double, string: String,
                    maxToReturn: Int) -> [(String, Double)] {
    var arr = Array(words.map{($0, jaroWinklerDistance(string1: string, string2: $0))}
        .filter{$0.1 <= maxDistance})
    arr.sort(by: { x, y in return x.1 < y.1 })
    return Array(arr[0..<min(maxToReturn, arr.count)])
}

func pad(string: String, width: Int) -> String {
    if string.count >= width {
        return string
    }
    return String(repeating: " ", count: width - string.count) + string
}

do {
    let dict = try loadDictionary("linuxwords.txt")
    for word in ["accomodate", "definately", "goverment", "occured",
                 "publically", "recieve", "seperate", "untill", "wich"] {
        print("Close dictionary words (distance < 0.15 using Jaro-Winkler distance) to '\(word)' are:")
        print("        Word   |  Distance")
        for (w, dist) in withinDistance(words: dict, maxDistance: 0.15,
                                        string: word, maxToReturn: 5) {
            print("\(pad(string: w, width: 14)) | \(String(format: "%6.4f", dist))")
        }
        print()
    }
} catch {
    print(error.localizedDescription)
}


var fs = require('fs')

// Jaro Winkler Distance Formula
function jaroDistance(string1: string, string2: string): number{
    // Compute Jaro-Winkler distance between two string
    // Swap strings if string1 is shorter than string 2
    if (string1.length < string2.length){
        const tempString: string = string1;
        string1 = string2;
        string2 = tempString
    }
    let len1: number = string1.length
    let len2: number = string2.length
    if (!len2){
        return 0.0
    }
    const delta: number = Math.max(1, len1 / 2.0) - 1.0;
    // Flags for transpositions
    let flag: boolean[] = Array(len2).fill(false)
    let ch1Match: string[] = Array(len1).fill('')
    // Count number of matching characters
    let matches = 0
    // Check if characters on both string matches
    for (let i: number = 0; i < len1; i++){
            const ch1: string = string1[i]
            for (let j = 0; j < len2; j++){
                const ch2: string = string2[j]
                if (j <= i + delta && j + delta >= 1 && ch1 == ch2 && !flag[j]){
                    flag[j] = true
                    ch1Match[matches++] = ch1;
                    break;
                }
            }
    }
    if (!matches){
        return 1.0
    }
    // Count number of transpositions (shared characters placed in different positions)
    let transpositions: number = 0.0
    for (let i: number = 0, j: number = 0; j < len2; j++){
            if (flag[j]){
                if (string2[j] != ch1Match[i]){
                    transpositions++
                }
                i++
            }
    }
    const m: number = matches
    // Jaro Similarity Formula simj = ( (m / length of s1) + (m / length of s2) + (m - t) / m ) / 3
    const jaro: number = (m / len1 + m / len2 + (m - transpositions / 2.0) / m) / 3.0
    // Length of common prefix between string up to 4 characters
    let commonPrefix: number = 0.0
    len2 = Math.min(4, len2)
    for (let i: number = 0; i < len2; i++){
        if (string1[i] == string2[i]){
            commonPrefix++
        }
    }
    // Jaro Winkler Distance Formula simw = simj + lp(1 - simj)
    return 1.0 - (jaro + commonPrefix * 0.1 * (1.0 - jaro))
}

// Compute Jaro Winkler Distance for every word on the dictionary against the misspelled word
function withinDistance(words: string[] ,maxDistance: number, string: string, maxToReturn: number): (string | number)[][]{
    let result: (string | number)[][]  = new Array()
    words.forEach(word =>{
        const distance = jaroDistance(word, string)
        // check if computed jaro winkler distance is within the set distance parameter
        if (distance <= maxDistance){
            const tuple = [distance, word]
            result.push(tuple)
        }
    })
    result.sort()
    // Limit of matches set to maxtoReturn
    return result.length <= maxToReturn ? result : result.slice(0, maxToReturn)
}

function loadDictionary(fileName: string): string[]{
    let words: string[] = new Array()
    try{
        //attacomsian.com/blog/reading-a-file-line-by-line-in-nodejs
        const data = fs.readFileSync(fileName, 'utf-8')
        const lines: string[] = data.split(/\r?\n/)
        lines.forEach(line => {
            words.push(line)
        })
        return words
    }
    catch(error){
        console.log("Error reading dictionary")
    }
}

function main(): void{
    try {
        const misspellings = [
            "accomodate",
            "definately",
            "goverment",
            "occured",
            "publically",
            "recieve",
            "seperate",
            "untill",
            "wich"
        ]
        //unixdict.txt from users.cs.duke.edu/~ola/ap/linuxwords
        let words: string[] = loadDictionary("unixdict.txt")

        misspellings.forEach(spelling =>{
            console.log("Misspelling:", spelling)
            const closeWord = withinDistance(words, 0.15, spelling, 5)
            closeWord.forEach(word =>{
                console.log((word[0] as number).toFixed(4) + " " + word[1])
            })
            console.log("")
        })
    }
    catch(error) {
        console.log("Error on main")
    }
}
main();


import os

fn jaro_sim(str1 string, str2 string) f64 {
    if str1.len == 0 && str2.len == 0 {
        return 1
    }
    if str1.len == 0 || str2.len == 0 {
        return 0
    }
    mut match_distance := str1.len
    if str2.len > match_distance {
        match_distance = str2.len
    }
    match_distance = match_distance/2 - 1
    mut str1_matches := []bool{len: str1.len}
    mut str2_matches := []bool{len: str2.len}
    mut matches := 0.0
    mut transpositions := 0.0
    for i in 0..str1.len {
        mut start := i - match_distance
        if start < 0 {
            start = 0
        }
        mut end := i + match_distance + 1
        if end > str2.len {
            end = str2.len
        }
        for k in start..end {
            if str2_matches[k] {
                continue
            }
            if str1[i] != str2[k] {
                continue
            }
            str1_matches[i] = true
            str2_matches[k] = true
            matches++
            break
        }
    }
    if matches == 0 {
        return 0
    }
    mut k := 0
    for i in 0.. str1.len {
        if !str1_matches[i] {
            continue
        }
        for !str2_matches[k] {
            k++
        }
        if str1[i] != str2[k] {
            transpositions++
        }
        k++
    }
    transpositions /= 2
    return (matches/f64(str1.len) +
        matches/f64(str2.len) +
        (matches-transpositions)/matches) / 3
}

fn jaro_winkler_dist(s string, t string) f64 {
    ls := s.len
    lt := t.len
    mut lmax := lt
    if ls < lt {
        lmax = ls
    }
    if lmax > 4 {
        lmax = 4
    }
    mut l := 0
    for i in 0 .. lmax {
        if s[i] == t[i] {
            l++
        }
    }
    js := jaro_sim(s, t)
    p := 0.1
    ws := js + f64(l)*p*(1-js)
    return 1 - ws
}

struct Wd {
    word string
    dist f64
}

fn main() {
    misspelt := [
        "accomodate", "definately", "goverment", "occured", "publically",
        "recieve", "seperate", "untill", "wich",
	]
    words := os.read_lines('unixdict.txt')?
    for ms in misspelt {
        mut closest := []Wd{}
        for word in words {
            if word == "" {
                continue
            }
            jwd := jaro_winkler_dist(ms, word)
            if jwd < 0.15 {
                closest << Wd{word, jwd}
            }
        }
        println("Misspelt word: $ms:")
		closest.sort(a.dist<b.dist)
        for i, c in closest {
            println("${c.dist:.4f} ${c.word}")
            if i == 5 {
                break
            }
        }
        println('')
    }
}


import "io" for File
import "/fmt" for Fmt
import "/sort" for Sort

var jaroSim = Fn.new { |s1, s2|
    var le1 = s1.count
    var le2 = s2.count
    if (le1 == 0 && le2 == 0) return 1
    if (le1 == 0 || le2 == 0) return 0
    var dist = (le2 > le1) ? le2 : le1
    dist = (dist/2).floor - 1
    var matches1 = List.filled(le1, false)
    var matches2 = List.filled(le2, false)
    var matches = 0
    var transpos = 0
    for (i in 0...s1.count) {
        var start = i - dist
        if (start < 0) start = 0
        var end = i + dist + 1
        if (end > le2) end = le2
        var k = start
        while (k < end) {
            if (!(matches2[k] || s1[i] != s2[k])) {
                matches1[i] = true
                matches2[k] = true
                matches = matches + 1
                break
            }
            k = k + 1
        }
    }
    if (matches == 0) return 0
    var k = 0
    for (i in 0...s1.count) {
        if (matches1[i]) {
            while(!matches2[k]) k = k + 1
            if (s1[i] != s2[k]) transpos = transpos + 1
            k = k + 1
        }
    }
    transpos = transpos / 2
    return (matches/le1 + matches/le2 + (matches - transpos)/matches) / 3
}

var jaroWinklerDist = Fn.new { |s, t|
    var ls = s.count
    var lt = t.count
    var lmax = (ls < lt) ? ls : lt
    if (lmax > 4) lmax = 4
    var l = 0
    for (i in 0...lmax) {
        if (s[i] == t[i]) l = l + 1
    }
    var js = jaroSim.call(s, t)
    var p = 0.1
    var ws = js + l*p*(1 - js)
    return 1 - ws
}

var misspelt = ["accomodate", "definately", "goverment", "occured", "publically", "recieve", "seperate", "untill", "wich"]
var words = File.read("unixdict.txt").split("\n").map { |w| w.trim() }.where { |w| w != "" }
for (ms in misspelt) {
    var closest = []
    for (word in words) {
       var jwd = jaroWinklerDist.call(ms, word)
       if (jwd < 0.15) closest.add([word, jwd])
    }
    System.print("Misspelt word: %(ms):")
    var cmp = Fn.new { |n1, n2| (n1[1]-n2[1]).sign }
    Sort.insertion(closest, cmp)
    for (c in closest.take(6)) Fmt.print("$0.4f $s", c[1], c[0])
    System.print()
}


INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit

INT FUNC Jacobi(INT a,n)
  INT res,tmp

  IF a>=n THEN
    a=a MOD n
  FI
  res=1
  WHILE a
  DO
    WHILE (a&1)=0
    DO
      a=a RSH 1
      tmp=n&7
      IF tmp=3 OR tmp=5 THEN
        res=-res
      FI
    OD
    tmp=a a=n n=tmp
    IF (a%3)=3 AND (n%3)=3 THEN
      res=-res
    FI
    a=a MOD n
  OD

  IF n=1 THEN
    RETURN (res)
  FI
RETURN (0)

PROC PrintTable(INT maxK,maxN)
  INT res,n,k
  CHAR ARRAY t(10)

  Put('n) Put(7) Put('k) Put(124)
  FOR k=0 TO maxK
  DO
    StrI(k,t) PrintF("%3S",t)
  OD
  PutE()

  Put(18) Put(18) Put(18) Put(19)
  FOR k=0 TO 3*maxK+2
  DO
    Put(18)
  OD
  PutE()

  FOR n=1 TO maxN STEP 2
  DO
    StrI(n,t) PrintF("%3S",t)
    Put(124)
    FOR k=0 TO maxK
    DO
      res=Jacobi(k,n)
      StrI(res,t) PrintF("%3S",t)
    OD
    PutE()
  OD
RETURN

PROC Main()
  Put(125) PutE() ;clear the screen
  PrintTable(10,39)
RETURN


jacobi: function [n,k][
    N: n % k
    K: k

    result: 1
    while [N <> 0][
        while [even? N][
            N: shr N 1
            if contains? [3 5] and K 7 ->
                result: neg result
        ]
        [N,K]: @[K,N]
        if and? 3=and N 3 3=and K 3 ->
            result: neg result
        N: N % K
    ]
    if K <> 1 ->
        result: 0

    return result
]

print ["" "k/n" "|"] ++ map to [:string] 1..20 'item -> pad.left item 2
print repeat "=" 67
loop range.step:2 1 21 'k [
    print [
        "" pad to :string k 3 "|" join.with:" " map to [:string] map 1..20 'n -> jacobi n k
                                                                        'item -> pad.left item 2
    ]
]


# syntax: GAWK -f JACOBI_SYMBOL.AWK
BEGIN {
    max_n = 29
    max_a = max_n + 1
    printf("n\\a")
    for (i=1; i<=max_a; i++) {
      printf("%3d",i)
      underline = underline " --"
    }
    printf("\n---%s\n",underline)
    for (n=1; n<=max_n; n+=2) {
      printf("%3d",n)
      for (a=1; a<=max_a; a++) {
        printf("%3d",jacobi(a,n))
      }
      printf("\n")
    }
    exit(0)
}
function jacobi(a,n,  result,tmp) {
    if (n%2 == 0) {
      print("error: 'n' must be a positive odd integer")
      exit
    }
    a %= n
    result = 1
    while (a != 0) {
      while (a%2 == 0) {
        a /= 2
        if (n%8 == 3 || n%8 == 5) {
          result = -result
        }
      }
      tmp = a
      a = n
      n = tmp
      if (a%4 == 3 && n%4 == 3) {
        result = -result
      }
      a %= n
    }
    if (n == 1) {
      return(result)
    }
    return(0)
}


<?php //Josephus.php
function Jotapata($n=41,$k=3,$m=1){$m--;
	$prisoners=array_fill(0,$n,false);//make a circle of n prisoners, store false ie: dead=false
	$deadpool=1;//count to next execution
	$order=0;//death order and *dead* flag, ie. deadpool
	while((array_sum(array_count_values($prisoners))<$n)){//while sum of count of unique values dead times < n (they start as all false)
		foreach($prisoners as $thisPrisoner=>$dead){
			if(!$dead){//so yeah...if not dead...
				if($deadpool==$k){//if their time is up in the deadpool...
					$order++;
					//set the deadpool value or enumerate as survivor
					$prisoners[$thisPrisoner]=((($n-$m)>($order)?$order:(($n)==$order?'Call me *Titus Flavius* Josephus':'Joe\'s friend '.(($order)-($n-$m-1)))));
					$deadpool=1;//reset count to next execution
				}else{$duckpool++;}
			}
		}
	}
	return $prisoners;
}
echo '<pre>'.print_r(Jotapata(41,3,5),true).'<pre>';


#include <stdlib.h>
#include <stdio.h>

#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))

int jacobi(unsigned long a, unsigned long n) {
	if (a >= n) a %= n;
	int result = 1;
	while (a) {
		while ((a & 1) == 0) {
			a >>= 1;
			if ((n & 7) == 3 || (n & 7) == 5) result = -result;
		}
		SWAP(a, n);
		if ((a & 3) == 3 && (n & 3) == 3) result = -result;
		a %= n;
	}
	if (n == 1) return result;
	return 0;
}

void print_table(unsigned kmax, unsigned nmax) {
	printf("n\\k|");
	for (int k = 0; k <= kmax; ++k) printf("%'3u", k);
	printf("\n----");
	for (int k = 0; k <= kmax; ++k) printf("---");
	putchar('\n');
	for (int n = 1; n <= nmax; n += 2) {
		printf("%-2u |", n);
		for (int k = 0; k <= kmax; ++k)
			printf("%'3d", jacobi(k, n));
		putchar('\n');
	}
}

int main() {
	print_table(20, 21);
	return 0;
}


#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>

int jacobi(int n, int k) {
    assert(k > 0 && k % 2 == 1);
    n %= k;
    int t = 1;
    while (n != 0) {
        while (n % 2 == 0) {
            n /= 2;
            int r = k % 8;
            if (r == 3 || r == 5)
                t = -t;
        }
        std::swap(n, k);
        if (n % 4 == 3 && k % 4 == 3)
            t = -t;
        n %= k;
    }
    return k == 1 ? t : 0;
}

void print_table(std::ostream& out, int kmax, int nmax) {
    out << "n\\k|";
    for (int k = 0; k <= kmax; ++k)
        out << ' ' << std::setw(2) << k;
    out << "\n----";
    for (int k = 0; k <= kmax; ++k)
        out << "---";
    out << '\n';
    for (int n = 1; n <= nmax; n += 2) {
        out << std::setw(2) << n << " |";
        for (int k = 0; k <= kmax; ++k)
            out << ' ' << std::setw(2) << jacobi(k, n);
        out << '\n';
    }
}

int main() {
    print_table(std::cout, 20, 21);
    return 0;
}


#general solution
(de jo (N K)
   (if (=1 N)
      1
      (inc
         (%
            (+ (dec K) (jo (dec N) K))
            N ) ) ) )

#special case when K is 2; much faster than general version.
(de jo2(N)
   (let P 1
      (while (<= P N)
         (setq P (* 2 P))
         (+ (- (* 2 N) P) 1) ) ) )

# find the survivor using an optimal solution
(de survivor (N K)
   (if (=0 (% N 2))
      (jo2 N)
      (jo N K) ) )
(print (survivor 5 2))
(print (survivor 41 3))


*process or(!) source attributes xref;
 joseph: Proc Options(main);
 /* REXX **************************************************************
 * 15.11.2012 Walter Pachl - my own solution
 * 16.11.2012 Walter Pachl generalized n prisoners + w killing distance
 *                         and s=number of survivors
 * 03.05.2013 Walter Pachl Translated From REXX Version 1
 **********************************************************************/
 Dcl dead(0:100) Bit(1);
 Dcl (n,nn,w,s,p,found) Bin Fixed(15);
 Dcl pp Pic'99';
 Dcl killed Char(300) Var Init('killed: '); /* output of killings     */
 Dcl survived Char(300) Var Init('Survivor(s): ');
 dead='';                               /* nobody's dead yet          */
 n=41;                                  /* number of alive prisoners  */
 nn=n;                                  /* wrap around boundary       */
 w=3;                                   /* killing count              */
 s=1;                                   /* number of survivors         */
 p=-1;                                  /* start here                 */
 Do Until(n=s);                         /* until one alive prisoner   */
   found=0;                             /* start looking              */
   Do Until(found=w);                   /* until we have the third    */
     p=p+1;                             /* next position              */
     If p=nn Then p=0;                  /* wrap around                */
     If ^dead(p) Then                   /* a prisoner who is alive    */
       found=found+1;                   /* increment found count      */
     End;
   dead(p)='1'b;                        /* shoot the one on this pos. */
   n=n-1;
   pp=p;
   killed=killed!!' '!!pp;              /* add to output              */
   End;                                 /* End of main loop           */
 Call o(killed);
 Do i=0 To nn-1;                        /* look for the surviving p's */
   If ^dead(i) Then Do;                 /* found one                  */
     pp=i;
     survived=survived!!' '!!pp;
     End;
   End;
 Call o(survived);

 o: Proc(s);
 /*********************************************************************
 * Formatted Output of given string:
 * xxxxxxxxxx xxx xx xx xxx ---
 *         xx xxx xxx
 *         xxxxx xxx
 *********************************************************************/
 Dcl s Char(*) Var;
 Dcl p Bin Fixed(15);
 Dcl ll Bin Fixed(15) Init(72);
 Do While(length(s)>ll);
   Do p=ll+1 To 10 By -1;
     If substr(s,p,1)=' ' Then
       Leave;
     End;
   Put Edit(left(s,p))(Skip,a);
   s=repeat(' ',8)!!substr(s,p+1);
   End;
 Put Edit(s)(Skip,a);
 End;

 End;


def jacobi(a, n)
  raise ArgumentError.new "n must b positive and odd" if n < 1 || n.even?
  res = 1
  until (a %= n) == 0
    while a.even?
      a >>= 1
      res = -res if [3, 5].includes? n % 8
    end
    a, n = n, a
    res = -res if a % 4 == n % 4 == 3
  end
  n == 1 ? res : 0
end

puts "Jacobian symbols for jacobi(a, n)"
puts "n\\a  0  1  2  3  4  5  6  7  8  9 10"
puts "------------------------------------"
1.step(to: 17, by: 2) do |n|
   printf("%2d ", n)
   (0..10).each { |a| printf(" % 2d", jacobi(a, n)) }
   puts
end


jacobi(_, N) when N =< 0 -> jacobi_domain_error;
jacobi(_, N) when (N band 1) =:= 0 -> jacobi_domain_error;
jacobi(A, N) when A < 0 ->
    J2 = ja(-A, N),
    case N band 3 of
        1 -> J2;
        3 -> -J2
    end;
jacobi(A, N) -> ja(A, N).

ja(0, _) -> 0;
ja(1, _) -> 1;
ja(A, N) when A >= N -> ja(A rem N, N);
ja(A, N) when (A band 1) =:= 0 -> % A is even
    J2 = ja(A bsr 1, N),
    case N band 7 of
        1 -> J2;
        3 -> -J2;
        5 -> -J2;
        7 -> J2
    end;
ja(A, N) ->    % if we get here, A is odd, so we can flip it.
    J2 = ja(N, A),
    case (A band 3 =:= 3) and (N band 3 =:= 3) of
        true  -> -J2;
        false -> J2
    end.


function Get-JosephusPrisoners ( [int]$N, [int]$K )
    {
    #  Just for convenience
    $End = $N - 1

    #  Create circle of prisoners
    $Prisoners = New-Object System.Collections.ArrayList ( , (0..$End) )

    #  For each starting point of the reducing circle...
    ForEach ( $Start in 0..($End - 1) )
        {
        #  We subtract one from K for the one we advanced by incrementing $Start
        #  Then take K modulus the length of the remaining circle
        $RoundK = ( $K - 1 ) % ( $End - $Start + 1 )

        #  Rotate the remaining prisoners K places around the remaining circle
        $Prisoners.SetRange( $Start, $Prisoners[ $Start..$End ][ ( $RoundK + $Start - $End - 1 )..( $RoundK - 1 ) ] )
        }
    return $Prisoners
    }


void setup() {
  println("Survivor: " + execute(41, 3));
  println("Survivors: " + executeAllButM(41, 3, 3));
}

int execute(int n, int k) {
  int killIdx = 0;
  IntList prisoners = new IntList(n);
  for (int i = 0; i < n; i++) {
    prisoners.append(i);
  }
  println("Prisoners executed in order:");
  while (prisoners.size() > 1) {
    killIdx = (killIdx + k - 1) % prisoners.size();
    print(prisoners.get(killIdx) + " ");
    prisoners.remove(killIdx);
  }
  println();
  return prisoners.get(0);
}

IntList executeAllButM(int n, int k, int m) {
  int killIdx = 0;
  IntList prisoners = new IntList(n);
  for (int i = 0; i < n; i++) {
    prisoners.append(i);
  }
  println("Prisoners executed in order:");
  while (prisoners.size() > m) {
    killIdx = (killIdx + k - 1) % prisoners.size();
    print(prisoners.get(killIdx) + " ");
    prisoners.remove(killIdx);
  }
  println();
  return prisoners;
}


NewList prisoners.i()

Procedure f2l(List p.i())
  FirstElement(p())    : tmp.i=p()
  DeleteElement(p(),1) : LastElement(p())
  AddElement(p())      : p()=tmp
EndProcedure

Procedure l2f(List p.i())
  LastElement(p())   : tmp.i=p()
  DeleteElement(p()) : FirstElement(p())
  InsertElement(p()) : p()=tmp
EndProcedure

OpenConsole()
Repeat
  Print(#LF$+#LF$)
  Print("Josephus problem - input prisoners : ") : n=Val(Input())
  If n=0 : Break : EndIf
  Print("                 - input steps     : ") : k=Val(Input())
  Print("                 - input survivors : ") : s=Val(Input()) : If s<1 : s=1 : EndIf
  ClearList(prisoners()) : For i=0 To n-1 : AddElement(prisoners()) : prisoners()=i : Next
  If n<100 : Print("Executed : ") : EndIf
  While ListSize(prisoners())>s And n>0 And k>0 And k<n
    For j=1 To k : f2l(prisoners()) : Next
    l2f(prisoners()) : FirstElement(prisoners()) : If n<100 : Print(Str(prisoners())+Space(2)) : EndIf
    DeleteElement(prisoners())
  Wend
  Print(#LF$+"Surviving: ")
  ForEach prisoners()
    Print(Str(prisoners())+Space(2))
  Next
ForEver
End


function gcdp( a as uinteger, b as uinteger ) as uinteger
    if b = 0 then return a
    return gcdp( b, a mod b )
end function

function gcd(a as integer, b as integer) as uinteger
    return gcdp( abs(a), abs(b) )
end function

function jacobi( a as uinteger, n as uinteger ) as integer
    if gcd(a, n)<>1 then return 0
    if a = 1 then return 1
    if a>n then return jacobi( a mod n, n )
    if a mod 2 = 0 then
        if n mod 8 = 1 or n mod 8 = 7 then
            return jacobi(a/2, n)
        else
            return -jacobi(a/2, n)
        end if
    end if
    dim as integer q = (-1)^((a-1)/2 * (n-1)/2)
    return q/jacobi(n, a)
end function

'print a table

function padto( i as ubyte, j as integer ) as string
    return wspace(i-len(str(j)))+str(j)
end function

dim as uinteger pn, k, prime(0 to 16) = {3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61}
dim as string outstr = "  k       "

for k = 1 to 36
    outstr = outstr + padto(2, k)+"  "
next k
print outstr
print " n"
for pn=0 to 16
    outstr= " "+padto( 2, prime(pn) )+"       "
    for k = 1 to 36
        outstr = outstr + padto(2, jacobi(k, prime(pn))) + "  "
    next k
    print outstr
next pn


[ stack ]                      is survivors           (     --> s   )

[ stack ]                      is prisoners           (     --> s   )

[ stack ]                      is executioner-actions (     --> s   )

[ [] swap times [ i^ join ]
  prisoners put ]              is make-prisoners      (   n -->     )

[ prisoners take
  behead join
  prisoners put ]              is walk                (     -->     )

[ prisoners take
  behead drop
  prisoners put ]              is kill                (     -->     )

[ [] swap 1 - times
     [ ' walk nested join ]
  ' kill nested join
  executioner-actions put ]    is make-executioner    (   n -->     )

[ executioner-actions take
  behead dup do nested join
  executioner-actions put ]    is execute-kth         (     -->     )

[ survivors put
  make-executioner
  make-prisoners
  [ execute-kth
    prisoners share
    size
    survivors share = until ]
  survivors release
  executioner-actions release
  prisoners take ]             is josephus             ( n n n --> n )


package main

import (
    "fmt"
    "log"
    "math/big"
)

func jacobi(a, n uint64) int {
    if n%2 == 0 {
        log.Fatal("'n' must be a positive odd integer")
    }
    a %= n
    result := 1
    for a != 0 {
        for a%2 == 0 {
            a /= 2
            nn := n % 8
            if nn == 3 || nn == 5 {
                result = -result
            }
        }
        a, n = n, a
        if a%4 == 3 && n%4 == 3 {
            result = -result
        }
        a %= n
    }
    if n == 1 {
        return result
    }
    return 0
}

func main() {
    fmt.Println("Using hand-coded version:")
    fmt.Println("n/a  0  1  2  3  4  5  6  7  8  9")
    fmt.Println("---------------------------------")
    for n := uint64(1); n <= 17; n += 2 {
        fmt.Printf("%2d ", n)
        for a := uint64(0); a <= 9; a++ {
            fmt.Printf(" % d", jacobi(a, n))
        }
        fmt.Println()
    }

    ba, bn := new(big.Int), new(big.Int)
    fmt.Println("\nUsing standard library function:")
    fmt.Println("n/a  0  1  2  3  4  5  6  7  8  9")
    fmt.Println("---------------------------------")
    for n := uint64(1); n <= 17; n += 2 {
        fmt.Printf("%2d ", n)
        for a := uint64(0); a <= 9; a++ {
            ba.SetUint64(a)
            bn.SetUint64(n)
            fmt.Printf(" % d", big.Jacobi(ba, bn))
        }
        fmt.Println()
    }
}


jose <-function(s, r,n){
y <- 0:(r-1)
 for (i in (r+1):n)
  y <- (y + s) %% i
 return(y)
}
> jose(3,1,41) # r is the number of remained prisoner.
[1] 30


#lang racket
(define (josephus n k (m 0))
  (for/fold ((m (add1 m)))
    ((a (in-range (add1 m) (add1 n))))
    (remainder (+ m k) a)))

(josephus 41 3) ; ->30


sub Execute(@prisoner, $k) {
    until @prisoner == 1 {
	@prisoner.=rotate($k - 1);
	@prisoner.shift;
    }
}

my @prisoner = ^41;
Execute @prisoner, 3;
say "Prisoner {@prisoner} survived.";

# We don't have to use numbers.  Any list will do:

my @dalton = <Joe Jack William Averell Rantanplan>;
Execute @dalton, 2;
say "{@dalton} survived.";


jacobi :: Integer -> Integer -> Integer
jacobi 0 1 = 1
jacobi 0 _ = 0
jacobi a n =
  let a_mod_n = rem a n
  in if even a_mod_n
       then case rem n 8 of
              1 -> jacobi (div a_mod_n 2) n
              3 -> negate $ jacobi (div a_mod_n 2) n
              5 -> negate $ jacobi (div a_mod_n 2) n
              7 -> jacobi (div a_mod_n 2) n
       else if rem a_mod_n 4 == 3 && rem n 4 == 3
              then negate $ jacobi n a_mod_n
              else jacobi n a_mod_n


NB. direct translation of the Lua program found
NB. at the wikipedia entry incorporated here in comments.

NB.function jacobi(n, k)
jacobi=: dyad define every

  k=. x  NB. k is the left argument
  n=. y  NB. n is the right hand argument

NB.assert(k > 0 and k % 2 == 1)
  assert. (k > 0) *. 1 = 2 | k

NB.n = n % k
  n =. k | n

NB.t = 1
  t =. 1

NB.while n ~= 0 do
  while. n do.

NB. while n % 2 == 0 do
    while. -. 2 | n do.

NB.   n = n / 2
      n =. <. n % 2

NB.   r = k % 8
      r =. 8 | k

NB.   if r == 3 or r == 5 then
      if. r e. 3 5 do.

NB.     t = -t
        t =. -t

NB.   end
      end.

NB. end
    end.

NB. n, k = k, n
    'n k' =. k , n

NB. if n % 4 == 3 and k % 4 == 3 then
    if. (3 = 4 | n) *. (3 = 4 | k) do.

NB.   t = -t
      t =. -t

NB. end
    end.

NB. n = n % k
    n =. k | n

NB.end
  end.

NB.if k == 1 then
  if. k = 1 do.

NB. return t
    t

NB.else
  else.

NB. return 0
    0

NB.end
  end.

NB.end
)


public class JacobiSymbol {

    public static void main(String[] args) {
        int max = 30;
        System.out.printf("n\\k ");
        for ( int k = 1 ; k <= max ; k++ ) {
            System.out.printf("%2d  ", k);
        }
        System.out.printf("%n");
        for ( int n = 1 ; n <= max ; n += 2 ) {
            System.out.printf("%2d  ", n);
            for ( int k = 1 ; k <= max ; k++ ) {
                System.out.printf("%2d  ", jacobiSymbol(k, n));
            }
            System.out.printf("%n");
        }
    }

    //  Compute (k n), where k is numerator
    private static int jacobiSymbol(int k, int n) {
        if ( k < 0 || n % 2 == 0 ) {
            throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n);
        }
        k %= n;
        int jacobi = 1;
        while ( k > 0 ) {
            while ( k % 2 == 0 ) {
                k /= 2;
                int r = n % 8;
                if ( r == 3 || r == 5 ) {
                    jacobi = -jacobi;
                }
            }
            int temp = n;
            n = k;
            k = temp;
            if ( k % 4 == 3 && n % 4 == 3 ) {
                jacobi = -jacobi;
            }
            k %= n;
        }
        if ( n == 1 ) {
            return jacobi;
        }
        return 0;
    }

}


rebol []

execute: func [death-list [block!] kill [integer!]] [
    assert [not empty? death-list]
    until [
        loop kill - 1 [append death-list take death-list]
        (1 == length? remove death-list)
    ]
]

prisoner: [] for n 0 40 1 [append prisoner n]
execute prisoner 3
print ["Prisoner" prisoner "survived"]


/* REXX **************************************************************
* 15.11.2012 Walter Pachl - my own solution
* 16.11.2012 Walter Pachl generalized n prisoners + w killing distance
*                         and s=number of survivors
* 09.05.2013 Walter Pachl accept arguments n w s and fix output
*                         thanks for the review/test
* I see no need for specifying a start count (actually a start number)
* This task states:      n    prisoners are standing on a circle,
*    sequentially numbered from  0  to  n-1.    The 1st prisoner is  0.
* This program should work on EVERY REXX.
* Pls report if this is not the case and let us know what's a problem.
**********************************************************************/
Parse Arg n w s .
If n='?' Then Do
  Say 'Invoke the program with the following arguments:'
  Say 'n number of prisoners            (default 41)'
  Say 'w killing count                  (default  3)'
  Say 's number of prisoners to survive (default  1)'
  Exit
  End
If n='' Then n=41                      /* number of alive prisoners  */
If w='' Then w=3                       /* killing count              */
If s='' Then s=1                       /* nuber of survivors         */
dead.=0                                /* nobody's dead yet          */
nn=n                                   /* wrap around boundary       */
p=-1                                   /* start here                 */
killed=''                              /* output of killings         */
Do until n=s                           /* until one alive prisoner   */
  found=0                              /* start looking              */
  Do Until found=w                     /* until we have the third    */
    p=p+1                              /* next position              */
    If p=nn Then p=0                   /* wrap around                */
    If dead.p=0 Then                   /* a prisoner who is alive    */
      found=found+1                    /* increment found count      */
    End
  dead.p=1
  /*
  Say 'killing' p 'now'
  */
  n=n-1                                /* shoot the one on this pos. */
  killed=killed p                      /* add to output              */
  End                                  /* End of main loop           */
Say 'killed:'killed                    /* output killing sequence    */
s=''
Do i=0 To nn-1                            /* look for the surviving p's */
  If dead.i=0 Then s=s i               /* found one                  */
  End
Say 'Survivor(s):'s                    /* show                       */


fun jacobi(A: Int, N: Int): Int {
    assert(N > 0 && N and 1 == 1)
    var a = A % N
    var n = N
    var result = 1
    while (a != 0) {
        var aMod4 = a and 3
        while (aMod4 == 0) {    // remove factors of four
            a = a shr 2
            aMod4 = a and 3
        }
        if (aMod4 == 2) {       // if even
            a = a shr 1         // remove factor 2 and possibly change sign
            if ((n and 7).let { it == 3 || it == 5 })
                result = -result
            aMod4 = a and 3
        }
        if (aMod4 == 3 && n and 3 == 3)
            result = -result
        a = (n % a).also { n = a }
    }
    return if (n == 1) result else 0
}


TableForm[Table[JacobiSymbol[n, k], {n, 1, 17, 2}, {k, 16}],
 TableHeadings -> {ReplacePart[Range[1, 17, 2], 1 -> "n=1"],
   ReplacePart[Range[16], 1 -> "k=1"]}]


template isOdd(n: int): bool = (n and 1) != 0
template isEven(n: int): bool = (n and 1) == 0

func jacobi(n, k: int): range[-1..1] =
  assert k > 0 and k.isOdd
  var n = n mod k
  var k = k
  result = 1
  while n != 0:
    while n.isEven:
      n = n shr 1
      if (k and 7) in [3, 5]:
        result = -result
    swap n, k
    if (n and 3) == 3 and (k and 3) == 3:
      result = -result
    n = n mod k
  if k != 1: result = 0

when isMainModule:

  import strutils

  stdout.write "n/k|"
  for n in 1..20:
    stdout.write align($n, 3)
  echo '\n' & repeat("—", 64)

  for k in countup(1, 21, 2):
    stdout.write align($k, 2), " |"
    for n in 1..20:
      stdout.write align($jacobi(n, k), 3)
    echo ""


n = 41
k=3
see "n =" + n + " k = " + k + " final survivor = " + josephus(n, k, 0) + nl

func josephus (n, k, m)
lm = m
for a = m+1  to n
     lm = (lm+k) % a
next
josephus = lm
return josephus


n = (ARGV[0] || 41).to_i
k = (ARGV[1] || 3).to_i

prisoners = (0...n).to_a
prisoners.rotate!(k-1).shift  while prisoners.length > 1
puts prisoners.first


const N: usize = 41;
const K: usize = 3;
const M: usize = 3;
const POSITION: usize = 5;

fn main() {
    let mut prisoners: Vec<usize> = Vec::new();
    let mut executed: Vec<usize> = Vec::new();
    for pos in 0..N {
        prisoners.push(pos);
    }

    let mut to_kill: usize = 0;
    let mut len: usize = prisoners.len();

    while len > M {
        to_kill = (to_kill + K - 1) % len;
        executed.push(prisoners.remove(to_kill));
        len -= 1;
    }

    println!("JOSEPHUS n={}, k={}, m={}", N, K, M);
    println!("Executed: {:?}", executed);
    println!("Executed position number {}: {}", POSITION, executed[POSITION - 1]);
    println!("Survivors: {:?}", prisoners);
}