Generating a unique random number between 2 numbers - android

For my specific purposes, I need to generate a whole number between 1 and 120 inclusive (which I can do no problem).
Once that number has been generated, I need to pull it from the pool so it can't be generated again.
Continue this process until all numbers are exhausted, at which point, the pool fills back up and we start over again.
How could I go about doing this?

Generate the whole list of numbers from 1 to 120. Shuffle the list. Take the first element (and remove it)
List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 120; i++) {
list.add(i)
}
Collections.shuffle(list);
...
int random = list.remove(0);
...
int otherRandom = list.remove(0);
Check for list.empty() in case you run out of numbers. If empty, create the list again and shuffle it.

The obvious way to do it is to fill a list with all numbers between 1 and 120, then when you need a random number, generate one between 1 and the list count, take the item from the list at that index, return it to the caller and then remove it from the list. Once the list is empty, refill and keep picking indices.

I believe that all you need is to shuffle an array or a collection. You can refer to this question for example.

Related

How to get strings from array randomly without repeating the string?

I'm making a quiz app I have string array and I want to load them on button click, strings should be loaded randomly into Text View. Strings should not be repeated.
Thanks..
Because it's your quiz, I'm gonna give you hints not the whole soltion
Random rnd = new Random;
while(array.size()>0){
// 1. use rng to get a index between 0 to current array.size()
// 2. remove the string by array.remove(index) so that it won't duplicated.
// 3. setText(string)
}
Try this, you can add comments if you need more details.
One way to do it is to convert the array to a list and shuffling it.
List myList = Arrays.asList(yourArray);
Collections.shuffle(myList);
After that you can just iterate over the list.

Android random but repeat 2 times

I have a little question concerning the usage of
Android Resouce by ID / Change image onClick / no change of imageView
I have established my images picked randomly here, using:
#Override
public void onClick(View v) {
Log.d("MYAPP", "Like-Button clicked");
/*imageViewMeasurement.setImageResource(R.drawable.p13);*/
TypedArray images = getResources().obtainTypedArray(R.array.images_primes);
int chosenImageNumber = (int) (Math.random() * images.length());
// setImageResource to the random chosenImageNumber
imageViewMeasurement.setImageResource(images.getResourceId(chosenImageNumber, R.color.colorPrimaryDark));
images.recycle();
// Confirmation if the random generator picked a Number from the array
String chosenImageNumberTest = String.valueOf(chosenImageNumber);
Log.d("MYAPP Choice Number", chosenImageNumberTest);
}
This runs through an array of 40 images and will be repeated one time. So every image will be shown two times (?).
That's the question:
When I use a pool of 40 images randomly for 80 picks, do I get every image two times (draw with cover), or is every try a new random out of those 40 images (draw without replacement), so the reult could be number 1 for 4 times and number 38 for 0 times? Is there an other function that prevents to such a behaviour?
Best,
tigercode
As I understand your code, you would NOT get every image twice, you would get some images multiple times and some images might not even come at all.
Don't use Random if you don't actually want Random. By the laws of probability you'd only have a chance of getting the same image twice, not a certainty.
You could use a boolean array to keep track of which numbers have already been used (if index n is true this means the number has already been taken e.g.).
Edit: The comment below from vims liu is right. It's much more efficient run time wise to define a list of indexes and shuffle the list.
So better use the following solutions, even if it won't make a big differences considering your numbers are quite small.
List<Integer> indexes = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //...
Collections.shuffle(indexes);
You can then iterate through the indexes list and use the current number as current index.
Sorry for answering late, and sorry for a beginner question, I'm new to android developing.
I changed my code (and write my comment what I understood it does:
#Override
public void onClick(View v)
Log.d("MYAPP", "Like-Button clicked");
// 1. Get the array of images in the images_primes XML-List AS int (number of every image in array)
TypedArray images = getResources().obtainTypedArray(R.array.images_primes);
// 2. Takes an array-list and shuffles it
List<Integer> indexes = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //...
Collections.shuffle(indexes);
// Great, it shuffles! ;-)
Log.d("MYAPP", indexes);
// 3. takes the number from the shuffled image list
int chosenImageNumber = (int) (indexes);
// 2. Old code: picks a number out of the image array from 1. / commented out
//int chosenImageNumber = (int) (Math.random() * images.length());
// 4. setImageResource to the random chosenImageNumber
imageViewMeasurement.setImageResource(images.getResourceId(chosenImageNumber, R.color.colorPrimaryDark));
images.recycle();
// Confirmation if the random generator picked a Number from the array
String chosenImageNumberTest = String.valueOf(chosenImageNumber);
Log.d("MYAPP Choice Number", chosenImageNumberTest);
}
Step 1: Open the list of images (as items), use it as array (1,2,3)
Step 2: Have a second number of arrays (possible to connect 1 and 2), SHUFFLE! :-)
Step 3: Here is my problem. If I got that right, I get a string-list from step 2, which numbers I can't use as Int (Error "Integer to int" won't work) -> result should be a number (?)
Step 4: Number from 3 should be used to pick out an image from list / array from 1.
I think, there is a thinking error on my side.
Thanks for your help in advance,
tigercode

Gerator Image Random

I have is how to generate random images without repeating , as an example driving in an array 15 images and 7 images to send imageview but that are not repeated .
int[] img={ R.drawable.ima1,R.drawable.ima2,R.drawable.ima3,R.drawable.ima4,R.drawable.ima5,R.drawable.ima6,R.drawable.ima7,R.drawable.ima8,R.drawable.ima9,R.drawable.ima10,R.drawable.ima11,R.drawable.ima12,R.drawable.ima13,R.drawable.ima14,R.drawable.ima15};
int [] game= new int[7];
Random numerRan = new Random();
for (int i=0;i<game.length ;i++)
{
int num= numerRan.nextInt(17);
int x= img[num];
game[i]=img[num];
}
img1.setImageResource(juego[0]);
img2.setImageResource(juego[1]);
img3.setImageResource(juego[2]);
img4.setImageResource(juego[3]);
img5.setImageResource(juego[4]);
img6.setImageResource(juego[5]);
img7.setImageResource(juego[6]);
img8.setImageResource(juego[7]);
When I press the button control images to the score rando the position that was generated . The problem I have is that images are repeated.
I am using 2 arrangements the first is to save all the images and the second keep the random images that will assign imageview .
Instead of using an int[] array, use a List<Integer> instead, such as an ArrayList<Integer>.
That way, you'll be able to use Collections#shuffle(), which will have the desired effect. It'll randomly permute your list, in a non-repeating way. All you'll have to do later is to iterate on that List.
For more info, please refer to the Collections documentation.
You can also convert that array to a List, like the following:
List<Integer> myList = Arrays.asList(img);
For more info about that, take a look at this question.

Create List of Remaining Values from List after generating Random numbers in android

I am creating "Jacks Or Better" game in android, in that i am generating 5 random numbers from list of 52 numbers and storing it to a list now i want to store remaining 47 numbers in other list so that i can again generate random numbers from the list of remaining numbers. i did following code,
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
while (true) {
Integer next = rng.nextInt(52);
if (!generated.contains(next)) {
generated.add(next);
openCards.add(CardArray.get(next));
break;
}
}
}
The above code is for generating 5 random numbers and storing it into a list but i don't have any how to store remaining 47 numbers into other list.
please help me.
You probably want SecureRandom instead.
Reimplement CardArray as a CardSet and remove from it as you "pull" the cards. You can add cards back to the set or you can simple clone the CardSet before use depending on how you want to optimize space vs compute.

Android: Getting a count of the visible children in a listview

Is there are way to get a count of the number of visible listview children?
I have a listview with info linked to a database that can change at any time. When the database is changed, I send out a broadcast notifying the ui class handling the list view. The child element relating to the changed data is then updated. I am achieving this by giving each listview item a tag, and then iterating over the listviews to find the row matching the tag from the broadcast.
I want to only iterate over the visible children. There is no need for me to manually update views that are not visible, as they will reflect the new data when they are created. I currently iterate from listView.getfirstVisiblePosition() to listView.getChildCount(). This is better than nothing, as I don't examine rows above the visible rows, but I don't want to examine the rows below them either.
I checked the android developers listView page and didn't find anything. Anyone know of a way I can get the count of visible children?
Thanks!
This is a quick way to get visible children count:
int visibleChildCount = (listView1.getLastVisiblePosition() - listView1.getFirstVisiblePosition()) + 1;
listView.getLastVisiblePosition(), is this what you are looking for? if not,
Iteration through child views...
int count = 0;
for (int i = 0; i <= listView.getLastVisiblePosition(); i++)
{
if (listView.getChildAt(i) != null)
{
count++; // saying that view that counts is the one that is not null,
// because sometimes you have partially visible items....
}
}
In reference to greg7gkb's comment above - just wanted to point out in case anyone is using this that it will make your count off by one. It should be
(listView1.getLastVisiblePosition() - listView1.getFirstVisiblePosition()) + 1
So, if the last visible was 8 and the first visible was 5, you would have (8-5)+1 = 4 showing:5,6,7, and 8.
It looks like A. Abiri got it right below.

Categories

Resources