About
object name { def main(args:Array[String]):Unit= { println("hlo") } }
**fact object name { def main(args:Array[String]):Unit= { println(fact(5)); } def fact(x:BigInt):BigInt=if(x==0)1 else xfact(x-1) } **explict type*** scala> val msg2: java.lang.String = "Hello again, world!" val msg2: String = Hello again, world!
scala> val msg3: String = "Hello yet again, world!" msg3: String = Hello yet again, world! multi line scala> def max(x: Int, y: Int): Int = { | if (x > y) x | else y | } def max(x: Int, y: Int): Int
in notepadd object name { def main(args:Array[String]):Unit= { println(max(4,7)) } def max(x:Int,y:Int):Int={ if(x>y)x else y} } args println("Hello, " + args(0) + "!") Now run D:\PPL\Scala>scala helloarg.scala planet Hello, planet! loops object name { def main(args:Array[String]):Unit= { var i=0 while(i<args.length){ println(args(i)) i=i+1 } } }
-----print func--- var i = 0 while (i < args.length) { if (i != 0) print(" ") print(args(i)) i += 1 } println()
--foreach funct--- object name { def main(args:Array[String]):Unit= { args.foreach(arg=>println(arg)); } }
----forexpression--- object forargs { def main(args:Array[String]) { for (arg <- args) println(arg) } }
case object name { def main(args:Array[String]):Unit= { //val age1=18; val age1=20; val age="50"; age1 match { case 20 => println(age1); case 18 => println(age1); case 30 => println(age1); case 40 => println(age1); case 50 => println(age1); case _ => println("Default"); } val result = age match { case "20" => age; case "18" => age; case "30" => age; case "40" => age; case "50" => age; case _ => println("Default"); } println("result=" + result); val i=7; i match { case 1 | 3 | 5 | 7 | 9 => println("odd") case 2 | 4 | 6 | 8 | 10 => println("even"); } } }
*string** object strintrp { def main(args:Array[String]) { val name = "john" val age = 21 println(s"$name is"+ age + "years old") println(s"$name is $age years old") println(f"$name%s is $age%f years old") println(s"Hello \n world") println(raw"Hello \n world") } }
*array,list,tuples\ ----array___ object name { def main(args:Array[String]):Unit= { var greet=new ArrayString greet(0)="ji" greet(1)="kl" greet(2)="oi" for(i<-0 to 2) println(greet(i)) } } _____explixct___=val greetStrings: Array[String] = new ArrayString
update method* object name { def main(args:Array[String]):Unit= { var greet=new ArrayString greet.update(0,"lk") greet(1)="kl" greet(2)="oi" for(i<-0 to 2) println(greet(i)) } }
**array*=val numNames = Array("zero", "one", "two") listconcat
val oneTwo = List(1, 2)
val threeFour = List(3, 4)
val oneTwoThreeFour = oneTwo ::: threeFour
println(oneTwo + " and " + threeFour + " were not mutated.")
println("Thus, " + oneTwoThreeFour + " is a new list.")Add list element
val twoThree = List(2, 3)
val oneTwoThree = 1 :: twoThree
println(oneTwoThree)
**tuples
val pair = (99, "Luftballons")
println(pair._1)
println(pair._2)
**Array creation and Access – Example*
import Array._
object arraydemo
{
val myarr1:Array[Int] = new ArrayInt; //Creation method 1
val myarr2 = new ArrayString; //Creation method 2
val myarr3 = Array(1.5,2.3,6.4); //Creation method 3
val myarr4 = Array(1,2,3,4);
def main(args:Array[String])
{
myarr1(0)=20; //Assignments
myarr1(1)=50;
myarr1(2)=10;
myarr1(3)=30;
for(i<-myarr1) //Access Method 1
{
println(i);
}
for(i<- 0 to (myarr1.length-1)) //Access Method 2
{
println(myarr1(i));
}
for(i<-myarr2) //Prints default value if unassigned
{
println(i);
}
println(myarr3.length); //no of elements
val join = concat(myarr1,myarr4); //concatenates same array type
for(i<-join)
{
println(i);
}
}
}
*list creation and processing
object listdemo
{
val mylist1:List[Int] = List(1,2,3,4);
val mylist2:List[String]=List("John", "Tim", "Ken");
def main(args:Array[String])
{
println(mylist1);
println(mylist2);
//mylist1(0)=50; //List is immutable - cant change //println(mylist1);
println(50::mylist1); //cons :: to prepend println(mylist1); //value does'nt change by ::
println(1::3::5::Nil); //creates and prints a list
println(mylist2.head); //to print first item println(mylist2.tail); //prints last item
println(mylist2.isEmpty); //checks if list is empty
println(mylist1.reverse); //prints list in reverse
println(List.fill(5)(2)); //creates a list of 5 2's
println(mylist1.max); //prints max item in list
mylist2.foreach(println); //iterates thru each elt
var sum:Int=0; //sum of list using foreach mylist1.foreach(sum += _); println(sum);
for(i<-mylist2) //iteration using for { println(i); } println(mylist2(1)); //list indexing }
}
tuple craetion and process object tupdemo {
val mytuple1 = (1,2,"hi",false);
val mytuple2 = new Tuple4 (3,4,"hello",true); //no of items to be specified - allowed upto 22 elements
val mytuple3 = new Tuple3 (5,"welcome",(1,2)); //Tuple in tuple
def main(args:Array[String]) { println(mytuple1); println(mytuple2._3); //Tuples indexed from 1 println(mytuple3._3); //To print nested tuple println(mytuple3._3._2); //To print nested tuple element
mytuple1.productIterator.foreach //iterating thru a tuple { i => println(i); }
}
} ***comom(((( object CheckIntegers { def main(args: Array[String]): Unit = { var hg=Array(1,2,3,4) var jk=Array(8,4,3) val xy=hg.intersect(jk) xy.foreach(arg=>println(arg)) } }
*reverse)))) object CheckIntegers { def main(args: Array[String]): Unit = { var hg=Array(1,2,3,4) hg=hg.reverse println(hg(0)) } }assgn***
1.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 Sum {
def main(args: Array[String]): Unit = {
val a = 5
val b = 5
val sum = if (a == b) 3 * (a + b) else a + b
println(s"The sum is $sum")
}
}
Output:
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 { def main(args: Array[String]): Unit = { val n = 52 val result = absoluteDifference(n) println(result) } def absoluteDifference(n: Int): Int = {
val diff = math.abs(n - 51) if (n > 51) diff * 3 else diff } } Output: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 CheckIntegers { def main(args: Array[String]): Unit = { val a = 20 val b = 20 val result = checkIntegers(a, b) println(result) }def checkIntegers(a: Int, b: Int): Boolean = { if (a == 30 || b == 30 || a + b == 30) true else false } } Output:
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.
object RemoveCharacter { def main(args: Array[String]): Unit = { val str = "Hello World" val pos = 7 val result = removeCharacter(str, pos) println(result) }def removeCharacter(str: String, pos: Int): String = { if (pos >= 0 && pos < str.length) { str.substring(0, pos) + str.substring(pos + 1) } else { str } } } Output:
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 LargerValue { def main(args: Array[String]): Unit = { val a = 30 val b = 25 val result = largerValue(a, b) println(result) }
def largerValue(a: Int, b: Int): Int = { if ((a >= 20 && a <= 30) && (b >= 20 && b <= 30)) { if (a > b) a else b } else { 0 } } } Output:
Obtain a temperature in degrees Fahrenheit from the user. If the temperature is 80degrees or more display the message "Go play golf" otherwise, if the temperature is 70 -79 degrees display the message "Put on a jacket", otherwise display the message "It isway too cold." Make a variable list, flowchart, and perform a desk check using the following values: 95, 72, 50. object TemperatureCheck { def main(args: Array[String]): Unit = { println("Enter temperature in Fahrenheit: ") val temperature = scala.io.StdIn.readInt() if (temperature >= 80) { println("Go play golf") } else if (temperature >= 70 && temperature <= 79) { println("Put on a jacket") } else { println("It is way too cold") } } } Output:
Obtain a name and age from the user. If the user is 16 or older, output a message indicating they are old enough to drive. For people under 16, output a message indicating how many years they must wait before they can drive legally. object DrivingCheck { def main(args: Array[String]): Unit = { println("Enter your name: ") val name = scala.io.StdIn.readLine() println("Enter your age: ") val age = scala.io.StdIn.readInt() if (age >= 16) { println(s"$name, you are old enough to drive") } else { val yearsToWait = 16 - age println(s"$name, you need to wait $yearsToWait years before you can drive legally") } } } Output:
Check if a given number is a palindrome. object PalindromeCheck { def main(args: Array[String]): Unit = { val number = 12321 val isPalindrome = checkPalindrome(number) if (isPalindrome) { println(s"$number is a palindrome") } else { println(s"$number is not a palindrome") } }
def checkPalindrome(number: Int): Boolean = { val reverse = number.toString.reverse.toInt if (number == reverse) { true } else { false } } } Output:
Check if a given number is an Armstrong number. object ArmstrongCheck { def main(args: Array[String]): Unit = { val number = 162 val isArmstrong = checkArmstrong(number) if (isArmstrong) { println(s"$number is an Armstrong number") } else { println(s"$number is not an Armstrong number") } }
def checkArmstrong(number: Int): Boolean = { val digits = number.toString.map(_.asDigit) val sum = digits.map(d => math.pow(d, digits.length)).sum.toInt if (number == sum) { true } else { false } } } Output:
Strings
- 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
object SumNumbers { def main(args: Array[String]): Unit = { val str = "it 15 is25 a 20string" val sum = sumNumbers(str) println(s"The sum of the numbers in the said string is $sum") }
def sumNumbers(str: String): Int = { val regex = """\d+""".r val numbers = regex.findAllIn(str).map(_.toInt) numbers.sum } } Output:
- 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
object RotationCheck { def main(args: Array[String]): Unit = { val str1 = "ABACD" val str2 = "CDABA" if (checkRotation(str1, str2)) { println("The given strings are: " + str1 + " and " + str2) val concat = str1 + str1 println("The concatenation of the first string twice is: " + concat) println("The second string " + str2 + " exists in the new string.") println("Strings are rotations of each other") } else { println("The given strings are not rotations of each other.") } }
def checkRotation(str1: String, str2: String): Boolean = { if (str1.length != str2.length) { false } else { (str1 + str1).contains(str2) } } }
Output:
Write a Scala program to count and print all the duplicates in the input string. object DuplicateCount { def main(args: Array[String]): Unit = { val str = "hello world" val duplicates = findDuplicates(str) println(s"The duplicates in '$str' are: $duplicates") }
def findDuplicates(str: String): List[Char] = { val counts = str.groupBy(identity).mapValues(_.length) counts.filter(_._2 > 1).keys.toList } } Output:
Write a Scala program to convert all the characters to lowercase, uppercase strings. object StringConverter { def main(args: Array[String]): Unit = { val inputString = "hello world" val lowercaseString = inputString.toLowerCase val uppercaseString = inputString.toUpperCase println("Lowercase string: " + lowercaseString) println("Uppercase string: " + uppercaseString) } } Output:
Write a Scala program to get a substring of a given string between two specified positions. object SubstringGetter { def main(args: Array[String]): Unit = { val inputString = "Hello World" val startPosition = 3 val endPosition = 7 val substring = inputString.substring(startPosition, endPosition) println("Substring: " + substring) } } Output:
Write a Scala program to read a string and a character and return a new string after removing the character and its immediate neighbours. object CharacterRemover { def main(args: Array[String]): Unit = { val inputString = "Hello World" val characterToRemove = 'l' val outputString = removeCharacterAndNeighbors(inputString, characterToRemove) println("Output string: " + outputString) }
def removeCharacterAndNeighbors(inputString: String, characterToRemove: Char): String = { inputString.replaceAll(s"(?i)${characterToRemove}.{0,1}", "") } } Output:
Arrays
Write a Scala program to reverse an array of integer values using the same array. object ArrayReverser { def main(args: Array[String]): Unit = { val inputArray = Array(1, 2, 3, 4, 5) reverseArrayInPlace(inputArray) println("Reversed array: " + inputArray.mkString(", ")) }
def reverseArrayInPlace(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 } } } Output:
Write a Scala program to find the common elements between two arrays of integers. object CommonElementsFinder { def main(args: Array[String]): Unit = { val array1 = Array(1, 2, 3, 4, 5) val array2 = Array(3, 4, 5, 6, 7) val commonElements = findCommonElements(array1, array2) println("Common elements: " + commonElements.mkString(", ")) }
def findCommonElements(array1: Array[Int], array2: Array[Int]): Array[Int] = { array1.intersect(array2) } } Output:
Write a Scala program to find the common elements between two arrays of strings. object CommonElementsFinder { def main(args: Array[String]): Unit = { val array1 = Array("apple", "banana", "orange", "mango") val array2 = Array("orange", "mango", "kiwi", "pear") val commonElements = findCommonElements(array1, array2) println("Common elements: " + commonElements.mkString(", ")) }
def findCommonElements(array1: Array[String], array2: Array[String]): Array[String] = { array1.intersect(array2) } } Output:
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 { def main(args: Array[String]): Unit = { val inputArray = Array(1, 5, 2, 8, 3) val difference = findDifference(inputArray) println("Difference: " + difference) }
def findDifference(array: Array[Int]): Int = { require(array.length > 0, "Array must have at least one element") val max = array.max val min = array.min max - min } } Output:
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 ClosestToZeroFinder { def main(args: Array[String]): Unit = { val inputArray = Array(-5, -3, 1, 8, -9, 4, 7, -2) val (closest1, closest2) = findClosestToZero(inputArray) println("Closest elements: " + closest1 + " and " + closest2) }
def findClosestToZero(array: Array[Int]): (Int, Int) = { var closest1 = 0 var closest2 = 0 var minSum = Int.MaxValue for (i <- 0 until array.length - 1) { for (j <- i + 1 until array.length) {
val sum = array(i) + array(j) if (Math.abs(sum) < minSum) { minSum = Math.abs(sum) closest1 = array(i) closest2 = array(j) }
} } (closest1, closest2) } } Output:
A Scala function that reads marks of ‘n’ students of a class and displays the class average. Also if more than 2 students have marks less than class average, display a suitable message. object ClassAverage { def main(args: Array[String]): Unit = { val marks = Array(80, 70, 90, 60, 50, 75, 85, 95, 65, 55) val classAverage = calculateAverage(marks) println("Class average: " + classAverage) if (countBelowAverage(marks, classAverage) > 2) { println("More than 2 students have marks less than class average") } }
def calculateAverage(marks: Array[Int]): Double = { marks.sum.toDouble / marks.length }
def countBelowAverage(marks: Array[Int], classAverage: Double): Int = { marks.count(_ < classAverage) } } Output:
A Scala function to find the Number Occurring Odd Number of Times in an list. Input :arr = {1, 2, 3, 2, 3, 1, 3} Output : 3 Input :arr = {5, 7, 2, 7, 5, 2, 5} Output : 5
object OddOccurrence { def main(args: Array[String]): Unit = { val arr1 = List(1, 2, 3, 2, 3, 1, 3) val arr2 = List(5, 7, 2, 7, 5, 2, 5) println("Odd occurrence in arr1: " + findOddOccurrence(arr1)) println("Odd occurrence in arr2: " + findOddOccurrence(arr2)) }
def findOddOccurrence(arr: List[Int]): Int = { val counts = arr.groupBy(identity).mapValues(_.size) counts.find(_._2 % 2 != 0).get._1 } }
Output:
Lists
Write a Scala program to remove single and multiple elements from a given list. object ListRemover { def main(args: Array[String]): Unit = { val inputList = List(1, 2, 3, 4, 5, 6, 7) val singleElementToRemove = 3 val multipleElementsToRemove = List(2, 5, 7) val outputList = removeElements(inputList, singleElementToRemove, multipleElementsToRemove) println("Output list: " + outputList) }
def removeElements(list: List[Any], singleElement: Any, multipleElements: List[Any]): List[Any] = { val filteredList = list.filterNot(element => element == singleElement || multipleElements.contains(element)) filteredList } } Output:
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 ListSumProduct { def main(args: Array[String]): Unit = { val inputList = List(1, 2, 3, 4, 5) printList(inputList) val sum = calculateSum(inputList) println("Sum: " + sum) val product = calculateProduct(inputList) println("Product: " + product) }
def printList(list: List[Any]): Unit = { for (element <- list) { println(element) } }
def calculateSum(list: List[Int]): Int = { list.sum }
def calculateProduct(list: List[Int]): Int = { list.product } } Output:
Write a Scala program to remove duplicates from a given list. object ListDeduplicator { def main(args: Array[String]): Unit = { val inputList = List(1, 2, 2, 3, 4, 4, 5, 5, 5) val outputList = removeDuplicates(inputList) println("Output list: " + outputList) }
def removeDuplicates(list: List[Any]): List[Any] = { list.distinct } } Output:
Write a Scala program to get the difference between two given lists.
object ListDifference { def main(args: Array[String]): Unit = { val list1 = List(1, 2, 3, 4, 5) val list2 = List(3, 4, 5, 6, 7) val difference = findDifference(list1, list2) println("Difference: " + difference) }def findDifference(list1: List[Any], list2: List[Any]): List[Any] = { list1.diff(list2) } } Output:
Write a Scala program to check a given list is a palindrome or not. object ListPalindrome { def main(args: Array[String]): Unit = { val inputList1 = List(1, 2, 3, 2, 1) val inputList2 = List(1, 2, 3, 4, 5) println("Is inputList1 a palindrome? " + isPalindrome(inputList1)) println("Is inputList2 a palindrome? " + isPalindrome(inputList2)) }
def isPalindrome(list: List[Any]): Boolean = { list == list.reverse } } Output:
A Scala function to display all the duplicates elements in the list. object ListDuplicates { def main(args: Array[String]): Unit = { val inputList = List(1, 2, 2, 3, 4, 4, 5, 5, 5) val duplicates = findDuplicates(inputList) println("Duplicates: " + duplicates) }
def findDuplicates(list: List[Any]): List[Any] = { list.diff(list.distinct) } } Output:
A Scala function that reads a list and print the odd numbers in the list. object ListOddNumbers { def main(args: Array[String]): Unit = { val inputList = List(1, 2, 3, 4, 5, 6, 7, 8, 9) printOddNumbers(inputList) }
def printOddNumbers(list: List[Int]): Unit = { for (num <- list) { if (num % 2 != 0) {
println(num)
} } } } Output:
A Scala function that reads a list and print the sum of even numbers in the list. object ListEvenSum { def main(args: Array[String]): Unit = { val inputList = List(1, 2, 3, 4, 5, 6, 7, 8, 9) val evenSum = calculateEvenSum(inputList) println("Sum of even numbers: " + evenSum) }
def calculateEvenSum(list: List[Int]): Int = { list.filter(_ % 2 == 0).sum } } Output:
HIGHER ORDER_____ ^^^^map&&&& -- Doubles each element in a list doubleList :: [Int] -> [Int] doubleList xs = map (\x -> x * 2) xs
main :: IO () main = do let numbers = [1, 2, 3, 4, 5] let doubledNumbers = doubleList numbers putStrLn $ "Original list: " ++ show numbers putStrLn $ "Doubled list: " ++ show doubledNumbers
^^^^filter*
-- Filters even numbers from a list
filterEven :: [Int] -> [Int]
filterEven xs = filter (\x -> x mod
2 == 0) xs
main :: IO () main = do let numbers = [1, 2, 3, 4, 5] let evenNumbers = filterEven numbers putStrLn $ "Original list: " ++ show numbers putStrLn $ "Even numbers: " ++ show evenNumbers
&&&&foldr*((( -- Sums all elements in a list using foldr sumList :: [Int] -> Int sumList xs = foldr (+) 0 xs
main :: IO () main = do let numbers = [1, 2, 3, 4, 5] let sum = sumList numbers putStrLn $ "Original list: " ++ show numbers putStrLn $ "Sum: " ++ show sum
&&&&&zipwith(((( -- Adds corresponding elements of two lists addLists :: [Int] -> [Int] -> [Int] addLists xs ys = zipWith (+) xs ys
main :: IO () main = do let numbers1 = [1, 2, 3, 4, 5] let numbers2 = [10, 20, 30, 40, 50] let addedNumbers = addLists numbers1 numbers2 putStrLn $ "List 1: " ++ show numbers1 putStrLn $ "List 2: " ++ show numbers2 putStrLn $ "Added lists: " ++ show addedNumbers
*foldl(((( -- Computes the product of a list using foldl productList :: [Int] -> Int productList xs = foldl (\acc x -> acc * x) 1 xs
main :: IO () main = do let numbers = [1, 2, 3, 4, 5] let product = productList numbers putStrLn $ "Original list: " ++ show numbers putStrLn $ "Product: " ++ show product