-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Pap Lőrinc
committed
Mar 6, 2016
1 parent
77599cd
commit d0a8e98
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
src/main/groovy/Ch06_MathAndLogicPuzzles/_06_08_EggDrop.groovy
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
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
17
src/test/groovy/Ch06_MathAndLogicPuzzles/_06_08_EggDropTest.groovy
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
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*/ | ||
} |