Android: Check Array for a number Random - android

I hope you can help me.
I make a game like 4Pics1Word.
I want to load the Level Randomly, I want a loop which generate a Random number from 0 to 10, and then check if the generated number is the first time loaded.
If yes write it in an array and end the loop.
If the number is not the first time loaded, generate a new random number and check it again until it is not used.
For example this is my code (don´t work right):
Boolean usedImageSet = false;
for (int t = 0; t <= usedImages.length; t++) {
if (usedImageSet == false) {
StringBuilder sb = new StringBuilder();
sb.append(currentQuestion);
String used = sb.toString();
if (usedImages[t] != null) {
System.out.println("usedImage" + t
+ " = not Null, it is" + usedImages[t]);
if (usedImages[t].equals(used)) {
System.out.println("String: "
+ used
+ " found it here: [" + t + "]");
currentQuestion = (int) (Math.random() * 10);
}else {
System.out.println("String: "
+ used + " not found");
}
}
if (usedImages[t] == null) {
usedImages[t] = used;
System.out.println("useddImage[" + t + "]: "
+ usedImages[t]);
System.out.println("usedImage" + t + " is Null, change to"
+ usedImages[t]);
usedImageSet = true;
}
}
}
PS:
Thank you all, I think the solution from Oren is the best
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
But how can I save the list if I close the game?

You would probably be much better off creating a List of the numbers you want and then calling Collections.shuffle() on that list.
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}

int oldnumber = 5;
int newnumber = new Random().nextInt(10);
while (newnumber == oldnumber){
newnumber = new Random().nextInt(10);
}

Related

How to find similar values in two arrays and pass to the new position

I searched for my problem on StackOverflow. But This problem is not the same as them. I have two arrays. The first array has too many words. The second array has custom words that user inputs. My purpose is; I want to search for similar values but when I find the similar value, It passes to next value of the second array. How can ı do it?
Example ;
first array elements; all words of one language
second array elements ; " cat ", "dog"
result array; " category", "dogde"
Here is my code ;
for (String s: second_array
) {
for (int i = 0; i < first_array.size(); i++) {
if (first_array.get(i).toString().contains(s)){
result_array.add(first_array.get(i).toString());
}
}
}
for (int j = 0; j <result_array.size() ; j++) {
Log.i(TAG, "onCreate: " + result_array.get(j) + " "+ result_array.size());
}
if This code runs , I get too many values.
You need to break the for of first_array, but this only get the first similar word:
for (int i = 0; i < first_array.size(); i++) {
if (first_array.get(i).toString().contains(s)){
result_array.add(first_array.get(i).toString());
//Add this line
break;
}
}
EDIT: To put the "There is no such word" if not found a similar word, your code it should look like this:
for (String s: second_array) {
boolean isFound = false;
for (int i = 0; i < first_array.size(); i++) {
if (first_array.get(i).toString().contains(s)){
result_array.add(first_array.get(i).toString());
isFound = true;
break;
}
}
if(!isFound) result_array.add("There is no such word");
}
for (int j = 0; j <result_array.size() ; j++) {
Log.i(TAG, "onCreate: " + result_array.get(j) + " "+ result_array.size());
}

Filter number from Array of string and get the index of last two greater number in android

I have a ArrayList that has value like [Value,Sum3,121,data8input,in:21::7,7.00,9.01] and I want to extract only number as the output should be like this [3,121,8,21,7,7.00,9.01] and then have to rearrange ascending and then get the index of last two number as result will be [21,121].
My tried code below,
for (int i = 0; i < arrayString.size(); i++) {
Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher(arrayString.get(i).getvalue);
numbers.addAll(m);
for (int j = 0; j < numbers.size(); j++) {
Log.d("REMEMBERFILTER", allCollection.get(i).getTextValue());
}
}
}
do something like this, though it is not exactly memory efficient as I am using another list.
ArrayList<String> tempList = new ArrayList<>();
for (int i = 0; i < yourArrayList.size(); i++) {
tempList.add(yourArrayList.get(i).replaceAll("[^0-9]", ""));
}
//Arrange in ascending order
Collections.sort(tempList);
//Also try to remove those indexes which has only letters with
tempList.removeAll(Arrays.asList("", null));
for (int i = 0; i < tempList.size(); i++) {
Log.d("+++++++++", "" + tempList.get(i));
}
//You can get the last two or any element by get method of list by //list.size()-1 and list.size()-2 so on
This is a way to do it, finalArray has the 2 numbers you want:
String[] str = new String[] {"Value", "Sum3", "121", "data8input", "in:21::7", "7.00,9.01"};
StringBuilder longStringBuilder = new StringBuilder();
for (String s : str) {
longStringBuilder.append(s).append(" ");
}
String longString = longStringBuilder.toString();
String onlyNumbers = " " + longString.replaceAll("[^0-9.]", " ") + " ";
onlyNumbers = onlyNumbers.replaceAll(" \\. ", "").trim();
while (onlyNumbers.indexOf(" ") > 0) {
onlyNumbers = onlyNumbers.replaceAll(" ", " ");
}
String[] array = onlyNumbers.split(" ");
Double[] doubleArray = new Double[array.length];
for (int i = 0; i < array.length; i++) {
try {
doubleArray[i] = Double.parseDouble(array[i]);
} catch (NumberFormatException e) {
e.printStackTrace();
doubleArray[i] = 0.0;
}
}
Arrays.sort(doubleArray);
int numbersCount = doubleArray.length;
Double[] finalArray;
if (numbersCount >= 2) {
finalArray = new Double[]{doubleArray[numbersCount - 2], doubleArray[numbersCount - 1]};
} else if (numbersCount == 1) {
finalArray = new Double[]{ doubleArray[0]};
} else {
finalArray = new Double[]{};
}
for (Double number : finalArray) {
System.out.println(number);
}

How can i add as well as remove layout pragmatically in android?

I want to work as AutoCompleteTextview. But I am not using auto complete text view in my project. I have used edit text and taking it the value for sorting the value of adapter using those values of adapter I am creating a dynamic button. But actually, I want to delete dynamically created button. When a user enters new value in edit text at that case it sorts new value in adapter according to the button has to created. But, my problem is that dynamically created button does not get deleted when a user enters new text on edit text view. It has to looking like this:
if (!s.equals("")) {
final String query = s.toString().trim();
filteredTags.clear();
((ViewManager) btnTag.getParent()).removeView(btnTag);
for (int i = 0; i < TagArray.size(); i++) {
final String tagName = TagArray.get(i).gettagName();
if (tagName.contains(query)) {
filteredTags.add(TagArray.get(i));
}
}
count1 = filteredTags.size();
layout = (LinearLayout) dialog.getCustomView().findViewById(R.id.layoutTags);
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical"
layout.setWeightSum(1);
float rowneed = ((float) count1 / 5);
k = 0;
for (int i = 0; i < ceil(rowneed); i++) {
row1 = new LinearLayout(getContext());
row1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
/* layout.setVisibility(View.VISIBLE);
row.setVisibility(View.VISIBLE);*/
for (int j = 0; j < 5; j++) {
btnTag = new Button(getContext());
btnTag.setHeight(15);
btnTag.setWidth(0);
btnTag.setMinimumWidth(155);
btnTag.setMinimumHeight(135);
mTagList1 = new ArrayList<>();
if (k < count1) {
btnTag.setText(filteredTags.get(k).gettagName());
btnTag.setId(k);
k++;
btnTag.setVisibility(View.VISIBLE);
} else {
btnTag.setVisibility(View.INVISIBLE);
}
Log.e("count", " " + k + " " + count1 + " " + ceil(rowneed) + " " + edtTag.getText().toString());
btnTag.setTextSize(7);
btnTag.setGravity(0);
row1.addView(btnTag);
}
layout.addView(row1);
}
for (int btnId = 0; btnId < filteredTags.size(); btnId++) {
btnTag = (Button) dialog.getCustomView().findViewById(btnId);
final int finalId1 = btnId;
btnTag.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TagNameArray.add(new Tags(filteredTags.get(finalId1).gettagId(), filteredTags.get(finalId1).gettagName()));
// Log.e("button","Button clicked index = " + finalId +" "+ TagArray.get(finalId1).gettagName()+" "+TagNameArray.size());
}
});
}
}
Add this line of code :
layout.removeAllViews();
layout.invalidate();
row.removeAllViews();
row.invalidate();
This might help you, give me a feedback for what you got, wish I help you
set a dynamic tag for btnTag for example
btnTag.setTag(DynamicTagInt++);
and then
row1.removeView(btnTag.findViewById(DynamicTagInt));
//DynamicTagInt= the desired button that you want to delete
or by the ID of the button for example
row1.removeView(btnTag.findViewWithTag(k));

android multichoice listview error Exception

for choosing favorite contact ,i load all contact inside a list view and declare my adapter like below :
ArrayAdapter<String> cnct_List_Adapter =new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_multiple_choice,info);
and for show result i use this codes :
try
{
SparseBooleanArray a = LvPopupContacts.getCheckedItemPositions();
String my_sel_items="";
for(int i = 0; i < LvPopupContacts.getCount() ; i++)
{
if (a.valueAt(i))
{
/*
Long val = lView.getAdapter().getItemId(a.keyAt(i));
Log.v("MyData", "index=" + val.toString()
+ "item value="+lView.getAdapter().getItem(i));
list.add(lView.getAdapter().getItemId((a.keyAt(i))));
*/
my_sel_items = my_sel_items + ","
+ (String) LvPopupContacts.getAdapter().getItem(i);
}
}
Toast.makeText(getActivity(),String.valueOf(a.size()), 0).show();
Log.v("Contacts :" ,my_sel_items);
} catch (Exception e) {
Log.v("e Error" ,e.toString());
}
now , when i use this in emulator it work rightly , but when it test in Device return e Exception
Exception: java.lang.ArrayindexOutOfBoundsException length=13;index=13
remember , my Device have about 220 concacts.
your bug is here:
for(int i = 0; i < LvPopupContacts.getCount() ; i++)
"a" array contains all of checked items but you loop over all LvPopupContacts so change it to
for(int i = 0; i < a.size() ; i++)

Android/Java String Concatenation with Unwanted "\n"

I am writing an Android program that parses data from the Translink API web page. The program works, but I am having an issue with the data that I am storing. It seems that each time the program loops, a "\n" is added to the String itself. Here is the code itself:
private class DownloadWebpageText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String...urls) {
// params comes from the execute() call: params[0] is the url.
try {
// Test Code
for(int h=0; h<prev_stops.size(); h++) {
Document doc = Jsoup.connect("http://api.translink.ca/rttiapi/v1/stops/" + prev_stops.get(h) + "/estimates?&timeframe=120&apikey=XMy98rbwFPLcWWmNcKHc").get();
nextbuses = doc.select("nextbus");
schedules = doc.select("schedules");
String bus_times = "";
temp += "Arrival Times for Stop " + prev_stops.get(h) /*+ " (Previous Stop: " + prev_stop + "): \n" + "\nPrevious Stops: " + prev_stop*/;
for(int i=0; i<nextbuses.size(); i++) {
temp += parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp = temp.concat(", ");
}
temp = temp.concat(parseData(expectedleavetime.get(j).toString()));
}
temp += "\n";
}
temp += "\n";
}
return "";
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
Where the parseData() function is just this:
public String parseData(String input) {
int beg = input.indexOf(">") + 1;
int end = input.lastIndexOf("<") - 1;
return input.substring(beg, end);
}
Here is the output from the console:
Arrival Times for Stop 56549
402:
4:10pm,
4:40pm,
5:10pm,
5:40pm
What I want the output to be like is this:
Arrival Times for Stop 56549
402: 3:40pm, 4:10pm, 4:40pm, 5:10pm
403: .....
You could use an ArrayList, which you define outside all for-loops
// Define our ArrayList
ArrayList<String> allStops = new ArrayList<String>();
// Define a string that holds information about the current stop
String currentStopInfo = "Arrival Times for Stop " + prev_stops.get(h);
for(int i=0; i<nextbuses.size(); i++) {
// Define a temporary String that holds all the times for a specific bus
String temp_2 = parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp_2 += ", ";
}
temp_2 = temp_2.concat(parseData(expectedleavetime.get(j).toString()));
}
// Add the string that holds info for one bus to our Array
allStops.add(temp_2);
}
And when you want to print all of your strings(all of your stops for each bus)(every string contains information about one bus) you just do:
//Print the line that holds the current stop information
System.out.println(currentStopInfo);
for(String x : allStops) {
// Loop through our ArrayList, and print the information
System.out.println(x);
}

Categories

Resources