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();) } }

One Response to “Solving a typical interview question with SWE”

  1. naiem Says:

    Note that SWE is not released yet, so you can’t actually run the above code. I am really busy these days and takes me a while to finish the first release.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: