Skip to content

Instantly share code, notes, and snippets.

@JasonShin
Created September 4, 2018 09:14
Show Gist options
  • Save JasonShin/d830a8d9c2e13a6ab1b5345395fbba99 to your computer and use it in GitHub Desktop.
Save JasonShin/d830a8d9c2e13a6ab1b5345395fbba99 to your computer and use it in GitHub Desktop.
import scala.io.StdIn.{readLine, readInt}
import scala.math._
import scala.collection.mutable.ArrayBuffer
import java.io.PrintWriter
import scala.io.Source
object ScalaTutorial {
def main(args: Array[String]) {
var i = 0
do {
println(i)
i += 1
} while (i <= 20)
var z = 0
for (z <- 1 to 10) {
println(z)
}
val randLetters = "ABCDAFFADFASF"
for (i <- 0 until randLetters.length)
println(randLetters(i))
val aList = List(1,2,2,3,4)
for (i <- aList)
println("List items" + i)
var k = 0
var evenList = for { k <- 1 to 20 if (k % 2) == 0 } yield k
print(evenList)
var m = 0
for (m <- 1 to 5; n <- 6 to 10) {
println("m : " + m)
println("n: " + n)
}
def printPrimes() {
val primeList = List(1, 2, 3, 4 ,5, 6, 11)
for (c <- primeList) {
if (c == 11) {
return
}
if (c != 1) {
println(c)
}
}
}
printPrimes
var numberGuess = 0
do {
print("Guess a number ")
numberGuess = readLine.toInt
print(numberGuess)
} while (numberGuess != 15)
printf("You guessed the secret number %d\n", 15)
val name = "Jason"
val age = 15
val weight = 1241.5
println(s"Hello $name")
println(f"I am ${age + 1} and weight $weight")
printf("'%d'\n", 5)
// Strings
var randSent = "Hello I like Scala hahahah"
println("3rd index: ", randSent(3))
println(randSent.length)
println(randSent.concat("yoyo"))
println("dragon starts at index" + randSent.indexOf("Hello"))
println(randSent.toArray)
// Functions
def getSum(num1: Int = 1, num2: Int = 1): Int = {
return num1 + num2
}
println("5 + 4 = " + getSum(5, 4))
println("5 + 4 = " + getSum(num2 = 6, num1 = 23))
def sayHi(): Unit = {
println("Hi how are you")
}
sayHi
def getSum2(args: Int*) : Int = {
var sum : Int = 0
for (num <- args) {
sum += num
}
sum
}
println("get sum " + getSum2(1, 2, 3, 4))
def factorial(num : BigInt) : BigInt = {
if (num <= 1)
1
else
num * factorial(num - 1)
}
println("Factorial of 50 = " + factorial(50))
// Arrays
val favNums = new Array[Int](20)
val friends = Array("Bob", "Tom")
friends(0) = "Sue"
println("Best friends " + friends(0))
val friends2 = ArrayBuffer[String]()
friends2.insert(0, "Phil")
friends2 += "Mark"
friends2 ++= Array("Susy", "Paul")
friends2.insert(1 ,"Jason", "Tom")
friends2.remove(1, 2)
var friend : String = " "
for (friend <- friends2)
println(friend)
for (g <- 0 to favNums.length - 1) {
favNums(g) = g
println(favNums(g))
}
val favNumsTimes2 = for(num <- favNums) yield 2 * num
favNumsTimes2.foreach(println)
var favNumsDiv4 = for(num <- favNums if num % 4 == 0) yield num
favNumsDiv4.foreach(print)
var multTable = Array.ofDim[Int](10, 10)
for (i <- 0 to 9) {
for (j <- 0 to 9) {
multTable(i)(j) = i * j
}
}
for (i <- 0 to 9) {
for (j <- 0 to 9) {
printf("%d : %d = %d\n", i, j, multTable(i)(j))
}
}
println("Sum : " + favNumsTimes2.sum)
println("Min: " + favNumsTimes2.min)
println("Max: " + favNumsTimes2.max)
val sortedNums = favNumsTimes2.sortWith(_>_)
println(sortedNums.deep.mkString(", "))
// Map
val employees = Map("Manager" -> "Bob Smith", "Secretary" -> "Sue Brown")
if(employees.contains("Manager")) {
printf("Manager: %s\n", employees("Manager"))
}
val customers = collection.mutable.Map(100 -> "Paul Smith", 101 -> "Sally Smith")
printf("Cust 1: %s\n", customers(100))
customers(100) = "Tom Marks"
customers(102) = "Megan Swift"
for ((k, v) <- customers)
printf("%d : %s\n", k, v)
// Tuples
var tupleMarge = (103, "Marge Simpson", 10.25)
printf("%s owes us $%.2f\n", tupleMarge._2, tupleMarge._3)
tupleMarge.productIterator.foreach{ i => println(i) }
println(tupleMarge.toString())
// Classes
val rover = new Animal
rover.setName("Rover")
rover.setSound("Woof")
printf("%s says %s\n", rover.getName, rover.getSound)
val whisker = new Animal("Whisker", "Meow")
println(s"${whisker.getName} with id ${whisker.id} says ${whisker.getSound}")
println(whisker.toString)
val spike = new Dog("Spike", "Woof", "Grrrr")
spike.setName("Spike")
println(spike)
val fang = new Wolf("Fang")
fang.moveSpeed = 36.0
println(fang.move)
val superman = new Superhero("Superman")
println(superman.fly)
println(superman.hitByBullet)
println(superman.ricochet(2500))
// Higher order functions
val log10Func = log10 _
println(log10Func(1000))
List(1000.0, 10000.0).map(log10Func).foreach(println)
List(1, 2, 3, 4, 5).map((x : Int) => x * 50).foreach(println)
List(1, 2, 3, 4, 5).filter(_ % 2 == 0).foreach(println)
def times3(num : Int) = num * 3
def times4(num : Int) = num * 4
def multIt(func : (Int) => Double, num : Int) = {
func(num)
}
printf("3 * 100 = %.1f\n", multIt(times4, 100))
val divisorVal = 5
val divisor5 = (num : Double) => num / divisorVal
println("5 / 5 = " + divisor5(5.0))
// Exceptions
def divideNums(num1 : Int, num2 : Int) = try {
(num1 / num2)
} catch {
case ex : java.lang.ArithmeticException => "Can't divide by zero"
} finally {
// clean up after exception
}
println("3 / 0 " + divideNums(3, 0))
}
trait Flyable {
def fly : String
}
trait BulletProof {
def hitByBullet : String
def ricochet(startSpeed : Double) : String = {
"The bullet ricochets at a speed of %.1f ft/sec".format(startSpeed * .75)
}
}
class Superhero(val name: String) extends Flyable with BulletProof {
def fly = "%s flys through the air".format(this.name)
def hitByBullet = "The bullet bounces off of %s".format(this.name)
}
// Abstract class
abstract class Mammal(val name : String) {
var moveSpeed : Double
def move : String
}
class Wolf(name : String) extends Mammal(name) {
var moveSpeed = 35.0
def move = "The worlf %s runs %.2f mph".format(this.name, this.moveSpeed)
}
class Animal(var name: String, var sound: String) {
this.setName(name)
val id = Animal.newIdNum
def getName() : String = name
def getSound() : String = sound
def setName(name: String) {
if(!(name.matches(".*\\d+.*"))) {
this.name = name
} else {
this.name = "No Name"
}
}
def setSound(sound: String) {
this.sound = sound
}
// Constructor with params
def this(name: String) {
this("No Name", "No Sound")
this.setName(name)
}
// Constructor with no params
def this() {
this("No Name", "No Sound")
}
override def toString() : String = {
return "%s with the id %d says %s".format(this.name, this.id, this.sound)
}
}
object Animal {
private var idNumber = 0
private def newIdNum = { idNumber += 1; idNumber }
}
class Dog(name: String, sound: String, growl: String) extends Animal(name, sound) {
def this(name: String, sound: String) {
this("No Name", sound, "No Growl")
this.setName(name)
}
def this(name: String) {
this("No Name", "No Sound", "No Growl")
this.setName(name)
}
def this() {
this("No Name", "No Sound", "No Growl")
}
override def toString(): String = {
return "Growl!!"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment