Skip to content

Instantly share code, notes, and snippets.

@alexspurling
Created August 3, 2015 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexspurling/b95b881432caff37ca74 to your computer and use it in GitHub Desktop.
Save alexspurling/b95b881432caff37ca74 to your computer and use it in GitHub Desktop.
Two methods for generating a random distance matrix one in Elm and one in Javascript.
import Array
import Debug
import Random
import Matrix
planetNames : Array.Array String
planetNames = Array.fromList [
"Terra",
"Vulcan",
"Omicron Persei 8",
"Altair III",
"Qo'noS" ]
planetDistances : Random.Seed -> Matrix.Matrix Int
planetDistances seed =
let
numPlanets = Array.length planetNames
--Get a whole bunch of random distances (one for each pair of planets i.e n^2)
(randomDistances, seed') = Random.generate (Random.list (numPlanets * numPlanets) (Random.int 1 10000)) seed
randomMatrix = Array.indexedMap
(\index planet ->
let
--Get a subset of the random numbers that we generated earlier
randomSubset = List.take numPlanets (List.drop (index * numPlanets) randomDistances)
in
Array.fromList randomSubset) planetNames
mirroredMatrix = mirrorMatrix randomMatrix
finalMatrix = zeroDiagonal mirroredMatrix
foo = Debug.log "Distances" finalMatrix
in
finalMatrix
--copies the bottom left of the matrix over to the top right
mirrorMatrix : Matrix.Matrix Int -> Matrix.Matrix Int
mirrorMatrix matrix =
Matrix.mapWithLocation
(\(x, y) distance ->
if x < y then
distance
else
Maybe.withDefault 0 (Matrix.get (y, x) matrix))
matrix
zeroDiagonal : Matrix.Matrix Int -> Matrix.Matrix Int
zeroDiagonal matrix =
Matrix.mapWithLocation (\(x, y) distance -> if x == y then 0 else distance) matrix
var planets = [
"Terra",
"Vulcan",
"Omicron Persei 8",
"Altair III",
"Qo'noS" ]
function planetDistances() {
var numPlanets = planets.length;
var distances = [];
//Initialise the matrix (this wouldn't be necessary in Java)
for (var i = 0; i < numPlanets; i++) {
distances[i] = []
distances[i][i] = 0
}
for (var i = 0; i < numPlanets; i++) {
for (var j = 0; j < i; j++) {
var randomValue = Math.floor(Math.random() * 10000)
distances[i][j] = randomValue
distances[j][i] = randomValue
}
}
return distances
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment