, , , . , . , :
[2, 0, 2, 0, 2]
[2/3, 4/3, 2/3, 4/3, 2/3]
[2/3, 0, 2, 0, 2]
[2/3, 8/9, 2, 0, 2]
[2/3, 8/9, 26/9, 0, 2]
:
struct Body {
x: i16,
y: i16,
v: i16,
}
fn main() {
let mut bodies = vec![
Body { x: 10, y: 10, v: 0 },
Body { x: 20, y: 30, v: 0 },
];
for _ in 0..2 {
let next_bodies = bodies
.iter()
.map(|b| {
let next_v = bodies
.iter()
.fold(b.v, { |a, b_inner| a + b.x * b_inner.x });
Body { v: next_v, ..*b }
})
.collect();
bodies = next_bodies;
}
println!("{:?}", bodies);
}
:
[Body { x: 10, y: 10, v: 600 }, Body { x: 20, y: 30, v: 1200 }]
, , , . .
., Cell RefCell, :
use std::cell::Cell;
struct Body {
x: i16,
y: i16,
v: i16,
}
fn main() {
let bodies = vec![
Cell::new(Body { x: 10, y: 10, v: 0 }),
Cell::new(Body { x: 20, y: 30, v: 0 }),
];
for i in 0..2 {
println!("Turn {}", i);
for b_outer_cell in &bodies {
let mut b_outer = b_outer_cell.get();
println!("{:?}", b_outer);
let mut a = b_outer.v;
for b_inner in &bodies {
let b_inner = b_inner.get();
a = a + b_outer.x * b_inner.x;
println!("{:?}, a: {}", b_inner, a);
}
b_outer.v = a;
b_outer_cell.set(b_outer);
}
}
println!("{:?}", bodies);
}
[Cell { value: Body { x: 10, y: 10, v: 600 } }, Cell { value: Body { x: 20, y: 30, v: 1200 } }]