Description of the problem.
Choose a number between 0 and 4 (the randomly number will indicate how many values from the list will be displayed)
Get random values from list, so that they are unique and display as a result.
My code does not work, please let me know how to fix it. I will be grateful for your help.
import groovy.json.JsonOutput
import java.util.Random
Random random = new Random()
def num = ["0","1","2","3","4"]
def randomNum = random.nextInt(num.size())
def min = 0;
def max = num[randomNum];
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
while(max > min) {
def randomValue = random.nextInt(list.size())
def theValue = list[randomValue] + '"'+ "," +
max++;
}
The result that I would like to achieve is for example:
Toy","Cup (if 2 is randomly selected)
Toy","Tiger","Book" (if 3 is randomly selected)
the available number is from 0 to 4 as many as there are possible
elements to choose from 0 - Toy, 1 - Mouse 2- Cup 3- Book 4 - tiger.
First, a number, e.g. 2, is drawn and then 2 elements are selected
randomly from the list of values.
You could do something like this:
Random random = new Random()
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
// this allows zero to be selected... if that is a violation
// of the requirement, adjust this....
int numberOfElementsToSelect = random.nextInt(list.size())
def results = []
numberOfElementsToSelect.times {
results << list.remove(random.nextInt(list.size()))
}
println results
println results.join(',')
EDIT:
Works great, I have one more question what to do to exit the script
without showing any results in case the value is empty
If you want to exit the script without showing results, you could do something like this:
Random random = new Random()
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
// this allows zero to be selected... if that is a violation
// of the requirement, adjust this....
int numberOfElementsToSelect = random.nextInt(list.size())
def results = []
numberOfElementsToSelect.times {
results << list.remove(random.nextInt(list.size()))
}
if(results) {
// do what you want with the results, like...
println results.join(',')
} else {
// do something else, could be exit the script...
System.exit(-2)
}
Related
I am new to this group and this is my first post.
Can some one please help me to generate 5 Unique numbers in min and max range and then sort them in ascending order using groovy.
note: I am doing this in soapui.
import org.apache.commons.lang.RandomStringUtils
import java.util.Random
Random r = new Random();
def i
List random_num
for (i=1;i<=5;i++)
{
random_num(i) = r.nextInt(9+2)
if(i>0)
{
if(random_num[i]==random_num[i-1])
random_num[i] = r.nextInt(9+2)
}
}
random_num.sort() ;
log.info random_num
thank you
The part about rand between a min and max can be found
here.
For the other constraints:
Unique values: use a Set for your result
Ascending order: use a sorted Set
E.g.:
import java.util.concurrent.ThreadLocalRandom
def n = 5
def min = 5
def max = 42
def result = new TreeSet()
while (result.size()<n) {
result << ThreadLocalRandom.current().nextInt(min, max + 1)
}
println result
// → [7, 8, 29, 37, 42]
Note: make sure max - min > n
Your code is very Java-ish. Groovy was developed, partly to eliminate a lot of the Java ceremony.
This is what I use to generate a random number:
def randNum(minSize, maxSize) {
return Math.abs(new Random().nextInt(maxSize + 1 - minSize) + minSize)
}
You can call that five times, collect the results in a list, and sort the list. To call a routine, you can use:
5.times {randNum(minSize, maxSize)}
I have to find the greatest even number possible using the digits of given number
Input : 7876541
Desired output : 8776514
Can anyone help me with the logic?
How about this?
convert it into string
sort the numbers in reverse order
join them and convert it as number
def n = 7876541
def newN = (n.toString().split('').findAll{it}.sort().reverse().join()) as Integer
println newN
You can quickly try it on-line demo
EDIT: Based on the OP comments, updating the answer.
Here is what you can do -
- find the permutations of the number
- find the even number
- filter it by maximum number.
There is already found a thread for finding the permutations, so re-using it with little changes. Credits to JavaHopper.
Of course, it can be simplified by groovified.
class Permutations {
static def list = []
public static void printPermutation(char[] a, int startIndex, int endIndex) {
if (startIndex == endIndex)
list << ((new String(a)) as Integer)
else {
for (int x = startIndex; x < endIndex; x++) {
swap(a, startIndex, x)
printPermutation(a, startIndex + 1, endIndex)
swap(a, startIndex, x)
}
}
}
private static void swap(char[] a, int i, int x) {
char t = a[i]
a[i] = a[x]
a[x] = t
}
}
def n = 7876541
def cArray = n.toString().toCharArray()
Permutations.printPermutation(cArray, 0, cArray.size())
println Permutations.list.findAll { it.mod(2) == 0}?.max()
Quickly try online demo
There is no need to create permutations.
Try this solution:
convert the source number into a string.
split the string into an array,
sort the numbers, for the time being, in ascending order,
find the index of the first even digit,
remove this number from the array (storing it in a variable),
reverse the array and add the removed number,
join the digits from the array and convert them into integer.
So the whole script looks like below:
def inp = 7876541
def chars1 = inp.toString().split('')
// findAll{it} drops an empty starting element from the split result
def chars2 = chars1.findAll{it}.sort()
// Find index of the 1st even digit
def n = chars2.findIndexOf{it.toInteger() % 2 == 0}
def dig = chars2[n] // Store this digit
chars2.remove(n) // Remove from the array
def chars3 = chars2.reverse() // Descending order
chars3.add(dig) // Add the temporarily deleted number
def out = (chars3.join()) as Integer // result
println out
my following code
def traineeDetails = session.traineeDetailsForAuto
on printing gives:
traineeDetails = [name:[Hus, Vin], email:[hus#gmail.com, vin#gmail.com], phone:[9908877654, 9987655432], jobTitle:[SE, ST]]
def count = traineeDetails.name.size() gives correct value =2
but when the map key contains one value
def traineeDetails = session.traineeDetailsForAuto
on printing gives:
traineeDetails = [name:Hus, email:hus#gmail.com, phone:9987766543, jobTitle:SE]
def count= traineeDetails.name.size() gives wrong answer 3 which is the total number of character in name
but here i need to get total count of value that the key name holds..
how to do it?
If you're going to mix types in a map, then you're going to need to check the type:
def count = traineeDetails.name.with { it instanceof Collection ? it.size() : 1 }
Using your examples, it works fine:
traineeDetails = [name:['Hus', 'Vin'], email:['hus#gmail.com', 'vin#gmail.com'], phone:['9908877654', '9987655432'], jobTitle:['SE', 'ST']]
count = traineeDetails.name.with { it instanceof Collection ? it.size() : 1 }
assert count == 2
traineeDetails = [name:'Hus', email:'hus#gmail.com', phone:'9987766543', jobTitle:'SE']
count = traineeDetails.name.with { it instanceof Collection ? it.size() : 1 }
assert count == 1
Can you provide actual non-working examples?
How to select random item from a combo box, without selecting what is there already in the combobox.
I guess you want something like this:
Random random = new Random();
int newIndex = -1;
do {
newIndex = random.Next(comboBox.Items.Count);
} while (newIndex == comobBox.SelectedIndex && comboBox.Items.Count > 1);
comobBox.SelectedIndex = random.Next(comboBox.Items.Count);
Basically Combo box has items in string so if you can describe me some clear then we may help more anyway here is sample code
n you can do it
ComboBox b = new ComboBox();
Random rt = new Random();
string myText = "";
myText = b.Items[rt.Next(0, b.Items.Count - 1)].ToString();
You should use the Random class to get a random number between 0 and the max amount of items in the combobox. You should get this number repeatedly until you get one that doesn't match what is already selected within the combobox, like so:
Random random = new Random();
int newSelectedIndex = comboBox.SelectedIndex;
while (newSelectedIndex == comboBox.SelectedIndex) {
newSelectedIndex = random.Next(0, comboBox.Items.Count);
}
comboBox.SelectedIndex = newSelectedIndex;
// Item
// comboBox.Items[newSelectedIndex];
This may not work C/P'd, as I wrote it from the top of my head and don't have an IDE to test right now, but I hope you get the idea.
IMPORTANT: If you only have 1 item which is also selected, this may get into an endless loop...
What I have so far is:
def imageColumns = ["products_image", "procuts_subimage1", "products_subimage2", "prodcuts_subimage3", "products_subimage4"]
def imageValues = ["1.jpg","2.jpg","3.jpg"]
def imageColumnsValues = []
// only care for columns with values
imageValues.eachWithIndex { image,i ->
imageColumnsValues << "${imageColumns[i]} = '${image}'"
}
println imageColumnValuePair.join(", ")
It works but I think it could be better. Wish there was a collectWithIndex ... Any suggestions?
There's no collectWithIndex, but you can achieve the same result with a little effort:
def imageColumns = ["products_image", "procuts_subimage1", "products_subimage2", "prodcuts_subimage3", "products_subimage4"]
def imageValues = ["1.jpg","2.jpg","3.jpg"]
def imageColumnsValues = [imageValues, 0..<imageValues.size()].transpose().collect { image, i ->
"${imageColumns[i]} = '${image}'"
}
println imageColumnsValues.join(", ")
This takes the list of items and a range of numbers from 0 size(list) - 1, and zips them together with transpose. Then you can just collect over that result.