L
L
Lici2015-03-16 22:03:17
Objective-C
Lici, 2015-03-16 22:03:17

Swift: how to access a random element of a two-dimensional array?

I set an array of arrays (2D array):
var multArray = Array<Array<String>>()
I carried out the procedure of its "initialization" that was not completely clear to me, without which an error is generated:

for i in 0..<firstBlockStruct.count {
            multArray.append(Array(count:0, repeatedValue:String()))
        }

It stores words and phrases. Now I need to pick a random phrase like:
multArray[i][j], where j is a number from 0 to a number equal to the number of elements in the array.
I tried like this:
multArray[i][Int(arc4random_uniform(UInt8(multArray[i].count)))]

multArray[i][Int(arc4random_uniform(multArray[i].count))]

multArray[i][Int(random(multArray[i].count))]

multArray[i][random(multArray[i].count)]

In all these cases, some quibbles in the style of "This is an Int and it will not turn into UInt32" or "This is a string, not an Int" and I can not overcome them. At the same time, if you insert just the number zero as the content of the second brackets, then everything is OK, but the first character is taken:
multArray[i][Int(arc4random_uniform(0))]
So how is it correct to feed the parameter of the number of elements in the second dimension as an argument to the randomizer? (and am I using the same randomizer?)
(or maybe I created an array of arrays in vain and here you can somehow do pascal-style array[1..10][1..10][1..10] ?)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gressmc, 2015-03-17
@Lici

// Playground - noun: a place where people can play
import UIKit
var multArray:
multArray = Array(count:10, repeatedValue:Array(count:10, repeatedValue:"What"))
// Got 2- x dimensional array "matrix" 10x10
for i in 0..<10 {
let j = multArray[i].count
println(multArray[i][Int(arc4random_uniform(UInt32(j-1)))])
}

P
Pavel Litvinenko, 2015-03-16
@gerasim13

Try this.
multArray[i][Int(arc4random_uniform(0))%multArray[i].count]
So?
UInt32 count = multArray[i].count;
multArray[i][Int(arc4random_uniform(count))]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question