One-liner to generate Powerball picks in Swift? - ruby

With the U.S.'s large $1.5 Billion lottery this week, I wrote a function in Ruby to make Powerball picks. In Powerball, you choose 5 numbers from the range 1..69 (with no duplicates) and 1 number from the range 1..26.
This is what I came up with:
def pball
Array(1..69).shuffle[0..4].sort + [rand(1..26)]
end
It works by creating an array of integers from 1 to 69, shuffling that array, choosing the first 5 numbers, sorting those, and finally adding on a number from 1 to 26.
To do this in Swift takes a bit more work since Swift doesn't have the built-in shuffle method on Array.
This was my attempt:
func pball() -> [Int] {
let arr = Array(1...69).map{($0, drand48())}.sort{$0.1 < $1.1}.map{$0.0}[0...4].sort()
return arr + [Int(arc4random_uniform(26) + 1)]
}
Since there is no shuffle method, it works by creating an [Int] with values in the range 1...69. It then uses map to create [(Int, Double)], an array of tuple pairs that contain the numbers and a random Double in the range 0.0 ..< 1.0. It then sorts this array using the Double values and uses a second map to return to [Int] and then uses the slice [0...4] to extract the first 5 numbers and sort() to sort them.
In the second line, it appends a number in the range 1...26. I tried adding this to the first line, but Swift gave the error:
Expression was too complex to be solved in reasonable time; consider
breaking up the expression into distinct sub-expressions.
Can anyone suggest how to turn this into a 1-line function? Perhaps there is a better way to choose the 5 numbers from 1...69.

Xcode 8.3 • Swift 3.1
import GameKit
var powerballNumbers: [Int] {
return (GKRandomSource.sharedRandom().arrayByShufflingObjects(in: Array(1...69)) as! [Int])[0..<5].sorted() + [Int(arc4random_uniform(26) + 1)]
}
powerballNumbers // [5, 9, 62, 65, 69, 2]
Swift 2.x
import GameKit
var powerballNumbers: [Int] {
return (GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(Array(1...69)) as! [Int])[0...4].sort() + [Int(arc4random_uniform(26).successor())]
}
powerballNumbers // [21, 37, 39, 42, 65, 23]

I don't find the "one-liner" concept very compelling. Some languages lend themselves to it; others don't. I would suggest giving Swift a shuffle method to start with:
extension Array {
mutating func shuffle () {
for var i = self.count - 1; i != 0; i-- {
let ix1 = i
let ix2 = Int(arc4random_uniform(UInt32(i+1)))
(self[ix1], self[ix2]) = (self[ix2], self[ix1])
}
}
}
But since I made this mutating, we still need more than one line to express the entire operation because we have to have a var reference to our starting array:
var arr = Array(1...69)
(1...4).forEach {_ in arr.shuffle()}
let result = Array(arr[0..<5]) + [Int(arc4random_uniform(26)) + 1]
If you really insist on the one-liner, and you don't count the code needed to implement shuffle, then you can do it, though less efficiently, by defining shuffle more like this:
extension Array {
func shuffle () -> [Element] {
var arr = self
for var i = arr.count - 1; i != 0; i-- {
let ix1 = i
let ix2 = Int(arc4random_uniform(UInt32(i+1)))
(arr[ix1], arr[ix2]) = (arr[ix2], arr[ix1])
}
return arr
}
}
And here's your one-liner:
let result = Array(1...69).shuffle().shuffle().shuffle().shuffle()[0..<5] + [Int(arc4random_uniform(26)) + 1]
But oops, I omitted your sort. I don't see how to do that without getting the "too complex" error; to work around that, I had to split it into two lines:
var result = Array(1...69).shuffle().shuffle().shuffle().shuffle()[0..<5].sort(<)
result.append(Int(arc4random_uniform(26)) + 1)

How about this:
let winningDraw = (1...69).sort{ _ in arc4random_uniform(2) > 0}[0...4].sort() + [Int(arc4random_uniform(26)+1)]
[edit] above formula wasn't random. but this one will be
(1...69).map({Int(rand()%1000*70+$0)}).sort().map({$0%70})[0...4].sort() + [Int(rand()%26+1)]

For the fun of it, a non-GameplayKit (long) one-liner for Swift 3, using the global sequence(state:next:) function to generate random elements from the mutable state array rather than shuffling the array (although mutating the value array 5 times, so some extra copy operations here...)
let powerballNumbers = Array(sequence(state: Array(1...69), next: {
(s: inout [Int]) -> Int? in s.remove(at: Int(arc4random_uniform(UInt32(s.count))))})
.prefix(5).sorted()) + [Int(arc4random_uniform(26) + 1)]
... broken down for readability.
(Possible in future Swift version)
If the type inference weren't broken inout closure parameters (as arguments to closures), we could reduce the above to:
let powerballNumbers = Array(sequence(state: Array(1...69), next: {
$0.remove(at: Int(arc4random_uniform(UInt32($0.count)))) })
.prefix(5).sorted()) + [Int(arc4random_uniform(26) + 1)]
If we'd also allow the following extension
extension Int {
var rand: Int { return Int(arc4random_uniform(UInt32(exactly: self) ?? 0)) }
}
Then, we could go on to reduce the one-line to:
let powerballNumbers = Array(sequence(state: Array(1...69), next: { $0.remove(at: $0.count.rand) }).prefix(5).sorted()) + [26.rand + 1]

Xcode 10 • Swift 4.2
Swift now has added shuffled() to ClosedRange and random(in:) to Int which now makes this easily accomplished in one line:
func pball() -> [Int] {
return (1...69).shuffled().prefix(5).sorted() + [Int.random(in: 1...26)]
}
Further trimmings:
Because of the return type of pball(), the Int can be inferred in the random method call. Also, .prefix(5) can be replaced with [...4]. Finally, return can be omitted from the one-line function:
func pball() -> [Int] {
(1...69).shuffled()[...4].sorted() + [.random(in: 1...26)]
}

Related

counting pairs in a list

I've recently started on HackerRank and I'm attempting "Sales by Match". I've arrived at a solution I'm content with in terms of exploiting Kotlin's function programming capabilities. However, I'm not getting the expected answer...
Problem summary:
Given an Array:
-> find and return the total number of pairs.
i.e:
input -> [10, 20, 20, 10, 10, 30, 50, 10, 20]
number of pairs -> 3
here is my code and some comments to explain it:
fun sockMerchant(n: Int, pile: Array<Int>): Int{
var count = 0
mutableMapOf<Int, Int>().withDefault { 0 }.apply {
// the [attempted] logic behind this piece of code here is
// that as we iterate through the list, the 'getOrPut()'
// function will return either the value for the given [key]
// or throw an exception if there is no such key
// in the map. However, since our map was created by
// [withDefault], the function resorts to its `defaultValue` <-> 0
// instead of throwing an exception.
for (e in values) {
// this simplifies our code and inserts a zero [+1] where needed.
// if (key exists)
// // return its associated value and MOD it:
// case: even -> increment counter
// else -> do nothing
// else if (key dne)
// // insert default value <-> [0] + 1
// ....
// ....
// ....
if (getOrPut(e, { getValue(e) + 1 } ) % 2 == 0) count++
}
}
return count
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val ar = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray()
val result = sockMerchant(n, ar)
println(result)
}
--
Any help or tips would go a long way here:)
I was able to do this by grouping the numbers together, taking the resulting lists, and summing how many pairs each one contains:
fun sockMerchant(n: Int, pile: Array<Int>): Int =
pile.groupBy { it }.values.sumBy { it.size / 2 }
After we do pile.groupBy { it }, we have this structure:
{10=[10, 10, 10, 10], 20=[20, 20, 20], 30=[30], 50=[50]}
We take the values, and sum by each of their size dividing by 2. This will round half-pairs down to 0 and full pairs to 1 each.
Note: I am not entirely clear what the purpose of n is in this case.
I modified it a bit to be more easily testable, but here is the fixes :
import java.util.*
fun sockMerchant(n: Int, pile: Array<Int>): Int{
var count = 0
mutableMapOf<Int, Int>().withDefault { 0 }.apply {
// the [attempted] logic behind this piece of code here is
// that as we iterate through the list, the 'getOrPut()'
// function will return either the value for the given [key]
// or throw an exception if there is no such key
// in the map. However, since our map was created by
// [withDefault], the function resorts to its `defaultValue` <-> 0
// instead of throwing an exception.
for (e in pile) {
// this simplifies our code and inserts a zero [+1] where needed.
// if (key exists)
// // return its associated value and MOD it:
// case: even -> increment counter
// else -> do nothing
// else if (key dne)
// // insert default value <-> [0] + 1
// ....
// ....
// ....
println(e)
put(e, getValue(e) + 1)
if (getValue(e) % 2 == 0) count++
println(entries)
}
}
return count
}
val n = 5
val ar = "10 10 10 10 20 20 30 40".split(" ").map{ it.trim().toInt() }.toTypedArray()
val result = sockMerchant(n, ar)
println(result)
Output :
10
[10=1]
10
[10=2]
10
[10=3]
10
[10=4]
20
[10=4, 20=1]
20
[10=4, 20=2]
30
[10=4, 20=2, 30=1]
40
[10=4, 20=2, 30=1, 40=1]
3
Pair.kts:3:18: warning: parameter 'n' is never used
fun sockMerchant(n: Int, pile: Array<Int>): Int{
^
Process finished with exit code 0
Explanation :
You looped over "values", which is at start empty, so you never did anything with your code
Even when looping over pile, your incrementation logic didn't go above 1, so the condition was never satisfied and the count was never incremented.
But the main reasoning behind was correct.

Sort an unsorted array with Closures

let unsortedArray = [98,23,643,678,2,568,1,234,556,4] {
(first:Int , second:Int) -> Bool in
if first < second {
return true
} else{
return false
}
}
Above code is to sort an unsorted array with Swift 2 and Xcode 7.3.
I want to know how can i print the result?
The syntax is:
let unsortedArray = [98, 23, 643, 678, 2, 568, 1, 234, 556, 4]
let sortedArray = unsortedArray.sort() { (first: Int, second: Int) -> Bool in
if first < second {
return true
} else {
return false
}
}
print("\(sortedArray)")
Note, in Swift 2.3 that's sort, but in Swift 3, it is now called sorted.
By the way, this can be simplified:
let sortedArray = unsortedArray.sort { (first: Int, second: Int) -> Bool in
return first < second
}
Or, further simplified to use anonymous closure arguments:
let sortedArray = unsortedArray.sort {
return $0 < $1
}
Which because there is a single expression inside the closure, you can further simply to:
let sortedArray = unsortedArray.sort { $0 < $1 }
Or, further simplified to:
let sortedArray = unsortedArray.sort(<)
Or, because the elements of the array, Int types, conform to Comparable, you can omit the closure entirely and use a different sort method that takes no parameters at all:
let sortedArray = unsortedArray.sort()
Note, this requires that the elements of the array have:
The less-than operator (func <) defined in
the Comparable conformance is a
strict weak ordering
over the elements in self.

How to iterate and extract values out of a for loop in Rust

I'm new to Rust and looking to understand concepts like borrowing. I'm trying to create a simple two dimensional array using standard input. The code:
use std::io;
fn main() {
let mut values = [["0"; 6]; 6]; // 6 * 6 array
// iterate 6 times for user input
for i in 0..6 {
let mut outputs = String::new();
io::stdin().read_line(&mut outputs).expect(
"failed to read line",
);
// read space separated list 6 numbers. Eg: 5 7 8 4 3 9
let values_itr = outputs.trim().split(' ');
let mut j = 0;
for (_, value) in values_itr.enumerate() {
values[i][j] = value;
j += 1;
}
}
}
This won't compile because the outputs variable lifetime is not long enough:
error[E0597]: `outputs` does not live long enough
--> src/main.rs:20:5
|
14 | let values_itr = outputs.trim().split(' ');
| ------- borrow occurs here
...
20 | }
| ^ `outputs` dropped here while still borrowed
21 | }
| - borrowed value needs to live until here
How can I get the iterated values out of the block into values array?
split() gives you substrings (string slices) borrowed from the original string, and the original string is outputs from line 6.
The string slices can't outlive the scope of outputs: when a loop iteration ends, outputs is deallocated.
Since values is longer lived, the slices can't be stored there.
We can't borrow slices of outputs across a modification of outputs. So even if the String outputs itself was defined before values, we couldn't easily put the string slices from .split() into values; modifying the string (reading into it) invalidates the slices.
A solution needs to either
Use a nested array of String, and when you assign an element from the split iterator, make a String from the &str using .to_string(). I would recommend this solution. (However an array of String is not at as easy to work with, maybe already this requires using Vec instead.) 1
Read all input before constructing a nested array of &str that borrows from the input String. This is good if the nested array is something that you only need temporarily.
1: You can use something like vec![vec![String::new(); 6]; 6] instead
This answer was moved from the question, where it solved the OPs needs.
use std::io;
fn main() {
let mut values = vec![vec![String::new(); 6]; 6];
for i in 0..6 {
let mut outputs = String::new();
io::stdin().read_line(&mut outputs)
.expect("failed to read line");
let values_itr = outputs.trim().split(' ');
let mut j = 0;
for (_, value) in values_itr.enumerate() {
values[i][j] = value.to_string();
j += 1;
}
}
}

