Skip to content

Commit

Permalink
Extract jump methods
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelgwelch committed Mar 14, 2012
1 parent 05348d6 commit 4b15b4c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 24 deletions.
3 changes: 0 additions & 3 deletions csharp/BrainmessShort/BrainmessShort.csproj
Expand Up @@ -80,8 +80,5 @@
<Install>true</Install> <Install>true</Install>
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project> </Project>
65 changes: 44 additions & 21 deletions csharp/BrainmessShort/Main.cs
Expand Up @@ -17,7 +17,6 @@ public static void Run(string program)
int pc = 0; int pc = 0;
int[] tape = new int[5000]; int[] tape = new int[5000];
int tc = 2500; int tc = 2500;
int nestLevel;
while(pc < program.Length) while(pc < program.Length)
{ {
char instruction = program[pc]; char instruction = program[pc];
Expand Down Expand Up @@ -45,33 +44,57 @@ public static void Run(string program)
case '[': case '[':
if (tape[tc] == 0) if (tape[tc] == 0)
{ {
nestLevel = 1; pc = JumpForward(program, pc);
while(nestLevel > 0)
{
instruction = program[pc];
if (instruction == '[') nestLevel++;
else if (instruction == ']') nestLevel--;
pc++;
}
} }
break; break;
case ']': case ']':
if (tape[tc] != 0) if (tape[tc] != 0)
{ {
pc -= 2; pc = JumpBackward(program, pc);
nestLevel = 1;
while(nestLevel > 0)
{
instruction = program[pc];
if (instruction == '[') nestLevel--;
else if (instruction == ']') nestLevel++;
pc--;
}
pc++;
} }
break; break;
} }
} }
} }
}
private static int JumpForward(string program, int pc)
{
int nestLevel = 1;
while (nestLevel > 0)
{
char instruction = program[pc];
if (instruction == '[')
{
nestLevel++;
}
else if (instruction == ']')
{
nestLevel--;
}
pc++;
}
return pc;
}

private static int JumpBackward(string program, int pc)
{
pc -= 2;
int nestLevel = 1;
while (nestLevel > 0)
{
char instruction = program[pc];
if (instruction == '[')
{
nestLevel--;
}
else if (instruction == ']')
{
nestLevel++;
}
pc--;
}
pc++;
return pc;
}
}
} }

0 comments on commit 4b15b4c

Please sign in to comment.