Puzzle 8-12-08 (Spoiler)

Wyverex wyverex.cypher at gmail.com
Tue Aug 12 15:39:21 PDT 2008


Wyverex wrote:
> 
> 1)First is simple..
> 
> What's the  "condition" so that the following code
> snippet  prints both HelloWorld !
> 
> if  "condition"
> printf ("Hello");
> else
> printf("World");

!printf("Hello")

opens a new possibility, run if on a list...
if( [true, false] )
  printf ("Hello");
else
  printf("World");

other possibility, hijack if... maybe messy

Nop out the else jump in memory!!!


> 
> 
> 2)Next little data structure knowledge need
> 
> You are provided with two stacks, and pop() and push() functions for 
> them. You have to implement queue i.e. enqueue() and dequeue() using the 
> available operations.

didn't code up but basically

Stack work, temp;

enqueue( item )
   try
     while(1) temp.push(work.pop);
   catch(Object o) {} //work will throw underflow, maybe overflow?

   work.push(item);

   try
     while(1) work.push(temp.pop);
   catch(Object o) {} //temp will throw underflow

dequeue
    try
      return work.pop;
    catch(Object o) //underflow
      return null;


> 
> 3) little string manipulation
> 
> How do you reverse the words in a string?
> 
> "My name is Amit Agarwal"
> to
> "Agarwal Amit is name My"
> 
> **try without using the library!

//Yeah taking ML Programming was worth it!!!
import std.stdio;

char[] rev(char[] str)
{
   if(str.length == 0) return "";

   int index = -1;
   foreach(i, c; str)
     if(c == ' ') { index = i; break; }

   if(index == -1) return str;
   if(index == 0) return rev(str[1..$]);

   return rev(str[index+1..$]) ~ " " ~ str[0..index];
}


void main()
{
   char[] str = " My Name is   Wyverex Cypher     ";
   writefln("%s\n%s", str, rev(str));
}


More information about the Digitalmars-d-learn mailing list