I have an array of arrays called Lines
Numbers = [[1,2,3],[4,5,6],[7,8,9]]
and var numberInt = 10
how do i append this numberInt inside the last array of the multidimensional array? so it would look like
Numbers = [[1,2,3],[4,5,6],[7,8,9,10]]
Thank you.
Use Numbers[Numbers.count - 1] to get last one-dimensional array and append method to add item:
Numbers[Numbers.count - 1].append(numberInt)
print(Numbers) // prints "[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]"
I'd also recommend you to take a look at this answer: https://stackoverflow.com/a/25128237/1796907
Related
I having two Arrays.
Index values Array1 = [1,2,3,4]
totalarray = [100,20,40,50,76,88,90,76,55,43,32,12,345]
How do I find Array1 index values in totalarray.
Assuming you want to find the indexes where each element of Array1 appears in totalarray, you can use a map statement:
let Array1 = [1,2,3,4]
let totalarray = [100,20,40,50,76,88,90,76,55,43,32,12,345]
let indexes = Array1.map { totalarray.firstIndex(of: $0) }
print(indexes)
Note that none of the values in Array1 appear in totalArray, so the above code will put an array of 4 nulls into indexes, so the output will be [nil, nil, nil, nil]
If you used the sample data from Sanzio Angeli's answer:
let Array1 = [7, 6, 4, 8]
let totalarray = [20, 30, 6, 7, 10, 40]
The output would be:
[Optional(3), Optional(2), nil, nil]
The other way to interpret your question is that you want to treat every value in Array1 as an index into totalarray, and want to build an array of the elements at those indexes in totalarray. As mentioned in Sulthan's comment, that could would look like this:
let Array1 = [1,2,3,4]
let totalarray = [100,20,40,50,76,88,90,76,55,43,32,12,345]
let indexes = Array1.map { totalarray[$0] }
print(indexes)
And would print the output [20, 40, 50, 76]. However that code would crash if any of the values in Array1 were larger than totalarray.count - 1. It really needs range checking.
I want to change subscript coordinates in an Array of Arrays [[Int]] in order to be able to address each value in a way similar to a spreadsheet, so assigning values, formulas across cells, etc.
Currently to address each value I need to subscript like table[2][1] = 12 or similar. I would like to subscript like a spreadsheet table[a][2] = 12, so that I can adapt long and complicated formulas in bigger speadsheets to similar tables using the same system used in spreadsheets.
The question is: how to change the subscript system in an efficient way? I send a simplified example to ilustrate the point
class ViewController: UIViewController {
var table = [[0, 1, 2, 3],
[1, 32, 44, 25],
[2, 12, 66, 43],
[3, 3, 4, 5]]
override func viewDidLoad() {
super.viewDidLoad()
print(table[2][1]) // 12
table[1][1] = 100
table[3][3] = table[1][1] * table[3][1] * 10
print(table[3][3])
printArray(table: table, j: 3)
}
// MARK: - Function
func printArray(table: [[Int]], j:Int) {
for i in 0...j {
print(table[i])
}
}
}
The closest solution I found is to use enums, like here:
enum Column:Int {
case a
case b
case c
// and so on
}
extension Array {
subscript(col:Column) -> Element {
get {
return self[col.rawValue]
}
set(newValue) {
self[col.rawValue] = newValue
}
}
}
var table = [[0, 1, 2, 3],
[1, 32, 44, 25],
[2, 12, 66, 43],
[3, 3, 4, 5]]
table[.a][2] = 12
let val = table[.a][2]
print (val)
Nevertheless, there are two little drawbacks:
you first have hard-code all the "column" letters you want to access to the Column enum.
then, something like table[5][.c] and table[.a][.b] will also be allowed - so you could access the rows via letter, not only the columns
I'm trying to create 2D array of Integers:
var arr: [[Int]] = []
arr[0][0] = [123, 456, 789]
But I'm getting the following error in the second line:
error: contextual type 'Int' cannot be used with array literal
arr[0][0] = [123, 456, 789]
Any of you knows how can I add the int values to the 2D array with no errors?
I want to add the following values in the 2D array:
[123, 456, 789]
[2, 3, 5]
[100, 300, 400]
I'll really appreciate your help.
arr[0][0] is a single Int, but you're trying to assign [123, 456, 789] to it, which is an [Int] (a.k.a. Array<Int>).
You can nest Array literals to achieve what you want:
let array = [ //inferred type: [[Int]]
[123, 456, 789],
[ 2, 3, 5],
[100, 300, 400],
]
I want to add the following values in the 2D array:
[123, 456, 789]
[2, 3, 5]
[100, 300, 400]
You could achieve this in a few different manners.
Simply include the sub-arrays at array initialization
var arr = [[123, 456, 789], [2, 3, 5], [100, 300, 400]]
This allows you to let arr be an immutable (let arr = ...), in case all the sub-arrays are known at compile time, and you know you wont need to mutate arr at a later time.
In case the content of your array is not fully known at compile time: you could use append(...) to add sub-arrays one by one when available
In case the sub-arrays are not available at the time of arr instantiation, you could use the += operator for arrays, or the append(_:) method, to dynamically add sub-arrays to array when they are provided
var arr = [[Int]]()
// ... at some later (run-)time point
let somSubArrProvidedAtRuntime = [100, 300, 400]
arr.append(somSubArrProvidedAtRuntime)
// ....
As an alternative to append(_:), add a number of sub-arrays at once using append(contentsOf:)
Given the same case above, but where a number of sub-arrays are provided at once, you could use the append(contentsOf:) method to append several sub-arrays to the array at once
// some (one) sub-arr known at initialization
var arr = [[123, 456, 789]]
// some sub-arrays provided at runtime, a time later
// than initialization
let subArrB = [2, 3, 5]
let subArrC = [100, 300, 400]
// ... using the `+=` operator for arrays
arr += [subArrB, subArrC]
// ... alternatively, using append(contentsOf:)
arr.append(contentsOf: [subArrB, subArrC])
I have an Array which I have defined
var array: [Int] = Array(1...24)
I then add
array.insert(9999, atIndex: 0)
I would like to do something like
var array: [Int] = Array(9999...9999,1...24)
Is this possible ?
You could simply concatenate the arrays created from each range:
let array = Array(10 ... 14) + Array(1 ... 24)
Alternatively:
let array = [10 ... 14, 1 ... 4].flatMap { $0 }
which has the small advantage of not creating intermediate arrays
(as you can see in the open source implementation https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb).
As MartinR mentioned, you could simply concenate arrays using the + operator; and if this method is an answer for you, than this thread is a duplicate (see MartinR:s link), and should be closed.
If you explicitly wants to initialize an Int array using several ranges at once (see e.g. hola:s answer regarding array of ranges), you can make use of reduce as follows
let arr = [1...5, 11...15].reduce([]) { $0.0 + Array($0.1) }
Or, alternatively, flatten
var arr = Array([1...5, 11...15].flatten())
Both the above yields the following result
print(arr.dynamicType) // Array<Int>
print(arr) // [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
For an array of ranges you define the array as
let array: [Range<Int>] = [0...1, 5...100]
and so on and so forth.
I have an basic Int array
Array = [8, 9, 8]
How do i sum all of its values progressively so that the end result would look like this
EndResult = [8, 17, 25]
Tried using for and while loops, but to no avail.
NB: Basic array[0] + array[1] advices will not work. I'm looking for something automatic like a loop solution.
Looking forward to your advices.
Thanks!
May be this:
var arr = [8, 9, 8]
for i in 1..<arr.count {
arr[i] += arr[i-1]
}
print(arr)
Probably there are better ways than this one, but it works
var array = [8, 9, 8]
var result = [Int]()
for i in 0..<array.count{
var temp = 0;
for j in 0...i{
temp+=array[j]
}
result.append(temp)
}
print(result) //[8, 17, 25]
You could use a reduce function in Swift to accomplish this. Note that you can't really do it with map, because you would need to know what the previous call to the map function returned, keep state in a variable outside the map function (which seems dirty), or loop over your array for every map function call.
let array = [8, 9, 8]
let results = array.reduce((0, []), combine: { (reduction: (lastValue: Int, values: Array<Int>), value: Int) in
let newValue = reduction.lastValue + value
return (newValue, reduction.values + [newValue])
}).1