Skip to content

Instantly share code, notes, and snippets.

@misterhat
Last active December 25, 2016 04:40
Show Gist options
  • Save misterhat/60962763740a5ca280bf to your computer and use it in GitHub Desktop.
Save misterhat/60962763740a5ca280bf to your computer and use it in GitHub Desktop.
use std::io;
static MEM_SIZE: uint = 30_000;
fn main() {
// Initialize the memory with 30 000 0 bytes.
let mut memory = [0 as u8, ..MEM_SIZE];
// The current "cell" we're in, in memory.
let mut pointer = 0;
// The instruction list, a vector of characters.
let mut instructions = vec!();
for command in io::stdin().chars() {
let instruction = command.unwrap();
match instruction {
// It's a valid command, append it to our instruction list.
'>'|'<'|'+'|'-'|'['|']'|'.'|'#' => instructions.push(instruction),
// It isn't a valid command, don't add it to the instruction
// list.
_ => {}
}
// The "#" indicates the end of a program.
if instruction == '#' {
break;
}
}
// The current position we are in the instruction list.
let mut index = 0;
// Keep track of where the open "[" are located as indexes in the
// instruction list.
let mut open = vec!();
loop {
let instruction = *instructions.get(index);
match instruction {
// Move the pointer right one cell.
'>' => pointer += 1,
// Move the pointer left one cell.
'<' => pointer -= 1,
// Increment the current memory position by one.
'+' => memory[pointer] += 1,
// Decrement the current memory position by one.
'-' => memory[pointer] -= 1,
// Skip ahead to the next "]" if the current cell is 0.
'[' => {
open.push(index);
},
// Go back to the previous "[" unless the current cell is 0.
']' => {
if memory[pointer] != 0 {
index = *open.last().unwrap();
} else {
open.pop();
}
},
// Print the current memory position as a character.
'.' => print!("{}", memory[pointer] as char),
// End the program.
'#' => break,
// An unknown character (this shouldn't happen).
_ => {}
}
index += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment