UVA 10550 – Combination Lock

A bit of math but an otherwise really simple problem. I would have voted this as harder than the earlier problems as you need to figure out certain numbers based on the direction you are rotating.

import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 
 * @author Sanchit M. Bhatnagar
 * @see http://uhunt.felix-halim.net/id/74004
 * 
 */
public class P10550 {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    while (sc.hasNextLine()) {
      int degree = sc.nextInt();
      int first = sc.nextInt();
      int second = sc.nextInt();
      int third = sc.nextInt();
      if (first == second && second == third && third == degree && degree == first) {
        break;
      } else {
        out.println(doSolve(degree, first, second, third));
      }
    }
    out.close();
    sc.close();
  }

  private static long doSolve(int degree, int first, int second, int third) {
    // 40 numbers = 360 degrees. 1 number = 9 degrees.
    long ans = 0;
    // 2 clockwise turns.
    ans += 720;
    // To first number
    ans += 9 * findWay(degree, first, 0);
    // One counterclockwise turn
    ans += 360;
    // To second number
    ans += 9 * findWay(first, second, 1);
    // To third number
    ans += 9 * findWay(second, third, 0);
    return ans;
  }

  private static int findWay(int from, int to, int cw) {
    //Could memo this technically.
    
    int count = 0;
    if (cw == 1) {
      while (from != to) {
        from++;
        if (from == 40)
          from = 0;
        count++;
      }
    } else {
      while (from != to) {
        from--;
        if (from == -1)
          from = 39;
        count++;
      }
    }
    return count;
  }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.