Advertisement
Guest User

Untitled

a guest
Dec 13th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.95 KB | None | 0 0
  1. use std::cmp::Ordering;
  2. //use std::fs;
  3.  
  4. fn lcm(a: u64, b: u64) -> u64 {
  5.     return a * b / gcd(a, b);
  6. }
  7.  
  8. fn gcd(mut a: u64, mut b: u64) -> u64 {
  9.     let mut remainder;
  10.  
  11.     return loop {
  12.         remainder = a % b;
  13.         a = b;
  14.         b = remainder;
  15.  
  16.         if b == 0 {
  17.             break a;
  18.         }
  19.     }
  20. }
  21.  
  22. fn main() {
  23.     let mut pos : [[i64; 4]; 3];
  24.     let mut vel : [[i64; 4]; 3] = [[0; 4]; 3];
  25.  
  26.     // pos = [[7, 10, 17], [-2, 7, 0], [12, 5, 12], [5, -8, 6]];
  27.     pos = [[7, -2, 12, 5], [10, 7, 5, -8], [17, 0, 12, 6]];
  28.  
  29.     // let data = fs::read_to_string("input12.txt").expect("Couldn't read input file.");
  30.     // println!("{:?}", data);
  31.  
  32.     let pos0 = pos.clone();
  33.     let vel0 = vel.clone();
  34.  
  35.     let mut periods = [0, 0, 0];
  36.  
  37.     // calculate periods for each dimension
  38.     for dim in 0..3 {
  39.         let mut i : u64 = 0;
  40.  
  41.         loop {    
  42.             // apply gravity to each moon
  43.             for (moon1, p1) in pos[dim].iter().enumerate() {
  44.                 for moon2 in moon1+1..4 {
  45.                     if *p1 < pos[dim][moon2] {
  46.                         vel[dim][moon1] += 1;
  47.                         vel[dim][moon2] -= 1;
  48.                     } else if  *p1 > pos[dim][moon2] {
  49.                         vel[dim][moon1] -= 1;
  50.                         vel[dim][moon2] += 1;
  51.                     }
  52.                 }      
  53.             }
  54.  
  55.             // adjust velocity
  56.             for moon in 0..4 {
  57.                 pos[dim][moon] += vel[dim][moon];
  58.             }
  59.            
  60.             i += 1;
  61.  
  62.             // check if pos the same is the starting point
  63.             if pos[dim].cmp(&pos0[dim]) == Ordering::Equal && vel[dim].cmp(&vel0[dim]) == Ordering::Equal {
  64.                 break;
  65.             }
  66.         };
  67.  
  68.         periods[dim] = i;
  69.     }
  70.     let result = periods.iter().fold(1, |acc, period| lcm(acc, *period));
  71.     println!("Periods are {:?}, same after {:?} iterations.", periods, result);
  72.    
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement