I have an Array of Arrays such as:
Arraylist<myObjec> subArray = {item1_1,item1_2, item1_3}
Arraylist<myObjec> subArray = {item2_1,item2_2, item2_3, item2_4}
Arraylist<myObjec> mainArray = {subArray_1,subArray_2}
I want to create the newArray to be something like that:
newArray = {item1_1, item1_2, item2_1, item2_2, item1_3, item2_3, item2_4}
So I want to take a segment of item say get from every subArray 2 item and go back through array of Arrays till I finish.
what would be the best practices to approach this result?
Update:
I tried with this recursive function:
try {
postList = CreateOneListFromSubArrays(mySmoraTemp, postList, 0, countSublArray(mySmoraTemp), 2);
} catch (Exception c){
}
private ArrayList<MyItemClass> CreateOneListFromSubArrays (ArrayList<SmoraItem[]> _array, ArrayList<SmoraItem> result,int n, int _size, int _sectionSize){
if(result.size() < _size){
for (int i=0; i<_array.size(); i++){
for (int j=n; j<n+_sectionSize; j++) {
result.add(i, _array.get(i)[n+j]);
}
}
n += 1;
CreateOneListFromSubArrays(_array, result, n, _size, _sectionSize);
}
return result;
}
but I wonder is there a better way?
You don't have to make it recursive. And one for loop to twice of size of the sorter array is enough.
int array1[] = {1,2,3,4,5,6,7,8,9,8,7,5};
int array2[] = {11,22,33,44,55,66,77,88};
int result[] = new int[array1.length + array2.length];
int y = 0;
for(int x = 0; x < array2.length * 2 ;) { // twice of the sorter's length
result[x++] = array1[y];
result[x++] = array1[y + 1];
result[x++] = array2[y];
result[x++] = array2[y + 1];
y+=2;
}
This is not the soution, you have to find the sorter array first and after this loop you have to handle the remaining elements in the longer array.
Related
The following is my code for Merge Sort in JAVA, but the output is not expected.
given input is [49, 1, 3, 200, 2, 4, 70, 5]
The output is :
Merge sort : [2, 4, 49, 1, 3, 70, 5, 200]
Which the number is not sorted. I believe the problem is in the merge method. Can anyone help?
merge_sort method:
private static int[] merge_sort(int[] unsorted_array) {
if (unsorted_array.length < 2) {
return unsorted_array;
}
int mid = unsorted_array.length / 2;
int[] first_array = new int[mid];
int[] second_array = new int[unsorted_array.length - mid];
//Copy element to first and second array.
for (int i = 0; i < mid; i ++) {
first_array[i] = unsorted_array[i];
}
for (int i = 0; i < second_array.length; i++) {
second_array[i] = unsorted_array[mid + i];
}
merge_sort(first_array);
merge_sort(second_array);
int[] sorted_array = merge(first_array, second_array);
return sorted_array;
}
merge method:
private static int[] merge(int[] first_array, int[] second_array) {
int[] result = new int[first_array.length + second_array.length];
int index_result = 0;
int index_first = 0;
int index_second = 0;
while (index_first < first_array.length && index_second < second_array.length) {
if (first_array[index_first] < second_array[index_second]) {
result[index_result] = first_array[index_first];
index_first++;
} else {
result[index_result] = second_array[index_second];
index_second++;
}
index_result++;
}
while (index_first < first_array.length) {
result[index_result] = first_array[index_first];
index_result++;
index_first++;
}
while (index_second < second_array.length) {
result[index_result] = second_array[index_second];
index_result++;
index_second++;
}
return result;
}
You've made a very simple mistake.
Those two following lines are wrong in your code:
merge_sort(first_array);
merge_sort(second_array);
You should write those two lines as follows:
first_array = merge_sort(first_array);
second_array = merge_sort(second_array);
cause, your merge_sort() method returns a sorted array. It does not sort in place the unsorted_array parameter. Rather, it returns the sorted elements in a newly created sorted_array. So, you would get the sorted result from return value of merge_sort() method and then, you should merge them. Rather than doing that, you were just merging two unsorted arrays.
Its not necessary, but you could write as follows for clarification:
int[] sorted_first_array = merge_sort(first_array);
int[] sorted_second_array = merge_sort(second_array);
// and then merge
int[] sorted_array = merge(sorted_first_array, sorted_second_array);
// then return
return sorted_array;
[P.S.]: When you are coding in java, please use java variable and method naming convention. Its easier to read code when you're following convention.
You are not using the sorted intermediate results to merge, instead using the original splitted arrays. Modify your code as below:
first_array = merge_sort(first_array);
second_array = merge_sort(second_array);
int[] sorted_array = merge(first_array, second_array);
Also you don't need to create these intermediate arrays. You just have to pass the low, high pointers to your array to indicate the portions of the array you are sorting and merging.
Like :
private static void merge_sort(int[] unsorted_array, int low, int high) {
if (low == high) return;
int mid = low + ( high - low ) / 2;
merge_sort(unsorted_array, low, mid);
merge_sort(unsorted_array, mid+1, high);
merge(unsorted_array, low, mid, high);
}
where high is inclusive and you call this like : merge_sort(arr, 0, arr.length-1)
a) Create an array of random numbers, whose size is a power of 2. Using loops, find the difference for each pair of values (index 0 & 1, 2 & 3, 4 & 5 etc.) and store them in a new array. Then find the difference for each pair of differences and so on until you have only one difference left.
Hint: Think carefully about your loop bounds
b) Now, create a solution that is 'in place', i.e., It does not require the creation of new arrays. Again, this will require careful consideration of loop bounds.
c) Finally, write a solution that makes use of a recursive function, instead of loops.
I have been trying to solve the above exercise but I am stuck with what b means and how can I use recursive function. The following is my solution for part a :
public class RandomArray{
private static double ArrayFn(int p){
double[] orignalArray = new double[(int)Math.pow(2,p)];
for (int i = 0; i< orignalArray.length; i++){
orignalArray[i] = (int)(Math.random() * 10) ;
}
System.out.println(Arrays.toString(orignalArray));
double y = ArrayDifferenceloop(orignalArray);
System.out.println("Value of Array" + y);
return y;
}
private static double ArrayDifferenceloop(double[] arg){
do{
double[] newArr = new double[(arg.length/2)];
for (int i = 0; i< arg.length; i+=2){
newArr[i/2] = arg[i] - arg[i+1];
}
System.out.println("New Array is =" + Arrays.toString(newArr));
//copy newArr to arg
arg = new double[(newArr.length)];
System.arraycopy(newArr,0,arg,0,newArr.length);
}while(arg.length > 1);
return arg[0];
}
public static void main(String[] args){
double z = ArrayFn(3);
System.out.println("value" + z);
}
}
I can help you with point b)
you can store the differences in the original array itself:
difference of [0] and [1] put in [0],
difference of [2] and [3] put in [1],
and so on.
You can calculate the index to put the result from the indexes of the pair or keep two index variables for the result and for picking the pairs.
you just keep iterate over the original array repeatedly, each time over fewer cells until only two cells left.
the recursive solution should be clear...
I guess option b means use the original array to store the differences, rather than creating a new array.
This can be achieved by dynamically changing the active range of elements used, ignoring others (see also Sharon Ben Asher answer ):
private static double ArrayDifferenceloop(double[] array){
int activeLength = array.length;
do{
int index =0; //index where to store difference
for (int i = 0; i< activeLength; i+=2){
array[index++] = array[i] - array[i+1];
}
System.out.println("Modified array (only "+index+ " elements are significant) " + Arrays.toString(array));
activeLength /=2;
}while(activeLength > 1);
return array[0];
}
/* Solution for part (b) hope it works for you*/
public class RandomArray{
static int len; /*modification*/
private static double ArrayFn(int p){
double[] orignalArray = new double[(int)Math.pow(2,p)];
len=(int)Math.pow(2,p);
for (int i = 0; i< orignalArray.length; i++){
orignalArray[i] = (int)(Math.random() * 10) ;
}
System.out.println(Arrays.toString(orignalArray));
double y = ArrayDifferenceloop(orignalArray);
System.out.println("Value of Array" + y);
return y;
}
private static double ArrayDifferenceloop(double[] arg){
do{
for (int i = 0; i< len; i+=2){ /*modification*/
arg[i/2] = arg[i] - arg[i+1];
}
//copy newArr to arg
//arg = new double[(arg.length)];
len=len/2; /*modification*/
System.out.print("new Array : ");
for(int i=0;i<len;i++){
System.out.print(arg[i]+" , ");
}
// System.arraycopy(arg,0,arg,0,len);
}while(len > 1);
return arg[0];
}
public static void main(String[] args){
double z = ArrayFn(3);
//System.out.println(Arrays.toString(orignalArray));
System.out.println("value" + z);
}
}
To simplify the context, Let's say we have a 2D array in Java and we need to get the index of given 1D array. Is there any cleaner way of doing the same? The size of my array was pretty small (3 x 8), So I managed to brute force the elements using a for loop and got the index, But what if the size of array is large enough? For my purpose I used the following code:
private int getIndex(double[][] centerArrayOriginal, double[] row){
double[] currRow;
int index = -1;
for (int i=0; i<centerArrayOriginal.length;i++){
currRow = centerArrayOriginal[i];
if ((currRow[0] == row[0]) && (currRow[1] == row[1]) && (currRow[2] == row[2])){
index = i;
}
}
return index;
}
Obviously this is not the most cleaner way of doing the same, I tried using an ArrayList of double[] elements and used .indexOf() method, but it always returned -1.
If you have to search for a given row within an array, I don't see an alternative to "brute-forcing". However, as you are working with double arrays, it should be noted that because of rounding errors, the row-finding algorithm may not work if the row 1D array comes from e.g. a calculation result. You should only assume reliable results when the data for both centerArrayOriginal and row consist of double literals (constants).
Anyways, here is a solution that uses two nested for-loops for finding the row from a 2D array of arbitrary size:
private static int getIndex(double[][] centerArrayOriginal, double[] row) {
for (int i = 0; i < centerArrayOriginal.length; i++) {
double[] currRow = centerArrayOriginal[i];
if (currRow.length != row.length) {
throw new IllegalArgumentException(String.format(
"The size of the input row (%d) does not "
+ "match the size of the rows in the array (%d)",
row.length, currRow.length));
}
boolean allElementsEqual = true;
for (int j = 0; j < row.length; j++) {
if (currRow[j] != row[j]) {
allElementsEqual = false;
break;
}
}
if (allElementsEqual) {
return i;
}
}
return -1;
}
Code for testing:
double[][] data = new double[][]
{
{ 1.0d, 2.0d, 3.0d },
{ 4.0d, 5.0d, 6.0d },
{ 7.0d, 8.0d, 9.0d }
};
double[] test = new double[] {4.0d, 5.0d, 6.0d};
System.out.println(getIndex(data, test));
prints out
1
I used an ArrayList at first. But then my course teacher told me that I can't use ArrayList in my program. He said that I can only use arrays.
The problem is when I add an integer to array, it just puts zero on the first index.
Here is the code :
int[] Bag = new int[1];
boolean isit = true;
do {
int[] NewBag = new int[Bag.length + 1];
String name = scanner.next();
if (name.equals("A")){
int number = scanner.nextInt();
for (int i = 0; i < Bag.length; i++) {
NewBag[NewBag.length - 1] = number;
NewBag[i] = Bag[i];
}
Bag = NewBag;
System.out.println(number + " added to Bag.");
}
} while (isit == true);
Please help me guys. I can't make Minimum and Size operations without the correct Add operation.
You start with a single-element array, and immediately add a second element to it:
int[] NewBag = new int[Bag.length + 1];
Thus by the time you've read one number your array already contains two elements (i.e. one element too many).
To correct this, you need to change the
int[] Bag = new int[1];
to
int[] Bag = new int[0];
If this looks odd, see Why does Java allow arrays of size 0?
You'll also need to move
NewBag[NewBag.length - 1] = number;
out of the loop.
I don't know what you want to do with your array, but if you want to wrap an array into something, that has similar methods to an ArrayList, you could do something like this (mind, that once it reaches the array's size, int wont grow.):
class MyArray {
private final int[] mArray;
private int mSize = 0;
public MyArray(final int maxSize) {
mArray = new int[maxSize];
}
public void add(final int element) {
if (mSize < mArray.length) {
mArray[mSize++] = element;
} else {
throw new IndexOutOfBoundsException("No more room");
}
}
public int get(final int index) {
return mArray[index];
}
public int size() {
return mSize;
}
}
Then you could do your logic:
int maxSize = scanner.nextInt();
MyArray array = new MyArray(maxSize);
for(int i=0; i<maxSize; i++) {
array.add(scanner.nextInt());
}
I have an array of numbers and I need the biggest of three number with respective index value. I have an array like this:
int [] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;
How to find the largest numbers and their index values?
I suspsect this is homework, so I'm going to give some help, but not a full solution.
You need the biggest three numbers, as well as their index values?
Well, walk over the array, keeping track of the highest three numbers you have found so far. Also keep track of their index numbers.
You could start by doing this for only the biggest number and its index. That should be easy.
It takes two variables, e.g. BiggestNumber and indexOfBiggestNumber. Start with finding the biggest number (trivial), then add some code to remember it's index.
Once you have that, you can add some more code to keep track of the second biggest number and it's index as well.
After that, you do the same for the third biggest number.
I have done it for you, and this works.
here goes the complete code:
import java.util.Arrays;
class tester {
public static void main(String[] args) {
int[] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;
int size = value.length;
int[] temp = (int[]) value.clone();
Arrays.sort(temp);
for (int i = 0; i < 3; i++) {
System.out.println("value: " + temp[size - (i + 1)] +
" index " + getIndex(value, temp[size - (i + 1)]));
}
}
static int getIndex(int[] value, int v) {
int temp = 0;
for (int i = 0; i < value.length; i++) {
if (value[i] == v) {
temp = i;
break;
}
}
return temp;
}
}
No need to traverse through array and keep tracking of so many variables , you can take advantage of already implemented methods like below.
I would suggest to use a List of Map.Entry<key,value > (where key=index and value=number) and then implement Comparator interface with overridden compare method (to sort on values). Once you have implemented it just sort the list .
public static void main(String[] args) {
int[] value = {5, 3, 12, 12, 7};
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int k = 0; k < value.length; k++)
map.put(k, value[k]);
List<Map.Entry<Integer, Integer>> list =
new LinkedList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(
Entry<Integer, Integer> e1,
Entry<Integer, Integer> e2) {
return e2.getValue().compareTo(e1.getValue());
}
});
for (Entry<Integer, Integer> lValue : list)
System.out.println("value = " + lValue.getValue()
+ " , Index = " + lValue.getKey());
}
Results:
value = 12 , Index = 2
value = 12 , Index = 3
value = 7 , Index = 4
value = 5 , Index = 0
value = 3 , Index = 1
By this approach you can get top N largest numbers with their index.
To get the three biggest, basically, you sort, and pick the last three entries.
Getting their indexes takes a little more work, but is definitely doable. Simply bundle the number and its index together in a Comparable whose compareTo function only cares about the number. Sort, get the last three items, and now you have each number and its index.
class IntWithIndex implements Comparable<IntWithIndex> {
public int number, index;
public IntWithIndex(number, index) {
this.number = number;
this.index = index;
}
public int compareTo(IntWithIndex other) {
return number - other.number;
}
}
...
IntWithIndex iwi[] = new IntWithIndex[yourNumbers.length];
for (int i = 0; i < yourNumbers.length; ++i) {
iwi[i] = new IntWithIndex(yourNumbers[i], i);
}
Arrays.sort(iwi);
int largest = iwi[iwi.length - 1].number;
int largestIndex = iwi[iwi.length - 1].index;
// and so on
Sort the array in descending order and show the first 3 element.