Generate Unique Random Numbers with Range - android

I am beginner in android.
display random numbers of images, kids have to count number images
for answer generate 4 random choice, code is working fine
but sometimes app get hanged, can't optimize code.
Generate Answer
int[] answer = new int[4];
int count=0,random_integer;
while(count<=3){
random_integer = r.nextInt((imageCount+2) - (imageCount-2)) + (imageCount-2);
if(!exists(random_integer,answer)){
answer[count] = random_integer;
Log.d("answer","Array " + count + " = " + random_integer);
count++;
}
}
if(!exists(imageCount,answer)){
answer[r.nextInt(3 - 0) + 0] = imageCount;
}
Check Duplicate
public boolean exists(int number, int[] array) {
if (number == -1)
return true;
for (int i=0; i<array.length; i++) {
if (number == array[i])
return true;
}
return false;
}
Logcat
While generating 4 value it stopped
Thanks in advance

The answer array is initialized with zeroes. This means, a random_integer of 0 will not be accepted by the exists check.
In the case that imageCount is 2, the only four possible random answers are 0, 1, 2, 3. Since 0 is not accepted, the while loop will never terminate.
A similar problem appears if imageCount is smaller than 2.

Related

This code generates five columns with 6 childs but according to this code it should generate six columns. What is the problem?

This is the code which should generate 6 columns but instead generating 5.
Please point out any logical error in the code due to which desired output cannot be obtained.
sem1Data= new String[18];
sem2Data= new String[18];
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int stdA = 0, stdB = 0;
int counter = 0;
int colCounter = 1;
LabName = editText.getText().toString();
setLabRef = database.getReference("/" + LabName);
String colName;
for (int i = 0; i <6; i++) {
colName = "col" + colCounter;
//Toast.makeText(Activity1.this, colCounter, Toast.LENGTH_SHORT).show();
if ( colCounter%2 == 0) {
for ( ; stdB<18; stdB++)
{
if(counter<6)
{
setLabRef.child(colName).child(String.valueOf(counter)).setValue(sem2Data[stdB]);
counter++;
}
else
{
counter=0;
colCounter++;
break;
}
}
}
else {
for ( ; stdA<18; stdA++)
{
if (counter<6){
setLabRef.child(colName).child(String.valueOf(counter)).setValue(sem1Data[stdA]);
counter++;
}
else {
counter=0;
colCounter++;
break;
}
}
}
}
}
});
The expected result should be 6 generated columns in firebase but instead only five are generated.
firebase screenshot
In first loop change validation block to i <=6 or i < 7
for( int i = 0; i <= 6; i++)
UPD:
if(counter<7)
I'm not sure what is the purpose of your code but here is my opinion , it might help you to clear things out.
if you will add the line Log.d(TAG, "Log track : stdB : " + stdB +" stdA : " +stdA); At the beginning of your for-loop , you will see that the values of stdA and stdB never set to zero in they just keep increasing according to the logic of your code , actually the both end with the values :
Log track : stdB : 12 stdA : 18
now , if you will look at the case where colCounter = 5 , i = 4 the value of stdA is 12
.
Thats mean that the for-loop at the else section will run (colCounter mod 2 is not zero) only 6 times and by that will not execute:
else
{
counter=0;
colCounter++;
break;
}
and by that you are missing the increase of colCounter from 5 to 6 .

Android: Count strings and drawables

I'm circulating some drawable images (fx. I have a few images named image_1, image_2 etc.) as header images in a fragment. The images are loaded randomly as I hardcode the number of images available for me, and generate a random index from 0 to this number.
mHeaderBackgroundImagesCount is a final:
private int getHeaderBackground() {
// Random index between 0 and mHeaderBackgroundImagesCount
Random rand = new Random();
int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1;
return getResources()
.getIdentifier("image_" + index, "drawable", getPackageName());
}
As hard coding anything isn't normally the way to go in correct programming, I therefore like to dynamically find out how many 'image_X' drawables I have and set it to mHeaderBackgroundImagesCount.
I would like to do the same with strings from the strings.xml resource file as I'm also circulating some strings on every page load.
Solution Update
This update is inspired by Lalit Poptani's suggestion below. It includes syntax corrections and optimizations and have been tested to work.
private int countResources(String prefix, String type) {
long id = -1;
int count = -1;
while (id != 0) {
count++;
id = getResources().getIdentifier(prefix + (count + 1),
type, getPackageName());
}
return count;
}
System.out.println("Drawables counted: " + countResources("image_", "drawable"));
System.out.println("Strings counted: " + countResources("strTitle_", "string"));
Note: This method assumes that the resources counted start with index 1 and have no index holes like image_1 image_2 <hole> image_4 etc. because it will terminate on first occasion of id=0 thus resulting a faulty count.
If you are sure that your list of drawables will be in a sequence of image_1, image_2,... and so on then you can apply below logic,
int count = 0;
int RANDOM_COUNT = 10; //which is more than your drawable count
for (int i = 1; i < RANDOM_COUNT; i++){
int id = getResources().getIdentifier("ic_launcher_"+i,
"drawable", getPackageName());
if(id != 0){
count = + count;
}
else{
break;
}
}
Log.e(TAG, "This is your final count of drawable with image_x - "+ count);
You use this logic because of there will be no drawable with any name as image_x then id will be 0 and you can break the loop
I am not sure if it's possible to dynamically get the number of resources or drawables.
A way to circumvent this issue is to use string arrays as resources in strings.xml.
e.g.
<resources>
<string-array name="foo_array">
<item>abc1</item>
<item>abc2</item>
<item>abc3</item>
</string-array>
int count = getResources().getStringArray(R.array.foo_array).length;

Android arraylist.get getting the wrong value using an index

I'm at my wit's end with this one! Here's some of my code:
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> indices;
int total = 10;
for(int c = 0; c < total; ++c)
{
score.add(c);
}
indices = new ArrayList<Integer>(total);
for(int c = 0; c < total; ++c)
{
indices.add(c);
}
Collections.shuffle(indices);
rando1 = indices.get(0);
int currentScore;
currentScore = score.get(indices.get(rando1));
Toast.makeText(getApplicationContext(),
"score location should be: " + rando1, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"score location is: " + currentScore, Toast.LENGTH_SHORT).show();
The toasts were to help me see what's going on. For some reason, no matter what I try, the rando1 and the currentScore will almost always be different numbers.
This is baffling me because I use rando1 on a number of other arrays (string arrays), and it always gets the correct items from the other arrays.
My question is why doesn't this get the same index item (the integer at whatever index) from the integer array as it does from the other string arrays. I've tried isolating just this code. I've tried changing various things. I've done a lot of testing. And the searches don't turn up anything too specific (but I've tried what I found there as well).
Desired output of the toasts: "score location should be: 3", "score location is: 3"
Actual output: "score location should be: 3", "score location is: 5" (replace 5 with any other number, because there's never a set pattern between what it should be and what it is).
Use the following code to get a random element ArrayList.
Random r = new Random();
currentScore = score.get(r.nextInt(score.size()))
If you want to the output, as you have, then change the following line:
currentScore = score.get(rando1);

String Multiline - Android

i got this issue and i don't know how to solve it. Here is the problem:
1 - i have a data in my database who i split into a strings[] and then i split this strings[] into another 2 strings[] (even and odd lines). Everything works fine but when i want to join all the lines into a single String i got a multi line string intead of a single line. Someone can help me?
data
abcdef//
123456//
ghijkl//
789012
code:
String text = "";
vec1 = data.split("//"); //split the data
int LE = 0;
for (int a = 0; a < vec1.length; a++) { //verify how many even and odds line the data have
if (a % 2 == 0) { //if 0, LE++
LE++;
}
}
resul1 = new String[LE];
int contA = 0, contB = 0;
for (int c = 0; c < resul1.length; c++) {
if (c % 2 != 0) {
text += " " + resul1[c].toLowerCase().replace("Á","a").replace("Ã","a").replace("ã","a").replace("â","a").replace("á","a").replace("é","e").replace("É","e")
.replace("ê","e").replace("í","i").replace("Í","i").replace("ó","o").replace("Ó","o").replace("õ","o").replace("Õ","o").replace("ô","o").replace("Ô", "o")
.replace("Ú","u").replace("ú","u").replace("ç","c").replace("_","").replace("<","").replace(">","");
contA++;
}
}
And the String looks like
abcdef
ghijkl
instead of
abcdefghijkl
You should use replaceAll() method.
text.replaceAll("\\r\\n|\\r|\\n", ""); // the method removes all newline characters

Displaying values to a TextView

hi i have problem in displaying a value into my TextView..
For example i will input 1,2,3,4 then i like to display the output in this manner in my TextView..How can i do that? please help me, thank you in advance
1 appeared 1 times
2 appeared 1 times
3 appeared 1 times
4 appeared 1 times
here's my code:
String []values = ( sum.getText().toString().split(","));
double[] convertedValues = new double[values.length];
Arrays.sort(convertedValues);
int i=0;
int c=0;
while(i<values.length-1){
while(values[i]==values[i+1]){
c++;
i++;
}
table.setText(values[i] + " appeared " + c + " times");
c=1;
i++;
if(i==values.length-1)
table.setText(values[i] + " appeared " + c + " times");
Make your textView to support multipleLines and after that create in code a StringBuffer and append to it the results, something like
resultString.append(result).append(" appeared").append(c).append(" times\n");
after that you set text for textView like:
textView.setText(resultString.toString());
Here is the idea :
// this is test string, you can read it from your textView
String []values = ( "2, 1, 3, 5, 1, 2".toString().split(","));
int [] intValues = new int[values.length];
// convert string values to int
for (int i = 0; i < values.length; ++i) {
intValues[i] = Integer.parseInt(values[i].trim());
}
// sort integer array
Arrays.sort(intValues);
StringBuilder output = new StringBuilder();
// iterate and count occurrences
int count = 1;
// you don't need internal loop, one loop is enough
for (int i = 0; i < intValues.length; ++i) {
if (i == intValues.length - 1 || intValues[i] != intValues[i + 1]) {
// we found end of "equal" sequence
output.append(intValues[i] + " appeared " + count + " times\n");
count = 1; // reset count
} else {
count++; // continue till we count all equal values
}
}
System.out.println(output.toString()); // prints what you extected
table.setText(output.toString()); // display output

Categories

Resources