mardi 14 juillet 2015

Avoiding repetition with arc4random in Swift

I have the following code to generate a randomly populated grid in Swift:

import Foundation

var tile: [String] = []

// Create an empty 30 x 30 grid
for i in 0...899 {
    tile.append(".")
}

// Randomly populate the grid with hashes
for i in 0...400 {
    tile[Int(arc4random_uniform(899))] = "#"
}

// Print the grid to console
for y in 0...(29) {
    for x in 0...(29) {
        print("\(tile[y * 10 + x])")
    }
    println("")
}

Running this code produces a grid which looks like the following:

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

You can clearly see that a pattern is repeating itself. Is there a way to "throw" function so that the generation is more convincing?




Aucun commentaire:

Enregistrer un commentaire