Skip to content

Commit

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

/** You have bottles (from which 1 is poisoned) and poison detecting strips.
* You can reuse strips, but it takes several days for a strip to show the results (contained poison or not).
* How long would it take to find the poison? */
class _06_10_Poison {
static getPoisonedBottle(int bottleCount, Closure<List<Boolean>> test) {
def strips = markStrips(bottleCount)
def results = test(strips).collect { it ? 1 : 0 }
Integer.valueOf(results.join(), 2)
}

private static markStrips(int bottleCount) {
def strips = [].withDefault { [] }
bottleCount.times { bottle ->
for (strip in BitSet.valueOf(bottle).stream())
strips[strip] += bottle
}
strips.reverse()
}
}
19 changes: 19 additions & 0 deletions src/test/groovy/Ch06_MathAndLogicPuzzles/_06_10_PoisonTest.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package Ch06_MathAndLogicPuzzles

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

import static Ch06_MathAndLogicPuzzles._06_10_Poison.getPoisonedBottle

@Unroll class _06_10_PoisonTest extends Specification {
/*@formatter:off*/
def 'poison?'() {
expect: bottleCount.times { poisonedBottle ->
def test = { List<List> strips -> strips.collect { it.contains(poisonedBottle) } }
assert getPoisonedBottle(bottleCount, test) == poisonedBottle
}
where: bottleCount | _
1000 | _
}
/*@formatter:on*/
}

0 comments on commit ea39690

Please sign in to comment.