Skip to content

Instantly share code, notes, and snippets.

@iboss-ptk
iboss-ptk / decrypt.scala
Created September 23, 2015 10:06
Single line Caesar cipher decryption in Scala
println(scala.io.Source.fromFile("assgn.txt").toList.map( x => if( "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toList contains x ) (("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toList zip "GHIDDKLMNOFPMRSCTEUVBWXYYA".toList)(scala.collection.breakOut): Map[Char, Char])(x) else x ).mkString)
@iboss-ptk
iboss-ptk / 0_reuse_code.js
Created December 12, 2015 11:23
Here are some things you can do with Gists in GistBox.
// Use Gists to store code you would like to remember later on
console.log(window); // log the "window" object to the console
case class Book(
id: Int, name: String, authors: List[String], rating: Double)
val books = List(
Book(1, "The Pragmatic Programmer",
List("Andrew Hunt", "Dave Thomas"), 4.3),
Book(2, "Lean Startup", List("Eric Ries"), 4.5),
Book(3, "Clean Code", List("Robert C. Martin"), 3.1),
Book(4, "Agile Software Development, Principles, Patterns, and Practices",
List("Robert C. Martin"), 4.5),
// map each element to a key-value pair of id and the book object itself
val bookMap = books.map(book => (book.id, book)).toMap
bookMap(1) // => Book(1,The Pragmatic Programmer,List(Andrew Hunt, Dave Thomas),4.3)
val authors = books.flatMap(book => book.authors).toSet
// => Set(Andrew Hunt, Eric Ries, Blake Masters, Robert C. Martin, Peter Thiel, Dave Thomas)
val fourOrMoreRatingBooks = books
.filter(book => book.rating > 4.0)
.map(book => book.name)
// => List(The Pragmatic Programmer, Lean Startup,
// Agile Software Development, Principles, Patterns, and Practices, From Zero to One)
val numbers = List(1,2,3,4,5)
numbers.reduce((acc, curr) => acc + curr) // => 15
numbers.foldLeft(0)((acc, curr) => acc + curr) // => 15
val accumulatingList = numbers
.foldLeft(List[Int]())((acc, curr) =>
if(!acc.isEmpty) acc :+ (acc.last + curr) else acc :+ curr)
// => List(1, 3, 6, 10, 15)
def contains(numbers: List[Int], target: Int) =
numbers.foldLeft(false)((acc, curr) => if(curr == target) true else acc || false)
contains(numbers, 4) // => true
contains(numbers, 20) // => false
def dotProduct(vector1: Vector[Double], vector2: Vector[Double]) =
vector1.zip(vector2)
.map(v => v._1 * v._2)
.reduce((acc, curr) => acc + curr)
val vector1 = Vector(1.7, 2.3, 4.0)
val vector2 = Vector(2.4, 1.3, 5.1)
dotProduct(vector1, vector2) // => 27.47
List(1, 2, 3) zip List(1, 1)
// => List((1,1), (2,1))