java - Card Magic Trick, algorith that orders cards -



java - Card Magic Trick, algorith that orders cards -

i've been working on question quite time now, question below:

consider next “magic” trick. have deck of n cards, labeled 1,2,...,n (but not in order). repeat next process until no cards left:

show public card on top of deck, , remove deck take next card top of deck , place @ bottom of deck, without showing it.

your goal have ordered cards in deck cards shown public in increasing order: 1, 2, ...,n.

for example: if n=5, starting arrangement 1,5,2,4,3 work: 1,5,2,4,3 -> 2,4,3,5 -> 3,5,4 -> 4,5 -> 5

question: write algorithm prints appropriate initial ordering given number n of cards.

algorithm ordercards(n) input: integer n output : prints right card ordering.

i managed following:

n=1 --> 1 n=2 --> 1,2 n=3 --> 1,3,2 n=4 --> 1,3,2,4 n=5 --> 1,5,2,4,3 n=6 --> 1,4,2,6,3,5 n=7 --> 1,6,2,5,3,7,4 n=8 --> 1,5,2,7,3,6,4,8

as can see there pattern in every other number such 1,x,2,x,4,x... believe algorithm different depending on if n value or odd, i'm not sure how. if n sec element = value(n-2) + 1

any advice appreciated!

never obey "play" rules when comes magic (or writing generators based on reductions, or reducers based on generation rules): know final ordering want, generate start sequence running trick in reverse. treat cards visible, set lastly card on top of "empty" deck, move bottom top (this doesn't alter order lastly card of course) , set next card on top. repeat until done.

so, let's start final order want "end with". say, 1,2,3,4,5. then:

1,2,3,4,5, set lastly visible on top of deck → 1,2,3,4 + 5. move bottom top, add together lastly visible card: → 1,2,3 + 4,5. move bottom top, add together lastly visible card: → 1,2 + 3,(4,5 → 5,4) = 3,5,4. move bottom top, add together lastly visible card: → 1 + 2,(3,5,4 → 4,3,5) = 2,4,3,5. move bottom top, add together lastly visible card: → 1,(2,4,3,5 → 5,2,4,3) = 1,5,2,4,3.

done.

if run 1,2,3,4,5,6,7,8,9,10 1,6,2,10,3,7,4,9,5,8, in 10 steps.

also notice algorithm o(n): sequence of 1000 cards perform 1000 "move bottom top, add together card on top" steps. can improve on this? possibly, requires looking @ longer sequences see if can find pattern in permutations generates.

we know it's extremely regular, there improvements made - instance, sequence 1,2,...,n-1,n can determine "odd" cards in deck: 1,2,...,n/2 (in 1..5 sequence, numbers 1,x,2,x,3, , 1..10 see 1,x,2,x,3,x,4,x,5,x). if can figure out how rest of numbers fall place, we'll able find o(1) algorithm generating deck sequence start with. beyond scope of answer, though.

java algorithm math

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -