Skip to content

Commit 051e521

Browse files
authored
Add Josephus Problem in Ruby (#4484)
1 parent fb62ccf commit 051e521

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

archive/r/ruby/josephus-problem.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def josephus_problem(array, k, start)
2+
if (array.length == 1)
3+
# if the array is one item left, return the survivor value
4+
puts array[0]
5+
else
6+
# set the index position (start + (k - 1)) and set wrap with %
7+
index = (start + k - 1)
8+
wrap = index % array.length
9+
array.delete_at(wrap)
10+
return josephus_problem(array, k, wrap)
11+
end
12+
end
13+
14+
def error()
15+
puts "Usage: please input the total number of people and number of people to skip."
16+
end
17+
18+
# check for incorrect number of arguments
19+
# .any? loops over the elements of ARGV to check if the argument contains non-digit characters or empty strings
20+
if ARGV.length != 2 || ARGV.any? { |arg| arg.match(/[^0-9]/) || arg.empty? }
21+
error()
22+
else
23+
# convert the arguments to integers
24+
n = ARGV[0].to_i
25+
k = ARGV[1].to_i
26+
27+
# create an array with a length of argument n
28+
array = [*1..n]
29+
30+
# pass our array to the function with k and our start index (0)
31+
josephus_problem(array, k, 0)
32+
end

0 commit comments

Comments
 (0)