Working on a side-project indirectly involved with Parrot, I recently came across a tough problem. I managed to solve it, but the solution is inelegant. Here's the problem:
Given these resources:The restrictions, of course, are based on the current Parrot opcode set. Imagine yourself programming in assembly language...Design a routine to sort the stack, and return to the caller with the stack looking like it did before (depth on top) except sorted below that point.
- A single stack, with the depth of the stack stored on top and strings to be sorted below that.
- The depth of the stack is arbitrary.
- Your tools for manipulating and examining the stack are exclusively limited to: push, pop, and rotate_up() (see below)
- No other stacks (arrays, hashes, etc..) or data structures allowed.
- But as many scalar variables as you wish
- You can use branches, conditional logic, loops, comparison operators, even functions (see next item), and any other control logic you wish.
- No lexical variables or closures are permitted. local() would be allowed.
- Running off the end of the stack (on either side) is a fatal exception.
- The stack *must* be returned in its original state. You may not manipulate items *below* the given depth.
A sample stack might be:
and you would have to produce:@stack=qw(d b f a e c 6); # <-- bottom .. top -->
The rotate_up instruction takes the thing on top of the stack and shifts it farther down in the stack, moving all of the displaced elements up a notch. rotate_up(0) and rotate_up(1) are no-ops. rotate_up with a negative number will throw a fatal exception.@stack=qw(f e d c b a 6); # <-- bottom .. top -->
So can ya do it?# You are not allowed to modify this. sub rotate_up { local($a,$b); $a=$_[0]; $a--; return if $a<1; $b=pop @stack; splice(@stack, -$a, 0, $b); }
Points are given for:
I'll post my solution as a reply on Monday March 25th at 5pm Eastern Standard time. You may be horrified. :)
In reply to Algorithm Pop Quiz: Sorting by clintp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |