0% found this document useful (0 votes)
487 views

Lab Manual AInDS Scala (Updated)

Uploaded by

navy22ainds
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
487 views

Lab Manual AInDS Scala (Updated)

Uploaded by

navy22ainds
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

CMR INSTITUTE OF

TECHNOLOGY
Affiliated to VTU, Approved by AICTE, Accredited by
NBA and NAAC with “A++” Grade
ITPL MAIN ROAD, BROOKFIELD, BENGALURU-
560037, KARNATAKA, INDIA

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & DATA


SCIENCE ENGINEERING

BE - IV SEMESTER

SCALA
LABORATORY
MANUAL -BDSL456A

ACADEMIC YEAR – 2023-24


PROGRAMME OUTCOMES(PO’s)
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
Sr. Name of Experiment / Program
No
1 a 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.
b Write a Scala program to check two given integers, and return true if one of
them is 22 or if their sum is 32.
2 a 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.
b Write a Scala program to create a new string taking the first 5 characters of a
given string and return the string with the 5 characters added at both the front
and back.
3 a Write a Scala program to print the multiplication table of a given number using
a for loop.
b Write a Scala program to find the largest element in an array using pattern
matching
4 a Write a Scala function to calculate the product of digits in a given number
b Write a Scala function to check if a given number is a perfect square
5 a Write a Scala program that creates a subclass Student that extends the Person
class. Add a property called grade and implement methods to get and set it.
b Write a Scala program that creates a class Triangle with properties side1, side2,
and side3. Implement a method is Equilateral to check if the triangle is
equilateral.
6 a Write a Scala program that creates an enum class Color with values for
different colors. Use the enum class to represent an object's color.
b Write a Scala program that creates a class ContactInfo with properties name,
email, and address. Create a class Customer that includes a ContactInfo object.
7 a Write a Scala program to create a set and find the difference and intersection
between two sets.
b Write a Scala program to create a set and find the second largest element in the
set.
8 a Write a Scala program to create a list in different ways.
Note: Use Lisp style, Java style, Range list, Uniform list, Tabulate list
b Write a Scala program to flatten a given List of Lists, nested list structure.
9 a Write a Scala program to add each element n times to a given list of integers.
b Write a Scala program to split a given list into two lists.
10 a Write a Scala program to swap the elements of a tuple Further print no
swapping required if elements are same.
b Write a Scala program to find non-unique elements in a tuple
Experiment No. 1 (a)
Problem Statement:

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.
Theory:
In this program we will define a function for Sum or Triple. Inputs a and b will be given to this
function. Then it will check the condition using if …. Else. Based on condition it will perform normal
Sum and then display its triplet
Program:
object SumCalculator {
def main(args: Array[String]): Unit = {
// Test cases
println(sumOrTriple(2, 3)) // Output should be 5
println(sumOrTriple(5, 5)) // Output should be 30
println(sumOrTriple(-1, -1)) // Output should be -6
}
def sumOrTriple(a: Int, b: Int): Int = {
if (a == b) {
3 * (a + b)
} else {
a+b
}
}
}
Output:

OR
import scala.io.StdIn

object SumCheck {
def main(args: Array[String]): Unit = {
// Prompt the user to enter a number
println("Enter a first number:")

// Read the number entered by the user


val a = StdIn.readLine().toInt

println("Enter a second number:")

// Read the number entered by the user


val b = StdIn.readLine().toInt

if(a==b){
val c=3 * (a + b)
println("Result is:"+c)
}
else {
val d=a + b
println("Result is:"+d)
}
}

Conclusion:
In this Program we understood how to compute the sum of the two given integer values and if the two
values are the same, then how to return triples their sum.

Problem Statement:
Write a Scala program to check two given integers, and return true if one of them is 22 or if
their sum is 32.
Theory:

In this program we will define a function checkIntegers. We will give 2 values to the function.
Then it will check whether any one of the values is 22 or whether sum of those values is 32. If
any one of condition is satisfied then it will return True as an answer otherwise False

Program
object IntegerChecker {
def main(args: Array[String]): Unit = {
// Test cases
println(checkIntegers(10, 22)) // Output should be true
println(checkIntegers(20, 10)) // Output should be false
println(checkIntegers(15, 17)) // Output should be true
println(checkIntegers(15, 18)) // Output should be false
}

def checkIntegers(a: Int, b: Int): Boolean = {


(a == 22 || b == 22) || (a + b == 32)
}
}

Output:

OR
import scala.io.StdIn

object IntegerCheck {
def main(args: Array[String]): Unit = {
// Prompt the user to enter a number
println("Enter a first number:")

// Read the number entered by the user


val a = StdIn.readLine().toInt

println("Enter a second number:")

// Read the number entered by the user


val b = StdIn.readLine().toInt

// Check if any one of them is 22 or if their sum is 32


val result = if (a == 22 || b == 22 || a + b == 32) true else false

println(result)
}
}

Conclusion:
In this Program we understood how to check two given integers, and return true or false
depending upon the condition.

Problem Statement

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.
Theory:
Program:
object RemoveCharacter {
def main(args: Array[String]): Unit = {
// Sample string
val inputString = "Hello, World!"

// Given position to remove


val positionToRemove = 7 // Change this to any valid position

// Check if position to remove is within the string length


if (positionToRemove >= 0 && positionToRemove < inputString.length) {
// Remove the character at the given position
val resultString = inputString.substring(0, positionToRemove) +
inputString.substring(positionToRemove + 1)

// Print the result


println(s"Original string: $inputString")
println(s"Position to remove: $positionToRemove")
println(s"Result string: $resultString")
} else {
println("Invalid position.")
}
}
}
Output:

OR

import scala.io.StdIn

object RemoChar {
def main(args: Array[String]): Unit = {
// Sample string

// Prompt the user to enter a string


println("Enter a string:")
val s1 = StdIn.readLine()

//Read Position to remove


println("Enter position to remove character from string :")
val p = StdIn.readLine().toInt

// Check if position to remove is within the string length


if (p >= 0 && p < s1.length) {
// Remove the character at the given position
val resultString = s1.substring(0, p) + s1.substring(p + 1)

// Print the result


println("Original string:"+s1)
println("Position to remove:"+p)
println(s"Result string: $resultString")
} else {
println("Invalid position.")
}

}
}

Conclusion:
In this Program we understood how to remove the character in a given position of a given string
Problem Statement

Write a Scala program to create a new string taking the first 5 characters of a given string and return
the string with the 5 characters added at both the front and back.
Theory:
Program:
object StringManipulation {
def main(args: Array[String]): Unit = {
// Test cases
println(addFirstFive("HelloWorld")) // Output should be "HelloHelloHelloWorldHelloHelloHello"
println(addFirstFive("Scala")) // Output should be "ScalaScalasca"
println(addFirstFive("12345")) // Output should be "123451234512345"
}

def addFirstFive(str: String): String = {


val firstFive = str.take(5)
firstFive + str + firstFive
}
}
Output:

Conclusion:
In this Program we understood how to create a new string taking the first 5 characters of a given string
and return the string with the 5 characters added at both the front and back.

3 a) Write a Scala program to print the multiplication table of a given number using a for
loop.

Program:

object MultiplicationTable {
def main(args: Array[String]): Unit = {
val number: Int = 5 // Number for which you want to print the multiplication table
val tableSize: Int = 12 // Size of the multiplication table

println(s"Multiplication Table of $number:")


for (i <- 1 to tableSize) {
val product = number * i
println(s"$number * $i = $product")
}
}
}

Sample Output:
Multiplication Table of 5:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
5 * 11 = 55
5 * 12 = 60

Explanation:

In the above Program -

First we define a variable "number" and assign it a value (5 in this case) for which we want to
print the multiplication table. We also define a variable "tableSize" and assign it a value (12
in this case) which determines the size of the multiplication table.

We use a for loop to iterate from 1 to "tableSize". Inside the loop, we calculate the product of
"number" and the current iteration value i and store it in the variable product. We then use
println to display the multiplication expression and result.

3 b ) Write a Scala program to find the largest element in an array using pattern matching

Program:

object LargestElementFinder {
def main(args: Array[String]): Unit = {
// Array containing the numbers
val numbers: Array[Int] = Array(23, 36, 36, 55, 19, 8)
// Print all the array elements
println("Original Array elements:")
for ( x <- numbers ) {
print(s"${x}, ")
}

val largestElement: Option[Int] = findLargestElement(numbers)

largestElement match {
case Some(largest) => println(s"\nThe largest element is: $largest")
case None => println("\nThe array is empty.")
}
}

def findLargestElement(numbers: Array[Int]): Option[Int] = {


numbers match {
case Array() => None
case Array(x) => Some(x)
case Array(x, y, rest @ _*) =>
val maxRest = findLargestElement(Array(y) ++ rest.toArray)
if (x > maxRest.get) Some(x) else maxRest
}
}
}

Sample Output:
Original Array elements:
23, 36, 36, 55, 19, 8,
The largest element is: 55

Explanation:

In the above Program,

The function 'findLargestElement()' takes an array as input and returns an Option[Int]


representing the largest element. The function uses pattern matching to handle different
cases:

● If the numbers array is empty, it returns None.


● If the numbers array contains only one element, it returns that element wrapped in
Some.
● If the numbers array contains more than one element, it uses a variable pattern rest @
_* to capture the remaining elements after the first two (x and y). It recursively calls
findLargestElement with an array composed of y and the remaining elements (rest),
converts it to an array, and compares the result (maxRest) with x. If x is greater than
maxRest, it returns Some(x); otherwise, it returns maxRest.
● In the "main()" method, we call the "findLargestElement()" function passing the
numbers array and assigning the result to largestElement, which will be an
Option[Int]. We use pattern matching to handle the Some and None cases and print
the largest element or a message indicating an empty array.

At the end of the program, the largest element in the array will be displayed.

val numbers: Array[Int] = Array(23, 36, 36, 55, 19, 8)

Now, when findLargestElement(numbers) is called, and the pattern matching case


Array(x, y, rest @ _*) => ... is encountered, it's checking if the array numbers

has at least two elements (x and y). Here's how it works:

1. x: The first element of the array (x = 23).


2. y: The second element of the array (y = 36).
3. rest @ _*: This syntax captures the remaining elements of the array (if any)
into a sequence called rest.

So, after this pattern match:

● x will be 23.
● y will be 36.
● rest will be the sequence containing the remaining elements: rest =
Seq(36, 55, 19, 8).

Then, the function recursively calls findLargestElement with y (36) and the
sequence rest (Seq(36, 55, 19, 8)).

OR

object LargestElement {

def findLargest(arr: Array[Int]): Int = arr match {

case Array() => throw new NoSuchElementException("Array is empty")

case Array(x) => x

case Array(x, _*) => arr.foldLeft(x) { (max, elem) => if (elem > max) elem else max }

}
def main(args: Array[String]): Unit = {

val numbers = Array(3, 6, 2, 8, 4)

try {

val largest = findLargest(numbers)

println(s"The largest element in the array is: $largest")

} catch {

case e: Exception => println(e.getMessage)

Output:

This program defines an object named LargestElement with a method

findLargest that takes an array of integers as input. The method uses pattern
matching to handle different cases:

● If the array is empty, it throws a NoSuchElementException.

● If the array has only one element, it returns that element.

● If the array has more than one element, it uses foldLeft to iterate through
the elements and find the largest one.

The main method creates an array of integers, calls the findLargest method, and
prints out the largest element. It also includes exception handling for cases where
the array might be empty.

4 a) Write a Scala function to calculate the product of digits in a given number

Program:

import scala.io.StdIn.{readInt,readBoolean}
object sum_digit {
def main(args: Array[String]): Unit = {
println("display sum of digits of a number")
var n:Int=readInt()
println("Enter number:"+n);
var mul=1;
while(n!=0)
{
mul=mul*n%10;
n=n/10;

}
println("Product of digits of a number:"+mul)
}
}

Sample Output:

STDIN

123

Output

display sum of digits of a number

Enter number:123

sum of digits of a number:6


4 b) Write a Scala function to check if a given number is a perfect square

Program:

object SquareChecker {
def isPerfectSquare(number: Int): Boolean = {
val sqrt = math.sqrt(number).toInt
sqrt * sqrt == number
}

def main(args: Array[String]): Unit = {


val number1 = 36
val number2 = 19

println(s"Is $number1 is a perfect square? ${isPerfectSquare(number1)}")


println(s"Is $number2 is a perfect square? ${isPerfectSquare(number2)}")
}
}

Sample Output:

Is 36 is a perfect square? true


Is 19 is a perfect square? false

5 a. Write a Scala program that creates a subclass Student that extends the Person
class. Add a property called grade and implement methods to get and set it

Program:
class Person(var name: String, var age: Int, var country: String) {
def getName: String = name

def setName(newName: String): Unit = {


name = newName
}

def getAge: Int = age

def setAge(newAge: Int): Unit = {


age = newAge
}

def getCountry: String = country

def setCountry(newCountry: String): Unit = {


country = newCountry
}
}

class Student(name: String, age: Int, country: String, var grade: String)
extends Person(name, age, country) {

def getGrade: String = grade

def setGrade(newGrade: String): Unit = {


grade = newGrade
}
}

object StudentApp {
def main(args: Array[String]): Unit = {
val student = new Student("Saturnino Nihad", 18, "USA", "A")

println("Original Student:")
println(s"Name: ${student.getName}")
println(s"Age: ${student.getAge}")
println(s"Country: ${student.getCountry}")
println(s"Grade: ${student.getGrade}")

student.setName("Albino Ellen")
student.setAge(20)
student.setCountry("Canada")
student.setGrade("B")

println("\nUpdated Student:")
println(s"Name: ${student.getName}")
println(s"Age: ${student.getAge}")
println(s"Country: ${student.getCountry}")
println(s"Grade: ${student.getGrade}")
}
}
Sample output:

Explanation:
In the above exercise -

The "Person" class defines the properties name, age, and country, along with the
corresponding getter and setter methods.

The "Student" class extends the Person class and adds an additional property called
grade. It also includes getter and setter methods specific to the grade property.

The StudentApp object contains the main method, which demonstrates the Student
class usage. It creates a Student object, prints its original values, updates the
properties using the setter methods inherited from the Person class and the setGrade
method from the Student class. It then prints the updated values.

5b. Write a Scala program that creates a class Triangle with properties side1, side2,
and side3. Implement a method isEquilateral to check if the triangle is equilateral.
class Triangle(val side1: Double, val side2: Double, val side3: Double) {
def isEquilateral(): Boolean = {
side1 == side2 && side2 == side3
}
}

object TriangleApp {
def main(args: Array[String]): Unit = {
val triangle1 = new Triangle(6.0, 6.0, 6.0)
val triangle2 = new Triangle(3.0, 4.0, 5.0)

println(s"Triangle 1 is equilateral: ${triangle1.isEquilateral()}")


println(s"Triangle 2 is equilateral: ${triangle2.isEquilateral()}")
}
}

Explanation:

In the above exercise,

● The "Triangle" class is defined with a constructor that takes side1, side2, and side3
as parameters and initializes the corresponding properties. The properties are
defined as val, making them read-only.
● The "isEquilateral()" method is defined in the Triangle class. It checks if all three
sides of the triangle are equal, indicating an equilateral triangle.
● The "TriangleApp" object contains the main method to test functionality. It creates
instances of Triangle with different side lengths, and calls the isEquilateral method
to check if the triangles are equilateral.

6a. Write a Scala program that creates an enum class Color with values for different
colors. Use the enum class to represent an object's color.

Program:
sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
case object Orange extends Color

object ColorApp {
def main(args: Array[String]): Unit = {
val myColor: Color = Red
//val myColor: Color = Blue
printColor(myColor)
}

def printColor(color: Color): Unit = color match {


case Red => println("The color is Red.")
case Green => println("The color is Green.")
case Blue => println("The color is Blue.")
case Orange => println("The color is Orange.")
case _ => println("Unknown color.")
}
}

Without using trait

enum Color {
case Red, Green, Blue, Orange
}

object ColorApp {
def main(args: Array[String]): Unit = {
val myColor: Color = Color.Red
//val myColor: Color = Color.Blue
printColor(myColor)
}

def printColor(color: Color): Unit = color match {


case Color.Red => println("The color is Red.")
case Color.Green => println("The color is Green.")
case Color.Blue => println("The color is Blue.")
case Color.Orange => println("The color is Orange.")
case _ => println("Unknown color.")
}
}

Sample Output:
Explanation:

In the above exercise,

● First, we define a sealed trait "Color" that serves as the base type for different color
objects. Then, we define case objects "Red", Green, and Blue that extend the Color
trait to represent specific colors.
● The "ColorApp" object contains the “main()” method where we can test
functionality. It assigns the "Red" color to the myColor variable and calls the
"printColor()" method to print the color name.
● The "printColor()" method uses pattern matching to determine the specific color of
the object and prints a corresponding message.

6b. Write a Scala program that creates a class ContactInfo with properties name,
email, and address. Create a class Customer that includes a ContactInfo object.

Program:
class ContactInfo(val name: String, val email: String, val address: String)

class Customer(val contactInfo: ContactInfo)

object CustomerApp {
def main(args: Array[String]): Unit = {
val contact = new ContactInfo("Serafim Eline", "[email protected]", "11 Open
Street")
val customer = new Customer(contact)

println(s"Customer Name: ${customer.contactInfo.name}")


println(s"Customer Email: ${customer.contactInfo.email}")
println(s"Customer Address: ${customer.contactInfo.address}")
}
}

Sample Output:

Explanation:
In the above exercise,

● The "ContactInfo" class is defined with the properties name, email, and address. It
has a primary constructor that takes these properties as parameters.
● The "Customer" class is defined by the property contactInfo of type ContactInfo. It
represents a customer and includes contact information.
● The CustomerApp object contains the main method to test functionality. It creates
an instance of the ContactInfo class with sample information and then creates a
Customer object using the ContactInfo instance.
● Finally, the program prints the customer's name, email, and address using string
interpolation.

7a. Write a Scala program to create a set and find the difference and intersection
between two sets.
Program:

object SetIntersectionExample {
def main(args: Array[String]): Unit = {

// Create two sets


val set1 = Set(9, 2, 0, 4)
val set2 = Set(8, 4, 5, 6)

// Print the set elements


println("Set1: " + set1)
println("Set2: " + set2)

// Find the intersection of the two sets


val intersectionSet = set1.intersect(set2)
// Find the difference between the sets
val difference = set1.diff(set2)

// Print the intersection set


println("Intersection Set: " + intersectionSet)
// Print the Difference set
println("Difference: " + difference)
}
}

Output:

Explanation:
This program creates two sets, set1 and set2, and then finds their difference and intersection
using the diff and intersect methods provided by Scala's Set class. Finally, it prints the
original sets, the difference, and the intersection.
7b. Write a Scala program to create a set and find the second largest element in the set.

Program:
object SecondLargestElement {
def main(args: Array[String]): Unit = {
// Create a set
val mySet = Set(100, 59, 20, 15, 25, 30)

// Find the second largest element


val secondLargest = findSecondLargest(mySet)

// Print the result


println("Set: " + mySet)
println("Second Largest Element: " + secondLargest)
}

def findSecondLargest(set: Set[Int]): Option[Int] = {


if (set.size < 2) {
None // Set has less than 2 elements, so second largest doesn't exist
} else {
Some(set.toList.sorted.reverse(1)) // Sort the set in descending order and get the second
element
}
}
}

Output:

Explanation:
This program defines a function findSecondLargest that takes a set of integers as input and
returns an Option[Int], where the option contains the second largest element if it exists, or
None otherwise. It sorts the set in descending order and retrieves the second element if the set
has at least two elements. Finally, it prints the original set and the second largest element (if
found).
8a.Write a Scala program to create a list in different ways.
Program:
//Using List constructor directly:
val myList1 = List(1, 2, 3, 4, 5)
println(myList1)

//Using :: (cons) operator:


val myList2 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
println(myList2)

//Using List.tabulate:
val myList3 = List.tabulate(5)(_ + 1)
println(myList3)

//Using List.fill:
val myList4 = List.fill(5)(scala.util.Random.nextInt(10))
println(myList4)

//Using List.range:
val myList5 = List.range(1, 6)
println(myList5)

//Using a combination of methods:

val myList6 = (1 to 5).toList


println(myList6)

Write a Scala program to create a list in different ways.


Note: Use Lisp style, Java style, Range list, Uniform list, Tabulate list

object ListCreation extends App {

// Lisp style
val lispList = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
println(s"Lisp style list: $lispList")

// Java style
val javaList = List(1, 2, 3, 4, 5)
println(s"Java style list: $javaList")

// Range list
val rangeList = (1 to 5).toList
println(s"Range list: $rangeList")

// Uniform list
val uniformList = List.fill(5)(42)
println(s"Uniform list: $uniformList")

// Tabulate list
val tabulateList = List.tabulate(5)(n => n * n)
println(s"Tabulate list: $tabulateList")
}

Output:

Explanation:
Each of these methods creates a list containing the elements 1 to 5. You can replace
the elements or modify the ranges/methods as needed to create lists with different
contents

Lisp style:

● Using the cons operator :: and Nil to construct the list.

Java style:

● Using the List companion object's apply method to create the list.

Range list:

● Using a range with to and converting it to a list with toList.

Uniform list:

● Using List.fill to create a list where every element is the same value.

Tabulate list:
● Using List.tabulate to create a list where each element is generated by
applying a function to its index.

In Scala, App is a trait that can be used to quickly turn objects into executable
programs. When you extend App, the code within the object body is executed as the
main program. The App trait provides a main method, which makes it easy to write
small applications without needing to define the main method explicitly.

8b. Write a Scala program to flatten a given List of Lists, nested list structure.
Program:
object FlattenList {
def main(args: Array[String]): Unit = {
// Define a list of lists
val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7, 8))

// Flatten the list of lists


val flattenedList: List[Int] = flatten(nestedList)

// Print the flattened list


println("Original List of Lists: " + nestedList)
println("Flattened List: " + flattenedList)
}

def flatten(list: List[List[Int]]): List[Int] = {


list.flatten
}
}

Output:

Explanation: In this program, the flatten method is called on the nestedList, which flattens the
list of lists into a single list. Then, it prints both the original list of lists and the flattened list.

Without Function:

object FlattenList extends App {


// Example nested list
val nestedList = List(
List(1, 2, 3),
List(4, 5),
List(6, 7, 8, 9)
)
// Flatten the nested list directly
val flattenedList = nestedList.flatten

// Print the flattened list


println(s"Flattened list: $flattenedList")
}

Without Flatten Keyword.

object FlattenNestedList {
def flattenList(nestedList: List[Any]): List[Any] = {
var result: List[Any] = List()

def flatten(currentList: List[Any]): Unit = {


for (elem <- currentList) {
elem match {
case list: List[Any] => flatten(list)
case other => result = result :+ other
}
}
}

flatten(nestedList)
result
}

def main(args: Array[String]): Unit = {


val nestedList = List(List(1, 2, List(3, 4)), 5, List(6, List(7, 8)), 9)
val flattenedList = flattenList(nestedList)
println(flattenedList) // Output: List(1, 2, 3, 4, 5, 6, 7, 8, 9)
}
}

9 a Write a Scala program to add each element n times to a given list of integers.
b Write a Scala program to split a given list into two lists.

a) Write a Scala program to add each element n times to a given list of integers

Program :
object Scala_List {

// function to add each elements in a list n times using List.fill(n) Method Here n= 3
def n_times_elements[A](o_list:List[A], n: Int):List[A] = {
o_list flatMap { element => List.fill(n)(element) }
}

def main(args: Array[String]): Unit = {

// List which 7 elements


val nums = List(1,2,3,3,4,5,6,7)
println("Original List:")
// Print list
println(nums)

//call the function n_times_elements


val result = n_times_elements(nums, 3)
println("Add each element 3 times to a given list of integers:")

// print List after adding add each elements in a list n times


println(result)
}
}

Output :

Original List:
List(1, 2, 3, 3, 4, 5, 6, 7)
Add each element 3 times to a given list of integers:
List(1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7)

Conclusion:

In this Program we understood about List and Fill() Method . List. fill() method creates a list
consisting of zero or more copies of the same element

b) Write a Scala program to split a given list into two lists.

Program :

object Scala_List {

// function to split a given list using take() and drop() Method.drop() method is
utilized to drop the first 'n' elements from the top of the stack and 'take' method in
Scala is used with iterators to get the first 'n' elements from a collection
def split_list[A](nums: List[A], n: Int): (List[A], List[A]) = {
(nums.take(n), nums.drop(n))
}

def main(args: Array[String]): Unit = {

//List with 8 Elements


val nums1 = List(1,2,3,4,5,6)
println("Original List:")
println("Split the said list into 2 lists:")

// call the function split_list and print the split list


println(split_list(nums1, 2))
println(split_list(nums1, 3))
}
}
Output :

Original List:
List(1,2,3,4,5,67,8)
Split the said list into 2 lists:
(List(1, 2),List(3, 4, 5, 6))
(List(1, 2, 3),List(4, 5, 6))

Conclusion:

In this Program we understood about List and take() and drop() Method . drop() method is
utilized to drop the first 'n' elements from the top of the stack and 'take' method in Scala is
used with iterators to get the first 'n' elements from a collection.

Extra :

Write a Scala program to count the number of occurrences of each element in a


given list.

object Scala_List {

def list_elemnt_occurrences[A](list1:List[A]):Map[A, Int] = {


list1.groupBy(el => el).map(e => (e._1, e._2.length))
}

def main(args: Array[String]): Unit = {


println(list_elemnt_occurrences(List(1,1,1,2,2,3,6,4,4,6,1,6,2)))
println(list_elemnt_occurrences(List("Red", "Green", "White", "Black", "Red", "Green",
"Black")))
}
}

HashMap(1 -> 4, 6 -> 3, 2 -> 3, 3 -> 1, 4 -> 2)


HashMap(Black -> 2, Green -> 2, Red -> 2, White -> 1)

10.
a.Write a Scala program to swap the elements of a tuple Further print no
swapping required if elements are same.

object SwapTupleElementsExample {
def main(args: Array[String]): Unit = {
// Create a tuple
val nums = (100, 200)
println("Original Tuple: "+nums)
// Swap the elements of the tuple
val swappedTuple = nums.swap

// Print the swapped tuple


println("Swapped tuple: " + swappedTuple)
}
}

Original Tuple: (100,200)


Swapped tuple: (200,100)

b.Write a Scala program to find non-unique elements in a tuple

object NonUniqueElementsInTuple {
def main(args: Array[String]): Unit = {
// Define a sample tuple with some elements
val tuple = (1, 2, 3, 2, 4, 5, 3, 6, 1, 7, 8)

// Convert the tuple to a list


val elementsList = tuple.productIterator.toList

// Find non-unique elements


val nonUniqueElements = elementsList
.groupBy(identity)
.collect { case (x, List(_, _, _*)) => x }
.toList

// Print the non-unique elements


println(s"Non-unique elements: $nonUniqueElements")
}
}

Non-unique elements: List(1, 2, 3)

Extra : Write a Scala program to check if two tuples are equal.

object CheckTupleEqualityExample {
def main(args: Array[String]): Unit = {
// Create two tuples
val tuple1 = (1, "Kotlin", true)
val tuple2 = (1, "Kotlin", true)
val tuple3 = (2, "Java", false)
println("Tuple1: "+tuple1)
println("Tuple2: "+tuple2)
println("Tuple3: "+tuple3)
// Check if the tuples are equal
val areEqual1 = tuple1 == tuple2
val areEqual2 = tuple1 == tuple3

// Print the results


println(s"Are tuple1 and tuple2 equal? $areEqual1")
println(s"Are tuple1 and tuple3 equal? $areEqual2")
}
}

Tuple1: (1,Kotlin,true)
Tuple2: (1,Kotlin,true)
Tuple3: (2,Java,false)
Are tuple1 and tuple2 equal? true
Are tuple1 and tuple3 equal? false

You might also like