Advertisement
apad464

Gearing Up for Destruction Solution

Apr 14th, 2022 (edited)
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. public class Solution {
  2.     public static int[] solution(int[] pegs) {
  3.        
  4.         /*source: http://nicholas.rinard.us/2017/03/foo bar-gearing-up-for-destruction.html
  5.         if that link doesn't work use this one: https://web.archive.org/web/20220415012306/http://nicholas.rinard.us/2017/03/foo bar-gearing-up-for-destruction.html (remove the spaces between foo bar in the urls. i had to put spaces or pastebin blocks it)*/
  6.  
  7.         // finds the radius of gear 1
  8.         int numerator = pegs[0];
  9.         int negative = -1;
  10.         for(int peg: pegs) {
  11.             numerator+= 2 * peg * negative;
  12.             negative *= -1;
  13.         }
  14.         numerator+= pegs[pegs.length-1] * negative;
  15.         numerator*= 2;
  16.         int denominator = (pegs.length%2==0) ? 3 : 1;
  17.  
  18.         // simplifies the fraction
  19.         if(numerator%denominator==0) {
  20.             numerator/= denominator;
  21.             denominator = 1;
  22.         }
  23.  
  24.         // checks to see if the fraction is spatially sound
  25.         float limit = ((float)numerator) / ((float)denominator);
  26.         for(int i = 0; i < pegs.length - 2; i++) {
  27.             int space = pegs[i+1] - pegs[i];
  28.             if(limit < 0 || limit > (space-1)) return new int[] {-1, -1};
  29.             limit = space - limit;
  30.         }
  31.  
  32.         return new int[] {numerator, denominator};
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement