This question already has answers here:
Randomly select an item from a list
(5 answers)
Closed 8 years ago.
Alright, I keep trying to oogle this but It keeps showing answers with a string array which I can't use. This is currently my code:
List<String> Shuffle = new ArrayList<String>();
if(EAmount == finalk){
Shuffle.add("Emerald");
}
if(DAmount == finalk){
Shuffle.add("Diamond");
}
if(GAmount ==finalk){
Shuffle.add("Gold");
}
if(IAmount == finalk){
Shuffle.add("Iron");
}
I can't find out how to get a random string from Shuffle. Please help!
BTW: The Amounts and finalk are integers
You can generate a random integer between zero and the size of the collection (exclusive), and then use it as an index to refer to the corresponding item of the collection.
int randIndex = new Random().nextInt(Shuffle.size()); //generate rand int [0, size[
String randString = Shuffle.get(randIndex); //get random string
It is the same as with Arrays, you just need to use the get Method:
Shuffle.get(random)
Related
This question already has answers here:
Generate random number without duplicate in certain range
(10 answers)
Closed 6 years ago.
I have used this code in order to randomise 1000000 numbers without duplication's. Here's what I have so far.
enter code here protected void randomise() {
int[] copy = new int[getArray().length];
// used to indicate if elements have been used
boolean[] used = new boolean[getArray().length];
Arrays.fill(used,false);
for (int index = 0; index < getArray().length; index++) {
int randomIndex;
do {
randomIndex = getRandomIndex();
} while (used[randomIndex]);
copy[index] = getArray()[randomIndex];
used[randomIndex] = true;
}
for (int index = 0; index < getArray().length; index++) {
getArray()[index] = copy[index];
//Checks if elements in array have already been used
}
}
public static void main(String[] args) {
RandomListing count = new SimpleRandomListing(1000000);
//Will choose 1000000 random numbers
System.out.println(Arrays.toString(count.getArray()));
}
This method is too slow can you let me know how this can be done more efficiently. I appreciate all replies.
Regards,
A more efficient way to do this is by starting with a pool of numbers (e.g. an List of all numbers between 0 and 1000000) and then remove numbers that you've already used. That way, every time you try to get a new number, that number is guaranteed to never having been used before rather than spending time trying to find a "good" unused number.
It looks like your using a linear search to find matches. Try using a binary search it's more efficient. The array you are searching must be sorted to implement a binary search.
This question already has answers here:
Ways to iterate over a list in Java
(13 answers)
Closed 7 years ago.
Here's my list example:
List<String> l2 = new ArrayList<String>();
l2.add("Apple");
l2.add("Kiwi");
l2.add("Orange");
So Basically I want to iterate through this list until it finds for example "Orange" then it'll return a Line number (3 in this example). But I'm really not sure how to do this. Anyone that can help me?
You need a for loop to iterate through any Array or list. In this case being an Array list you would iterate through it with the following for loop
for(int x = 0; x < l2.size();x++){
if(l2.get(x).equals("Orange")){
// this is where the code will end up when it selects Orange
}
}
The l2.size() method gets the whole size of the ArrayList and x 1 is added to x each time it is smaller than the Arraylist size. The if statement will stop as soon as it finds the text in the ArrayList in the equals parameters, this is where you should put your code if you want to add, remove or do something at this point.
There are many ways to do this while iterating over the list. Here's an example:
int i = 0;
for( String s : l2){
if(s.equals("Orange")) System.out.println(i);
i++;
}
Did some research and found a much easier way:
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm trying to create this two dimensional array in java and print the output, but when it outputs I am not getting the numbers or a two-dimensional structure. Java appears to be giving me what looks like memory addresses for each array result.
My code
public static int[][] generateSampleTable(int smallest, int largest, int sampleSize)
{
int sampleTable[][] = new int[sampleSize][2];
for (int i = 0; i < sampleSize; i++)
{
sampleTable[i][0] = 5150;
sampleTable[i][1] = 2738;
}
return sampleTable;
}
public static void main(String[] args){
System.out.println(Arrays.toString(generateSampleTable(1,1,10)));
}
My output appears like this:
[[I#803816, [I#22b4b7, [I#1079ed1, [I#231c5d, [I#178cf47, [I#d65c13, [I#1fca60e, [I#1f99518, [I#fa7e97, [I#90925f]
Ignore the smallest and largest arguments in that method as I haven't implemented the calculations for them yet and am not using them right now.
Other than what you see here, I guess I should tell you that yes, I imported java.util.Arrays
Not sure what is going on. Any help would be appreciated.
Thanks
Arrays.toString() knows how to print 1 dimensional arrays. For 2-dimensional arrays you should use Arrays.deepToString().
This question already has answers here:
Arrays.asList() not working as it should?
(12 answers)
Closed 9 years ago.
So I'm just learning about arrays in Java (interesting stuff) but I'm having some problems getting my head around the contains() method.
I tried:
Random rn = new Random();
int first = 12;
int[] tab = new int[first];
for (int i = 0; i <= first - 1; i++) {
tab[i] = rn.nextInt(10);
Which seemed to work fine for filling in my Array, but then I tried a:
System.out.println(Arrays.asList(tab).contains(9));
And no matter what, even if I fill the array manually with 9's, it'll still only print up "false".
What am I doing wrong?
Try this
Integer[] tab = new Integer[]{9};
System.out.println(java.util.Arrays.asList(tab).contains(9));
I get
true
This question already has an answer here:
Pick random element from array, but unique
(1 answer)
Closed 9 years ago.
I'm trying to make an array of random colors from another array.
String [] colors = new String[6];
colors[0] = "red";
colors[1] = "green";
colors[2] = "blue";
colors[3] = "yellow";
colors[4] = "purple";
colors[5] = "orange";
That's my array as of now. I want to make a new array with just 4 of those colors without duplicates.
So far I know how to make an array of randoms; however, I don't know how to take care of duplicates efficiently.
Sounds like you want a Set. A Set is designed to remove duplicates.
Set<String> set = ...
for(String s : "a,b,c,d,e,f,d,e,c,a,b".split(","))
set.add(s);
This set will have all the unique strings.
List<String> colourList = new ArrayList<String>(Arrays.asList(colors));
Collections.shuffle(colourList);
return colourList.subList(0,4).toArray();
I'd strongly suggest you don't use arrays for this. Add what you need to a Set and it will handle duplicate management for you. You can always convert back to an array if need be.
You can just select random entries from colors, and add them into a Set until the set has four elements:
Set<String> randomStrings = new HashSet<String>();
Random random = new Random();
while( randomStrings.size() < 4) {
int index = random.nextInt( colors.length);
randomStrings.add( colors[index]);
}
You can try it out in this demo, where it selects four colors at random when you run it. You'll get output similar to:
Random colors: [orange, red, purple, blue]