Skip to content

Commit

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

import static java.lang.Math.max
import static java.lang.Math.sqrt

/** You are given two identical eggs to find out from which floor of a tall building they would break */
class _06_08_EggDrop {
static dropCount(int floorCount, Closure<Boolean> breaks) {
def increment = max(2, (sqrt(1 + 8 * floorCount) - 1) / 2) // x * (x + 1) / 2 = floorCount
def floor = increment
while (floor < floorCount && !breaks(floor as int))
floor += --increment

floor = (floor - increment + 1) as int
while (floor <= floorCount && !breaks(floor))
floor++

(floor > floorCount) ? Integer.MAX_VALUE
: floor
}
}
17 changes: 17 additions & 0 deletions src/test/groovy/Ch06_MathAndLogicPuzzles/_06_08_EggDropTest.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package Ch06_MathAndLogicPuzzles

import spock.lang.Specification

import static Ch06_MathAndLogicPuzzles._06_08_EggDrop.dropCount

class _06_08_EggDropTest extends Specification {
/*@formatter:off*/
def 'eggDrop?'() {
expect: for (floorCount in 1..100) {
assert dropCount(floorCount) { false } == Integer.MAX_VALUE
for (breakingFloor in 1..floorCount)
assert dropCount(floorCount) { it >= breakingFloor } == breakingFloor
}
}
/*@formatter:on*/
}

0 comments on commit d0a8e98

Please sign in to comment.