Swift Semantics Continuum Fresco Play Hands-on Solution HackerRank

Learn Swift programming Advance features like Closures, Enumerations, Properties, Protocols, Data Structures, Classes and Methods with Handson.
Swift Semantics Continuum Fresco Play Hands-on Solution HackerRank - www.pdfcup.com

Lab 1: Welcome to Swift - Program using closure to find sum of two numbers.

Try it Out - Program using closure to find sum of two numbers.

Solution 1:

import Foundation
/*
 * Complete the 'Sum' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER num1
 *  2. INTEGER num2
 */

//Task 1: Write a programe using a closure that accepts two integer numbers (num1 and num2), and returns the sum of those numbers.

func Sum(num1: Int, num2: Int) -> Int {
    let sum = num1 + num2
    return sum

}

// Check out the 'Optional' function calling code below if interested!
/*func Sum(num1: Int, num2: Int)*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let num1 = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

guard let num2 = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

let result = Sum(num1: num1, num2: num2)

fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

Lab 2: Welcome to Swift - Program to store names of 10 students in an array and Sort it.

Try it Out - Program to store names in an array and Sort

Solution 2:


import Foundation



/*
 * Complete the 'sort_names' function below.
 *
 * The function accepts STRING_ARRAY names as parameter.
 */

//Task 1: Write a program to store the names of 5 students in an array. Sort the array in ascending order alphabetically.

func sort_names(names: [String]) -> Void {
    var n = names
    
    n.sort(by:<)
    for i in n{
        print(i)
    }
    
    

}

guard let namesCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

var names = [String]()

for _ in 1...namesCount {
    guard let namesItem = readLine() else { fatalError("Bad input") }

    names.append(namesItem)
}

guard names.count == namesCount else { fatalError("Bad input") }

sort_names(names: names)



Lab 3: Welcome to Swift - Program to store details of 5 students

Try it Out - Program to store details of 5 students

Solution 3:



// Enter your code here. Read input from STDIN. Print output to STDOUT

// Task 1: Write a programe to store details of 5 students: Roll number, Name, Marks of 3 Subjects.



class Student{
  var roll : Int
  var name : String
  var mark1 : Int
  var mark2 : Int
  var mark3 : Int

  
// assign value using initializer
  init(rollno: Int,name: String, mark1: Int, mark2: Int, mark3: Int){
  self.roll = rollno
  self.name = name
  self.mark1 = mark1
  self.mark2 = mark2
  self.mark3 = mark3
}
  
}

var s1 = Student(rollno: 1, name: "Alan", mark1: 45, mark2: 50, mark3: 42)
var s2 = Student(rollno: 2, name: "Ben", mark1: 48, mark2: 50, mark3: 32)
var s3 = Student(rollno: 3, name: "Cassey", mark1: 41, mark2: 35, mark3: 42)
var s4 = Student(rollno: 4, name: "Dexter", mark1: 43, mark2: 30, mark3: 42)
var s5 = Student(rollno: 5, name: "Elle", mark1: 45, mark2: 47, mark3: 32)

// Task 2: Fetch the roll number of student s1
print(s1.roll)

Lab 4: Welcome to Role Manager

Try it Out - Role Manager

Solution 4:



import Foundation



/*
 * Complete the 'roleManager' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts STRING role as parameter.
 */


//Task 1: Create an enum named Role which contains 3 members admin, owner, and guest.
enum Role:String{
     case admin
     case owner
     case guest
     case none
 }
 
// Task 2: Create a function roleManager which takes the Role as the argument, and return the following values:
// Role.admin : "Full Access Granted"
// Role.owner : "Read Write Access Granted"
// Role.guest : "Temporary Access Granted" 

func roleManager(role:Role) -> String {
  // guard let roles = role else { fatalError("Bad input") }
  // if anOptionalInt != nil {
  //     print("Contains a value!")
  // } else {
  //     print("Doesn’t contain a value.")
  // }
if role == .admin  {

  return "Full Access Granted"
}
if  role == .owner{     
  return "Read Write Access Granted"
}
if  role == .guest{    
  return "Temporary Access Granted"

}
return ""
}

let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let role = readLine() else { fatalError("Bad input") }

let arg=Role(rawValue:role)!
let result = roleManager(role: arg)

fileHandle.write(result.data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)


Lab 5: Welcome to Grading System

Try-it-Out Grading System

Solution 5: Welcome to Grading System



import Foundation



/*
 * Create the 'Student' class below.
 */

protocol Person{
   var name:String{set get}
   var age:Int{get set}
}
// Task 1: Adopt a Person prtotocol to create a class Student.
// The stiudent Class should contain additional members:
//  mark1:Int, mark2:Int, mark3:Int
//  average()-> Double should return the average marks (round off to 2 decimal points) of a given students
// Create a Initilizer to initilize every member.

class Student : Person {
    var age :Int
    var name :String
    var mark1 : Int
    var mark2 : Int
    var mark3:Int

    init(name:String,age:Int,mark1:Int,mark2:Int,mark3:Int){
        self.name = name
        self.age = age
        self.mark1 = mark1
        self.mark2 = mark2
        self.mark3 = mark3

    }
    // print(mark1+mark2+mark3)/3)
      func average() ->Double{
            let t = Double(mark1+mark2+mark3)/3
            return round(t * 100) / 100.0 

    }
}



let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let name:String = readLine() else { fatalError("Bad input") }

guard let age:Int = Int(readLine()!) else { fatalError("Bad input") }

guard let m1:Int = Int(readLine()!) else { fatalError("Bad input") }
guard let m2:Int = Int(readLine()!) else { fatalError("Bad input") }
guard let m3:Int = Int(readLine()!) else { fatalError("Bad input") }
let std = Student(name:name,age:age,mark1:m1,mark2:m2,mark3:m3)
let result = std.average()

fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)


Lab 7: Swift Class Bank - Creating a Banking Application

Try-It-On : Banking System

Solution 7:


import Foundation




// Problem: Create a Banking application with a code containing:
/*
Customer class with i
    * ID:Int
    * name:String
    * balance:Double attributes
*/


class  Customer{
  var id:Int
  var name:String
  var balance:Double
  init(id:Int,name:String,balance:Double){
    self.id = id
    self.name = name   
    
    // Task 3: On constructor creation, minimum balance of 500 should be assigned to the custoemr.
    
    if(balance <= 500.0){
        self.balance = 500.0
    } else {
        self.balance = balance
    }
}
    
}
class Bank {
 
    // Task 1: Create Customer array attribute with the name customers
    var customers = [Customer ]()
    
    // Task 2: Create a constructor which receives count as parameter, and dynamically builds the customer array based on count.
    init(count:Int){  
          
        // Task 4: Customer ID must start from 1, and should increment by 1.
        for i in  1...count{
        customers.append(Customer(id:i, name:"Test",balance:Double(i)))
        // print(i)
        }
}
  
  // Task 5: deposit amount to customer balance
  func deposit(id:Int, amount:Double) -> Void {
    
    // print("->",customers.count)
    for customer in customers{
      
      if customer.id == id{
        print(customer.id, customer.balance )
        customer.balance += amount
        print(customer.id, customer.balance )
      }
    //   print(customer.id, customers)


    }
  }
  
    // Task 6: Withdraw amount from customer balance and maintain minimum balance of 500.0.
  func withdraw(id:Int, amount:Double) -> Void{


    for customer in customers{
      if customer.id == id{
        if customer.balance - amount >= 500.0 {
          customer.balance = customer.balance - amount
        }


      }
    }
  }


    // Task 7:  return customer object respective to the id, if not found then nil.
    func getCustomer(id:Int) -> Customer?{
      for customer in customers{
        if customer.id == id{
          return customer
        }
      }
      return nil
    }
}


let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!


guard let custCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }


guard let testCaseCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }


var bank = Bank(count:custCount)


guard let id = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }


for _ in 1...testCaseCount {
    guard let ops = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }
    
    guard let amount = Double((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }
    
   switch ops{
       case 1 ://deposit
                bank.deposit(id:id,amount:amount)
       case -1 : //withdraw
                bank.withdraw(id:id,amount:amount)
       default : break
       
   }
}






let cust:Customer! = bank.getCustomer(id:id)
fileHandle.write(String(bank.customers.count).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)


if cust != nil {
fileHandle.write(String(cust.balance).data(using: .utf8)!)
}





Lab 8: Welcome to Math Class Impl

Try-It-Out : Math class mock

Solution 8:



import Foundation

// Create a Math class which includes the following class/static methods:
// Note: Round off the result to 2 decimal points (except for round method).

class Math{
 
  // Task 1: Create function: pow (a:Int,b:Int)->Int returns a raised to b.
  // Example:  pow (a:3,b:4) returns 81
  static func pow(a:Int, b:Int) -> Int{

     var list_of_same_num = [Int](repeating: a, count: b)
     print("List: ", list_of_same_num)
     let index = 0
     var power = 1
     while list_of_same_num.count != 0 {
       power = list_of_same_num[index]*power
       list_of_same_num.remove(at : index)

     }
   
    print("\(a) power of \(b) is: ",power)
    return power
  }

  //  Task 2: Create function: round (num:Double,point:Int) -> Double rounds num to point decimal points.
  // Example:  round (num:3.3546,point:2) returns 3.35

  static func round(num:Double, point:Int) -> Double {    

    let round_value = Double(String(format: "%.\(point)f", num))!
   
    print("\(num) round in \(point)th place is: ",round_value)
    return round_value    

  }

  // Task 3: Create function: divide (a:Int,b:Int)->Double returns the division result of a and b.
  // Example:  divide (a:100,b:3) returns 33.33
  static func divide(a:Int, b:Int) -> Double{
    let quotient = Double(a) / Double(b)
    let str_quotient = String(quotient)

    let split_str_by_dot = str_quotient.components(separatedBy: ".")
    let fractonal_two_place = String(split_str_by_dot[1].prefix(2))
    let final_quotient:Double = Double(split_str_by_dot[0] + "." + fractonal_two_place)!
   
    print("\(a) divide by \(b) is: ", final_quotient)
    return  final_quotient

  }

  // Task 4: Create function: sqrt (num:Int)->Double returns the square root of num.
  // Example: sqrt (num:4) returns 2.0

  static func sqrt(num:Int) -> Double {
    var half_of_num : Double = Double(num)/2
    var stopper : Double = 0
    while Double(half_of_num) != Double(stopper) {
      stopper = half_of_num
      half_of_num = (Double(num)/stopper + stopper)/2

    }


    let n = 2
    let Square_root = Double(String(format: "%.\(n)f", half_of_num))!
   
    print("Square Root of \(num) is: ", Square_root)
    return Square_root
  }


}

let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let a = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

guard let b = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }


guard let num = Double((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

guard let point = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }


guard let num1 = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

let dev=Math.divide(a:a,b:b)
let pow=Math.pow(a:a,b:b)
let round=Math.round(num:num,point:point)
let sqrt=Math.sqrt(num:num1)

fileHandle.write(String(dev).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

fileHandle.write(String(pow).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

fileHandle.write(String(round).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

fileHandle.write(String(sqrt).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)





Lab 6: Welcome to Swift LinkedLIst.

Try-It-Out Swift Linked List.

Solution 6:


[1:10 PM] Uniyal, Manish
import Foundation
 
 
class Node{
    var data:Int
    var next:Node!
    init(data:Int){
        self.data = data
        self.next = nil
       
    }
}
 
class LinkedList {
   
    // Task 3: head:Node holds the first element reference.
    private(set) var head: Node?
   
    // Task 2: count:Int keeps track of the number of nodes in the link.
    private(set) var count: Int = 0
   
    // Task 1: The function insert (data:Int) inserts data to the list, and returns nothing.
   
    // Inserts a new node with the given data into the linked list
    func insert(data: Int) {
        let newNode = Node(data: data)
       
        if head == nil {
            head = newNode
        } else {
            var current = head
            while current?.next != nil {
                current = current?.next
            }
            current?.next = newNode
        }
       
        count += 1
    }
}
 
 
 
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
 
guard let arrCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
 
 
var list = LinkedList()
if arrCount>0{
for _ in 1...arrCount {
    guard let arrItem = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }
 
   list.insert(data:arrItem)
}
}
 
let count = list.count
 
fileHandle.write(String(count).data(using: .utf8)!)
var temp:Node! = list.head
while temp != nil {
     fileHandle.write("\n".data(using: .utf8)!)
    fileHandle.write(String(temp.data).data(using: .utf8)!)
   
    temp = temp.next
}
 
 


About the author

D Shwari
I'm a professor at National University's Department of Computer Science. My main streams are data science and data analysis. Project management for many computer science-related sectors. Next working project on Al with deep Learning.....

1 comment

  1. Anonymous
    I'm facing issue with exercise 6, can you help by sharing the solution plzz??