- Edited
I was just given a challenge...
I was given access to a string (okay, character stream) through a function read()
that returned each character of the string in turn. That was all I had. A sufficient mock function would be
function read()
{
static $string = 'This is a test; it is only a test; it is not the real thing; if it were the real thing you would not be reading this; you would be reading something else.';
static $position = 0;
return $string[$position++];
}
You can see I didn't have much to work with. I was under even tighter constraints than that.
Here's what I had to do: output the string, but each time I encountered a semicolon, I had to reverse the character order of each word; tsuj ekil siht; until another semicolon reversed the reversal. Spaces and semicolons had to remain where they were (between and at the ends of words). There was also a full stop on the end: I was assured that the string would end with a full stop so that I could know when to, well, stop (since I couldn't know in advance how long the string would be). That had to be in the final output, too. Anything other than spaces, semicolons, or full stops could be considered part of the word.
For example, the result of mangling the above string should be:
This is a test; ti si ylno a tset; it is not the real thing; fi ti erew eht laer gniht uoy dluow ton eb gnidaer siht; you would be reading something else.
Those tighter constraints? I could only explicitly work with one character at a time. No substrings (of input or output or working space), no arrays, no character buffers, no random access of the source string. Read a character, deal with it, move on to the next. I had a while(true) { $c = read(); ...}
loop and $c
was the only part of the string I could refer to throughout the loop and I could only hold on to one "$c
" at a time.
The final result isn't stored as a string, but output (one character at a time since you aren't building strings).
Before I post my solution, I'd like to see what others come up with. If the rules need clarifying, let me know.