Int type Random number generator function

Dear forum members,

It’s not my intention to re-invent the wheel creating this Function with an int type input parameter (the max int number to choose), e.g. 40
The chosen random number will be from 1 to 40 in this example. The exit variable will be int type as well.

How would you code such a function for a Swift Library?

Thank you for your suggestions or pointing links to this piece of code.

Yours sincerely

Jorge Guillermo

You are looking for:

// Any integer from 1 to 40 included
(1...40).randomElement()

You can also use

Int.random(in: 0...40)

this will return an Int type instead of an optional

4 Likes

That’s it.

Int.random(in: 1...40), since OP wants to exclude zero. But this is what you should use.

2 Likes

Pls explain what is an optional?

https://developer.apple.com/documentation/swift/optional

Feel free to ask questions after reading (ideally start a new thread for that).

Thank for your previous help. I tried to implement this random generation function (Int) to look for a random subscript in an array of Strings so then I could print the subscripted new Value I used the following code but to no avail. Still does not compile. Please….Where are the error issues?
// Playground

import Cocoa

//

var declars : [String] = [“txt0”,….,”txt29”]

subscript(index:Int) -> Int {

get {

Int.random(in 0…29) -> Int

index

}

set (NewValue) {

print(NewValue[index])

}

}

You can format code blocks by surrounding them with groups of three ASCII grave accents like this:

```

// Playground
import Cocoa
// ...

```

It makes it easier for the rest of us to read.


Do you just want the following?

var declars : [String] = (0...29).map { "txt\($0)" }
print("All: \(declars)") // ["txt0", "txt1", "txt2", /* ... */ "txt29"]

if let randomEntry = declars.randomElement() {
    print("Random: \(randomEntry)") // e.g. “txt19”
}

Hi Jeremy,
Yes, it does compile! Great!! But at runtime the ‘prints' don't work. It also appears the random number generator does not execute. It’s expected this experimental app will offer the user some more real-life random chat inducers such as: Hullo there, you alright? or I can’t understand your chat. or Give me please some more hints. etc (up to 30 different inducers), coming up at him randomly and automatically.

Yours sincerely

Jorge Guillermo

Dear forum members

Is there in Swift any elegant and simple function such as those found in Python or similars? Something that perform on an user defined data structure type, as follows:

// data structure and definition with initiation values
client[(1,”any text here”),(2,”any other text”),…..,(40,”some text")]
import random
repeat until exit_char {
r = random.randint(1…40)
print(Client,r,txtr)
// whatever other action here
}

Thank you

Jorge Guillermo Forero

Could you please send me the email address of Apple team in charge of Swift development projects.
Thank you

I’m not quite sure how to respond to that—it comes across like the precursor to a complaint. I don’t work for Apple or even really know which of the other users does and doesn’t. The best I can do is get the attention of @Nicole_Jacque, who tends to be the one who answers forum‐related questions, and @John_McCall, who is most often the one who steps in to diffuse heated threads.

@tkremenek is the head of the Swift project. But as a general matter, several people at Apple (including me) read these forums, so if you have a comment to make, you can just make it here and we'll see it.

4 Likes

Thank you, John… in real terms the trouble isn’t that serious. It seems to me that something is missing in a multi-paradigm language like Swift. It’s perhaps its first order logic maths handling (i.e. rules such as action/s :- condition/s) where the symbol :- stands for “imply”. My experience with logic languages such as LISP and Prolog comes to me, particularly when I developed List handling predicates currently at the Oxford University’s C-Prolog database repository. These are my donation and they are currently in the public domain.
Yours sincerely

Jorge Guillermo Forero, PhD (Computer Science)

At the moment I am visiting NJ, Franklin Lakes.

How close does this get:

var client = [(1,"any text here"),(2,"any other text"),(3,"some further text")] // populate array of tuples manually
(4...40).map { client.append(($0, "text block \($0)")) } // or populate it programatically using map on a closed range
var exit_bool = false // set up an exit condition
repeat { // a repeat loop - runs at least once
    let r = Int.random(in: 1...40) // choose a random int from 1 to 40
    print(client[r-1]) // print the corresponding tuple from the array, remembering arrays are indexed from 0
    print(client[r-1].0) // or just print the first item in the tuple
    print(client[r-1].1) // or just the second
    // whatever other action here
    exit_bool = Bool.random() && Bool.random() && Bool.random() // give the exit condition a chance to indicate exit
} while !exit_bool // repeat if exit condition not reached

Dear John McCall

I am quite having second thoughts about Swift por diverse applications in several Apple’s platforms. From outside Apple I perceive the language is coming to age with different paradigms
as old times software engineering courses. I.e. Declarative, Object oriented, Functional and maybe Logic, among others. In reference to the last we could point out to C Prolog the original French development. Surprisingly this approach was used successfully to manipulate Natural Language applications, originally parsers first in grammar structures. First degree mathematical logic applications and semantics a good second. I wonder whether somehow that has been contemplated to extend Swift?

In this case, the programming objections I noted in my earlier attempts when tried to use set theory with Swift to solve some primitive AI applications, that could develop new vision and perspective for Swift. Let me refer to my my good will contribution in the 80’s to the Oxford University C Prolog with some predicates to manage List structures. Based on this particular data structure, which is composed of just two elements a Head and a Tail, whereby the Head is just one element (its first) and its Tail a sublist of the original List - but without its Head. The tail is always a List itself and by a recursive procedure the programmer could reach all its elements and operate as required in a particular logic programme. Membership could be a good example.

Essentially by using this extended approach I manage to get a first semantic interpreter in English which became my approved PhD thesis in 1992.

At the moment I am located in Reading UK, but I was travelling to New York where the University of Columbia show me some interest in a particular AI application together with a textbook on this matter. Further explanation merit a larger exposition. Needless to say I would like to extend it.

Please I requested your intervention before the development team so I can finally use Swift (and the Apple hardware) to implement this App at this University.

Best wishes

Jorge Guillermo Forero, PhD (Computer Science).

IIUC, Swift it self does not include Logic. In theory it could embed other Domain Specific Language in due time with the coming of function builder (one of the planned swift feature). From what I can see, function builder should be able to support Prolog.

PS

The discussion here reminds me of Swift for TensorFlow for some reason.

1 Like

I think it’s unlikely that we’d add builtin logic-proframming engine to Swift as opposed to e.g. allowing someone to hook up an existing constraint-solving library. I think you could write a very fluent interface to such a library in Swift as it exists today, but if you encountered challenges, they’d be interesting to hear about.