Make a random array and print it one by one - android

I want to make a random array and print it over one by one. But I need to print all of it without make any duplicate. I've try to adding it into list but it seems fail.
My Code :
String quest1 = "5x5#5*10#8/4"
String[] quest = quest1.split("#");
ArrayList <String> question = new ArrayList<String>();
question.add(quest[0]);
question.add(quest[1]);
question.add(quest[2]);
Random rand = new Random();
int id = rand.nextInt(question.size());
System.out.println(question.get(id));
question.remove(id);
I want to print 5x5 5*10 8/4 but in random order and I want to print each of it without print it again.

Make a key value 2d object array or a hashmap of integer and boolean. Against all the numbers keep the boolean value false (implying that the number hasn't been printed yet ). Then generate a random number using Random class. Let this be n. Calculate n%array.length. Now see if for this new index whether you have true/false in the 2dArray/hashmap. If false then print the corresponding number and else don't print anything. I hope it's clear to you

Try following code
ArrayList<Integer> questionPrinted = new ArrayList<Integer>();
int i=0;
while (question.size()>0) {
Random rand = new Random();
int id = rand.nextInt(question.size());
if (questionPrinted.size() > 0) {
if (questionPrinted.contains(id)) {
while (!questionPrinted.contains(id))
id = rand.nextInt(question.size());
}
}
questionPrinted.add(i);
System.out.println(question.get(id));
question.remove(id);
i++;
}

Related

random array android from string

I want to assign the numbers of my array at random to the keys key0, key1 etc ..
I'm using this code where in the first two lines I have my array, and with setText I assign the number. but i can't get it to work ..
String[] shuffledKeys = {"0","1","2","3","4","5","6","7","8","9"};
Random random = new Random(); // or create a static random field...
String randString = shuffledKeys[random.nextInt(shuffledKeys.length)];
key0.setText(shuffledKeys.get(0));
key1.setText(shuffledKeys.get(0));
key2.setText(shuffledKeys.get(0));
key3.setText(shuffledKeys.get(0));
key4.setText(shuffledKeys.get(0));
key5.setText(shuffledKeys.get(0));
key6.setText(shuffledKeys.get(0));
key7.setText(shuffledKeys.get(9));
key8.setText(shuffledKeys.get(8));
key9.setText(shuffledKeys.get(9));
String[] keys = {"0","1","2","3","4","5","6","7","8","9"};
Set<String> addedKeys = new HashSet<String>();
List<String> shuffledKeys = new ArrayList<String>();
Random random = new Random();
while (shuffledKeys.size() < keys.length) {
int index = Math.abs(random.nextInt() % keys.length);
if (!addedKeys.contains(keys[index])) {
addedKeys.add(keys[index]);
shuffledKeys.add(keys[index]);
}
}
/// Shuffled keys should now actually be "shuffled"
key0.setText(shuffledKeys.get(0));
key1.setText(shuffledKeys.get(1));
key2.setText(shuffledKeys.get(2));
key3.setText(shuffledKeys.get(3));
key4.setText(shuffledKeys.get(4));
key5.setText(shuffledKeys.get(5));
key6.setText(shuffledKeys.get(6));
key7.setText(shuffledKeys.get(7));
key8.setText(shuffledKeys.get(8));
key9.setText(shuffledKeys.get(9));

How to change Random in to Sequence Order

I am developing word scramble android app. I want to display the String of word in Sequence order but in below code it get random word from the dictionary. My question is how to change my code to get words from Dictionary in Sequence Order?
String[] dictionary=
{"One","Server","Terminate","Analyze","Finish","Start","Wonder","Slow"};
r = new Random(System.currentTimeMillis());
newGame();
// shuffle algorithm
private String shuffleWord(String word){
List<String> letters = Arrays.asList(word.split(""));
Collections.shuffle(letters);
String Shuffled="";
for (String letter : letters ){
Shuffled += letter;
}
return Shuffled;
}
private void newGame(){
// get random word from dictionary
currentWord= dictionary[r.nextInt(dictionary.length)];
// show the shuffled word
tv_word.setText(shuffleWord(currentWord));
// clear the textfield
et_guess.setText("");
// switch buttons
b_new.setEnabled(false);
b_check.setEnabled(true);
}
}
Actually you pick your word with a random position
r = new Random(System.currentTimeMillis());
using an integer random from 0 to ArrayOfWords lenght.
currentWord= dictionary[r.nextInt(dictionary.length)];
Why you dont try to make a counter instead?
int r = 0;
while (r<dictionary.length()) {
currentWord = dictionary[r];
r++;
}
Or I don't understand your answer. But there is the pseudo of what I understand.

Looping with while loop while fetching records from database is not working properly

Im trying to iterate two arrays simultaneously as follows,
First if countriesIterator has got next element, domain Iterator will be looped.
CountryIterator has got two elements and domain iterator might contain n elements.
when Im looping the domainIterator, Im populating an arraylist with values that I have looped.
and when the loop reaches the country iterator, Im putting the arraylist within a hashmap.
Iterator<String> domainIterator = selectedDomains.iterator();
Iterator<String> countriesIterator = selectedCountries.iterator();
filteredComplianceCount = new ArrayList<Integer>();
inProgressComplianceCount = new ArrayList<Integer>();
delayedComplianceCount = new ArrayList<Integer>();
nonComplianceCount = new ArrayList<Integer>();
//Looping Countries
while (countriesIterator.hasNext()) {
String countryKey = countriesIterator.next();
Country country = aparjithaDb.getCountryId(countryKey);
//Looping Domains
while (domainIterator.hasNext()) {
Domain domain = aparjithaDb.getDomain(domainIterator.next());
int domainId = domain.getDomainId();
int countryId = country.getCountryId();
//fetch datas from db based on country and domain id/
List<ChartData> allChartCDCounts = db.getAllChartCDCounts(countryId, domainId);
//iterate the list to get the count values
for (ChartData al : allChartCDCounts) {
int complied_count = al.getComplied_count();
int delayed_compliance_count = al.getDelayed_compliance_count();
int not_complied_count = al.getNot_complied_count();
int inprogress_compliance_count = al.getInprogress_compliance_count();
//add the count values to an arraylist
filteredComplianceCount.add(complied_count);
delayedComplianceCount.add(delayed_compliance_count);
inProgressComplianceCount.add(inprogress_compliance_count);
nonComplianceCount.add(not_complied_count);
}
}
//put the arraylist with in hashmap
compMap.put(countryKey, filteredComplianceCount);
delayedCompMap.put(countryKey, delayedComplianceCount);
inProgMap.put(countryKey, inProgressComplianceCount);
nonCompMap.put(countryKey, nonComplianceCount);
}
The problem with my code is that, the key of hashmap remains unique (The keys are two different country names after adding values) but the values remains the same for both keys. The domain Iterator is being invoked only once but it should have been invoked twice because there are two different keys. How can I sort this out?
by the first iteration of countriesIterator you have your domainIterator reached the end. You probably should include your Iterator<String> domainIterator = selectedDomains.iterator(); into countriesIterator loop so it started to iterate again from the beginning on the each iteration of countriesIterator.

Random call name in Android

How to make a 'random call' name in List in database sqlite. How can I call one by one without repeating its value. My layout is one textview, If I click the name it will change. Thank you.
Untested, but should be fine:
Query your database, then use the returned Cursor to populate a LinkedList with whatever options you would like.
LinkedList list = new LinkedList();
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
list.add(cursor.getString(etc...);
}
}
Create a Random object, and use it to select and remove a random element from list each time:
Random rnd = new Random();
//The below section could be repeated on, for instance, a button click.
int randomValue = rnd.nextInt(list.size());
String result = list.get(randomValue);
list.remove(randomValue);
Each time an element is removed, the LinkedList will adjust in size to accommodate it, so no results will be repeated.
#PPartisan not working.
I add button to test the result from textview. 1 row only detected when I pressed back and back to activity the result is the same value. I clicked the button did not work.
rnd = new Random();
randomValue = rnd.nextInt(list.size());
result =list.get(randomValue).toString();
list.remove(randomValue);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
tv.setText(result);
}
});

Generating a random number outside of the oncreate method

I'm trying to set up my activity so that I can generate a set of random numbers from methods outside of my onCreate method. Here's how my activity is set up...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.optionOne();
this.optionTwo();
this.optionThree();
}
public void optionOne() {
// generate a random number here
int random = Math.random();
// generate more random numbers and do more stuff here
}
The problem is, any random numbers I generate outside of the onCreate method are considered 'static' and the numbers are always 0. If I generate numbers inside the onCreate method, it of course works just fine. How can I fix this?
private static Random ranGenerator=new Random();
Declare it as a member of the class.
then just call ranGenerator.nextInt() any time to get it.
To generate random number use,this will create random between specific range
public void optionOne() {
var=(int)(Math.random() * (max - min) + min) //math.random will return integer values
// use your var wisely
}
use
Random rand = new Random();
int random = rand.nextInt();
or
int random = rand.nextInt(range);
According to doc here
Math.random() Returns a pseudo-random double n, where n >= 0.0 && n < 1.0.
This will help you to create an array list of non repeating random numbers
ArrayList<Integer> indexArray = new ArrayList<Integer>();
for (i = 0; i < 202; ++i) {
number.add(i);
// number.add(num);
}
Collections.shuffle(number);

Categories

Resources