How to count repeated elements in given array? Please give me any suggestion as an alternative for this problem.
public static void main(String[] args)
{
// TODO Auto-generated method stub
int a[]={1,2,3,1,2,4,4,4,5};
int c=0;
for(int i=0;i!='\0';i++)
{
c=1;
for(int k=i+1;k<9;k++)
{
if(a[i]==a[k] && a[i]!='\0')
{
c++;
// a[k]='\0';
}
}
if(a[i]!='\0')
{
System.out.println("value is"+a[i]+"repeated in"+c);
System.out.println("\n");
}
}
}
Here's another simple approach that does not require a separate data structure:
Sort the array using Arrays static method
Now you can iterate over the array knowing all duplicates will be grouped together. Shouldn't be hard to figure out....
Pilfering my code from another answer:
public static void main(String[] args) throws Exception {
int[] a = {1, 2, 3, 1, 2, 4, 4, 4, 5};
final Counter<Integer> counter = new Counter<>();
IntStream.of(a).forEach(counter::add);
IntStream.rangeClosed(1, 5).forEach(i -> {
System.out.printf("%s has a count of %s%n", i, counter.count(i));
});
}
public static class Counter<T> {
final Map<T, Integer> counts = new HashMap<>();
public void add(T t) {
counts.merge(t, 1, Integer::sum);
}
public int count(T t) {
return counts.getOrDefault(t, 0);
}
}
Output:
1 has a count of 2
2 has a count of 2
3 has a count of 1
4 has a count of 3
5 has a count of 1
Related
I need a program that prints only the unique elements of an Array, OR, if there are no unique elements, it prints "Null".
My code already can find the unique elements and print it, but it's printing Null for each repeated ones too. I need to print just one "Null" if there are no unique numbers, or just the unique elements (which is working already for that).
The example below, it should print 3 (the non repeated element), and if you put another 3 in the list, should print Null one time only (which I can't figure out how).
I appreciate the help in advance!
public static void main(String[] args) {
int IDs[] = { 1, 2, 3, 2, 2, 1, 5, 5 };
int items = IDs.length;
uniqueIDs(IDs, items);
}
static void uniqueIDs(int IDs[], int items) {
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < items; i++) {
if (hash.containsKey(IDs[i])) {
hash.put(IDs[i], hash.get(IDs[i]) + 1);
}
else {
hash.put(IDs[i], 1);
}
}
for (Map.Entry<Integer, Integer> uniqueIDs : hash.entrySet())
if (uniqueIDs.getValue() == 1)
System.out.print(uniqueIDs.getKey() + "\n");
else {
System.out.println("null");
}
}
}
After the first loop in your method you should add this:
public static void main(String[] args) {
int IDs[] = {1, 2, 3, 2, 2, 1, 5, 3, 5};
int items = IDs.length;
uniqueIDs(IDs, items);
}
static void uniqueIDs(int IDs[], int items) {
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < items; i++) {
if (hash.containsKey(IDs[i])) {
hash.put(IDs[i], hash.get(IDs[i]) + 1);
} else {
hash.put(IDs[i], 1);
}
}
boolean flag = false; //We assume we don't have unique elements
for (Map.Entry<Integer, Integer> uniqueIDs : hash.entrySet()) {
if (uniqueIDs.getValue() == 1) {
flag = true;//Now we have at least one unique element
}
}
if (flag) {
for (Map.Entry<Integer, Integer> uniqueIDs : hash.entrySet()) {
if (uniqueIDs.getValue() == 1) {
System.out.print(uniqueIDs.getKey() + "\n");
}
}
} else {
System.out.println("null");
}
}
//Output:
null
Also: a more general advice, in complex codes add the {} because sometimes it gets really hard to understand where a code block starts or ends for someone else trying to read your code, or even yourself sometimes!
I am new to this programming world. I tried to print length of the array without using predefined functions.
But when i run my code i am getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
can someone please help me to find out the bug
Here is my code.
public class Arraylen {
public static void main(String[] args) {
int[] ary = {1, 3, 4, 5, 68, 9};
int len;
for(len = 1; ary[len] != '\0'; len++) {
System.out.println(len);
}
}
}
What is wrong with using ary.length? .length is a property and not a function. You would not be coding ary.length(), let alone that "function" doesn't even exist.
public class StackOverflow {
public static void main(String args[]) {
int[] ary = {1, 3, 4, 5, 68, 9};
System.out.println(ary.length);
}
}
Result:
6
Just use an enhanced for loop:
public class Arraylen
{
public static void main(String[] args)
{
int[] ary = {1,3,4,5,68,9};
int len = 0;
for(int number : ary)
{
len++;
}
System.out.println(len);
}
}
This iterates over every item in the array, without you having to worry that the index will go over the array size.
You could also use a while loop with a try-catch block to find the length.
Something like this:
boolean lengthFound = false;
int length = 0;
while (!lengthFound) {
try {
// This line throws an Exception when length is equal to the length of the array
int notImportant = array[length] + 2;
length++;
}
// This prevents the exception from breaking anything and gets you out of the
// loop
catch (ArrayOutOfBoundsException ex) {
lengthFound = true;
}
}
// At this point array.length == length
import java.util.*;
public class ArrayList5 {
static int max(ArrayList list) { // to be completed
if (list.size() == 0) {
return 0;
}
else
{
int first = (Integer) list.get(0);
list.remove(0);
if (first > max(new ArrayList(list)))
{
return first;
}
else
{
return max(list);
}
}
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
Collections.addAll(list, 4, 5, 3, 2, 3, 1, 3);
// int t=Console.readInt("Enter Target:");
int res1 = max(new ArrayList(list));
System.out.println("max=" + res1);
}
}
I don't understand why the max(new ArrayList(list))) part is required. Why does it have to create a new one and why can't it continue to work with the one list?
Also why doesn't it get caught in a loop (it's recursion so it will keep sending up a new list so I don't understand why 'first' isn't going to be 4 every time)?
Actually, there is a lot of superfluous code that is not required and make the code cumbersome/more difficult to read/understand.
You can simplify the code a lot and get rid of any reference to ArrayList which are not really necessary and by using proper generic at the right places, make the code actually readable.
You don't need to cast or create list all over the place.
public class ArrayList5 {
static int max(final List<Integer> list) {
if(list.isEmpty()) return 0;
final int head = list.get(0);
final List<Integer> tail = list.subList(1, list.size());
return (head > max(tail)? head:max(tail));
}
public static void main(final String... args) {
final int res1 = max(Arrays.asList(4, 5, 3, 2, 3, 1, 3));
System.out.printf("max=%d", res1);
}
}
You should try this:
static int max(ArrayList<Integer> list) {...}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
Collections.addAll(list, 4, 5, 3, 2, 3, 1, 3);
// int t=Console.readInt("Enter Target:");
int res1 = max(new ArrayList(list));
System.out.println("max=" + res1);
}
The compiler is probably throws a warning because you don't declare the type of the ArrayList.
I have this code which is to check in the two arrays and print out the values that dont exist in the other array. I think the way i did it is not the most efficient way to do it hence can anyone offer a better OOP way to write this code in Java?
Thanks
public class Calculate {
static int [] x = {1,2,4,6,7};
static int [] y = {2,3,4,6,7};
static boolean xflag = true;
static boolean yflag = true;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<x.length; i++)
{
for (int b=0; b<y.length; b++)
{
if(x[i]!= y[b])
{
xflag= false;
}
else
{
xflag = true;
break;
}
}
if(xflag==false)
{
System.out.println(x[i] +" does not exist in array 2");
}
}
for(int i = 0; i<x.length; i++)
{
for (int b=0; b<y.length; b++)
{
if(y[i]!= x[b])
{
yflag= false;
}
else
{
yflag = true;
break;
}
}
if(yflag==false)
{
System.out.println(y[i] +" does not exist in array1");
}
}
}
}
Using Collection class removeAll method
String original[] = { "1","2","3","4","6"};
String testStr[] = { "1","2","3","5","7" };
List origList = new ArrayList(Arrays.asList(original));
List testList = new ArrayList(Arrays.asList(testStr));
System.out.println(origList.removeAll(testList));
System.out.println(origList);
you can use java collection framework, Many function are there,
here is simple example check it.
public static void main(String a[]){
List<String> sl = new ArrayList<String>();
sl.add("apple");
sl.add("java");
sl.add("c++");
sl.add("unix");
sl.add("orange");
sl.add("airtel");
List<String> tl = new ArrayList<String>();
tl.add("job");
tl.add("oracle");
tl.add("jungle");
tl.add("cricket");
boolean isCommon = Collections.disjoint(sl,tl);
System.out.println("Does not found any common elements? "+isCommon);
tl.add("java");
isCommon = Collections.disjoint(sl,tl);
System.out.println("Does not found any common elements? "+isCommon);
}
You may use Apache's CollectionUtils for this purpose if you want an abstraction from the implementation logic.E.g:
public static void main(String[] args) {
List<Integer> list1=Arrays.asList(1,2,4,6,7);
List<Integer> list2=Arrays.asList(2,3,4,6,7);
System.out.println(CollectionUtils.disjunction(list1,list2));
}
You can code this way
List<Integer> array1 = Arrays.asList(1,2,4,6,7);
List<Integer> array2 = Arrays.asList(2,3,4,6,7);
List<Integer> disjointArray = new ArrayList<Integer>();
for (Integer value : array1) {
if (!array2.contains(value)) {
disjointArray.add(value);
}
}
And then you can print disjointArray or do whatever manipulation you want.
Here a running example using Javas Collection classes:
public class Disjunction {
public static void main(String args[]) throws UnsupportedEncodingException {
//Some data preparation
List<Integer> list1=Arrays.asList(1,2,4);
List<Integer> list2=Arrays.asList(5,2,8);
//Here calculating data1-data2 and data2-data1, collect all list items
//that are in data1 or in data2 but not in both.
List<Integer> data1 = new ArrayList<>(list1);
data1.removeAll(list2);
List<Integer> data2 = new ArrayList<>(list2);
data2.removeAll(list1);
//Merging both results. data1 contains now exclusive or of list1 and list2
data1.addAll(data2);
System.out.println("exclusive or is " + data1);
}
}
It prints out
exclusive or is [1, 4, 5, 8]
Try the following program that checks two arrays for numbers they both have and numbers they don't have:
package test;
import java.util.ArrayList;
public class ArrayDifferentiater {
public static void main(String[] args) {
int[] ori = { 1, 5, 4, 8, 6, 65, 16, 6, 575, 64, 561, 57, 57 };
int[] che = { 1, 4, 8, 6 };
sort(ori, che);
}
public static void sort(int[] a, int[] b) {
/**
* 'foundNum' contains the numbers which exists in both array.
* 'notFoundNum' contains the numbers which exists in only first array.
*/
ArrayList<Integer> foundNum = new ArrayList<>();
ArrayList<Integer> notFoundNum = new ArrayList<>();
// First for loop starts
for (int i = 0; i < a.length; i++) {
// Second for loop starts
for (int j = 0; j < b.length; j++) {
/**
* Check if array 1 contains value of array 2.
* If contains than add it to "foundNum" arraylist.
*/
if (a[i] == b[j]) {
foundNum.add(a[i]);
// Remove the number which exists in both arrays from "notFoundNum" arraylist.
if (notFoundNum.contains(a[i])) {
for (int k = 0; k < notFoundNum.size(); k++) {
if (notFoundNum.get(k) == a[i]) {
notFoundNum.remove(k);
}
}
}
break;
} // First if block ends
/**
* Checks if a not found number does not exists in 'notFoundNum' arraylist (to reduce redundancy)
* then adds a not found number to 'notFoundNum' arraylist
* */
if (!notFoundNum.contains(a[i]))
notFoundNum.add(a[i]);
} // Second for loop ends
} // First for loop ends
System.out.println("Found Numbers : " + foundNum);
System.out.println("Not Found Numbers : " + notFoundNum);
}
}
Here is the output for the above program:
Found Numbers : [1, 4, 8, 6, 6]
Not Found Numbers : [5, 65, 16, 575, 64, 561, 57]
Using the public boolean contains(Object o) in the ArrayList library does not work in this case. Consider
ArrayList<int[][]> test = new ArrayList<>();
int[][] one = {
{1,2,3},
{4,5,6}
};
int[][] two = {
{1,2,3},
{4,5,6}
};
int[][] three = {
{9,7,5},
{1,2,4},
{5,6,7}
};
test.add(one);
System.out.println(test.contains(one));
System.out.println(test.contains(two));
System.out.println(test.contains(three));
The above code returns
true
false
false
Is there a way to check for equality between the two and make sure that no duplicate values enter the list?
The easiest approach I know is to extract it into a method using Arrays.deepEquals(Object[], Object[]), something like -
public static boolean contains(List<int[][]> al, int[][] toFind) {
for (int[][] arr : al) {
if (Arrays.deepEquals(arr, toFind)) {
return true;
}
}
return false;
}
Then you can test it like
public static void main(String[] args) {
ArrayList<int[][]> test = new ArrayList<int[][]>();
int[][] one = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] two = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] three = { { 9, 7, 5 }, { 1, 2, 4 }, { 5, 6, 7 } };
test.add(one);
if (contains(test, two)) {
System.out.println("Found two");
}
}
Output is
Found two
One solution would be to wrap the arrays in a class that provides an appropriate equals implementation.
class SquareArray {
private int[][] array;
public SquareArray(int[][] array) {
this.array = array;
}
public int[][] getArray() {
return array;
}
#Override
public boolean equals(Object o) {
return (o instanceof SquareArray) &&
Arrays.deepEquals(array, ((SquareArray)o).array);
}
#Override
public int hashCode() {
return Arrays.deepHashCode(array);
}
#Override
public String toString() {
return Arrays.deepToString(array);
}
}
Now you would use a List<SquareArray>; for instance:
int[][] a = {{1,2,3}, {4,5,6}};
int[][] b = {{1,2},{3,4},{5,6}};
int[][] c = {{1,2,3}, {4,5,6}};
SquareArray x = new SquareArray(a);
SquareArray y = new SquareArray(b);
SquareArray z = new SquareArray(c);
List<SquareArray> list = new ArrayList<>();
list.add(x);
System.out.println(list.contains(x));
System.out.println(list.contains(y));
System.out.println(list.contains(z));
true
false
true
Reference:
Arrays.deepEquals
Arrays.deepHashCode
Arrays.deepToString
I'd like to propose another solution using Java 8 streams and predicates:
The Stream#anyMatch method may be used to check whether the given list contains a certain element. The required predicate can be build concisely using Arrays#deepEquals:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GenericContainsTest
{
public static void main(String[] args)
{
List<int[][]> list = new ArrayList<int[][]>();
int[][] one =
{ { 1, 2, 3 },
{ 4, 5, 6 } };
int[][] two =
{ { 1, 2, 3 },
{ 4, 5, 6 } };
list.add(one);
if (list.stream().anyMatch(e->Arrays.deepEquals(e, two)))
{
System.out.println("Found two");
}
}
}
However, you mentioned that your intention is to...
... make sure that no duplicate values enter the list
In this case, you should at least consider to not use a List, but a Set - particularly, a Set<SquareArray> using the SquareArray class that arashajii proposed in his answer.
contains method use the method equals(e) and when you use equals on array it's the same thing as using == hence you check for reference equality, not content.
To check if two arrays are equals you have to use Arrays.equals(array1, array2) or Arrays.deepEquals(nestedArray1, nestedArray2) for nested arrays.