How to resolve the algorithm Josephus problem step by step in the R programming language
How to resolve the algorithm Josephus problem step by step in the R programming language
Table of Contents
Problem Statement
Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n − 1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
, removing every
k
{\displaystyle k}
-th prisoner and killing him.
As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed. >
For example, if there are
n
5
{\displaystyle n=5}
prisoners and
k
2
{\displaystyle k=2}
, the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2.
Given any
n , k
0
{\displaystyle n,k>0}
, find out which prisoner will be the final survivor.
In one such incident, there were 41 prisoners and every 3rd prisoner was being killed (
k
3
{\displaystyle k=3}
).
Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale.
Which number was he?
The captors may be especially kind and let
m
{\displaystyle m}
survivors free, and Josephus might just have
m − 1
{\displaystyle m-1}
friends to save.
Provide a way to calculate which prisoner is at any given position on the killing sequence.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Josephus problem step by step in the R programming language
Source code in the r programming language
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
josephusProblem <- function(n, k, m)
{
prisoners <- 0:(n - 1)
exPos <- countToK <- 1
dead <- integer(0)
while(length(prisoners) > m)
{
if(countToK == k)
{
dead <- c(dead, prisoners[exPos])
prisoners <- prisoners[-exPos]
exPos <- exPos - 1
}
exPos <- exPos + 1
countToK <- countToK + 1
if(exPos > length(prisoners)) exPos <- 1
if(countToK > k) countToK <- 1
}
print(paste0("Execution order: ", paste0(dead, collapse = ", "), "."))
paste0("Survivors: ", paste0(prisoners, collapse = ", "), ".")
}
You may also check:How to resolve the algorithm Copy a string step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Abundant odd numbers step by step in the Python programming language
You may also check:How to resolve the algorithm Odd word problem step by step in the BaCon programming language
You may also check:How to resolve the algorithm Grayscale image step by step in the OCaml programming language
You may also check:How to resolve the algorithm ADFGVX cipher step by step in the Go programming language