[Android]How to get item number(position) from a String[] - java

I have a String[] that contains number of strings, what I'm trying to do is set a ProgressBar's progress according to which string is used.
For example, I have already determined number of strings and set max progress of progress bar accordingly; here is the list:
"zero one two three four five six seven eight nine...."
..
String[] cpu0freqslist = cpu0freqs.split("\\s");
countcpu0 = cpu0freqslist.length;
..
ProgressBar cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1);
cpu0progbar.setMax(countcpu0);
But now I need to set the progress of progressbar according to the item that is used, and I don't know how to get item position.
So if I want to set a progress bar to the position of item five (in this case it would be 6) how can I do that - how can I get the position of item five?

essentially what you're looking for is a indexOf(...) ...
since arrays don't have it, you'll have to search thru it to find the desired string. so something like this (feel free to optimize)
public int indexOfString(String searchString, String[] domain)
{
for(int i = 0; i < domain.length; i++)
if(searchString.equals(domain[i]))
return i;
return -1;
}
Then again, if you dynamically fetch your String[] data, it would be wiser to use an ArrayList and just invoke list.indexOf(myString);

You can use the Arrays utility class:
List<String> list = Arrays.asList(new String[] {"First", "Second", "Third"});
int index = list.indexOf("Second"); // 1

cpu0freqslist[5]
Does this help you?

Ok let me break your query into parts...
String[] arr = {"First","Second","Third"}; // String array with 3 elements
for(int i=0 ; i<arr.length ; i++){
int j = i ; // Position of the element
String s = a[i] ; // Element Itself
System.out.println("The "+i+" element is "+s);
}

Related

Compare elements from an ArrayList

