How to set array starting and end indices in swift? - arrays

I tried to create an array from 1-100 elements create in playground, but while i'm trying to print it doesn't print the values in the array.
code:
var ab:Array = [1...100]
for i in ab {
print(i)
}
output:
But in the playground it didn't shown any error.
Did i do anything wrong?
Thanks

You create an array of Range<Int> elements (a single one, 1..<101)
var ab: Array = [1...100] // element TYPE inferred from 1...100
// to be Range<Int>
print(ab.dynamicType)
// Array<Range<Int>>
But I assume you're attempting to create an array of 100 Int elements.
var ab = Array(1...100) // Array with elements intialized to Int,
// using Range<Int> to intialize
for i in ab {
print(i)
} // 1 2 3 ... 100
If you're only looking to print the numbers in the range 1...100, you needn't necessarily create an array if integers to do so (or an array at all). Instead, you could use a single Range<Int> variable and loop over the elements contained in this range. E.g.
let myRange = 1...5 // inferred as type Range<Int>
for i in myRange {
print(i) // the type of 'i' is Int, the same as in
// the array case above.
} // 1 2 3 4 5

Use clear and effective ;
var ab = Array(1...100)
for i in ab {
print(i)
}
Output
1 2 3.... 100

Related

Swift enums as index to an array

How can I do a simple index into an array using enums in Swift?
I am a C programmer trying to understand Swift. This is perplexing.
var arr: [String] = ["2.16", "4.3", "0.101"]
enum Ptr: Int {
case first = 0
case second = 1
case third = 2
}
var ix = Int(Ptr.first)
print (ix)
let e = Double (arr[ix])
`
I would expect that Ptr.first would yield a 0 integer which I could as an index into array arr.
Why it doesn't work is because all cases in your enum (first, second, third) are essentially of type Ptr (the type of your enum). So in order to get 0 you need to access the case's rawValue property which is an Int:
var ix = Ptr.first.rawValue //accessing the case's rawValue property
print (ix)
let e = Double (arr[ix])
Hope that helps!

Can't make a slice of a column of a 2d array "cannot use Sudoku[0:9][0] (type [9]int) as type []int in assignment"

I'm making a simple game of sudoku using slices of a 9x9 2d array. I'm still starting out with Golang and have some C++ experience. I keep getting the error message "cannot use Sudoku[0:9][0] (type [9]int) as type []int in assignment".
var row1 []int = Sudoku[0][0:9]
This line correctly took the values of the first row of the 2d array and placed them into the row1 slice, but using var col1 []int = Sudoku[0:9][0] results in the error message above. What can I do? Thanks in advance!
For example,
package main
import "fmt"
func main() {
var Sudoku [9][9]int
fmt.Println(Sudoku)
var row1 []int = Sudoku[0][0:9]
fmt.Println(row1)
var col1 []int = Sudoku[0:9][0]
fmt.Println(col1)
}
Playground: https://play.golang.org/p/Jk6sqqXR5VE
10:6: cannot use Sudoku[0:9][0] (type [9]int) as type []int in assignment
TLDR: In Go, array and slice are not exactly the same. You can't assign a slice variable to an array value.
Details:
We start with Sudoku [9][9]int variable is an array.
The valid line var row1 []int = Sudoku[0][0:9]:
Sudoku[0] returns the element at index 0 of Sudoku, which is an array [9]int. Let's say we call this temporary result temp
Then temp[0:9]returns a slice of elements between index 0 and 9 (exclusive) in temp. That's why you can assign that to a slice variable row1
Now the trouble line var col1 []int = Sudoku[0:9][0]. Based on the naming, I guess your intention is to return the first column from Sudoku array
? Unfortunately, this is what happens:
Sudoku[0:9] returns the slice of elements between index 0 and 9 (exclusive) of Sudoku. Because each element in Sudoku is an array, this temp value actually holds all the rows from Sudoku and of type [][9]int.
Now temp[0]returns the first element of temp, which actually is just the first row of Sudoku and of type array [9]int. Thus, Go will complain when you try to assign it to a variable of type []int (a slice)
So if Sudoku is a matrix of
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
...
9 9 9 9 9 9 9 9 9
Even if Go does not complain about typing, the returned value will be [1 1 1 1 1 1 1 1 1] and not [1 2 3 4 5 6 7 8 9]
var col1 []int = Sudoku[0:9][0] gets you an array, not a slice. You could either declare as var col1 [9]int = Sudoku[0:9][0] (or better: col1 := Sudoku[0:9][0]), or if you really want a slice: var col1Slice []int = col1[:] after getting col1.
In general, things would be much easier if your sudoku structure were a 2D slice instead of 2D array, then you'd be dealing with only slices.
Working example of all of these:
https://play.golang.org/p/LE8qwFSy1m_e

Swift 3 2d array of Int

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)

Adding an element of an array with respective element of other arrays

I have multiple array, number can be arbitrary. but the size of all array is same. How do i add each element of with respective element of all the arrays and maybe save it in another array
A1 = [1 2 3 4 5 6]
A2 = [1 2 3 4 5 6]
.
.
.
.
final = [1+1+1+... 2+2+2+.... 3+3+3+3.... 4+4+4.... 5+5+5+5... 6+6+6+6...]
As your arrays are all the same length you can just add the arrays forming a new array.
final = A1+A2
This function searches in your workspace looking for all variables containing capital 'A'. The for loop adds all found variables. If there are other variables containing 'A', other restrictions has to be made.
variables = who %# all variable names from workspace
index = strmatch('A',variables) %# indices matching "A"
newarray = 0
for j = 1:numel(index)
tmp = eval(char(variables(index(j)))); %# store variable in tmp
newarray = newarray + tmp; %# sum
end
If you have an unknown number of A's, you can try something like this:
final = 0
i = 1
while exist(['A' num2str(i)]) == 1 % ['A' num2str(i)] constructs the variable name, eval calls it
final = final + eval(['A' num2str(i)]);
i = i + 1;
end
This should work as long as the variables are stored in the workspace, are of the same length and are named A1, A2, A3, ... A9, A10, ...
Let's say you have this structure (as you write in the comments):
main = struct('err',{1:6,5:10,1:6,1:6},'seg_err',{1:6,5:10,1:6,5:10});
you can convert it to matrix:
m = vertcat(main.seg_err);;
And than take the sum in a simple command:
final = sum(m)
which results:
final =
12 16 20 24 28 32
and thanks to #beaker :)

swift getting an array from something like array[0..<10]

I want to get a range of objects from an array. Something like this:
var array = [1,3,9,6,3,4,7,4,9]
var newArray = array[1...3] //[3,9,6]
The above would access elements from index 1 to 3.
Also this:
newArray = array[1,5,3] // [3,4,6] would be cool
This would retrieve elements from index 1, 5 and 3 respectively.
That last example can be achieved using PermutationGenerator:
let array = [1,3,9,6,3,4,7,4,9]
let perms = PermutationGenerator(elements: array, indices: [1,5,3])
// perms is now a sequence of the values in array at indices 1, 5 and 3:
for x in perms {
// iterate over x = 3, 4 and 6
}
If you really need an array (just the sequence may be enough for your purposes) you can pass it into Array's init method that takes a sequence:
let newArray = Array(perms)
// newArray is now [3, 4, 6]
For your first example - with arrays, that will work as-is. But it looks from your comments like you're trying it with strings as well. Strings in Swift are not random-access (for reasons relating to unicode). So you can't use integers, they have an String-specific bidirectional index type:
let s = "Hello, I must be going"
if let i = find(s, "I") {
// prints "I must be going"
println(s[i..<s.endIndex])
}
This works :
var n = 4
var newArray = array[0..<n]
In any case in
Slicing Arrays in Swift you'll find a very nice sample of the Python slice using a extension to Arrays in Swift.

Resources