Android: Methods for finding matching elements in arrays? - java

Hi I am stuck in a particular case
I have two arrays, ArrayA[] with 50 items and another ArrayB[] with 10 items.
I want to convert the values of the ArrayB[] (10 items) to be 1 if they match a value in ArrayA[] and 0 if they don't.
I have been trying various techniques for past 5 hours- would be great to get some guidance in what I can do to get this!
Thanks for any help!

If I understand you well, this is what you are looking for:
public static void method(int[] arrayA, int[] arrayB)
{
boolean match = false;
label: for(int i = 0; i < arrayA.length; i++)
for(int j = 0; j < arrayB.length; j++)
if(arrayA[i] == arrayB[j])
{
match = true;
break label;
}
int k = (match?1:0);
for(int i = 0; i < arrayB.length; i++)
arrayB[i] = k;
}
If not, please elaborate!

List l = Arrays.asList(arrayA);
for (int i = 0; i < arrayB.length; i++)
arrayB[i] = l.contains(arrayB[i]) ? 1 : 0;

Related

Array method printing is almost right, just one value is off which I'm not sure why

So I'm trying to get an array to be passed into a separate method and then return a new sized array but the program has just one incorrect value. For example, I have an array
int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};
That I'm trying to pass into my createLowerArray method
public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
int [] betterInches = {0,0,0,0,0,0,0,0,0,0};
int count = 0;
for (int i = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
count++;
}
betterInches = new int [count];
int newCount = 0;
for (int q = 0; q < betterInches.length; q++) {
if (myInchesParam[newCount] < maxParam) {
betterInches[q] = myInchesParam[newCount];
}
newCount++;
}
}
return betterInches;
}
With maxParam just being whatever the user inputs. So let's say they put in 40, the second method will see that only 4 elements, (12,33,7, and 23) are less than 40 and create an array of length 4 with position 0 being 12, [1] = 33, [2] = 7, and [3] = 23, but for some reason my program makes it so. Position 0 in the new array is 0, [1] = 12, [2] = 33, and [3] = 7. the length is correct but the values aren't in the right positions. I got help with this earlier and thought I had it, it feels bad to be back so fast but I just can't seem to figure it out. Thank you to anyone who helps. I know this can be made easier with lists, streams and the like but I need practice with loops.
Expected output should be
int length = 4
[0] = 12
[1] = 33
[2] = 7
[3] = 23
Current output is
int length = 4
[0] = 0
[1] = 12
[2] = 33
[3] = 7
The immediate problem is here:
for (int q = 0; q < betterInches.length; q++) {
if (myInchesParam[newCount] < maxParam) {
betterInches[q] = myInchesParam[newCount];
}
newCount++;
}
You are always incrementing newCount, even if you didn't copy the value. Also, you need to loop over myInchesParam, not betterInches:
for (int j = 0, q = 0; j < myInchesParam.length; j++) {
if (myInchesParam[j] < maxParam) {
betterInches[q] = myInchesParam[j];
q++;
}
}
Additionally, you are doing a lot more work than necessary - your current code is quadratic in the size of the input array. You create the new betterInches array on each iteration of the outer loop, and then discard that and create it again on the next iteration.
Move the inner loop out of the outer loop:
for (int i = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
count++;
}
}
betterInches = new int [count];
for (int i = 0, q = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
betterInches[q++] = myInchesParam[i];
}
}
Try this
for (int q = 0; q < betterInches.length; q++) {
if (myInchesParam[q] < maxParam) {
betterInches[newCount] = myInchesParam[q];
newCount++;
}
}
Updated
Actually you are not iterating on whole array for getting your params. changed second loop to this.
int newCount = 0;
for (int q = 0; q < myInchesParam.length; q++) {
if (myInchesParam[q] < maxParam) {
betterInches[newCount] = myInchesParam[q];
newCount++;
}
}
seprate first loop and second loop. your second loop is inside the first loop. take a look on code below.
public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
int [] betterInches = {0,0,0,0,0,0,0,0,0,0};// Dont need to initialize
int count = 0;
for (int i = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
count++;
}
} // First loop end here
betterInches = new int [count];
int newCount = 0;
for (int q = 0; q < myInchesParam.length; q++) {
if (myInchesParam[q] < maxParam) {
betterInches[newCount] = myInchesParam[q];
newCount++;
}
} // Second Loop ends heer
return betterInches;
}

Not able to add to ArrayList properly

I have 2 methods in my program, one to add ***** above and below the smallest int in the array and one to add %%%%% above and below the largest. The method for the largest is essentially the same as the other but for some reason isn't adding what is needed.
Here is the smallest element method:
public static ArrayList smallestElement() {
int smallest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] < smallest)
smallest = array[i];
String smallestString = String.valueOf(smallest);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
if (smallestString.equals(String.valueOf(array[i]))) {
list.add("*****");
list.add(Integer.toString(array[i]));
list.add("*****");
} else {
list.add(Integer.toString(array[i]));
}
}
return list;
}
Here is the method for the largest element:
public static ArrayList largestElement() {
int largest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] > largest)
largest = array[i];
String largestString = String.valueOf(largest);
for(int i = 0; i < array.length; i++) {
if (largestString.equals(String.valueOf(array[i]))) {
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
} else {
smallestElement().add(Integer.toString(array[i]));
}
}
System.out.println(smallestElement());
return smallestElement();
}
}
If anyone knows why this isn't performing correctly, I would really appreciate the help
You are creating a new object every time you are executing the smallestElement function. Instead do something like,
ArrayList<String> list = smallestElement();
Then use this list object every time you are calling smallestElement() method
You have already created the list 3 times over by this line
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
Create just 1 list and use it instead of calling the smallestelementelement() function multiple times
You are overcomplicating things here. There is no need to turn that minimum array value into a string right there (and to then do String comparisons later on). Btw: those string comparisons are also your problem: your code will definitely not work when your minimal value shows up several times in your array - because your code will put in those patterns for each match!
Instead, you could do something like:
int indexToUse = 0;
for (int i = 0; i < array.length; i++) { // please always use braces!
if (array[i] < array[indexToUse]) {
indexToUse = i;
}
}
List<String> valuesWithMarkerStrings = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (i == indexToUse -1 || i == indexToUse+1) {
valuesWithMarkerStrings.add("******");
} else {
valuesWithMarkerStrings.add(Integer.toString(array[i]);
}
}
(where my solution assumes that you want to have *** ... instead of array[i] for such rows ... )

JAVA Writing the diagonal of an 2-dimensional array into an 1-dimensional array

Want to write the diagonal of an 2-dimensional array (n*n Matrix) into an one-dimensional array.
1 2 3
4 5 6 => 1 5 9
7 8 9
public int[] getDiagonalFromArray(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array[0].length];
int k=0;
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
for (int l = 0; l < two_d_array[0].length; l++) {
diagonal_array[k]=two_d_array[i][j];} //HERE SHOULD BE THE ERROR... HOW DO I CYCLE THROUGH THE 1dim "diagonal_array"?
}
}
return diagonal_array;
}
This method delivers wrong values.
This method of mine works, but just Prints the diagonale, instead of putting it into an 1dim array.
public void getDiagonal(int[][] two_d_array){
//int[] diagonal_array = new int[two_d_array[0].length];
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
if (i==j) System.out.print(two_d_array[i][j]+" ");
}
}
}
Where is the logical difference? I tried the if-clause on the first method, but it raises the "outofbound"-Exception.
Thanks in advance.
Why do you need more than one loop?
for (int i = 0; i < two_d_array[0].length; i++) {
diagonal_array[i]=two_d_array[i][i];
}
Seems to be enough to me.
If your matrix has the same width and height, this is a solution:
public int[] getDiagonal(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array.length];
for (int i = 0; i < two_d_array.length; i++) {
diagonal_array[i] = two_d_array[i][i];
}
return diagonal_array;
Here, I consider principal diagonal elements to be the set of elements , where n & m are the number of rows and the number of columns (per row?) respectively.
Thus, the number of diagonal elements is never greater than min(numOfRows, numOfColumns).
And so, you can always try:
public int[] getDiagonalFromArray(int[][] 2DArray){
int[] diagonalArray = new int[Math.min(2DArray.length, 2DArray[0].length]);
int k=0;
for (int i = 0; i < 2DArray.length && k < diagonalArray.l length; ++i) {
for (int j = 0; j < 2DArray[i].length && k < diagonalArray.l length; ++j) {
if (i == j) {
diagonalArray[k++]=2DArray[i][j];
}
}
}
return diagonalArray;
}
Threw in some bounds checks for good measure.
Your input matrix must at be at least rectangular (square makes most sense), otherwise, the code will behave unreliably.
This is the same as #Andreas' answer, but I sacrifice performance and brevity here for the sake of understanding.

ArrayIndexOutOfBounds Exception for some input values

The following is a part of my code.
For some values of bands and bandRows the code seems to run perfectly alright. But for some it gives an ArrayIndexOutOfBounds exception.
Any ideas where I might have gone wrong? I cannot find any mistake in the code.
Thanks in advance
for(int i=0; i<bands; i++)
{
int a=0;
while(a<bucketSize)
{
bandBuckets[i][a] = new ArrayList();
a++;
}
}
for (int i = 0; i < bands; i++)
{
for (int j = 0; j < preprocessedList.size(); j++)
{
int[][] forBuckets = new int[bands][bandRows];
for (int k = 0; k < bandRows; k++)
{
Arrays.fill(forBuckets[i], Bands[i][k][j]);
}
bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)].add(j);
}
}
Here's the h.hashBands() function which is in another class
public int hashBands(int[] in, int bucketSize)
{
int hashVal = 0;
int k = in.length;
int base = 3;
for (int i = 0; i < in.length; i++) {
// for (int j = 0; i < in[i].length; i++)
hashVal += in[i] * Math.pow(base, k - i - 1);
}
return hashVal % bucketSize;
}
Perhaps there is an overflow in your hashBands() function.
The max value for an int is 231 - 1. hashVal will overflow when k - i - 1 is greater than 19. In Java, exceptions aren't thrown for overflows and underflows. Consider using a BigInteger and its modPow() function.
Can you tell where exactly you are getting ArrayIndexOutOfBoundException.
Seeing your code it seems that there might be some problem while returning from hashBands() function. It might be returning something greater than expected.
bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)]
For the 2nd dimension of this array h.hashBands(forBuckets[i], bucketSize) --> this value might be greater than the expected value for that part.....

Trying to use a Hashmap<Integer, Integer>

how would I increment the key [i] by 1 in this situation every time I run through this for loop with the way I currently have it set up all the elements only get mapped to 1. I am trying to find out how many times each number occurs. I have tried +1 in the empty spot after list.get(i) but again only maps each element to 1. thank you.
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
System.out.println(list);
int count = 1;
for(int i = 0; i < list.size(); i ++) {
Mode.put(list.get(i), );
You need to specify a Key here.
for(int i = 0; i < list.size(); i++) {
int value=list.get(i);
if(!Mode.containsKey(value))
Mode.put(value,1);
else
Mode.put(value,Mode.get(value)+1);
}
According to your comment,
for(int i = 0; i < list.size(); i ++) {
if(Mode.containsKey(list.get(i)) ){
Integer count = Mode.get(list.get(i));
Mode.put(list.get(i), ++count);}
else
Mode.put(list.get(i), 1);
If you have the option, you may find it easier to use something like Multiset from Guava.
Multiset<Integer> seen = HashMultiset.create();
for (int[] row : arr) {
for (int elem : row) {
seen.add(elem); // none of that nasty dealing with the Map
}
}
// you can look up the count of an element with seen.count(elem)
E mostCommon = null;
int highestCount = 0;
for (Multiset.Entry<Integer> entry : seen.entrySet()) {
if (entry.getCount() > highestCount) {
mostCommon = entry.getElement();
highestCount = entry.getCount();
}
}
return mostCommon; // this is the most common element

Categories