Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::cmp::Ordering;
- //use std::fs;
- fn lcm(a: u64, b: u64) -> u64 {
- return a * b / gcd(a, b);
- }
- fn gcd(mut a: u64, mut b: u64) -> u64 {
- let mut remainder;
- return loop {
- remainder = a % b;
- a = b;
- b = remainder;
- if b == 0 {
- break a;
- }
- }
- }
- fn main() {
- let mut pos : [[i64; 4]; 3];
- let mut vel : [[i64; 4]; 3] = [[0; 4]; 3];
- // pos = [[7, 10, 17], [-2, 7, 0], [12, 5, 12], [5, -8, 6]];
- pos = [[7, -2, 12, 5], [10, 7, 5, -8], [17, 0, 12, 6]];
- // let data = fs::read_to_string("input12.txt").expect("Couldn't read input file.");
- // println!("{:?}", data);
- let pos0 = pos.clone();
- let vel0 = vel.clone();
- let mut periods = [0, 0, 0];
- // calculate periods for each dimension
- for dim in 0..3 {
- let mut i : u64 = 0;
- loop {
- // apply gravity to each moon
- for (moon1, p1) in pos[dim].iter().enumerate() {
- for moon2 in moon1+1..4 {
- if *p1 < pos[dim][moon2] {
- vel[dim][moon1] += 1;
- vel[dim][moon2] -= 1;
- } else if *p1 > pos[dim][moon2] {
- vel[dim][moon1] -= 1;
- vel[dim][moon2] += 1;
- }
- }
- }
- // adjust velocity
- for moon in 0..4 {
- pos[dim][moon] += vel[dim][moon];
- }
- i += 1;
- // check if pos the same is the starting point
- if pos[dim].cmp(&pos0[dim]) == Ordering::Equal && vel[dim].cmp(&vel0[dim]) == Ordering::Equal {
- break;
- }
- };
- periods[dim] = i;
- }
- let result = periods.iter().fold(1, |acc, period| lcm(acc, *period));
- println!("Periods are {:?}, same after {:?} iterations.", periods, result);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement