Answer:
Here's a Smalltalk script that does what you've described:
Code:
| orderedCollection random |
orderedCollection := OrderedCollection new.
20 timesRepeat: [
random := (Random new next: 16) asInteger. "Generate a random integer between 0 and 15"
orderedCollection add: random.
].
"Print the contents of the OrderedCollection"
orderedCollection do: [:each | Transcript show: each asString; cr.].
"Print the number of unique elements in the OrderedCollection"
| uniqueElements |
uniqueElements := orderedCollection asSet.
Transcript show: 'Number of unique elements: ', uniqueElements size asString; cr.
Step-by-step explanation:
Let me explain the Smalltalk script step by step:
| orderedCollection random |:
This line declares two variables, orderedCollection and random, which will be used in the script.
orderedCollection := OrderedCollection new.:
Here, we create an empty OrderedCollection object and assign it to the orderedCollection variable. This collection will hold our random integers.
20 timesRepeat: [ ... ].:
This is a loop that repeats the code inside the square brackets 20 times. Each iteration of the loop generates a random integer and adds it to the orderedCollection.
random := (Random new next: 16) asInteger.:
Inside the loop, we create a new instance of the Random class using Random new. Then, we use the next: method to generate a random number between 0 and 15 (inclusive). We convert the result to an integer and assign it to the random variable.
orderedCollection add: random.:
We add the generated random integer to the orderedCollection.
"Print the contents of the OrderedCollection" ...:
After adding all 20 random integers to the orderedCollection, we loop through the collection using do: and print each element on the Transcript, which is a common way to display output in Smalltalk.
"Print the number of unique elements in the OrderedCollection" ...:
To find the number of unique elements in the orderedCollection, we convert it to a Set using asSet. A Set in Smalltalk contains only unique elements. We then get the size of the Set to determine the number of unique elements and print it on the Transcript.
So, when you run this script in a Smalltalk environment, you'll see the contents of the orderedCollection, which will be 20 random integers between 0 and 15, and the number of unique elements among them.