Swift Semantics Fresco Play Hands-on Solution HackerRank

Swift Semantics Fresco Play Hands-on Solution, Learn: Dictionary, Tuples, Set-Get Functions, Collection Types, Optionals, classes with constructor etc
Swift Semantics Fresco Play Hands-on Solution HackerRank - www.pdfcup.com

Lab 1: Welcome to Swift - Program to print given name and address.

Try it out- Write a program to print your name on the console.

Solution 1:


import Foundation

/*
 * Complete the function below.
   Task 1: write a Swift function print_name() that accepts name as input, and returns the string "Hello \(name)... How are you?" as output. 
 */
 
func print_name(name: String) -> String {
    return "Hello \(name)... How are you?"
}
/* Refer 'Function_call' code which is given below if required. */ 

/*func print_name(name: String)*/
guard let name = readLine() else { fatalError("Bad input") }
let res = print_name(name: name)

let fileName = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
let fileURL = URL(fileURLWithPath: fileName)

do {
    try res.write(to: fileURL, atomically: false, encoding: .utf8)
} catch let error { fatalError(error as! String) }

Lab 2: Welcome to Swift - Program to add two variables given and print the result on the console

Try it Out -Program to add two given variables and print

Solution 2:

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

// Task 1: Write a program to add two variables, and print the result on a console.

var X = 10
var Y = 20

print(X+Y)


Lab 3: Welcome to Swift - Program to add two variables and print the result on the console

Try it Out - Program to add two variables and print the result

Solution 3:

import Foundation

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


// Task 1: write a Swift Function add_num that accepts two numbers (num1 and num2), and returns the sum of those numbers as integer.

func add_num(num1: Double, num2: Double) -> Int {
    return Int(num1+num2)

}
/*func add_num(num1: Double, num2: Double)*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

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

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

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

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

Lab 4: Welcome to Swift- Program to return the lengthiest city name from a group of cities.

Try it Out- Print City with Lengthiest Name.

Solution 4:

import Foundation

/*
 * Complete the 'longestCity' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts STRING_ARRAY cityArray as parameter.
 */

func longestCity(cityArray: [String]) -> String {

    var max = 0
    var ret_word = ""
    for language in cityArray {
      let s = language.length
      if max < s{
          max = s
          ret_word = language
          
      }
}
    return ret_word
}
/*func longestCity(cityArray: [String])*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

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

var cityArray = [String]()

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

    cityArray.append(cityArrayItem)
}

guard cityArray.count == cityArrayCount else { fatalError("Bad input") }

let result = longestCity(cityArray: cityArray)

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

Lab 5: Welcome to swift tuple: minMax

Try it Out: Find min-max.

Solution 5:

import Foundation

/*
 * Complete the 'minMax' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts INTEGER_ARRAY inputArray as parameter.
 */

func minMax(inputArray: [Int]) -> (min:Int,max:Int) {
    var  min: Int?
    var  max: Int?
    
    min =  inputArray.min()   
    max = inputArray.max()
    
    print(min!, max!)
    return (min!, max!)

}
/*func minMax(inputArray: [Int])*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

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

var inputArray = [Int]()

for _ in 1...inputArrayCount {
    guard let inputArrayItem = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }

    inputArray.append(inputArrayItem)
}

guard inputArray.count == inputArrayCount else { fatalError("Bad input") }

let result = minMax(inputArray: inputArray)
var min:String=String(result.min)
var max:String=String(result.max)
fileHandle.write(min.data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)
fileHandle.write(max.data(using: .utf8)!)

Lab 6: Welcome to Swift-Program to find the odd numbers from an input array.

Try it Out-find odd numbers in a given array.

Solution 6:

import Foundation
/*
 * Complete the 'print_odd' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts INTEGER_ARRAY inputArray as parameter.
 */

func print_odd(inputArray: [Int]) -> [Int] {
    
    var arr = [Int]()
    // print(inputArray)
    
    for language in inputArray {
        let s = language % 2
        if s != 0 {
          arr.append(language)          
        }
    }

    return arr
}
/*func print_odd(inputArray: [Int])*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

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

var inputArray = [Int]()

for _ in 1...inputArrayCount {
    guard let inputArrayItem = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }

    inputArray.append(inputArrayItem)
}

guard inputArray.count == inputArrayCount else { fatalError("Bad input") }
let result = print_odd(inputArray: inputArray)

fileHandle.write(result.map{ String($0) }.joined(separator: "\n").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

Lab 7: Welcome to swift odd array generator.

Try it out- Generate Odd Array

Solution 7:

import Foundation

/*
 * Complete the 'generate' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts INTEGER len as parameter.
 */

func generate(len: Int) -> [Int] {
    
    //Checking element of Array >0
    if(len > 0){
        
    } else { 
        return [] 
    }
    
    let n = len*2+1
    var ar = [Int]()
    var arr = [Int]()
    
    for i in 1...n{
        ar.append(i)
        
    }
    for i in ar{
        if(i%2 != 0){
            arr.append(i)        
        }
    }
    
    let arr_slice = arr[0...len-1]

    var odd_array = Array(arr_slice)
    
    odd_array.sort(by:<)
    // print(odd_array)
    return odd_array

}
/*func generate(len: Int)*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

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

let result = generate(len: len)

fileHandle.write(result.map{ String($0) }.joined(separator: "\n").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

Lab 8: Welcome to Swift calculator.

Try it Out- Create a Calculator

Solution 8:

import Foundation
/*
 * Complete the 'calc' function below.
 *
 * The function is expected to return a DOUBLE.
 * The function accepts following parameters:
 *  1. DOUBLE a
 *  2. DOUBLE b
 *  3. CHARACTER op
 */

func calc(a: Double, b: Double, op: Character) -> Double {
    
    let plus: Character = "+"
    let minus:Character = "-"
    let mul: Character = "*"
    let div: Character = "/"
    let mod: Character = "%"
    let poww: Character = "^"
    
    if( op == plus){
        return a+b
        
    }
    else if( op == minus){
        return a-b
        
    }
    else if( op == div){
        return a/b
        
    }
    else if( op == mul){
        return a*b
        
    }
    
    else if( op == poww){
        return pow(a,b)
        
    }
    else if( op == mod){
        return  Double(Int(a) % Int(b))
        
    }
    return 0

}
/*func calc(a: Double, b: Double, op: Character)*/
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

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

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

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

let op = opTemp.isEmpty ? "\0" : opTemp[opTemp.startIndex]

let result = calc(a: a, b: b, op: op)

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

Lab 9: Welcome to Duplicate remover.

Try-it-Out: Remove duplicates.

Solution 9:


import Foundation



/*
 * Complete the 'removeDuplicate' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts INTEGER_ARRAY inputArray as parameter.
 */

func removeDuplicate(inputArray: [Int]) -> [Int] {
    var res = Array(Set(inputArray))
    
    res.sort(by:<) //Sorting array in ascending Order
    
    // print(res)
    
    return res
    

}

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

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

var inputArray = [Int]()

for _ in 1...inputArrayCount {
    guard let inputArrayItem = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }

    inputArray.append(inputArrayItem)
}

guard inputArray.count == inputArrayCount else { fatalError("Bad input") }

let result = removeDuplicate(inputArray: inputArray)

fileHandle.write(result.map{ String($0) }.joined(separator: "\n").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)


Lab 10: Welcome to Swift- Dictionary : Authentication System.

Try-It-Out: Authentication System.

Solution 10:


import Foundation


func authenticate(user: String, pass: String) -> Bool {
    var numbers = ["admin": "admin123", "user": "someone123", "guest": "guest999", "you": "yourpass", "me": "mypass190"]
    let ky = Array(numbers.keys)
    let val = Array(numbers.values)
    var con: Bool?
    
    // var con = true
    if numbers.keys.contains(user){
        if numbers.values.contains(pass){         
            con = true
        }
        else{
            con = false
        }        
    }
    else{
        con = false
    }
    
    return con!

}

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

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

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

let result = authenticate(user: username, pass: pass)

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


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.....

Post a Comment