Author |
Topic: A = B-1 (Read 363 times) |
|
harpoo4n5
Newbie
Posts: 6
|
Using only the following 3 constructs: X = 0 //A variable can be assigned an initial value of 0 X++ //A variable can be incremented Loop(X) //A loop that will go through X times How would you implement 1. A = B.C 2. A = B-1 for 1. I got: A= 0 Loop(B) Loop(C) A++ but can't figure out #2
|
|
IP Logged |
|
|
|
SMQ
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 2084
|
|
Re: A = B-1
« Reply #1 on: Sep 25th, 2007, 12:42pm » |
Quote Modify
|
Hint: how would you implement A = B? Hint 2: you need a third variable --SMQ
|
|
IP Logged |
--SMQ
|
|
|
harpoo4n5
Newbie
Posts: 6
|
|
Re: A = B-1
« Reply #2 on: Sep 25th, 2007, 12:45pm » |
Quote Modify
|
Not sure how the hints help A = 0 loop (B) A++ If I have a 3rd variable C, then I could do: C = 0 C++ which would make C = 1; but not sure how that helps?
|
« Last Edit: Sep 25th, 2007, 12:59pm by harpoo4n5 » |
IP Logged |
|
|
|
SMQ
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 2084
|
|
Re: A = B-1
« Reply #3 on: Sep 25th, 2007, 1:05pm » |
Quote Modify
|
Hint 3: The main loop is C = B Hint 4: Increment A one time fewer than C --SMQ
|
|
IP Logged |
--SMQ
|
|
|
harpoo4n5
Newbie
Posts: 6
|
|
Re: A = B-1
« Reply #4 on: Sep 25th, 2007, 1:13pm » |
Quote Modify
|
Still stuck: C = 0; loop B C++ but to increment A one less time doesn't seem possible.
|
|
IP Logged |
|
|
|
SMQ
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 2084
|
|
Re: A = B-1
« Reply #5 on: Sep 25th, 2007, 1:22pm » |
Quote Modify
|
Hint 5: At the end of each iteration you want A to be what C was at the end of the previous iteration Give Away: Copy C to A before incrementing C Solution: Loop (B) A = 0 Loop (C) A++ C++ --SMQ
|
|
IP Logged |
--SMQ
|
|
|
SMQ
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 2084
|
|
Re: A = B-1
« Reply #6 on: Sep 25th, 2007, 1:53pm » |
Quote Modify
|
Of course that implementation is pretty inefficient -- it takes O(B2) operations just to calculate B - 1. It's possible to write an implementation which only takes O(B) operations. Hint: If X can only be 0 or 1, "Loop(X)" acts like "If X" --SMQ
|
|
IP Logged |
--SMQ
|
|
|
FiBsTeR
Senior Riddler
Gender:
Posts: 581
|
|
Re: A = B-1
« Reply #7 on: Sep 25th, 2007, 3:05pm » |
Quote Modify
|
A=0 C++ Loop(B) A++ Loop(C) A=0 C=0
|
« Last Edit: Sep 25th, 2007, 3:06pm by FiBsTeR » |
IP Logged |
|
|
|
SMQ
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 2084
|
|
Re: A = B-1
« Reply #8 on: Sep 25th, 2007, 7:57pm » |
Quote Modify
|
That'll work, and is a few instructions shorter than what I had in mind: A=0 C=0 D=0 D++ Loop(B) Loop(C) A++ Loop(D) C++ D=0 --SMQ
|
|
IP Logged |
--SMQ
|
|
|
|