About
Scala Practice Exercises – VI Sem CSE ‘B’ – 11/5/23 Basic:
Write a Scala program to compute the sum of the two given integer values. If the two values are the same, then return triples their sum.
object SumCalculator { val value1 = 4; val value2 = 5;def main(args: Array[String]): Unit = {
val sum = calculateSum(value1,value2); println(s"Sum:$sum");
}
def calculateSum(a:Int,b:Int):Int = {
if( a == b) { 3*(a+b) } else { a+b }
}
}
Write a Scala program to get the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference. object AbsoluteDifference { val value = 65; def main(args: Array[String]): Unit = {
val difference = calculateDifference(value); println(s"Absolute Difference:$difference");
}
def calculateDifference(value: Int) :Int =
{
val absoluteDifference = Math.abs(value - 51)
if(value>51)
{
3*absoluteDifference
}
else
{
absoluteDifference
}
}
}
- Write a Scala program to check two given integers, and return true if one of them is 30 or if their sum is 30.
object NumberChecker { val number1 = 15 val number2 = 20 def main(args:Array[String]) : Unit = {
}val result = checkNumbers(number1,number2) println(s"result:$result")
def checkNumbers(a: Int, b: Int): Boolean =
{
if (a == 30 || b == 30 || a + b == 30)
{
true
}
else
{
false
}
} }
- Write a Scala program to remove the character in a given position of a given string. The given position will be in the range 0...string length -1 inclusive.
Write a Scala program to find the larger value from two positive integer values in the range 20..30 inclusive, or return 0 if neither is in that range. object ValueComparator { def main(args: Array[String]): Unit = { val value1 = 25 val value2 = 28
val result = findLargerValue(value1, value2)
println(s"Larger value: $result") }
def findLargerValue(a: Int, b: Int): Int = { if (a >= 20 && a <= 30 && b >= 20 && b <= 30) { if (a > b) {
a
} else {
b
} } else { 0 } } } Strings: 6.Write a Scala program to calculate the sum of the numbers appear in a given string. The given string is: it 15 is25 a 20string The sum of the numbers in the said string is: 60
- Write a Scala program to check if two given strings are rotations of each other: Sample Output: The given strings are: ABACD and CDABA The concatination of 1st string twice is: ABACDABACD The 2nd string CDABA exists in the new string. Strings are rotations of each other
- Write a Scala program to count and print all the duplicates in the input string.
- Write a Scala program to convert all the characters to lowercase, uppercase strings.
- Write a Scala program to get a substring of a given string between two specified positions. Arrays: 11.Write a Scala program to reverse an array of integer values using the same array. object ReverseArray { val array = Array(1, 2, 3, 4, 5) def main(args: Array[String]): Unit = {
println("Original Array:")
printArray(array)
reverseArray(array)
println("Reversed Array:")
printArray(array)
}
def reverseArray(array: Array[Int]): Unit =
{
var start = 0
var end = array.length - 1
while (start < end) {
val temp = array(start)
array(start) = array(end)
array(end) = temp
start += 1
end -= 1
}
}
def printArray(array: Array[Int]): Unit =
{
array.foreach(element => print(element + " "))
println()
}
}
12.Write a Scala program to find the common elements between two arrays of integers.
object CommonElements
{
val array1 = Array(1, 2, 3, 4, 5)
val array2 = Array(4, 5, 6, 7, 8)
def main(args: Array[String]): Unit =
{
val commonElements = findCommonElements(array1,array2)
println("Common Elements:")
printArray(commonElements)
}
def findCommonElements( array1 : Array[Int] , array2 : Array[Int]): Array[Int] =
{
array1.intersect(array2);
}
def printArray(array: Array[Int]): Unit =
{
array.foreach(element => print(element + " "))
println()
}
}
13.Write a Scala program to find the common elements between two arrays of strings. object CommonElements { val array1 = Array("apple", "banana", "orange", "kiwi"); val array2 = Array("banana", "kiwi", "grape", "pear"); def main(args: Array[String]): Unit = { val commonElements = findCommonElements(array1,array2); println("Common Elements:"); printArray(commonElements);
}
def findCommonElements(array1: Array[String], array2: Array[String]): Array[String] =
{
array1.intersect(array2)
}
def printArray(array: Array[String]): Unit =
{
array.foreach(element => print(element + " "))
println()
}
} 14.Write a Scala program to get the difference between the largest and smallest values in an array of integers. The length of the array must be 1 and above.
object arrayDifference { val array = Array (5, 2, 8, 1, 10); def main(args:Array[String]) : Unit = { val difference = findarrayDifference(array); println(s"Difference:$difference");
}
def findarrayDifference(array : Array[Int]):Int =
{
val max = array.max
val min = array.min
max - min
}
} 15.Write a Scala program to find the two elements from a given array of positive and negative numbers such that their sum is closest to zero.
object ClosestToZero { def main(args: Array[String]): Unit = { val array = Array(4, -2, 8, -5, 3, -9, 1)
val (closestElement1, closestElement2) = findClosestToZero(array)
println(s"The two elements closest to zero: $closestElement1 and $closestElement2")
}
def findClosestToZero(array: Array[Int]): (Int, Int) = { var closestSum = Int.MaxValue var closestElement1 = 0 var closestElement2 = 0
for (i <- 0 until array.length - 1) {
for (j <- i + 1 until array.length) {
val sum = array(i) + array(j)
val absoluteSum = Math.abs(sum)
if (absoluteSum < closestSum) {
closestSum = absoluteSum
closestElement1 = array(i)
closestElement2 = array(j)
}
}
}
(closestElement1, closestElement2)
} } Lists:
Write a Scala program to remove single and multiple elements from a given list. object ListRemoval extends App { val myList = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val updatedmyList1 = myList.filter(_ != 5)
val elementsToRemove = List(2, 4, 6) val updatedmyList2 = myList.filterNot(elementsToRemove.contains)
println("Original List: " + myList) println("Updated List (Single Element Removal): " + updatedmyList1) println("Updated List (Multiple Element Removal): " + updatedmyList2)
}
- Write a Scala program to iterate over a list to print the elements and calculate the sum and product of all elements of this list.
object ListSumandProduct { val mylist1:List[Int] = List(1,2,3,4);
def main(args:Array[String]):Unit = { mylist1.foreach(println); val sum:Int = mylist1.sum; println(s"Sum of the list elements: $sum")
val product:Int = mylist1.product
println(s"Product of the list elements: $product")
} }
object ListSumandProduct { val mylist1:List[Int] = List(1,2,3,4);
def main(args:Array[String]):Unit = { mylist1.foreach(println); //var sum:Int = 0; //mylist1.foreach(sum+=_); val sum:Int = mylist1.sum println(s"Sum of the list elements: $sum")
val product:Int = mylist1.product
println(s"Product of the list elements: $product")
} }
- Write a Scala program to remove duplicates from a given list.
object removeDuplicates { val mylist1 = List(1, 2, 3, 4, 2, 3, 5, 6, 4, 7, 8, 7, 9); def main(args:Array[String]):Unit = { val mylist2 = mylist1.distinct; println("List without duplicates:"); mylist2.foreach(println); } }
object RemoveDuplicatesWithoutDistinct { val mylist1 = List(1, 2, 3, 4, 2, 3, 5, 6, 4, 7, 8, 7, 9); def main(args: Array[String]): Unit = {
val mylist2 = removeDuplicates(mylist1);
println("List without duplicates:")
mylist2.foreach(println);
}
def removeDuplicatesA: List[A] = { list.foldLeft(List.empty[A]) { (result, element) => if (!result.contains(element)) { result :+ element } else { result } } } }
- Write a Scala program to get the difference between two given lists.
object listDifference { val mylist1:List[Int] = List(1, 2, 3, 4, 5); val mylist2:List[Int] = List(3, 4, 5, 6, 7); def main(args:Array[String]):Unit= { val diff = mylist1.foldLeft(ListInt)((resultList, current) => { if (!mylist2.contains(current)) { resultList :+ current } else { resultList } })
println(diff) } }
object ListDifference { def main(args: Array[String]): Unit = { val list1 = List(1, 2, 3, 4, 5) val list2 = List(3, 4, 5, 6, 7)
// Calculating the difference between the two lists
val difference = list1.diff(list2)
// Printing the difference
println("Difference between the two lists:")
difference.foreach(println)
} } 20.Write a Scala program to check a given list is a palindrome or not.
object ListPalindrome { def main(args: Array[String]): Unit = { val list1 = List(1, 2, 3, 2, 1) val list2 = List(1, 2, 3, 4, 5)
println(s"Is list1 a palindrome? ${isPalindrome(list1)}")
println(s"Is list2 a palindrome? ${isPalindrome(list2)}")
}
def isPalindromeA: Boolean = { list == list.reverse } }