I have a small problem, I want to go through a list and compare two objects of the array. Each object has 3 elements, I use a StringTokenizer to be able to remove the separator, so each object has 3 elements. I would like to know how to make a method that gets the third element of each object and compare them. And if that element is less than another delete that element and the 2 before it.
I tried to make them with an iterator but I wouldn't know very well that it started from the 3 element and increased the position by 3.
Iterator<Integer> it = lisM.iterator();
int num;
while (it.hasNext()){
num = it.next();
System.out.println(num);
}
Is --> if, I was wrong to put it in the picture
This only answers part of your question. I could not understand the question completely, please edit it and I can edit my answer.
You should not remove items from a list whilst in a for loop, therefore you can, for example, create another boolean list with the same size divided by 3 and just fill it with true Booleans then set the position divided by 3 to false if you want to delete the three items. Then you can create a new list, iterate over the boolean list and add 3 "Objects" which are actually Strings (thanks #JB Nizet) at a time, every time the boolean list element is true. When it is false you just don't add the elements and by doing so you are practically deleting the two elements before that element together with that element.
You casted a String to an int, that does not work you have to parse the Strings.
I corrected some of your code and added the boolean list here:
ArrayList<String> lisM = new ArrayList<>(); // here I initialise the list as an array list with strings.
ArrayList<Boolean> booleanList = new ArrayList<>();
for (int i = 0; i < lisM.size() / 3; i++) {
booleanList.add(true);
}
for(int i = 3; i < lisM.size();i+=3) {
int m = Integer.parseInt(lisM.get(i)); // here I changed the casting to parsing and moved it out of the for loop, there is no need to initialize it again every single time since you do not change it in the second for loop.
for (int j = 6; j < lisM.size(); j += 6) {
int m1 = Integer.parseInt(lisM.get(j));// here I changed the casting to parsing again.
if (m > m1) { // this makes no sense here because you are going over all of the elements of the list and comparing them to all of them. But I kept it here for the sake of example.
booleanList.set(i/3,false);
}
// if you want to go over the whole list you will have to clear the list and start over again for every element.
}
}
and here is how you could create the new list without the elements you do not want:
ArrayList<String> newLisM = new ArrayList<>();
for (int i = 0; i <booleanList.size(); i++) {
if(booleanList.get(i))
for (int j = 0; j < 3; j++) {
newLisM.add(lisM.get(i+j));
}
}

How to change an element in a list of lists Java

This is a peice of my code, i am making a grid of 5x5 with random colors set to each section. I need to set the specified y_loc and x_loc in the list to the color randomly picked except i have not been able to find out how. It should be the second last line that is not operating as id like. I understand that i could do this in much much longer code but it would be nice to do it in less.
//making the map
ArrayList<ArrayList<String>> fullmap = new ArrayList<ArrayList<String>>();
ArrayList<String> y_row_0 = new ArrayList<String>();
ArrayList<String> y_row_1 = new ArrayList<String>();
ArrayList<String> y_row_2 = new ArrayList<String>();
ArrayList<String> y_row_3 = new ArrayList<String>();
ArrayList<String> y_row_4 = new ArrayList<String>();
//adding each row
fullmap.add(y_row_0);
fullmap.add(y_row_1);
fullmap.add(y_row_2);
fullmap.add(y_row_3);
fullmap.add(y_row_4);
Random rn = new Random();
//loop to randomly pick colors then set them to their destined locations
for (int y_loc = 0; y_loc < 6; y_loc++){
for (int x_loc = 0; x_loc < 6; x_loc++){
colorPicked = false;
while (!colorPicked){
int ranNum = rn.nextInt();
if (ranNum ==0){
if (redTot < 5) {
redTot += 1;
fullmap.set(y_loc).set(x_loc, "Red"));
colorPicked = true;
Since you have lists in list here, to set something at a specific location, you'll have to get the inner list and then perform the set on it.
The following should work:
fullmap.get(y_loc).set(x_loc, "Red"));
Also, since you seem to always have a 5x5 matrix, I'd recommend using a double array instead. That'd make that line:
fullmap[x_loc][y_loc] = "Red";
You should have something like this:
fullmap.get(y_loc).set(x_loc, "Red"));
Notice the "get". You are "getting" the list at the y location, which returns an array list, then calling "set" against that array list to set the actual value in the index of the "x_loc" value.
You need to make a couple of changes:
While declaring the sub lists, you need to make sure they have 5 empty/null elements. Otherwise set will throw IndexOutOfBoundsException. E.g. you need to declare the lists like this:
ArrayList<String> y_row_0 = Arrays.asList(new String[5]);//Assuming it will have 5 elements
While setting the element, you first need to get the corresponding sub list, e.g. the following needs to be changed from:
fullmap.set(y_loc).set(x_loc, "Red"));
to
fullmap.get(y_loc).set(x_loc, "Red"));
Others have already discussed the indexing issue. Apart from that, I believe that your conditionals may not be executing as you expect. nextInt() will return a reasonable uniform random number in the range of -2147483648 to 2147483647. You have a 1/2^64 chance of getting a 0. Reduce the random number range to something more reasonable. For example, nextInt(10) will return a random number between 0 and 9.
Furthermore, if the probability is too low, you will not get 5 reds all the time. To guarantee 5 picks and for the sake of computational efficiency, it is better to randomly pick array indices and evaluate whether a color is set or not, such as the following pseudo-code
int redTot = 0;
while ( redTot < 5 ) {
int r = rn.nextInt( 5 );
int c = rn.nextInt( 5 );
String color = fullmap.get( r ).get( c );
if ( color == null ) {
fullmap.get( r ).set( c, "Red" );
redTot++;
}
}

Can you remove an element from an array by placing it at the end of the array and decreasing the size of the array?

for(int i = 0; i < bag.length; i++)
{
if(bag[i].equals(a))
{
tmp = bag[i];
bag[i] = bag[bag.length-1];
bag[bag.length-1] = tmp;
numElements--;
break;
}
}
The goal of this is to find an object in the array and then remove it? is it possible??
Changing the length of an array is not possible. Recall that array is a static data structure whose size is determined before hand. Increasing or decreasing is not supported in this data structure. The fact that one has to increase or decrease the size depending on the usecase means that they have picked up the wrong data structure. They should perhaps go with an ArrayList.
Anyway, coming back to your question, you can simulate the 'size decrease' by maintaining a variable which you let track the array index and decrease the size of this variable. This lets you give the impression of shrinking the array.
The code you have provided does the same. Note however, that you should be using this modified index to track the contents of your array.
for(int i = 0; i < bag.length; i++)
{
if(bag[i].equals(a))
{
tmp = bag[i];
bag[i] = bag[bag.length-1];
bag[bag.length-1] = tmp;
numElements--;
break;
}
}
Whenever a particular bag at a given index equals to the item under question i.e., 'a', we swap elements so that the current bag element to be removed moves to the last and also we reduce the size of our new index - numElements by 1 to simulate this.
If you have the full code with you, please consider adding the following snippet at the end of that program to understand this more:
// Simulation of the array shrinking.
for(int i = 0; i < numElements; i++)
{
System.out.println( bag[i] );
}
// Movement of uninteresting elements to the end of the array.
for(int i = 0; i < bag.length; i++)
{
System.out.println( bag[i] );
}
It's not possible to change the length of an array. You can overwrite the element you wish to remove with the last element of the array and then copy the first bag.length - 1 elements of your array to a new array whose length is bag.length - 1.
for(int i = 0; i < bag.length; i++) {
if(bag[i].equals(a)) {
bag[i] = bag[bag.length-1];
bag = Arrays.copyOf (bag, bag.length - 1);
break;
}
}
public static String[] removeElements(String[] input) {
List<String> result = new ArrayList<String>();
String deleteValue = "somevalue";
for(String item : input)
if(!deleteValue .equals(item))
result.add(item);
return result.toArray(input);
}
This is one method you can fit this into your program.
You cannot decrease the size of an array. okay no problem! you can create your own data structure which supports that right?
Now, create a class named say MyArray with functions like increaseLenght(int) and decreseLength(int). Try it if you want to, will be fun for sure..
You cannot reduce the size of an array. Arrays are fixed length. What you can do is have a variable that indicates how many entries of the array you are using. This is what you are doing with numElements. The standard class ArrayList is implemented like this. The data is kept in an array and a private field size is used. With an ArrayList, when you remove an element, all the elements to the right are shifted left. However I also like your idea.
I would suggest 2 changes.
Make the last element null instead. If you are removing the element, why does it still need to be in the array?
Use numElements - 1 rather than bag.length-1 as the array could be bigger.
With these changes it becomes:
for(int i = 0; i < bag.length; i++)
{
if(bag[i].equals(a))
{
bag[i] = bag[numElements-1];
bag[numElements-1] = null;
numElements--;
break;
}
}

Most efficient way of combining elements of lists of items into sets of combinations?

Let's say we're giving a List of lists of some items, say Strings.
list 1: "a", "b", "c"
list 2: "d", "e", "f"
list 3: "1", "2", "3"
results: (a, d, 1), (a, d, 2), ... (c, f, 3)
(the real use case has nothing to do with strings and such, this is just a mock up)
I wrote a recursive method to do it, but I am not happy with it because it creates a lot of temporary sets that get tossed (yeah, I know object creation is cheap in java, usually fewer cpu instructions than a malloc in C (source: Java Concurrency in Action, p241), eden GC is cheap, blah blah blah. humor me :).
void combine(List<List<String>> itemLists, List<Set<String>> combinations, Set<String> partial) {
if (itemLists == null || itemLists.isEmpty()) return;
List<String> items = itemLists.get(0);
for (String s : items) {
Set<String> tmpSet = new HashSet<>(partial);
tmpSet.add(s);
if (itemLists.size() == 0) //termination test
combinations.add(tmpSet);
else
combine(itemLists.subList(1, itemLists.size()), combinations, tmpSet);
}
}
So, how would you go about this?
edit: To be clear, I do not want to create permutations. I want to create sets that are sizeof(list of lists) big.
What you're looking for is the "cartesian product."
If you're okay with using Sets instead of Lists, you can use Sets.cartesianProduct. There is still some garbage allocated as you iterate over the resulting Lists... but not nearly as much as other approaches.
(Note that as a common library method, it's been very exhaustively tested, so you can have a little more confidence in it than in pasting dozens of lines of code out of SO.)
FYI there has been a request for Lists.cartesianProduct as well, but I don't think anyone's working on it.
You want a list of all possible sets, containing exactly one value from each of the provided lists, assuming that the number of lists is variable and the size of those lists is also variable. Correct?
Something like this, then?
static List<Set<String>> combine(List<List<String>> itemLists)
{
// Calculate how many combinations we'll need to build
int remainingCombinations = itemLists.get(0).size();
for(int i=1; i<itemLists.size(); i++)
{
remainingCombinations *= itemLists.get(i).size();
}
List<Set<String>> allSets = new ArrayList<Set<String>>();
// Generate this combination
for (;remainingCombinations > 0; remainingCombinations --)
{
Set<String> currentSet = new HashSet<String>();
int positionInRow = remainingCombinations;
// Pick the required element from each list, and add it to the set.
for(int i=0; i<itemLists.size(); i++)
{
int sizeOfRow = itemLists.get(i).size();
currentSet.add(itemLists.get(i).get(positionInRow % sizeOfRow));
positionInRow /= sizeOfRow;
}
allSets.add(currentSet);
}
return allSets;
}
This is more efficient: Approach it the same way counting works (each "position" is one of your lists and each "digit" that can go in that position is an element of your list):
List<Set<String>> combine( List<List<String>> input ){
final int n = input.size();
int[] index = new int[n];
List<Set<Sting>> result = new List<>();
int position = 0;
while( position < n ){ // "overflow" check
// Add set to result.
Set<String> set = new HashSet<>();
for( int i=0; i<n; i++ )
set.add( input.get(i).get( index[i] ) );
result.add( set );
// Now the "hard" part: increment the index array
position = 0;
while( position < n ){
if( index[ position ] < input.get( position ).size() ){
index[position]++;
break;
}
else // carry
index[ position++ ] = 0;
}
}
return result;
}
(Not tested, might have some bugs, but the main idea is there).
In general, recursion is slower than iteration.

String[] array taking items out individually

I have a method that requires a String[] for some details but after putting these details in how do I get them out one by one?
new String[] otherDetails = {"100", "100", "This is a picture"};
now in the picture I want to set the first string as the height, the second as the width, and the third as a description.
You refer to an element of an array by its index, like this:
height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture
You use the index to get the values
height = otherDetails[0];
width = otherDetails[1];
description = otherDetails[2];
Extract The details from array as follows :
height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture
Then call your method MyFunction(String heigth,String width,String description);
The index comments are probably what you're looking for, but you can also iterate through the elements using a loop.
int arraySize = stringArray.length;
for(int i=0; i<arraySize; i++){
if(i==0)
height = stringArray[i]; //do stuff with that index
}
This isn't the "right" approach for your particular problem, but I think it might help you understand ways that you can access items inside an array.
Side note, you could use alternative syntax:
String[] array = new String[3];
//fill in array
for(String s : array){
//this cycles through each element which is available as "s"
}

Categories