Swift 3 2d array of Int - arrays

It's actually a very simple question, but after an hour I can not solve my problem.
I need to create a 2d array of Int.
var arr = [[Int]]()
or
var arr : [[Int]] = []
tried to change value :
arr[x][y] = 1
fatal error: Index out of range
Should I use APPEND or I need specify the size of the array?
I'm confused..

It's not simple really. The line:
var arr : [[Int]] = []
Creates a variable of type Array of Array of Int and initially the array is empty. You need to populate this like any other other array in Swift.
Let's step back to a single array:
var row : [Int] = []
You now have an empty array. You can't just do:
row[6] = 10
You first have to add 7 values to the array before you can access the value at index 6 (the 7th value).
With your array of arrays, you need to fill in the outer array with a whole set of inner arrays. And each of those inner arrays need to be filled out with the proper number of values.
Here is one simple way to initialize your array of arrays assuming you want a pre-filled matrix with every value set to 0.
var matrix : [[Int]] = Array(repeating: Array(repeating: 0, count: 10), count: 10)
The outer count represents the number of rows and the inner count represents the number of columns. Adjust each as needed.
Now you can access any cell in the matrix:
matrix[x][y] = 1 // where x and y are from 0 to rows-1/columns-1

Not only you need to initialize both the array and subarrays before being able to assign any values, but also each array length must be greater than the index position you are trying to set.
This is because Swift does neither initialize the subarrays for you, neither increments the array length when assigning to an index.
For instance, the following code will fail:
var a = [Int]()
a[0] = 1
// fatal error: Index out of range
Instead, you can initialize an array with the number of elements you want to hold, filling it with a default value, zero for example:
var a = Array(repeating: 0, count: 100)
a[0] = 1
// a == [1, 0, 0, 0...]
To create an matrix of 100 by 100 initialized to 0 values:
var a = Array(repeating: Array(repeating: 0, count: 100), count: 100)
a[0][0] = 1
If you don't want to specify an initial size for your matrix, you can do it this way:
var a = [[Int]]()
a.append([])
a[0].append(1)

Related

Determine Size of Multidimensional Array in Swift

I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name

iOS : In Swift 3, how to remove the n last rows from a section in a two-dimentional array?

I created a two-dimensional array, and I would like to remove the n last rows from a section.
Example:
var timeTable : [[Int]] = Array(repeating: Array(repeating: 0, count: 50), count: models.count)
for i in (0..<models.count)
{
timeTable[i] = timeTable[i].dropLast(50 - models[i].slots.count) //=> problem: Cannot assign value of type 'ArraySlice<Int>' to type '[Int]'
for j in (0..<models[i].slots.count)
{
print("model:",i, ", slots:", j)
let minutes = models[i].slots[j].endDate.minutes(from: models[i].slots[j].startDate)
print(minutes)
timeTable[i][j] = minutes
}
}
Here is an example of my models :
The values for models[i].slots.count are different, rarely the same.
I want to do that because I have to allocate the place for the rows of the array, I don't know how to allocate it... So I allocate 50 first, and during the loop, I remove the last rows that aren't useful... (If if is possible to allocate first, I should prefer...)
Thanks in advance.
Why not just do this:
var timeTable : [[Int]] = []
for model in models {
let modelArray = Array(repeating: 0, count:model.slots.count)
timeTable.append(modelArray)
}

Is there any way to create dynamic array in scala? Means inserting values at run time?

var arr=Array.ofDim[Int](4,4)
arr(0)(0)(0)(0)=12
this is one way to insert elements in array.
but if i need to initialize size of array dynamically or at run time. How can we do it in scala?
Here
val n = StdIn.readInt
val m = StdIn.readInt
val arr = Array.ofDim[Int](n, m)
arr(5)(15) = 1
println(arr.deep.mkString("\n"))
I created 2-dimensional array with sizes known only in runtime (I entered 10 and 20).
Or maybe you need scala.collection.mutable.ArrayBuffer if you're going to change sizes.
ArrayBuffer[Int] is 1-dimensional, ArrayBuffer[ArrayBuffer[Int]] is 2-dimensional etc.
val arr: ArrayBuffer[ArrayBuffer[Int]] =
ArrayBuffer.fill(10)(ArrayBuffer.fill(20)(0))
arr(5)(15) = 1
println(arr.mkString("\n"))
println
arr(5) += 1
arr += ArrayBuffer.fill[Int](25)(0)
println(arr.mkString("\n"))

How to obtain three arrays containing three objects or less?

I want to obtain three arrays containing three objects or less. I have a class named Product and an array who have 9 products or less downloaded form Firebase, so I want to generate three arrays, each one will have three different products in order. This is what I have:
var products = [Product]()
products = [product1, product2, product3, product4, product5, product6, product7, product8, product9]
And this is what I want to obtain:
array1 = [product1, product2, product3]
array2 = [product4, product5, product6]
array3 = [product7, product8, product9]
In some cases the array named product will have a number of products less than 9 so I have to create those arrays automatically with 3 or less products.
I'm doing this because my code have to generate an array that has three arrays inside, each one with three products or less to show in a collection view inside a tableview [[Product]].
You can slice an array by using the [] operator with a range. Note that this returns a view into the original array, so if you want a copy you pass the slice to Array() to create a new copy:
let numbers:[Int] = stride(from: 1, to: 10, by: 1).map{$0}
print(numbers.count)
let first = Array(numbers[0...2])
let second = Array(numbers[3...5])
let third = Array(numbers[6...8])
print(first, second, third)
To convert an array of arbitrary length into a number of arrays with 3 elements or less:
let numbers:[Int] = stride(from: 1, to: 14, by: 1).map{$0}
var bins: [[Int]] = []
for index in stride(from: 0, to: numbers.count, by: 3) {
let endIndex = min(index + 2, numbers.count - 1)
bins.append(Array(numbers[index...endIndex]))
}
print(bins)
Gustavo expects the extra variables to contain empty arrays when there are fewer than 6 or 3 products.
this should do it:
let productsBy3 = (0..<3).map{ i in products.indices.filter{$0/3==i}.map{products[$0]}}

Is there a way to instantly generate an array filled with a range of values in Swift?

In python I could generate an array of values
Example:
arr = range(0,30)
Is there a way to instantly generate an array filled with a range of values in Swift?
You can create an array with a range like this:
var values = Array(0...100)
This give you an array of [0, ..., 100]
You can create a range and map it into an array:
var array = (0...30).map { $0 }
The map closure simply returns the range element, resulting in an array whose elements are all integers included in the range. Of course it's possible to generate different element and types, such as:
var array = (0...30).map { "Index\($0)" }
which generates an array of strings Index0, Index1, etc.
You can use this to create array that contains same value
let array = Array(repeating: 5, count: 10)
Or if you want to create an array from range you can do it like this
let array = [Int](1...10)
In this case you will get an array that contains Int values from 1 to 10
create an Int array from 0 to N-1
var arr = [Int](0..<N)
create a Float array from 0 to N-1
var arr = (0..<N).map{ Float($0) }
create a float array from 0 to 2π including 2π step 0.1
var arr:[Float] = stride(from: 0.0, to: .pi * 2 + 0.1, by: 0.1).map{$0}
or
var arr:[Float] = Array(stride(from: 0.0, to: .pi * 2 + 0.1, by: 0.1))

Resources