21
loading...
This website collects cookies to deliver better user experience
map
through one and transform values. let lonesomeDoveCharacters = ["Gus", "Woodrow", "Deets"]
lonesomeDoveCharacters.append("Jake")
for-in
loop...for character in lonesomeDoveCharacters {
print("Character name: \(character)")
}
[
["Gus", "Woodrow", "Deets"],
["Jake", "Laurie", "Newt"],
["July", "Roscoe", "Clara"]
]
|15 - 17|
which would be 2
.let twoD = [[1,2,3], [4,5,6], [9,8,9]]
0
in twoD
is the array [1, 2, 3]
. Let's call this subArray1
. 1
in twoD
is the array [4, 5, 6]
Let's call this subArray2
.2
in twoD
is the array [9, 8, 9]
Let's call this subArray3
. twoD
array is also the index of the value I need inside each object (subArray).for-in
loop would give me access to the objects (subArrays) as well as the index value of each object (subArray). So I could write something like this:func diagonalDifference(from arr: [[Int]]) -> Int {
var frontWardsSum = 0
for (index, subArray) in arr.enumerated() {
frontWardsSum += subArray[index]
}
return frontWardsSum
}
func diagonalDifference(from arr: [[Int]]) -> Int {
// to obtain frontwards diagonal value
var frontwardsSum = 0
for (index, subArray) in arr.enumerated() {
frontWardsSum += subArray[index]
}
// to obtain backwards diagonal value
var backwardsSum = 0
for (index, subArray) in arr.enumerated() {
let endPosition = subArray.count - 1
backwardsSum += subArray[endPosition - index]
}
let absoluteValue = abs(frontwardsSum - backwardsSum)
return absoluteValue
}
endPosition
had to be reduced by 1 on account of arrays being zero-based indexing, so if the array has three objects (as these do), those positions are 0
, 1
, and 2
rather than 1
, 2
, and 3
. twoD
array so endPosition
minus 0
is still endPosition
. As I work to the next object, it's position is 1
and the object value I need is endPosition
minus 1
and so on. abs(_:)
function.func diagonalDifference(from arr: [[Int]]) -> Int {
var frontwardsSum = 0
var backwardsSum = 0
for (index, subArray) in arr.enumerated() {
// to obtain frontwards diagonal value
frontWardsSum += subArray[index]
// to obtain backwards diagonal value
let endPosition = subArray.count - 1
backwardsSum += subArray[endPosition - index]
}
let absDifference = abs(frontwardsSum - backwardsSum)
return absDifference
}