Josephus problem: Difference between revisions

m
m (syntax highlighting fixup automation)
 
(33 intermediate revisions by 13 users not shown)
Line 462:
{{out}}
<pre>n = 41, k = 3, final survivor: 30</pre>
 
=={{header|ANSI Standard BASIC}}==
Translated from ALGOL 68
<syntaxhighlight lang="ansi standard basic">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
130 FOR a = m+1 TO n
140 LET lm = MOD(lm+k, a)
150 NEXT a
160 LET josephus = lm
170 END FUNCTION
180 LET n = 41
190 LET k=3
200 PRINT "n =";n, "k =";k,"final survivor =";josephus(n, k, 0)
210 END
</syntaxhighlight>
 
=={{header|AppleScript}}==
Line 894 ⟶ 878:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebolarturo">josephus: function [n,k][
p: new 0..n-1
i: 0
Line 922 ⟶ 906:
 
josephus 41 3 =>
Prisoner killing order: [1 3 0 4 2 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</pre>
 
Line 1,041 ⟶ 1,025:
{{out}}
<pre>Survivor is number 30</pre>
 
==={{header|ANSI BASIC}}===
{{trans|ALGOL 68}}
{{works with|Decimal BASIC}}
<syntaxhighlight lang="basic">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
130 FOR a = m+1 TO n
140 LET lm = MOD(lm+k, a)
150 NEXT a
160 LET josephus = lm
170 END FUNCTION
180 LET n = 41
190 LET k=3
200 PRINT "n =";n, "k =";k,"final survivor =";josephus(n, k, 0)
210 END
</syntaxhighlight>
{{out}}
<pre>
n = 41 k = 3 final survivor = 30
</pre>
 
==={{header|Applesoft BASIC}}===
Line 1,054 ⟶ 1,059:
<pre>GIVE N AND K (N,K): 41,3
N = 41, K = 3, SURVIVOR: 30</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">n = 41 #prisoners
k = 3 #order of execution
 
print "n = "; n, "k = "; k, "final survivor = "; Josephus(n, k, 0)
end
 
function Josephus(n, k, m)
lm = m
for i = m + 1 to n
lm = (lm + k) mod i
next
return lm
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic">REM >josephus
PRINT "Survivor is number "; FNjosephus(41, 3, 0)
END
:
DEF FNjosephus(n%, k%, m%)
LOCAL i%
FOR i% = m% + 1 TO n%
m% = (m% + k%) MOD i%
NEXT
= m%</syntaxhighlight>
{{out}}
<pre>Survivor is number 30</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 n = 41
110 k = 3
120 print "n = ";n,"k = ";k,"final survivor = ";josephus(n,k,0)
130 end
140 function josephus(n,k,m)
150 lm = m
160 for i = m+1 to n
170 lm = (lm+k) mod i
180 next
190 josephus = lm
200 end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">'using 1 to n
 
define prisoners = 0, step = 0, killcount = 0, survivor = 0
define fn (josephus) as ( survivor + step ) % killcount
 
do
 
input "Prisoners", prisoners
input "Step", step
 
gosub executioner
 
loop
 
sub executioner
 
let killcount = 1
 
do
 
let killcount = killcount + 1
let survivor = (josephus)
 
loop killcount < prisoners
 
print "survivor = ", survivor
 
return</syntaxhighlight>
{{out| Output}}<pre>prisoners? 41
step? 3
survivor = 30</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">
Function Josephus (n As Integer, k As Integer, m As Integer) As Integer
Dim As Integer lm = m
For i As Integer = m + 1 To n
lm = (lm + k) Mod i
Next i
Josephus = lm
End Function
 
Dim As Integer n = 41 'prisioneros
Dim As Integer k = 3 'orden de ejecución
 
Print "n ="; n, "k ="; k, "superviviente = "; Josephus(n, k, 0)
</syntaxhighlight>
{{out}}
<pre>
n = 41 k = 3 superviviente = 30
</pre>
 
==={{header|FTCBASIC}}===
<syntaxhighlight lang="basic">define prisoners = 0, step = 0, killcount = 0
define survivor = 0, remainder = 0
 
do
 
print "Prisoners: " \
input prisoners
 
print "Step: " \
input step
 
gosub executioner
 
loop
 
sub executioner
 
let killcount = 1
 
do
 
let killcount = killcount + 1
let survivor = survivor + step
let survivor = survivor / killcount
carry survivor
 
loop killcount < prisoners
 
print "survivor = " \
print survivor
 
return</syntaxhighlight>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Dim n As Integer = 41 'prisoners
Dim k As Integer = 3 'order of execution
Print "n = "; n, "k = "; k, "final survivor = "; Josephus(n, k, 0)
End
 
Function Josephus(n As Integer, k As Integer, m As Integer) As Integer
Dim lm As Integer = m
 
For i As Integer = m + 1 To n
lm = (lm + k) Mod i
Next
Return lm
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|MSX Basic}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 LET N = 41
20 LET K = 3
30 LET M = 0
40 GOSUB 100
50 PRINT "n ="; N, "k ="; K, "final survivor ="; LM
60 END
100 REM Josephus
110 REM Return m-th on the reversed kill list; m=0 is final survivor.
120 LET LM = M : REM Local copy of m
130 FOR A = M+1 TO N
140 LET LM = (LM+K) MOD A: REM MOD function
150 NEXT A
160 RETURN</syntaxhighlight>
 
==={{header|IS-BASIC}}===
Line 1,070 ⟶ 1,252:
220 LET JOSEPHUS=M
230 END DEF</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
{{works with|Run BASIC}}
<syntaxhighlight lang="qbasic">10 LET N = 41
20 LET K = 3
30 LET M = 0
40 GOSUB 100
50 PRINT "N ="; N, "K ="; K, "FINAL SURVIVOR ="; S
60 GOTO 150
100 LET S = M
110 FOR A = M+1 TO N
120 LET S = INT(A * ((S+K) / A - INT((S+K) / A)) + 0.5)
130 NEXT A
140 RETURN
150 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|Palo Alto Tiny BASIC}}===
{{trans|ANSI BASIC}}
<syntaxhighlight lang="basic">
10 REM JOSEPHUS PROBLEM
20 LET N=41,K=3,M=0
30 GOSUB 100
40 PRINT #1,"N =",N,", K =",K,", FINAL SURVIVOR =",L
50 STOP
90 REM ** JOSEPHUS
100 LET L=M
110 FOR A=M+1 TO N
120 LET L=L+K-((L+K)/A)*A
130 NEXT A
140 RETURN
</syntaxhighlight>
{{out}}
<pre>
N = 41, K = 3, FINAL SURVIVOR = 30
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">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</syntaxhighlight>
{{out}}
<pre>Josephus problem - input prisoners : 5
- input steps : 2
- input survivors : 1
Executed : 1 3 0 4
Surviving: 2
 
Josephus problem - input prisoners : 41
- input steps : 3
- input survivors : 1
Executed : 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
Surviving: 30
 
Josephus problem - input prisoners : 41
- input steps : 3
- input survivors : 3
Executed : 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
Surviving: 15 30 34
 
Josephus problem - input prisoners : 71
- input steps : 47
- input survivors : 11
Executed : 46 22 70 48 26 5 56 36 17 0 54 38 23 9 66 55 43 33 25 16 11 6 2 69 68 1 4 10 15 24 32 42 53 65 20 40 60 19 47 8 44 13 52 31 12 62 57 50 51 61 7 30 59 34 18 3 21 37 67 63
Surviving: 64 14 27 28 29 35 39 41 45 49 58
 
Josephus problem - input prisoners :</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">FUNCTION josephus (n, k, m)
lm = m
FOR i = m + 1 TO n
lm = (lm + k) MOD i
NEXT i
josephus = lm
END FUNCTION
 
n = 41
k = 3
PRINT "n = "; n, "k = "; k, "final survivor = "; josephus(n, k, 0)
END</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 LET N = 41
20 LET K = 3
30 LET M = 0
40 GOSUB 100
50 PRINT "N = " ; N; " K = "; K; " FINAL SURVIVOR ="; S
60 END
100 LET S = M
110 FOR A = M+1 TO N
120 LET S = INT(A * ((S+K) / A - INT((S+K) / A)) + 0.5)
130 NEXT A
140 RETURN</syntaxhighlight>
 
==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="qbasic"> REM Josephus problem
 
LET N = 41
LET K = 3
LET M = 0
GOSUB 10
PRINT "N = ", N
PRINT "K = ", K
PRINT "FINAL SURVIVOR = ", S
END
REM ** JOSEPHUS
10 LET S = M
LET I = M + 1
20 IF I = N THEN GOTO 30
LET S = S + K - ((S + K) / I) * I
LET I = I + 1
GOTO 20
30 RETURN
</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION josephus(n, k, m)
LET lm = m
FOR i = m+1 TO n
LET lm = REMAINDER(lm+k,i)
NEXT i
LET josephus = lm
END FUNCTION
 
LET n = 41
LET k = 3
PRINT "n = "; n, "k = "; k, "final survivor = "; josephus(n, k, 0)
END</syntaxhighlight>
{{out}}
<pre>Same as QBasic entry.</pre>
 
==={{header|VBScript}}===
<syntaxhighlight lang="vb">
Function josephus(n,k,s)
Set prisoner = CreateObject("System.Collections.ArrayList")
For i = 0 To n - 1
prisoner.Add(i)
Next
index = -1
Do Until prisoner.Count = s
step_count = 0
Do Until step_count = k
If index+1 <= prisoner.Count-1 Then
index = index+1
Else
index = (index+1)-(prisoner.Count)
End If
step_count = step_count+1
Loop
prisoner.RemoveAt(index)
index = index-1
Loop
For j = 0 To prisoner.Count-1
If j < prisoner.Count-1 Then
josephus = josephus & prisoner(j) & ","
Else
josephus = josephus & prisoner(j)
End If
Next
End Function
 
'testing the function
WScript.StdOut.WriteLine josephus(5,2,1)
WScript.StdOut.WriteLine josephus(41,3,1)
WScript.StdOut.WriteLine josephus(41,3,3)
</syntaxhighlight>
 
{{Out}}
<pre>
2
30
15,30,34
</pre>
 
==={{header|Visual Basic .NET}}===
{{trans|D}}
<syntaxhighlight lang="vbnet">Module Module1
 
'Determines the killing order numbering prisoners 1 to n
Sub Josephus(n As Integer, k As Integer, m As Integer)
Dim p = Enumerable.Range(1, n).ToList()
Dim i = 0
 
Console.Write("Prisoner killing order:")
While p.Count > 1
i = (i + k - 1) Mod p.Count
Console.Write(" {0}", p(i))
p.RemoveAt(i)
End While
Console.WriteLine()
 
Console.WriteLine("Survivor: {0}", p(0))
End Sub
 
Sub Main()
Josephus(5, 2, 1)
Console.WriteLine()
Josephus(41, 3, 1)
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>Prisoner killing order: 2 4 1 5
Survivor: 3
 
Prisoner killing order: 3 6 9 12 15 18 21 24 27 30 33 36 39 1 5 10 14 19 23 28 32 37 41 7 13 20 26 34 40 8 17 29 38 11 25 2 22 4 35 16
Survivor: 31</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">n = 41 //prisoners
k = 3 //order of execution
 
print "n = ", n, "\tk = ", k, "\tfinal survivor = ", Josephus(n, k, 0)
end
 
sub Josephus(n, k, m)
local lm
lm = m
for i = m + 1 to n
lm = mod(lm + k, i)
next
return lm
end sub</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|ZX Spectrum Basic}}===
{{trans|ANSI BASIC}}
<syntaxhighlight 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
40 STOP
100 REM Josephus
110 REM Return m-th on the reversed kill list; m=0 is final survivor.
120 LET lm=m: REM Local copy of m
130 FOR a=m+1 TO n
140 LET lm=FN m(lm+k,a)
150 NEXT a
160 RETURN
200 DEF FN m(x,y)=x-INT (x/y)*y: REM MOD function
</syntaxhighlight>
 
=={{header|Batch File}}==
Line 1,110 ⟶ 1,581:
Press any key to continue . . .</pre>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic">REM >josephus
PRINT "Survivor is number "; FNjosephus(41, 3, 0)
END
:
DEF FNjosephus(n%, k%, m%)
LOCAL i%
FOR i% = m% + 1 TO n%
m% = (m% + k%) MOD i%
NEXT
= m%</syntaxhighlight>
{{out}}
<pre>Survivor is number 30</pre>
 
=={{header|Befunge}}==
Line 1,502 ⟶ 1,960:
Survivor: 30</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,Classes,StdCtrls,ExtCtrl}}
Uses standard Delphi TList to hold and delete numbers as it analyzes the data.
 
<syntaxhighlight lang="Delphi">
type TIntArray = array of integer;
 
procedure GetJosephusSequence(N,K: integer; var IA: TIntArray);
{Analyze sequence of deleting every K of N numbers}
{Retrun result in Integer Array}
var LS: TList;
var I,J: integer;
begin
SetLength(IA,N);
LS:=TList.Create;
try
{Store number 0..N-1 in list}
for I:=0 to N-1 do LS.Add(Pointer(I));
J:=0;
for I:=0 to N-1 do
begin
{Advance J by K-1 because iterms are deleted}
{And wrapping around if it J exceed the count }
J:=(J+K-1) mod LS.Count;
{Caption the sequence}
IA[I]:=Integer(LS[J]);
{Delete (kill) one item}
LS.Delete(J);
end;
finally LS.Free; end;
end;
 
procedure ShowJosephusProblem(Memo: TMemo; N,K: integer);
{Analyze and display one Josephus Problem}
var IA: TIntArray;
var I: integer;
var S: string;
const CRLF = #$0D#$0A;
begin
GetJosephusSequence(N,K,IA);
S:='';
for I:=0 to High(IA) do
begin
if I>0 then S:=S+',';
if (I mod 12)=11 then S:=S+CRLF+' ';
S:=S+IntToStr(IA[I]);
end;
Memo.Lines.Add('N='+IntToStr(N)+' K='+IntToStr(K));
Memo.Lines.Add('Sequence: ['+S+']');
Memo.Lines.Add('Survivor: '+IntToStr(IA[High(IA)]));
Memo.Lines.Add('');
end;
 
procedure TestJosephusProblem(Memo: TMemo);
{Test suite of Josephus Problems}
begin
ShowJosephusProblem(Memo,5,2);
ShowJosephusProblem(Memo,41,3);
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
N=5 K=2
Sequence: [1,3,0,4,2]
Survivor: 2
 
N=41 K=3
Sequence: [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,30]
Survivor: 30
</pre>
 
{{trans|Javascript}}
Line 1,525 ⟶ 2,059:
Josephus(41,2,1) -> 30 / 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
Josephus(23482,3342,3) -> 1087 1335 13317 / 3342 6685 10028 13371 16714 20057 23400 3261 6605 9949 13293 16637 19981 23325 3187 6532 9877 13222 16567 19912 23257 3120 6466 9812 13158 16504 19850 23196 3060 6407 9754 13101 16448 19795 23142 3007 6355 9703 13051 16399 19747 23095 2961 6310 9659 ...</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
n = 41
k = 3
print "prisoners: " & n
print "step size: " & k
for i = 1 to n
lm = (lm + k) mod i
.
print "final survivor: " & lm
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Line 1,569 ⟶ 2,115:
 
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
The algorithm is of the "increasing modulus" type. Though written independently of the Ring solution, it seems to be essentially the same. The (n,k) pairs used by the demo program are taken from solutions on this page. Running time totals 1.2 EDSAC minutes for the first eight examples, and 12.5 for the last two.
<syntaxhighlight lang="edsac">
[Jospehus problem - Rosetta Code
EDSAC program (Initial Orders 2)]
 
[Arrange the storage]
T45K P56F [H parameter: library subroutine R4 to read integer]
T46K P80F [N parameter: subroutine to print 17-bit non-neg integer]
T47K P160F [M parameter: main routine]
T51K P128F [G parameter: subroutine to find last survivor]
 
[Library subroutine M3, runs at load time and is then overwritten.
Prints header; here, last character sets teleprinter to figures.]
PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF
*!!!!N!!!!!K!!!!SURVIVOR@&#..PZ
 
[============== G parameter: Subroutine to find last survivor ==============
Input: 4F = n = number of prisoners
5F = k = executioner's step
Output: 0F = 0-based index of last survivor]
 
[Pascal equivalent:
z := 0; // solution when n = 1
for j := 2 to n do z := (z + k) mod j;
result := z;]
E25K TG GK
A3F T22@ [plant return link as usual]
T23@ [z := 0]
A2F T24@ [j := 2]
E16@ [jump to middle of loop]
[6] TF [clear acc]
A23@ A5F [acc := z + k]
[Get residue modulo j by repeatedly subtracting j.
The number of subtractions is usually small.]
[9] S24@ E9@ [subtract j till result < 0]
A24@ [add back the last j]
T23@ [update z]
A24@ A25@ T24@ [inc(j)]
[16] A4F S24@ [acc := n - j]
E6@ [loop back if j <= n]
TF [done: clear acc]
A23@ TF [return z (last survivor) to caller in 0F]
[22] ZF [(planted) jump back to caller]
[Storage]
[23] PF [Pascal z]
[24] PF [Pascal j]
[25] PD [constant 1]
 
[====================== M parameter: Main routine ======================]
E25K TM GK
[0] PF [negative data count]
[1] PF [number of prisoners]
[2] PF [executioner's step]
[3] !F [space]
[4] @F [carriage return]
[5] &F [line feed]
[6] K4096F [null character]
[Enter with acc = 0]
[7] A7@ GH [call subroutine R4, sets 0D := count of (n,k) pairs]
SF [acc := count negated; it's assumed that count < 2^16]
E46@ [exit if count = 0]
LD [shift count into address field]
[12] T@ [update negative loop counter]
A13@ GH [call library subroutine R4, 0D := number of prisoners]
AF T1@ [store number of prisoners, assumed < 2^16]
A17@ GH [call library subroutine R4, 0D := executioner's step]
AF T2@ [store executioner's step, assumed < 2^16]
A3@ T1F [to print leading 0's as spaces]
A1@ TF [pass number of prisoners to print subroutine]
A25@ GN O3@ [print number of prisoners, plus space]
A2@ TF [same for executioner's step]
A30@ GN O3@
A1@ T4F [pass number of prisoners to "last survivor" subroutine]
A2@ T5F [same for executioner's step]
A37@ GG [call subroutine, 0F := 0-based index of last survivor]
A39@ GN O4@ O5@ [print last survivor, plus CR,LF]
A@ A2F [increment negative counter]
G12@ [loop back if still negative]
[46] O6@ [print null to flush printer buffer]
ZF [halt the machine]
 
[The next 3 lines put the entry address into location 50,
so that it can be accessed via the X parameter (see end of program).]
T50K
P7@
T7Z
 
[================== H parameter: Library subroutine R4 ==================
Input of one signed integer, returned in 0D.
22 locations.]
E25K TH GK
GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF
 
[============================= N parameter ==============================
Subroutine to print non-negative 17-bit integer.
Input: 0F = integer to be printed (not preserved)
1F = character for leading zero (preserved)
Workspace: 4F..7F, 38 locations]
E25K TN
GKA3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F
T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF
 
[==========================================================================
On the original EDSAC, the following (without the whitespace and comments)
might have been input on a separate tape.]
E25K TX GK
EZ [define entry point]
PF [acc = 0 on entry]
[Count of (n,k) pairs, then the pairs, to be read by library subroutine R4.
Note that sign comes *after* value.]
10+5+2+12+4+41+3+50+2+60+3+71+47+123+3+123+47+10201+17+23482+3343+
</syntaxhighlight>
{{out}}
<pre>
N K SURVIVOR
5 2 2
12 4 0
41 3 30
50 2 36
60 3 40
71 47 29
123 3 54
123 47 101
10201 17 7449
23482 3343 1335
</pre>
 
=={{header|Eiffel}}==
Line 1,822 ⟶ 2,496:
deallocate(next)
end program</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Function Josephus (n As Integer, k As Integer, m As Integer) As Integer
Dim As Integer lm = m
For i As Integer = m + 1 To n
lm = (lm + k) Mod i
Next i
Josephus = lm
End Function
 
Dim As Integer n = 41 'prisioneros
Dim As Integer k = 3 'orden de ejecución
 
Print "n ="; n, "k ="; k, "superviviente = "; Josephus(n, k, 0)
</syntaxhighlight>
{{out}}
<pre>
n = 41 k = 3 superviviente = 30
</pre>
 
=={{header|friendly interactive shell}}==
Line 1,907 ⟶ 2,561:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Josephus_problem}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution:'''
 
We start with two lists. The first one contains initially the prisoners (their number), and the second one contains the kills, and it is initially empty.
 
On every kill, the number of the killed prisoner is deleted from the first list, and it is (striked out) appended to the second one, in order to show the order of kills.
 
In order to leave more than one survivor, the cycle is repeated n-s times, where n is the number of prisoners and s is the number of survivors.
 
At the end, the two lists are retrieved.
 
Even when Fōrmulæ is 1-based, the list is filled starting with the 0 prisoner, in order to the results can be compared with other languages (mostly 0-based).
 
[[File:Fōrmulæ - Josephus problem 01.png]]
 
'''Case 1.''' 5 prisoners, killing every 2:
 
[[File:Fōrmulæ - Josephus problem 02.png]]
 
[[File:Fōrmulæ - Josephus problem 03.png]]
 
'''Case 2.''' 41 prisoners, killing every 3:
 
[[File:Fōrmulæ - Josephus problem 04.png]]
 
[[File:Fōrmulæ - Josephus problem 05.png]]
 
'''Case 3.''' The captors may be especially kind and let m survivors free, and Josephus might just have m - 1 friends to save.:
 
[[File:Fōrmulæ - Josephus problem 06.png]]
 
[[File:Fōrmulæ - Josephus problem 07.png]]
 
'''Case 4. Larger example.''' 23,482 prisoners, killing every 3,343, leaving 3 survivors. Only the survivors are shown (the first element of the resulting list is extracted):
 
[[File:Fōrmulæ - Josephus problem 08.png]]
 
[[File:Fōrmulæ - Josephus problem 09.png]]
 
'''Drawing history'''
 
The following function creates a raster graphics of size n squares width, and n + 1 squares height, where n is the number of prisoners. The size of the square is defines as pixels.
 
The horizontal axis (right to left) is the number of the prisoner. The vertical axis (top to bottom) is the number of cycle.
 
An alive prisoner is drawn as green, a dead one is drawn as black.
 
[[File:Fōrmulæ - Josephus problem 10.png]]
 
'''Example 1.''' Drawing for the case 41 prisoners, killing every 3 (cell size is 5x5 pixels)::
 
[[File:Fōrmulæ - Josephus problem 11.png]]
 
[[File:Fōrmulæ - Josephus problem 12.png]]
 
'''Example 2.''' Drawing for the case 500 prisoners, killing every 6 (cell size is 1x1 pixel)::
 
[[File:Fōrmulæ - Josephus problem 13.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Josephus problem 14.png]]
In '''[https://formulae.org/?example=Josephus_problem this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Go}}==
Line 2,562 ⟶ 3,272:
end
</syntaxhighlight>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
josephus_list(n,k):=(result:[],pos:1,ref:makelist(i,i,n),while ref#[] do (pos:mod(pos+k-2,length(ref))+1,push(ref[pos],result),ref:delete(ref[pos],ref)),
reverse(result));
/* Example */
/* last_survivor:last(josephus_list(41,3));
31
*/
</syntaxhighlight>
 
 
=={{header|Modula-2}}==
Line 2,844 ⟶ 3,565:
=={{header|Phix}}==
I managed to identify eight algorithms in use on this page, so I translated all of them. Kill ordering lists omitted for sanity.<br>
Unclassified: Haskell, Python[4 aka learning iter in python], REXX[version 2], RPL (plus Befunge, J, and Mathematica, which I'm happy to ignore)<br>
Note all indexes and results are 1-based. For skipping/linked_list/sliding_queue, prisoners do not have to be numbers, the
same would be true for contractacycle and contractalot with the tiniest of tweaks. For recursive/iterative, prisoners are implicitly numbers, not that it would be difficult to use the result(s) to subscript a list of string names.
Line 2,937 ⟶ 3,658:
 
===contractalot===
11L, Arturo, AutoHotkey, C#, C++, Delphi, Frink, Formulae, Java (both), JavaScript[2], Julia[2], Kotlin, Lua, NanoQuery, Nim, Objeck,
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. Often implemented as execute all prisoners then release last one killed.
<!--<syntaxhighlight lang="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>
Line 2,964 ⟶ 3,685:
 
===iterative===
ALGOL 68, ANSI Standard BASIC, AppleScript[1,3(!!)], BASIC(*11), Batch File, C (but not ULL), Common Lisp[1], Craft Basic, Easylang, EDSAC (allegedly), Factor, Forth, FreeBASIC, FTCBASIC, 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.
<!--<syntaxhighlight lang="phix">-->
Line 3,313 ⟶ 4,034:
return prisoners;
}</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">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</syntaxhighlight>
{{out}}
<pre>Josephus problem - input prisoners : 5
- input steps : 2
- input survivors : 1
Executed : 1 3 0 4
Surviving: 2
 
Josephus problem - input prisoners : 41
- input steps : 3
- input survivors : 1
Executed : 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
Surviving: 30
 
Josephus problem - input prisoners : 41
- input steps : 3
- input survivors : 3
Executed : 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
Surviving: 15 30 34
 
Josephus problem - input prisoners : 71
- input steps : 47
- input survivors : 11
Executed : 46 22 70 48 26 5 56 36 17 0 54 38 23 9 66 55 43 33 25 16 11 6 2 69 68 1 4 10 15 24 32 42 53 65 20 40 60 19 47 8 44 13 52 31 12 62 57 50 51 61 7 30 59 34 18 3 21 37 67 63
Surviving: 64 14 27 28 29 35 39 41 45 49 58
 
Josephus problem - input prisoners :</pre>
 
=={{header|Python}}==
Line 3,745 ⟶ 4,404:
<pre>
n =41 k = 3 final survivor = 30
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
===Last survivor===
We use here the recursive approach.
≪ IF OVER 1 - THEN LAST OVER JPHUS SWAP + SWAP MOD ELSE DROP2 0 END
'JPHUS' STO
 
5 2 JPHUS
41 3 JPHUS
{{out}}
<pre>
2: 2
1: 30
</pre>
===m survivors + ordered list of executed prisoners===
Program execution mimics prisoners' execution ;-)
≪ OVER SIZE → list idx len
≪ {}
1 len 1 - FOR j
list
j idx + 1 - len MOD 1 +
GET +
NEXT
≫ ≫
'RnDL' STO
≪ → n k m
≪ {} DUP
1 n FOR j j 1 - + NEXT
m n 1 - START
k 1 - OVER SIZE MOD 1 +
DUP2 GET 4 ROLL SWAP + 3 ROLLD
RnDL
NEXT
≫ ≫
'JPHUL' STO
 
41 3 2 JPHUL
{{out}}
<pre>
2: { 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 }
1: { 15 30 }
</pre>
 
Line 4,017 ⟶ 4,721:
remaining: 30
remaining 4: 3,34,15,30
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function josephus(n,k,s)
Set prisoner = CreateObject("System.Collections.ArrayList")
For i = 0 To n - 1
prisoner.Add(i)
Next
index = -1
Do Until prisoner.Count = s
step_count = 0
Do Until step_count = k
If index+1 <= prisoner.Count-1 Then
index = index+1
Else
index = (index+1)-(prisoner.Count)
End If
step_count = step_count+1
Loop
prisoner.RemoveAt(index)
index = index-1
Loop
For j = 0 To prisoner.Count-1
If j < prisoner.Count-1 Then
josephus = josephus & prisoner(j) & ","
Else
josephus = josephus & prisoner(j)
End If
Next
End Function
 
'testing the function
WScript.StdOut.WriteLine josephus(5,2,1)
WScript.StdOut.WriteLine josephus(41,3,1)
WScript.StdOut.WriteLine josephus(41,3,3)
</syntaxhighlight>
 
{{Out}}
<pre>
2
30
15,30,34
</pre>
 
Line 4,100 ⟶ 4,761:
</pre>
 
=={{header|VisualV Basic .NET(Vlang)}}==
{{trans|D}}
<syntaxhighlight lang="vbnet">Module Module1
 
'Determines the killing order numbering prisoners 1 to n
Sub Josephus(n As Integer, k As Integer, m As Integer)
Dim p = Enumerable.Range(1, n).ToList()
Dim i = 0
 
Console.Write("Prisoner killing order:")
While p.Count > 1
i = (i + k - 1) Mod p.Count
Console.Write(" {0}", p(i))
p.RemoveAt(i)
End While
Console.WriteLine()
 
Console.WriteLine("Survivor: {0}", p(0))
End Sub
 
Sub Main()
Josephus(5, 2, 1)
Console.WriteLine()
Josephus(41, 3, 1)
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>Prisoner killing order: 2 4 1 5
Survivor: 3
 
Prisoner killing order: 3 6 9 12 15 18 21 24 27 30 33 36 39 1 5 10 14 19 23 28 32 37 41 7 13 20 26 34 40 8 17 29 38 11 25 2 22 4 35 16
Survivor: 31</pre>
 
=={{header|Vlang}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">// basic task fntion
fn final_survivor(n int, kk int) int {
// argument validation omitted
Line 4,224 ⟶ 4,851:
40 30
</pre>
 
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="ecmascriptwren">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,338 ⟶ 4,964:
Survivors: [15,30,34]
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|ANSI Standard BASIC}}
<syntaxhighlight 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
40 STOP
100 REM Josephus
110 REM Return m-th on the reversed kill list; m=0 is final survivor.
120 LET lm=m: REM Local copy of m
130 FOR a=m+1 TO n
140 LET lm=FN m(lm+k,a)
150 NEXT a
160 RETURN
200 DEF FN m(x,y)=x-INT (x/y)*y: REM MOD function
</syntaxhighlight>
 
{{omit from|GUISS}}
2,120

edits