constUnsafePointer unresolved identifier in Swift FFT

I have been looking at examples of FFTs in Swift, and they all seem to have ConstUnsafePointer when using vDSP_ctozD as in the example below:
import Foundation
import Accelerate
internal func spectrumForValues(signal: [Double]) -> [Double] {
// Find the largest power of two in our samples
let log2N = vDSP_Length(log2(Double(signal.count)))
let n = 1 << log2N
let fftLength = n / 2
// This is expensive; factor it out if you need to call this function a lot
let fftsetup = vDSP_create_fftsetupD(log2N, FFTRadix(kFFTRadix2))
var fft = [Double](count:Int(n), repeatedValue:0.0)
// Generate a split complex vector from the real data
var realp = [Double](count:Int(fftLength), repeatedValue:0.0)
var imagp = realp
withExtendedLifetimes(realp, imagp) {
var splitComplex = DSPDoubleSplitComplex(realp:&realp, imagp:&imagp)
// Take the fft
vDSP_fft_zripD(fftsetup, &splitComplex, 1, log2N, FFTDirection(kFFTDirection_Forward))
// Normalize
var normFactor = 1.0 / Double(2 * n)
vDSP_vsmulD(splitComplex.realp, 1, &normFactor, splitComplex.realp, 1, fftLength)
vDSP_vsmulD(splitComplex.imagp, 1, &normFactor, splitComplex.imagp, 1, fftLength)
// Zero out Nyquist
splitComplex.imagp[0] = 0.0
// Convert complex FFT to magnitude
vDSP_zvmagsD(&splitComplex, 1, &fft, 1, fftLength)
}
// Cleanup
vDSP_destroy_fftsetupD(fftsetup)
return fft
}
// To get rid of the `() -> () in` casting
func withExtendedLifetime<T>(x: T, f: () -> ()) {
return Swift.withExtendedLifetime(x, f)
}
// In the spirit of withUnsafePointers
func withExtendedLifetimes<A0, A1>(arg0: A0, arg1: A1, f: () -> ()) {
return withExtendedLifetime(arg0) { withExtendedLifetime(arg1, f) }
}
However when I try to use it in my project, this ConstUnsafePointer is seen as an unresolved identifier. Any clue how to fix this? Thanks in advance.
The name ConstUnsafePointer was used in early Swift betas last summer (at that time, UnsafePointer meant mutable). Now, constant pointers are just UnsafePointer and mutable pointers are UnsafeMutablePointer.

Swift returning the indexes that will sort an array (similar to numpy argsort) [duplicate]

This question already has an answer here:
Index of element in sorted()
(1 answer)
Closed 7 years ago.
I'm trying to return the indices of an array which correspond to the sorted values. For example,
let arr = [7, 10, -3]
let idxs = argsort(arr) // [2, 0, 1]
My attempt works but is not pretty, and only functions for CGFloat. I'm looking for some ways in which I can improve the function, make it generic and easier to read. The code just looks ugly,
func argsortCGFloat( a : [CGFloat] ) -> [Int] {
/* 1. Values are wrapped in (index, values) tuples */
let wrapped_array = Array(Zip2(indices(a),a))
/* 2. A comparator compares the numerical value from
two tuples and the array is sorted */
func comparator(a: (index : Int, value : CGFloat), b: (index : Int, value : CGFloat)) -> Bool {
return a.value < b.value
}
var values = sorted(wrapped_array, comparator)
/* 3. The sorted indexes are extracted from the sorted
array of tuples */
var sorted_indexes: [Int] = []
for pair in values {
sorted_indexes.append(pair.0)
}
return sorted_indexes
}
You can do it by creating an array of indexes, and sorting them using the array from the outer context, like this:
func argsort<T:Comparable>( a : [T] ) -> [Int] {
var r = Array(indices(a))
r.sort({ a[$0] > a[$1] })
return r
}
let arr = [7, 10, -3]
let idxs = argsort(arr)
println (idxs)

Resources