i want to replace duplicate element with "repeated" string for example,
the arraylist is ["a","b","b","c","a","c","a"], the new array is ["a","b","repeated","c","repeated","repeated","repeated]
i have tried this
ArrayList<String> m = new ArrayList();
m.add("a");
m.add("b");
m.add("b");
m.add("c");
m.add("a");
m.add("c");
m.add("a");
System.out.println(m);
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m.size(); j++) {
if (m.get(i).equals(m.get(j))){
m.set(j, "repeated");
}
}
}
but it's not working
No need to two nested loop. just use a Set to store repeated string.
Set<String> repeat = new HashSet<>();
int index = -1;
for (String s:m){
index++;
m.set(index, repeat.add(s) ? s : "repeated");
}
Two errors:
You print your list before updating. Move the
System.println(...) after the loop.
You are replacing all elements (not just the duplicates) with the "repeated" String since
the first comparison in the loop is with the element
itself.
ArrayList<String> m = new ArrayList<>();
m.add("a");
m.add("b");
m.add("b");
m.add("c");
m.add("a");
m.add("c");
m.add("a");
for (int i = 0; i < m.size(); i++) {
for (int j = i + 1; j < m.size(); j++) {
if (m.get(i).equals(m.get(j))){
m.set(j, "repeated");
}
}
}
System.out.println(m);
Related
Im trying to initialise all the elements of the 2d array into a string "EMPTY". but When ever I try to initialise the array it gets null values. I checked errors in the for loop but couldn't see any
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
}
Your loops are nested wrongly, which will result in the filling process not being complete while you're trying to process its results. You need
public static void arr_2d() {
String[][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
Actually for(int b) is in for(int i); that's why you observe null values. If you move for(int b) outside of for(int i), there will be no null values.
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
Check the comments given below in the snippet:
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
// you can have the sysout statement here as well instead of having looping the entire array again.
System.out.print(arr[i][a] + " ");
}
// this loop must be executed separately inorder to check values present in the array or else you can have a sysout statement when assigning the "empty" value in the array.
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
}
Although the answers you have are correct I will add that one problem is your code style is prone to errors.
Your mistake was traversing the array incorrectly. The correct way is traversing the array twice, one of filling and another for printing, but instead it seems you have attempted to do everything in one shot. That mistake can be avoided with a better code style.
This is how I would have written your code in imperative style:
String[][] arr = new String[3][2];
for (String[] a : arr)
Arrays.fill(a, "EMPTY");
for (String[] a : arr)
System.out.println(Arrays.toString(a));
Notice the code is much shorter, so there's less chances of mistakes. It's also a lot more obvious that you're traversing twice.
Instead of traversing an array explicitly:
for (int i = 0; i++; i < arr.length())
Use the implicit for loop:
for (String[] value: arr)
Instead of filling an array explicitly:
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
Use the already provided fill method:
Arrays.fill(value, "EMPTY");
Instead of printing an array explicitly:
for (String string : strings) {
System.out.print(string + " ");
}
System.out.println();
Use the already provided print method:
for (String[] a : arr)
System.out.println(Arrays.toString(a));
However, I would have written in functional style:
String [][] arr = new String[3][2];
Arrays.stream(arr)
.forEach(a -> Arrays.fill(a, "EMPTY"));
Arrays.stream(arr)
.map(Arrays::toString)
.forEach(System.out::println);
One particular advantage is that you are encouraged to think in a more abstract way. Instead of thinking how to explicitly set or print each element of the array, you are encouraged to use methods that implicitly traverse, transform or perform generic computations on all elements of the array.
So I'm trying to make a program that counts the occurences of int in an array. what i tried to do is to make a method that lists the unique integers, then another method to compare the list items to the original array items.
public List listUnique(int[] arr){
Arrays.sort(arr);
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
}
return temp;
}
public int[] countDupli(List unique, int[] arr){
int [] ret = new int[unique.size()];
Iterator <Integer> iterator = unique.iterator();
for (int l = 0; l < unique.size(); l++){
ret[l] = iterator.next().intValue();
}
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
for (int k = 0; k < ret.length; k++){
for (int i = 0; i < arr.length; i++){
if ( ret[k] == arr[i]){
dupli[k]+= 1;
}
}
k++;
}
return dupli;
}
It isn't doing what is intended to do tho. For example, an input of {1,2,...,1,2} 10 items of those, prints the correct unique items but only outputs the count of 1 but not 2. dupli = [5,0]. where did the algorithm go wrong? thanks
In your code try debugging or just print ret[] values and see if all unique values are present.
Other Suggestions:
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
You can simply use HashSet, then you don't have to write above code to find unique values. HashSet does not store duplicate values.
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
Then you can use iterator and compare with your sorted array and increase count simultaneously.
You can skip the following for loop, as java initializes it to 0 by default.
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
my title is bad but I don't have an idea what it should be. My question is simple, I have four arraylist and I want to get similar words from two of them and put another arraylists. Anyway my array lists like;
arrList1 = {car, apple, many, car, tyty, man, superman};
arrList2 = {stack, vs, etc, vs, car, tyty, stack, tyty, many, car, apple};
I tried this;
for (int i = 0; i < arrList1.size(); i++) {
for (int j = 0; j < arrList2.size(); j++) {
if (arrList1.get(i).equals(arrList2.get(j))) {
arrList3.add(arrList1.get(i);
arrList4.add(arrList2.get(j);
}
}
But as you see arrList1 and arrList2 have duplicates so arrList4 will have same element more than normal. Also I have to count elements which are in arrList1 and arrList2 so I shouldn't use Set Collections. What should I do?
Try
ArrayList<String> temp = new ArrayList<String>();
boolean found = false;
for (int i = 0; i < arrList1.size(); i++) {
found = false;
for (int j = 0; j < arrList2.size(); j++) {
if (arrList1.get(i).equals(arrList2.get(j))) {
found = true;
if (!temp.contains(arrList2.get(j)) {
arrList4.add(arrList2.get(j));
}
}
}
if (found) {
arrList3.add(arrList1.get(i));
temp.add(arrList1.get(i));
}
}
This will check if the new ArrayList does not already contain the item.
Try this
ArrayList tempList=new ArrayList(arrList1);
tempList.removeAll(arrList2);
arrList4 = new ArrayList(arrList1);
arrList4.removeAll(tempList);
You should use another type of list but you can also make-do with an arraylist like so:
for (int i = 0; i < arrList1.size(); i++) {
for (int j = 0; j < arrList2.size(); j++) {
if (arrList1.get(i).equals(arrList2.get(j))) {
if(!(arrList3.contains(arrList1.get(i))) {
arrList3.add(arrList1.get(i);
}
if(!(arrList4.contains(arrList2.get(j))) {
arrList4.add(arrList2.get(j);
}
}
}
hope that helps.
I want to make a loop on Two-dimensional array in Java.
How I do that? I wrote:
for (int i = 0; i<=albums.size() - 1; i++){
for (int j = 0; j<=albums.size() - 1; j++){
But it didn't work. Thanks.
Arrays have a read-only field called length, not a method called size. A corrected loop looks like this:
for(int i = 0; i < albums.length; i++ ) {
for (int j = 0; j < albums[i].length; j++) {
element = albums[i][j];
You have to recognize that a 2-D array is just an array whose element type happens to be another array. So the i loop iterates over each element in albums (which is an array) and the j loop iterates over that child array (with a potentially different size).
A more transparent way would be like this:
String[][] albums;
for(int i = 0; i < albums.length; i++ ) {
String[] childArrayAtI = albums[i];
for (int j = 0; j < childArrayAtI.length; j++) {
String element = childArrayAtI[j];
}
}
Try this if you are working with Java 1.5+:
for(int [] album : albums) {
for(int albumNo : album) {
System.out.print(albumNo + ", ");
}
System.out.println();
}
First of all, a two-dimensional array looks like this in Java:
int[][] albums = new int[10][10];
Now, for iterating over it:
for (int i = 0; i < albums.length; i++) {
for (int j = 0; j < albums[i].length; j++) {
int value = albums[i][j];
}
}
I have a 2D Array and I would like to find an easier way to manipulate my code so that it will find if there is a duplicate in the column and easier way then what I have below:
for (int i=0; i < array.length; i++) {
for (int j=0; j < array.length; j++) {
for (int k=1; k < array.length; k++){
if (array[j+k][i] == array[j][i]) {
if (array[j][i] != 0) {
return true;
}
}
}
}
}
return false;
EDIT: KINDLY POINTED OUT THE ABOVE ^^ WON'T WORK EITHER AS IT WILL THROW AN OUT OF BOUNDS EXCEPTION
This way has too many loops and I am sure there must be an easier way to find duplicates rather than going through this massive looping process.
This is for a square 2D array, ie. an array with rows = columns.
If so, how can this new way work - and how can I manipulate it to work to find duplicate values in the rows as well.
Thanks for the help.
you can use HashSet to store all already encountered elements. should be something like this:
static boolean noDupes(int[][] array) {
for (int i=0; i < array.length; i++) {
HashSet<Integer> set = new HashSet<Integer>();
for (int j=0; j < array.length; j++) {
if (set.contains(array[j][i])) return false;
set.add(array[j][i]);
}
}
return true;
}
this solution is O(length^2) = O(n) where n is the matrix total size. I think it is ideal in terms of big O, because you need to check all elements.
int[][] array = new int[3][5];
for (int i = 0; i < array.length; i++) // array initialization
for (int j = 0; j < array[i].length; j++ )
array[i][j] = i*j;
Map<Integer, Set<Point>> map = new HashMap<Integer, Set<Point>>();
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
if (map.containsKey(array[i][j]))
map.get(array[i][j]).add(new Point(i, j));
else
{
Set<Point> set = new HashSet<Point>();
set.add(new Point(i, j));
map.put(array[i][j], set);
}
for (Map.Entry<Integer, Set<Point>> entry : map.entrySet())
if (entry.getValue().size() > 1)
{
System.out.println("value = " + entry.getKey());
for (Point p : entry.getValue())
System.out.println("coordinates = " + p);
System.out.println();
}
The output is as expected:
value = 0
coordinates = java.awt.Point[x=0,y=3]
coordinates = java.awt.Point[x=0,y=0]
coordinates = java.awt.Point[x=2,y=0]
coordinates = java.awt.Point[x=0,y=4]
coordinates = java.awt.Point[x=0,y=2]
coordinates = java.awt.Point[x=1,y=0]
coordinates = java.awt.Point[x=0,y=1]
value = 2
coordinates = java.awt.Point[x=1,y=2]
coordinates = java.awt.Point[x=2,y=1]
value = 4
coordinates = java.awt.Point[x=2,y=2]
coordinates = java.awt.Point[x=1,y=4]
Finding the Duplicate Elements in a given Matrix - JAVA
static void findDuplicates(String[][] matrix) {
HashSet<String> uniqInp = new HashSet<String>();
HashSet<String> allDup = new HashSet<String>();
System.out.println("***** DUPLICATE ELEMENTS *****");
for(int row=0;row<matrix.length;row++)
{
for(int col=0;col<matrix[0].length;col++)
{
if(uniqInp.add(matrix[row][col]))
//If not duplicate it will add
continue;
else {
// If Duplicate element found, it will come here
if(allDup.add(matrix[row][col]))
System.out.print(matrix[row][col]+" ");
}
}
}
}