0% found this document useful (0 votes)
13 views16 pages

Swift Language Code Examples

Its easy to understand ios codes

Uploaded by

mmind6167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views16 pages

Swift Language Code Examples

Its easy to understand ios codes

Uploaded by

mmind6167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Mohammed Nazim

Set – 1 Mathematical Problem

1. Armstrong number

import Foundation

func isArmstrongNumber(_ number: Int) -> Bool {


let digits = String(number).compactMap { Int(String($0)) }
let power = digits.count
let sum = digits.reduce(0) { $0 + Int(pow(Double($1), Double(power))) }
return sum == number
}

let number = 1634


if isArmstrongNumber(number) {
print("\(number) is an Armstrong number.")
} else {
print("\(number) is not an Armstrong number.")
}

2. GCD of two numbers

func gcd(_ a: Int, _ b: Int) -> Int {


var x = a
var y = b
while y != 0 {
let remainder = x % y
x=y
y = remainder
}
return x
}

let num1 = 10
let num2 = 15
let result = gcd(num1, num2)
print("The GCD of \(num1) and \(num2) is \(result).")
Mohammed Nazim

Set – 2 Puzzles Problems

1. Trailing zeroes in factorial

func trailingZeroesInFactorial(_ n: Int) -> Int {


var count = 0
var divisor = 5
var num = n
while num / divisor > 0 {
count += num / divisor
divisor *= 5
}
return count
}

let number = 25
let trailingZeroes = trailingZeroesInFactorial(number)
print("The number of trailing zeroes in \(number)! is \(trailingZeroes).")

2. Number of open doors

func numberOfOpenDoors(_ n: Int) -> Int {


return Int(Double(n).squareRoot())
}

let doors = 10
let openDoors = numberOfOpenDoors(doors)
Mohammed Nazim

print("The number of open doors out of \(doors) doors is \(openDoors).")


Mohammed Nazim

Set – 3 Array Problems

1. Remove duplicate elements from sorted Array

func removeDuplicates(from sortedArray: [Int]) -> [Int] {


guard !sortedArray.isEmpty else { return [] } var
uniqueArray = [sortedArray[0]] for i in
1..<sortedArray.count { if sortedArray[i] != sortedArray[i
- 1] { uniqueArray.append(sortedArray[i])
} } return
uniqueArray
}
let sortedArray = [1, 1, 2, 3, 3, 4, 5, 5] let uniqueArray =
removeDuplicates(from: sortedArray) print("Array after
removing duplicates: \(uniqueArray)")

2. Maximum Sub Array

func maxSubArray(_ nums: [Int]) -> Int {


guard !nums.isEmpty else { return 0 }

var currentMax = nums[0]


var globalMax = nums[0] for
i in 1..<nums.count {
currentMax = max(nums[i], currentMax + nums[i])
globalMax = max(globalMax, currentMax)
}

return globalMax
}
Mohammed Nazim

let array = [ 1, -3, 4, -1, 2, 1, -5, 4]


let maxSum = maxSubArray(array) print("Maximum
subarray sum is \(maxSum)")

Set – 4 String Problems

1. Extract Maximum

func extractMaximum(from array: [Int]) -> Int? {


return array.max()
}
let numbers = [3, 5, 1, 9, 2]
if let maxValue = extractMaximum(from: numbers) {
print("The maximum value is \(maxValue)")
} else {
print("The array is empty.")
}

2. URLify a Given String

func urlify(_ text: String) -> String {


return text.replacingOccurrences(of: " ", with: "%20")

let originalString = "Hello World This Is Swift" let


urlifiedString = urlify(originalString)
print("URLified string: \(urlifiedString)")
Mohammed Nazim

Set- 5 Search problems

1. Floor in a sorted array

func floor(of target: Int, in array: [Int]) -> Int? {


var low = 0 var high = array.count - 1 var
result: Int? = nil while low <= high { let
mid = (low + high) / 2 if array[mid] ==
target { return array[mid] // Exact match
} else if array[mid] < target { result =
array[mid] low = mid + 1 } else {
high = mid - 1
} }
return result
}
let sortedArray = [1, 2, 8, 10, 10, 12, 19] let
target = 5
if let floorValue = floor(of: target, in: sortedArray) {
print("Floor value is: \(floorValue)")
} else { print("No floor
found")
}

2. Last index of One

let array = [1, 2, 3, 4, 1] if let lastIndex =


array.lastIndex(of: 2) { print("The last
index of 2 is \(lastIndex)")
Mohammed Nazim

} else {
print("2 is not in the array")
}

Set – 6 Sorting Problems

1. Reversing a String

func bubbleSort(_ array: inout [Int]) {


let n = array.count for i in 0..<n {
var swapped = false for j in
1..<(n - i) { if array[j - 1] >
array[j] { array.swapAt(j -
1, j) swapped = true
}
}
if !swapped {
break
}
}
}
var numbers = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(&numbers) print("Sorted
array: \(numbers)")

2. Quick Sort

func quickSort(_ array: inout [Int]) {


quickSortHelper(&array, low: 0, high: array.count - 1)
}
Mohammed Nazim

private func quickSortHelper(_ array: inout [Int], low: Int, high: Int) {
if low < high {
let pivotIndex = partition(&array, low: low, high: high)
quickSortHelper(&array, low: low, high: pivotIndex - 1)
quickSortHelper(&array, low: pivotIndex + 1, high: high)
}
}
private func partition(_ array: inout [Int], low: Int, high: Int) -> Int {
let pivot = array[high] var i = low - 1 for j in low..<high {
if array[j] <= pivot { i += 1 array.swapAt(i, j)
}
}
array.swapAt(i + 1, high)
return i + 1
}

var numbers = [10, 7, 8, 9, 1, 5]


quickSort(&numbers) print("Sorted
array: \(numbers)")

Set – 7 Hashing Problems

1. check if two arrays are equal or not

func areArraysEqual<T: Equatable>(_ array1: [T], _ array2: [T]) -> Bool {


return array1 == array2
}

let array1 = ["apple", "banana", "cherry"]


let array2 = ["apple", "banana", "cherry"]
let array3 = ["apple", "banana", "kiwi"]
Mohammed Nazim

let array4 = [true, false, true] let array5 =


[true, true, false]

let result1 = areArraysEqual(array1, array2) // true


let result2 = areArraysEqual(array1, array3) // false
let result3 = areArraysEqual(array4, array5) // false
print(result1) // Output: true print(result2) //
Output: false print(result3) // Output: false

2. count pairs with given sum

func countPairsWithSum(_ array: [Int], targetSum: Int) -> Int {


var count = 0 var frequency: [Int: Int] = [:] for number in
array {
let complement = targetSum - number if let
complementCount = frequency[complement] {
count += complementCount
}
frequency[number, default: 0] += 1
} return
count
}

let numbers = [1, 5, 7, -1, 5]


let targetSum = 6
let pairCount = countPairsWithSum(numbers, targetSum: targetSum)
print(pairCount) // Output: 3
Mohammed Nazim

Set – 9 Recursion

1. Print Pattern

func printPattern(_ n: Int, currentRow: Int = 1) {


if currentRow > n { return
}
for _ in 1...currentRow {
print("*", terminator: "")
}
print()
printPattern(n, currentRow: currentRow + 1)
} let n = 5
printPattern(n)

2. Tower of Hanoi

func towerOfHanoi(n: Int, from source: String, to destination: String, using auxiliary: String) {
if n == 1 {
print("Move disk 1 from \(source) to \(destination)")
return
}
towerOfHanoi(n: n - 1, from: source, to: auxiliary, using: destination)

print("Move disk \(n) from \(source) to \(destination)")


towerOfHanoi(n: n - 1, from: auxiliary, to: destination, using: source)
}

let n = 3
towerOfHanoi(n: n, from: "A", to: "C", using: "B")
Mohammed Nazim

Set – 11 Linked List Problems

1. Reorder List

class ListNode {
var val: Int var
next: ListNode?
init(_ val: Int) {
self.val = val
self.next = nil
}
}
func reorderList(_ head: ListNode?) {

guard var head = head else { return }


var slow = head var fast = head

while fast.next != nil && fast.next!.next != nil {


slow = slow.next! fast = fast.next!.next!
}

var secondHalf = slow.next


slow.next = nil secondHalf =
reverseList(secondHalf)

var firstHalf = head while let


secondNode = secondHalf { let
temp1 = firstHalf.next let temp2 =
secondNode.next
Mohammed Nazim

firstHalf.next = secondNode
secondHalf = temp2

if temp1 == nil { break }

secondNode.next = temp1
firstHalf = temp1!
}
}

func reverseList(_ head: ListNode?) -> ListNode? {


var prev: ListNode? = nil var current = head
while current != nil { let nextNode =
current!.next current!.next = prev prev =
current current = nextNode
}
return prev
}

func printList(_ head: ListNode?) {


var current = head while current !=
nil { print(current!.val,
terminator: " ") current =
current!.next
}
print() }

let head = ListNode(1) head.next =


ListNode(2) head.next?.next =
ListNode(3) head.next?.next?.next =
ListNode(4) head.next?.next?.next?.next =
ListNode(5)
Mohammed Nazim

print("Original List:")
printList(head) reorderList(head)
print("Reordered List:")
printList(head)

2. reverse a linked list

class ListNode {
var value: Int var
next: ListNode?
init(_ value: Int) {
self.value = value
self.next = nil
}
}

func reverseLinkedList(_ head: ListNode?) -> ListNode? {


var prev: ListNode? = nil var current = head while
current != nil { let next = current?.next
current?.next = prev prev = current
current = next
} return
prev
}

func printList(_ head: ListNode?) { var


current = head while current != nil {
print(current!.value, terminator: " -> ")
current = current?.next
}
print("nil") // End of the list
}
Mohammed Nazim

let node1 = ListNode(1) let


node2 = ListNode(2) let
node3 = ListNode(3) let
node4 = ListNode(4) let
node5 = ListNode(5)

node1.next = node2 node2.next


= node3 node3.next = node4
node4.next = node5
print("Original List:")

printList(node1)
let reversedHead = reverseLinkedList(node1)
print("Reversed List:") printList(reversedHead)
Mohammed Nazim

Set – 14 queue and deque


1. Implement queue using array

struct Queue<T> { private var


elements: [T] = [] mutating func
enqueue(_ element: T) {
elements.append(element)
}
mutating func dequeue() -> T? {
guard !isEmpty() else { return nil }
return elements.removeFirst()
}
func isEmpty() -> Bool {
return elements.isEmpty
}
func front() -> T? {
return elements.first
}
}
var queue = Queue<String>()
queue.enqueue("First") queue.enqueue("Second")

print(queue.front() ?? "Queue is empty") // Output: First print(queue.dequeue() ??


"Queue is empty") // Output: First print(queue.front() ?? "Queue is empty") //
Output: Second

2. circular tour

func circularTour(petrol: [Int], distance: [Int]) -> Int {


let n = petrol.count var totalPetrol = 0 var
Mohammed Nazim

totalDistance = 0 var currentPetrol = 0 var


startIndex = 0 for i in 0..<n { totalPetrol +=
petrol[i] totalDistance += distance[i]
currentPetrol += petrol[i] - distance[i] if
currentPetrol < 0 { startIndex = i + 1
currentPetrol = 0
}
}
return (totalPetrol >= totalDistance) ? startIndex : -1
}
let petrol = [4, 6, 7, 4]
let distance = [6, 5, 3, 5]
let startingPump = circularTour(petrol: petrol, distance: distance)
if startingPump != -1 {
print("The circular tour can be started at petrol pump index: \(startingPump)")
} else {
print("The circular tour cannot be completed.")
}

You might also like