How to merge two sorted arrays in Java? - java

I'm trying to create a third sorted array, c, from the two previously created arrays, a and b; however, I'm getting several errors within the merge method that say "The type of the expression must be an array type but it resolved to OrdArray". I've been at it for hours already, and feel like my brain is mush now. Can someone help me out?
class OrdArray
{
private long[] a; // ref to array a
private int nElems; // number of data items
//-----------------------------------------------------------
public OrdArray(int max) // constructor
{
a = new long[max]; // create array a
nElems = 0;
}
//-----------------------------------------------------------
public int size()
{ return nElems; }
//-----------------------------------------------------------
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;
while (true)
{
curIn = (lowerBound + upperBound ) / 2;
if (a[curIn] == searchKey)
return curIn; // found it
else if (lowerBound > upperBound)
return nElems; // can't find it
else // divide range
{
if (a[curIn] < searchKey)
lowerBound = curIn + 1; // it's in upper half
else
upperBound = curIn - 1; // it's in lower half
} // end else divide range
} // end while
} // end find()
//-----------------------------------------------------------
public void insert(long value) // put element into array
{
int j;
for (j = 0; j < nElems; j++) // find where it goes
if (a[j] > value) // (linear search)
break;
for (int k = nElems; k > j; k--) // move bigger ones up
a[k] = a[k-1];
a[j] = value; // insert it
nElems++; // increment size
} // end insert()
//-----------------------------------------------------------
public boolean delete(long value)
{
int j = find(value);
if (j == nElems) // can't find it
return false;
else // found it
{
for (int k = j; k < nElems; k++) // move bigger ones down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
} // end delete()
//-----------------------------------------------------------
public void display() // displays array contents
{
for (int j = 0; j < nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}
//-----------------------------------------------------------
public static long[] merge(OrdArray a, OrdArray b)
{
long[] c = new long[a.nElems + b.nElems];
int i = 0, j = 0, k = 0;
while (i < a.nElems && j < b.nElems)
{
if (a.data[i] < b.data[j])
c[k++] = a.data[i++];
else
c[k++] = b.data[j++];
}
while (i < a.nElems)
c[k++] = a.data[i++];
while (j < b.nElems)
c[k++] = b.data[j++];
return c;
}
} // end class OrdArray
////////////////////////////////////////////////////////////////
class OrderedApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
OrdArray a, b, c; // reference to array
a = new OrdArray(maxSize); // create the array
b = new OrdArray(maxSize);
c = new OrdArray(maxSize);
a.insert(11);
a.insert(13);
a.insert(15);
a.insert(17);
a.insert(19);
a.insert(21);
a.insert(23);
a.insert(25);
a.insert(27);
a.insert(29);
b.insert(12);
b.insert(14);
b.insert(16);
b.insert(18);
b.insert(20);
b.insert(32);
b.insert(24);
b.insert(26);
b.insert(28);
b.insert(30);
OrdArray.merge(a,b);
System.out.print("Array a: ");
a.display();
System.out.println();
System.out.print("Array b: ");
b.display();
System.out.println();
System.out.print("Array c: ");
c.display();
System.out.println();
} // end main()
}// end class OrderedApp

OrdArray is not an array type (despite the name); therefore, you can't index it like an array. This expression
a[i++]
where a is an OrdArray, will have no meaning. Java doesn't give you a way to define your own [] operator for classes (unlike C++). Therefore, you'll have to add a method to OrdArray to return the element at a given index, something like
public long get(int index) { ...write the code... }
a.get(i++) // will then get the element at that index
Although I'm not sure this is what you want, since you've declared c to be an int[] and the array in OrdArray to be a long[], so I'm not sure what you're trying to do.
EDIT: After reading your comment, I realized that the merge method is inside the OrdArray class. I missed that before. Since that's the case, you don't need to add a get method; you can access the private fields of your OrdArray parameters directly. In your method:
public void merge(OrdArray a, OrdArray b)
you want to get at the private array a that you declare for each OrdArray. If you just use a, the variable will refer to the OrdArray, which isn't an array (as described above); to get at the long[] a belonging to the OrdArray a, you need to say
a.a[i++]
and likewise, for b,
b.a[i++]
This can look confusing to a reader, so I suggest coming up with a better name so that you're not calling two things a. Perhaps data?
A couple other things: You use merge like this: c.merge(a,b), which means that merge is an instance method and c is the instance you're operating on. But your method doesn't do anything with the current instance. (The c you declare in merge is a local variable that has nothing to do with the c you use when calling merge.) Right now, your method is going to a lot of trouble to construct the local array c, but then it just throws it away. You either need to (1) fix the method so that it sets up the a (or data) array in the current instance; or (2) make it a static method and make the method return the new array as a function result. I'm not sure which one your instructor wants you to do.

I'm not exactly sure what you are trying to do. But to resolve error, i have corrected the articular block.
To note, OrdArray class is not an array. It's a class that has a long[] a. So you need to get the array like any other property from the object.
For betterment, please change the method signature like this:
public void merge(OrdArray ordArr1, OrdArray ordArr2) {//Note parameters' name change
.
.
.
while (i < ordArr1.nElems && j < ordArr2.nElems)
{
if (ordArr1.a[i] < ordArr2.a[j]) //should resolve
c[k++] = ordArr1.a[i++];
else
c[k++] = ordArr2.a[j++];
}
while (i < a.nElems)
c[k++] = ordArr1.a[i++];
while (j < b.nElems)
c[k++] = ordArr2.a[j++];
}

If you accept solution wit Lists it would be:
List<Integer> result = new ArrayList<Integer>(Arrays.asList(sourceArray));
result.addAll(Arrays.asList(secondSourceArray));
Collections.sort(result);
You can optionally convert it back to array with
result.toArray();

I am confused why you are using binary search. Simple way is to insert two arrays using two insert methods or one. Using a merge method, just merge those two already sorted arrays by comparing the least element among two sorted arrays.
Remove delete, search etc methods, they are not required.
This is my code. I have inserted two integer arrays(elements) into inserta() and insertb() sorted them and merged them using insert() method. Finally I have this sorted array after merging them. Please see my code here:
package sample;
/**
*
* #author Shivasai
*/
public class Merge {
int i;
int j;
int k;
int n;
int m;
int p;
private long[] a;
private long[] b;
private long[] c;
public Merge()
{
a=new long[10];
b=new long[10];
c=new long[100];
n=0;
m=0;
p=0;
}
void inserta(long key)
{
for(i=0;i<n;i++)
{
if(a[i]>key)
break;
}
for(j=n;j>i;j--)
{
a[j]=a[j-1];
}
a[j]=key;
n++;
}
void insertb(long value)
{
for(i=0;i<m;i++)
{
if(b[i]>value)
break;
}
for(j=m;j>i;j--)
{
b[j]=b[j-1];
}
b[j]=value;
m++;
}
void insert()
{
i=0;
j=0;
while(i>n || j<m)
{
if(a[j]<b[i])
{
c[p]=a[j];
j++;
p++;
}
else
{
c[p]=b[i];
i++;
p++;
}
}
}
void displaya()
{
for(k=0;k<10;k++)
{
System.out.print("," +a[k]);
}
System.out.println();
}
void displayb()
{
for(k=0;k<10;k++)
{
System.out.print("," +b[k]);
}
System.out.println();
}
void displayc()
{
for(k=0;k<20;k++)
{
System.out.print("," +c[k]);
}
}
public static void main(String[] args)
{
Merge obj = new Merge();
obj.inserta(25);
obj.inserta(12);
obj.inserta(1800);
obj.inserta(9);
obj.inserta(10);
obj.inserta(15);
obj.inserta(18);
obj.inserta(19);
obj.inserta(0);
obj.inserta(1500);
obj.insertb(36);
obj.displaya();
obj.insertb(2);
obj.insertb(3);
obj.insertb(2000);
obj.insertb(5);
obj.insertb(6);
obj.insertb(7);
obj.insertb(8);
obj.insertb(21);
obj.insertb(85);
obj.displayb();
obj.insert();
obj.displayc();
}
}

Related

Adding elements to the beginning of an array of ints

