Skip to content

Commit

Permalink
CTCI 6.09: Lockers.groovy
Browse files Browse the repository at this point in the history
  • Loading branch information
Pap Lőrinc committed Mar 6, 2016
1 parent d0a8e98 commit 72e565f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/main/groovy/Ch06_MathAndLogicPuzzles/_06_09_Lockers.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package Ch06_MathAndLogicPuzzles

/** Given closed lockers, by opening everyone, closing every second, opening every third, etc, which lockers will be open at the end? */
class _06_09_Lockers {
static openLockers(int lockerCount) {
def results = new BitSet()

def lockerRange = 0..lockerCount
for (step in lockerRange)
lockerRange.step(step + 1) { results.flip(it) }

results.stream().collect()
}
}
17 changes: 17 additions & 0 deletions src/test/groovy/Ch06_MathAndLogicPuzzles/_06_09_LockersTest.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package Ch06_MathAndLogicPuzzles

import spock.lang.Specification
import spock.lang.Unroll

import static Ch06_MathAndLogicPuzzles._06_09_Lockers.openLockers
import static java.lang.Math.sqrt

@Unroll class _06_09_LockersTest extends Specification {
/*@formatter:off*/
def 'lockers?'() {
expect: openLockers(lockerCount) == result
where: lockerCount || result
100 || (0..sqrt(lockerCount)).collect{ it**2 }
}
/*@formatter:on*/
}

0 comments on commit 72e565f

Please sign in to comment.