Created
December 17, 2014 13:11
-
-
Save tauty/09860bd394181fb7e9cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.tauty.study.quiz; | |
import java.util.Arrays; | |
/** | |
* Created by tetsuo.uchiumi on 12/17/14. | |
*/ | |
public class LightSwitchingPuzzle { | |
public static void main(String[] args) { | |
new LightSwitchingPuzzle().execute(); | |
} | |
private void execute() { | |
System.out.println(minFlips("YYYYYY")); | |
System.out.println(minFlips("YNYNYNYNY")); | |
System.out.println(minFlips("NNNNNNNNNN")); | |
System.out.println(minFlips("YYYNYYYNYYYNYYNYYYYN")); | |
System.out.println(minFlips("NYNNYNNNYNNNNYNNNNNYNNNNNNYNNNNNNNY")); | |
} | |
public int minFlips(String state) { | |
char[] chars = new char[state.length()]; | |
state.getChars(0, state.length(), chars, 0); | |
return turn(chars, 0, 0); | |
} | |
private int turn(char[] chars, int index, int times) { | |
System.out.println(Arrays.toString(chars)); | |
for (int i = index; i < chars.length; i++) { | |
char c = chars[i]; | |
if(c == 'Y') { | |
toggle(chars, i + 1); | |
return turn(chars, i + 1, times + 1); | |
} | |
} | |
return times; | |
} | |
private void toggle(char[] chars, final int DELTA) { | |
for (int i = DELTA - 1; i < chars.length; i += DELTA) { | |
chars[i] = chars[i] == 'Y' ? 'N' : 'Y'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment