Find the dimension of array - java

I know its a silly question but I want to know that Is it possible to find the array dimension? when we have the following code
public class ArrayDimentionCheck {
public static void main(String[] args) {
Integer[][] arr = { { 1, 2 }, { 2, 3 } };
printDimension(arr);
Integer[][] arr1 = { { 1, 2, 4 }, { 2, 3, 6 } };
printDimension(arr1);
}
private static void printDimension(Object arr) {
System.out.println("given object dimension:");
}
}
Can we write some generic code in printDimension method to identify the array dimension??

but I want result in following format for arr it should be 2x2 and arr1 3x2
You should know, that in java you can do this:
Integer[][] arr = { { 1, 2 }, { 1, 3, 4, 5 } };
So the code below doesn't work for jagged arrays.
Also it doesn't work for 0-length arrays such as:
new boolean[11][0][4]
Here the code is:
public static void printDimension(Object array) {
if (array == null) {
System.out.println("Object is null!");
return;
}
if (!array.getClass().isArray()) {
System.out.println("Object is not array!");
return;
}
String ans = "";
Object cur = array;
while (cur != null && cur.getClass().isArray()) {
ans += "x" + Array.getLength(cur);
if (!cur.getClass().getComponentType().isPrimitive()) {
cur = ((Object[]) cur)[0];
} else {
break;
}
}
System.out.println(ans.substring(1));
}
Example of usage:
printDimension(new boolean[1][11]);
printDimension(new boolean[1][11][4]);
printDimension(new Integer[14][88]);
Output:
1x11
1x11x4
14x88

2-D array is a array of arrays. So each array can have variable length (which represents columns in case of 2-D array). You can get length of individual arrays using
args[0].length;
args[1].length;
and so on
and length of whole 2-D array using
args.length
which is number of rows in 2-D array.
Related question: Multi-Dimension length array reflection java

you can use Array.lenght to know the lenght .. and by using this you can find the dimension . for example
int xx = arr.length; // will return the number of row
int yy = arr[0].length; // will return the number of column
N.B. assuming that every row has same number of columns

You can find the dimensions of an array using recursion and reflection.
Given the method dimensions:
private int dimensions(Class arrayType)
{
return arrayType.isArray() ? 1 + dimensions(arrayType.getComponentType()) : 0
}
When calling the dimensions method like this:
int[] oneDimensionalArray = new int[0];
int[][] twoDimensionalArray = new int[0][0];
int[][][] threeDimensionalArray = new int[0][0][0];
System.out.println(dimensions(oneDimensionalArray.getClass()));
System.out.println(dimensions(twoDimensionalArray.getClass()));
System.out.println(dimensions(threeDimensionalArray.getClass()));
Will print:
1
2
3

I think you are asking obj is single dimension or double dimension or ... of array type.
private static void printDimension(Object arr) {
final String className = arr.getClass().toString();
Pattern pattern = Pattern.compile("([\\[])");
Matcher matcher = pattern.matcher(className);
int count = 0;
while (matcher.find()) count++;
int length = count>1?((Object[][])arr)[0].length:0;
System.out.println("given object dimension:"+count+"x"+length);
}
...
Integer[][][] arr = new Integer[3][2][2];
printDimension(arr);
Integer[] arr1 = {};
printDimension(arr1);
printDimension(new Object());
result :
given object dimension:3x2
given object dimension:1x0
given object dimension:0x0

Related

Print array length without using predefined functions

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

Java Calculate all possible combinations of given int array

I am trying to construct a program that would take an array of int({1,2,3} and a length value and calculate all possible combinations of this array.
For example:
int[] arr= new char[] {0,1};
int[] tes = new int[3];
possiblecomb(2, arr,tes,0);
This will output:
00
10
01
11
But i keep getting a Stack overflow error when i try to call the possiblecomb in the for loop
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
// Create an arr to work with
int[] test = new int[] {0,1};
int[] tes = new int[3];
// Find all possible combinations of this arr in the string size of 3
possiblecomb(3, test,tes,0);
}
public static void possiblecomb(int maxLength, int[] nums, int[] curr,int end) {
// If the current array has reached it's maximum length
if(end == maxLength) {
System.out.println(Arrays.toString(curr));
// Else add each number from the numbs to new array and process these new arrays again
} else {
for(int i = 0; i < nums.length; i++) {
int[] oldCurr = curr.clone();
curr[end]= nums[i];
possiblecomb(maxLength,nums,curr,end++);
curr = oldCurr.clone();
}
}
}
}
Try moving your recursive call outside of the for.
You are using the for in order to copy contents.
Your end variable will eventually increment above max lenght, and your (==) comparison won't be a stopper.
Take the example where num.Length = 2 and end is 2 :
You will call your function once with end = 3 which will stop and print inside the recursive call, and next, when i == 1 your end will be 4 and the recursive call won't break.
If you want to avoid the infinite recurssion with your current code in order to better debug with output, put the break condition
if (end>=maxLength)
As #MichaelCMS said you never stop the recursion, hence a stack overflow.
If you don't mind using Lists instead of arrays this is a solution:
import java.util.*;
public class Program {
private static List<List<Integer>> combinations(List<Integer> list, int maxLength) {
return combinations(list, maxLength, new ArrayList(), new ArrayList());
}
private static List<List<Integer>> combinations(List<Integer> list, int length, List<Integer> current, List<List<Integer>> result) {
if (length == 0) {
List<List<Integer>> newResult = new ArrayList<>(result);
newResult.add(current);
return newResult;
}
List<List<List<Integer>>> res3 = new ArrayList<>();
for (Integer i : list) {
List<Integer> newCurrent = new ArrayList<>(current);
newCurrent.add(i);
res3.add(combinations(list, length - 1, newCurrent, result));
}
List<List<Integer>> res2 = new ArrayList<>();
for (List<List<Integer>> lst : res3) {
res2.addAll(lst);
}
return res2;
}
public static void printCombinations(List<Integer> list, int maxLength) {
List<List<Integer>> combs = combinations(list, maxLength);
for (List<Integer> lst : combs) {
String line = "";
for (Integer i : lst) {
line += i;
}
System.out.println(line);
}
}
public static void main(String[] args) {
List<Integer> l = Arrays.asList(0, 1);
printCombinations(l, 2);
}
}
That gives you:
00
01
10
11

comparing values of two arrays if exist or not

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]

Print only the Current Value of an array or array index

Java Novice:
I am using a for loop to iterate an array and check it's values.
For example: If the array contains the number 100. Then do something,
However if it doesn't then get the current value of the current variable.
Is it possible to get the value of the current variable when the check was made?
Currently, when I print using the else I get everything printed out.
Like this:
1
2
3
Found Something!
Please forgive my ignorance. Just experimenting:
public class MyArrayExample {
private int[] intArray = new int[] {1, 2, 3, 100};
public int[] getArrayValues() {
return intArray;
}
public static void main(String[] args)
{
MyArrayExample example = new MyArrayExample();
int[] arrayValues = example.getArrayValues();
for(int counter=0; counter<arrayValues.length; counter++) {
int current = arrayValues[counter];
if(current == 100)
{
System.out.println("Found Something!");
}
else{
System.out.println(current);
}
}
}
}
To get the value of current when the check was made, declare it outside the for loop in order to have the access to the variable value and add a boolean flag isFound:
int current = 0;
boolean isFound = false;
for(int counter=0; counter<arrayValues.length; counter++) {
current = arrayValues[counter];
if(current == 100)
{
isFound = true;
// do something
}
}
Then once the check is made you can get the value of current or print that found something:
if (isFound) {
System.out.println("Found Something!");
} else {
System.out.println("current: " + current);
}
Note. If the value you are looking for is not present in the array, current is always assigned with the last value in the array.
As an addition - you don't even have to write a loop yourself, you can just use existing array/collection methods, for example:
Integer[] intArray = new Integer[] {1, 2, 3, 100};
List<Integer> myList = Arrays.asList(intArray);
System.out.println(myList.contains(100)); // checks if 100 exists in your array
System.out.println(myList.indexOf(100)); // shows the position of the element 100

Join two arrays in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to concatenate two arrays in Java?
I have two objects
HealthMessage[] healthMessages1;
HealthMessage[] healthMessages2;
HealthMessage[] healthMessagesAll;
healthMessages1 = x.getHealth( );
healthMessages2 = y.getHealth( );
How should I join the two objects, so I can return only one:
return healthMessagesAll;
What's the recommended way?
Using Apache Commons Collections API is a good way:
healthMessagesAll = ArrayUtils.addAll(healthMessages1,healthMessages2);
I'd allocate an array with the total length of healthMessages1 and healthMessages2 and use System.arraycopy or two for loops to copy their contents. Here is a sample with System.arraycopy:
public class HelloWorld {
public static void main(String []args) {
int[] a = new int[] { 1, 2, 3};
int[] b = new int[] { 3, 4, 5};
int[] r = new int[a.length + b.length];
System.arraycopy(a, 0, r, 0, a.length);
System.arraycopy(b, 0, r, a.length, b.length);
// prints 1, 2, 3, 4, 5 on sep. lines
for(int x : r) {
System.out.println(x);
}
}
}
This is more intuitive to write and you don't have to deal with array indexes:
Collection<HealthMessage> collection = new ArrayList<HealthMessage>();
collection.addAll(Arrays.asList(healthMessages1));
collection.addAll(Arrays.asList(healthMessages2));
HealthMessage[] healthMessagesAll = collection.toArray(new HealthMessage[] {});
.. but don't ask me about it's performance in contrast to System.arraycopy.
I would go with System.arraycopy
private static HealthMessage[] join(HealthMessage[] healthMessages1, HealthMessage[] healthMessages2)
{
HealthMessage[] healthMessagesAll = new HealthMessage[healthMessages1.length + healthMessages2.length];
System.arraycopy(healthMessages1, 0, healthMessagesAll, 0, healthMessages1.length);
System.arraycopy(healthMessages2, 0, healthMessagesAll, healthMessages1.length, healthMessages2.length);
return healthMessagesAll;
}
Arrays are fixed length, so you have various alternatives. Here are a couple:
a) Create a new array with the size of the others and copy all the elements manually.
healthMessagesAll = new HealthMessage[healthMessages1.length + healthMessages2.length];
int i = 0;
for (HealthMessage msg : healthMessases1)
{
healthMessagesAll[i] = msg;
i++;
}
for (HealthMessage msg : healthMessages2)
{
healthMessagesAll[i] = msg;
i++;
}
b) Use the methods provided by the Arrays class. You can convert the array to a List, or copy elements around in bulk. Have a look at the functions it provides and choose the one that suits you.
UPDATE
Seeing your comment about duplicates. You might want to put everything in a Set which guarantees uniqueness. If you add the same element twice, it won't be added the second time.
You can then convert the Set back to an array if you explicitly require an array with its own toArray() method.
As suggested by other respondents, System.arraycopy() helps you copy the contents of the elements too, so its a shorter version of my alternative (a) above.
And for the most complex but least memory-hungry solution you can wrap them in an object. This one provides an Iterator<T> across all of the items and a copyTo method to copy to a new array. It could be easily enhanced to provide getters and setters.
public class JoinedArray<T> implements Iterable<T> {
final List<T[]> joined;
// Pass all arrays to be joined as constructor parameters.
public JoinedArray(T[]... arrays) {
joined = Arrays.asList(arrays);
}
// Iterate across all entries in all arrays (in sequence).
public Iterator<T> iterator() {
return new JoinedIterator<T>(joined);
}
private class JoinedIterator<T> implements Iterator<T> {
// The iterator across the arrays.
Iterator<T[]> i;
// The array I am working on. Equivalent to i.next without the hassle.
T[] a;
// Where we are in it.
int ai;
// The next T to return.
T next = null;
private JoinedIterator(List<T[]> joined) {
i = joined.iterator();
a = nextArray();
}
private T[] nextArray () {
ai = 0;
return i.hasNext() ? i.next() : null;
}
public boolean hasNext() {
if (next == null) {
// a goes to null at the end of i.
if (a != null) {
// End of a?
if (ai >= a.length) {
// Yes! Next i.
a = nextArray();
}
if (a != null) {
next = a[ai++];
}
}
}
return next != null;
}
public T next() {
T n = null;
if (hasNext()) {
// Give it to them.
n = next;
next = null;
} else {
// Not there!!
throw new NoSuchElementException();
}
return n;
}
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
public int copyTo(T[] to, int offset, int length) {
int copied = 0;
// Walk each of my arrays.
for (T[] a : joined) {
// All done if nothing left to copy.
if (length <= 0) {
break;
}
if (offset < a.length) {
// Copy up to the end or to the limit, whichever is the first.
int n = Math.min(a.length - offset, length);
System.arraycopy(a, offset, to, copied, n);
offset = 0;
copied += n;
length -= n;
} else {
// Skip this array completely.
offset -= a.length;
}
}
return copied;
}
public int copyTo(T[] to, int offset) {
return copyTo(to, offset, to.length);
}
public int copyTo(T[] to) {
return copyTo(to, 0);
}
#Override
public String toString() {
StringBuilder s = new StringBuilder();
Separator comma = new Separator(",");
for (T[] a : joined) {
s.append(comma.sep()).append(Arrays.toString(a));
}
return s.toString();
}
public static void main(String[] args) {
JoinedArray<String> a = new JoinedArray<String>(
new String[]{
"One"
},
new String[]{
"Two",
"Three",
"Four",
"Five"
},
new String[]{
"Six",
"Seven",
"Eight",
"Nine"
});
for (String s : a) {
System.out.println(s);
}
String[] four = new String[4];
int copied = a.copyTo(four, 3, 4);
System.out.println("Copied " + copied + " = " + Arrays.toString(four));
}
}
what about something along this way:
List<String> l1 = Arrays.asList(healthMessages1);
l1.addAll(Arrays.asList(healthMessages2));
HealthMessage[] result = l1.toArray();
(needs a bit of generification... :)

Categories

Resources