Difference between revisions of "Code Snippet: Random Strings"

From Coder Merlin
Line 1: Line 1:
== Select a Random String from an Array ==
= Select a Random String from an Array =
 
== Swift ==
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
// Select a random string from an array and print the result
// Select a random string from an array and print the result
Line 26: Line 28:
}
}
</syntaxhighlight>
</syntaxhighlight>
== Python ==

Revision as of 17:44, 24 December 2018

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Select a Random String from an Array[edit]

Swift[edit]

// Select a random string from an array and print the result
let verbs = ["walk", "jump", "run", "swim", "dance"]                                                                                                                                                                                                                                                                                                                
let verb = verbs[Int.random(in:0..<verbs.count)]                                                                                                                                                                                                                                                                                                                    
print(verb)
// Select a random string from an array and print the result (with syntactic sugar)
let verbs = ["walk", "jump", "run", "swim", "dance"]
if let verb = verbs.randomElement() {// Note: randomElement() returns an optional string
    print(verb)
}
// Select multiple random strings from two arrays and print the results 
let geographicFeatures = ["river", "lake", "ocean", "mountain", "desert"]
let verbAndPrepositions = ["walk to", "jump over", "run to", "dance around"]

for _ in 0 ..< Int.random(in: 3...5) {
    let verb = verbAndPrepositions.randomElement()!
    let geographicFeature = geographicFeatures.randomElement()!
    print("\(verb) the \(geographicFeature)")
}

Python[edit]