diff --git a/library/util/Random.scala b/library/util/Random.scala new file mode 100644 index 0000000000000000000000000000000000000000..e055dc51bf2e0ffa6426fa2b2ddbddb2888b2f8f --- /dev/null +++ b/library/util/Random.scala @@ -0,0 +1,32 @@ +/* Copyright 2009-2016 EPFL, Lausanne */ + +package leon.util + +import leon.annotation._ +import leon.lang.xlang._ + +object Random { + + @library + def nextBoolean(): Boolean = epsilon((x: Boolean) => true) + + @library + def nextInt(): Int = epsilon((x: Int) => true) + + @library + def nextInt(max: Int): Int = { + require(max > 0) + epsilon((x: Int) => x >= 0 && x < max) + } ensuring(res => res >= 0 && res < max) + + @library + def nextBigInt(): BigInt = epsilon((x: BigInt) => true) + + @library + def nextBigInt(max: BigInt): BigInt = { + require(max > 0) + epsilon((x: BigInt) => x >= 0 && x < max) + } ensuring(res => res >= 0 && res < max) + +} + diff --git a/testcases/verification/xlang/GuessNumber.scala b/testcases/verification/xlang/GuessNumber.scala index 806948060f944a1e91061e1305bf84c4290faf78..ca1ea724a51d25f3652092e1644259ba07013e5c 100644 --- a/testcases/verification/xlang/GuessNumber.scala +++ b/testcases/verification/xlang/GuessNumber.scala @@ -1,32 +1,35 @@ import leon.lang._ import leon.lang.xlang._ +import leon.util.Random object GuessNumber { - def random(min: Int, max: Int): Int = epsilon((x: Int) => x >= min && x <= max) + def pickRandomly(min: BigInt, max: BigInt): BigInt = { + require(min >= 0 && max >= min) + Random.nextBigInt(max - min + 1) + min + } def main(): Unit = { - val choice = random(0, 10) + val choice = pickRandomly(0, 10) - var guess = random(0, 10) - var top = 10 - var bot = 0 + var guess = pickRandomly(0, 10) + var top: BigInt = 10 + var bot: BigInt = 0 (while(bot < top) { if(isGreater(guess, choice)) { top = guess-1 - guess = random(bot, top) + guess = pickRandomly(bot, top) } else if(isSmaller(guess, choice)) { bot = guess+1 - guess = random(bot, top) + guess = pickRandomly(bot, top) } - }) invariant(guess >= bot && guess <= top && bot >= 0 && top <= 10 && bot <= top && choice >= bot && choice <= top && - true) + }) invariant(guess >= bot && guess <= top && bot >= 0 && top <= 10 && bot <= top && choice >= bot && choice <= top) val answer = bot assert(answer == choice) } - def isGreater(guess: Int, choice: Int): Boolean = guess > choice - def isSmaller(guess: Int, choice: Int): Boolean = guess < choice + def isGreater(guess: BigInt, choice: BigInt): Boolean = guess > choice + def isSmaller(guess: BigInt, choice: BigInt): Boolean = guess < choice }