Slashdot Mirror


Programming Puzzles

An anonymous reader writes "Spotted over at the Economist: 'Sliding-block puzzles look easy, but they can be tricky to solve. The best known is the 15 Puzzle, which became hugely popular in the late 1870s. This involves square tiles labelled with the numbers 1 to 15, which must be arranged in the correct order inside a four-by-four frame.' While we've all tried these puzzles, the inventor of Quzzle set out to design the easiest looking - yet most difficult puzzle around and turned to CS to find it. While the original article touches on it, at the puzzle's site you'll find Jim Lewis, the inventor, wrote a program in Haskell, a functional programming language to find the best design."

392 comments

  1. I will help YOU get a JOB! (Programming puzzles) by Amsterdam+Vallon · · Score: 1, Interesting

    Check these out that I found online, they're great things to use b4 interviews!

    Programming Puzzles

    Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.

    1. Write a "Hello World" program in 'C' without using a semicolon.
    2. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
    3. C/C++ : Exchange two numbers without using a temporary variable.
    4. C/C++ : Find if the given number is a power of 2.
    5. C/C++ : Multiply x by 7 without using multiplication (*) operator.
    6. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
    7. Remove duplicates in array
    8. Finding if there is any loop inside linked list.
    9. Remove duplicates in an no key access database without using an array
    10. Convert (integer) number in binary without loops.
    11. Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
    12. From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
    13. Swap two numbers without using a third variable.
    14. Given an array (group) of numbers write all the possible sub groups of this group.

    [ von http://www.onesmartclick.com ]

    --

    Reply or e-mail; don't vaguely moderate. Ex-O'Reilly/MIT employee, now a full-time Google employee.
  2. Reminds me of Klotski by TheLink · · Score: 1, Informative
    --
    1. Re:Reminds me of Klotski by Refrozen · · Score: 0

      Klotski is such a 1337/hard game. It was so much fun, I remember playing it in the Windows 98 WEP pack when I was a young gaffer.

      Here's another version

    2. Re:Reminds me of Klotski by Sardak · · Score: 1

      Sorry, but I think Lufia 2 already took the title "Hardest Puzzle in the World."

    3. Re:Reminds me of Klotski by Radix37 · · Score: 1

      See my URL for a version with hundreds of puzzles, adding new elements like magnets, magic blocks, holes, eliminators etc etc. Pretty addicting if you like puzzle games.

      --
      Speed Demos Archive - Lots of speed runs!
  3. this was my first assignment at uni by Leonig+Mig · · Score: 1

    using CLEAN, a functional language no-body had ever heard before.

    nobody got it to work (except a couple of russian guys?).

    apparently the professor said that was the whole point of the assignment?

    1. Re:this was my first assignment at uni by eeg3 · · Score: 1

      The point was to prove Russians are better than us? Interesting professor.

    2. Re:this was my first assignment at uni by Leonig+Mig · · Score: 1

      yeah, i think he was trying to teach us we all suck.

      - but the russian guys got him beat. ;)

    3. Re:this was my first assignment at uni by orangesquid · · Score: 1

      well, in scheme, the function would be something like:
      (define (solve grid)
      (return-whichever-grid-is-solved
      (solve (slide-hole-up grid))
      (solve (slide-hole-down grid))
      (solve (slide-hole-left grid))
      (solve (slide-hole-right grid))))

      slow, but, works (i think?).
      you can squeeze it all into one function using lambda and let.

      --
      --TheOrangeSquid Is it any wonder things seem so awry? We swim in a sea of confusion and don't have to think to survive
  4. high return rate by Tablizer · · Score: 3, Insightful

    People are going to buy it because it *looks* simple, but take it back after long times of fiddling in frustration. Or, give it bad reviews in websites.

    Ideally puzzles offer some form of partial gratification if one can see that they are getting closer. I don't know yet if this puzzle is all-or-nothing. There are a lot of different factors that make a puzzle commercially successful. Driving them crackers with deceiptful design is not aways one of them. But, it is an interesting idea.

    1. Re:high return rate by Hatta · · Score: 2, Interesting

      People are going to buy it because it *looks* simple, but take it back after long times of fiddling in frustration. Or, give it bad reviews in websites.

      Ideally puzzles offer some form of partial gratification if one can see that they are getting closer.


      In solving the rubiks cube the partial gratification of completing a side must be forsaken for the larger goal of solving the whole cube. This didn't stop it from becoming immensely popular.

      --
      Give me Classic Slashdot or give me death!
    2. Re:high return rate by Tablizer · · Score: 1

      This didn't stop it from becoming immensely popular.

      Yeah, but a lot of puzzles flopped. I think Rubix was commercially successful because of the physical concept of spinning two axises (axi?), not so much the puzzlement.

    3. Re:high return rate by mrmeval · · Score: 1

      Or just give it to the dog as a chew toy, just like Rubiks tupperware.

      --
      I'd go on a Vegan diet but the delivery time from Vega is too long. --brownkitty
  5. the 15-square puzzle by bm17 · · Score: 5, Interesting

    here's an interesting factoid: Put 15 squares in a 4x4 frame at random and that state will fall into one of two subspaces; call it parity, odd or even. From there, sliding a piece is an operation that will keep the resulting state within the original subspace. So if you have a friend with one of these puzzles, and you pry out two of the pieces and swap them, you will reverse the partiy of the game and he'll never be able to solve it. I leave it to the reader to come up with usefull applications.

    1. Re:the 15-square puzzle by PMJ2kx · · Score: 1

      That reminds me of what i did to my friend's Rubiks cube.

    2. Re:the 15-square puzzle by Tablizer · · Score: 3, Funny

      So if you have a friend with one of these puzzles, and you pry out two of the pieces and swap them, you will reverse the partiy of the game and he'll never be able to solve it.

      My brother used to pull multiple Rubix Cubes apart and add extra color blocks to a side or two (making it unsolvable), and them give them to Rubix gurus to solve under the guise of needing help. It was interesting to watch them as their facial expression switched from a confident processing mode to confusion mode. We could take bets on how long it would take them to identify why it was not solvable. The good ol' Rubix days.

    3. Re:the 15-square puzzle by Fortran+IV · · Score: 5, Interesting
      A nasty variant of that I've read (but never seen) about is a 15-block puzzle that starts with the pattern:
      R A T E
      Y O U R
      M I N D
      P A L
      Show your victim the solved puzzle, then scramble it up. Before you give it to him, make sure the R from YOUR is moved into the top-left corner (replacing the R from RATE). If your target is someone who thinks he already knows how these things work, he's likely to leave that R right where you put it - destroying the parity of the puzzle. He's seen that the puzzle can be solved, but he'll never solve it until he moves that R (so I'm told).
      --
      I figure by 2030 or so my 6-digit UID will be something to brag about.
    4. Re:the 15-square puzzle by Artifakt · · Score: 1

      Niven and Barnes used this trick for a minor puzzle in the novel "The California Voodoo Game" (part of the Dream Park series). The poser swapped two letter R's that could only be told apart by color.

      --
      Who is John Cabal?
    5. Re:the 15-square puzzle by Anonymous Coward · · Score: 0

      Couldn't you do this merely by flipping one of the edge blocks around, so that for those two adjoining color sides, there is one block that's flipped, and then mix it up and melt brains with it?

    6. Re:the 15-square puzzle by Otto · · Score: 1

      It's easier to just flip over a couple of the edge pieces. With even one of the edges reversed, it becomes unsolvable. Of course, if you do it to only one edge piece it's obviously messed up. Do it to 4 or 5 of them, and it's not quite so obvious. ;)

      Or give a couple of the corner pieces a clockwise rotation. That's even more evil.

      --
      - Give a man a fire and he's warm for a day, but set him on fire and he's warm for the rest of his life.
    7. Re:the 15-square puzzle by AndyL · · Score: 2, Funny

      I'll bet that the labels on most Rubix Cubes are easily removable.
      If you swap the labels on two pieces it could make it unsolvable.

      I'm looking at my Rubix Cube now and I'm noticing that a couple of the labels aren't on straight. Hmmmm....
      Either this means that manufacturing standards are low enough that you probably wouldn't notice this type of hoaxing, or it means that someone has already done it to my Rubix cube and I still haven't noticed.

    8. Re:the 15-square puzzle by Anonymous Coward · · Score: 1, Informative

      why does the r have to come from r. You still have to destroy the parity even if you use the r from rate

    9. Re:the 15-square puzzle by xenocide2 · · Score: 2, Informative

      The point isnt't to actually cheat, the point is to trick the puzzle solver by moving one of the Rs to the wrong R spot. They'll leave it there when it belongs down below, unless they're lucky or supergeniuses.

      --
      I Browse at +4 Flamebait

      Open Source Sysadmin

    10. Re:the 15-square puzzle by Westacular · · Score: 5, Interesting

      Actually, he can solve it without moving the R if he also happens to use the A from PAL to make RATE. As you said, it's the parity -- and in an even/odd setup such as this, two wrongs make a right.

      For this reason, an alternate way to ensure his confounding is to leave the orginal R for RATE in the corner and then mix the puzzle up such that the A of PAL is near the top and the A of RATE is near the bottom.

    11. Re:the 15-square puzzle by kinema · · Score: 1

      Interesting... can anyone prove this?

    12. Re:the 15-square puzzle by Anonymous Coward · · Score: 0

      Sam Loyd, the original deviser of the '15 puzzle', knew this and deliberately put the squares in such an insoluble state. He offered $1000 to the first person to solve the puzzle, knowing full well that it was impossible, and soon it had become a craze across America and Europe.

    13. Re:the 15-square puzzle by sharkey · · Score: 1
      I'm looking at my Rubix Cube now and I'm noticing that a couple of the labels aren't on straight. Hmmmm.... Either this means that manufacturing standards are low enough that you probably wouldn't notice this type of hoaxing, or it means that someone has already done it to my Rubix cube and I still haven't noticed.

      Actually, it means that you need to stop buying the crappy, gray-market knockoffs and buy a real Rubik's Cube. You might want to trade in your Sorny TV, too.

      --

      --
      "Outlook not so good." That magic 8-ball knows everything! I'll ask about Exchange Server next.
    14. Re:the 15-square puzzle by OblongPlatypus · · Score: 1

      ... or have read Slashdot lately. But oh wait, we're all supergeniuses here, right? :)

      --
      -- If no truths are spoken then no lies can hide --
    15. Re:the 15-square puzzle by Superfluid+Blob · · Score: 3, Informative

      The original (and I believe it was Sam Lloyd himself who came up with it) had RATEYOUR in on colour of tile and MINDPAL in another, so there was no possibility of swapping the As around.

    16. Re:the 15-square puzzle by Fortran+IV · · Score: 2, Insightful

      Oops, you're right. I wrote a Q&D simulator for it, and sure enough you can swap the A's to solve the puzzle.

      For this to work right, you also have to color the squares in a checkerboard pattern, like the old plastic ones I used to have. Then the two R's are the same color, but the two A's are not. So if your victim uses the other A, the puzzle still won't look right

      --
      I figure by 2030 or so my 6-digit UID will be something to brag about.
    17. Re:the 15-square puzzle by ucblockhead · · Score: 1

      The rubik's cube had the same parity issue. You could make it unsolvable by flipping a side peice.

      --
      The cake is a pie
    18. Re:the 15-square puzzle by Fahrenheit+450 · · Score: 1

      Eeeets got Sony guts!!!

      You like, you buy. Is no big deal...

      --
      -30-
    19. Re:the 15-square puzzle by Anonymous Coward · · Score: 0

      Interesting... can anyone prove this?

      http://www.orie.cornell.edu/~aarcher/Research/15pu zzle.ps

    20. Re:the 15-square puzzle by DavidTC · · Score: 1

      It's perfectly allowable by the directions to take off all the labels, and thus solve the puzzle by making all the sides the same color.

      --
      If corporations are people, aren't stockholders guilty of slavery?
  6. Got an idea by Tablizer · · Score: 1

    I am going to run over a bunch of Rubix cubes in an SUV and sell them on Ebay as "sliding block 2D puzzles with unknown solutions".

  7. Computers play games, too by PMJ2kx · · Score: 1

    Eh, I think it'd be more fun to play chess with Deep Blue. Heck, how fast do you think Deep Blue could solve it?

    1. Re:Computers play games, too by Anonymous Coward · · Score: 0

      Never, dipshit.

    2. Re:Computers play games, too by shoolz · · Score: 1

      Since Deep Blue is designed to play chess, and chess alone, I'd have to say "never".

    3. Re:Computers play games, too by Anonymous Coward · · Score: 0

      Heck, how fast do you think Deep Blue could solve it?

      You are either making a pretty lame joke, or you are one stupid son of a bitch.

  8. The "15" Puzzle by Claire-plus-plus · · Score: 3, Interesting

    I am reminded that the "15" puzzle was set up to be impossibleby the inventor. As is stated on this page and other places the way the puzzle was set up made it impossible to solve. This is because there was a prize for the first person to solve it. It looked possible but wasn't. What a scam eh?

    --
    99 bottles of beer in 175 characte
    1. Re:The "15" Puzzle by Anonymous Coward · · Score: 0

      __________
      |____|___|
      |________|

      1. Draw this on a piece of paper (use lead not ink)
      2. Draw a single continuous curve through all line segments in the figure without crossing a straight line twice.
      3. ????
      4. Profit.

    2. Re:The "15" Puzzle by Anonymous Coward · · Score: 0

      Err, this should be:

      _______________
      | | |
      |______|_______|
      | |
      |______________|

    3. Re:The "15" Puzzle by leed_25 · · Score: 0

      onslouble unles crossing throuh a vertex counts as crossing both lines.

    4. Re:The "15" Puzzle by Lehk228 · · Score: 1

      do the top, middle, left, and right lines count as one or two segments each?

      is the curve allowed to cross itself?

      --
      Snowden and Manning are heroes.
    5. Re:The "15" Puzzle by Lehk228 · · Score: 1

      impossible like this

      green assumes each line counts only once, red and blue count each intersection as breaking a segment into two parts.

      --
      Snowden and Manning are heroes.
    6. Re:The "15" Puzzle by Fahrenheit+450 · · Score: 1

      Simple, make a rubber stamp with the appropriate shape on it, dip stamp in pile of ground up pencil lead, stamp image on paper.

      Now then... where's my goddamn profit?

      --
      -30-
  9. Anyone Know by Omkar · · Score: 0

    A java version of this hardest version? It would be nice to preview the puzzle without the expense^W hassle of a plastic version.

    1. Re:Anyone Know by Infinityis · · Score: 2, Informative

      http://www.johnrausch.com/SlidingBlockPuzzles/quzz le.htm

  10. Re:I will help YOU get a JOB! (Programming puzzles by mtrisk · · Score: 3, Informative

    That's all great and dandy, but take a look at the article. It's about a guy who writes programs that will make physical puzzles; this has nothing to do with programming puzzles or exercises.

    --

    Without a proper flamewar, Anonymous was undecided on what shell to run.
  11. Flash/Java... version of this puzzle? by CheesyPeteza · · Score: 2, Informative

    You'd think he would have created a web version of this puzzle so we could all try it out. :/

  12. You can play it here by ambrosine10 · · Score: 5, Informative

    The puzzle can be played here.

    1. Re:You can play it here by CheesyPeteza · · Score: 1

      Thank you. It tooke all of 2 minutes to get stuck. I just keep going back and forward. :/

    2. Re:You can play it here by Anonymous Coward · · Score: 2, Informative

      And for those looking to cheat, the solution is availible here (warning: pdf document) on page 20.

      Unfortunately, reading the solution is almost a puzzle intself.

    3. Re:You can play it here by kjd · · Score: 1

      I got it in 93 moves on the first try, and I've been drinking tonight. Easier than it looks, or just difficult to get in 84 moves?

    4. Re:You can play it here by kjd · · Score: 1

      Either that, or I just moved it to the wrong corner and proclaimed myself winner. Oops. I'LL STILL GET IT.

  13. Whats so special? by ryen · · Score: 3, Insightful

    The Economist needs to do some research on current AI practices.. in particular, that of which taught in a beginning AI course at any university.
    The puzzle presented in the article can be solved easily using a variety of basic AI heuristic search algorithms. A* and its varients come to mind.
    I fail to see the significance of this guys program when people in my beginners AI class do this stuff for course projects every semester.

    1. Re:Whats so special? by Fortran+IV · · Score: 2, Insightful

      He didn't write a program to solve the puzzle; he wrote a program to invent the puzzle. "Given a specific class of simple-looking puzzles, find the most difficult to solve." A much broader and deeper problem than finding the solution for a specific puzzle.

      --
      I figure by 2030 or so my 6-digit UID will be something to brag about.
    2. Re:Whats so special? by ryen · · Score: 1

      Well, the article doesn't state what search method he used. There are many AI search methods which use trees to explore possible moves. Breadth-first-search will give an optimal solution but will take the longest time to compute, this tree will also be broad but not necessarily long in depth. Depth-first-search will be long in depth but will probably be fairly lobsided.

      My guess is that he used BFS and just brute-forcely tried as many shape combinations that he could (given a reasonable amount of time, because BFS is ass slow). Then he just picked the shape combination that yielded the tree with the longest depth... but who knows =)

    3. Re:Whats so special? by itsNothing · · Score: 2, Interesting
      From the sound of it, the guy did an exhautive search on the trees of all puzzles which were 4x4.

      And incredibly so, he did it in Haskell (crowd gasps!), a functional programming language which requires recursive execution of algorithms. What was it, 50 lines of code? 75?

      What impresses me is how this guy got so many column inches in the Economist. I need better marketting...

    4. Re:Whats so special? by khallow · · Score: 1

      This brings up the classic difference between theory and application. Theoretically, this program is pretty simple and of little interest from that point of view. However, this guy may make a considerable sum of money from the design that the program found. Even simple applications can be profound in the real world.

    5. Re:Whats so special? by Anonymous Coward · · Score: 0

      I agree. As an undergraduate student, I took an introductory course in AI. The prof said at one point: "If you're going to remember one thing from this course, remember A*." What this guy did is he tried all possible "simple" puzzles, and he applied A* and then chose the deepest and broadest tree.

    6. Re:Whats so special? by Anonymous Coward · · Score: 0

      What's so special is this person is creating interesting puzzles for real people in real markets. Too bad you haven't been able to take any of your AI theory and creat a useful and lucrative product from it. Thus is the difference between teaching and business.

    7. Re:Whats so special? by CaptainPinko · · Score: 1
      My guess is that he used BFS and just brute-forcely tried as many shape combinations that he could (given a reasonable amount of time, because BFS is ass slow)

      but isn't BFS highly parellizable? get a small cluster and that should help quite a bit non?

      --
      Your CPU is not doing anything else, at least do something.
  14. Re:I will help YOU get a JOB! (Programming puzzles by Refrozen · · Score: 0

    1. Inline Assembly (I guess that doesn't count as C)? 2. cout "1"; cout "2"; ? There must be a trick there. 3. Not a clue. 4. Fooling around with sqrt() (or mod?) for a while might help? I don't know though. 5. result = x + x + x + x + x + x + x? 6. Ahahaha, yeah.... Later. 7. Use a temporary array, add them all, the repeatedly loop through comparing all values... removing is a little harder. 8. Dunno anything 'bout Linked Lists, am not really a C programmer my self. 9. Is there not a ACCESS function to do that, like adding a unique column? 10. Mmm, you can typecast it or something, I remember that from when I was using C. 11. Well, since C isn't a scripting language I don't see how that's possible. 12. Bah. 13. What's the difference in this, and 3? I give up.

  15. GAP by Anonymous Coward · · Score: 1, Informative

    You can analyze puzzles like this using GAP. Here is an example using Rubik's cube(Google cache since the site seems down to be down at the moment.)

  16. Re:I will help YOU get a JOB! (Programming puzzles by Tablizer · · Score: 3, Funny

    But if you really want to stump a slashdotter:

    15. Go outside and meet girls.

  17. Re:I will help YOU get a JOB! (Programming puzzles by ajs · · Score: 3, Interesting

    ITA Software also has some great puzzles related to employment.

  18. MOD PARENT DOWN TROLL by Anonymous Coward · · Score: 0

    Author is a KNOWN TROLL. If you do not believe me, check his posting history for yourself. Also, some of the puzzles in the list are impossible.

    1. Re:MOD PARENT DOWN TROLL by LnxAddct · · Score: 1

      Everything in there is possible. I've done them before. Any CS undergraduate should have done most of those.
      Regards,
      Steve

    2. Re:MOD PARENT DOWN TROLL by Anonymous Coward · · Score: 0

      I've done them before.

      Please show your work.

  19. Re:I will help YOU get a JOB! (Programming puzzles by Stevyn · · Score: 2, Insightful

    Here's the thing. I can look at each example and see a solution. But how important is it to actually give the solution?

    Computer science has devolved into programming. Is the code that important, or the solution in regular syntax?

    I think most people would find this difficult because they forget how to program in these languages, but that doesn't mean they can't see the answer

  20. Done the 8 Puzzle by cmad_x · · Score: 1, Interesting

    I have done the 8 Puzzle in C++. I doubt the 15 puzzle is more difficult. Sure some things might change, but the idea should remain the same :)

    1. Re:Done the 8 Puzzle by Anonymous Coward · · Score: 0

      I have done the 8 Puzzle in C++. I doubt the 15 puzzle is more difficult.

      Indeed. I've already completed a trivial program to solve those pesky 2-SAT problems that are so popular in CompSci classes. I imagine that 3-SAT can't be any more difficult...

  21. Re:I will help YOU get a JOB! (Programming puzzles by kyhwana · · Score: 1

    3 and 13 are the same..

    --
    My email addy? should be easy enough.
  22. Question 3 Solved by LighthouseJ · · Score: 5, Informative

    3. C/C++ : Exchange two numbers without using a temporary variable.

    My Computer Architecture teacher asked us essentially this question, he said Intel asked it in a way more palatible for computer engineers than CS students but it still works.

    If A contains one number (int or register) and B contains the other:

    B = A XOR B;
    A = A XOR B;
    B = A XOR B;

    Explanation:
    XOR is bitwise exclusive OR and is basically true when the bits differ.
    Say if we're dealing with 4-bit numbers. In the example, say A = 1011 (11 in decimal) and B = 0101 (5 in decimal).

    Step 1: If you take the exclusive OR of A (1011) and B(0101), the result is 1110 and put that into B (or A would be fine). Do bit by bit comparisons based on position from left to right and if the bits are different, mark a one in it's position, if they are the same, mark a zero. By this point A contains an original pattern, 1011 (decimal 11) and B contains the difference 1110 (decimal 14) between patterns.

    Step 2: Take the XOR of A and B again and store in the variable with an original pattern (A in this instance). 1011 XOR 1110 comes out to being 0101 (the original value for B) and we store it in A.

    Step 3: Take the final XOR of A and B again, store in last register B. 0101 XOR 1110 comes out to 1011 (our original A) and is stored in register B.

    Voila, 2 values exchanged very elegantly without wasted space and done in the same amount of steps as using a temporary variable. If you still don't understand, it works on the premise that if you have two piece of data, you only need one piece of data and whats different from the two pieces of data, that way you can reconstruct the other piece of data.

    1. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      I guess you could do this with exclusive nor as well.

    2. Re:Question 3 Solved by szap · · Score: 1, Interesting

      The solution is canonically written in C/C++ as:

      a ^= b ^= a ^= b;

      or

      #define SWAP(a,b) (a^=b^=a^=b);

    3. Re:Question 3 Solved by LighthouseJ · · Score: 1

      I'm sure there was a bitwise XOR operator, but I am more familiar with assembly and assembly-style level of thought.

    4. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      How about :
      x = x + y
      x = x - y
      y = x - y

    5. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      oops, make that :
      x = x + y
      y = x - y
      x = x - y

    6. Re:Question 3 Solved by LighthouseJ · · Score: 1

      Doesn't work with signed numbers.

      If x = 3, and y = -4:

      x = 3 + -4 -> x:= -1
      x = -1 - -4 -> x:= +4
      y = 3 - -4 -> y:= +7

      At completion, x = 4, y = 7, won't work.

    7. Re:Question 3 Solved by LighthouseJ · · Score: 1

      I refer you here.

    8. Re:Question 3 Solved by brer_rabbit · · Score: 2, Insightful

      That isn't correct C/C++. You're modifying the same variable multiple times in the same statement. Although it'll probably work on most compilers, the result is technically undefined.

    9. Re:Question 3 Solved by EvanED · · Score: 1

      If done right, it'll work:

      x -= b
      b += a
      a = b-a

      With your 3 and -4:
      3 -4 (start)
      7 -4 (after x-=b)
      7 3 (after b+=a)
      -4 3 (a = b-a)

      I think if there's no overflow it'll work. Even if there is, as long as it doesn't trap and just rolls over to the opposite sign, I think it'd be okay.

    10. Re:Question 3 Solved by cliveholloway · · Score: 3, Informative

      What a mouthful! Us Perl programmers are, of course, lazy :)

      ($A,$B)=($B,$A);

      cLive ;-)

      --
      -- Trinity in high heels carrying a whip: The donimatrix - there is no spoonerism
    11. Re:Question 3 Solved by Lehk228 · · Score: 2, Insightful

      I thought that was the whole point of having an order in which operators were resolved, so such things could be done, though the code would certainly be more legible if it were seperated into descrete statements.

      --
      Snowden and Manning are heroes.
    12. Re:Question 3 Solved by akuma(x86) · · Score: 1

      Bonus question.

      Why would the XOR swap method run slower than the TMP register method on an out of order processor?

    13. Re:Question 3 Solved by Anonymous Coward · · Score: 2, Informative
      Why would the XOR swap method run slower than the TMP register method on an out of order processor?

      A good bonus question. Anyone who can answer it (or even would think to ask it) realizes how useless micro-optimizations like the XOR swap trick tend to be.

      My answer, check me: an out-of-order processor does dependency analysis to form a partial order of the operations. Where there are no dependencies, some operations can be performed in parallel. The XOR swap method has a partial order length of 3. The temporary swap method has a partial order length of 2. Thus, the temporary swap method is faster. (Assuming the temporary is available and the processor can perform two operations in parallel.)

    14. Re:Question 3 Solved by Anonymous Coward · · Score: 0, Interesting

      the hacker style (c/c++/java and more):
      a = b + 0*(b=a);

      ~avinu

    15. Re:Question 3 Solved by mrchaotica · · Score: 1
      Heh, I had that for homework last spring:
      /*
      * Part 1: xor_swap(int *, int *)
      *
      * This should swap the values located in '*x' and '*y'. You may only
      * use the 3 operators '=', '^', and '*'. Upon return from the function
      * the value of x should now be in y, and the value of y should be in x.
      * This one will take some thought, sit down and think it through!
      *
      * Invocation Example:
      * int a = 5;
      * int b = 7;
      * xor_swap(&a, &b);
      * --- at this point in time, a = 7 and b = 5 if written correctly ---
      */
      void xor_swap(int *x, int *y) {
      /* This works because it does both (*x ^ *y) _before_ changing *x : ) */
      /* Incidentally, it _does_ work if *x = *y : ) */
      *y = (*x ^ *y) ^ ( *x = (*x ^ *y) ^ *x );
      return;
      }


      I wrote the "it _does_ work if *x = *y" because the teaching assistant's solution didn't. : )
      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    16. Re:Question 3 Solved by mrchaotica · · Score: 1
      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    17. Re:Question 3 Solved by HeghmoH · · Score: 1

      I think you're confusing operator precedence with the order of operations. Operators have a defined precedence, but operators which have side effects do not have a defined order in which their side effects are applied. Something like j = i++ * i++, if i = 1, could produce 1 or 2, depending on whether the increment in the first i++ is applied before or after the second i++ is evaluated. Either order would be acceptable behavior.

      --
      Mod down posts with a "Free Mac Mini/iPod" sig, they're spam!
    18. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      Or it could produce a completely different result, or even crash. One possible reason could be that the first increment is evaluated during the evaluation of the second. That would be acceptable behaviour as well.

    19. Re:Question 3 Solved by Dreadlord · · Score: 1
      How is the interesting? It's plain wrong, (b=a) will be executed first, and b's value will be lost.
      #include <stdio.h>

      int main(void) {
      int a = 1, b = 2;
      a = b + 0 * (b = a);
      printf("a = %d, b = %d\n", a, b);
      }
      Output is a = 1, b = 1

      --
      The IT section color scheme sucks.
    20. Re:Question 3 Solved by akuma(x86) · · Score: 1

      Excellent answer!

      This is the kind of question that might be asked at an Intel interview --- speaking as an Intel engineer myself :)

    21. Re:Question 3 Solved by bgreenlee · · Score: 1

      Am I missing something, or will the XOR trick only work for numbers less than the bit-size of your architecture? i.e. if you're doing this on a 32-bit machine, and A or B is greater than 4294967295, it won't work.

    22. Re:Question 3 Solved by LighthouseJ · · Score: 1

      It'll work for any bus length as long as the XOR operation itself is long enough to support the bus. If A or B is greater than 2^(32) - 1, that's the fault of the previous instruction to cause an overflow. The XOR trick certainely can't be held responsible for problems with code before it.

    23. Re:Question 3 Solved by Lehk228 · · Score: 1

      I thought that was defined as the default left to right order, of course i could be wrong.

      --
      Snowden and Manning are heroes.
    24. Re:Question 3 Solved by Fahrenheit+450 · · Score: 0, Flamebait

      Yep. Works in OCaml (let a,b = b,a) and a few other languages as well.

      And unlike the sad little C/C++ solutions people are tossing around, this works for *any* type, not just ints & chars...

      --
      -30-
    25. Re:Question 3 Solved by wgrim · · Score: 1
      And unlike the sad little C/C++ solutions people are tossing around, this works for *any* type, not just ints & chars...


      You are an idiot. Don't you realize you can swap the memory addresses of automatic variables?

      Sounds like you just have a personal problem with computers, because swapping the memory addresses can swap ANY data type. I bet that's how perl and other languages (OCaml) probably do it at the implementation level even.

      Don't be an idiot and say other people's solutions are sad without thinking first, moron.
    26. Re:Question 3 Solved by Fahrenheit+450 · · Score: 1

      Of course that's how they do it. And of course you can swap the contents of variables that hold pointers to the other types. But how many people here on slashdot bothered to take that into account?

      This is especially true if you want to really get pedantic. The problem said numbers and people are throwing up int based solutions. Try throwing them at floats, or arbitrary precision integers. But "everybody knows" that

      The solution is canonically written in C/C++ as:

      a ^= b ^= a ^= b;

      or

      #define SWAP(a,b) (a^=b^=a^=b);


      Which only swaps two ints, not two numbers, for that you have to add the code to take the addresses, cast them to ints, yadda, yadda, yadda... I stand by my assertion that these are sad little solutions...

      --
      -30-
    27. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      This can be written simply in the general form in C++ as:

      template <typename T>
      void swap(T &a, T &b)
      {
      b = a ^ b;
      a = a ^ b;
      b = a ^ b;
      }

      Which has the problem that:

      int main(void)
      {
      int x = 23;
      swap(x, x);
      std::cout << x << '\n';
      }

      will print 0 instead of 23.

      Considering the speed relative to using a temp var, the problem with aliasing (above), and the readability, this trick is all but useless. I dare say that 99%+ of the people here will never see a situation where it makes sense to use this. (I stake my reputation as Anonymous Coward on it!)

    28. Re:Question 3 Solved by lars_stefan_axelsson · · Score: 1
      I thought that was defined as the default left to right order, of course i could be wrong.

      Yes, I'm afraid that's it. Look up the definition of 'sequence point' in e.g. the comp.lang.c faq that's got a very good explanation of this. IMHO the whole comp.lang.c. faq is a must read for any 'C' programmer. Trust me, time spent going through it is well spent.

      --
      Stefan Axelsson
    29. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      "Considering the speed relative to using a temp var, the problem with aliasing (above), and the readability, this trick is all but useless."

      To be fair to the solution, it can easily be changed to not have the aliasing problem. Just add "if (&a == &b) return;" to the beginning of the swap function.

      Though I agree that it's essentially useless.

    30. Re:Question 3 Solved by Chris+Hall · · Score: 1

      You can do the same trick with gcc, using some portable inline assembler:

      asm("":"=g"(a),"=g"(b):"0"(b),"1"(a));
    31. Re:Question 3 Solved by Fahrenheit+450 · · Score: 1
      Now that is much better. Or at least it would be if it worked...
      int main ()
      {
      float a = 1.234;
      float b = 5.678;
      int c = 13;

      printf("a: %f, b: %f\n",a,b);
      asm("":"=g"(a),"=g"(b):"0"(b),"1"(a));
      printf("a: %f, b: %f\n",a,b);

      printf("a: %f, c: %d\n",a,c);
      asm("":"=g"(a),"=g"(c):"0"(c),"1"(a));
      printf("a: %d, c: %f\n",a,c);
      }
      [228] 12:45PM% gcc t.c -o t
      [229] 12:45PM% ./t
      a: 1.234000, b: 5.678000
      a: 5.678000, b: 1.234000
      a: 5.678000, c: 13
      a: 920256512, c: 0.000000
      Of course it's possible I'm doing something wrong... am I?
      --
      -30-
    32. Re:Question 3 Solved by ultranova · · Score: 1

      My answer, check me: an out-of-order processor does dependency analysis to form a partial order of the operations. Where there are no dependencies, some operations can be performed in parallel. The XOR swap method has a partial order length of 3. The temporary swap method has a partial order length of 2. Thus, the temporary swap method is faster. (Assuming the temporary is available and the processor can perform two operations in parallel.)

      1. TMP = A
      2. A = B
      3. B = TMP

      These must be performed in this exact order, or the end result will be undefined. Each step depends on the results of previous steps.

      You must assing to TMP first, or A's value will be lost. You must assing to A second, or B's value will be lost. So you must assing to B last, and can't do any of these steps in parallel.

      Or did I miss something ?

      Or are we talking about running these steps in parallel with some other instructions preceding or following them ?

      --

      Forget magic. Any technology distinguishable from divine power is insufficiently advanced.

    33. Re:Question 3 Solved by Chris+Hall · · Score: 1

      Because the prototype for printf() doesn't explicitly list its argument types (for obvious reasons), the compiler has to use its default function argument conversions. In particular, this means that any floating-point parameter to printf() will be passed as a double rather than a float.

      As sizeof(double)!=sizeof(int) (at least on the platform you're using), merely swapping the %d and %f over doesn't work. Assuming your ints are the same size as your floats, try replacing the last printf with something like

      printf("a: %d, c: %f\n",*(int*)&a,*(float*)&c);

      Or you could just swap the values back again before printing them. :-)

    34. Re:Question 3 Solved by Perky_Goth · · Score: 1

      yep, read up on pipelines. it means that as soon as the result is calculated, but before storing the result, the next op is already working.

    35. Re:Question 3 Solved by Fahrenheit+450 · · Score: 1
      Thanks for the info, but I've got to say... Holy crap is that horriffic. It just strikes me as one of the things wrong with C, (there's plenty right with it, but that's just bad). For example, in C I can do:
      int main ()
      {
      float a = 1.234; float b = 5.678; float f = 100.001;
      int c = 13; char * s = "hubba bubba";

      printf("a: %f, b: %f\n",a,b);
      asm("":"=g"(a),"=g"(b):"0"(b),"1"(a));
      printf("a: %f, b: %f\n",a,b);
      printf("a: %f, c: %d\n",a,c);
      asm("":"=g"(a),"=g"(c):"0"(c),"1"(a));
      printf("a: %d, c: %f\n",a,c);
      z = c + 1.0; printf("z: %f\n",z);
      printf("f: %f, s: %s\n",f,s);
      asm("":"=g"(f),"=g"(s):"0"(s),"1"(f));
      printf("f: %s, s: %f\n",f,s);
      }
      And not only do I get errors when I try to print or compute with the result of the swap, I can get segfaults too...
      [248] 2:20PM% gcc t.c -o t
      [249] 2:21PM% ./t
      a: 1.234000, b: 5.678000
      a: 5.678000, b: 1.234000
      a: 5.678000, c: 13
      a: 920256512, c: 0.000000
      z: 1085649408.000000
      f: 100.000999, s: hubba bubba
      zsh: segmentation fault ./t
      Whereas in OCaml, we have
      Open Printf;;
      let a,b,c,f,s = 1.234,5.678,13,100.001,"hubba bubba";;

      printf "a: %f, b: %f\n" a b;;
      let a,b = b,a;;
      printf "a: %f, b: %f\n" a b;;
      printf "a: %f, c: %d\n" a c;;
      let a,c = c,a;;
      printf "a: %d, c: %f\n" a c;;
      let z = c +. 1.;;
      printf "z: %f\n" z;;
      printf "f: %f, s: %s\n" f s;;
      let f,s = s,f;;
      printf "f: %s, s: %f\n" f s;;
      Which works properly, and the source is much easier to read and maintain.
      [253] 2:35PM% ocamlopt t.ml -o tml
      [254] 2:35PM% ./tml
      a: 1.234000, b: 5.678000
      a: 5.678000, b: 1.234000
      a: 5.678000, c: 13
      a: 13, c: 5.678000
      z: 6.678000
      f: 100.001000, s: hubba bubba
      f: hubba bubba, s: 100.001000
      Plus, if I were to have screwed up and written that last printf statement as printf "f: %f, s: %s\n" f s;;, the type conflict is detected at compile time...
      --
      -30-
    36. Re:Question 3 Solved by Anonymous Coward · · Score: 0

      *y = (*x ^ *y) ^ ( *x = (*x ^ *y) ^ *x );

      Cute, but nonsensical garbage. There's still the fact that C doesn't guarantee much when it comes to order of operations (although most programmers wrongly assume a left-to-right evaluation). Allow me to point out the two expressions that may be evaluated in a different orders, depending on what compiler you're using:

      a) (*x ^ *y)
      b) ( *x = (*x ^ *y) ^ *x )

      If the first expression ("a)") completely evaluates before the second ("b)"), then the "old" value of *x is XORed with the value of *y for both a) and b). However, if the b) evaluates completely before a), then the "old" value of *x will be used for b), but it will be altered before the a)'s XOR is executed. Heck, it could even be argued that your code doesn't even provide an answer to the question, since "(*x ^ *y)" could be considered an unnamed temporary.

      Moral of the story: don't try to be too cute with you programming constructs, because it will only bite you in the ass later on. This is doubly true if you're coding in C or C++.

    37. Re:Question 3 Solved by ragshas · · Score: 1

      #include void main() { int a=1,b=2; a=a+b; b=a-b; a=a-b; printf("a=%d, b=%d",a,b); getch(); } output: a=2 b=1 This can be the solution in my perspective.

  23. A plug and a question... by Rahga · · Score: 3, Informative

    First of all, for GNOME 2.10, gnome-game's Klotski has been updated and now supports SVG and comes with 37 puzzles, several classic wood puzzles from Minrobu Abe (this one may be solvable in 227 moves, not sure...)

    I've also started a hint function that thells the user the precalculated minimum number of moves for each puzzle. The only problem is that Microsoft's Sunshine puzzle is huge, and I've not seen any solutions for it online yet, never mind a calculated minimum. Any klotski addicts out there want to help me out?

    1. Re:A plug and a question... by Radix37 · · Score: 1
      The only problem is that Microsoft's Sunshine puzzle is huge, and I've not seen any solutions for it online yet, never mind a calculated minimum. Any klotski addicts out there want to help me out?

      Head to my homepage URL to find it. You'll need to go to the competitions section and download the old competitions, sunshine was the first one. The outside is slightly different than the MS version because in Bricks you can't have pieces starting on floor elements (the destination in this case). The barrier is cleared at 361 moves, and finished at 746 moves. There's a bigger puzzle that takes 2269 moves! Well... can probably be done in a few less, but that's the best that the best Bricks players have managed.

      --
      Speed Demos Archive - Lots of speed runs!
  24. plurals don't end in 'i' in English by Anonymous Coward · · Score: 0

    Main Entry: axis
    Pronunciation: 'ak-s&s
    Function: noun
    Inflected Form(s): plural axes /-"sEz/
    Etymology: Latin, axis, axle; akin to Old English eax axis, axle, Greek axOn, Lithuanian asis, Sanskrit aksa
    1 a : a straight line about which a body or a geometric figure rotates or may be supposed to rotate b : a straight line with respect to which a body or figure is symmetrical -- called also axis of symmetry c : a straight line that bisects at right angles a system of parallel chords of a curve and divides the curve into two symmetrical parts d : one of the reference lines of a coordinate system

    1. Re:plurals don't end in 'i' in English by Qrlx · · Score: 1

      Youu're 50% on grammar but you flunked the math.

      (The Rubik's Cube has not two but three axes.)

      Furhtermore, the existence of thousands of University campii throughout the world leads me to believe you might benefit from attending one.

    2. Re:plurals don't end in 'i' in English by Anonymous Coward · · Score: 0

      Two problems with your post:
      1: I didn't say anything about the number of axes in a Rubik's Cube. The person I was replying to did.

      2: "Campii" isn't a word (in English, at least). The plural form of "campus" is "campuses". Check a dictionary sometime.

      Based on your poor reading comprehension and ignorance of basic English, I think you could benefit from attending one of those thousands of university campuses too.

    3. Re:plurals don't end in 'i' in English by Anonymous Coward · · Score: 0

      Furhtermore, the existence of thousands of University campii throughout the world leads me to believe you might benefit from attending one.

      Ignoring the obvious typo, you might like to know that the Latin plural of "campus" is "campi". Only one 'i'.

      Grammar nazis, take note: making mistakes in your posts makes you look even more ignorant than the people you're trying to correct. And please don't try to excuse your ignorance with the claim that you're being "ironic" - it doesn't work, sorry.

    4. Re:plurals don't end in 'i' in English by Qrlx · · Score: 1

      Ah, that's it. Campi. I knew campii looked a little off. radius > radii | campus > campi. Thanks.

  25. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    computers tend to use exhaustive methods to find solutions. Perhaps they should consult a mathmatician.

  26. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 2, Insightful
    1. int main(void) { if(puts("Hello, world")) {} }
    3. int x = 5, y = 10; x ^= y; y ^= x; x ^= y;
    4. !(var & (var - 1))
    5. x /= (1.0 / 7); =)
    6. simple: int f(int i) { return i == 7 ? 4 : 7; }
    "clever": return 11 - i;


    I only did the ones that specifically listed C. Number 3 (and, I suppose, 4 for that matter) is dubious because ^ won't work for all types. And beware of the "better" version: x ^= y ^= x ^= y; That's not defined behavior in C!
  27. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    A troll calling someone else a troll.

    Humour, thy name is Slashdot.

  28. Re:Question 3 Solved (alternative method) by JasonSkywalker · · Score: 2, Informative

    This is what popped into my head upon reading this post... same principal as the XOR method but simpler to explain to layfolk...

    A = A*B
    B = A/B (gives B the orig A)
    A = A/B (gives A the orig B)

    --
    I have Unix underpants.
  29. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    I generally find people using these sorts of things as an employment test to be asinine, since most of them are generally just "oh, you heard how to do that, eh?" or you find them out by a lot of experience. But since other posters here haven't seemed to figure it out, I'll suggest a few answers...

    1. Tri-graphs; 2. Recursion; 3. x ^= y ^= x ^= y; 4. Search for a single 1-bit; 5. Good googly moogly x86 assembly programmers love this one: (x << 2) + (x << 1) + x; 9. select with a sort on the desired column, check each row to see if it's the same as the last; 11. This one's been covered ad nauseum but needless to say, it is possible. Is 12 even a programming problem?!

    That's just at a glance, so I don't doubt they are all possible one way or another.

    Anyway, to remain on topic (and prove I RTFA ;), since when are problems based on computability an "bizarre diversion" of CS? Last I checked, that was most of the point of it, at least if you asked Turing. Certainly that is one of the areas of most ongoing research.

  30. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    1. Depending on how literally you take this, you might say "I didn't use a semicolon. I used two."

    Failing that, how about:

    cat > filename.c main()
    {
    printf("Hello World")SEMI
    }
    EOF

    gcc -DSEMI=';'

    Or I've seen other people write it as "if (prinf("Hello world")) {}".

    2. "if" is not a loop. that said:

    printf("1 2 3 4 5 6 7 8 9 .... 100");
    printf("100 99 98 97... 1");

    or

    function(int k)
    {
    return (k > 100 ? 0 : printf("%d", k) && function(k+1));
    }

    function(1);

    3. This involves xor. I'm not going to do it.

    4. A. Use log functions.
    B. bits=0;
    for (i=0; i if (bits != 1) printf("Not power of two\n"); else printf("yup.\n");

    5. x+x+x+x+x+x+x

    6. return (number ^ 3)

    7. What's hard about that? 1. Sort. 2. if val[k]== val[k-1] dump it.

    8. The lazy way? Free each entry as you go. If you crash, there was a loop. :-D Alternately, just set a bit in the data structure to 1 and if you see it set to 1, there was a loop. Much faster than the naive method, and it's provably optimal-O(n) in the length of the list. :-D

    9. Step 1: repartition the computer. Step 2: install Linux and MySQL. Step 3: save the Access database as a text file. Step 4: use 'sort' on the text file with -u. Step 5: import into MySQL.

    10. Easy way? Create a table containing 256 entries each with appropriate 8 character strings for each possible value. Then printf("%s%s%s%s\n", bitvalues[int>>24], bitvalues[(int>>16) & 0xff], bitvalues[(int>>8) & 0xff], bitvalues[int & 0xff]);

    11. How about:

    main()
    {
    printf("an exact copy of the source\n");
    }

    12.

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  31. Re:Question 3 Solved (alternative method) by kylemonger · · Score: 1

    This fails if A or B is zero because A * B will lose information.

  32. one related puzzle I remember by jonwil · · Score: 1

    Is that old puzzle that apple had where you had to reassemble the apple logo.
    Man I remember messing with that in the labs at school (back when they had macs) instead of doing work.

  33. Re:Question 3 Solved (alternative method) by LighthouseJ · · Score: 2, Informative

    True, but what if you have large numbers, like 64-bit values? To properly handle that, your ALU need to be able to multiply 2 64-bit values and the result is a 128-bit product then perform the division. With my style, you can keep the 64-bit bus sizes and the computation needed is considerably small, XOR is a very cheap instruction computationally.

  34. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    Did Not Have Very Flesh Coder Troll?
    |\
    You suck |-\t it.
    | \

  35. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    Whoops, meant to click preview.

    12. Pick 1. Then, whatever the other person picks, pick 7-n, unless they pick too many 6s. As your final number, pick a number large enough to win. There will always be a number large enough to win... if I'm doing the math right.

    13. See #3 and I'm still not doing it.

    14. Umm... no.

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  36. hum. by Anonymous Coward · · Score: 0

    Too bad he couldn't program his computer to recognize the difference between the possessive "its" and the contraction "it's," or to recognize that "ten's" is possessive, not a plural. Imagine the possibilities... a program that could find grammar mistakes! Revolutionary!

  37. Use only subtraction and addition by silvergoose · · Score: 1

    a = a + b b = a - b a = a - b Same idea as the multiplication answer, since both are commutative, but this gets around divide by zero.

    1. Re:Use only subtraction and addition by LighthouseJ · · Score: 1

      The only problem I see now is what if A and B are unsigned integers and you were dealing with 4-bit numbers and a = 1111 and b = 1101, you get overflows and crap.

      The addition/subtraction responses shows thought, but it's too much. The original XOR method is very slim and cheap computationally because the addition/subtraction requires you to wait for the calculations. XOR is more like a straight shot and it works with any bus length.

    2. Re:Use only subtraction and addition by Anonymous Coward · · Score: 0
      The only problem I see now is what if A and B are unsigned integers and you were dealing with 4-bit numbers and a = 1111 and b = 1101, you get overflows and crap.

      In C, addition and subtraction are modular. If an integer is four bits, 1111 + 1101 = 1100. 1100 - 1111 = 1101. 1100 - 1101 = 1111. The algorithm works.

      That also holds true for signed numbers. It just maps a different meaning on those values (via twos complement). The actual additional and subtraction operations are the same except for sign extension, which is only relevant for mixed-size operations.

      The original XOR method is very slim and cheap computationally because the addition/subtraction requires you to wait for the calculations. XOR is more like a straight shot and it works with any bus length.

      Any modern processor can do an addition or subtraction in a single clock. Yes, carries make it a bit more complex, but that work is done for you by the processor designer.

    3. Re:Use only subtraction and addition by LighthouseJ · · Score: 1

      That's a feature of C then. That's the thing, I'm being taught to become a processor designer. We are taught to not presume anything. The question originally posed to me from my teacher was that we had 2 registers and an ALU that were connected in a loop. ALU's that we deal with don't inherently have that capability. Even if the ALU could detect a carry, the added conditional statements would balloon the instructions enough to make adding/subtracting unreasonable.

      We look at ways of getting things done as quick as possible on as many architectures as possible, from the very big (x86, 68k, etc...) to very small (homemade architectures, 6811, etc...).

    4. Re:Use only subtraction and addition by hazem · · Score: 2, Insightful

      Your answer points out that the problem definition is inadequate or ambiguous.

      Maybe the people who start generating code without properly understanding and defining the problem to be solved don't get the job? Who wants a programmer who jumps into code-writing as the first step of design?

    5. Re:Use only subtraction and addition by Anonymous Coward · · Score: 0
      > > In C, addition and subtraction are modular. If an integer is four bits, 1111 + 1101 = 1100. 1100 - 1111 = 1101. 1100 - 1101 = 1111. The algorithm works.

      > That's a feature of C then.

      Not so. That's the behavior that results from not using a carry bit. Typically, processors perform an operation and stuff the carry into the flags register; the program never looks at the carry flag. C doesn't even have a facility for doing so, so you'd have to dip down to assembler. There really are only about three reasons to use this bit:

      1. If it's part of a number larger than a processor register, in an bignum library like gmp.
      2. A specialization of #1: some languages (Python) start out with an int4 and replace it with a bignum if it's too large. The same effect but a little more efficient than using bignums everywhere.
      3. If your language actually does throw overflow and underflow errors on integers. These languages are fewer than you'd think...maybe Ada does? (If you've seen an overflow or underflow error elsewhere, it's probably from a floating-point operation.)

      > > Any modern processor can do an addition or subtraction in a single clock. Yes, carries make it a bit more complex, but that work is done for you by the processor designer.

      > We look at ways of getting things done as quick as possible on as many architectures as possible, from the very big (x86, 68k, etc...) to very small (homemade architectures, 6811, etc...).

      Even a homemade architecture should do addition or subtraction in a single clock, or it's just not worth using. God, I hope they showed you ways to do that. Here's the obvious, easy one - make a table of the inputs and outputs, make SOP (sum of products) logic to produce the outputs, and apply a logic minimization algorithm (such as Karnaugh diagrams or the Quine-McCluskey method). If it meets your fan-in, fan-out, and gate count constraints, you're good to go. And in two levels of logic; you'll get no faster than that.

    6. Re:Use only subtraction and addition by LighthouseJ · · Score: 1

      I think you misunderstood me, the carry flag in the PSW or CCR (or whatever you call it) would be set if it should be. If we are on the assembly level, you'd have to employ add/sub with carry/borrow instead of vanilla add/sub. The compiler would have to reasonably account for this.

      I don't know about your first 2 reasons, never dealt with that. However, on point 3, you can't dismiss overflows just because you might not think they will happen often. You have to accomodate for all special cases otherwise the design is only partially correct.

      I know homemade arch's should do it in a single clock, but I'm slicing the issue into smaller amounts of time. It's a better practice to make it as fast as possible as soon as possible because if you start pipelining your architecture and find out your ALU add is the slowest (unlikely since memory is the big bottleneck), then you have to rework it anyway.

    7. Re:Use only subtraction and addition by Anonymous Coward · · Score: 0
      I think you misunderstood me, the carry flag in the PSW or CCR (or whatever you call it) would be set if it should be. If we are on the assembly level, you'd have to employ add/sub with carry/borrow instead of vanilla add/sub. The compiler would have to reasonably account for this.

      It doesn't. The C compiler never carries. Except maybe on architectures that have types (long long) longer than their registers. Even then, the most significant word's carry is never used.

      However, on point 3, you can't dismiss overflows just because you might not think they will happen often.

      That may be true, but the point is that it's not your decision. The language designers made it, and you just have to live with it. You seem to think that it's common for programming languages to raise integral overflow and underflow errors when appropriate. In fact, it's almost unheard of. Look up the definition of addition, subtraction, or multiplication in your favorite programming language. You'll be surprised.

      I know homemade arch's should do it in a single clock, but I'm slicing the issue into smaller amounts of time. It's a better practice to make it as fast as possible as soon as possible because if you start pipelining your architecture and find out your ALU add is the slowest (unlikely since memory is the big bottleneck), then you have to rework it anyway.

      I don't understand what you're saying. Even if you don't use arithmetic here, you'll have to somewhere. Either your processor can do addition/subtraction in a clock, or it can't. If it can't, avoiding it some of the time isn't going to help. You need to fix it.

  38. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    There is no trigraph for semicolon. Otherwise, that would be a good answer. You might be able to define your own in some way, though.... not sure.

    And 12 is a variant on nim, I think. Very much not a programming problem, but a logic problem.

    Here's another one that took about 30 seconds and had me rolling on the floor:

    1
    1 1
    2 1
    1 2 1 1
    1 1 1 2 2 1

    What's the next entry in the pattern?

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  39. Re:I will help YOU get a JOB! (Programming puzzles by LnxAddct · · Score: 1

    For number 11, here is the solution. I'm not the guy who coded this and I don't know who to attribute it to so I guess we'll just say: Copyright SCO 1994-2004 ;) (laugh)
    Here is the C program that prints itself (also known as a self-reproducing program or a quine)

    char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10 );}%c"; main(){printf(f,34,f,34,10);}

    Regards,
    Steve

  40. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    "2. Recursion"

    Okay, now how do you notice you're at the base case without an if statement? (?: is cheating too I think)

  41. Re:I will help YOU get a JOB! (Programming puzzles by fredrikj · · Score: 1
    5. Good googly moogly x86 assembly programmers love this one: (x << 2) + (x << 1) + x

    More efficiently:
    (x << 3) - x
  42. Re:I will help YOU get a JOB! (Programming puzzles by binary42 · · Score: 1

    5. could be this... much better btw. a = (a)+(a1)+(a2);

    --
    ruby -le"32.times{|y|print' '*(31-y),(0..y).map{|x|~y&x>0?' .':' A'}}"
  43. Re:I will help YOU get a JOB! (Programming puzzles by davebaum · · Score: 1

    Trigraphs were my first thought on how to solve #1 too, but then I looked them up and it turns out that semicolon is part of the ISO 646 standard 7-bit character set, so there isn't a trigraph for it. I think the intended solution is to exploit the fact that code blocks after an if or while statement do not need a terminating semicolon: #include int main() { if (printf("Hello, world\n")) { } }

  44. Re:I will help YOU get a JOB! (Programming puzzles by falzer · · Score: 1

    3 1 2 2 1 1

  45. And, of course, we all remember... by Anonymous Coward · · Score: 0

    ...that in "Metamagical Themas", Douglas Hofstadter used the "15 puzzle" to prove/demonstrate some things. If you reassemble the puzzle, but switch two of the tiles:

    1 2 3 4
    5 6 7 8
    9 a b c
    d f e ...the puzzle is unsolvable. The challenge, then is to make a computer program that can compute the probability of a random assemblage of the tiles for solvability.

  46. Re:I will help YOU get a JOB! (Programming puzzles by binary42 · · Score: 1

    !! stupid formating!!! a = (a)+(a<<1)+(a<<2);

    --
    ruby -le"32.times{|y|print' '*(31-y),(0..y).map{|x|~y&x>0?' .':' A'}}"
  47. Number 5 by Anonymous Coward · · Score: 0

    5. C/C++: Multiply x by 7 without using multiplication (*) operator.

    Too easy (assumed x was int)

    x / (1.0/7.0)

    (x << 3) - x

    1. Re:Number 5 by ArsenneLupin · · Score: 1
      Too easy (assumed x was int)

      Even easyer:

      x+x+x+x+x+x+x

      Got, that's so awfully trivial that I wonder what the point of the question is!

      Number 2 can be solved in an equally trivial way, assuming there is enough time on the test to write the solution down...

  48. Re:I will help YOU get a JOB! (Programming puzzles by Yaztromo · · Score: 1
    What's the next entry in the pattern?

    312211

    Yaz.

  49. Re:I will help YOU get a JOB! (Programming puzzles by davebaum · · Score: 2, Informative

    ooops - should've previewed. The code didn't paste well into HTML. Here's another try:

    #include <stdio.h>

    int main()
    {
    if (printf("Hello, world\n")) { }
    }

  50. Re:I will help YOU get a JOB! (Programming puzzles by sahonen · · Score: 1

    I'm not a programmer, so excuse my ignorance, but how does a quine work? When you compile it, it gets turned into machine code, so how does the program know what the source code is?

    --
    Make me a friend and I'll mod you up
  51. Two *REAL* solutions to #2 by EvanED · · Score: 1

    It is possible to do #2 without any explicit control structures, and without manually typing all the numbers from 1 to 100.

    No If, While, For, ?:, etc.

    Hints to the solution I found:

    Hint 1:
    If you know Ml, think how you could do it with Ml. If you don't know Ml, it would look like this in pseudo-Ml code:

    fun printI(1) = (print "1";)
    | printI(i) = (printI(i-1); print i;);

    Ml performs pattern matching on the code. It's functionally equivalant to:
    fun printI(i) = if i=1 then print "1!;
    else (printI(i-1);
    print i;)
    end;

    Is there anything in C++ that can mimic Ml's pattern matching?

    Hint 2:

    Look up C++'s template specialization.

    My solution is at http://www.personal.psu.edu/users/e/e/eed132/misc/ count.cpp

    There is another solution a friend of mine came up that I think is slighty more conventional and doesn't use features that are anywhere near as obscure.

    Hints to his solution:

    The following code:
    stupidfoo(int i) {}

    print(int i)
    {
    if(i > 0)
    {
    print(i-1);
    printf("%i", i);
    }
    else
    {
    stupidfoo(i);
    }
    }

    is as good as a normal recursive solution in terms of correctness. Calling a function that returns right away is as good as just returning right away in the first place.

    Step 2:
    So we can replace the if statement with a single expression (this gets into the realm of questionable readability, but whatever):
    print(int i)
    {
    ((i > 0) ? print : uselessfoo)(i);
    }

    Ponder that line for a moment, it may not be clear right away.

    Step 3:
    We can put print and uselessfoo into an array of type void(*)(int), with print in [0] and uselessfoo in [1]. Thus the above line can be replaced by
    (functions[(i > 0) ? 0 : 1])(i);

    Step 4:
    Now, can you get a 0 or 1 out of i without using any control expressions?

    href="http://www.personal.psu.edu/ users/e/e/eed132/misc/count2.cpp has the final code.

    I'm also imagining solutions with purposely raising exceptions when i is 0 and then catching them in main.

    1. Re:Two *REAL* solutions to #2 by Anonymous Coward · · Score: 0
      Here is my general purpose code. This abuses the fact that when and AND is being evaluated, when it reaches something false it doesn't continue.
      #include <stdio.h>

      int go(int n, int max, int inc)
      {
      printf("%i\n",n);
      return (!(n+inc==max) && go(n+inc,max,inc) || (n+inc==max) && printf("%i\n",max));
      }

      void main()
      {
      go(0,100,1);
      go(100,0,-1);
      }
      -Matt
    2. Re:Two *REAL* solutions to #2 by HeghmoH · · Score: 1
      That looks unbelievably complicated. Here's a nicer solution to the 1-100 problem (100-1 being very much the same, of course):
      int printnums(int i)
      {
      printf("%d\n", i);
      (i < 100 ? printnums(i+1) : 0);
      return i;
      }

      int main(void) { printnums(1); return 0; }
      You don't need to actually use the result of the ?: operator in order to use it as a control structure. (You do need to provide it with expressions which have the same type; this is why printnum() returns int and not void.) If ?: is too close to 'if', you can replace it with || or && and take advantage of their short-circuiting nature.
      --
      Mod down posts with a "Free Mac Mini/iPod" sig, they're spam!
    3. Re:Two *REAL* solutions to #2 by Anonymous Coward · · Score: 0

      I liked Matt's solution, using the AND behaviour as the control structure.
      Here's my solution, stack be damned:

      typedef int (targ_t)(void);
      int i = 0;
      int main(); int down(); int done();
      targ_t * targ[3] = {main, down, done};
      int done() {
      exit(0);
      }
      int down() {
      printf("%d ", 200-i++);
      targ[(i/100)]();
      }
      int main() {
      printf("%d ", i+++1);
      targ[(i/100)]();
      }

      - aaron gcc -o foo foo.c

    4. Re:Two *REAL* solutions to #2 by ArsenneLupin · · Score: 1
      ...and without manually typing all the numbers from 1 to 100.

      Well, this condition is actually not in the problem as stated... I wouldn't be too quick to rule that one out. Maybe the purpose of this particular interview question is not to test the candidates intelligence, but to check whether he has the chuzpa to give this insultingly trivial solution? You know, in the job, you do not only need to be smart, you ocasionnally need to be daring too, like the student writing only "this!" as the answer on a test "What's courage?" !

      Note: if the interviewer really wanted to rule out this solution, he would have asked for the numbers 1 to 1000000 instead.

    5. Re:Two *REAL* solutions to #2 by SpinyNorman · · Score: 1

      In Zen minimalist form, that'd be:

      bool up(int i)
      {
      printf("%i\n", i);
      return (i == 100) || up(++i);
      }

      int main(void) {return (int) up(1);}

    6. Re:Two *REAL* solutions to #2 by HeghmoH · · Score: 1
      Ok, now you got me started. Here's the best I could come up with:
      int main(int argc, char **argv) {
      return printf("%d\n", argc) == 4 || main(argc + 1, argv);
      }
      Do I get any bonus points for never using '100' anywhere? Is there an even more minimal way?
      --
      Mod down posts with a "Free Mac Mini/iPod" sig, they're spam!
    7. Re:Two *REAL* solutions to #2 by SpinyNorman · · Score: 1

      Is there an even more minimal way?

      No! :-)

    8. Re:Two *REAL* solutions to #2 by dalleboy · · Score: 1

      struct Slashdot
      {
      static int i;
      Slashdot()
      {
      std::cout << ++i << std::endl;
      }

      ~Slashdot()
      {
      std::cout << i-- << std::endl;
      }
      };

      int Slashdot::i = 0;

      int main()
      {
      Slashdot a[100];
      }

  52. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    how about:

    a = (a3) - a;

  53. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    4. A. Use log functions.
    B. bits=0;
    for (i=0; i if (bits != 1) printf("Not power of two\n"); else printf("yup.\n");


    Happened to see a better solution to this one earlier today:
    if (x<1) return false;
    return (x&(x-1))==0;

    stolen from here

  54. Solutions to some of these... by Otto · · Score: 4, Informative

    1. Write a "Hello World" program in 'C' without using a semicolon.

    void main()
    {
    if (printf("Hello World!\n") {}
    }

    2. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;

    Dumb....

    void main()
    {
    printf("1\n2\n3\n... and so on...");
    }

    3. C/C++ : Exchange two numbers without using a temporary variable.

    x^=y; y^=x; x^=y;

    4. C/C++ : Find if the given number is a power of 2.

    if (!( x & (x-1)) printf("x is a power of 2\n");

    5. C/C++ : Multiply x by 7 without using multiplication (*) operator.

    x = (x6. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7

    int function(int x) {
    switch (x)
    {
    case 7: return 4;
    case 4: return 7;
    }
    }
    Or countless other ways...

    10. Convert (integer) number in binary without loops.

    I assume you mean to print the binary form of an int without using loops. So I didn't use a loop, I used recursion. ;)

    void printbits(int x)
    {
    int n=x%2;
    if(x>=2) printbits(x/2);
    printf("%d", n);
    }

    13. Swap two numbers without using a third variable.

    Same problem as #3 above.

    That's enough for now...

    --
    - Give a man a fire and he's warm for a day, but set him on fire and he's warm for the rest of his life.
    1. Re:Solutions to some of these... by Boronx · · Score: 1

      On your number four, you need to check for x=0, which isn't a power of two.

    2. Re:Solutions to some of these... by pediddle · · Score: 1

      2. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;

      Dumb....

      void main()
      {
      printf("1\n2\n3\n... and so on...");
      }


      Try recursion instead....

      Any programmer, let alone computer scientist, who hardcodes a list of values that is otherwise easily constructed programmatically should be drug out into the street and shot. Trust me -- I once worked at a small dot-com company where the CTO(!!) literally did not understand the concept of a loop. He'd copy and paste everything -- leading to 100% unmaintainable code that all had to be scrapped some months later. What a nightmare.
    3. Re:Solutions to some of these... by FuzzyMan45 · · Score: 1

      And i bet he was thinking.. "What job security!"

    4. Re:Solutions to some of these... by robbyjo · · Score: 2, Informative

      I think much of the tricks are covered in Bit Twiddling hacks here.

      --

      --
      Error 500: Internal sig error
    5. Re:Solutions to some of these... by xiox · · Score: 1

      Can you get recursion to work without an if statement?

    6. Re:Solutions to some of these... by the_duke_of_hazzard · · Score: 1
      Nonsense - he's answered the question as stated.


      It's already a ridiculously artificial question if you can't use loops, so why not hard-code?


      I'd give extra credit for not creating a knee-jerk baroque and superfluous object hierarchy to solve a simple problem, as most people I interview seem to these days.


      I'd also give extra credit for doing the simple thing. Sometimes that's the best way.

    7. Re:Solutions to some of these... by CableModemSniper · · Score: 1

      Yes, ?:, or switch or for the really weird temlate meta-programming. (Then the string is generated at compile time anyway though)

      --
      Why not fork?
    8. Re:Solutions to some of these... by Anonymous Coward · · Score: 0

      There are at least 4 totally different solutions higher in the thread. Templates, function pointers, short circuit evaluation, exceptions.

    9. Re:Solutions to some of these... by Otto · · Score: 1

      leading to 100% unmaintainable code that all had to be scrapped some months later

      Agreed, but the point of the puzzle wasn't to write maintainable code. I was just answering the given question. Sure, you could do it using recursion, but at the cost of readability and understanding.

      It's not like a realistic problem anyway. I mean, you're limited to not using loops, which would be the most readable easy way to solve the problem. It didn't force recursion, and the most sensible, understandable, fastest, *easiest* way to solve the stated goals is to just hardcode the solution. Recursion, for this problem, is way overkill.

      --
      - Give a man a fire and he's warm for a day, but set him on fire and he's warm for the rest of his life.
    10. Re:Solutions to some of these... by pediddle · · Score: 1

      We could never have fired him, but the product was so crappy that the company failed... kind of backfired on him I guess.

    11. Re:Solutions to some of these... by Zaak · · Score: 1

      It didn't force recursion, and the most sensible, understandable, fastest, *easiest* way to solve the stated goals is to just hardcode the solution. Recursion, for this problem, is way overkill.

      I notice that you didn't write out the whole hardcoded solution. Perhaps writing out an entire recursive solution would be easier?

      I agree though. It is a very artificial problem.

      TTFN

    12. Re:Solutions to some of these... by dillon_rinker · · Score: 1
      Any programmer, let alone computer scientist, who hardcodes a list of values that is otherwise easily constructed programmatically should be drug out into the street and shot

      ...unless, of course, he's optimizing for speed. =)

      BTW, why would you expect a CTO to understand the concept of a loop? You do realize that a CTO is one step down from a CEO, right? Would you expect a CEO to understand the concept of a loop? A CTO is a business person, not a technical person. Of course, the fact that your CTO was writing code and that you (I'm assuming you're a down-in-the-trenches type) were permitted to speak with him tells me he wasn't a CTO at all, merely a glorified supervisor. I'm curious - how long did it take him to create code that would endure for months? How long did it take you to do the same?

    13. Re:Solutions to some of these... by pediddle · · Score: 1

      He was the founder -- he would never have been hired as a CTO at any other company, but he gave himself the title. That probably explains a lot (and also explains why the company's no longer in business).

      Everyone in the company (only 10-20 people) was down in the trenches. It might have taken me the same amount of time to write the code, but I would have done it right ;-).

    14. Re:Solutions to some of these... by Wescotte · · Score: 1



      Nonsense! A CTO understands

      10 goto work
      20 profit
      30 goto 10

      as they also understand

      10 don't goto work
      20 profit
      30 goto 10

  55. Re:I will help YOU get a JOB! (Programming puzzles by OneHungLo · · Score: 1
    The stupid filter doesn't like me posting the code to answer these, so I guess I'll just post the first 3.

    1.
    #include <stdio.h>

    main()
    {
    if (printf("Hello, world!")) {}
    }
    2.
    #include <iostream>

    template<class T>
    inline void printinc(T i, const T limit)
    {
    std::cout<<i<<" ";
    if(i<limit)
    printinc(++i, limit);
    }

    template<class T>
    inline void printdec(T i, const T limit)
    {
    std::cout<<i<<" ";
    if(i>limit)
    printdec(--i, limit);
    }

    int main()
    {
    using namespace std;

    printinc(1, 100);

    cout<<endl<<endl;

    printdec(10 0, 1);
    }
    3.
    #include <algorithm>

    int main()
    {
    using std::swap;

    int x=1, y=2;

    swap(x,y);
    }
  56. Rubik's Cube by microbox · · Score: 1

    Look up the solution... there's no way that someone works out how to do it without learning the solution... the solution required study from specialized people. The last "move" took a whole bunch of people a long time to work out how to do reliably. The solution is easy to learn as an algorithm, but understanding how it works and reaching those conclusions without help... is a wild leap. It was the most simple-complex puzzle of its time.

    I do believe that some people would understand how to solve the Rubik's Cube intuitively, but I think you'd be talking 1 in a million... adding to the myth-ous and "coolness" of the puzzle.

    --

    Like all pain, suffering is a signal that something isn't right
    1. Re:Rubik's Cube by Qrlx · · Score: 2, Interesting

      Or derive the solution...

      I was a kid when the Rubik's Cube came out. Our neighbor was a topologist. He went out and bought the cube, and presented it to his wife to have her scramble it. Then it sat, unmolested, on the coffee table for many nights while the topologist figured out the necessary moves to solve the puzzle.

      It took him lots of pages on a legal pad but he did solve it. After about two weeks as I recall.

      I, being a kid, bought the "How To Solve The Rubik's Cube" book on the family vacation and was solving the cube in under a minute shortly thereafter. I've long since forgotten the patterns, but I bet the topologist could still solve it.

    2. Re:Rubik's Cube by Hank+the+Lion · · Score: 1

      [How to solve Rubik's cube]: Look up the solution... there's no way that someone works out how to do it without learning the solution... the solution required study from specialized people.

      If you don't really like puzzles, you're right.
      When I bought my Rubik's Cube (was that in '82?), it was because it was a complete enigma to me.
      I simply had to have it because I did not understand it one bit.
      Then I just started to turn, and turn, and turn, and gradually I started recognizing patterns in what specific combinations of turns would do.
      In about two weeks, I could solve it reliably.
      After some more practice, I could do it in one and a half minute.
      Later, I learned from a book how I could do the last face more efficiently. It brought my time down to about 45 seconds.
      But now, 22 years later, I can still do it the way I originally found out. In about two minutes. Because I understood what I was doing. The way I learned from the book is completely gone.

      And about that 'study from specialized people' bit: I was just a highschool kid then...

    3. Re:Rubik's Cube by ArsenneLupin · · Score: 1
      The solution is easy to learn as an algorithm, but understanding how it works and reaching those conclusions without help... is a wild leap.

      Not that difficult. A short while after the Rubik's cube came out, there were a number of knock-off tools based on other geometric shapes. My sister an I had a isocahedron shaped variant.

      We still managed to work out an algorithmic solution by experimentation and taking meticulous notes. Just two afternoon's work for high school kids (... but we did know the plain Rubik cube's solution beforehand, and knew that in order to tackle the problem, we would need to progress by "levels").

      The general trick is to figure out two different ways of undoing/redoing the "levels" that you already have (for instance rotate one piece out of the top level, and then move it back it using a different method). Then observe the effect of the concatenation of both move sequences on the next level (by comparing the final state of that level with your notes that you took before the sequence). From there on, it's pretty easy to work your way all through to the "bottom" level. It takes some amount of discipline (you need to take notes of every move you do), but it's definately not out of reach off two high-school kids.

      Granted, the isocahedron may have been easyer than the original cube (more axles, thus more degrees of freedom?), but on the other hand took more patience (many more "levels" than the cube, which only has 3).

  57. Re:I will help YOU get a JOB! (Programming puzzles by binary42 · · Score: 1

    yeah... just saw that lower on this page. nifty. Here is correct formatting ;) a = (a<<3) - a;

    --
    ruby -le"32.times{|y|print' '*(31-y),(0..y).map{|x|~y&x>0?' .':' A'}}"
  58. Traffic by FlunkedFlank · · Score: 3, Informative

    The pic in the article reminds me of Traffic, that awesomely addicting old Palm game (based on a real-world sliding block puzzle). I wish there was a PocketPC version!

    1. Re:Traffic by AgBullet · · Score: 1

      There is! Not free though...

      http://www.clickgamer.com/moreinfo.htm?pid=109

    2. Re:Traffic by FlunkedFlank · · Score: 1

      Sweet! Thanks for the tip!

  59. Another... by EvanED · · Score: 1

    Here's the fruit of my thoughts on the exception:

    void print(int x)
    {
    double i = 1/(101-x);
    printf("%i ", x);
    print(x+1);
    }

    int main()
    {
    try{ print(1); }
    catch(...){}
    }

    I suspect this is closest to what they are looking for.

  60. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    312211

    ?

  61. Re:I will help YOU get a JOB! (Programming puzzles by LnxAddct · · Score: 3, Interesting

    It doesn't. It is simply a clever trick on the programmers part. Another quine, in perl is:
    $b='$b=%c%s%c;printf$b,39,$b,39;';printf$b,39 ,$b,39;
    Looks confusing right? Actually if you format it nicer it makes more sense:
    $b='$b=%c%s%c;printf$b,39,$b,39;';
    printf$b,39, $b,39;

    You'll see that $b is a string that is equal to the entire source code except for what b is equal to. (Give it some thought and it'll make sense). printf then prints b substituting %c%s%c with the appropriate values ( quotation marks and the value of $b in the middle). It's going to be hard for a non-programmer to grasp, but hopefully this helped.
    Regards,
    Steve

  62. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    'if' is outlawed for #2. If you could use if, even without goto, it'd be much, much simpler than what you say.

    And why do you go "using std::swap; ... swap(x,y);" instead of just saying "std::swap(x,y);"?

  63. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    I've got problems with #1: You can't write a valid (i.e. compiles without errors or warnings) C program without a semicolon. Every complete, valid C program must have a main() function. The main function must have a return statement (and each statement must end in a semicolon). (The return statement in main is optional in C++ but not in C.) So, the answer to #1 as stated is "you can't".

    I can write something without a semicolon that prints "Hello World" when passed through gcc, but it uses only the C pre-processor and does not result in a compiled program, therefore it can't really be called a C program:

    #error Hello World

  64. Re:I will help YOU get a JOB! (Programming puzzles by Refrozen · · Score: 0

    For number 11, it states you cannot just echo the source. :-(

    Other then that, you are a flippin' genious.

  65. Re:I will help YOU get a JOB! (Programming puzzles by EvanED · · Score: 1

    "7. What's hard about that? 1. Sort. 2. if val[k]== val[k-1] dump it."

    Okay, now do it in faster time. I bet that they want a better solution.

    Here's a somewhat related problem from my MS interview:
    You have an array of n integers in the range 0 to n-1. Write a function that returns true if there are duplicates in the array and false if not. That runs in O(n) time. Without allocating extra storage.

  66. Re:I will help YOU get a JOB! (Programming puzzles by simcop2387 · · Score: 1

    simple offer them candy for their passwords!

  67. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    All pretty intro puzzles. Btw if is not a loop, its a conditional statement.

  68. Re:I will help YOU get a JOB! (Programming puzzles by orangesquid · · Score: 1

    [13. identical to 3]
    8. this is just graph traversal; keep track of all visited nodes (mark them, or make your own list of them)
    7. nearly same technique as #8, but with just the numbers
    12 involves a bit of work, but doesn't sound difficult. just keep careful track of everything.
    14 is ambiguous... is this an unordered set? or an order-critical list? the list is slightly easier, but, the set subgroups can be generated from the list subgroups by ordering each subgroup and removing duplicate ones.
    2:
    a(int c){printf("%d ",c);(c^100)&&a(c+1);}
    b(int c){printf("%d ",c,(c^100)&&b(c+1));}
    main(){a(1);puts("\n");b(1 );puts("\000");}

    10:
    d(int x){
    int i;
    i = x&1;
    x&&d(x>>1);
    printf("%d",i);
    }

    main(){
    d(1234);
    puts("");
    }

    11 can be generated by this prog:
    main(){
    char q[1]={34};
    char x[3]={98,61,34};char y[3]={99,61,34};
    char*a=
    "main(){char q[1]={34};"
    "char x[3]={98,61,34};char y[3]={99,61,34};"
    "char*a=";
    char*b=";char*";
    char*c=
    ";"
    "write(1,a,strlen(a));"
    "write(1,q,1);"
    "write(1,a,strlen(a));"
    "write(1,q,1);"
    "write(1,b,strlen(b));"
    "write(1,x,3);"
    "write(1,b,strlen(b));"
    "write(1,q,1);"
    "write(1,b,strlen(b));"
    "write(1,y,3);"
    "write(1,c,strlen(c));"
    "write(1,q,1);"
    "write(1,c,strlen(c));"
    "}";
    write(1,a,strlen(a));
    write(1,q,1);
    write(1,a,strlen(a));
    write(1,q,1);
    write(1,b,strlen(b));
    write(1,x,3);
    write(1,b,strlen(b));
    write(1,q,1);
    write(1,b,strlen(b));
    write(1,y,3);
    write(1,c,strlen(c));
    write(1,q,1);
    write(1,c,strlen(c));
    }

    --
    --TheOrangeSquid Is it any wonder things seem so awry? We swim in a sea of confusion and don't have to think to survive
  69. Re:I will help YOU get a JOB! (Programming puzzles by Refrozen · · Score: 0

    312211

    I've seen that one before though. It's just taking the last one, and incrementing the numbers across so they are the same... Wow, it's hard to explain

  70. Re:I will help YOU get a JOB! (Programming puzzles by EvanED · · Score: 1

    alderaan 7% cat crap.c
    #include <stdio.h>

    int main ()
    {
    if(printf("Hello World\n")) {}
    }
    alderaan 8% gcc crap.c
    alderaan 9% a.out
    Hello World
    alderaan 10% gcc --version
    gcc (GCC) 3.3
    Copyright (C) 2003 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions. There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    alderaan 11%

  71. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    #2 (Thewe two functions could probably be combined, but I'm not going to bother optimizing and factoring coe for Slashdot. This gives you the idea, at lesat:)

    #include <stdio.h>

    int printDown(int num)
    {
    return num ? (printf("%d ", num), printDown(num-1)) : 0;
    }

    int printUp(int num, int stop)
    {
    return (num <= stop) ? (printf("%d ", num), printUp(num+1, stop)) : 0;
    }

    int main(void)
    {
    printDown(100);
    printf("\n");
    printUp(1, 100);
    printf("\n");
    return 0;
    }

  72. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    #4: newNum = (num << 3) - num;

  73. Re:I will help YOU get a JOB! (Programming puzzles by Lehk228 · · Score: 1

    5) x= (x << 3)-x;

    --
    Snowden and Manning are heroes.
  74. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    What's the difference between #3 and #13?

  75. More computer assisted puzzles by AndrewStephens · · Score: 3, Informative

    This idea is not new, the guy that runs www.puzzlebeast.com uses a similar program to generate ingenious puzzles. Read about the program he uses, then check our his java applets if you have a an hour or eight to spare.

    --
    sheep.horse - does not contain information on sheep or horses.
  76. Re:I will help YOU get a JOB! (Programming puzzles by EvanED · · Score: 1

    Though to be fair,

    alderaan 2% gcc -Wall crap.c
    crap.c: In function `main':
    crap.c:6: warning: control reaches end of non-void function
    alderaan 3%

    Didn't think to compile with -Wall.

  77. Re:Question 3 Solved (alternative method) by JasonSkywalker · · Score: 1

    Good points. I yield.

    --
    I have Unix underpants.
  78. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    Shame on you for having . in your path.

  79. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    What's the difference between #3 and #13?

    -10

  80. Re:I will help YOU get a JOB! (Programming puzzles by Malawar · · Score: 0

    Just say it out loud to get the next line... 1 - one one 11 - two ones 21 - one one one two 1112 - three ones one two 3112 - one three two ones one two 132112 and so on..

  81. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    add them and see if you get n(n-1)/2 ? easy enough...

  82. Re:nice to know by 808140 · · Score: 0

    I presume you're making a joke, but in case you aren't, soluble also means solvable. It's quite common to see it used that way in mathematical papers and journals.

  83. Solutions for Questions 1-6 by wtarreau · · Score: 1
    Questions 1-6 are relatively easy, it takes about 10 minutes to solve them all.

    1. Write a "Hello World" program in 'C' without using a semicolon.

    You don't need a semicolon after a closing brace :
    main() {
    if (printf("Hello world !\n")) {}
    }
    2. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;

    Use recursion instead of the loop. A pre-initialized increment is reverted once it reaches 100 (using a division) :
    int inc(int i, int j) {
    printf("%d\n",i);
    j -= (i/100) * 2;
    i += j;
    return i ? inc(i, j) : 0;
    }

    main() {
    inc(1, 1);
    }
    3. C/C++ : Exchange two numbers without using a temporary variable.

    This one is well known to people who write assembler code, simply use 3 XOR. Note that Q13 is the same.
    #define SWAP(a, b) { a^=b; b^=a; a^=b; }
    4. C/C++ : Find if the given number is a power of 2.

    A power of 2 has only one bit equal to 1. So the same number minus 1 has this bit set to zero, and all bits below set to 1. If you AND the two values, you get zero only if the number is a power of 2 or zero.
    int ispower2(int i) {
    return i && !(i & (i-1));
    }
    5. C/C++ : Multiply x by 7 without using multiplication (*) operator.

    To multiply by anything without using a multiplication operator, do exactly as you would if you didn't have the 'mul' instruction on your
    processor : binary shifts & adds. 7 == 4 + 2 + 1, so x*7 == x*4 + x*2 + x*1
    int times7(int i) {
    return (i<<2) + (i<<1) + i;
    }
    6. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7

    Relation between 7 and 4 ? 7+4==11, 7^4==3, 7*4==28, etc... Note that other values give undefined results.
    int f74_xor(int i) {
    return i ^ 3;
    }

    int f74_sub(int i) {
    return 11 - i;
    }

    int f74_div(int i) {
    return 28 / i;
    }

    int f74_if(int i) {
    return (i == 4) ? 7 : 4;
    }
    Other questions take longer code and need real boring programming. Q10 is the same as Q5. I've seen a program which did Q11 once. The trick is *not* to lose time trying to put the program into a string, and instead, call a function which adds all necessary delimitors and escape where necessary. Q13 is Q3.

    Have fun,
    Willy
    1. Re:Solutions for Questions 1-6 by xenocide2 · · Score: 1

      Actually, I'd be careful on #1. Its quite possible for the compiler to see an empty if body and just optimize the entire program away. Of course, almost every task listed there is an exercise in demonstrating how poorly your complier follows the standard, and generally speaking anyone solving problems that way is only making trouble for their replacement.

      --
      I Browse at +4 Flamebait

      Open Source Sysadmin

    2. Re:Solutions for Questions 1-6 by HeghmoH · · Score: 1

      If your if statement's conditional has side effects, and the compiler optimizes away the if statement because the body is empty, you have a broken optimizer. It's possible, but it would be a bug in the compiler.

      --
      Mod down posts with a "Free Mac Mini/iPod" sig, they're spam!
    3. Re:Solutions for Questions 1-6 by xenocide2 · · Score: 1

      Yes, you'd have a broken optimizer. But once you leave the realm of gcc and intel compilers for god knows what other platform and compilers, chances are the compiler you'll be working with isn't very careful about the wholer standardized C thing.

      --
      I Browse at +4 Flamebait

      Open Source Sysadmin

  84. Re:I will help YOU get a JOB! (Programming puzzles by EvanED · · Score: 1

    Nope.

    Say you have [0,1,2,3]. They sum to 6 right enough, but so does [0,2,2,2].

  85. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    Wait... the integers themselves are limited to the range 0 to n-1? Easy.... I'm going to assume I can at least have a couple of local variables here, since I'm pretty sure this is impossible without at least an iterator.

    for (i=0; i<n-1; i++) {ttl = val[i]; cmp += i;}
    if (ttl != cmp) return true;
    return false;

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  86. #2 solution by akuma(x86) · · Score: 1

    Perhaps they are looking for a recursive solution.

    void print_down(int base)
    {
    if (base == 0) {
    return;
    } else {
    printf("%d\n", base);
    print_down(base - 1);
    }
    }

    Hmmm, no conditionals?

    Then you're asking for a C++ template solution. You can get templates to evaluate conditionals at compile time to generate the correct code. This makes my head hurt.

    1. Re:#2 solution by UfoZ · · Score: 1

      #include <iostream>

      template<int N>
      class CountUp {
      public:
      void operator() ()
      {
      std::cout << N << std::endl;
      CountUp<N+1> c;
      c();
      }
      };

      template<>
      class CountUp<100> {
      public:
      void operator() ()
      {
      std::cout << 100 << std::endl;
      }
      };

      template<int N>
      class CountDown {
      public:
      void operator() ()
      {
      std::cout << N << std::endl;
      CountDown<N-1> c;
      c();
      }
      };

      template<>
      class CountDown<1> {
      public:
      void operator() ()
      {
      std::cout << 1 << std::endl;
      }
      };

      int main()
      {
      CountUp<1> c;
      CountDown<100> d;
      c();
      d();
      return 0;
      }

      // Yay for template metaprogramming :D

    2. Re:#2 solution by Ben+Hutchings · · Score: 1

      It's not that difficult:

      #include <iostream>

      template<int n>
      void foo()
      {
      foo<n-1>();
      std::cout << n << "\n";
      }

      template<>
      void foo<0>()
      {}

      int main()
      {
      foo<100>();
      }

    3. Re:#2 solution by LazyBoy · · Score: 1
      Hmmm, no conditionals? Then you're asking for a C++ template solution.

      Or,

      int print_down(int base) { return base == 0 ? 0 : (printf("%d\n", base), print_down(base - 1)); }
      --

      If Chaos Theory has taught us anything, it's that we must kill all the butterflies.

    4. Re:#2 solution by akuma(x86) · · Score: 1

      The ? : operator is a conditional.

    5. Re:#2 solution by tepples · · Score: 1

      The ? : operator is a conditional.

      You may have misread the problem:

      Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1

      The problem stated nothing about ?: or conditionals in general; it banned only if and looping constructs.

    6. Re:#2 solution by EvanED · · Score: 1

      Banning if but not ?: is silly since you can type

      (condition) ? (iftrue) : (ifelse) ;

      is equivalent to

      if (condition) (iftrue); else (ifelse);

      I would treat the banning of ?: as implied.

  87. Re:I will help YOU get a JOB! (Programming puzzles by orangesquid · · Score: 1

    n integers, range 0 to n-1, means that, if there is a duplicate, there will be one missing. (but this would only help if the array were known to be sorted)

    it also means that any value in the array will also be a valid index into the array. we can flag the values we find by marking the equivalent position in the array by adding N. if we find a position is >=N when we go to add N to it, we must have had a duplicate. in a way, this does use extra storage, but, we'll assume we aren't going from 0 to MAXUINT, so there's some extra bits floating around anyway.

    i hacked up something like this:
    checkdup(int z[10]) {
    int j, i;
    for(i=0;i<10;++i) {
    printf("%02d %02d %02d %02d %02d %02d %02d %02d %02d %02d\n",
    z[0], z[1], z[2], z[3], z[4],
    z[5], z[6], z[7], z[8], z[9]);
    j = z[i];
    if(j>=10)
    j -= 10;
    if(z[j]>=10)
    return 1;
    z[j] += 10;
    }
    return 0;
    }

    main(){
    int a[10]={9,4,7,0,1,2,3,5,8,6};
    int b[10]={2,9,5,7,2,0,8,4,3,1};
    printf("%d %d\n", checkdup(a), checkdup(b));
    }

    --
    --TheOrangeSquid Is it any wonder things seem so awry? We swim in a sea of confusion and don't have to think to survive
  88. Ob. Soviet Russia Joke by Impeesa · · Score: 0

    The point was to prove Russians are better than us?

    In Soviet Russia, we are better than Russians!

    Yeah, I'm still trying to figure it out too.

  89. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    Whoops. I just noticed some of my content was missing.

    4. B. shoudl have said for (i=0; i<LONG_BITS; i++) printf...

    Assuming a long int. Appropriate changes otherwise.

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  90. Re:I will help YOU get a JOB! (Programming puzzles by akuma(x86) · · Score: 1

    >> 14. Given an array (group) of numbers write all the possible sub groups of this group.

    There are 2^N sub-groups in an array of N elements (inluding the NULL group). There is a 1-to-1 mapping from the binary represenatation of all numbers from 0 to (2^N)-1.

    Let's say our array has 3 elements

    1 2 3

    The subsets are

    000 = { x x x }
    001 = { x x 3 }
    010 = { x 2 x }
    011 = { x 2 3 }
    100 = { 1 x x }
    101 = { 1 x 3 }
    110 = { 1 2 x }
    111 = { 1 2 3 }

  91. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    Just to be pedantic, I didn't -just- echo the source. I echoed "an exact copy of the source".

    Besides, it said I couldn't echo the source -file-, and by 'echo', I assume they meant cat, since echoing the source file would probably result in something resembling stupid_problem.c[newline]. Either way, echoing "the source file" wouldn't make the output be "an exact copy of the source".

    :-)

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  92. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    Ugh, yeah, that doesn't work.... :-|

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  93. Re:I will help YOU get a JOB! (Programming puzzles by dj245 · · Score: 1
    But if you really want to stump a slashdotter: 15. Go outside and meet girls.

    Oh but that one is easy. Go downtown and get a hooker! It decreases the rejection rate from 100% to a more managable 82%, for me anyway.

    --
    Even those who arrange and design shrubberies are under considerable economic stress at this period in history.
  94. FULL SOLUTION by Kelerain · · Score: 3, Informative

    I've worked through that solution, and writen up a much more aproachable version. Slashdots lameness filter prevents me from posting it in full, so I will link to it on my website here:
    http://www.abysmalstudios.com/files/quzzlesolution .txt

    although that will most certainly disapear in a while, as I clean up my server from time to time. In the interests of preserving history, I'll give you the excessively condensed version:

    The goal is to move the A block in the far upper left corner, to the far upper right corner.

    ----
    AA11
    AA23
    **23 - starting puzzle condition (* is a space)
    4556
    4778
    ----

    The code below gives a block (1-8 or 'A') and an u/d/l/r direction.
    AD1LL2U3U6UL3DD2R6UUAR4UU5L7L8LU7RR5D8 LLAD6DL2L3UU AR8RU5U7LLAD8RR2D1R4U6DL2L8LU3D1R2U6RR2D4D1LL8U3U6 UAU7RR5D2D6L8D1R4U2LAL3DD1R8R6R4R2UUAL6DD8L3U6RAR2 DD4L8LUAU6LL7U5RR6DR7L5L3DDAR8DD4R2UU8LD4D2D1LAU

    You will have to break it up manually, because slashdots lameness filter wont even let me put line breaks in. Grab a copy of the text from my site while you can!

    1. Re:FULL SOLUTION by Anonymous Coward · · Score: 3, Informative

      Near the end of the solution is the sequence:

      5RR6DR7L5L

      The correct sequence is:

      5RR6DL7L5L

      Note that changes only one move from R to L.

      Other than that, the solution works wonderfully :-) Thanks for posting it.

    2. Re:FULL SOLUTION by Zro+Point+Two · · Score: 2, Funny

      hardest puzzle? bah...10 minutes and 37 moves total.
      lets see if i can reproduce it here for people.
      AD...1L...1L...2U...3U...6U...6U...3D...3 D...2R... 6U...6U...AR...4U...4U...5L...7L...8L...8U...7R... 7R...5D...8R...8R...AD...6D...6L...2L...3U...3U... AR...8L...8U...5U...7L...7L...AD

      It's amazing what you can learn playing the 11th Hour :)

      --
      Zro . two

      "I come from Canada...they say I'm slow....eh?"
    3. Re:FULL SOLUTION by Zro+Point+Two · · Score: 1

      oops, that second 6U should be 6L... should have looked a bit closer to my typing... my bad.

      proper solution below.

      AD...1L...1L...2U...3U...6U...6L...3D...3D...2R. .. 6U...6U...AR...4U...4U...5L...7L...8L...8U...7R... 7R...5D...8R...8R...AD...6D...6L...2L...3U...3U... AR...8L...8U...5U...7L...7L...AD

      --
      Zro . two

      "I come from Canada...they say I'm slow....eh?"
    4. Re:FULL SOLUTION by Andorion · · Score: 1

      You mixed some Ls and Rs, and this moves the block to the bottom left corner, not upper right corner like you're supposed to.

    5. Re:FULL SOLUTION by Zro+Point+Two · · Score: 1

      hmmm...didn't see where it was supposed to end up in the article, so had just assumed that it was like Dads and needed to go to the bottom right.

      Glad I was wrong though, cause that was a little easy to be hailed as the hardest simple puzzle.

      Thanks for the correction Andorion.

      --
      Zro . two

      "I come from Canada...they say I'm slow....eh?"
    6. Re:FULL SOLUTION by nachoboy · · Score: 2, Informative

      The solution on your website [Last-Modified: Sat, 04 Dec 2004 08:52:13 GMT] mislabels move 69 as move 68, and move 72 is noted as 6DR but should be 6DL.

      Despite that, the instructions were quite helpful. Thank you.

    7. Re:FULL SOLUTION by Feanturi · · Score: 1

      That gets you to the bottom-right, not the top-right as the solution demands. You only got about halfway there.

    8. Re:FULL SOLUTION by Kelerain · · Score: 1

      Glad I could help, and thanks for the corrections, I've posted a fixed version. I figured at 1 am there were bound to be a few, but luckily the R would mean taking it off the board, so the change was obvious.

      It surprised me that the full solution wasn't documented in a post sooner, unless I missed something, and again, I'm glad my time spent geeking out over the puzzle instead of getting some much needed sleep wasn't wasted!

    9. Re:FULL SOLUTION by Anonymous Coward · · Score: 0

      I believe step 83 should be 1LL if you want it 100% correct...

      -Allan

  95. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    2.

    #include <iostream>

    using namespace std;

    class incr
    {
    public:
    incr ()
    {
    cout << i++ << endl;
    }
    ~incr ()
    {
    cout << --i << endl;
    }

    private:
    static int i;
    };

    int incr::i = 1;

    int main ()
    {
    incr k[100] = {};
    }

  96. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    That works, but to put it in mathematical terms: each line is a run length encoding of the previous. (With the run length preceding the symbol, rather than following it.)

  97. Re:I will help YOU get a JOB! (Programming puzzles by Jason+Foo · · Score: 1

    #include <stdio.h>

    void (*function[2])(int);

    void print(int i)
    {
    printf("%d\n", i);
    function[i / 100](i + 1);
    /* put printf here instead to count down */
    }

    void nop(int i)
    {
    }

    int main(void)
    {
    function[0] = print;
    function[1] = nop;

    print(1);

    return 0;
    }

  98. Re:I will help YOU get a JOB! (Programming puzzles by mrchaotica · · Score: 1
    11. Well, since C isn't a scripting language I don't see how that's possible.
    Wanna bet? pself.c:
    main(){char*p="main(){char*p=%c%s%c;(void)printf(p ,34,p,34,10);}%c";(void)printf(p,34,p,34,10);}
    No, I didn't write it. However, I did solve #3 (and #13) in another post
    --

    "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

  99. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    The question is: How did you solve 7?

  100. Re:I will help YOU get a JOB! (Programming puzzles by Kevin143 · · Score: 1

    11. Well, since C isn't a scripting language I don't see how that's possible.

    It's very possible. It's called a quine. They're fascinating, and it's possible for programs to output themselves in all sorts of different interesting ways.

    This page is a great resource.
  101. Re:I will help YOU get a JOB! (Programming puzzles by Jason+Zaman · · Score: 1

    switch...case could work

  102. Easy C++ solution by johannesg · · Score: 1
    template<typename T>
    void Swap (T &a, T&b)
    {
    const T temp = a;
    a = b;
    b = temp;
    }
    And before you complain about any alleged use of variables, 'temp' is a constant ;-)

    And unlike those oh-so-clever xor based solutions, this one works for any type that supports assignment (including floating point numbers and classes that have operator= overloaded).

    Plus, you can actually expect to be able to understand it in five years time when you do to some maintenance on the code.

  103. Re:I will help YOU get a JOB! (Programming puzzles by Cygnus78 · · Score: 1

    I have solved number 7. Just remove nr 3 and 13.

  104. Number one revisited by johannesg · · Score: 1
    I'm kinda partial to this one:

    #error Hello world!
    But only if I had already established that the interviewers have a sense of humor ;-)
  105. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    Write a "Hello World" program in 'C' without using a semicolon. I want to see this one.

    #include
    int main () {printf("Hello World\n")}

    Opps Gcc some modern version says where is the ;.

  106. Re:I will help YOU get a JOB! (Programming puzzles by mrchaotica · · Score: 1
    Alternatively, you could get this warning instead:
    $ gcc -Wall hellonosemi.c
    hellonosemi.c:4: warning: return type of `main' is not `int'
    (using void as the return type for main)
    --

    "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

  107. What's so current about A*? by xenocide2 · · Score: 1

    Judging by actual research, the current AI approach would be to model the puzzles with a gaussian curve, then build a Bayesian network to find the most frustrating puzzle.

    --
    I Browse at +4 Flamebait

    Open Source Sysadmin

    1. Re:What's so current about A*? by Anonymous Coward · · Score: 0

      A* is still widely used (in fact, you would probably use it for a probabilistic approach to this puzzle).

  108. Re:I will help YOU get a JOB! (Programming puzzles by scolbe · · Score: 1

    15. Go outside and meet girls.


    oh well I've been told that's easy, (uh.. you dont have to get the girls to talk back, right??), now if I could only remember how to get this damn door open.
    --
    Lead me not into temptation... I can find it myself 8+)
  109. Re:I will help YOU get a JOB! (Programming puzzles by dgatwood · · Score: 1
    Here's a thought that I'm too tired to try to prove. I don't think there's any way for the numbers to total the same value -and- for the number of instances of each bit to be even or odd at the same frequency, so...

    accum = 0;
    xor = 0;
    xorb = 0;
    for (i=0; i&lt;n i++) {
    accum += val[i];
    xor ^ val[i];
    xorb ^ i;
    }

    if (accum != (2 * n) - 1) return true;
    if (xor != xorb) return true;

    return false;
    Or it could just be the sleep deprivation talking. Anybody?

    --

    Check out my sci-fi/humor trilogy at PatriotsBooks.

  110. Re:I will help YOU get a JOB! (Programming puzzles by Trillan · · Score: 1

    Just looking through that list, some of those questions strike me as quite clever (#2/4) whereas others strike me as pure syntatical trickery (#1) or truly bad coding practices (#3/13, for instance).

    I don't know how I'd judge the results of #3/13. They're clever, but they've done something that I never want to see in code. (Okay, okay... there are some exceptions, but in general it's true.)

  111. Java Version by ex+falso+quodlibet · · Score: 1

    I was given a wooden puzzle very similar to this several years ago - it has the same layout and initial state as the puzzle that one reader calls 'Klotski' but I know it as 'Free The Prisoner'. A couple of my students coded it up in Java a few years ago - you can find it at: http://activation.braininavat.net/archives/000069. html

    1. Re:Java Version by Anonymous Coward · · Score: 0

      Well that was very fun. I wish it had a timer or move counter though, but I think I did it in 20 minutes, give or take. No idea how many moves.

  112. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    I always thought Microsofts favourite one was "Write an operating system without checking for buffer overflows".

  113. Re:I will help YOU get a JOB! (Programming puzzles by orangesquid · · Score: 1

    I'm not sure I follow.. care to rephrase that, and I can reparse? ;)

    But, as I understand it, it sounds like a good idea, but, I'm not sure it would work:

    1+2+3+4+5=15
    001,010,011,100,101={2,2,3}={E,E,O }={0,0,1}

    1+2+2+5+5=15
    001,010,010,101,101={2,2,3}={E,E,O }={0,0,1}

    As long as a bitwise carry doesn't occur when modifying two values by some +Z and -Z, respectively, the XOR trick will always fail to detect a change (like a parity error where two bits flip).

    There might be a similar technique that would work, perhaps? It does seem like it's going in the right direction... maybe use an error-correction technique instead of a simple parity technique? =)

    --
    --TheOrangeSquid Is it any wonder things seem so awry? We swim in a sea of confusion and don't have to think to survive
  114. Messing with a Rubik's Cube by Westacular · · Score: 1

    Do it to one of them, and it's unsolvable -- do it to two and it's solvable again; there is a even/odd parity to the edge pieces so it's only unsolvable if an odd number of edge cubelets have been flipped from their starting state.

    Whether or not the cube is solvable (even when mixed up) can be determined in a fairly straight-forward manner, but most people wouldn't bother to do this. In any case, once the cube is practically solved it becomes obvious when, of the last few edge cubelets to orient, an odd number need flipping.

    Similarly, there is a modulo-3 parity involved with the corner piece orientation, and the total "twist" remains the same (at 0) when normally manipulating the cube, while randomly turning corner pieces could result in an unsolvable total twist of -1 or +1. In any case, there isn't anything "more" unsolvable that can be done by twisting multiple corners that couldn't be done by simply twisting a single corner cubelet either clockwise or counterclockwise. As with the edges, it's straight-forward but normally not worthwhile to determine ahead of time if the twist parity of the cube is what it should be, and it won't truly pose a problem until all of the corners have been properly oriented save one, at which point the tampering becomes obvious.

    The Rubik's Cube (Rubik's, not Rubix -- named for Professor Erno Rubik, its inventor; he originally called it the Magic Cube but its name was changed to bear his when it started to get marketed worldwide) has a third form of parity involved that depends on the transposition of the corner and edge pieces. Swapping a single pair of edge pieces or a single pair of corners (but not both, or any even-numbered combination of pairs -- these are all solvable states) will result in the pieces of the cube not being able to be positioned properly, which is again annoying but obvious when the cube is mostly solved. One can determine if this is the case for some random cube, but I can't off the top of my head think of an algorithm that's as easy for a person to use as the ones for the other two cases.

    So, to review: supposing you took a Rubik's Cube apart and assembled it back together at random, you have a 1/12 change of this random permutation being one that the puzzle could be solved from -- there's a 1/2 chance that the edge-orientation parity is even (otherwise, at the end it will look like a single edge has been flipped), a 1/3 chance of getting the corner-orientation parity correct (otherwise it will appear like a single corner has been twisted either clockwise or counterclockwise), and a 1/2 chance that the positions of the pieces are such that they can be place properly (otherwise, it will appear as if a single pair of corner or edge pieces have been swapped -- these two cases are equivalent and can be moved between)

  115. Re:I will help YOU get a JOB! (Programming puzzles by binkzz · · Score: 1

    I remember writing my first quine in basic on the commodore 64:

    10 LIST

    --
    'For we walk by faith, not by sight.' II Corinthians 5:7
  116. The solution by kipsate · · Score: 1, Interesting

    Xn means: move piece X with n squares.

    a1, 12, 21, 31, 62, 32, 21, 62, a1, 42, 51, 71, 82, 72, 51, 82, a1, 62, 21, 32, a1, 82, 51, 72, a1

    Try it here

    --
    My karma ran over your dogma
    1. Re:The solution by brentcastle · · Score: 1

      nice try, but thats not the solution according to the page. you need to move it to the UPPER-right, not the bottom right. anyone could get it to the bottom right :-). keep trying.

      --
      http://www.brentcastle.com
    2. Re:The solution by Feanturi · · Score: 1

      Same thing as I pointed out above. Those moves only go about half-way to the solution, you have to get A to the TOP-right. On the very link you give, the goal corner is marked in black, have another look.

  117. Re:I will help YOU get a JOB! (Programming puzzles by binkzz · · Score: 1

    I don't suppose this would count as a quine?

    test.c:1: error: syntax error before '.' token

    Or what about:

    --
    'For we walk by faith, not by sight.' II Corinthians 5:7
  118. lets do it the hard way 'cause we got computers by frovingslosh · · Score: 1
    The challenge, then is to make a computer program that can compute the probability of a random assemblage of the tiles for solvability.

    Some things are just too simple to solve by a program. This is one of them. There are two states that the puzzle can be in, solvable or unsolvable. Any exchange of pieces changes that state. It might seem that there being 15 pieces rather than 16 has some effect on it and complicates things, but it doesn't. You get the exact same problem if you imagine that there are 16 pieces arranged randomly, and then that piece 16 is discarded before the puzzle is attempted to be solved. There is no preference at all for the solvable or unsolvable state when 16 pieces are put in a 4x4 matrix, so therefore there is no preference when 15 pieces and a blank space are put in a 4x4 matrix. So the solution, no matter how complex you make the computer program, will have to be 50%.

    --
    I'm an American. I love this country and the freedoms that we used to have.
    1. Re:lets do it the hard way 'cause we got computers by Anonymous Coward · · Score: 0

      That would be true, IF it were a puzzle with uniformly sized/shaped pieces. It isn't.

    2. Re:lets do it the hard way 'cause we got computers by cgibbard · · Score: 1

      the discussion was about the 15 puzzle, not the puzzle in the article.

    3. Re:lets do it the hard way 'cause we got computers by Anonymous Coward · · Score: 0

      You're saying that because there are two mutually exclusive properties that the "probability" of each occuring must be 1/2? Not even.

    4. Re:lets do it the hard way 'cause we got computers by frovingslosh · · Score: 1
      You're saying that because there are two mutually exclusive properties that the "probability" of each occuring must be 1/2? Not even.

      NO, I certainly didn't say that. I said that in this case the two probabilities are 50%. That's clear from the fact that any swap of 2 tiles results in a change of state, and because there is clearly no preference for one state or the other in the original random selection of the 16 tiles (or 15 tiles and a space).

      You can confirm this another way. Look at the case of having only 3 tiles in a 4 tile space. computer the perminations and how many of them are solvable (you can do it in your head). The answer is 50%. Enlarge the puzzle, to say 5 tiles in a 2x3 space. The probability doesn't change (if you think it does you would have to justify in which bias (solvable or unsolvable) it changes, and there is no dirrerence in either state). Enlarge it again. And so on, up to a 4x4 puzzle or larger.

      So if you want to support your Not even statement, perhaps you can offer your own theory about what the probability is? And do you somehow think it favors solvable or unsolvable?

      --
      I'm an American. I love this country and the freedoms that we used to have.
    5. Re:lets do it the hard way 'cause we got computers by DavidTC · · Score: 1
      A better way to state it might be:

      Lay down 14 pieces. These pieces do not matter. They can go anyway.

      If you put the two remaining pieces one way, it is solvable. If you put them the other way, it is unsolvable.

      Any combination of 14 pieces already laid down results in two remaining possibilities, one right, and one not. Hence the probability is always 50/50.

      You can even say 'We're going to make the first line 5, 2, 7, and 11.', and the odds are still the same, there's no way to alter them. (Well, unless you specificed 15 pieces, and then it would either be solvable or unsolvable with 100% odds, because there's only one possible position. But that's silly.)

      --
      If corporations are people, aren't stockholders guilty of slavery?
    6. Re:lets do it the hard way 'cause we got computers by Anonymous Coward · · Score: 0

      I apologize for not having offered my own theory, yours is obviously superior to my non-theory.

      I verified the 2x2 case, it is indeed solvable half of the time. What doesn't seem obvious to me is that, for example

      1 2 3
      4 5 6
      8 7

      is unsolvable. how do you know you can't do some really clever rearranging? It's tempting to see it as "obvious", I admit.

  119. Re:I will help YOU get a JOB! (Programming puzzles by nogginthenog · · Score: 1

    It's worrying that more people *didn't* see this solution.

  120. article's author puzzled by grammar by Anonymous Coward · · Score: 0

    Mr. Lewis knows his puzzle is the world's hardest of it's type as his computer considered every possible puzzle among ten's of thousands, each having an often long sequence of moves.


  121. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0
    $ cat test.c
    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
    if (printf("Hello World\n"), exit(EXIT_SUCCESS), 0) {}
    }
    $ gcc -Wall -pedantic test.c
    $
  122. Was recently asked this one on an application... by Anonymous Coward · · Score: 0

    Similar to #5 above:

    "Given a very simple microprocessor with no multiply, divide, or subtract instructions what algorithm would you use to implement an integer divide by 7? Assume that the microprocessor and your algorithm will be part of real-time process control system. Explain why you think your algorithm is a good choice for use in a real-time control system."

    I suppose the goal of the question was to construct an algorithm without doing the simple O(n/m) version. They like my answer, and offered me the job :). So, yes these exercises can help you get hired.

  123. Play OriMazes in JavaScript by johntromp · · Score: 2, Informative
    Orimazes are sliding block puzzles in disguise where the blocks are all unit size but limited to either horizontal or vertical movement. There is only one free spot, so sliding the blocks is equivalent to moving the free spot, which gives it the flavor of a maze.

    The hardest 4x4 instance can be played at
    http://www.cwi.nl/~tromp/oriscript4.html
    while the hardest 5x5 instance is at
    http://www.cwi.nl/~tromp/oriscript5.html

    -John

    1. Re:Play OriMazes in JavaScript by slothman32 · · Score: 1

      What is the point? How do I win? I can move the square around but I don't know what to do. And what is the arrow piece? I can move across it in both directions.

      --
      Why don't you guys have friends or journals?
    2. Re:Play OriMazes in JavaScript by j.bellone · · Score: 1

      I'm assuming the top left... if so I finished it in 20 moves, website says a few dozen.

      --
      I'm f#$king magic!
    3. Re:Play OriMazes in JavaScript by Kegetys · · Score: 1

      It says "Get the target piece -- to the left.". That means you need to get the piece with the arrow to the left.

    4. Re:Play OriMazes in JavaScript by johntromp · · Score: 1
      Yes, the target piece (marked <-) has to be moved to the leftmost column.
      The optimal solution takes 40 moves, so I have no idea where your 20 comes from:-(

      See also the paper I wrote about it at http://www.cwi.nl/~tromp/orimaze.html

      -John

    5. Re:Play OriMazes in JavaScript by DavidTC · · Score: 1
      Erm...all 2D sliding puzzles move the free space. The only other way to do is a puzzle is to have it rotate, and you can only only do that in one direction in 2D, which isn't much of a puzzle. (Rotate the clock hands until they read 3:47.)

      (Note it would, in theory, be possible to build a 2D sliding puzzle with a back that 'tiles' could wrap around to, with no free space. I don't know of any puzzle like that, or if it would technically be 2D.)

      --
      If corporations are people, aren't stockholders guilty of slavery?
  124. Re:I will help YOU get a JOB! (Programming puzzles by tijsvd · · Score: 1
    This is what I thought of:

    int has_dups(int *array, int n) {
    int i=0, val;
    while(i<n) {
    val = array[i];
    if(val == i)
    i++; // already correct, advance
    else if(array[val] == val)
    return 1; // duplicate
    else { // swap
    array[i] = array[val];
    array[val] = val;
    }
    }
    return 0;
    }

    (How do you get indenting in here?) This swaps numbers in the array, with each swap putting at least one number such that array[i]==i. Each execution of the loop either swaps a number (max n times) or advances the index i (also max n times). The loop can thus never execute more than 2*n times, which is O(n).

  125. Paper? by beelsebob · · Score: 1

    Does anyone know if this guy has written a paper on the subject. It appears that his primary reason for doing this was as a piece of research, that just happened to produce a puzzle out of it. So, is there a paper?

    Bob

  126. Re:I will help YOU get a JOB! (Programming puzzles by ArsenneLupin · · Score: 1
    Is the code that important, or the solution in regular syntax?

    I think most people would find this difficult because they forget how to program in these languages

    Actually, only the questions 1 and 11 depend on syntactic knowledge of the language; the others are purely algorithmic, i.e. a valid answer could be described in plain English. And some questions, such as for instance 2 and 5 are downright trivial... Unless there is a hidden catch, or unless the goal of the questions is to test whether the candidate has chuzpa, rather than intelligence!

  127. Matlab programming competition by jpreen · · Score: 1

    Funnily enough the recent Matlab comp was along these lines: Main Page. Given a number of unknown grids of boxes of different weights a program was needed to solve the rearrangement problem as efficiently as possible.

  128. uhg somebody mod this up by Anonymous Coward · · Score: 0

    w00t arrays of functions & recursion

  129. small nitpick by muyuubyou · · Score: 1

    1 wasn't proper ANSI C. In ANSI C, main HAS TO return int. Picky teachers will "mod you down" for that.

    int main(void){if (printf("Hello World!\n")){}}

    (you left a parenthesis open)

    1. Re:small nitpick by Anonymous Coward · · Score: 0

      However, falling of the end of main without a value is bad behaviour as is invoking printf-like functions without providing prototypes.. try

      int main(void){if (puts("Hello World!"), exit(0)){}}

      nyah nyah.

    2. Re:small nitpick by Anonymous Coward · · Score: 0

      "error: void value not ignored as it ought to be"

    3. Re:small nitpick by Anonymous Coward · · Score: 0
      1 wasn't proper ANSI C. In ANSI C, main HAS TO return int. Picky teachers will "mod you down" for that.

      In proper ANSI C (or K&R, for that matter), there should NOT be a semicolon before a closing statement, and adding one is simply adding a superfluous null statement. So this is really a proper C hello world without a semicolon:

      int main(void) {
      return puts("Hello World!")
      }

      That gcc barfs on it reflects on gcc.
    4. Re:small nitpick by Anonymous Coward · · Score: 0

      What have you smoked?

  130. turtlelady13@earthlink.net by Anonymous Coward · · Score: 0

    That will teach ya.

  131. Re:I will help YOU get a JOB! (Programming puzzles by the_duke_of_hazzard · · Score: 1

    You can write that and you can't get indenting!? ;-)

  132. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    I don't know which is more horrible, your post, or the fact that someone modded you +1 insightful.

  133. Re:I will help YOU get a JOB! (Programming puzzles by ArsenneLupin · · Score: 1
    Shame on you for having . in your path.

    $ echo $PATH /usr/local/bin:.:/usr/bin:/usr/X11R6/bin:/bin:/usr /games:/opt/gnome/bin:/opt/kde3/bin:/usr/lib/java/ bin:.

    Shame on me for having . in my path twice!

    (SCNR)

    Or as the Governor of Texas would say...:

    $ echo %PATH%
    %PATH%

    Hmmm...

    $ set PATH

    Hmmm...

    $ help PATH
    sh: command not found: help

    Hmmm...

    $ echo /?
    sh: no matches found: /?

    Matches?!?! I'm looking for weapons of mass destruction! you goddam stoopid machine you! And if you can't find them, keep on looking! ===> You CAN'T HAVE . MORE THAN ONCE IN YOUR PATH!

  134. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    1. ___
    /
    | 10 print "hello world"
    \___

    2.
    #include <iostream>
    int main() {
    cout << "numbers from 1 to 100 and 100 to 1");
    return 0;
    }

    3.
    before: return 2+3;
    after: return 3+2;
    4.
    int ispowerof2(float number) { return number>0; }
    5.
    x *= 7;
    6.
    int buf[8];
    #define f [buf]
    int function(void) {
    return f(7)=4 && f(4)=7;
    }
    char *another(void) {
    return "f(7)=4 and f(4)=7";
    }

  135. he didn't "invent" the puzzle by jeif1k · · Score: 1

    These kinds of sliding block puzzles have been around for a long, long time. He just picked one of the many possible designs for his plastic version using a software program.

    The computer versions of these puzzles have been around for a long time and come with many levels. His particular design seems like a fairly regular collection of blocks, and some computer version probably already includes it as a level.

  136. How about the A's by gr8_phk · · Score: 1

    I hope switching the A's does not change make it possible again. I would guess it doesn't.

  137. Huh? by Sun · · Score: 1

    I have a similar puzzle at home. I was missing one 1x2 piece to build the pattern shown in the web site. I complemented it using a piece of paper.

    It took me about 15 minutes of manual sliding to find a 29 moves solution. This is, by far, not the hardest form possible. Unless the picture they show on the web site is not it, I'm afraid this whole effort was in vain.

    Shachar

    1. Re:Huh? by Sun · · Score: 1

      My bad. I thought I was meant to move it to the *bottom* right corner. I take it back...

    2. Re:Huh? by Headw1nd · · Score: 1

      Are you sure you went to the right corner? The object is to move from the top left to the top right corner...a number of people in this thread claim to have solved it, but went to the bottom right corner instead.

  138. big prize never awarded by obtuse · · Score: 1

    The puzzle was popular because Sam Loyd offered a $1,000 prize for solving his sliding block puzzle, but the parity was broken because 14 & 15 were transposed. It was unsolvable. He sold lots of puzzles, and then bragged about his fraud. Those wacky victorians.

    --
    Assembly is the reverse of disassembly.
    1. Re:big prize never awarded by DavidTC · · Score: 1

      That's not fraud. It's not like the puzzle design was a secret.

      --
      If corporations are people, aren't stockholders guilty of slavery?
  139. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    How about modifying an existing system with no time or budget and everchanging requirements. Oh, and the original developer did lots of cute little tricks like not using loops or temp variables.

    THAT will get you a job.

  140. Solution by Anonymous Coward · · Score: 0

    The solution to the sliding block problems is actually fairly easy -- use an A* search. (Anyone having taken an AI course at the university level has probably coded just such a thing to solve just such a problem -- at least, I know I did.)

    I'd say that it would take about ... oh ... at most 2 hours to cobble the code together.

    1. Re:Solution by roscodagama · · Score: 1

      According to the site, it's possible in 84 steps ?

      I'll try your solution.
      Thanks, anyway,
      rosco

  141. Re: A Java-version of #2 by Anonymous Coward · · Score: 0

    This anonymous coward has no C/C++ skills, so many pardons if this isn't easily rewritten for those:

    public class Countdown
    {
    public static void main(String args[])
    {
    Countdown c = new Countdown();
    c.count(100);
    }

    public boolean count(int count)
    {
    System.out.println(count);
    boolean uglyHack = (count > 1 && count(--count));
    return uglyHack;
    }
    }

    If it's any GOOD, on the other hand, is quite a different kettle of the old tea.

  142. Constraint Programming by ppswede · · Score: 1

    Seems like a perfect problem to solve via Constraint programming (which I happen to be taking a course in atm) ... Amazing stuff with the help of some magic, for example with OZ:

    http://www.mozart-oz.org/documentation/fdt/

    1. Re:Constraint Programming by Anonymous Coward · · Score: 0

      While constraint solving is a very useful paradigm, constraint-based programming languages are probably doomed to the same trash bin as every other innovative academic CS language. However, it is interesting that the same ideas are making some headway in the business world in the form of "business rules" engines, especially in the Java world.

    2. Re:Constraint Programming by Anonymous Coward · · Score: 0

      Oz isn't a constraint programming language by any means. It merely allows it as one of many possible paradigms. Other paradigms include declarative, logic, functional, imperative, object oriented ...
      So writing a OOP constraint program is a kinch. But unlike Java you have the option of using other paradigms instead of stateful imperative OOP with the constraints.

    3. Re:Constraint Programming by NateTech · · Score: 1

      When all you have is a hammer...

      --
      +++OK ATH
  143. Lufia 2: Rise of the Sinistrals by Ghoser777 · · Score: 1

    I played this old SNES game for the first time this summer, and it had this really tough puzzle near the end that I solved the first time using a walkthrough, but I thought it would be interesting to write a program that would find the shortest solution... and so I did! Source code and working java applet provided:

    http://homepage.mac.com/fahrenba/diff_puzzle/dif f_ puzzle.html

    --
    James Tiberius Kirk: "Spock, the women on your planet are logical. No other planet in the galaxy can make that claim."
  144. Re:I will help YOU get a JOB! (Programming puzzles by Fahrenheit+450 · · Score: 1

    More about quines than you ever wanted to know.

    --
    -30-
  145. Solving sliding block puzzles in Perl by Anonymous Coward · · Score: 0

    There was a thread about them on Perl Monks: http://perlmonks.org/?node_id=396259 .

  146. Re:I will help YOU get a JOB! (Programming puzzles by woah · · Score: 1
    Well...

    No 11 is wrong. You wrote printf("an exact copy of the source". Given that you only wrote three lines of code, that should be pretty easy do, right?

    The question is recursive. If you include the source in the printf statement, than you'd have to include the printf statement itself as well, together with the source...

    I kind of had a look at it and managed to come up with this:

    int main() { char* a = "int main() { char* a = "; char b[128] = " printf( %s%c%s%c; char b[128] = %c%s%c; , a, 34, a, 34, 34, b, 34); b[8] = b[40] = 34; puts(b); }"; printf("%s%c%s%c; char b[128] = %c%s%c;", a, 34, a, 34, 34, b, 34); b[8] = b[40] = 34; puts(b); }

    It should work OK in unix. Not sure about Windows. Not terribly elegant, I know. There's probably loads of better ways of doing it.

    Other than that everything looks pretty good!!

  147. That puzzle should be easier than the 15-puzzle... by ca1v1n · · Score: 1

    At least for a computer. The scramble counting method used will result in lots of redundant positions. If you do a heuristic search, you'll never encounter redundant board configurations. The variable piece size will actually lower the effective branching factor for heuristic searches, since many moves that are feasible will generate infeasible children, and never again be visited. Also, since the ratio of open to occupied space is higher, you'll have a larger proportion of states where the branching factor is also diminished by the fact that the space is adjacent to a side of the board, meaning that no piece can fill it from that side.

    I actually wrote a program that used a variety of searches and heuristics to solve the 15-puzzle (GBFS with the Manhattan Distance heuristic worked fastest, but gave less optimal answers than A*, obivously.) If I weren't in the middle of finals, I'd dust off that code and mangle it to do this to prove it.

    My point is, while the puzzle shown may have a deeper and wider solution tree, by being smart, you can prune the width and avoid depth-increasing inefficiencies, so the less uniform structure actually help here.

  148. Re:I will help YOU get a JOB! (Programming puzzles by woah · · Score: 1
    Most of them are quite easy, except for number 11. I knew instantly how to do each of them, but number 11 kind of jumped at me and I thought, this is interesting...

    I managed to come up with this after an hour or two:

    int main() { char* a = "int main() { char* a = "; char b[128] = " printf( %s%c%s%c; char b[128] = %c%s%c; , a, 34, a, 34, 34, b, 34); b[8] = b[40] = 34; puts(b); }"; printf("%s%c%s%c; char b[128] = %c%s%c;", a, 34, a, 34, 34, b, 34); b[8] = b[40] = 34; puts(b); }
    There's probably loads of more elegant ways of doing it, though.
  149. Re:I will help YOU get a JOB! (Programming puzzles by Dominic_Mazzoni · · Score: 1

    Here's the thing. I can look at each example and see a solution. But how important is it to actually give the solution?

    If you can't figure it out, how you reason through it is just as important to the interviewer.

    Computer science has devolved into programming. Is the code that important, or the solution in regular syntax?

    No, only 5% of C.S. jobs really require true C.S., the rest really are just programming jobs. And for the jobs that really do require C.S., I'm sure they'd far prefer a candidate who is not only good at the theory, but knows several programming languages inside out. (Good interviewers will let you choose one of several popular programming languages to use to answer most of your questions in.)

    I think most people would find this difficult because they forget how to program in these languages, but that doesn't mean they can't see the answer

    If the job involves mostly GUI programming, or server-side web app development, then this test is just nitpicky. But if the job involves writing device drivers in C, this test is totally fair. Someone who couldn't breeze their way through all of these questions would be exactly the type of person who would be likely to waste 2-3 days tracking down a silly bug involving idiosyncracies of the C language.

  150. Re:I will help YOU get a JOB! (Programming puzzles by sadr · · Score: 1

    The hard version of #8 specifies that you can't use memory proportional to the size of the list, nor can you modify the contents of the list.

    There's a slick way to handle this, which I'll write in the margin.

  151. Re:I will help YOU get a JOB! (Programming puzzles by yRabbit · · Score: 1

    Oh, so it's not a case of programming your way out of a paper bag, you have to program your way out of your room/house. ;)

  152. Solution for 3/13. by Spy+der+Mann · · Score: 1

    a^=(b^=a);b^=a;

    (^ is the XOR operator)

  153. #5 is too easy, and doen't need a shift operator by Nom+du+Keyboard · · Score: 1
    5. C/C++ : Multiply x by 7 without using multiplication (*) operator.

    You can be clever with shift operators, or just:

    answer = x + x + x + x + x + x + x;

    Now which could you have come up with faster?

    --
    "It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
  154. Re:Lufia 2: Rise of the Sinistrals -- JTK by Nom+du+Keyboard · · Score: 1
    ---
    James Tiberius Kirk: "Spock, the women on your planet are logical. No other planet in the galaxy can make that claim."

    So the "T" in James T. Kirk stands for Tiberius. But what does the Tiberius stand for?

    --
    "It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
  155. Re:I will help YOU get a JOB! (Programming puzzles by Refrozen · · Score: 0

    Can we use & n b s p ; here?

  156. Re:#5 is too easy, and doen't need a shift operato by smallfries · · Score: 1

    answer = (x 3) - x;

    --
    Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
  157. It's not HARD! by John+Sokol · · Score: 1

    I just cut out some wood blocks and tried to solve it and was able to in like under a minute.

    It's not hard to see the solution , but this computer program had a hard time brute forcing it. Because it can't work towards a goal! and Can't eleminate obvious dead ends.

    --
    I am always doing that which I can not do, in order that I may learn how to do it. - Pablo Picasso
  158. Re:#5 is too easy, and doen't need a shift operato by smallfries · · Score: 1

    DOH!

    Should have read:

    answer = (x3) - x;

    Foiled by the auto-formatting...

    --
    Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
  159. No for loops in the C code..... by Anonymous Coward · · Score: 0

    #!/usr/bin/perl

    @up, @down;
    for($i=1; $i<=100; $i++)
    {
    push @up, $i;
    push @down, 101 - $i;
    }
    $s = join(" ", @up) . " " . join(" ", @down);

    open FILE, ">code.c";
    print FILE <<EOF;

    int main()
    {
    printf("$s\\n");
    return 0;
    }
    EOF

    close FILE;

  160. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    1. main() { if (printf("hello world\n")){} }
    2. main() { int i = 0; a: printf( "%d\n", ++i ); if (i < 100) goto a; b: printf( "%d\n", i-- ); if (i > 0) goto b; }
    3 / 13. main() { int a = 65535; int b = 1453; printf( "a = %d, %b = %d\n", a, b ); swapbit( 0x0 ); swapbit( 0x1 ); swapbit( 0x2 ); swapbit( 0x3 ); swapbit( 0x4 ); swapbit( 0x5 ); swapbit( 0x6 ); swapbit( 0x7 ); swapbit( 0x8 ); swapbit( 0x9 ); swapbit( 0xa ); swapbit( 0xb ); swapbit( 0xc ); swapbit( 0xd ); swapbit( 0xe ); swapbit( 0xf ); printf( "a = %d, %b = %d\n", a, b ); }
    4. main() { int a = 65535; while (a) { if (a & 1) { if (a != 1) printf( "not a power of two\n" ); else printf( "is a power of two\n" ); break; } a >>= 1; } }

    These bore me, but I already have a job so I guess it doesn't matter.

  161. Re:#5 is too easy, and doen't need a shift operato by EvanED · · Score: 1

    Is it wrong if I came up with "x + (x1) + (x2)" faster than x+x+x+x+x+x+x?

  162. Re:#5 is too easy, and doen't need a shift operato by EvanED · · Score: 1

    Yeah, there should be shifts in there... x + x<<1 + x<<2

  163. "void value not ignored" by tepples · · Score: 1

    nosemi.c:1: void value not ignored as it ought to be

    Unless you're treating warnings as errors, the following will work in GCC:

    int main(void) { if(puts("Hello World!"), exit(0), 1) {} }

    But if you're turning on all warnings and treating them as errors (as one would in C++), then you'll also get a warning about missing the prototype for puts() and exit(). You'll need to include stdio.h and stdlib.h, making it a three-liner. Anyway, this compiles without errors or warnings in gcc -Wall -W:

    #include <stdio.h>
    #include <stdlib.h>
    int main(void) { if(puts("Hello World!"), exit(0), 1) {} }
    1. Re:"void value not ignored" by Anonymous Coward · · Score: 0

      nosemi.c:1: void value not ignored as it ought to be

      oops.

      But if you're turning on all warnings and treating them as errors (as one would in C++)

      No. That's retarded. Seriously. Not all warnings are productive. -pedantic stuff is okay as is most of -Wall, but say -Wunused in the middle of debugging? No way.

  164. And get a stack overflow by tepples · · Score: 1

    Try recursion instead

    The ability to iterate using recursion without eating up the stack is an implementation quality issue, as ISO C does not require a compiler to optimize tail calls the way all Scheme compilers and interpreters must. Do the last few versions of Microsoft Visual C++ optimize tail calls? Does GCC 3.4.x (which apparently does) support the target platform?

    1. Re:And get a stack overflow by pediddle · · Score: 1

      Since the problem was to print only 1..100 and 100..1, the danger of stack overflow is pretty low.

    2. Re:And get a stack overflow by tepples · · Score: 1

      Have you seen the small-ish stacks on some handheld machines?

    3. Re:And get a stack overflow by pediddle · · Score: 1

      Simple answer: if you're coding for an embedded device, don't try and write a loop without loops :-)

  165. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0
    And here's the ultimate from Thomas Schumm, the polyglot: a quine in C, python and perl:

    #include <stdio.h>
    #define q(a,...) a
    #define substr q
    #define eval(a) main(){char c[]=a,n=10;c[419]=0;printf(c+4,n,n,n,n,34,34,n,34, 39,c+4,39,34,n);}/* Copyright (C) Thomas Schumm <phong@phong.org>
    exec("from sys import*;substr=q=lambda y:exit(stdout.write(y[4:-46]%((10,)*4+(34,34,10,34 ,39,y[4:-46],39,34,10))))",None);#*/
    eval(substr( q("$p='#include <stdio.h>%c#define q(a,...) a%c#define substr q%c#define eval(a) main(){char c[]=a,n=10;c[419]=0;printf(c+4,n,n,n,n,34,34,n,34, 39,c+4,39,34,n);}/* Copyright (C) Thomas Schumm <phong@phong.org>%cexec(%cfrom sys import*;substr=q=lambda y:exit(stdout.write(y[4:-46]%%((10,)*4+(34,34,10,3 4,39,y[4:-46],39,34,10))))%c,None);#*/%ceval(subst r(q(%c$p=%c%s%c;printf($p,(10)x4,34,34,10,34,39,$p ,39,34,10)%c),1,-1))%c';printf($p,(10)x4,34,34,10, 34,39,$p,39,34,10)"),1,-1))
  166. #11 print self by SpinyNorman · · Score: 1

    I think this'll work:

    char q = '"'; char *body = "int main(void) {printf(fmt, q, q, body, q, q, fmt, q, body); return 0;}"; char *fmt = "char q = '%c';char *body = %c%s%c;char *f = %c%s%c;%s"; int main(void) {printf(fmt, q, q, body, q, q, fmt, q, body); return 0;}

    1. Re:#11 print self by SpinyNorman · · Score: 1

      Or how about this one... it's kinda self-verifying, since it relies on itself working in order to work! :-)

      #include
      #include

      int main(int argc, char **argv)
      {
      char create_self[100];

      sprintf(create_self, "%s > /tmp/self", argv[0]);

      system(create_self);

      FILE *f = fopen("/tmp/self", "r");

      while (!feof(f)) putc(fgetc(f));

      return (0);
      }

  167. Re:I will help YOU get a JOB! (Programming puzzles by Dj-Zer0 · · Score: 1

    number 9 cant u just select unique rows import it to another table ? more like DISTINCT ( but i dont think access can do DISTINCT though i am not sure,

    --
    http://iesucks.org
  168. Bogus by frovingslosh · · Score: 1
    You know, I found this interesting too. But there's a major problem with it, at least in the way that you presented the way to make it hard for the player. OK, if you swap the other R into the first position the puzzle would be unsolvable .....if the other 13 pieces were unique. But they are not. If the player happens to move the second A (the one that started out in P A L) into place after the R, he will undo the problem you created with the R swap. Indeed, if you really randomized the other letters then he is as likely to move either A into place, so the puzzle is no harder than if you had just randomized everything (actuly slightly easier since you put an R in place for him.

    I suspect the real way to set this problem up for a user would be to leave the word RATE on the top line, or at least RAT, but to be sure that you swapped one and only one of the first two tiles when you did this. Or to leave it so very close to that solution that the user would likely make one move and be there (for example a top line of Y R A T and a second line of [space] [something ] [something] R, with the intended incorrect R and A in each position). But the way that you set the problem up just does not work.

    --
    I'm an American. I love this country and the freedoms that we used to have.
  169. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    Umm... your first example won't actually compile, and is therefore not a program. The second example is actually the shortest possible quine, and won the Obfuscated C Code contest in 1994.

  170. Re:I will help YOU get a JOB! (Programming puzzles by Moderatbastard · · Score: 1
    Some companies certainly ask for these things. Specially Microsoft.
    If they consider being able to fanny around with party games like this as a prerequisite for the job, it's no wonder they produce such shite.

    These have as much relevance to real world programming as keepie-uppie does to an actual game of soccer.

    --
    1/3 of jokes get modded OT. If you get the joke, mod 1 in 3 insightful/interesting/underrated to restore karma balance.
  171. Re:#5 is too easy, and doen't need a shift operato by p3d0 · · Score: 1

    Dude, you really need to take a second and try out the "Preview" button.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  172. Re:I will help YOU get a JOB! (Programming puzzles by Moderatbastard · · Score: 1
    "Perhaps they should consult a mathmatician"

    In Soviet Russia, a dictionary should consult you!!!

    --
    1/3 of jokes get modded OT. If you get the joke, mod 1 in 3 insightful/interesting/underrated to restore karma balance.
  173. RTFA by p3d0 · · Score: 1

    The guy wrote a program to design the puzzle, not to solve it.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  174. You're so SMART! by p3d0 · · Score: 1

    ...But you almost certainly did it wrong. Solving this in under a minute would require you to do more than one move per second with no errors.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    1. Re:You're so SMART! by John+Sokol · · Score: 1

      Accoring the the photo and rulls described by the article that was linked to, I can did it in 23 Moves! That's 2.5 second a move.

      if I number the blocks 1 to 9 from top left to right. E is empty

      I have
      1 1 2 2
      1 1 3 4
      E E 3 4
      5 6 6 7
      5 8 8 9

      The rulls are to move the 2x2 square from the top left to the bottom right I do the following

      1 down
      2 left
      3479 up
      7 left
      4 down
      3 right
      7 up
      1 right
      5 up
      689 left
      9 up
      8 right
      6 down
      9 left
      1 down
      7 down left
      3 left
      4 up
      1 right
      9 right up
      6 up
      8 left
      1 down

      Let me know if I am missing something, But this took more to write down then to solve....

      Having to deal with an inquisitive 4 year old and a screaming wife.

      I doesn't it required being smart but to just see the problem clearly.

      --
      I am always doing that which I can not do, in order that I may learn how to do it. - Pablo Picasso
    2. Re:You're so SMART! by osho_gg · · Score: 1

      You got it wrong. The puzzle is to move top-left to top-right . You solved the puzzle of moving from top-left to bottom-right (which is trivial). Try to solve it here (the link is from someone else's post) http://www.puzzleworld.org/SlidingBlockPuzzles/quz zle.htm Osho

    3. Re:You're so SMART! by p3d0 · · Score: 1
      The rulls are to move the 2x2 square from the top left to the bottom right...
      No, the rules are to move the 2x2 square from the top left to the top right. It's a common mistake.
      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    4. Re:You're so SMART! by John+Sokol · · Score: 1

      Thanks, that makes does make it more difficult.

      --
      I am always doing that which I can not do, in order that I may learn how to do it. - Pablo Picasso
  175. Re:Question 3 Solved (alternative method) by njh · · Score: 1

    Until B == 0.

    try:
    A = A + B
    B = A - B
    A = A - B

    (but that's just xor with some superfluous carrying)

  176. Re:I will help YOU get a JOB! (Programming puzzles by Matchstick · · Score: 1
    Taking the sum is tempting (or computing some other order-invariant property), but as other posters have found out, one can create input arrays that have the same value but aren't proper permutations.

    Computing something more complex might work, but all the schemes I can think of require arbitrary-size numbers. For example you could take the sum of 2^elt, effectively creating a bitstring; but that requires N bits.

    So how about reusing the solution that you didn't like: Sort. Return "duplicate" if you find a duplicate entry while sorting. Given the problem's constraints, the array can be sorted in O(n) time using something like an in-place radix sort.

    The inner loop is entered once per cycle within the permutation, and runs for the length of the cycle. The sum of the cycle lengths is N; thus the algorithm is O(n) even though it may not look like it at first glance.
    def HasDuplicates(array):
    for i in range(len(array)):
    while array[i] != i:
    val = array[i]
    if array[val] == val:
    return DUPLICATE
    array[i], array[val] = array[val], array[i]
    return NO_DUPLICATE
  177. Re:the 15-square puzzle - win $1000000 by LesPaul75 · · Score: 1

    Did you know that if you can truly "solve" the 15-square puzzle, you can win a million bucks? No joke. The 15-square puzzle is actually NP-complete. I'll spare the details, but basically, it's not known whether or not the puzzle (or any other NP-complete problem) can be solved in polynomial time. If you can write an algorithm that solves the puzzle in polynomial time (or prove that it can't be done) then you win the million bucks offered by the Clay Mathematics Institute. They call it a "Mellinium Prize." It's one of seven unanswered questions in mathematics, and each of them is worth a million bucks. Good luck...

  178. I'm a bit lower on the geek food chain... by Anonymous Coward · · Score: 0

    I can't even figure out the "Two Bent Nails" puzzle...

  179. Sliding Block Puzzles in Java by jcelko · · Score: 1

    http://www.puzzles.com/PuzzleLinks/NickBaxter'sSli dingBlockPuzzles.html Great stuff and Nick was on the ANSI X3H2 Database Standards Committee about a million years ago. There are some other contributors there also. --CELKO--

  180. How about any (n^k)-1 puzzle? by Pinball+Wizard · · Score: 1

    A general solution can be written for any (n^k)-1 puzzle using the A* algorithm. To implement A* you calculate the value of your state, and the value of each successive state. The possible successive state that gets you closest to the goal state is the state you move to next. You keep track of all visited states, so you don't keep following paths that don't reach your goal.

    With a 15-puzzle, you can develop a heuristic that allows you to determine how far you are away from the goal, as well as how far each successive state is from the goal. With the same algorithm you can extend your solution to solve any (n^k)-1 puzzle.

    This was actually a programming assignment in a previous class of mine. We had to implement A* and then use it to solve (n^k)-1, missionary-and-cannibal, and the shortest path problem. (and if you're interested and/or masochistic, check out the other projects that we had to complete in the space of a semester)

    --

    No, Thursday's out. How about never - is never good for you?

  181. Has anyone *actually* solved this? by ex+falso+quodlibet · · Score: 1

    A bunch of people who are clearly too smart to bother reading the instructions have managed to move it to the bottom right which is indeed trivial. Has anyone actually solved the thing themselves? Can you give us a screenshot of the completed puzzle from http://www.puzzleworld.org/SlidingBlockPuzzles/quz zle.htm? I've been messing around with it on and off for a couple of hours and damned if I can get there - so close and yet so far ...

    1. Re:Has anyone *actually* solved this? by nylreM · · Score: 1

      See my other post. I wrote a program. No way I'm wasting my time randomly trying things by hand...

  182. Solution by nylreM · · Score: 1

    Whipped up a solution finder. Here's the result.

    Pieces numbered scan order as 0, 1, 4, 5, 6, 2, 7, 3, 8. 0 is left, 1 is right, 2 is up, 3 is down. Moves counted one grid pos at a time - there may well be a shorter one under different move metrics. Kinda neat that big square piece visits all corners on way to finish.

    Not that anyone's impressed or anything - pretty easy to write a solver for this sort of puzzle in terms of 64 bit bit-ops. Is there anything in particular about Haskel that's good for this kind of thing?

    Solution found on level 115.
    0:3#1:0#1:0#4:2#5:2#7:2#7:0#5:3#5:3#4:1#7:2# 7:2#0: 1#6:2#3:0#6:2#
    2:0#8:0#8:2#3:1#3:1#2:3#8:0#8:0#0: 3#7:3#7:0#4:0#5: 2#5:2#0:1#8:1#
    6:3#7:0#8:2#8:2#0:0#5:3#5:3#4:1#1: 1#8:1#7:1#6:2#6: 2#0:0#5:0#4:3#
    1:1#7:2#8:0#5:2#3:2#2:1#2:1#0:3#6: 3#8:3#7:3#1:0#1: 0#4:2#5:2#8:1#
    7:3#8:1#5:3#1:1#6:2#7:0#5:0#8:0#4: 3#1:1#5:2#7:1#8: 2#7:1#0:2#2:0#
    2:0#3:3#7:3#7:1#0:1#6:3#6:3#5:0#8: 0#8:2#0:2#7:0#7: 0#3:2#2:1#2:1#
    7:3#3:0#4:3#7:0#2:0#4:3#0:1#8:3#8: 3#5:1#6:2#6:2#8: 0#5:3#1:0#8:3#
    6:3#1:0#0:2#
    done looking - minSolution is 115.

  183. The depths to which Adventure games have sunk by Finkbug · · Score: 1

    I knew things were bad when the Sam & Max sequel was cancelled, but this...

    --
    Feeling so good natured I could drool
  184. Solution (by hand using MegaBlocks) by Derivin · · Score: 0

    The puzzle actually looked really easy, but I was having a hard time visualizing it so I used my sons MegaBlocks(tm) to work it out.

    Key: (blocks numbered 1-9 starting upper left, to bottom right)

    1 2x2
    2 1x2
    3 2x1
    4 2x1
    5 2x1 (bottom left)
    6 1x2
    7 1x1
    8 1x2 (bottom center)
    9 1x1 (bottom right)

    > left >> double left
    < right << double right
    ^ up ^^ double up
    v down vv double down

    1 v
    2 <
    3 ^
    4 ^
    7 ^
    7 <
    4 vv
    3 >
    7 ^^
    1 >
    5 ^^
    6 <
    8 <
    9 <
    9 ^
    8 >>
    6 v
    9 <<
    1 v
    7 v
    7 <
    3 <
    4 ^^
    1 >
    9 >
    9 ^
    6 ^
    8 <<
    1 v

    In the end it took longer to type this up than it took me to solve this. The 15x15 is much harder in my opinion.

    1. Re:Solution (by hand using MegaBlocks) by nylreM · · Score: 2

      Uh, you have to get the 2x2 block to the upper right silly... Getting it to the lower right does happen as part of the full solution, but it's only the first of the corners you need to visit... See my other post.

  185. Map of Quzzle puzzle space by paylett · · Score: 2, Interesting
    Hey, don't know if anyone's still reading comments for this article now but..

    We've put together a graph linking all the positions you can get to with the Quzzle.

    Starting point shown in red. Top/right Ending point(s) shown in blue. And the (incorrect) bottom right solution in pink. The path from start to solution is shown in green.

    Notes: Used aiSee to draw the graph. The circuits that seem to appear in the solution are just due to the graph being drawn with crossovers.

    Ok.. time to go and find something less geeky to do with the rest of the evening.

    --

    Believing something doesn't make it true. Not believing something doesn't make it false.

    1. Re:Map of Quzzle puzzle space by RegDwight · · Score: 1

      Dear paylett,

      is there any chance for us to get the GDL source of your graph? I personally would like to play around with the various layout algorithms.

      Thank you in advance.

    2. Re:Map of Quzzle puzzle space by paylett · · Score: 1
      Yep, enjoy.

      I'd never used the graphing program before, but the layout algo's seemed to be pretty cool.

      Something I should note is that the node names encode the position at that point. The encoding is as follows: Each character represents a block ('2'=2x2, '1'=1x1, 'H'=2x1, 'V'=1x2, 'E'=empty). For any given puzzle orientation, scan from top to bottom, and left to right within each row. The character for any new block is recorded. (ie only record the top-left of each block).

      I hope that makes sense. If not, email me at the addr on the website.

      --

      Believing something doesn't make it true. Not believing something doesn't make it false.

  186. Re:I will help YOU get a JOB! (Programming puzzles by Anonymous Coward · · Score: 0

    they're great things to use b4 interviews!

    "b4"? Please. Go back to AOL.

    Also, you might want to RTFA, or even RTF write up, because this has nothing to do with programming exercises.

  187. The World's hardest puzzle (Funny and Insightful) by Taed · · Score: 1

    This is paraphrased from _The Zen of Programming_, a semi-humorous book of some note. The CEO of a game company hires a consultant to design the world's most difficult picture puzzle. After thinking about it for some time, the consultant does as he is asked and returns to the CEO's office. He brings with him a box full of pieces, which he dumps on the CEO's desk. The consultant explains that there are two ways to make a picture puzzle difficult. The first is to make the shapes similar, and the second is to make the colors similar. The consultant has done both, making the shapes the same and the colors the same. The CEO exclaims, "But these are just a bunch of identical black squares -- a child could put this together!" "Such as it is in life," the consultant continues, "Often the most difficult puzzles are the easiest to solve."

  188. Re:I will help YOU get a JOB! (Programming puzzles by lvaruzza · · Score: 1

    Puzzle 3: a+=b; b=a-b; a-=b;

  189. Way more elegant by hakkikt · · Score: 1

    6. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7

    int f(int x) {
    return (11-x);
    }

  190. Answer to 8 by rm999 · · Score: 1

    Didn't see anybody answer 8. Here's a solution (it's not c++ specific or anything, more of a data structures problem): Create two instances of the linked list, and start going through the list at different rates (for example, iterate twice on the first list for every time you iterate once on the second list, if that makes sense). If either one ends, it clearly has no loop. If they intersect (ie. both point to the same element in the linked list) then there is a loop.

  191. Solution - no conditionals or templates! by CedgeS · · Score: 1

    This C solution uses no control structures, loops, templates, conditionals, ? operator, or shortcut evaluation of logical operators to accomplish this. I could use just one printf if I wanted, but this is supposed to be fairly clear. It works if you reverse the array and remove the == operator, but I think switchptr is more robust as written.

    void * switchptr(int condition, void * trueptr, void * falseptr) {
    void * ptrarray[2];
    ptrarray[0] = trueptr;
    ptrarray[1] = falseptr;
    return ptrarray[condition == 0];
    }

    int stopnums(int num, int max) {
    return 0;
    }

    int printnums(int num, int max) {
    int (*nextfun) (int, int);
    printf("%i\n", num);

    nextfun = switchptr( num >= max, &stopnums, &printnums);

    nextfun(num + 1, max);

    printf("%i\n", num);
    return 0;
    }

    int main () {
    return printnums(1, 100);
    }

    1. Re:Solution - no conditionals or templates! by akuma(x86) · · Score: 1

      (condition == 0) is a conditional.
      (num >= max) is also a conditional.

      Anything that compiles into a branch is a conditional.

    2. Re:Solution - no conditionals or templates! by CedgeS · · Score: 1

      You are missing the point which is to use an indexed array and pointers to switch paths instead of the other features of the language.

      If these compile to a branch its because the compiler made them conditional and it was the compiler's choice to be that way. It could have compiled them differently. I included the == just 'cause, so we can remove it and switch the indices back. The >= is a little bit harder.

      First we subtract the numbers a la:

      num - max

      Now we have either a positive number, a negative number, or 0. Assuming int is a 16 bit number then the most significant bit will be 0 if this result is 0 or positive, and 1 if its negative. Let's make this the least significant bit:

      (num - max) >> 15

      Now we have either a 0 if num >= max or a 1 if num < max. We can flip these around easily enough with a bitwise not to flip all the bits then and with one to get rid of 1s in the leading bits:

      (~((num - max) >> 15 )) & 1

      We can rewite the whole program as (this is not debugged - I'm in Windows for a change):

      int ge(int a, int b) {
      return (~((a - b) >> 15 )) & 1;
      }

      void * switchptr(int condition, void * trueptr, void * falseptr) {
      void * ptrarray[2];
      ptrarray[1] = trueptr;
      ptrarray[0] = falseptr;
      return ptrarray[condition];
      }

      int stopnums(int num, int max) {
      return 0;
      }

      int printnums(int num, int max) {
      int (*nextfun) (int, int);
      printf("%i\n", num);

      nextfun = switchptr( ge(num,max), &stopnums, &printnums);

      nextfun(num + 1, max);

      printf("%i\n", num);
      return 0;
      }

      int main () {
      return printnums(1, 100);
      }

    3. Re:Solution - no conditionals or templates! by akuma(x86) · · Score: 1

      Nice solution!

  192. Re:Question 3 Solved (alternative method) by SporkLand · · Score: 1

    Why do multiplies when you can just as easily do

    A = A+B
    B = A-B
    A = A-B

  193. Re: More Full solutions by Anonymous Coward · · Score: 0

    Kelerain describes 32 optimal solution paths, but there are actually 1152 possible paths to a solution in 84 moves. First, there are four possible ways to do the first 21 moves:

    AD 1LL (2U 3U / 3U 2U) 6UL 3DD 2R 6UU AR 4UU
    (5L 7L / 7L 5L) 8LU 7RR 5D 8LL AD 6DL 2L 3UU AR.

    Then there are two variants for moves 22-63, each of which can be done in 36 ways. Variant a is

    8RU 5U 7LL AD 8RR 2D 1R 4U 6DL 2L
    8LU 3D 1R 2U 6RR (2D 4D / 4D 2D) 1LL
    (8U 6U 3U / 8U 3U 6U / 3U 8U 6U)
    AU 7RR 5D 2D 6L 8D 1R 4U 2L AL 3DD
    (1R 8R 6R / 8R 1R 6R / 8R 6R 1R) 4R
    2UU AL (6DD 8L 3U 6R / 6D 8L 3U 6DR),
    and Variant b is
    (8RU 4D 6L 8U / 8R 4D 6L 8UU) AL 3DD
    2R (1R 8R 6R / 8R 1R 6R / 8R 6R 1R)
    4UU AL 3L 2D 1R 6U 8L 3U 7U 4RR AD
    (4D 8D 6D / 8D 4D 6D / 8D 6D 4D)
    1LL (3U 2U / 2U 3U) 8RR 3D 1R 4U 6DL
    3L 8LU 2D 1R 3U 6RR AU 5LL 7D 6DR.

    Note that Variant b arrives at a position that looks the same as the end of Variant a, but has blocks 2, 3, and 4 in the positions used by blocks 3, 4, and 2 in Variant a, respectively. The remainder is annotated for for Variant b.

    Moves 64-84 can be done in four possible ways:

    AR 4DD 3L 8LU AU 6LL 7U 5RR 6DL (5L 7L / 7L 5L)
    2DD AR 8DD 3R 4UU 8LD (3D 4D / 4D 3D) 1LL AU.

    Note that the goal position is the (left-to-right) mirror image of the start, so solving the puzzle in reverse is the same as solving the puzzle in a mirror. Variant A is the mirror image of the reverse of Variant B.

    Dan Hoey <haoyuep@aol.com>



  194. Re: More Full solutions by Kelerain · · Score: 1

    Some people just can't leave a puzzle alone. Kudos! :)

  195. Quagnets TOO POWERFUL!!! by QuadZero · · Score: 1

    I visited this puzzle-maker's site (quirkle.com) and discovered the super-high-power magnet set, called 'Quagnet', and bought two of them for holiday presents.

    Okay, here's the deal: while the magnets are easily as powerful as described, they're too powerful for their own good! I'm serious. In about 5 minutes of playing with these things, two of the magnetic disks simply broke apart (one while I was trying to separate a magnet from the stack, the other during a playful pick-up from a distance of about 4-5 inches).

    Anyone else buy these things as gifts? I mean, very cool in its own right but not so durable. Also, the d*mn things PINCH your fingers/skin whenever they snap together. A single pinch is just a minor annoyance but when it keeps happening over and over again (as it did with my set) it really starts to hurt.

    I had bought these for a 12-year old girl and a 13-year old girl. Not gonna happen now. In fact, I did an on-the-sly inquiry of the 13-year old, telling her it was really a gift for her 10-year old brother and, by the way, what did she think?

    Her response? "They're too powerful for him; he'll probably get hurt." So I asked her, ever so casually, "What about you? If I had bought these for you, do you think you'd enjoy them?" She answered, "No, they scare me."

    C'est la vie! :-)

    --
    Richard (aka Merwyck, aka QuaDZeRo) I blog at http://richardharlos.com