- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Cool idea, include a math exercise in each story, and additional to the captcha the solution of the exercise must be provided. This might not totally avoid "first11!1" posts, but we might get less of the very stupid ones :-)
Admin
T-SQL (SQL Server 2008 although I bet 2005 would work too). I tried to avoid just writing "C style" code with variables and really use the database features:
Admin
Admin
I didnt have time to read all the comments so sorry if this is what has already been done...
def josephus(soldiers, skip): soldiers = range(1, soldiers+1)
while len(soldiers) > 1:
soldiers.pop((skip - 1) % len(soldiers))
soldiers = soldiers[2:] + soldiers[:2]
return soldiers
Admin
Hmm, you're right, and so was Wongo. When I correct it so it's a accurate representation of scratching in the sand I get this:
Which gets the same solution as you. So much for prime numbers!
Admin
There are some Haskell solutions, but no oneliner yet:
josephus n s = head $ (!!(n-1)) $ iterate (\x -> let y = drop (s-1) x in filter (/= head y) y) $ concat $ repeat [1..n]
Admin
Last 2 man standing, one of them has the axe, why the hell would he kill himself?
Admin
LOL!
Admin
bash + expr:
Admin
I think this could be done quicker or with less code but i guess it's solid
function calculateSafeSpot($iNumSoldiers, $iNumSkip) { $aMen = array_fill(1,$iNumSoldiers, 'alive'); $iCount = 1; while(count($aMen)>1) {
}
Admin
Rather boring one, but simple, in php ;)
<?php function joseph($ile, $jump = 3) { $tab = array(); for ($i=0; $i<$ile; $i++) { $tab[] = ($i+1); } $k = $i = 0; while (count($tab)>1) { if ($i>=count($tab)) { $i = ($i%count($tab)); } if ((($k+1)%$jump)==0) { array_splice($tab, $i, 1); $i--; } $k++; $i++; } echo 'joseph('.$ile.', '.$jump.') = '.$tab[0].''; } ?>
Admin
Admin
This programming praxis was let down by its simplicity and the well known nature of the problem. I love the idea of coding challenges but you need to come up with original problems for them.
Admin
If you call the Frisbeetarian object with a float, it just hangs....
Admin
Have one in sed with some help from bash.
Admin
A solution in Clean which starts with a list of soldiers numbered 1 to n and recursively kills soldiers until only one is left:
josephus n s = kill [1..n] (s - 1) where kill [j] s = j kill l s = kill (tl (rotate l s)) s
rotate l s = drop s l ++ take s l
Admin
Hacky solution in R. Remember that in R all indices begin with 1. Uncomment the cats to see how it works.
Admin
Uh...aw, bleep. I ran J(3,12) instead.
Sorry. You'd think I'd've learned not to flame after 10PM by now...
Admin
Python one-liner:
Admin
Addendum (2009-08-14 23:32): Updated: I have been studying theology and discovered that He is also claimed to be uncreated. Therefore he is static const, and the constructor is private.
Admin
BASIC code SAFE_SPOT is the return parameter.
I'm using a string of "1" characters, instead of an array, which are switched to "0" when dead.
Admin
javascript with caching to make it run fast ;)
Admin
If you're a follower of a polytheistic belief, such as Hinduism, you would require a getInstance() method for each god, and perhaps a factory class:
Finally, if you're Terry Pratchett, you can instantiate God objects with the 'new' operator. If the God object is not used, it will automatically be garbage collected.However, God objects are considered anti-patterns, and should therefore not be used.
Admin
Admin
Very interesting, thanks for the link. Still not something Josephus could have hacked together in the few seconds when the troup gathers (unless the guy was both a soldier AND a polymath, rather a rare occurrence)... Also, he would have to have known the constant K, which I'm not sure was known at the time.
Again, I might be completely wrong in interpreting the problem, maybe that "Josephus quickly found a solution" is just Alex's usual literary embellishment... But darn, those series look eerily simplifiable.
Admin
I'm currently in the middle of an XML training course, and it's really tempting to try to work out a way of doing this in an XSLT. Unfortunately I have two important work-related tasks that I have to finish tonight and it's 9pm already, so I don't have time to play around with it (and really I shouldn't be on this site at all).
But if the course is going slowly tomorrow, I make no guarantees :D
Admin
He there
I focused on ... getting it right ... fast. So I wrote down a pretty stupid piece of JAVA code (plus some debug output and profiling basics. I calculated that it would be O(n^2) ... so who cares if there is an O(n) solution anyway ;-)
But well, that one was really neat. Anyway, here we go.
Admin
This should be done with math but I haven't had my coffee yet. So I will use Mathematica. This seems to be a job for NestWhile, and we can use cyclicity and skip to the n'th person by RotateLeft'ing by n-1. So
JosephusLast[num_Integer?Positive, step_Integer?Positive] := NestWhile[Rest[RotateLeft[#, step - 1]] &, Range[num], Length[#] > 1 &][[1]]
E.g.
In[3]:= JosephusLast[12, 3]
Out[3]= 10
In[4]:= JosephusLast[41, 3]
Out[4]= 31
In[5]:= JosephusLast[40, 3]
Out[5]= 28
Replacing NestWhile with NestWhileList and removing the [[1]] gives who is left before each step.
Admin
Fascinating. For all those who won't follow the link, here is the gist of it: to calculate Fibo(n+1) given ONLY Fibo(n) (and not, as is usual, Fibo(n-1)), just do Fibo(n+1) = round(Fibo(n)* Phi). It works for all cases where n>1 (Phi is the golden number 1.618...).
There MUST be some similar solution to the Josephus problem...
Admin
C# (4.0):
Admin
Actually, the safe spot with 41 soldiers is 31, not 41. And 11 (soldiers) = 7 (safe spot), 13 = 13 (you're right for this one), 17=11, 19=17, 23=8... It doesn't work. I've also tried things like: safe spot = (soldiers - previous prime) * 2, safe spot = soldiers mod previous prime... No luck there either.
Admin
Yes, but:
That's a bit obvious (40 of them are praying, and only Josephus is drawing in the sand, mumbling "...skip Marcus, kill Anthony, skip Aurelius...").
What if they were 400 soldiers? ("Guys, please pray a bit more, I haven't finished calculating my, er... tax returns")
As I read the problem (again, I might be mistaken), he uses his wits to quickly find a general solution to the problem, which would accommodate for a variable number of soldiers and skip steps.
In fact, the question is now rather similar to the one about Fermat's Theorem: at the time, could he or could he not have found a solution that required none of the knowledge we now have?
Admin
Since this is The Daily WTF, I figured that the solution is worth nothing unless it is a WTF itself. So - here's my attempt at doing it in Microsoft-specific C++. N = the number of men; K = which one to kill (3 means every 3rd). The return value is the number of position (starting at 1).
int josephus(int n , int k) { int $,$=n,=2,$$=k;$^=$;$_:if(>$)goto $;$+=$$;$%=__++;goto $;$:return ++$_; }
Admin
First! (for 4, 9, 31, 70, 105, 355, 799, 1798, 2697 etc soldiers...)
(Sorry, couldn't resist.)
First off, iterative Josephus, O(n), in C:
Crunchy, but effective.
Secondly, here's that O(1) implementation, again in C:
Please note that this is specific to k=3.
Here's an O(Log N) (to the base k) implementation, C, based on Strilanc's solution.
Iterative O(Log(N)) proves difficult, because we have some maths on either side; the recursive n-ceil(n/k) on input, and the clever stuff after. Anyone have any ideas?
The story is likely to be apocryphal, or at least the part about figuring out where to stand being either attributed later or pure luck (anthropics!).
Also, bear in mind they were euthanising each other as a kindness. It would have been fairly easy for him to "do the kindest thing", and accept the last position.
Admin
by Damage
Admin
round pi('s) will kill you?
Admin
Here are 4 variations in C#
Admin
Bear in mind that modern historians regard TJF's credibility as "questionable".
And we only have TJF's account of what actually happened.
As Wongo implies there - during the battle, anything could have happened - there was no way TFJ could know in advance there would be exactly 41 individuals present.
So, the possibilities are:
1: there is a very rapid shortcut, that no subsequent mathematician has been able to rediscover...
2: he has previously calculated and memorised the answer for multiple scenarios...
3: he works it out just once cycle ahead - "1, 2, argh, 1, 2, glurg" - and moves position to stay alive one move cycle - "I'll just check that Aaron is actually dead there..." walks over, stabs the corpse and stays standing in that new location...
4: he was just genuinely lucky that day...
5: he lied about what happened...
6: he lied about what happened...
< Kryten_mode > Now I realise the last two suggestions are actually the same point, but I thought it was such a big one it was worth mentioning twice. < Kryten_mode />
So, in other words, the original documentation is faulty, and everyone here is now coding a solution to something other than the real situation... :)
Admin
The position that Josephus took was as the executioner.
MArk B.
Admin
Here's an overly complex and deadly game of Duck Duck Goose, done in DOS. For what it's worth, I wrote it in EDIT
Run pond.bat [NumberofDucks] [skips until kill]
It will create that many duck files. The Golden Goose will be put in the first spot. A duck increases the count, then either quacks (safe), dies (unsafe), craps (golden goose dies) or golds (golden goose last one standing).
If the pond gets crapped in, all the ducks are resurrected, and the golden goose is put into the next spot.
Repeat until the goose lays a golden egg in the pond, and the final position is reported.
======== pond.bat
@ECHO OFF REM usage: pond.bat NumberOfDucks SkipsUntilGoose
SET DUCKS=%1 SET GOOSE=%2
IF %DUCKS%=="" GOTO USAGE IF %GOOSE%=="" GOTO USAGE
REM *** Begin the spot-check loop *** :START REM start the golden goose at position 1 SET GOLDENGOOSE=1
:BREED
REM set the counter at 1 SET DUCKDUCK=1
REM reset the counter SET COUNT=1
:HATCH
copy liveduck.bat duck%COUNT%.bat >nul
SET /A COUNT=%COUNT%+1
IF %COUNT% GTR %DUCKS% GOTO ENTERPOND
GOTO :HATCH
:ENTERPOND
REM set the number of alive ducks SET QUACKERS=%DUCKS%
REM set the first calling duck SET QUACKER=1
:DUCKDUCK
CALL duck%QUACKER%.bat
REM Two ending conditions IF %POND%==crap GOTO BADRESULT IF %POND%==gold GOTO GOODRESULT IF %POND%==dead SET /A QUACKERS=%QUACKERS%-1
IF %QUACKERS% EQU 0 GOTO SOMETHINGAWFUL
REM Else the next duck should be called
SET /A QUACKER=%QUACKER%+1
REM loop back to the first duck if needed IF %QUACKER% GTR %DUCKS% SET QUACKER=1
GOTO DUCKDUCK
:SOMETHINGAWFUL echo exception all ducks died but the golden goose never crapped GOTO END
:BADRESULT REM oh no, the golden goose was killed! Let's start again, but move the REM goose one higher
ECHO Golden Goose unsafe at position %GOLDENGOOSE%
SET /A GOLDENGOOSE=%GOLDENGOOSE%+1
REM If we've exhausted positions, than this is unwinnable IF %GOLDENGOOSE% GTR %DUCKS% GOTO ROASTDUCK
REM Recreate the ducks GOTO BREED
:GOODRESULT REM the golden goose was safe! What position was he in? ECHO Golden Goose was safe at position %GOLDENGOOSE% GOTO END
:ROASTDUCK REM the golden goose was unsafe at any position ECHO There is no safe spot for the goose. Would you like leg or thigh? GOTO END
:USAGE ECHO Proper usage: ducks.bat NumberOfDucks NumberOfSkips
:END SET COUNT=1
:KILL del duck%COUNT%.bat SET /A COUNT=%COUNT%+1 IF %COUNT% LEQ %DUCKS% GOTO :KILL
============ liveduck.bat
@ECHO OFF
REM DUCKDUCK = the current loop counter REM GOLDENGOOSE = the position of the special goose REM POND = Where to put the return variable REM GOOSE = The max of the skip counter REM QUACKER = The last goose to act REM DUCKS = The number of ducks we started with
REM If the highest counter was hit, this duck dies IF %DUCKDUCK% EQU %GOOSE% GOTO FUCKTHATDUCK
REM Otherwise quack and move onto the next duck SET POND=quack REM Increase the count by one SET /A DUCKDUCK=%DUCKDUCK%+1
GOTO END
:FUCKTHATDUCK
SET DUCKDUCK=1
REM This duck must die. If this duck is the last duck alive, the golden REM goose is safe
IF %0==duck%GOLDENGOOSE%.bat GOTO GOLDDIGGER
REM Kill self SET POND=dead copy deadduck.bat %0 >nul GOTO :END
:GOLDDIGGER
REM The golden goose is about to die. See if it is the last duck alive, REM it wins. Ohterwise, bad.
SET POND=crap
IF %QUACKERS% EQU 1 SET POND=gold
GOTO END
:END
============ deadduck.bat
@ECHO OFF REM Dead ducks aren't much fun. They don't increase the duckduck counter, REM since they don't count. Just ignore this duck and move on
SET POND=brains
:END
Admin
Simple in Python with a list that gets shorter:
def josephus(n, k): soldiers = range(0,n) kill = -1 while n > 1: kill = (kill + k) % n soldiers.pop(kill) n -= 1 kill -= 1 return soldiers[0] + 1
Admin
mad props
Admin
The number 40 had great significance to Hebrews (it rained for 40 days and 40 nights, etc.) so I wouldn't be surprised if it was standard practice to give up if your fighting force dropped below 40 (assuming your cause was hopeless)
Admin
Aha! That's how he figured it out so quickly!
Using his trusty abacus, he put dirt on one side of each bead. With lightning speed, he rolled beads over one-by-one, and found the correct spot. Brute force wins!
Admin
He actually had plenty of time. If he knew who will be starting he could easily select position to not be killed in the first round, so he had 13*(time to commit suicide) to find out final solution (and if you are in such situation you think quickly) and create some excuse for changing the spot (they were not expecting cheater so it wasn't that big problem).
Admin
Admin
In PHP, with a nice visual representation
<style> body{background-color:#FFF; font-family:arial;} .circle{background-color:#000000; width:30px; height:30px; color:#FFFFFF;} .survivor{background-color:#00CC00;} .dead{background-color:#FF0000;} </style> <?php function circle($soldiers,$skip){ $circle=array(); for($i=0; $i<$soldiers; $i++){ $circle[]=$i+1; } $i=0; $compteur=1; while(count($circle)>1){ if($compteur%$skip==0){ unset($circle[$i]); $circle = array_values($circle); if($i==0){$i=count($circle);}else{$i--;} } if($i>=count($circle)-1){$i=0;}else{$i++;}; $compteur++; } return ($circle[0]); } if(isset($_GET['form_set'])){ $survivor=circle($_GET['soldiers'],$_GET['skip']); echo $survivor; echo "Reset"; ?> <?php $k=1; $radius=7*$_GET['soldiers']; echo '<div style="position:relative; margin:0 auto; width:10px; height:50%; margin-top:'.($radius+50).'px;">'; for($i=-2;$i<=1.99999;$i = $i+(4/$_GET['soldiers'])){ echo "\n"; $k++; } ?> <?php }else{ ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get"> <input type="hidden" name="form_set" value="on"/> <label for="soldiers">soldiers: </label><input name="soldiers" val=""/><label for="skip">skip: </label><input name="skip" val=""/>
<input type="submit"/> </form> <?php } ?>
Admin
It's just amazing now many of you dumbasses are willing to spend time working out and arguing over the workings of this puzzle. Are there really that many of you out of work?
Caveat: I work. I read TDWTF while my work is compiling. I make occasional comments unrelated to the topic.
Admin
Admin
Naturally, a Queue!
If you add a print statement inside the loop you can almost visualize them lining up to get the axe ;)
Soldiers: 2, Last Spot: 2 Soldiers: 3, Last Spot: 2 Soldiers: 4, Last Spot: 1 Soldiers: 5, Last Spot: 4 ... Soldiers: 39, Last Spot: 25 Soldiers: 40, Last Spot: 28 Soldiers: 41, Last Spot: 31