Working on an addBefore() method that adds a new element to the beginning of an array of ints and then causes the existing elements to increase their index by one.
This is what is showing in the console when trying to run --
java.lang.RuntimeException: Index 1 should have value 11 but instead has 0
at IntArrayListTest.main(IntArrayListTest.java:67)
Below is the code I have so far.
public class IntArrayList {
private int[] a;
private int length;
private int index;
private int count;
public IntArrayList() {
length = 0;
a = new int[4];
}
public int get(int i) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
return a[i];
}
public int size() {
return length;
}
public void set(int i, int x) {
if (i < 0 || i >= a.length) {
throw new ArrayIndexOutOfBoundsException(i);
}
a[i] = x;
}
public void add(int x) {
if (length >= a.length) {
int[] b = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
a = b;
//count += 1;
}
a[length] = x;
count++;
length = length + 1;
}
public void addBefore(int x) {
int[] b = new int[a.length*2];
for (int i = 0; i < a.length; i++) {
b[i+a.length] = a[i];
}
a = b;
a[index] = x;
length ++;
}
}
Whether you add first or last, you need to only grow the array size if it is already full.
The count field seems to be exactly the same as length, and index seems unused and meaningless as a field, so remove them both.
To rearrange values in an array, use this method:
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
You two "add" methods should then be:
public class IntArrayList {
private int[] a; // Underlying array
private int length; // Number of added elements in a
// other code
public void add(int x) {
if (length == a.length) {
int[] b = new int[a.length * 2];
System.arraycopy(a, 0, b, 0, length);
a = b;
}
a[length++] = x;
}
public void addBefore(int x) {
if (length < a.length) {
System.arraycopy(a, 0, a, 1, length);
} else {
int[] b = new int[a.length * 2];
System.arraycopy(a, 0, b, 1, length);
a = b;
}
a[0] = x;
length++;
}
}
If the answer requires you to do the looping yourself then something like this should work fine (one of a few ways to do this, but is O(n)) :
public void addBefore(int x) {
if(length + 1 >= a.length){
int[] b = new int[a.length*2];
b[0] = x;
for (int i = 0; i < length; i++) {
b[i + 1] = a[i];
}
a = b;
} else {
for (int i = length; i >= 0 ; i--) {
a[i + 1] = a[i];
}
a[0] = x;
}
length++;
}
I noticed this started running a "speed test" - not sure how useful a test like that is, as it would be based on cpu performance, rather than testing complexity of the algorithm ..
you had three problems with your solution:
you increased the length of a every time the method was called. this would quickly create an OutOfMemoryException
when you copied values from a to b, you did b[i+a.length] = a[i]; which means the values would be copied to the middle of b instead of shift just one place
at the end, you put the new value in the end of the array instead of at the beginning.
all this I was able to see because I used a debugger on your code. You need to start using this tool if you want to be able to detect and fix problems in your code.
so fixed solution would do this:
check if a is full (just like it is done with add() method) and if so, create b, and copy everything to it and so on)
move all values one place ahead. the easiest way to do it is to loop backwards from length to 0
assign new value at the beginning of the array
here is a working solution:
public void addBefore(int x) {
// increase length if a is full
if (length >= a.length) {
int[] b = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
a = b;
}
// shift all values one cell ahead
for (int i = length; i > 0; i--) {
a[i] = a[i-1];
}
// add new value as first cell
a[0] = x;
length ++;
}
}
You can use the existing Java methods from the Colt library. Here is a small example that uses a Python syntax (to make the example code small I use Jython):
from cern.colt.list import IntArrayList
a=IntArrayList()
a.add(1); a.add(2) # add two integer numbers
print "size=",a.size(),a
a.beforeInsert(0, 10) # add 10 before index 0
print "size=",a.size(),a
You can use DataMelt program to run this code. The output of the above code is:
size= 2 [1, 2]
size= 3 [10, 1, 2]
As you can see, 10 is inserted before 1 (and the size is increased)
Feel free to change the codding to Java, i.e. importing this class as
import cern.colt.list.IntArrayList
IntArrayList a= new IntArrayList()
You could use an ArrayList instead and then covert it to an Integer[] Array which could simplify your code. Here is an example below:
First create the ArrayList:
ArrayList<Integer> myNums = new ArrayList<Integer>();
Next you can add the values that you want to it, but I chose to just add the numbers 2-5, to illustrate that we can make the number 1 the first index and automatically increment each value by one index. That can simplify your addBefore() method to something such as this:
public static void addBefore(ArrayList<Integer> aList) {
int myInt = 1;
aList.add(0, myInt);
}
Since your ArrayList has ONE memory location in Java, altering the Array within a method will work (this would also work for a regular Array). We can then add any value to the beginning of the ArrayList. You can pass an Integer to this method as the second argument (int x), if you want, but I simply created the myInt primitive to simplify the code. I know that in your code you had the (int x) parameter, and you can add that to this method. You can use the ArrayList.add() method to add the int to index 0 of the Array which will increment each Array element by 1 position. Next you will need to call the method:
addBefore(myNums);//You can add the int x parameter and pass that as an arg if you want here
Next we can use the ArrayList.toArray() method in order to covert the ArrayList to an Integer Array. Here is an example below:
Integer[] integerHolder = new Integer[myNums.size()];
Integer[] numsArray = (Integer[])myNums.toArray(integerHolder);
System.out.println(Arrays.toString(numsArray));
First we create an ArrayHolder that will be the same size as your ArrayList, and then we create the Array that will store the elements of the ArrayList. We cast the myNums.toArray() to an Integer Array. The results will be as follows. The number 1 will be at index 0 and the rest of your elements will have incremented by 1 index:
[1, 2, 3, 4, 5]
You could do the entire process within the addBefore() method by converting the Array to an ArrayList within the method and adding (int x) to the 0 index of the ArrayList before converting it back into an Array. Since an ArrayList can only take a wrapper class object you'll simply need to convert the int primitive Array into the type Integer for this to work, but it simplifies your addBefore() method.

Sorting Integer array using Comparable

I am working on a project in which I have to sort an array of Integer objects by using Comparable.
My add method takes an item of type E. If my size variable (which tracks the elements in my array theData[]) is = 0 (which it is initialized to), I simply put the item in theData[0].
If it is not, I use item.compareTo to compare the item against each item already in the array. If the result of compareTo is < 0 for a number in the array, I shift everything at that number and after to the right, and insert the item before it.
If compareTo returns a 0, meaning the item is equal to the number in the array, I do nothing as I don't want duplicates in the array.
If none of the compareTo statements in the loop return a -1 or a 0, I put the item in theData[size], the end of the array, as it must be larger than all the other numbers.
However, this doesn't work. Any time I make a new Set and add a few numbers to it, then try to print out the contents of my set using a for loop,I keep getting a java.lang.ArrayIndexOutOfBoundsException: 10 error for this line:
theData[j + 1] = theData[j];
I've tried starting from scratch and re-writing my loop with different logic, and each time I keep hitting this wall. I know I must either be shifting incorrectly or not increasing the size of the array correctly with my reallocate method, but I can't wrap my head around it.
import java.util.*;
public class Set<E extends Comparable<E>> {
String s;
String name;
private static final int INITIAL_CAPACITY = 10;
private E[] theData;
private int size = 0;
private int capacity = INITIAL_CAPACITY;
#SuppressWarnings("unchecked")
public Set() {
theData = (E[]) new Comparable[capacity];
}
public Set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void add(E item) {
if (size == capacity) {
reallocate();
}
if (size == 0) { // If size is 0, add item to theData[0]
theData[size] = item;
size++;
return;
}
else { // Else compare the item to every item in loop.
for (int i = 0; i < size; i++) {
int result = item.compareTo(theData[i]);
if (result < 0) {
for (int j = 0; j < size; j++) { //If item is less than a number, shift everything
theData[j + 1] = theData[j]; //after that index to the right, and add item
theData[j] = item;
}
}
if (result == 0) {
return;
}
else { //If item is not less than or equal to any
theData[size] = item; //numbers in the array, add it to the end
size++;
}
}
}
}
/*
* if (size>=1){ int result = item.compareTo(theData[size-1]); if(result<0){
* E temp = theData[size-1]; theData[size-1] = item; theData[size] = temp; }
* if(result>1){ return; } }
*/
public E get(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return theData[index];
}
public int size() {
return size;
}
private void reallocate() {
capacity = 2 * capacity;
theData = Arrays.copyOf(theData, capacity);
}
}
Edit: The driver method I'm using to test it -
public class Driver {
String one = "two";
public static void main(String[] args){
Set<Integer> one = new Set<Integer>();
one.add(63);
one.add(20);
one.add(127);
one.add(10);
one.add(26);
one.add(15);
for(int i = 0; i < one.size(); i++){
System.out.println(one.get(i));
}
}
}
When j == size - 1, theData[j+1] will take you out of the array.
You want to loop to one before the end instead.
for (int j = 0; j < size - 1; j++) { //If item is less than a number, shift everything
theData[j + 1] = theData[j]; //after that index to the right, and add item
theData[j] = item;
}
So I've also taken a look at the logic you've got for the insertion, and it doesn't make a lick of sense. Why do you delay the insertion at all? If you've got the room, just add it!
Next, the double loops are essentially implementing bubble sort, but there's a fatal flaw with it: you don't ever complete the swap; you only overwrite your values repeatedly. You're also not comparing in the right direction; you want to swap if the value on the left is larger than the value on the right, since you're starting from the beginning of the array.
So, with that...this is what an implementation would have the form of...
public void add(E item) {
if (size == capacity) {
reallocate();
}
theData[size++] = item;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 1; j++) {
if (theData[j].compareTo(theData[j + 1]) > 0) {
// perform the swap (you need an extra variable!
}
}
}
}
I leave implementing the swap as an exercise for the reader.
First, in your shift loop, you are inserting the new item in every position instead of shifting then inserting in [i] because you copy theData[j] to the next position, but always assign item to theData[j], is that right?
Second, you are starting from the beginning of array since j starts with 0. J should start with i.
Third and main bug, you verify if result < 0 then you verify IF result == 0, change for a ELSE IF so the else don't get executed even when result < 0
shift elements to right can be done from right to left, like:
for (int j = size; j > i; j--) { // If item is less than a
// number, shift
// everything
theData[j] = theData[j - 1]; // after that index to the
// right, and add item
}
size++;
theData[i] = item;
break;// after insert the number, we can just break the for loop
once the new number is inserted, break the for loop, else, the size variable will not be correct
else { // If item is not less than or equal to any
theData[size] = item; // numbers in the array, add it to the end
size++;
break;
}

Storing a 2d array elements in an arrayList

I have a 2d grid of integers.
grid[][];
Suppose I am given an element randomly from the 2d array. My aim is to return its adjacent grid elements.
For that I am creating an ArrayList
ArrayList<int[][]> adjacentSidesList = new ArrayList<int[][]>();
I would have to go for quite a few number of cases and in each case the number of the adjacentSides would be different. So my choice of data structure is an ArrayList
But when I would add an element to the list
adjacentSidesList.add(grid[row][column+1]);
I understand this is wrong because I am adding the value of the grid element to the ArrayList and not the element itself. Does anyone have any idea on how to store the arrayElements in the arrayList and not the value stored in them ??
Any alternate method is also welcome with the reasons why the method is better
Thanks in Advance
Your grid object is a two-dimensional integer array. grid[row][column+1] is an integer, located in the respective indexes in your grid.
adjacentSidesList.add(grid[row][column+1]);
will not work, because you want to add an int to a list of ArrayList of two-dimensional int arrays. I believe you want to store numbers and you want to know what are those numbers. I wonder about the definition of neighbor. I will suppose here that the neighbor is the element located up, down, left or right to the current element, or, to put it more scientifically, the elements being located exactly at a distance of 1 from the current element in Taxicab-geometry.
The first problem is that a point might be at the margin of your space, which would mean they do not have a neighbor. The next problem is a general formula for the neighbors. I believe your numbers should be aware of their position, therefore we should define the following class:
public class GridHandler {
private static GridHandler[][] grid;
private int i;
private int j;
private int value;
public static void init(int[][] input) {
int rowNumber = input.length;
int columnNumber = input[0].length;
grid = new GridHandler[rowNumber][columnNumber];
for (int r = 0; r < rowNumber; r++) {
for (c = 0; c < columnNumber; c++) {
grid[r][c] = new GridHandler(r, c, input[r][c]);
}
}
}
public static GridHandler[][] getGrid() {
return grid;
}
public GridHandler(int i, int j, int value) {
this.i = i;
this.j = j;
this.value = value;
grid[i][j] = this;
}
public int getValue() {
return value;
}
public void setValue(value) {
this.value = value;
}
public int getLeftValue() throws ArrayIndexOutOfBoundsException {
if (j == 0) {
throw new ArrayIndexOutOfBoundsException("Left edge");
}
return grid[i][j - 1].getValue();
}
public int getUpValue() throws ArrayIndexOutOfBoundsException {
if (i == 0) {
throw new ArrayIndexOutOfBoundsException("Up edge");
}
return grid[i - 1][j].getValue();
}
public int getRightValue() throws ArrayIndexOutOfBoundsException {
if (j == grid[0].length - 1) {
throw new ArrayIndexOutOfBoundsException("Right edge");
}
return grid[i][j + 1].getValue();
}
public int getDownValue() throws ArrayIndexOutOfBoundsException {
if (i == grid.length - 1) {
throw new ArrayIndexOutOfBoundsException("Down edge");
}
return grid[i + 1][j].getValue();
}
}
Now, if you use that class, each element will be aware of their neighbors. You can initialize the whole thing like this:
GridHandler.init(grid);
I hope this helps.
You could create a new class which will hold row and column index of 2D array element like:
class Index {
private int row;
private int column;
//getter and setters
}
Now when you want to store the data in list, you store the index object and when you have to access the element, you can access it like:
Index index = adjacentSidesList.get(0);
int element = grid[index.getRow()][index.getColumn()];

toString method with adjustable Array size

Every source I've looked at I either don't understand, doesn't seem to apply, or uses something like an Array list. I'm not familiar with those. So I'd like to use a basic toString method that prints out the index of the array as well as the number held when compared to the variable 'length' -- num.length could be different as that's the physical size of the underlying array. The for loop at the bottom has the gist of it. I'm trying to print out the index (0-infinite) with int's that are held in the resizeable array. The variable 'length' is not the actual size of the array but a working size that contains 0 until another cell is added. The 'strang' variable is just something I've tried. I don't think it will work, but anything else I doesn't seem to help as I'm stuck.
public class XArray
{
private int[] nums;
private int length;
public XArray()
{
nums = new int[10];
length = 0;
}
public void add(int value)
{
if (length == nums.length)
{
int[] nums2 = new int[(int)(nums.length * 1.2)];
for ( int i = length - 1; i >= 0; i-- )
{
nums2[i] = nums[i];
}
nums = nums2;
}
nums[length] = value;
length++;
}
public void set(int index, int value)
{
if (index < length)
{
nums[index] = value;
}
}
public int get(int index)
{
return nums[index];
}
public int size()
{
return length;
}
public void remove()
{
nums[length - 1] = 0;
length--;
}
public String toString(int[] nums)
{
String strang = "l";
for ( int i = 0 ; i < length; i++ )
{
strang = "Index: " + i + " Number: " + nums[i] + ", ";
}
return strang;
}
}
You need to concatenate the values on each iteration of the loop...something like...
public String toString(int[] nums)
{
StringBuilder strang = new StringBuilder(length);
for ( int i = 0 ; i < length; i++ )
{
strang.append("Index: ").append(i).append(" Number: ").append(nums[i]).append(", ");
}
return strang.toString();
}
Generally speaking, toString should't take parameters, there would a difference between nums and length which could cause issues
#Override
public String toString() {...
This way, you will be printing the contents of the objects num array, which is contextually associated with length
You probably meant to use += instead of = in that method (though many people will tell you to use a StringBuilder because successive concatenations, if not optimized by a compiler` will generate a lot of garbage).
Also, don't pass in nums! You want to use the field nums; passing in an argument will use the argument. The real toString has no parameters (and should have an #Override annotation).

Is there any counterpart of MATLAB function numel in java?

I'm trying to use numel (function available in Matlab) in java.
Are they any implementations of this function available in java?
I am not sure if this is how you want numel to work but here you have few versions:
version1 - for arrays with irregular size like {{1},{2,3}}
this method will iterate over all elements of array counting them.
public static int numel(Object array) {
if (array == null)
return 1;// I will count nulls as elements since new String[10] is
// initialized with nulls
int total = 1;
if (array.getClass().isArray()) {
total = 0;
int length = java.lang.reflect.Array.getLength(array);
for (int index = 0; index < length; index++) {
total += numel(java.lang.reflect.Array.get(array, index));
}
}
return total;
}
version2 - for arrays with regular size like new String[2][3][4]
this method will only use size of first rows of different levels in array to get it size assuming that rows at same level have same size
public static int regularNumel(Object array) {
if (array == null)
return 1;
int total = 1;
if (array.getClass().isArray()) {
int length = java.lang.reflect.Array.getLength(array);
if (length > 0) {
Object row = java.lang.reflect.Array.get(array, 0);
if (row == null || !row.getClass().isArray())
return length;
else //now we know that row is also array
return length * regularNumel(row);
} else
return 0;
}
return total;
}
class main{
public static void main (String[] args){
// numel returns the number of array elements, as does .length in Java.
int[] testArr = {1,2,3,4,5,6,7,8};
System.out.println(testArr.length);
}
}
// Result: 8
I managed to solve this problem.
How I wish the size of an image, I made a small function that solved my problem.
public static int length(BufferedImage bi)
{
int x;
x=bi.getHeight()*bi.getWidth();
return x;
}
The numel function of matlab
n = numel(A) returns the the number of elements, n, in array A.
You Can make yours like
int arraycount(int a[])
{
int counter;
for(int i=0;i<a.length;i++)
{
counter++;
}
return counter;
}

Categories