Make zeros to certain rows in 2D array [duplicate] - swift

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

Swift Index and it's implementation

I'm new to programming. I was trying to understand how indices work in swift. This is the following code from swift documents.
converted into function.
func ind(){
var c = [10, 20, 30, 40, 50] //index = [0:5]
var i = c.startIndex //i = [0]
while i != c.endIndex { // i!= [5] , while i not equal to [5]
c[i] /= 5
i = c.index(after: i)
}
print(c) // [2,4,6,8,10]
}
the code line i = c.index(after: i) doesn't seems to make sense to me. "after" means the character of string after the string.index, but because we initialized the 'i' to be zero(0) the output should stay [4 and onwards]. secondly, if i replace the i let's say with integer 2. the loop keeps repeating itself. why? Thank you in advance for your time
after means the next element on your list in this context.
An index is more general and is not limited to String.
In addition, an index can have different types depending on the structure that you are manipulating.
For instance:
var c1 = [10, 20, 30, 40, 50] //
var i1 = c1.startIndex
// Print: Int
print(type(of: i1))
var c2 = "Hello" //
var i2 = c2.startIndex
// Print: Index
print(type(of: i2))
You can even create your own index for a specific type, as long as you provide a way to compute the next index.
Thus, in your code for this particular example, the index is of type Int.
If you change the value of i to be the constant 2, you can never equal the value of the end index (which is 5 here).
Then, your loop will never end.

how do I get the index from this function

this is demo of iOS Charts library (LineChart) and I want to input my data instead of arc4random data.
My data is in Array so I have to approach with index but I can't understand the (0..<count).map { (i) -> ChartDataEntry code.
func setChartValues(_ count : Int = 24) {
let values = (0..<count).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(UInt32(count))+3)
return ChartDataEntry(x: Double(i), y: val)
}
let set1 = LineChartDataSet(entries: values , label : "DataSet 1")
let data = LineChartData(dataSet: set1)
self.lineChartView.data = data
}
It seems you are new to iOS and swift. What you are looking for is an understanding of the functionning of closures in swift, plus the map function which is called an high order function
from apple doc ( https://developer.apple.com/documentation/swift/array/3017522-map ) :
Returns an array containing the results of mapping the given closure over the sequence’s elements.
In other words it maps your array into another array, according to the trailing closure you passed as a parameter.
In your specific case here his how to read it :
(0..<count) : creates an array of count lengh
example : if count = 4 then (0..<count) is [0, 1, 2, 3]
As said previously the map function will transform each of your element into another ( therefore keeping the length of the array ).
in your case val = Double(arc4random_uniform(UInt32(count))+3) will be equal to a random number calculated with count value, and create a new ChartDataEntry with this random value.
to sum it up the whole code is just saying "I will create a count length array of random ChartDataEntry", I guess as a mockup
I suggest you to read about closures here :
https://medium.com/the-andela-way/closures-in-swift-8aef8abc9474
and high order functions ( such as map(_:) ) here :
https://medium.com/#abhimuralidharan/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8
let values = (0.. ChartDataEntry in
let val = Double(arc4random_uniform(UInt32(count))+3)
return ChartDataEntry(x: Double(i), y: val)
}
The value mapped and return is you can say a hash function. (arc4random).
It index you are taking is just setting X axis of the chart like 0 , 1 ,2 etc...
and your graph Y it set according to the functions return (arc4random)

Swift: Can not access/set an empty array's first item by subscript [duplicate]

This question already has answers here:
Arrays and Swift
(3 answers)
Closed 5 years ago.
Why can not access/set an empty array's first item by subscript?
eg:
var array: [Int] = []
array[0] = 1 //fatal error: Index out of range
By var array: [Int] = [] you create empty array, so it doesn't have values with index 0.
To fix that you can append to the array like:
array.append(1)
print(array[0]) // 1
or set the array of values to your empty array:
array = [1] // another way to do that: "array += [1]"
print(array[0]) // 1
or predefine array filled with any values (0 for example):
let n = 10
array = Array(repeating: 0, count: 10)
array[0] = 0
The index is out of range because there are no elements in the array, so there is no index 0. To add an element to an array, you have to do
array.append(1)
After the above line, you can set the first element:
array[0] = 2
because there is an element in the array now.
Only use the subscript when you are sure that the index exists in the array.
Try,
array.append(1)
or
array.insert(1, at: 0)
or
array = [1]
Empty array initialization is fine. Than if you want to acces/set first item you just have to make:
array.append(1)
and it will be stored at index 0 at first and you can access it easily: array[0] - but that access is just to read not to add. To add value you have to make 'append'. But if array is not empty than you can CHANGE that value by making:
array[0] = 7
However if you still want to add value at specified index, you could use:
array.insert(1, at: 0) //value at index

Swift 3d Array creating

I want to create an array that is 3d. Array will be 5*5*infinite (the last or the innermost array will probably has like 3-5 object of type String).
I tried something like this:
var array3D = [[[String]]]()
and tried to add new string like this
array3D[ii][yy] += y.components(separatedBy: ";")
But had problems adding new arrays or strings to that. And got error of exc bad instruction
In school I have 5 lessons per day. So in week there is 25 lessons, and I want to make an iPhone app that represent my timetable.
A multidimensional array is just an array of arrays. When you say
var array3D = [[[String]]]()
What you've created is one empty array, which expects the values you add to it to be of type [[String]]. But those inner arrays don't exist yet (much less the inner inner arrays inside them). You can't assign to array3D[ii] because ii is beyond the bounds of your empty array, you can't assign to array3D[ii][yy] because array3D[ii] doesn't exist, and you can't append to an array in array3D[ii][yy] because array3D[ii][yy] doesn't exist.
Because your outer and middle levels of array are fixed in size (5 by 5 by n), you could easily create them using Array.init(count:repeatedValue:):
let array3D = [[[String]]](count: 5, repeatedValue:
[[String]](count: 5, repeatedValue: []))
(Here the innermost arrays are empty, since it appears you plan to always fill the by appending.)
However, it also looks like your use case expects a rather sparse data structure. Why create all those arrays if most of them will be empty? You might be better served by a data structure that lets you decouple the way you index elements from the way they're stored.
For example, you could use a Dictionary where each key is some value that expresses a (day, lesson, index) combination. That way the (day, lesson, index) combinations that don't have anything don't need to be accounted for. You can even wrap a nice abstraction around your encoding of combos into keys by defining your own type and giving it a subscript operator (as alluded to in appzYourLife's answer).
I slightly modified the Matrix struct provided by The Swift Programming Language
struct Matrix<ElementType> {
let rows: Int, columns: Int
var grid: [[ElementType]]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: [])
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> [ElementType] {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
Usage
Now you can write
var data = Matrix<String>(rows: 5, columns: 5)
data[0, 0] = ["Hello", "World"]
data[0, 0][0] // Hello

Not able to print values of array in swift

I am not able to print array values in swift. My code is:
var array = 1...10
println(array)
The result is:
VSs5Range (has 2 children)
But when I try to print the following array, it works:
var array = [1,2,3,4,5,6,7,8,9,10]
println(array)
Result is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Why isn't the first one printing correctly?
The expression 1...10 returns a Range, not an Array. Internally, a Range stores two values (a start and an end); an Array, on he other hand, is a dynamic structure containing "n" values.
As explained,
var array = 1...10
array, in this case, is a Range object, not an array
If you want to print its content do this (changed the name to something more suitable)
var range = 1...10
for value in range
{
println(value)
}