random - Avoiding repetition with arc4random in Swift -


i have following code generate randomly populated grid in swift:

import foundation  var tile = [string](count: 900, repeatedvalue: ".")  // randomly populate grid hashes in 0...400 {     tile[int(arc4random_uniform(899))] = "#" }  // print grid console y in 0...(29) {     x in 0...(29) {         print("\(tile[y * 10 + x])")     }     println("") } 

running code produces grid looks following:

..##..#.#...#..#..#.#.####.#.. ..#..#..#.#.####.#....###.#.#. #.####.#....###.#.#.#####..... ..###.#.#.#####.....#...#....# #####.....#...#....###.##.###. #...#....###.##.###..#.....#.. ##.##.###..#.....#...##..#.##. .#.....#...##..#.##...#.####.. .##..#.##...#.####..###..#.#.# ..#.####..###..#.#.#.#..#..... ###..#.#.#.#..#.........#...## .#..#.........#...##.##....... ....#...##.##............#...# .##............#...####....##. .....#...####....##..#.#.....# ###....##..#.#.....#........#. .#.#.....#........#...#.#..#.. ........#...#.#..#......#....# ..#.#..#......#....#.##.#...## ....#....#.##.#...###...#..#.. .##.#...###...#..#..#.#..#...# #...#..#..#.#..#...#####...##. #.#..#...#####...##..#.......# ####...##..#.......#.#.#.....# .#.......#.#.#.....##......... .#.#.....##..........##.#..#.# #..........##.#..#.##.#.#..... .##.#..#.##.#.#.....##...#.... #.#.#.....##...#......#.##.... ##...#......#.##.....#.######. 

you can see pattern repeating itself. there way "throw" function generation more convincing?

your print function wrong: tile[y*10 + x] should tile[y*30 + x].


as generating grids: what, precisely, want?

if answer "a random choice uniform distribution on space of all possible 30x30 grids, each cell either # or .", should choose each cell equal probability of # , .:

for in 0..<900 {     // arc4random_uniform(2) either 0 or 1, equal probability     tile.append(arc4random_uniform(2) == 0 ? "." : "#") } 

if answer "a random choice uniform distribution on 30x30 grids in exactly 400 cells #", should choose 400 unique indexes front, before converting them #.

as is, code may produce grids 1 # (though unlikely). , will never produce grids more 400 #s.


Comments