Skip to content

Instantly share code, notes, and snippets.

@retraigo
Last active December 13, 2022 04:56
Show Gist options
  • Save retraigo/279672aee366d48a48465b11aa7592de to your computer and use it in GitHub Desktop.
Save retraigo/279672aee366d48a48465b11aa7592de to your computer and use it in GitHub Desktop.
AI DS SEM 3 OOPS LAB
import scala.io.StdIn.{readInt};
import scala.collection.mutable.ArrayBuffer;
import scala.collection.immutable.List;
object Triplicate {
def main(args: Array[String]) = {
val arr = new ArrayBuffer[Int]();
println("Enter the numbers followed by a return after each number. Enter a non-number to stop.");
var continue = 1;
while(continue == 1) {
try {
arr.append(readInt());
}
catch {
case (_ : Throwable) => {
println("Ended input");
continue = 0;
}
}
}
println(s"Original List: ${List.from(arr)}");
// Using a list out of respect for list
val arr2 = arr.flatMap(x => List(x, x, x))
println(s"Triplicated List: ${List.from(arr2)}");
}
}
// SMALLER VERSION
object Triplicate2 {
def main(args: Array[String]): Unit = {
val arr = List(2, 3, 4, 5, 6, 7, 8, 9, 10);
val trip = arr.flatMap(x => List(x, x, x))
println(s"OG Array: ${arr.toSeq}")
println(s"Triplicated Array: ${trip.toSeq}")
}
}
class DivideByZeroException extends Exception("Cannot divide by Zero");
object ExceptionHandling {
def main(args: Array[String]) = {
try {
divideByZero(8);
} catch {
case ex: DivideByZeroException => println(ex);
}
}
@throws(classOf[DivideByZeroException])
def divideByZero(n: Int) = {
try {
n / 0;
} catch {
case _: Throwable => throw new DivideByZeroException();
}
}
}
import scala.io.StdIn.{readLine};
object StringOps {
def main(args: Array[String]) = {
println("Enter some text.")
val myString = readLine();
println(s"Length of the string is ${myString.length()}");
println(s"Concatenating string with itself -> ${myString.concat(myString)}");
println(s"String in lowercase is ${myString.toLowerCase()}");
println(s"String in uppercase is ${myString.toUpperCase()}");
println(s"String in reverse is ${myString.reverse}");
println(s"First character: ${myString.slice(0, 1)}");
println(s"First character but substring: ${myString.substring(0, 1)}");
println(s"Drop first 3 characters: ${myString.drop(3)}");
println(s"Replace D with P: ${myString.replace("D", "P")}");
println(s"Replace first D with P: ${myString.replaceFirst("D", "P")}");
println(s"Split for every e: ${myString.split("e")}");
println(s"Do nothing: ${myString.toString}");
println(s"Remove leading whitespaces: ${myString.trim}");
println(s"Does string start with C? ${myString.startsWith("C")}");
println(s"Hash of string is ${myString.hashCode()}");
}
}
/*
To develop a Scala application to generate Electricity bill.
Create a class with the following
members: Consumer no., consumer name, previous month reading,
current month reading, type
of EB connection (i.e domestic or commercial).
Compute the bill amount using the following
tariff.
If the type of the EB connection is domestic,
calculate the amount to be paid as follows:
• First 100 units - Rs. 1 per unit
• 101-200 units - Rs. 2.50 per unit
• 201 -500 units - Rs. 4 per unit
• >501 units - Rs. 6 per unit
If the type of the EB connection is commercial,
calculate the amount to be paid as follows:
• First 100 units - Rs. 2 per unit
• 101-200 units - Rs. 4.50 per unit
• 201 -500 units - Rs. 6 per unit
• >501 units - Rs. 7 per unit
*/
import scala.io.StdIn.{ readLine, readInt, readDouble }
object Something {
def main(args: Array[String]): Unit = {
println("BILL GENERATOR");
println("Enter name");
val name = readLine();
println("Enter consumer number");
val id = readInt();
println("Enter type of connection (domestic / commercial)")
val option = readLine();
println("Enter previous month reading")
val prev = readDouble()
println("Enter current month reading")
val curr = readDouble()
val connection = new EbConnection(id, name, prev, curr, option)
connection.calculateBill;
}
}
object Price {
val domestic = Array(1.0, 2.5, 4.0, 6.0);
val commercial = Array(2.0, 4.5, 6.0, 7.0);
}
class EbConnection(
val consumer_no: Int,
val consumer_name: String,
val previous_month: Double,
val current_month: Double,
val connection_type: String
) {
def calculateBill = {
val rate = connection_type match {
case "domestic" => Price.domestic
case "commercial" => Price.commercial
case _ => throw new Error("Invald")
}
val usage = current_month - previous_month;
val bill = total(rate, usage);
println(s"Total Units: $usage")
println(s"Amount to Pay: $bill")
}
def total(rate: Array[Double], usage: Double): Double = {
if (usage <= 100) {
return usage * rate(0)
} else if (usage > 100 && usage <= 200) {
val extra = usage - 100;
return (extra * rate(1)) + total(rate, 100);
} else if (usage > 200 && usage <= 500) {
val extra = usage - 200;
return (extra * rate(2)) + total(rate, 200);
} else {
val extra = usage - 500;
return (extra * rate(3)) + total(rate, 500);
}
}
}
// Scala 2
// First, `scalac ./filename.scala`
// Then, `scala Converter`
package converter {
class Currency {
def dollarToRupee(amount: Double): Double = {
return amount / 79.969958;
}
def rupeeToDollar(amount: Double): Double = {
return amount * 79.969958;
}
def euroToRupee(amount: Double): Double = {
return amount / 79.967401;
}
def rupeeToEuro(amount: Double): Double = {
return amount * 79.967401;
}
def yenToRupee(amount: Double): Double = {
return amount * 1.7360026;
}
def rupeeToYen(amount: Double): Double = {
return amount * 0.57602816;
}
}
class Distance {
def meterToKilometer(amount: Double): Double = {
return amount / 1000;
}
def kilometerToMeter(amount: Double): Double = {
return amount * 1000;
}
def mileToKilometer(amount: Double): Double = {
return amount * 1.609344;
}
def kilometerToMile(amount: Double): Double = {
return amount / 1.609344;
}
}
class Time {
def hourToMinute(amount: Double): Double = {
return amount * 60;
}
def minuteToHour(amount: Double): Double = {
return amount / 60;
}
def hourToSecond(amount: Double): Double = {
return amount * 3600;
}
def secondToHour(amount: Double): Double = {
return amount / 3600;
}
def minuteToSecond(amount: Double): Double = {
return amount * 60;
}
def secondToMinute(amount: Double): Double = {
return amount / 60;
}
}
}
import converter.{Time, Currency, Distance}
import scala.io.StdIn.{readDouble, readLine};
object Converter {
def main(args: Array[String]) = {
val TimeConverter = new Time();
val CurrencyConverter = new Currency();
val DistanceConverter = new Distance();
var i: Double = 1;
var value: Double = 0;
while (i != 0) {
println(
"1. USD to INR\n2. INR to USD\n3. EURO to INR\n4. INR to EURO\n5. JPY to INR\n6. INR to JPY"
);
println(
"7. Metre to Kilometre\n8. Kilometre to Metre\n9. Mile to Kilometre\n10. Kilometre to Mile"
);
println(
"11. Hour to Minute \n12. Minute to Hour \n13. Hour to Second \n14. Second to Hour \n15. Minute to Second \n16. Second to Minute"
)
i = readDouble();
println("Value to convert?")
value = readDouble();
i match {
case 1 => println(CurrencyConverter.dollarToRupee(value));
case 2 => println(CurrencyConverter.rupeeToDollar(value));
case 3 => println(CurrencyConverter.euroToRupee(value));
case 4 => println(CurrencyConverter.rupeeToEuro(value));
case 5 => println(CurrencyConverter.yenToRupee(value));
case 6 => println(CurrencyConverter.rupeeToYen(value));
case 7 => println(DistanceConverter.meterToKilometer(value));
case 8 => println(DistanceConverter.kilometerToMeter(value));
case 9 => println(DistanceConverter.mileToKilometer(value));
case 10 => println(DistanceConverter.kilometerToMile(value));
case 11 => println(TimeConverter.hourToMinute(value));
case 12 => println(TimeConverter.minuteToHour(value));
case 13 => println(TimeConverter.hourToSecond(value));
case 14 => println(TimeConverter.secondToHour(value));
case 15 => println(TimeConverter.minuteToSecond(value));
case 16 => println(TimeConverter.secondToMinute(value));
case 0 => sys.exit(0);
}
readLine();
}
}
}
/*
Develop a Scala application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile no as members. Inherit the classes, Programmer, Assistant Professor,
Associate Professor and Professor from employee class. Add Basic Pay (BP) as the member
of all the inherited classes with 17% of BP as DA, 10 % of BP as HRA, 12% of BP as PF,
0.1% of BP for staff club fund. The allowance for Programmer is Rs2000, Assistant Professor
is Rs5000, Associate Professor is Rs10000 and Professor is Rs15000. Calculate the salary as
gross salary=BP+DA+HRA+Allowance and deductions=PF+staffclubfund. Calculate the net
salary=gross salary - deductions. Generate pay slips for the employees with their gross and
net salary. Mention what type of inheritance is this.
*/
import scala.io.StdIn.{readDouble, readLine, readBoolean};
class Employee(
val emp_name: String,
val emp_id: String,
val mail_id: String,
val mobile_no: String,
val basic_pay: Double,
val allowance: Double
) {
def DA = basic_pay * 17 / 100;
def HRA = basic_pay * 0.1;
def PF = basic_pay * 12 / 100;
def SCF = basic_pay * 0.001;
};
class Programmer(
emp_name: String,
emp_id: String,
mail_id: String,
mobile_no: String,
basic_pay: Double
) extends Employee(
emp_name,
emp_id,
mail_id,
mobile_no,
basic_pay,
2000.0
);
class AssistantProfessor(
emp_name: String,
emp_id: String,
mail_id: String,
mobile_no: String,
basic_pay: Double
) extends Employee(
emp_name,
emp_id,
mail_id,
mobile_no,
basic_pay,
5000.0
)
class AssociateProfessor(
emp_name: String,
emp_id: String,
mail_id: String,
mobile_no: String,
basic_pay: Double
) extends Employee(
emp_name,
emp_id,
mail_id,
mobile_no,
basic_pay,
10000.0
)
class Professor(
emp_name: String,
emp_id: String,
mail_id: String,
mobile_no: String,
basic_pay: Double
) extends Employee(
emp_name,
emp_id,
mail_id,
mobile_no,
basic_pay,
15000.0
)
object PaySlipGenerator {
def main(args: Array[String]) = {
println("SCALA PAYSLIP GENERATOR");
var continue = true;
while (continue == true) {
println("Choose your profession:");
println(
"1. Programmer\n2. Assistant Professor\n3. Associate Professor\n4. Professor."
);
val profession = readDouble();
println("Enter your name.");
val name = readLine();
println("Enter your ID.");
val id = readLine();
println("Enter your mobile number.");
val mobile = readLine();
println("Enter your mail ID.");
val email = readLine();
println("Enter your basic pay.");
val basic_pay = readDouble();
val employee = profession match {
case 1.0 => new Programmer(name, id, email, mobile, basic_pay);
case 2.0 => new AssistantProfessor(name, id, email, mobile, basic_pay);
case 3.0 => new AssociateProfessor(name, id, email, mobile, basic_pay);
case 4.0 => new Professor(name, id, email, mobile, basic_pay);
case _ => {
println("Invalid choice. Defaulting to programmer.")
new Programmer(name, id, email, mobile, basic_pay)
};
}
val gross_salary =
employee.basic_pay + employee.DA + employee.HRA + employee.allowance;
val deductions = employee.PF + employee.SCF;
val net_salary = gross_salary - deductions;
println("============");
println("PAYSLIP");
println("============");
println(s"Gross Salary: $gross_salary");
println(s"Deductions: -$deductions");
println(s"Net Salary: $net_salary");
println("\nContinue? (true/false)");
continue = readBoolean();
}
}
}
/*
OUTPUT
SCALA PAYSLIP GENERATOR
Choose your profession:
1. Programmer
2. Assistant Professor
3. Associate Professor
4. Professor.
1
Enter your name.
Lolly
Enter your ID.
aids
Enter your mobile number.
6942069420
Enter your mail ID.
watermelon@banana.com
Enter your basic pay.
42000
============
PAYSLIP
============
Gross Salary: 55340.0
Deductions: -5082.0
Net Salary: 50258.0
Continue? (true/false)
*/
import scala.io.StdIn.{readInt, readLine}
trait StackOperations[T] {
def push(item: T): Unit;
def pop: Unit;
}
class Stack(val size: Int) extends StackOperations[String] {
val data = new Array[String](size);
var top = -1;
def push(item: String) = {
if (top == size - 1) throw new Error("Stack overflow");
top += 1;
data(top) = item;
}
def pop = {
if (top == -1) throw new Error("Stack underflow");
data(top) = ""
top -= 1;
}
}
object StackExample {
def main(args: Array[String]): Unit = {
println("Stack!")
val stack = new Stack(100)
var cont = true;
while (cont == true) {
println("1. Push\n2. Pop\n3. Display")
val choice = readInt()
choice match {
case 1 => {
println("Value?")
val str = readLine()
stack.push(str)
println("Pushed!")
}
case 2 => {
stack.pop;
println("Popped!")
}
case 3 => println(stack.data.toSeq);
case _ => cont = false;
}
}
}
}
import scala.io.StdIn.{readDouble, readLine, readInt};
import scala.sys.process.processInternal;
import scala.collection.mutable.ArrayBuffer;
class ArrayList() {
var data: ArrayBuffer[String] = new ArrayBuffer();
def append(value: String) = {
data.append(value);
}
def remove(value: String) = {
data -= value;
};
def insert(value: String, at: Int) = {
data.insert(at - 1, value);
}
def search(value: String) = if (data.exists(x => x == value)) "Exists" else "Doesn't Exist";
def startsWith(value: String) = data.filter(x => x.startsWith(value)).toSeq;
def display() = println(s"${data.toSeq}");
}
object StringArray {
def main(args: Array[String]) = {
var i: Double = 1;
var value: String = "";
var arr = new ArrayList();
while (i != 0) {
println(
"1. Append\n2. Insert\n3. Search\n4. Starts with?\n5. Size\n6. Remove"
);
println(
"7. Display\n"
);
i = try {
readInt();
} catch {
case _: Throwable => sys.exit(1);
}
if(i == 1 || i == 2 || i == 3 || i == 4 || i == 6) {
println("Value?")
value = readLine();
}
i match {
case 1 => arr.append(value);
case 2 =>
println("Insert At?");
val at = readInt()
if (at > 100) {
println("NO")
sys.exit(1)
}
arr.insert(value, at - 1);
case 3 => println(arr.search(value));
case 4 => println(arr.startsWith(value));
case 6 => {
arr.remove(value);
println("Done");
};
case 5 => println(s"${arr.data.length} items");
case 7 => arr.display();
case _ => sys.exit(0);
}
readLine();
}
}
}
import scala.io.StdIn.{readLine, readDouble}
abstract class Shape {
def printArea: Unit;
}
class Triangle(b: Double, h: Double) extends Shape {
def printArea: Unit = println(s"Area: ${0.5 * b * h}")
}
class Rectangle(l: Double, b: Double) extends Shape {
def printArea: Unit = println(s"Area: ${l * b}")
}
class Circle(r: Double) extends Shape {
def printArea: Unit = println(s"Area: ${3.14 * r * r}")
}
object AbstractClasses {
def main(args: Array[String]) = {
println("Choose a shape.")
val ch = readLine()
val shape: Shape = ch.toLowerCase match {
case "triangle" => {
println("Enter base")
val b = readDouble()
println("Enter height")
val h = readDouble()
new Triangle(b, h)
}
case "rectangle" => {
println("Enter length")
val l = readDouble()
println("Enter breadth")
val b = readDouble()
new Rectangle(l, b)
}
case _ => {
println("Enter radius")
val r = readDouble()
new Circle(r)
}
}
shape.printArea
}
}
import scala.io.StdIn.readInt;
object BuiltInException {
def main(args: Array[String]): Unit = {
println("Choose:");
println("1. Number Format Exception");
println("2. Array Index Out of Bound");
println("3. Negative Array Size Exception");
println("4. Arithmetic Exception");
val choice = readInt();
choice match {
case 1 => {
throw new NumberFormatException("thrown");
}
case 2 => {
throw new ArrayIndexOutOfBoundsException("thrown");
}
case 3 => {
throw new NegativeArraySizeException("thrown");
}
case 4 => {
throw new ArithmeticException("thrown");
}
case _ => throw new Exception("Should be 1 - 4");
}
}
}
import scala.io.StdIn.readInt
class NegativeAmountException(s: String) extends Exception(s)
object UserExceptions {
def main(args: Array[String]): Unit = {
try {
println("Enter amount")
val amount = readInt()
if (amount < 0)
throw new NegativeAmountException("Amount cannot be negative")
println("Amount deposited.")
} catch {
case e: NegativeAmountException => println("invalid amount")
case _: Throwable => println("some other error")
}
}
}
import scala.io.StdIn.{readInt};
import scala.collection.mutable.ArrayBuffer;
object OddOrEven {
def main(args: Array[String]) = {
val arr = new ArrayBuffer[Int]();
println("Enter the numbers followed by a return after each number. Enter a non-number to stop.");
var continue = 1;
while(continue == 1) {
try {
arr.append(readInt());
}
catch {
case (_ : Throwable) => {
println("Ended input");
continue = 0;
}
}
}
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);
}
}
// SMALLER VERSION
object EvenOdd {
def main(args: Array[String]): Unit = {
val arr = Array(2, 3, 4, 5, 6, 7, 8, 9, 10);
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(s"Sorted Array: ${arr.toSeq}")
}
}
@noob69master20
Copy link

noob69master20 commented Dec 13, 2022

class current(var custid:Int,var custname:String,var cmr:Int,var pmr:Int,var DorC:String)
{
def dom(cmr:Int):Unit=
{
if(cmr<100)
{
println("The amount for units: ",+cmr1)
}
else if(cmr>100 && cmr<=200)
{
println("The amount for units: "+cmr
2.50)
}
else if(cmr>200 && cmr<=500)
{
println("The amount for units: "+cmr4)
}
else
{
println("The amnount for the units: "+cmr
6)
}
}
def com(cmr:Int):Unit=
{
if(cmr<100)
{
println("The amount for units: ",+cmr2)
}
else if(cmr>100 && cmr<=200)
{
println("The amount for units: "+cmr
4.50)
}
else if(cmr>200 && cmr<=500)
{
println("The amount for units: "+cmr6)
}
else
{
println("The amnount for the units: "+cmr
7)
}
}
def custdetails(custname:String,custid:Int,cmr:Int,pmr:Int,DorC:String):Unit=
{
println("Electricity Bill")
println("Customer Name: "+custname)
println("Customer id: "+custid)
println("Previous month reading: "+pmr)
println("Current month reading: "+cmr)
println("Type of connection: "+DorC)
}
}
object suma
{
def main(args:Array[String]):Unit=
{

    println("Welcome..!!,Kindly Enter your details and readings.")
    println("Enter Customer name: ")
    var i=scala.io.StdIn.readLine()
    println("Enter customer id: ")
    var j=scala.io.StdIn.readInt()
    println("Enter the previous month reading: ")
    var k=scala.io.StdIn.readInt()
    println("Enter the current month reading: ")
    var l=scala.io.StdIn.readInt()
    println("Enter the type of connection(D for Domestic and C for Commercial)")
    var m=scala.io.StdIn.readLine()
    var s= new current(j,i,k,l,m)
    s.custdetails(i,j,k,l,m)
    if(m=="C")
    {
        s.com(l)
    }
    else
    {
        s.dom(l)
    }

    
    
    
    
    
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment