Josephus problem: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: typo, added Vlang to the sliding queue list)
m (syntax highlighting fixup automation)
Line 36:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F j(n, k)
V p = Array(0 .< n)
V i = 0
Line 46:
 
print(j(5, 2))
print(j(41, 3))</langsyntaxhighlight>
 
{{out}}
Line 59:
{{trans|REXX}}
The program uses two ASSIST macros (XDECO,XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Josephus problem 10/02/2017
JOSEPH CSECT
USING JOSEPH,R13 base register
Line 140:
DEAD DS 256X n max
YREGS
END JOSEPH</langsyntaxhighlight>
{{out}}
<pre>
Line 151:
=={{header|6502 Assembly}}==
This subroutine expects to be called with the value of <i>n</i> in the accumulator and the value of <i>k</i> in index register <tt>X</tt>. It returns with the index of the survivor in the accumulator, and also leaves an array beginning at address 1000 hex giving the order in which the prisoners died. For example, in the case where <i>n</i> = 5 and <i>k</i> = 2, the values stored in the array are 2, 0, 4, 1, 3. From this we see that prisoner 1 was the first to die, then prisoner 3, and so on. (Note that prisoner 2 in this instance is the survivor.)
<langsyntaxhighlight lang="6502asm">JSEPHS: STA $D0 ; n
STX $D1 ; k
LDA #$FF
Line 184:
JMP FIND
RETURN: TXA ; a <- index of survivor
RTS</langsyntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program josephus64.s */
Line 378:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 392:
=={{header|Ada}}==
The procedure reads up to 4 parameters from the command line: the number N of prisoners, the step size K, the number M of survivors, and an indicator whether the executions shall be printed ("1") or only surviving prisoners (any other input). The defaults are 41, 3, 1, 1. The prison cells are numbered from 0 to N-1.
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line, Ada.Text_IO;
 
procedure Josephus is
Line 434:
end loop;
end loop;
end Josephus;</langsyntaxhighlight>
{{out}}
<pre>$ ./josephus
Line 448:
=={{header|ALGOL 68}}==
Translated from the C
<langsyntaxhighlight lang="algol68">BEGIN
PROC josephus = (INT n, k, m) INT :
CO Return m-th on the reversed kill list; m=0 is final survivor. CO
Line 459:
printf (($"n = ", g(0), ", k = ", g(0), ", final survivor: ", g(0)l$,
n, k, josephus (n, k, 0)))
END</langsyntaxhighlight>
{{out}}
<pre>n = 41, k = 3, final survivor: 30</pre>
Line 465:
=={{header|ANSI Standard BASIC}}==
Translated from ALGOL 68
<langsyntaxhighlight ANSIlang="ansi Standardstandard BASICbasic">100 FUNCTION josephus (n, k, m)
110 ! Return m-th on the reversed kill list; m=0 is final survivor.
120 LET lm = m ! Local copy OF m
Line 477:
200 PRINT "n =";n, "k =";k,"final survivor =";josephus(n, k, 0)
210 END
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
Line 487:
{{trans|BBC BASIC}}
 
<langsyntaxhighlight lang="applescript">on josephus(n, k)
set m to 0
repeat with i from 2 to n
Line 496:
end josephus
 
josephus(41, 3) --> 31</langsyntaxhighlight>
 
Or with an option to specify the number of survivors:
 
<langsyntaxhighlight lang="applescript">on josephus(n, k, s)
script o
property living : {}
Line 531:
 
josephus(41, 3, 1) --> {31}
josephus(41, 3, 6) --> {2, 4, 16, 22, 31, 35}</langsyntaxhighlight>
 
===Composition of pure functions===
 
Composing a solution from generic and reusable (pure) functions, and using the zero-based notation of the problem statement:
<langsyntaxhighlight lang="applescript">-- josephusSurvivor :: Int -> Int -> Int
on josephusSurvivor(n, k)
script go
Line 677:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>Josephus survivor -> 30
Line 685:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly Raspberry PI */
Line 884:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
pi@raspberrypi:~/asm32/rosetta32/ass6 $ josephus 41 3
Line 894:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">josephus: function [n,k][
p: new 0..n-1
i: 0
Line 913:
 
print "josephus 41 3 =>"
josephus 41 3</langsyntaxhighlight>
 
{{out}}
Line 926:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AHKlang="ahk">; Since AutoHotkey is 1-based, we're numbering prisoners 1-41.
nPrisoners := 41
kth := 3
Line 949:
}
Until (nPrisoners = 1)
MsgBox % RegExReplace(list, "\|") ; remove the final separator</langsyntaxhighlight>
{{out}}
<pre>31</pre>
Note that since this is one-based, the answer is correct, though it differs with many other examples.
===Using Objects===
<langsyntaxhighlight AHKlang="ahk">nPrisoners := 41
kth := 3
list := []
Line 973:
}
Until (list.MaxIndex() = 1)
MsgBox % list.1 ; there is only 1 element left</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f JOSEPHUS_PROBLEM.AWK
# converted from PL/I
Line 1,014:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,032:
=={{header|BASIC}}==
Unstructured implementation: see solutions listed under specific BASIC dialects for structured versions.
<langsyntaxhighlight lang="basic">10 N=41
20 K=3
30 M=0
Line 1,038:
50 M=INT(I*((M+K)/I-INT((M+K)/I))+0.5)
60 NEXT I
70 PRINT "Survivor is number";M</langsyntaxhighlight>
{{out}}
<pre>Survivor is number 30</pre>
Line 1,044:
==={{header|Applesoft BASIC}}===
Translated from the BASIC implementation above and the ANSI Standard BASIC.
<syntaxhighlight lang="applesoft basic">
<lang Applesoft BASIC>
10 DEF FN MOD(X) = X - INT (X / A) * A
20 LM = 0: INPUT "GIVE N AND K (N,K): ";N,K
Line 1,050:
40 FOR A = 1 TO N: LM = FN MOD(LM + K): NEXT A
50 PRINT "N = ";N;", K = ";K;", SURVIVOR: ";LM
</syntaxhighlight>
</lang>
{{out}}
<pre>GIVE N AND K (N,K): 41,3
Line 1,056:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Josephus.bas"
110 INPUT PROMPT "Number of prisoners: ":NP
120 INPUT PROMPT "Execution step: ":EX
Line 1,069:
210 NEXT
220 LET JOSEPHUS=M
230 END DEF</langsyntaxhighlight>
 
=={{header|Batch File}}==
Uses C's <code>jos()</code> function.
{{trans|C}}
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 1,104:
)
echo !surv_list!
goto :EOF</langsyntaxhighlight>
{{Out}}
<pre>30
Line 1,111:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">REM >josephus
PRINT "Survivor is number "; FNjosephus(41, 3, 0)
END
Line 1,120:
m% = (m% + k%) MOD i%
NEXT
= m%</langsyntaxhighlight>
{{out}}
<pre>Survivor is number 30</pre>
Line 1,127:
The number of prisoners and step size are read from stdin.
 
<langsyntaxhighlight lang="befunge">>0" :srenosirP">:#,_&>>00p>>v
v0p01<&_,#!>#:<"Step size: "<
>1+:20p00g`!#v_0" :rovivru"v
^g02%g02+g01<<@.$_,#!>#:<"S"<</langsyntaxhighlight>
 
{{out}}
Line 1,138:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
// m-th on the reversed kill list; m = 0 is final survivor
Line 1,183:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,191:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
namespace Josephus
{
Line 1,272:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 1,353:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,391:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn rotate [n s] (lazy-cat (drop n s) (take n s)))
 
(defn josephus [n k]
Line 1,403:
", an executioner moving around the"))
(println (str "circle " k " at a time will leave prisoner number "
(inc (josephus n k)) " as the last survivor.")))</langsyntaxhighlight>
 
{{Output}}
Line 1,411:
=={{header|Common Lisp}}==
Using a loop:
<langsyntaxhighlight lang="lisp">(defun kill (n k &aux (m 0))
(loop for a from (1+ m) upto n do
(setf m (mod (+ m k) a)))
m)</langsyntaxhighlight>
Using a circular list.
<langsyntaxhighlight lang="lisp">(defun make-circular-list (n)
(let* ((list (loop for i below n
collect i))
Line 1,437:
(move-forward)
(kill-item))
(first list))))</langsyntaxhighlight>
{{out|Example}}
CL-USER > (kill 41 3)
Line 1,444:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">n = ARGV.fetch(0, 41).to_i # n default is 41 or ARGV[0]
k = ARGV.fetch(1, 3).to_i # k default is 3 or ARGV[1]
 
Line 1,450:
while prisoners.size > 1; prisoners.rotate!(k-1).shift end
puts "From #{n} prisoners, eliminating each prisoner #{k} leaves prisoner #{prisoners.first}."
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,465:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.string, std.range;
 
T pop(T)(ref T[] items, in size_t i) pure /*nothrow*/ @safe /*@nogc*/ {
Line 1,491:
writeln;
josephus(41, 3).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>Prisoner killing order:
Line 1,504:
 
{{trans|Javascript}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
int[][] Josephus(in int n, int k, int s=1) {
Line 1,520:
Josephus(41, 3);
Josephus(23482, 3343, 3);
}}</langsyntaxhighlight>
{{out}}
<pre>Josephus(5,1,1) -> 2 / 1 3 0 4
Line 1,528:
=={{header|EchoLisp}}==
We use a circular list and apply the 'process'. Successive rests are marked 🔫 (killed) or 😥 (remaining). NB: the '''(mark)''' function marks lists and sub-lists, not items in lists. The printed mark appears before the first item in the list.
<langsyntaxhighlight lang="lisp">
;; input
(define N 41)
Line 1,542:
(else (mark lst '😥 ) ;; relieved face
(kill (cdr lst ) (1- skip))))) ;; skip 1 and goto next
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
;; kill N-1
(for ((i (1- N) )) (set! last-one (kill last-one (1- K))))
Line 1,568:
🔫 33 😥 34 🔫 35 🔫 36 🔫 37 🔫 38 🔫 39 🔫 40 🔫 0 🔫 1 🔫 0 … ∞)
 
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,624:
 
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,644:
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule Josephus do
def find(n,k) do
Line 1,660:
 
Josephus.find(41,3)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,666:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(defun jo (n k)
(if (= 1 n)
1
Line 1,674:
 
(message "%d" (jo 50 2))
(message "%d" (jo 60 3))</langsyntaxhighlight>
 
{{out}}
Line 1,682:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( josephus_problem ).
 
Line 1,709:
kill_few( Kill, Prisoners ) ->
lists:split( Kill - 1, Prisoners ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,725:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM JOSEPHUS
 
Line 1,779:
MAIN(41,3,3->ERRORS)
END PROGRAM
</syntaxhighlight>
</lang>
Note: Adapted from AWK version! Output is the same.
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel locals math math.ranges sequences ;
IN: josephus
 
:: josephus ( k n -- m )
n [1,b] 0 [ [ k + ] dip mod ] reduce ;</langsyntaxhighlight>
<pre>IN: scratchpad 3 41 josephus .
30
Line 1,793:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: josephus 0 1 begin dup 41 <= while swap 3 + over mod swap 1+ repeat drop ;</langsyntaxhighlight>
<pre>josephus .
30
Line 1,800:
=={{header|Fortran}}==
Naive approach: prisonners are put in a "linked buffer" (implemented as an array giving number of "next living prisonner"). Then we iterate, killing one after each loop, until there is only one left.
<langsyntaxhighlight lang="fortran">program josephus
implicit none
integer :: n, i, k, p
Line 1,821:
print *, "Alive", p
deallocate(next)
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Function Josephus (n As Integer, k As Integer, m As Integer) As Integer
Dim As Integer lm = m
Line 1,837:
 
Print "n ="; n, "k ="; k, "superviviente = "; Josephus(n, k, 0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,844:
 
=={{header|friendly interactive shell}}==
<langsyntaxhighlight lang="fishshell">function execute
# If the list is empty, don't do anything.
test (count $argv) -ge 2; or return
Line 1,862:
end
 
echo Prisoner (execute 3 (seq 0 40))[-1] survived.</langsyntaxhighlight>
{{out}}
<pre>Prisoner 30 survived.</pre>
It's also possible to calculate more than one survivor.
<langsyntaxhighlight lang="fishshell">echo Prisoners (execute 3 (seq 0 40))[-3..-1] survived.</langsyntaxhighlight>
{{out}}
<pre>Prisoners 34 15 30 survived.</pre>
Prisoners don't have to be numbers.
<langsyntaxhighlight lang="fishshell">echo Prisoner (execute 2 Joe Jack William Averell Rantanplan)[-1] survived.</langsyntaxhighlight>
{{out}}
<pre>Prisoner William survived.</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
killingCycle[prisonerCount,killStep = 2] :=
{
Line 1,897:
 
println[killingCycle[41,3]] // Enter in total number of prisoners and the number to skip each cycle
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,914:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,962:
fmt.Printf("%5d%10d\n", i, position(41, 3, i))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,011:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">int[] Josephus (int size, int kill, int survivors) {
// init user pool
def users = new int[size];
Line 2,047:
 
println "4 safe spots for n = 10201 and k = 17: " + Josephus(10201,17,4);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,058:
The arguments to the "main" function are: n = number of prisoners, k = kill every kth prisoner,
m = show at most m survivors
<langsyntaxhighlight Haskelllang="haskell">import Data.List ((\\))
import System.Environment (getArgs)
 
Line 2,098:
(counter (read k)) (read m)
_ -> print $ snd $ killRecursive (prisoners 41) (counter 3) 1
</syntaxhighlight>
</lang>
 
Using modulo and list split, indices are 1-based. This is much faster than cycled list for larger numbers:
<langsyntaxhighlight Haskelllang="haskell">jseq :: Int -> Int -> [Int]
jseq n k = f n [1 .. n]
where
Line 2,116:
main = do
print $ jseq 41 3
print $ jos 10000 100</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 2,122:
The following works in both languages.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
m := integer(A[1]) | 41
c := integer(A[2]) | 3
Line 2,130:
procedure j(m,c)
return if m==1 then 0 else (j(m-1,c)+c)%m
end</langsyntaxhighlight>
 
{{out}}
Line 2,143:
This is done awkwardly, but I've had this laying around since the late 1980's...
 
<langsyntaxhighlight lang="unicon">procedure main(args)
n := total := integer(args[1]) | 41 # Number of people
k := count := integer(args[2]) | 3 # Count
Line 2,169:
n ?:= integer(tab(upto('.'))) + 1
return n
end</langsyntaxhighlight>
 
Sample run:
Line 2,187:
=== Tacit version ===
 
<langsyntaxhighlight Jlang="j"> 3 ([ (1 }. <:@[ |. ])^:(1 < #@])^:_ i.@]) 41
30</langsyntaxhighlight>
Structured derivation of the fixed tacit code
<langsyntaxhighlight Jlang="j"> DropNext=. 1 }. <:@[ |. ]
MoreThanOne=. 1 < #@]
WhileMoreThanOne=. (^:MoreThanOne f.) (^:_)
Line 2,196:
[ DropNext WhileMoreThanOne prisoners f.
[ (1 }. <:@[ |. ])^:(1 < #@])^:_ i.@]</langsyntaxhighlight>
 
=== Explicit version ===
<langsyntaxhighlight Jlang="j">Josephus =: dyad define NB. explicit form, assume executioner starts at position 0
NB. use: SKIP josephus NUMBER_OF_PRISONERS
N =: y
Line 2,214:
3 Josephus 41
30</langsyntaxhighlight>
 
 
=== Explicit version 2 ===
<langsyntaxhighlight Jlang="j"> NB. this is a direct translation of the algo from C code above.
Josephus2 =: 4 : '(| x&+)/i. - 1+y'
 
3 Josephus2 41
30</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
 
public class Josephus {
Line 2,265:
System.out.println("Survivors: " + executeAllButM(41, 3, 3));
}
}</langsyntaxhighlight>
{{out}}
<pre>Prisoners executed in order:
Line 2,275:
 
{{trans|Javascript}}
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
import java.util.List;
 
Line 2,311:
return s.substring(1, s.length()-1) + dot;
}
}</langsyntaxhighlight>
{{out}}
<pre>Josephus(5,1,1) -> 2 / 1, 3, 0, 4
Line 2,320:
=={{header|JavaScript}}==
Labels are 1-based, executioner's solution:
<langsyntaxhighlight lang="javascript">var Josephus = {
init: function(n) {
this.head = {};
Line 2,346:
return current.label;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,354:
 
With Array methods:
<langsyntaxhighlight lang="javascript">function Josephus(n, k, s) {
s = s | 1
for (var ps=[], i=n; i--; ) ps[i]=i
Line 2,360:
document.write((arguments.callee+'').split(/\s|\(/)[1], '(', [].slice.call(arguments, 0), ') -> ', ps, ' / ', ks.length<45?ks:ks.slice(0,45)+',...' , '<br>')
return [ps, ks]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,374:
 
The prisoners are numbered from 0 to (n-1) in keeping with jq's array index origin of 0, but the nature of their labeling is immaterial to the algorithm.
<langsyntaxhighlight lang="jq"># A control structure, for convenience:
# as soon as "condition" is true, then emit . and stop:
def do_until(condition; next):
Line 2,385:
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] );</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">def task(n;k;m):
"Survivors for n=\(n), k=\(k), m=\(m): \( josephus(n;k;m) )";
 
task(41;3;1),
task(23482; 3343; 3)</langsyntaxhighlight>
{{out}}
$ jq -M -r -n -f josephus.jq
Line 2,401:
 
'''Recursive (with Memoize)''':
<langsyntaxhighlight lang="julia">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)</langsyntaxhighlight>
 
{{out}}
Line 2,412:
 
'''Iterative''':
<langsyntaxhighlight lang="julia">function josephus(n::Integer, k::Integer, m::Integer=1)
p, i, seq = collect(0:n-1), 0, Vector{typeof(n)}(0)
while length(p) > m
Line 2,425:
 
seq, surv = josephus(41, 3, 3)
println("Prisoner killing in order: $seq\nSurvivor: $surv")</langsyntaxhighlight>
 
{{out}}
Line 2,434:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun josephus(n: Int, k: Int, m: Int): Pair<List<Int>, List<Int>> {
Line 2,466:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,485:
=={{header|Lua}}==
Lua indexes tables starting at 1. Positions are stored from 0,n-1.
<langsyntaxhighlight lang="lua">function josephus(n, k, m)
local positions={}
for i=1,n do
Line 2,509:
end
josephus(41,3, 1)
</syntaxhighlight>
</lang>
{{out}}
<pre>Execution order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15.
Line 2,516:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">survivor[n_, k_] := Nest[Most[RotateLeft[#, k]] &, Range[0, n - 1], n - 1]
survivor[41, 3]</langsyntaxhighlight>
{{out}}
<pre>{30}</pre>
Line 2,523:
=={{header|MATLAB}}==
 
<langsyntaxhighlight MATLABlang="matlab">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]
Line 2,561:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Josephus;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,589:
 
ReadChar
END Josephus.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def j(n, k)
p = list(range(0, n-1))
i = 0
Line 2,608:
println j(5,2)
println
println j(41,3)</langsyntaxhighlight>
 
{{out}}
Line 2,620:
{{trans|REXX}}
Hardly any changes at all...
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,652:
Loop i = 0 To 40 /* look for the surviving p's */
If dead[i] = 0 Then Say i /* found one */
End</langsyntaxhighlight>
{{out}}
<pre>
Line 2,667:
{{trans|Python}}
 
<langsyntaxhighlight lang="nim">import sequtils, strutils, sugar
 
proc j(n, k: int): string =
Line 2,686:
 
echo j(5,2)
echo j(41,3)</langsyntaxhighlight>
{{out}}
<pre>Prisoner killing order: 1, 3, 0, 4, 2.
Line 2,696:
 
Another more efficient way but without the killing order:
<langsyntaxhighlight Nimlang="nim">func prisonerPos(n, k: Positive): int =
## The result is computed backwards. We start from the winner at
## position 0 on last round and compute its position on previous rounds.
Line 2,705:
 
echo "Survivor: ", prisonerPos(5, 2)
echo "Survivor: ", prisonerPos(41, 3)</langsyntaxhighlight>
 
{{out}}
Line 2,712:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Josephus {
function : Execute(n : Int, k : Int) ~ Int {
killIdx := 0;
Line 2,762:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Oforth}}==
Line 2,768:
Oforth lists are 1-based : prisoners are numbered from 1 to n.
 
<langsyntaxhighlight Oforthlang="oforth">: josephus(n, k)
| prisoners killed i |
n seq asListBuffer ->prisoners
Line 2,780:
System.Out "Killed : " << killed << "\nSurvivor : " << prisoners << cr
;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,799:
It was modified to report indexes from 0 and also report the killed list:
 
<langsyntaxhighlight lang="oz">declare
fun {Pipe Xs L H F}
if L=<H then {Pipe {F Xs L} L+1 H F} else Xs end
Line 2,821:
result(survivor: Last-1 killed: {Reverse @Killed})
end
{Show {Josephus 41 3}}</langsyntaxhighlight>
 
{{Out}}
Line 2,827:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">Josephus(n, k)=if(n<2, n>0, my(t=(Josephus(n-1, k)+k)%n); if(t, t, n))</langsyntaxhighlight>
 
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight Perllang="perl">my @prisoner = 0 .. 40;
my $k = 3;
until (@prisoner == 1) {
Line 2,838:
}
 
print "Prisoner @prisoner survived.\n"</langsyntaxhighlight>
{{Out}}
<pre>Prisoner 30 survived.</pre>
Line 2,851:
Method: all prisoners stay where they are, executioner walks round and round, skipping over ever increasing numbers of dead bodies
(slowest of the lot, by quite some margin)
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">skipping</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">prisoners</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">survivors</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prisoners</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">nn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 2,866:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--?skipping({"Joe","Jack","William","John","James"},2,1) --&gt; {"William"}</span>
<!--</langsyntaxhighlight>-->
 
===linked list===
AArch64 Assembly, Ada, ARM Assembly, Common Lisp[2, probably], Fortran, JavaScript[1] (albeit dbl-lnk), Python[3].<br>
Method: like skipping, all prisoners stay where they are, but the executioner uses the links to speed things up a bit.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">linked_list</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">prisoners</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">survivors</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prisoners</span><span style="color: #0000FF;">)</span>
Line 2,887:
<span style="color: #008080;">return</span> <span style="color: #7060A8;">remove_all</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prisoners</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
===sliding queue===
Clojure, Crystal, D (both), Eiffel, Elixir, Erlang, friendly interactive shell, Go, jq, Perl, PowerShell, PureBasic (albeit one at a time), Quackery, Raku, REBOL, Ruby, Scala, Sidef[1], Tcl, Vlang.
Method: all skipped prisoners rejoin the end of the queue which sidles left, executioner stays put until the queue gets too short.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">sliding_queue</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">prisoners</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">survivors</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prisoners</span><span style="color: #0000FF;">)</span>
Line 2,902:
<span style="color: #008080;">return</span> <span style="color: #000000;">prisoners</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
===contractacycle===
Line 2,908:
Method: executioner walks along killing every k'th prisoner; while he walks back the queue contracts to remove gaps.
(once the queue gets too small it obviously reverts to one at a time, a bit more like contractalot below)
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">contractacycle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">living</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 2,932:
<span style="color: #008080;">return</span> <span style="color: #000000;">living</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
Groovy does not have a n=s test, it probably is entirely unnecessary. The Groovy code is also somewhat neater, always using
a loop and remove_all() - while not probihitively expensive, it may check lots of things for -1 that the slicing won't.
Line 2,940:
Oforth, Processing, Python[1], R[2], Rust, Seed7, Swift, VBScript, Vedit, VisualBasic.NET, XPL0, zkl. <br>
Method: executioner walks round and round, queue contracts after every kill.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">contractalot</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 2,952:
<span style="color: #008080;">return</span> <span style="color: #000000;">list</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
===recursive===
Emacs Lisp, Icon, Julia[1], PARI/GP, PicoLisp (less the optms.n), Sidef[2]<br>
Method: recursive mod maths madness - only handles the lone survivor case.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">recursive</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">recursive</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
===iterative===
ALGOL 68, ANSI Standard BASIC, AppleScript[1,3(!!)], BASIC, Batch File, C (but not ULL), Common Lisp[1], Factor, Forth, FreeBASIC, Modula-2, Python[2], R, Racket, Ring, SequenceL, ZX Spectrum Basic<br>
Method: iterative mod maths madness - but hey, it will be extremely fast. Unlike recursive, it can also deliver >1 survivor, one at a time.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">iterative</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Return m-th on the reversed kill list; m=0 is final survivor.</span>
Line 2,974:
<span style="color: #008080;">return</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- (make result 1-based)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
===iterative2===
Icon[2]<br>
Method: more iterative maths madness
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">iterative2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
Line 2,991:
<span style="color: #008080;">return</span> <span style="color: #000000;">nk</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">olda</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- (make result 1-based)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
===test driver===
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--demo/rosetta/Josephus.exw</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">show_all</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span><span style="color: #0000FF;">,</span>
Line 3,062:
<span style="color: #008080;">if</span> <span style="color: #000000;">show_all</span> <span style="color: #008080;">or</span> <span style="color: #000000;">show_iterative</span> <span style="color: #008080;">then</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"iterative"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ITER</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">show_all</span> <span style="color: #008080;">or</span> <span style="color: #000000;">show_iterative2</span> <span style="color: #008080;">then</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"iterative2"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ITER2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
{{out}}
As shown for sliding_queue, some of the result sets are in a slightly different order, sometimes, otherwise matching output replaced by "...".
Line 3,095:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?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
Line 3,115:
}
echo '<pre>'.print_r(Jotapata(41,3,5),true).'<pre>';
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
The counting starts from one instead of zero. The last remaining person is returned.
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
#general solution
(de jo (N K)
Line 3,143:
(print (survivor 5 2))
(print (survivor 41 3))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,151:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process or(!) source attributes xref;
joseph: Proc Options(main);
/* REXX **************************************************************
Line 3,213:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>killed: 02 05 08 11 14 17 20 23 26 29 32 35 38 00 04 09 13 18 22 27 31
Line 3,232:
Normally when we present the PowerShell parser with an array within an array, it treats it as a cast, and
we end up with the single array of elements. In those cases where we need an array to be treated as a single element of a parent array, we can use the unary comma to force PowerShell to treat it as an element.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-JosephusPrisoners ( [int]$N, [int]$K )
{
Line 3,253:
return $Prisoners
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
# Get the prisoner order for a circle of 41 prisoners, selecting every third
$Prisoners = Get-JosephusPrisoners -N 41 -K 3
Line 3,267:
$S = 3
"Last $S remaining: " + $Prisoners[-$S..-1]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,277:
=={{header|Processing}}==
Translation of Java example.
<langsyntaxhighlight lang="processing">void setup() {
println("Survivor: " + execute(41, 3));
println("Survivors: " + executeAllButM(41, 3, 3));
Line 3,312:
println();
return prisoners;
}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">NewList prisoners.i()
 
Procedure f2l(List p.i())
Line 3,348:
Next
ForEver
End</langsyntaxhighlight>
{{out}}
<pre>Josephus problem - input prisoners : 5
Line 3,377:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> def j(n, k):
p, i, seq = list(range(n)), 0, []
while p:
Line 3,390:
Prisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15.
Survivor: 30
>>> </langsyntaxhighlight>
 
===Faster way===
Does not show the killing order.
<langsyntaxhighlight lang="python">>>>def josephus(n, k):
r = 0
for i in xrange(1, n+1):
Line 3,404:
>>> print(josephus(41, 3))
Survivor: 30
>>> </langsyntaxhighlight>
 
===Alternate solution with a circular linked list===
Line 3,411:
In the program, a[p] is the index of the next living prisoner after 'p'. The program stops when p = a[p], that is, when there remains only one living prisoner.
 
<langsyntaxhighlight lang="python">def josephus(n, k):
a = list(range(1, n + 1))
a[n - 1] = 0
Line 3,429:
 
josephus(41, 3)[-1]
30</langsyntaxhighlight>
 
===learning iter in python===
<langsyntaxhighlight lang="python">from itertools import compress, cycle
def josephus(prisoner, kill, surviver):
p = range(prisoner)
Line 3,465:
The surviver is: [2]
The kill sequence is [1, 3, 0, 4]
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Not the fastest method, but illustrates use of ancillary stacks, and using nests as queues.
 
<langsyntaxhighlight Quackerylang="quackery">[ stack ] is survivors ( --> s )
 
[ stack ] is prisoners ( --> s )
Line 3,505:
survivors release
executioner-actions release
prisoners take ] is josephus ( n n n --> n )</langsyntaxhighlight>
 
'''Testing in Quackery shell:'''
Line 3,517:
=={{header|R}}==
===Growing circle solution===
<langsyntaxhighlight lang="rsplus">jose <-function(s, r,n){
y <- 0:(r-1)
for (i in (r+1):n)
Line 3,524:
}
> jose(3,1,41) # r is the number of remained prisoner.
[1] 30</langsyntaxhighlight>
===Iterative solution===
I hope to be proven wrong, but R seems to be the wrong tool for this problem:
Line 3,531:
*The idiomatic way to roll an array in R (e.g. as [[Josephus_problem#Ruby|the Ruby solution]] has) is to exploit the head and tail functions, but those break if we are rolling by more than the length of the array (see https://stackoverflow.com/q/18791212 for a few tricks for this).
Regardless, it is still solvable. The following adapts a great deal of [[Josephus_problem#Lua|the Lua solution]]. The arguments n, k, and m are as in the task description.
<langsyntaxhighlight lang="rsplus">josephusProblem <- function(n, k, m)
{
prisoners <- 0:(n - 1)
Line 3,551:
print(paste0("Execution order: ", paste0(dead, collapse = ", "), "."))
paste0("Survivors: ", paste0(prisoners, collapse = ", "), ".")
}</langsyntaxhighlight>
{{out}}
<pre>> josephusProblem(5, 2, 1)
Line 3,564:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (josephus n k (m 0))
(for/fold ((m (add1 m)))
Line 3,570:
(remainder (+ m k) a)))
 
(josephus 41 3) ; ->30</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 3,576:
{{Works with|rakudo|2015-11-12}}
Straightforward implementation of the executioner's algorithm:
<syntaxhighlight lang="raku" perl6line>sub Execute(@prisoner, $k) {
until @prisoner == 1 {
@prisoner.=rotate($k - 1);
Line 3,591:
my @dalton = <Joe Jack William Averell Rantanplan>;
Execute @dalton, 2;
say "{@dalton} survived.";</langsyntaxhighlight>
 
{{out}}
Line 3,599:
=={{header|REBOL}}==
Works in Rebol 2 or 3
<langsyntaxhighlight REBOLlang="rebol">Rebol []
 
execute: func [death-list [block!] kill [integer!]] [
Line 3,611:
prisoner: [] for n 0 40 1 [append prisoner n]
execute prisoner 3
print ["Prisoner" prisoner "survived"]</langsyntaxhighlight>
{{out}}
<pre>Prisoner 30 survived</pre>
And any kind of list will do:
<langsyntaxhighlight REBOLlang="rebol">for-the-chop: [Joe Jack William Averell Rantanplan]
execute for-the-chop 2
print [for-the-chop "survived"]</langsyntaxhighlight>
{{out}}
<pre>William survived</pre>
Line 3,623:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX **************************************************************
* 15.11.2012 Walter Pachl - my own solution
* 16.11.2012 Walter Pachl generalized n prisoners + w killing distance
Line 3,670:
If dead.i=0 Then s=s i /* found one */
End
Say 'Survivor(s):'s /* show */</langsyntaxhighlight>
 
{{out}}
Line 3,687:
 
This solution is an &nbsp; ''executor's'' &nbsp; solution.
<langsyntaxhighlight lang="rexx">/*REXX program solves Josephus problem: N men standing in a circle, every Kth kilt.*/
parse arg N K Z R . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 41 /* men not specified? Use default.*/
Line 3,710:
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1) /*plurals*/
th: y= arg(1); return y || word('th st nd rd', 1+ y // 10 * (y//100%10\==1) * (y//10<4))</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,729:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 41
k=3
Line 3,741:
josephus = lm
return josephus
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,748:
 
=={{header|Ruby}}==
<langsyntaxhighlight Rubylang="ruby">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</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const N: usize = 41;
const K: usize = 3;
const M: usize = 3;
Line 3,781:
println!("Executed position number {}: {}", POSITION, executed[POSITION - 1]);
println!("Survivors: {:?}", prisoners);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,794:
(Prisoners labeled 0 to n-1)
<langsyntaxhighlight lang="scala">def executed( prisonerCount:Int, step:Int ) = {
 
val prisoners = ((0 until prisonerCount) map (_.toString)).toList
Line 3,820:
print( dead.mkString(" ") )
println( "\n\nJosephus is prisoner " + alive(0) )</langsyntaxhighlight>
{{out}}
<pre>Prisoners executed in order:
Line 3,834:
uses ''str'' to define everything necessary to write an array of integers.
This way the main program can write the survivor array.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array integer: executeAllButM (in integer: n, in integer: k, in integer: m) is func
Line 3,875:
writeln("Survivor: " <& executeAllButM(41, 3, 1));
writeln("Survivors: " <& executeAllButM(41, 3, 3));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,889:
=={{header|SequenceL}}==
{{trans|Python}}
<langsyntaxhighlight lang="sequencel">main := josephus(41, 3);
josephus(n, k) := josephusHelper(n, k, 1, 0);
Line 3,896:
r when i > n
else
josephusHelper(n, k, i + 1, (r + k) mod i);</langsyntaxhighlight>
 
{{out}}
Line 3,905:
=={{header|Sidef}}==
Iterative:
<langsyntaxhighlight lang="ruby">func josephus(n, k) {
var prisoners = @^n
while (prisoners.len > 1) {
Line 3,911:
}
return prisoners[0]
}</langsyntaxhighlight>
 
Recursive:
<langsyntaxhighlight lang="ruby">func josephus(n, k) {
n == 1 ? 0 : ((__FUNC__(n-1, k) + k) % n)
};</langsyntaxhighlight>
 
Calling the function:
<langsyntaxhighlight lang="ruby">var survivor = josephus(41, 3);
say "Prisoner #{survivor} survived.";</langsyntaxhighlight>
{{out}}
<pre>Prisoner 30 survived.</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">class Josephus {
class func lineUp(#numberOfPeople:Int) -> [Int] {
Line 3,969:
println("Josephus is number: \(Josephus.execute(numberOfPeople: 41, spacing: 3))")
println()
println("Survivors: \(Josephus.execucteAllButM(numberOfPeople: 41, spacing: 3, save: 3))")</langsyntaxhighlight>
{{out}}
<pre>
Line 3,982:
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="typescript">function josephus(n: number, k: number): number {
if (!n) {
return 1;
Line 3,988:
 
return ((josephus(n - 1, k) + k - 1) % n) + 1;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,996:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc josephus {number step {survivors 1}} {
for {set i 0} {$i<$number} {incr i} {lappend l $i}
for {set i 1} {[llength $l]} {incr i} {
Line 4,009:
}
return [lrange $killseq end-[expr {$survivors-1}] end]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts "remaining: [josephus 41 3]"
puts "remaining 4: [join [josephus 41 3 4] ,]"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,020:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function josephus(n,k,s)
Set prisoner = CreateObject("System.Collections.ArrayList")
Line 4,053:
WScript.StdOut.WriteLine josephus(41,3,1)
WScript.StdOut.WriteLine josephus(41,3,3)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,067:
When the macro finishes, you can see the list of survivors in the edit buffer.
 
<langsyntaxhighlight lang="vedit">#1 = 41 // number of prisoners
#2 = 3 // step size
#3 = 1 // number of survivors
Line 4,086:
}
if (At_EOF) { BOF }
}</langsyntaxhighlight>
 
{{out}}
Line 4,102:
=={{header|Visual Basic .NET}}==
{{trans|D}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
'Determines the killing order numbering prisoners 1 to n
Line 4,126:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Prisoner killing order: 2 4 1 5
Line 4,136:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang="vlang">// basic task fntion
fn final_survivor(n int, kk int) int {
// argument validation omitted
Line 4,176:
}
}
</langsyntaxhighlight>
 
{{out}}
Line 4,228:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">var josephus = Fn.new { |n, k, m|
if (k <= 0 || m <= 0 || n <= k || n <= m) Fiber.abort("One or more parameters are invalid.")
var killed = []
Line 4,259:
System.print("Kill order : %(sk[1])")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 4,277:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
func Prisoner(N, K); \Return final surviving prisoner
Line 4,297:
[IntOut(0, Prisoner(5, 2)); CrLf(0);
IntOut(0, Prisoner(41, 3)); CrLf(0);
]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,306:
=={{header|zkl}}==
{{trans|Julia}}
<langsyntaxhighlight lang="zkl">fcn j(n,k){
reg p=[0..n-1].walk().copy(), i=0, seq=L();
while(p){
Line 4,314:
"Prisoner killing order: %s.\nSurvivor: %d"
.fmt(seq[0,-1].concat(","),seq[-1]);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,322:
Survivor: 30
</pre>
<langsyntaxhighlight lang="zkl">fcn j2(n,k,m){
reg p=[0..n-1].walk().copy(), i=0, seq=L();
while(p.len()>m){
Line 4,330:
"Prisoner killing order: %s.\nSurvivors: [%s]"
.fmt(seq.concat(","),p.concat(","))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,341:
=={{header|ZX Spectrum Basic}}==
{{trans|ANSI Standard BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET n=41: LET k=3: LET m=0
20 GO SUB 100
30 PRINT "n= ";n;TAB (7);"k= ";k;TAB (13);"final survivor= ";lm
Line 4,353:
160 RETURN
200 DEF FN m(x,y)=x-INT (x/y)*y: REM MOD function
</syntaxhighlight>
</lang>
 
{{omit from|GUISS}}
10,333

edits