Skip to content

Instantly share code, notes, and snippets.

@retraigo
Created September 4, 2022 07:48
Show Gist options
  • Save retraigo/672ce8f0897cd6cdf4aa03f002957084 to your computer and use it in GitHub Desktop.
Save retraigo/672ce8f0897cd6cdf4aa03f002957084 to your computer and use it in GitHub Desktop.
Scala assignments

1. Write a Scala program to sum values of a given array.

import scala.io.StdIn.{readDouble};
import scala.collection.mutable.ArrayBuffer;
object SumArray {
  def main(args: Array[String]) = {
    var listOfNumbers = new ArrayBuffer[Double]();
    println("Enter numbers to add. Enter 0 to stop.");
    var current = 1.0;
    while (current != 0.0) {
      try {
        current = readDouble();
        listOfNumbers.append(current);
      } catch {
        case e: NumberFormatException => {
          println("Enter only numbers.");
        }
        case _: Throwable => {
          println("An error occured.");
        }
      }
    }
    println(
      s"The sum of all numbers provided to the array is ${listOfNumbers.sum}"
    );
  }
}

Output

Enter numbers to add. Enter 0 to stop.
6546
4343
343
544
4335.95485
545.343
556.3
64
9
0
The sum of all numbers provided to the array is 17286.59785

2. Write a Scala program to remove a specific element from a given array.

import scala.io.StdIn.{readLine};
import scala.collection.mutable.ArrayBuffer;

object RemoveFromArray {
  def main(args: Array[String]) = {
    var listOfItems = new ArrayBuffer[String]();
    println("Enter elements to add to array. Enter 0 to stop.");
    var current = "";
    while (current != "0") {
      try {
        current = readLine();
        if(current != "0") listOfItems.append(current);
      } catch {
        case _: Throwable => {
          println("An error occured.");
        }
      }
    }
    println("Element to remove?");
    val toRemove = readLine();
    println(s"Original Array: $listOfItems");
    println(s"Array without $toRemove: ${listOfItems.filter(s => s != toRemove)}");
  }
}

Output

Enter elements to add to array. Enter 0 to stop.
dora
doraemon
mona
monaemon
dora
0
Element to remove?
dora
Original Array: ArrayBuffer(dora, doraemon, mona, monaemon, dora)
Array without dora: ArrayBuffer(doraemon, mona, monaemon)

3. Write a Scala program to rotate one element left of an given array (length 1 or more) of integers

import scala.io.StdIn.{readLine};
import scala.collection.mutable.ArrayBuffer;

object RotateArrayLeft {
  def main(args: Array[String]) = {
    var listOfItems = new ArrayBuffer[String]();
    println("Enter elements to add to array. Enter 0 to stop.");
    var current = "";
    while (current != "0") {
      try {
        current = readLine();
        if(current != "0") listOfItems.append(current);
      } catch {
        case _: Throwable => {
          println("An error occured.");
        }
      }
    }
    println(s"Original Array: $listOfItems");
    listOfItems = listOfItems.tail :+ listOfItems.head;
    println(s"Rotate left: $listOfItems");
  }
}

Output

Enter elements to add to array. Enter 0 to stop.
watermelon    
eats
bananas
0
Original Array: ArrayBuffer(watermelon, eats, bananas)
Rotate left: ArrayBuffer(eats, bananas, watermelon)

4. Write a Scala program to find the maximum and minimum value of an array of integers.

import scala.io.StdIn.{readInt};
import scala.collection.mutable.ArrayBuffer;
object MinMaxArray {
  def main(args: Array[String]) = {
    var listOfNumbers = new ArrayBuffer[Int]();
    println("Enter numbers to add. Enter 0 to stop.");
    var current = 1;
    while (current != 0) {
      try {
        current = readInt();
        if(current != 0) listOfNumbers.append(current);
      } catch {
        case e: NumberFormatException => {
          println("Enter only whole numbers.");
        }
        case _: Throwable => {
          println("An error occured.");
        }
      }
    }
    println(
      s"The max of all numbers provided to the array is ${listOfNumbers.max}"
    );
    println(
      s"The min of all numbers provided to the array is ${listOfNumbers.min}"
    );
  }
}

Output

Enter numbers to add. Enter 0 to stop.
1
3
5
7
9
0
The max of all numbers provided to the array is 9
The min of all numbers provided to the array is 1

5. Write a Scala program to find a missing number in an array of integers.

import scala.io.StdIn.{readInt};
import scala.collection.mutable.ArrayBuffer;
object MissingNumberInArray {
  def main(args: Array[String]) = {
    var listOfNumbers = new ArrayBuffer[Int]();
    println("Enter numbers to add. Enter 0 to stop.");
    var current = 1;
    while (current != 0) {
      try {
        current = readInt();
        if(current != 0) listOfNumbers.append(current);
      } catch {
        case e: NumberFormatException => {
          println("Enter only whole numbers.");
        }
        case _: Throwable => {
          println("An error occured.");
        }
      }
    }
    println(s"Original Array: $listOfNumbers");
    var missingNumbers = new ArrayBuffer[Int]();
    for(i <- listOfNumbers.min to listOfNumbers.max) {
      if(listOfNumbers.indexOf(i) == -1) missingNumbers.append(i);
    }
    println(s"Missing Numbers: $missingNumbers");
  }
}

Output

Enter numbers to add. Enter 0 to stop.
1
3
5
7
9
0
Original Array: ArrayBuffer(1, 3, 5, 7, 9)
Missing Numbers: ArrayBuffer(2, 4, 6, 8)

6. Write a Scala program to print after removing duplicates from a given string. 

import scala.io.StdIn.{readLine};
object MissingNumberInArray {
  def main(args: Array[String]) = {
    println("Enter string: ");
    var string = readLine();
    println(s"Original String: $string");
    var stringWithoutDuplicates = "";
    for (x <- 0 until string.length()) {
      if (string.indexOf(string(x)) == x) stringWithoutDuplicates += string(x);
    }
    println(s"String without duplicates: $stringWithoutDuplicates")
  }
}

Output

Enter string: 
She sells seashells by the seashore
Original String: She sells seashells by the seashore
String without duplicates: She slabytor

7. Write a Scala program to reverse every word in a given string.

import scala.io.StdIn.{readLine};
import scala.collection.mutable.ArrayBuffer;
object ReverseWordsInString {
  def main(args: Array[String]) = {
    println("Enter string: ");
    var string = readLine();
    println(s"Original String: $string");
    var stringWithReversed = ArrayBuffer.from(string.split(" ")).map((s: String) => s.reverse).mkString(" ")
    println(s"String with reversed words: $stringWithReversed")
  }
}

Output

Enter string: 
She sells seashells by the seashore
Original String: She sells seashells by the seashore
String with reversed words: ehS slles sllehsaes yb eht erohsaes

8. Write a Scala program to compare two strings lexicographically.

import scala.io.StdIn.{readLine};
import scala.collection.mutable.ArrayBuffer;
object CompareStrings {
  def main(args: Array[String]) = {
    println("Enter first string: ");
    val string1 = readLine();
    println("Enter second string: ");
    val string2 = readLine();
    if (string1 == string2) {
      println(s"\"$string1\" is equal to \"$string2\"");
    } else {
      if (string1.compareTo(string2) > 0) {
        println(s"\"$string1\" is less than \"$string2\"");
      } else {
        println(s"\"$string1\" is greater than \"$string2\"");
      }
    }
  }
}

Output

Enter first string: 
Pikachu
Enter second string: 
Polka
"Pikachu" is greater than "Polka"

Enter first string: 
Watermelon
Enter second string: 
Dragonfruit
"Watermelon" is less than "Dragonfruit"

Enter first string: 
Spider Lily
Enter second string: 
Spider Lily
"Spider Lily" is equal to "Spider Lily"

9. Write a Scala program to replace a specified character with another character.

import scala.io.StdIn.{readLine, readChar};
import scala.collection.mutable.ArrayBuffer;
object ReplaceString {
  def main(args: Array[String]) = {
    println("Enter template string: ");
    val string1 = readLine();
    println("Character to replace?");
    val characterToReplace = readChar();
    println("Character to replace with?");
    val characterToReplaceWith = readChar();
    val string2 = string1.map((c: Char) =>
      if (c == characterToReplace) characterToReplaceWith else c
    )
    println(s"Original String: \"$string1\"");
    println(s"Edited String: \"$string2\"");
  }
}

Output

Enter template string: 
pikachu
Character to replace?
c
Character to replace with?
t
Original String: "pikachu"
Edited String: "pikathu"

10. Write a Scala program to get a substring of a given string between two specified positions.

import scala.io.StdIn.{readLine, readInt};
import scala.collection.mutable.ArrayBuffer;
object SubString {
  def main(args: Array[String]) = {
    println("Enter template string: ");
    val string1 = readLine();
    println("Start of range?")
    val startOfRange = readInt() - 1
    if (startOfRange < 0 || startOfRange >= string1.length)
      println("Start range is out of string range.")
    println("End of range?")
    val endOfRange = readInt()
    if (endOfRange < 0 || endOfRange > string1.length)
      println("End range is out of string range.")
    println(s"Original String: \"$string1\"");
    println(s"Subtring: \"${string1.substring(startOfRange, endOfRange)}\"");
  }
}

Output

Enter template string: 
doraemon
Start of range?
2
End of range?
8
Original String: "doraemon"
Subtring: "oraemon"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment