Solving a typical interview question with SWE

Lets assume a typical interview question:

Write some code to reverse words in a sentence without using .Net string functions. For example, “this and that” should become “sith dna taht”. We want to preserve space patterns also.

This is the state machine for this purpose:

And I can write it as follows:

public class TextContext
public string Text;
public int Pos; //Current position
public string Word;
public string Result;

public static void Main()
var tc = new TextContex{Text="This and That"};
var sm = new StateMachineBuilder()
.State("Space", c => true, c => { c.Word += " "; c.Pos++; })
.Then(c => c.Pos >= c.Text.Length, "Fine")
.Then(c => c.Text[c.Pos] == ' ', "Space")
.Then("Word", c => {c.Result += c.Word; c.Word = '';})
.State("Word", c => true, c => {c.Word = c.Text[c.Pos] + c.Word; c.Pos++;})
.Then(c => c.Pos >= c.Text.Length, "Fine")
.Then(c => c.Text[c.Pos] != ' ', "Word")
.Then("Space", c => {c.Result += c.Word; c.Word = '';})



UPDATE: SWE is re-design. With the new version, the above code will look like the following:

var str = "This and That";
var word = new StringBuilder(); 
var smbuilder = StateMachine<int,string>.Create("word")
.State("leters", (s, i) => {
    if (str[i]==' ') { s.Return(word.ToString()); word.Clear(); return StateMachine.Named("spaces");};
    s.UpldateObject(i+1); //Update the pointer
    return StateMachine.Loop })
.State("spaces", (s, i) => {
    if(str[i]==' ') { return StateMachine.Loop; }
    return StateMachine.Named("letters");
var sm = smbuilder.BindTo(0);
while(sm.Process()){ if (sm.HasReturn) { Console.WriteLn (sm.GetReturned();) } }

Simple Workflow Engine

In the last post I talked about a workflow engine to define workflows over object quickly and efficiently.

Last night I had some time and implemented the basics of the engine. The lamp example in the previous post works and the code I wrote tend to be really simple and small.

The project is hosted in codeplex ( Download it and play with it.