A school yard blog presented an intriguing prisoner problem the other day I briefly mentioned in my think again! blog.
I found a solution, that later turned out to have a flaw, and wanted to illustrate the solution in a javascript program you can play with here.
The program has a few flaws on its own, but they will be ironed out in the next few days as I learn more.
To write the code I used the examples at w3school for inspiration. The coding took me a few hours. These syntactical details hampered me the most:
- I did not know how to write a for loop. I used comma instead of semi colon and got the order of the three elements in the beginning wrong.
- It took me some time to realise that an array likes [] better than ().
- I discovered that the elements of an array is not initialised to 0 when it is declared.
- I had some problems with lining up the { and } in a long if then else endif statement. The error message complained about an instruction far later than where the error was.
- I had some trouble remembering when to use == and when to use =.
- I tried to run an empty do while loop. It didn't like that. When I added nothing, i.e. { }, everybody was happy.
- To pick a random prisoner I found this at Google, Math.floor(Math.random() * prisoners).
- I still do not know how to keep the textbox and the button when clicking Start.
- I still don't know why the code doesn't stop to run.
- In Visual Basic loops often have the instruction doevents to allow the cpu doing other thing than the program so the machine won't freeze. This does not seem to exist in javascript. Some sites talked about settimeout, but I failed to understand it. The problem was that when I used a 'do while (solution not found)' the program made Mozilla freeze. I had to settle for a for loop.
- if ((beenthere[leader]) && (switchis == 'down')) seemed to behave better than if (beenthere[leader] && switchis == 'down')
Conclusion: great to learn a language by solving an intriguing puzzle and looking at examples and not descriptions for the right syntax.
Here is a sample run:
---
start of game
there are 5 prisoners, (prisoner# 0 to prisoner# 4)
switch is unknown
0 up
the leader was sent to the cell for the first time
count = 1 (added the leader, prisoner# 0)
4 down 3 down 2 down 1 down 4 down 1 down
count = 2 (added prisoner #4)
0 up 0 up 1 down 4 down
count = 3 (added prisoner #1)
0 up 0 up 2 down 1 down 1 down 1 down 1 down 3 down 2 down 3 down
count = 4 (added prisoner #2)
0 up 4 up 3 down
count = 5 (added prisoner #3)
release the prisoners!
25 moves to the cell
---
If you read the problem and comments at a school yeard blog you may understand what all this means. :)
Saturday, December 17, 2005
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment