Skip to content

Commit 257b468

Browse files
authored
Add Josephus Problem in Tcl (#5063)
1 parent f1f3f4c commit 257b468

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

archive/t/tcl/josephus-problem.tcl

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
proc usage {} {
2+
puts stderr {Usage: please input the total number of people and number of people to skip.}
3+
exit 1
4+
}
5+
6+
proc parseInt {s} {
7+
set s [string trim $s]
8+
if {[string is integer -strict $s]} { return $s }
9+
usage
10+
}
11+
12+
proc josephus {total skip} {
13+
if {$skip < 1 || $total < 1} { usage }
14+
15+
# If skip = 1, survivor is the last person
16+
if {$skip == 1} { return $total }
17+
18+
# Optimized case for skip = 2
19+
if {$skip == 2} {
20+
set power 1
21+
while {($power << 1) <= $total} {
22+
set power [expr {$power << 1}]
23+
}
24+
return [expr {2 * ($total - $power) + 1}]
25+
}
26+
27+
set result 0
28+
for {set i 2} {$i <= $total} {incr i} {
29+
set result [expr {($result + $skip) % $i}]
30+
}
31+
32+
return [expr {$result + 1}]
33+
}
34+
35+
if {$argc != 2} { usage }
36+
37+
set total [parseInt [lindex $argv 0]]
38+
set skip [parseInt [lindex $argv 1]]
39+
40+
puts [josephus $total $skip]

0 commit comments

Comments
 (0)