Langton's ant: Difference between revisions

→‎{{header|Rust}}: Updated to the Rust 1.3.0
(→‎{{header|Rust}}: Updated to the Rust 1.3.0)
Line 4,916:
 
=={{header|Rust}}==
<lang Rust>struct Ant {
x: usize,
struct Ant {
x y: uintusize,
dir: Direction
y: uint,
dir: Direction
}
 
#[derive(Clone,Copy)]
impl Ant {
enum Direction {
fn move(&mut self, vec: &mut Vec<Vec<u8>>) {
North,
East,
South,
West
 
use Direction::*;
let pointer = vec.get_mut(self.y).get_mut(self.x);
//change direction
match *pointer {
0 => self.dir = self.dir.right(),
1 => self.dir = self.dir.left(),
_ => fail!("Unexpected colour in grid")
}
//flip colour
//if it's 1 it's black
//if it's 0 it's white
*pointer ^= 1;
 
structimpl Ant {
//move direction
fn movemv(&mut self, vec: &mut Vec<Vec<u8>>) {
match self.dir {
let pointer = &mut vec.get_mut([self.y).get_mut(][self.x)];
North => self.y -= 1,
//change direction
South => self.y += 1,
match *pointer {
East => self.x += 1,
West 0 => self.xdir -= 1self.dir.right(),
0 1 => self.dir = self.dir.rightleft(),
}
_ => failpanic!("Unexpected colour in grid")
}
//flip colour
//if it's 1 it's black
//if it's 0 it's white
*pointer ^= 1;
 
//move direction
}
match self.dir {
North => self.y -= 1,
South => self.y += 1,
East => self.x += 1,
West => self.x -= 1,
}
 
}
enum Direction {
North,
East,
South,
West
}
 
impl Direction {
fn right(self) -> Direction {
match self {
North => East,
East => South,
South => West,
West => North,
}
}
}
}
 
fn left(self) -> Direction {
//3 rights equal a left
self.right().right().right()
}
}
}
 
fn main(){
//create a 100x100 grid using vectors
let mut grid: Vec<Vec<u8>> = Vec::from_elem(vec![vec![0; 100,]; Vec::from_elem(100, 0u8))];
let mut ant = Ant {
x: 50, y: 50, dir: Direction::North
};
 
while ant.x < 100 && ant.y < 100 {
ant.movemv(&mut grid);
}
}
for each in grid.iter() {
//construct string
//using iterator methods to quickly convert the vector
//to a string
let string = each.iter()
.map(|&x| if x == 0 { " " } else { "#" })
.map(|&x| String::from_byte(x+32))
.fold(String::new(), |x, y| x+y);
.replace println!("!{}", "#"string);
}
println!("{}", string);
}</lang>
}
}
</lang>
 
=={{header|Scala}}==