# array

A “Minority Report” Monte Carlo simulation in Scala alvin June 9, 2017 - 8:17am

“The Precogs are never wrong. But occasionally they do disagree.”
~ Minority Report

This article shares the source code for a Monte Carlo simulation that I wrote in Scala. It was inspired by the movie Minority Report, as well as my own experience.

## Background

For the purposes of this simulation, imagine that you have three people that are each “right” roughly 80% of the time. For instance, if they take a test with 100 questions, each of the three individuals will get 80 of the questions right, although they may not get the same questions right or wrong. Given these three people, my question to several statisticians was, “If two of the people have the same answer to a given question, what are the odds that they are correct? Furthermore, if all three of them give the same answer to a question, what are the odds that they are right?”

## Scala: How to fill/populate a list (same element or different elements)

As a quick note, if you ever need to fill/populate a Scala list with the same element X number of times, a simple solution is to use the `fill` method, like this:

``````scala> val x = List.fill(3)("foo")
x: List[String] = List(foo, foo, foo)``````

If you want to populate a list with different element values, another approach is to use the `tabulate` method:

How to print an array in Android Log output (Logcat) alvin February 7, 2017 - 7:55pm

If you need to dump the contents of an array to the Android Log (Logcat) output, I can confirm that this approach works, at least with simple arrays of integers and strings that know how to print themselves:

`Log.i("MyAndroidClass", Arrays.toString(arr));`

If you’re trying to print more complicated arrays of custom objects you’ll probably need to implement good `toString` methods on those objects, and then this technique should work.

## How to set Android Spinner data (array) from Java code

As a quick note, this source code shows how to set the data (array) on an Android Spinner from Java code:

Scala code to read a text file to an Array (or Seq) alvin January 17, 2017 - 5:04pm

As a quick note, I use code like this read a text file into an `Array`, `List`, or `Seq` using Scala:

```def readFile(filename: String): Seq[String] = {
val bufferedSource = io.Source.fromFile(filename)
val lines = (for (line <- bufferedSource.getLines()) yield line).toList
bufferedSource.close
lines
}```
Creating random strings and shuffling them (for JavaFX ListView) alvin January 17, 2017 - 4:35pm

As a short “note to self,” I just used this Scala code to (a) create a list that contains random strings of different lengths, then (b) shuffle the list of strings to create a more random effect:

## How to shuffle (randomize) a list in Scala

As a quick note today, to shuffle a list in Scala, use this technique:

`scala.util.Random.shuffle(List(1,2,3,4))`

Here’s what this approach looks like in the Scala REPL: