Skip to content

alexpaul/Array

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 

Repository files navigation

Array

Array Initialization

let genericArraySyntax: Array<String> = ["Alex", "John", "Steve", "Wozniak"]
let arrayLiteral = [1, 2, 3, 4, 5]
var emptyArray = [Int]()

var bucketsArray = Array(repeating: [Int](), count: 4)
print(bucketsArray) // [[], [], [], []]

Adding and Removing

var jobsApplied = ["Apple", "Peloton", "Google", "Box", "Zoom", "Bloomberg"]

var companiesToApply = ["Houzz", "ZocDoc", "Stockpile"]

Insert

jobsApplied.insert("Zwift", at: 1) // ["Apple", "Zwift", "Peloton", "Google", "Box", "Zoom", "Bloomberg"]

Append

We can append a single element or we can append a sequence e.g companiesToApply

jobsApplied.append(contentsOf: companiesToApply) // ["Apple", "Zwift", "Peloton", "Google", "Box", "Zoom", "Bloomberg", "Houzz", "ZocDoc", "Stockpile"]

Remove

jobsApplied.removeLast() // removes the last element - THIS WILL CRASH IF THE ARRAY IS EMPTY - PROCEED WITH CAUTION
jobsApplied.popLast() // safer as it returns an optional so will safely work on an empty array

Search

firstIndex(of:_)

let names = ["Bob", "Sally", "John", "Heather"]

if let index = names.firstIndex(of: "Bob") { // O(n) runtime operation
  print("found name at index \(index)") // found name at index 0
}

contains()

if names.contains("John") {
  print("Hi John Appleseed.") // Hi John Appleseed.
}

min()

let numbers = [-5, 1, 6, 0, 12, -9, 23, 9]

if let minNumber = numbers.min() {
  print("min number is \(minNumber)") // min number is -9
}

max()

let numbers = [-5, 1, 6, 0, 12, -9, 23, 9]

if let maxNumber = numbers.max() {
  print("max number is \(maxNumber)") // max number is 23
}

Accessing Elements

let fruits = ["apple", "banana", "oranges", "kiwi"]

first element

if let first = fruits.first {
  print("The first fruit is \(first)") // The first fruit is apple
}

last element

if let last = fruits.last {
  print("The last fruit is \(last)") // The last fruit is kiwi
}

randomElement

if let randomFruit = fruits.randomElement() {
  print("Randomly picking \(randomFruit)") // Randomly picking banana
}

Selecting Elements

prefix(Int)

let cohorts = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

let firstThreeCorts = cohorts.prefix(3)

print(firstThreeCorts) // [1.0, 2.0, 3.0]

suffix(Int)

let cohorts = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

let cohortStarted = cohorts.suffix(4)

print(cohortStarted) // [4.0, 5.0, 6.0, 7.0]

Heterogeneous Array

let arr: [Any] = [1, 2, 3.3, 4.3, 5.3, 6.3, "7.0"] // Heterogeneous collection must have an explicit type [Any]

for element in arr {
  if let char = element as? Character {
    print("\(char) is a Character")
  }
  if let int = element as? Int {
    print("\(int) is an Int")
  }
  if let double = element as? Double {
    print("\(double) is a Double")
  }
  if let string = element as? String,
     let stringValue = Double(string) {
    print("\(stringValue) is a Double")
  }
}

Stride

let names = ["Beth", "Josh", "Nancy", "Quincy", "Mary"]

for index in stride(from: 0, through: names.count - 1, by: 1) {
  print(names[index])
}

/*
 Beth
 Josh
 Nancy
 Quincy
 Mary
*/

Reordering an Array's elements

swapAt(Int, Int)

var priorityList = ["Applying to jobs", "DSA", "Learning Advance Topics", "Independent Project", "Networking"]

priorityList.swapAt(0, priorityList.count - 1)

print(priorityList) // ["Networking", "DSA", "Learning Advance Topics", "Independent Project", "Applying to jobs"]

shuffle()

var lunchOptions = ["salad", "pasta", "tacos", "fish and chips", "veggie burger"]

lunchOptions.shuffle() // shuffles array in-place

print(lunchOptions) // ["salad", "pasta", "veggie burger", "fish and chips", "tacos"]

sort()

lunchOptions.sort() // sorts in-place

print(lunchOptions) // ["fish and chips", "pasta", "salad", "tacos", "veggie burger"]

partition(by: (Element) -> Bool) -> Int

var ages = [7, 1, 34, 2, 23, 2, 4, 90, 34, 10]

let partitionIndex = ages.partition { $0 > 10 }

print(partitionIndex) // 6

print(ages) // [7, 1, 10, 2, 4, 2, 23, 90, 34, 34]

let ages10AndLess = ages[..<partitionIndex]
let agesOlderThan10 = ages[partitionIndex...]

print(ages10AndLess) // [7, 1, 10, 2, 4, 2]
print(agesOlderThan10) // [23, 90, 34, 34]

(2D Array, matrix or grid) Case Study

Given the following Tic Tac Toe board below.

let ticTacToe = [["X", "O", "O"],
                 ["X", "O", "X"],
                 ["X", "X", "O"]]

Perform the following operations:

Print the rows of the tic tac toe board

Solution
for row in 0..<ticTacToe.count {
  print(ticTacToe[row])
}

/*
 ["X", "O", "O"]
 ["X", "O", "X"]
 ["X", "X", "O"]
*/

Print all the individual values of the tic tac toe board

Solution
for row in 0..<ticTacToe.count {
  for col in 0..<ticTacToe.count {
    print(ticTacToe[row][col], terminator: " ")
  }
}
// X O O X O X X X O

Print the columns of the tic tac toe board

/*
 ["X", "O", "O"]
 ["X", "O", "X"]
 ["X", "X", "O"]
*/

/*
 [0,0]  [0,1]  [0,2]
 [1,0]  [1,1]  [1,2]
 [2,0]  [2,1]  [2,2]
*/
Solution
var colIndex = 0
for col in colIndex..<ticTacToe.count { // 0, 1, 2
  for row in 0..<ticTacToe.count { // 0, 1, 2
    print("\(ticTacToe[row][col])")
  }
  print()
}

/*
 X
 X
 X

 O
 O
 X

 O
 X
 O
*/

Print the diagonals of the tic tac toe board

/*
 ["X", "O", "O"]
 ["X", "O", "X"]
 ["X", "X", "O"]
*/

/*
 [0,0]  [0,1]  [0,2]
 [1,0]  [1,1]  [1,2]
 [2,0]  [2,1]  [2,2]
 
 
 [0,0]  [1,1]  [2,2] - leftTop -> rightBottom
 [2,0]  [1,1]  [0,2] - leftBottom -> rightTop
*/
Solution
// [0,0]  [1,1]  [2,2] - leftTop -> rightBottom
for i in 0..<ticTacToe.count {
  print(ticTacToe[i][i])
}
// X O O


// [2,0]  [1,1]  [0,2] - leftBottom -> rightTop
for i in 0..<ticTacToe.count {
  print(ticTacToe[ticTacToe.count - 1 - i][i]) // 2, 1, 0
}
// X O O

Challenges

Challenge 1

Constraints: do the problem below withou using built-in reverse()

HackerRank - Reverse Array

Challenge 2

HackerRank - Hour Glass

Challenge 3

LeetCode - Valid Tic Tac Toe State

Resources

  1. Apple documentation - Array
  2. Swift Programming Language - Collection Types
  3. LeetCode - Array

Releases

No releases published

Packages

No packages published