[java] AoC Day 13 Part 2 with Chinese Remainder Theorem

Viewer

copydownloadembedprintName: AoC Day 13 Part 2 with Chinese Remainder Theorem
  1.  public String partTwo() {
  2.         long time = 0;
  3.         
  4.         //Time after the time, where the bus should come
  5.         int[] dtime = new int[9];
  6.         
  7.         //Times, the bus arrives
  8.         int[] modulos = new int[9];
  9.         
  10.         //Fill dtime and modulos from input
  11.         int index = 0;
  12.         for(int i = 0; i < ids.length; i++){
  13.             if(ids[i] != -1) {
  14.                 modulos[index] = ids[i];
  15.                 dtime[index] = i;
  16.                 index++;
  17.             }
  18.         }
  19.         
  20.         //Product of all modulos
  21.         long M = 1;
  22.         for (int m : modulos) {
  23.             M *= m;
  24.         }
  25.  
  26.         //Calculate with the Chinese Remainder Theorem
  27.         for (int i = 0; i < modulos.length; i++) {
  28.             //Get greatest common divider in form 1 = my * modulos[i] + lam * (M / modulos[i])
  29.             Solution res = ExtendedEuclidianAlghorithm.getGCD(/ modulos[i], modulos[i]);
  30.             
  31.             //Add this to the time, according to the CRT
  32.             time += res.lam * (/ modulos[i]) * dtime[i];
  33.         }
  34.         return "" + Math.abs(time % M);
  35.     }

Editor

You can edit this paste and save as new:

public String partTwo() {
long time = 0;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

File Description
  • AoC Day 13 Part 2 with Chinese Remainder Theorem
  • Paste Code
  • 13 Dec-2020
  • 1.11 Kb
You can Share it: