Skip to content

Instantly share code, notes, and snippets.

@retraigo
Last active December 12, 2022 17:41
Show Gist options
  • Save retraigo/0f02ce11bf96d4cbd7501293c4ebdfad to your computer and use it in GitHub Desktop.
Save retraigo/0f02ce11bf96d4cbd7501293c4ebdfad to your computer and use it in GitHub Desktop.
object Triplicate {
def main(args: Array[String]): Unit = {
println("Enter numbers separated by a comma")
val nums = scala.io.StdIn.readLine()
val arr = nums.split(",").map(x => x.toInt)
val trip = arr.flatMap(x => List(x, x, x))
println(s"OG Array: ${arr.toSeq}")
println(s"Triplicated Array: ${trip.toSeq}")
}
}
import scala.io.StdIn.{readInt, readLine}
import scala.collection.mutable.ArrayBuffer
// Java has ArrayList for a growable array
// Scala does not have ArrayList
// We instead have ArrayBuffer
object StringOp {
def main(args: Array[String]): Unit = {
val arrList: ArrayBuffer[String] = new ArrayBuffer()
var cont = true
while(cont == true) {
println("1. Append to end")
println("2. Insert at")
println("3. Search an element")
println("4. List all elements starting with given letter")
val choice = readInt()
choice match {
case 1 => {
println("String to insert?")
val item = readLine()
arrList.append(item)
}
case 2 => {
println("String to insert?")
val item = readLine()
println("Insert at?")
var pos = readInt()
if(pos <= 0) pos = 1
arrList.insert(pos - 1, item)
}
case 3 => {
println("String to search?")
val item = readLine()
val pos = arrList.indexOf(item)
if(pos != -1) println(s"It exists at position ${pos + 1}")
else println("It does not exist.")
}
case 4 => {
println("Letter to start with?")
val item = readLine()
val res = arrList.filter(x => x.startsWith(item))
println(res)
}
case _ => {
println("Exiting")
cont = false
}
}
// Wait for input before proceeding to next
readLine()
}
}
}
object OddOrEven {
def main(args: Array[String]) = {
println("Enter numbers separated by a comma")
val nums = scala.io.StdIn.readLine()
val arr = nums.split(",").map(x => x.toInt)
for (i <- 0 until arr.length) {
for (j <- i until arr.length) {
if (arr(j) % 2 == 0) {
val k = arr(i);
arr(i) = arr(j);
arr(j) = k;
}
}
}
println(arr.toSeq);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment