Advertisement
alefhidalgo

ChristmasLights

Jun 20th, 2011
1,540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /**
  4.  * Tuenti Programming Contest
  5.  * Challenge 9: ChristmasLights
  6.  * @author alefhidalgo [at] gmail [dot] com
  7.  */
  8. public class ChristmasLights {
  9.  
  10.     public static final String ALL_OF = "All lights are off :(";
  11.  
  12.     /**
  13.      * optimizedTurnLights -When time > nLigths, even and odd lights are lighted
  14.      * On/off
  15.      *
  16.      * @param nLights
  17.      * @param time
  18.      * @return
  19.      */
  20.     public String optimizedTurnLights(int nLights, long time) {
  21.         if (time < (nLights + 2)) {
  22.             return turnLights(nLights, time);
  23.         } else {
  24.             int aux = (int) ((time - nLights) % 2);
  25.             long newTime = nLights + aux; // all lights switch between even and odd from t=nLigths
  26.             return turnLights(nLights, newTime);
  27.         }
  28.  
  29.     }
  30.  
  31.     private String turnLights(int nLights, long time) {
  32.         String ret = "";
  33.         boolean[] lights = new boolean[nLights];
  34.         lights[0] = true;
  35.         for (int t = 1; t < time; t++) {
  36.             turn(lights);
  37.         }
  38.         for (int i = 0; i < lights.length; i++) {
  39.             if (lights[i]) {
  40.                 ret += ((ret != "") ? " " : "") + i;
  41.             }
  42.         }
  43.         return ret.length() > 0 ? ret : ChristmasLights.ALL_OF;
  44.     }
  45.  
  46.     private void turn(boolean[] ligths) {
  47.         for (int i = 0; i < ligths.length; i++) {
  48.             if (ligths[i]) {
  49.                 if (i < ligths.length - 1) {
  50.                     ligths[i + 1] = true;
  51.                 }
  52.                 if (i > 0) {
  53.                     ligths[i - 1] = true;
  54.                 }
  55.                 ligths[i] = false;
  56.                 i++;
  57.             }
  58.         }
  59.     }
  60.  
  61.     public static void main(String args[]) {
  62.         ChristmasLights christmasLights = new ChristmasLights();
  63.         Scanner in = new Scanner(System.in);
  64.         int nCases = in.nextInt();
  65.         for (int i = 0; i < nCases; i++) {
  66.             System.out.println(christmasLights.optimizedTurnLights(in.nextInt(), in.nextLong()));
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement