File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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 ]
You can’t perform that action at this time.
0 commit comments