Here is one
of the latest java puzzle from dzone javalobby.
import
org.apache.commons.lang.StringUtils;
import
com.google.common.base.Function;
public class ClockPuzzle {
public Function<Integer, Integer> countOnes = new Function<Integer, Integer>() {
public Integer apply(Integer number) {
String binaryString = Integer.toBinaryString(number);
return StringUtils.countMatches(binaryString, "1");
}
};
public long countOnesInOneDay() {
long onesOccurrences = 0;
for (int hour = 0; hour < 24; hour++) {
for (int minute = 0; minute < 60; minute++) {
for (int second = 0; second < 60; second++) {
onesOccurrences += countOnes.apply(hour)
+
countOnes.apply(minute) + countOnes.apply(second);
}
}
}
return onesOccurrences;
}
}
import static org.junit.Assert.assertTrue;
import
org.apache.log4j.Logger;
import org.junit.Test;
public class ClockPuzzleTest {
public static final Logger logger = Logger.getLogger(ClockPuzzleTest.class);
ClockPuzzle clock = new ClockPuzzle();
@Test
public void shouldCoutOnes() {
assertTrue(clock.countOnes.apply(6) == 2);
assertTrue(clock.countOnes.apply(7) == 3);
assertTrue(clock.countOnes.apply(8) == 1);
}
@Test
public void shouldCoutOnesInOneDay() {
logger.info("From " + hourStart + " To " + hourEnd + " contains
"
+
clock.countOnesInOneDay() + " ones.");
}
}
Brak komentarzy:
Prześlij komentarz