random

A Java method that returns a random boolean value based on a probability

If you ever need a Java method that returns a boolean value based on a given probability, I can confirm that this method works:

/**
 * `probability` should be given as a percentage, such as
 * 10.0 (10.0%) or 25.5 (25.5%). As an example, if `probability` 
 * is 60% (60.0), 100 calls to this function should return ~60 
 * `true` values.
 * (Note that Math.random returns a value >= 0.0 and < 1.0.)
 */
static boolean getRandomBoolean(float probability) {
    double randomValue = Math.random()*100;  //0.0 to 99.9
    return randomValue <= probability;
}

ScalaCheck custom generator examples

Table of Contents1 - Custom generators2 - Built-in ScalaCheck generators3 - How to use ScalaCheck generators4 - More ScalaCheck generators

Writing custom generators for ScalaCheck can be one of the more difficult and/or time-consuming parts of using it. As a result I thought I’d start putting together a list of generators that I have written or seen elsewhere. Unfortunately I can’t credit all the ones I’ve seen in other places because I google’d and copied them many moons ago, but I’ll give credit/attribution to all the ones I can.

Back to top

Custom generators

This is a combination of generators I wrote, and some that I copied from other places and may have modified a little:

How to generate a small random number in Kotlin

If you need to generate a small random number in Kotlin, I find that this approach works:

val r = (1..10).shuffled().first()

That code generates a single random number in the range from 1 to 10 (including 1 on the low end and 10 on the high end).

You can use the technique to simulate the rolling of a dice (die):

val r = (1..6).shuffled().first()

Or simulate flipping a coin (0=heads, 1=tails, or vice versa):

val r = (1..2).shuffled().first()

This also works for the coin flip simulation:

Scala List class: methods, examples, and syntax alvin May 22, 2018 - 1:00pm

This page contains a large collection of examples of how to use the methods on the Scala List class.

The Scala List class as an immutable, linear, linked-list class. It’s very efficient when it makes sense for your algorithms to (a) prepend all new elements, (b) work with it in terms of its head and tail elements, and (c) use functional methods that traverse the list from beginning to end, such as filter, map, foldLeft, reduceLeft.

Scala Seq class: methods, examples, and syntax

This page contains a large collection of examples of how to use the methods on the Scala Seq class.

Important note about Seq, IndexedSeq, and LinearSeq

As an important note, I use Seq in the following examples to keep things simple, but in your code you should be more precise and use IndexedSeq or LinearSeq where appropriate. As the Seq class Scaladoc states: