Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::str::Chars;
- trait Turtle {
- fn move_forwards(&mut self);
- fn turn_right(&mut self);
- fn has_flower(&self) -> bool;
- }
- struct TestTurtle {
- pub moves: Vec<char>
- }
- impl Turtle for TestTurtle {
- fn move_forwards(&mut self) {
- self.moves.push('F');
- }
- fn turn_right(&mut self) {
- self.moves.push('R');
- }
- fn has_flower(&self) -> bool {
- false
- }
- }
- enum Instruction {
- Forwards,
- Right,
- Group { elements: Vec<Box<Instruction>> },
- Repeat { num: u8, element: Box<Instruction> },
- Conditional { first: Box<Instruction>, second: Box<Instruction> },
- }
- impl Instruction {
- fn parse(stream: &mut Chars) -> Option<Instruction> {
- let m_ins = stream.next();
- match m_ins {
- Some('F') => Some(Instruction::Forwards),
- Some('R') => Some(Instruction::Right),
- Some('[') => {
- let mut elements = Vec::new();
- while let Some(ins) = Instruction::parse(stream) {
- elements.push(Box::new(ins));
- }
- Some(Instruction::Group { elements })
- }
- Some(']') => None,
- Some('?') => {
- let first = Box::new(Instruction::parse(stream)?);
- let second = Box::new(Instruction::parse(stream)?);
- Some(Instruction::Conditional { first, second })
- }
- Some(rep) if rep > '0' && rep <= '9' => {
- let num = rep.to_digit(10).unwrap() as u8;
- let element = Box::new(Instruction::parse(stream)?);
- Some(Instruction::Repeat { num, element })
- }
- _ => None
- }
- }
- fn execute(&self, turtle: &mut dyn Turtle) {
- match self {
- Instruction::Forwards => turtle.move_forwards(),
- Instruction::Right => turtle.turn_right(),
- Instruction::Group { elements } => {
- for e in elements {
- e.execute(turtle);
- }
- }
- Instruction::Repeat { num, element } => {
- for _ in 0..*num {
- element.execute(turtle);
- }
- }
- Instruction::Conditional { first, second } => {
- if turtle.has_flower() {
- first.execute(turtle);
- } else {
- second.execute(turtle);
- }
- }
- };
- }
- }
- fn decode_google(mut stream: Chars) -> Vec<char> {
- let mut turtle = TestTurtle { moves: Vec::new() };
- while let Some(ins) = Instruction::parse(&mut stream) {
- ins.execute(&mut turtle);
- }
- turtle.moves
- }
- pub fn main() {
- let input = "4F2[RR]".to_string();
- let chars = input.chars();
- println!("{:?}", decode_google(chars));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement