I've been struggling to create a function to essentially find all the indices of duplicate elements in a multi-dimensional array(unsorted), in this case a 5x5 array, and then using the indices found changing the parallel elements in a score array. But only find duplicates within columns and not comparatively to the other columns in the array Here is what I've done so far, with research online. The main problem with this code is that it will find all the duplicate elements but not the originals. For example: if the array holds the elements:
{{"a","a","a"},{"b","b","b"},{"a","c","a"}}, then it should change the parallel score array to: {{0,1,0},{1,1,1},{0,1,0}}. But instead it only recognizes the last row and top the top row's duplicates.
Code:
public static void findDuplicates(String a[][])
{
System.out.println("*Duplicates*");
Set set = new HashSet();
for(int j = 0; j<a.length; j++)
{
for(int i=0; i < a[0].length; i++)
{
if(!set.contains(a[i][j]))
{
set.add(a[i][j]);
}
else
{
System.out.println("Duplicate string found at index " + i + "," + j);
scores[i][j] -= scores[i][j];
}
}
set = new HashSet();
}
}
I know my explanation is a bit complicated, but hopefully it is understandable enough. Thanks,
Jake.
Your logic is incorrect. Your outer loop is j and inner loop is i but you're doing:
set.add(a[i][j]);
It should be the other way around:
set.add(a[j][i]);
Technically you could get an out of bounds exception if the array isn't NxN. But you can state that as a precondition.
For some reason you're also setting to 0 with:
scores[i][j] -= scores[i][j];
Why not just:
scores[i][j] = 0;
But to find duplicates within columns:
public static void findDuplicates(String a[][]) {
for (int col=0; col<a[0].length; col++) {
Map<String, Integer> values = new HashMap<String, Integer>();
for (int row=0; row<a.length; row++) {
Integer current = values.put(a[row][col], row);
if (current != null) {
scores[row][col] = 0;
scores[current][col] = 0;
}
}
}
}
How does this work?
I've renamed the loop variables to row and col. There's no reason to use i and j when row and col are far more descriptive;
Like you I assume the input array is correct as a precondition. It can be NxM (rather than just NxN) however;
I use a Map to store the index of each value. Map.put() returns the old value if key is already in the Map. If that's the case you've found a duplicate;
The current (row,col) and (current,col) are set to 0. Why subtract the score from itself rather than simply setting to 0?
if the value "a" is found 3+ times in a column then scores[current][col] will be set to 0 more than once, which is unnecessary but not harmful and makes for simpler code.
I've declared the Map using generics. This is useful and advisable. It says the Map has String keys and Integer values, which saves some casting;
It also uses auto-boxing and auto-unboxing to convert an int (the loop variable) to and from the wrapper class Integer.
Related
I came across this problem in class and I'm stuck on it. I did plenty of research but I'm not being able to fix my code.
I need to create a matrix and find the smallest value in the row of the largest value (I believe this element is called minimax). I'm trying to do with a simple 3 x 3 matrix. What I have so far:
Scanner val = new Scanner(System.in);
int matrizVal[][] = new int[3][3];
for (int a = 0; a < matrizVal.length; a++) {
for (int b = 0; b < matrizVal.length; b++) {
System.out.print("(" + a + ", " + b + "): ");
matrizVal[a][b] = val.nextInt();
}
}
int largest = matrizVal[0][0];
int largestrow = 0;
int arr[] = new int[2];
for (int row = 0; row < matrizVal.length; row++){
for (int col = 0; col < matrizVal.length; col++){
if (largest < matrizVal[row][col]){
largest = matrizVal[row][col];
largestrow = row;
}
}
}
To find the so called minimax element I decided to create a for each loop and get all the values of largestrow except the largest one.
for (int i : matrizVal[largestrow]){
if (i != largest){
System.out.print(i);
}
}
Here's where I'm stuck! I'd simply like to 'sort' this integer and take the first value and that'd be the minimax. I'm thinking about creating an array of size [matrizVal.length - 1], but not sure if it's gonna work.
I did a lot of research on the subject but nothing seems to help. Any tips are welcome.
(I don't think it is but I apologize if it's a duplicate)
Given the code you have provided, matrizVal[largestrow] should be the row of the matrix that contains the highest valued element.
Given that your task is to extract the smallest value in this array, there are a number of options.
If you want to simply extract the minimum value, a naive approach would go similarly to how you determined the maximum value, just with one less dimension.
For example:
int min = matrizVal[largestrow][0];
for (int i = 0; i < matrizVal.length; i++) {
if (matrizVal[largestrow][i] < min) {
min = matrizVal[largestrow][i];
}
}
// min will be the target value
Alternatively, if you want to sort the array such that the first element of the array is always the smallest, first ensure that you're making a copy of the array so as to avoid mutating the original matrix. Then feel free to use any sorting algorithm of your choice. Arrays.sort() should probably suffice.
You can simplify your approach by scanning each row for the maximum and minimum values in that row and then deciding what to do with those values based on the maximum value found in previous rows. Something like this (untested) should work:
int largestValue = Integer.MIN_VALUE;
int smallestValue = 0; // anything, really
for (int[] row : matrizVal) {
// First find the largest and smallest value for this row
int largestRowValue = Integer.MIN_VALUE;
int smallestRowValue = Integer.MAX_VALUE;
for (int val : row) {
smallestRowValue = Math.min(smallestRowValue, val);
largestRowValue = Math.max(largestRowValue, val);
}
// now check whether we found a new highest value
if (largestRowValue > largestValue) {
largestValue = largestRowValue;
smallestValue = smallestRowValue;
}
}
This doesn't record the row index, since it didn't sound like you needed to find that. If you do, then replace the outer enhanced for loop with a loops that uses an explicit index (as with your current code) and record the index as well.
I wouldn't bother with any sorting, since that (1) destroys the order of the original data (or introduces the expense of making a copy) and (2) has higher complexity than a one-time scan through the data.
You may want to consider a different alternative using Java 8 Stream :
int[] maxRow = Arrays.stream(matrizVal).max(getCompertator()).get();
int minValue = Arrays.stream(maxRow).min().getAsInt();
where getCompertator() is defined by:
private static Comparator<? super int[]> getCompertator() {
return (a1, a2)->
Integer.compare(Arrays.stream(a1).max().getAsInt(),
Arrays.stream(a2).max().getAsInt()) ;
}
Note that it may not give you the (undefined) desired output if two rows include the same highest value .
I am having difficulty mapping the data in two lists into a third list. My sample data is as follows:
Categorylist ID: 1,2,3,4,5,6,7,8,9,10,42,46,49,50
CurrentMonthByCat ID: 1,2,3,4,5,6,7,8,9,10,42,49,50
(the transaction amount value for CurrentMonthByCat: 92,46,40,180,60,10,1510,200,500,10,234,12)
There is a missing 46 in the currentMonthByCat. I am trying to do it in a way such that if the currentMonthByCat ID does not exist from the categorylist ID, I will insert 0 into the third list rather than getting the transaction amount from CurrentMonthByCat and push it into the third list.
ArrayList<Double> total = new ArrayList<Double>();
for(int i = 0; i < categorylist.size(); i++){
for(int j = 0; j < currentMonthByCat.size(); j++){
if(categorylist.get(i).getCategoryID().equals(currentMonthByCat.get(j).getCategory().getCategoryID())){
Log.d("IIIII", categorylist.get(i).getCategoryID());
Log.d("JJJJJ", currentMonthByCat.get(j).getCategory().getCategoryID());
total.add((double)currentMonthByCat.get(j).getTransactionAmt());
}else{
total.add(0.0);
}
}
}
for(int k = 0; k < total.size(); k++){
Log.d("KKKKK", String.valueOf(total.get(k)));
}
But the printed out result of total list is:
92,0,0,0,0,0,0,0,0,0,0,0,0,0,46,0,0,0...
What I expected is:
92,46,40,180,60,10,1510,200,500,10,0,234,12
I wanted to insert 0 only if the ID in currentMonthByCat does not match the ID in categorylist. For instance, the ID 46 which is the 3rd position from the right.
I realized the reason is because firstly I inserted 92 into third array, then the categorylist ID is still at 1, then it will compare with all the rest in the currentMonthByCat before moving to ID 2. That is why the unnecessary zeros. But I not sure how to actually sort it to achieve what I wanted.
Any ideas?
Thanks in advance.
It's easy one. you can't take a decision of adding zero or value in the total array unless the inner loop finish. so probably you add element existAtIndex and initialize it with -1 and in the loop if you find the element then assign the index to existAtIndex and break the loop or if it's not exist then you add zero. so the code will be something like :
ArrayList<Double> total = new ArrayList<Double>();
int existAtIndex;
for(int i = 0; i < categorylist.size(); i++){
// search for the element index
existAtIndex = -1;
for(int j = 0; j < currentMonthByCat.size(); j++){
if(categorylist.get(i).getCategoryID().equals(currentMonthByCat.get(j).getCategory().getCategoryID())){
existAtIndex = j;
break;
}
}
// add the value in the element index or add zero if the element not exist
if (existAtIndex != -1) {
total.add((double)currentMonthByCat.get(existAtIndex).getTransactionAmt());
}
else {
total.add(0.0);
}
}
for(int k = 0; k < total.size(); k++){
Log.d(String.valueOf(total.get(k)));
}
For better code you could use contains method to check for the item if exist or not in arrayList instead of using the basic loop. Good luck
You have a lot of code for what you are trying to do here. I think the following snippet does what you want in a very readable and maintainable way.
//First of all we are interested in getting a transaction amount for each value in currentMonthByCat
//so loop around using your object (not sure what it's called)
for(CurrentMonth value : currentMonthByCat){
//check if it's present.
//We create a new method here that gets you your category list as a list of integers.
//This is key to making the whole method much more readable.
if(categorylist.getIdsAsList().contains(value.getCategory().getCategoryID())){
//it is so add it
total.add(value.getTransactionAmt());
} else {
//it's not so add a 0
total.add(0.0);
}
}
The getIdsAsList method could look like this:
public List<Integer> getIdsAsList(){
List<Integer> result = new ArrayList<>();
for (CategoryListItem item : categorylist) {
result.add(item.getCategoryId());
}
return result;
}
Put your values into Map<Integer, Double>
Map<Integer, Double> map = new HashMap<Integer, Double>();
for (int i = 0; i < currentMonthByCat.size(); ++i) {
//... categoryId = currentMonthByCat.get(i).categoryId
//... amount = currentMonthByCat.get(i).amount
map.put(categoryId, amount);
}
Then traverse the map using values from Categorylist ID:
// create result arraylist
ArrayList<Double> total = new ArrayList<Double>();
for (int i = 0; i < categorylist.size(); ++i) {
Double amount = map.get(categorylist.get(i));
if (amount == null) {
total.add(0.0);
} else {
total.add(amount);
}
}
The result list total will contain amounts for existing mappings, or zeros for non-existent.
Other way
If it is guaranteed categorylist is sorted and CurrentMonthByCat is sorted
you can then traverse one of the lists while keeping index/cursor to the other list and not iterating the other list from the beginning, but from previously remembered cursor value, resulting in better average performance than n^2
I wrote below code to get duplicate elements from Arraylist. My aerospikePIDs list doesn't have any duplicate value but still when I am executing below code it is reading if condition.
ArrayList<Integer> aerospikePIDs = new ArrayList<Integer>();
ArrayList<Integer> duplicates = new ArrayList<Integer>();
boolean flag;
for(int j=0;j<aerospikePIDs.size();j++) {
for(int k=1;k<aerospikePIDs.size();k++) {
if(aerospikePIDs.get(j)==aerospikePIDs.get(k)) {
duplicates.add(aerospikePIDs.get(k));
flag=true;
}
if(flag=true)
System.out.println("duplicate elements for term " +searchTerm+duplicates);
}
}
Your inner loop should start from j + 1 (not from 1), otherwise when j = 1 (second iteration of j), for k = 1 (first iteration of k for j value equals to 1).
aerospikePIDs.get(j)==aerospikePIDs.get(k)
returns true.
So the code should be:
ArrayList<Integer> aerospikePIDs = new ArrayList<Integer>();
ArrayList<Integer> duplicates = new ArrayList<Integer>();
for (int j = 0; j < aerospikePIDs.size(); j++) {
for (int k = j + 1; k < aerospikePIDs.size(); k++) {
if (aerospikePIDs.get(j)==aerospikePIDs.get(k)) {
duplicates.add(aerospikePIDs.get(k));
System.out.println("duplicate elements for term " +searchTerm+duplicates);
}
}
}
Note: the flag is not necessary, because if you addeda duplicate you can print it directly in the if, without defining new unnecessary variables and code.
Use higher level abstractions:
Push all list elements into a Map<Integer, Integer> - key is the entry in your PIDs list, value is a counter. The corresponding loop simply checks "key present? yes - increase counter; else, add key with counter 1".
In the end, you can iterate that map, and each entry that has a counter > 1 ... has duplicates in your list; and you even get the number of duplicates for free.
And questions/answers that show you nice ways to do such things ... are posted here on almost daily basis. You can start here for example; and you only need to adapt from "String" key to "Integer" key.
Really: when working with collections, your first step is always: find the most highlevel way of getting things done - instead of sitting down and writing such error-prone low-level code as you just did.
You are iterating using the same arraylist. You are checking every data in inner for loop, for sure it will display duplicates.
I have a JLabel array that starts with an integer number of elements. How can I remove an certain number of elements from the array? For example, every time the int is updated:
int i = 21;
i = i - removedElements
How can I update the array to contain that many elements, instead of creating an entirely new array with the desired number of elements?
As others have already mentioned, List is the way to go here since it is specifically designed for adding and or deleting elements.
However if you would prefer to use the JLabel Array you already have in established then you will need to realize that the only way to delete an element from that array is to actually create another array with the desired element to delete excluded from it then return it into the original array. Below I have supplied a simple method named deleteJLabelFromArray() that can do this for you:
public static JLabel[] deleteJLabelFromArray(JLabel[] srcArray, int... indexesToDelete) {
int counter = 0;
JLabel[] newArray = new JLabel[srcArray.length - indexesToDelete.length];
for (int i = 0; i < srcArray.length; i++) {
boolean noGo = false;
for (int j = 0; j < indexesToDelete.length; j++) {
if (i == indexesToDelete[j]) { noGo = true; break; }
}
if (noGo == false) { newArray[counter] = srcArray[i]; counter++; }
}
return newArray;
}
With this method you can delete whatever indexes you supply within the indexesToDelete argument (delimited with a comma). Copy/Paste the code into your project then you can use it something like this:
JLabel[] jla = {jLabel2,jLabel3,jLabel4,jLabel5};
jla = deleteJLabelFromArray(jla, 2);
for (int i = 0; i < jla.length; i++) {
System.out.println(jla[i]);
}
In this example we are going to delete the element number 2 (remember that arrays are 0 based) and therefore jLabel4 would be removed from the Array.
Keep in mind that this would be scary stuff with really big arrays.
Hope this helps.
I have an arraylist. For example
A = [1,2,3,4,5,6,7,8];
I need to change the order of the arraylist so that I can get
A = [2,1,4,3,6,5,8,7]. It means odd position item will be positioned in even positions and vice-versa.
Thanks
A simple approach that assumes
Length of A is given as A.size()
Array A can be accessed by A.get(index) and A.set(index, value)
If your array is not even, the last element is left as-is
Is to swap values in pairs - like this:
for (int index = 1; index < A.size(); index += 2) { // Swap on even indices.
// Swap values at positions index-1 and index.
Object temp = A.get(index-1); // Save value before overwrite.
A.set(index-1, A.get(index)); // First half of swap.
A.set(index, temp); // Final operation for swap.
}
Edit: Changed int to Object, and used A.size, A.get and A.set instead of [] indexers as suggested by comments.
You could do it in the following way:
int a[] = {1,2,3,4,5,6,7,8};
System.out.println("A=["+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+","+a[5]+","+a[6]+","+a[7]+"]");
for (int i = 0; i < a.length/2; i++) {
int help;
help = a[i*2];
a[i*2]=a[i*2+1];
a[i*2+1] = help;
}
System.out.println("A=["+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+","+a[5]+","+a[6]+","+a[7]+"]");
Ask if you have questions about the code.
Edit: I missed the arraylist, but the principle is the same.