Related
I have an array of objects in Java, and I am trying to pull one element to the top and shift the rest down by one.
Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0 and all elements from 0 to 5 will be shifted down by one.
This algorithm does not properly shift the elements:
Object temp = pool[position];
for (int i = 0; i < position; i++) {
array[i+1] = array[i];
}
array[0] = temp;
How do I do it correctly?
Logically it does not work and you should reverse your loop:
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
Alternatively you can use
System.arraycopy(array, 0, array, 1, position);
Assuming your array is {10,20,30,40,50,60,70,80,90,100}
What your loop does is:
Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}
Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}
What you should be doing is
Object temp = pool[position];
for (int i = (position - 1); i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
You can just use Collections.rotate(List<?> list, int distance)
Use Arrays.asList(array) to convert to List
more info at: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)
Instead of shifting by one position you can make this function more general using module like this.
int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;
for(int i=0; i<original.length;i++)
reordered[i] = original[(shift+i)%original.length];
Just for completeness: Stream solution since Java 8.
final String[] shiftedArray = Arrays.stream(array)
.skip(1)
.toArray(String[]::new);
I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.
Manipulating arrays in this way is error prone, as you've discovered. A better option may be to use a LinkedList in your situation. With a linked list, and all Java collections, array management is handled internally so you don't have to worry about moving elements around. With a LinkedList you just call remove and then addLast and the you're done.
Try this:
Object temp = pool[position];
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
Look here to see it working: http://www.ideone.com/5JfAg
Using array Copy
Generic solution for k times shift k=1 or k=3 etc
public void rotate(int[] nums, int k) {
// Step 1
// k > array length then we dont need to shift k times because when we shift
// array length times then the array will go back to intial position.
// so we can just do only k%array length times.
// change k = k% array.length;
if (k > nums.length) {
k = k % nums.length;
}
// Step 2;
// initialize temporary array with same length of input array.
// copy items from input array starting from array length -k as source till
// array end and place in new array starting from index 0;
int[] tempArray = new int[nums.length];
System.arraycopy(nums, nums.length - k, tempArray, 0, k);
// step3:
// loop and copy all the remaining elements till array length -k index and copy
// in result array starting from position k
for (int i = 0; i < nums.length - k; i++) {
tempArray[k + i] = nums[i];
}
// step 4 copy temp array to input array since our goal is to change input
// array.
System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
}
code
public void rotate(int[] nums, int k) {
if (k > nums.length) {
k = k % nums.length;
}
int[] tempArray = new int[nums.length];
System.arraycopy(nums, nums.length - k, tempArray, 0, k);
for (int i = 0; i < nums.length - k; i++) {
tempArray[k + i] = nums[i];
}
System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
}
In the first iteration of your loop, you overwrite the value in array[1]. You should go through the indicies in the reverse order.
static void pushZerosToEnd(int arr[])
{ int n = arr.length;
int count = 0; // Count of non-zero elements
// Traverse the array. If element encountered is non-zero, then
// replace the element at index 'count' with this element
for (int i = 0; i < n; i++){
if (arr[i] != 0)`enter code here`
// arr[count++] = arr[i]; // here count is incremented
swapNumbers(arr,count++,i);
}
for (int j = 0; j < n; j++){
System.out.print(arr[j]+",");
}
}
public static void swapNumbers(int [] arr, int pos1, int pos2){
int temp = arr[pos2];
arr[pos2] = arr[pos1];
arr[pos1] = temp;
}
Another variation if you have the array data as a Java-List
listOfStuff.add(
0,
listOfStuff.remove(listOfStuff.size() - 1) );
Just sharing another option I ran across for this, but I think the answer from #Murat Mustafin is the way to go with a list
public class Test1 {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5, 6 };
Test1 test = new Test1();
x = test.shiftArray(x, 2);
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public int[] pushFirstElementToLast(int[] x, int position) {
int temp = x[0];
for (int i = 0; i < x.length - 1; i++) {
x[i] = x[i + 1];
}
x[x.length - 1] = temp;
return x;
}
public int[] shiftArray(int[] x, int position) {
for (int i = position - 1; i >= 0; i--) {
x = pushFirstElementToLast(x, position);
}
return x;
}
}
A left rotation operation on an array of size n shifts each of the array's elements unit to the left, check this out!!!!!!
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]); //no. of elements in the array
int d = Integer.parseInt(nd[1]); //number of left rotations
int[] a = new int[n];
for(int i=0;i<n;i++){
a[i]=scanner.nextInt();
}
Solution s= new Solution();
//number of left rotations
for(int j=0;j<d;j++){
s.rotate(a,n);
}
//print the shifted array
for(int i:a){System.out.print(i+" ");}
}
//shift each elements to the left by one
public static void rotate(int a[],int n){
int temp=a[0];
for(int i=0;i<n;i++){
if(i<n-1){a[i]=a[i+1];}
else{a[i]=temp;}
}}
}
You can use the Below codes for shifting not rotating:
int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
int n = arr.length;
int d = 3;
Programm for shifting array of size n by d elements towards left:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {4,5,6,7,8,9,10,11,12,10,11,12}
public void shiftLeft(int []arr,int d,int n) {
for(int i=0;i<n-d;i++) {
arr[i] = arr[i+d];
}
}
Programm for shifting array of size n by d elements towards right:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {1,2,3,1,2,3,4,5,6,7,8,9}
public void shiftRight(int []arr,int d,int n) {
for(int i=n-1;i>=d;i--) {
arr[i] = arr[i-d];
}
}
import java.util.Scanner;
public class Shift {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int array[] = new int [5];
int array1[] = new int [5];
int i, temp;
for (i=0; i<5; i++) {
System.out.printf("Enter array[%d]: \n", i);
array[i] = input.nextInt(); //Taking input in the array
}
System.out.println("\nEntered datas are: \n");
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
}
temp = array[4]; //We declared the variable "temp" and put the last number of the array there...
System.out.println("\nAfter Shifting: \n");
for(i=3; i>=0; i--) {
array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
}
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array1[i]);
}
input.close();
}
}
Write a Java program to create an array of 20 integers, and then implement the process of shifting the array to right for two elements.
public class NewClass3 {
public static void main (String args[]){
int a [] = {1,2,};
int temp ;
for(int i = 0; i<a.length -1; i++){
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
for(int p : a)
System.out.print(p);
}
}
In below code I'm trying to add integers at last in array if array elements matches with specific key let's say k=1 in my case. But I'm not able to figure out how to iterate array after adding elements at last in array to check if any element can be shifted to last of the array.
Also,I don't want to use any java collection.Please help me in this regard.
int[] a=new int[8];
int key=1;
int temp,c=0;
a[0]=1;a[1]=1;a[2]=2;a[3]=1;
a[4]=1;a[5]=1;a[6]=3;a[7]=4;
int l=a.length;
for(int i=0;i<l;i++) {
c=i;
if(a[i]==key) {
temp=a[i];
while(c<l-1) {
a[c]=a[c+1];
c++;
}
a[l-1]=temp;
}
}
As we can see, in above code key=1 matches with elements present at index(i=0,1,3,4,5) and I am putting elements at last and shifting all other elements to previous index but problem is that after shifting, again I need to check if array has any element which is still matching with key(k=1) and need to put at last of the array. Hope I could clear my problem.
this outputs- 12134111
but desired output is 23411111.
Meaning all elements which matches with key=1, should be put at last.
You can a little bit modify your algorithm according to this:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = new int[8];
int key = 1;
a[0] = 1;
a[1] = 1;
a[2] = 2;
a[3] = 1;
a[4] = 1;
a[5] = 1;
a[6] = 3;
a[7] = 4;
for (int i = 0; i < a.length; i++) {
if (a[i] != key) {
continue;
}
//find next element which doesn't equal to key and swap
for (int j = i; j < a.length; j++) {
if (a[j] != a[i]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
break;
}
}
}
System.out.println(Arrays.toString(a));
}
}
Output: [2, 3, 4, 1, 1, 1, 1, 1]
public static void main(String args[])
{
int a[]={1,1,2,1,1,1,3,3};
int k=1,n=a.length-1;
for(int i=0;i<a.length;i++)
{
if(a[i]==k)
{
int temp=a[i];
for (int j=i;j<n-1;j++)
{
a[j]=a[j+1];
}
a[n]=temp;
}
}
}
public class intersect {
public static void find(int[] a, int[] b, int[] acc)
{
int position = 0;
for (int j = 0; j < a.length; j++) {
for (int k = 0; k<b.length; k++) {
if (a[j] == b[k]) {
acc[position] = b[k];
position++;
}
}
}
System.out.println(java.util.Arrays.toString(acc));
}
public static void main (String[] s)
{
int[] acc = new int[2];
int[] a = {1,2,3};
int[] b = {2,3,4};
find(a, b, acc);
}
}
I have written the above code to solve the problem.
But if you see, the function is very limited because I have to change the length of the acc every time. That means I have to know how many elements are intersecting. In this case, the array {1,2,3} and {2,3,4} have {2,3} in common, so the length of the acc would be 2.
I am sure there are millions of ways of tackling this problem, but I cannot seem to think of a way of fixing this.
Please help!
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find() method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
To find intersection of 2 sorted arrays, follow the below approach :
1) Use two index variables i and j, initial values with 0
2) If array1 is smaller than array2 then increment i.
3) If array1 is greater than array2 then increment j.
4) If both are same then print any of them and increment both i and j.
check this link for more information
https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
public class FindIntersection {
static void findInterSection(int array1[], int array2[], int array1NoOfElements, int
array2NoOfElements) {
int i = 0, j = 0;
while (i < array1NoOfElements && j < array2NoOfElements) {
if (array1[i] < array2[j]) {
i++;
} else if (array2[j] < array1[i]) {
j++;
}
// if both array elements are same
else {
System.out.println(array2[j++] + " ");
i++;
}
}
}
public static void main(String[] args)
{
int myFirstArray[] = { 1, 2, 4, 5, 5 };
int mySecondArray[] = { 2, 3, 5, 7 };
int m = myFirstArray.length;
int n = mySecondArray.length;
findInterSection(myFirstArray, mySecondArray, m, n);
}
}
Make your intersection array's size the size of the smaller of your original arrays. That way, you won't ever have to increase it's capacity.
Then you can use Arrays.copy to transfer your results into an appropriately sized array.
Not sure if this is the best solution, but you don't need to hard-code the size of the intersection ahead of time (which is one thing you were concerned about).
As you iterate through both arrays, you can add elements found in both sets to a StringBuilder (along with some delimiter, I used a comma in the example below). Once you're finished, you can call toString() & then split() using the delimiter afterwards to get a String[]. At that point, you can put convert those String objects to int primitives & return an int[].
public class Scratch {
public static void main(String[] s) {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] intersection = findIntersection(a, b);
System.out.println(Arrays.toString(intersection));
}
public static int[] findIntersection(int[] a, int[] b) {
StringBuilder intersectionStringBuilder = new StringBuilder();
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (a[j] == b[k])
intersectionStringBuilder.append(a[j] + ",");
}
}
String[] intersectionStringArray = intersectionStringBuilder.toString().split(",");
int[] intersection = new int[intersectionStringArray.length];
for (int current = 0; current < intersectionStringArray.length; current++) {
intersection[current] = Integer.parseInt(intersectionStringArray[current]);
}
return intersection;
}
}
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j] && !index.contains(j)){
list.add(arr1[i]);
index.add(j);
break;
}
}
}
int result[]=new int[list.size()];
int k=0;
for(int i:list){
result[k]=i;
k++;
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
return result;
}
So basically there are two separate presorted arrays, and you have to combine them and sort them (without sort() methods of course). Here is my code:
public static void main(String[] args) {
int a [] = {3,5,7,9,12,14, 15};
int b [] = {6 ,7, 10};
int j = 0;
//output array should be 3,5,6,7,7,9,10,12,14,15
int c [] = new int[a.length+b.length];//10 values
for (int i = 0;i<b.length;i++){
while(b[i]>a[j]){
c[j] = a[j] ;
j++;
}
if(b[i] == a[j]){
c[j] = b[i];
c[j+1] = a[j];
}
c[j] = b[i];
j++;
}
for(int i = 0;i<c.length;i++)
System.out.println(c[i]);
}
I'm guessing the zeros I am getting are from a mistake in one of the booleans (< & >), but I cant seem to figure it out. It works fine for the first 4, but once I get to the repeating 7's, it just goes crazy.
Please help me understand, don't just change the code.
This is how it should be in a simple way:
public static void main(String[] args) {
int a [] = {3,5,7,9,12,14, 15};
int b [] = {6 ,7, 10};
int j = 0, k = 0;
//output array should be 3,5,6,7,7,9,10,12,14,15
int c [] = new int[a.length+b.length];//10 values
// we're filling c with the next appropriate number
// we start with checking a[0] and b[0] till we add
// all the elements
for (int i = 0; i < c.length; i++) {
// if both "a" and "b" have elements left to check
if (j < a.length && k < b.length) {
// check if "b" has a smaller element
if (b[k] < a[j]) {
// if so add it to "c"
c[i] = b[k];
k++;
}
// if "a" has a smaller element
else {
// add it to "c"
c[i] = a[j];
j++;
}
}
// if there are no more elements to check in "a"
// but there are still elements to check in "b"
else if (k < b.length) {
// add those elements in "b" to "c"
c[i] = b[k];
k++;
}
// if there are no more elements to check in "b"
// but there are still elements to check in "a"
else {
// add those elements in "a" to "c"
c[i] = a[j];
j++;
}
}
for(int i = 0; i < c.length; i++)
System.out.println(c[i]);
}
Hope it helps.
You can try this code.
public static void main(String[] args) {
int a[] = { 3, 5, 7, 9, 12, 14, 15 };
int b[] = { 6, 7, 10 };
// output array should be 3,5,6,7,7,9,10,12,14,15
int alen = a.length;
int blen = b.length;
int c[] = new int[a.length + b.length];// 10 values
int s[] = null;
int[] l = null;
if (alen < blen) {
s = a;
l = b;
} else {
s = b;
l = a;
}
// Constructing Combined Array
for (int i = 0, p = 0; i < c.length; i++, p++) {
if (i == s.length) {
p = 0;
}
if (i < s.length) {
c[i] = s[p];
} else {
c[i] = l[p];
}
}
//Sorting the C array
for (int i = 1; i < c.length; i++) {
int j = i;
int B = c[i];
while ((j > 0) && (c[j - 1] > B)) {
c[j] = c[j - 1];
j--;
}
c[j] = B;
}
for (int i = 0; i < c.length; i++)
System.out.print(c[i]);
}
Actually it's better to say merging (not combining) two arrays.
Simple algorithm (taken from this article) for merging sorted arrays A and B[0..n-1] into result C[0..m+n-1]:
Introduce read-indices i, j to traverse arrays A[0..m-1] and B, accordingly. Introduce write-index k to store position of the first free cell in the resulting array. By default i = j = k = 0.
At each step: if both indices are in range (i < m and j < n), choose minimum of (A[i], B[j]) and write it to C[k]. Otherwise go to step 4.
Increase k and index of the array, algorithm located minimal value at, by one. Repeat step 2.
Copy the rest values from the array, which index is still in range, to the resulting array.
Hope it helps.
Use ai and bi for the indices in both source arrays and ci as the index for the destination array.
You only need one loop.
Try to keep this very clear and advance in c by exactly one element at each iteration.
In the loop, check wether the end of one array was reached. If so, just take an element from the other array. Otherwise, take only the smaller element of a[ai] and b[bi] and increment the corresponding index.
It is very easy to make mistakes in mergesort (or in any code where two arrays need to be walked in parallel) by thinking "hey I can go along with a while loop instead of just doing a single if", but then you typically have two loops nested in a third one, and for each of the loops you have to do the right bounds checks, and there is typically no significant gain in performance.
p.s. Doing one main loop and then two cleanup loops after the main loop is fine, just avoid nested loops if they are not necessary, in particular in interviews where this may also cause confusion when calculating the runtime.
Try this, your error is you are using the same cellular index for array A and array C:
public class MainClass {
public static void main(String[] args) {
int[] arrayA = { 23, 47, 81, 95 };
int[] arrayB = { 7, 14, 39, 55, 62, 74 };
int[] arrayC = new int[10];
merge(arrayA, arrayA.length, arrayB, arrayB.length, arrayC);
for (int i : arrayC) {
System.out.println(i);
}
}
public static void merge(int[] arrayA, int sizeA, int[] arrayB, int sizeB, int[] arrayC) {
int arrayAIndex = 0, arrayBIndex = 0, arrayCIndex = 0;
while (arrayAIndex < sizeA && arrayBIndex < sizeB)
if (arrayA[arrayAIndex] < arrayB[arrayBIndex])
arrayC[arrayCIndex++] = arrayA[arrayAIndex++];
else
arrayC[arrayCIndex++] = arrayB[arrayBIndex++];
while (arrayAIndex < sizeA)
arrayC[arrayCIndex++] = arrayA[arrayAIndex++];
while (arrayBIndex < sizeB)
arrayC[arrayCIndex++] = arrayB[arrayBIndex++];
}
}
This is another version
// size of C array must be equal or greater than
// sum of A and B arrays' sizes
public void merge(int[] A, int[] B, int[] C) {
int i, j, k, m, n;
i = 0;
j = 0;
k = 0;
m = A.length;
n = B.length;
while (i < m && j < n) {
if (A[i] <= B[j]) {
C[k] = A[i];
i++;
} else {
C[k] = B[j];
j++;
}
k++;
}
if (i < m) {
for (int p = i; p < m; p++) {
C[k] = A[p];
k++;
}
} else {
for (int p = j; p < n; p++) {
C[k] = B[p];
k++;
}
}
}
public class Combinearray {
public static void main(String[] args) {
int[] array1= {5,4,6,2,1};
int[] array2= {2,5,8,4,1,6,4};
int m=array1.length;
int n=array2.length;
int[] array3=new int[m+n];
int a=1;
for(int i=0;i<m;i++) {
array3[i]=array1[i];//array1 is copied to array3
}
for(int i=0;i<n;i++) {
array3[m-1+a]=array2[i];//array2 is copied to array3
a++;
}
//array3 is combined array
int l=array3.length;
int temp[]=new int[l];
for(int i=0;i<l;i++) {
for(int j=i+1;j<l;j++) {
if(array3[i]>array3[j]) {
temp[i]=array3[i];
array3[i]=array3[j];
array3[j]=temp[i];
}
}
}
System.out.println("sorted array is ");
System.out.print("[");
for(int i=0;i<l;i++) {
System.out.print(array3[i]+" ");
}
System.out.print("]");
}
}
I'm trying to make an implementation of 'adding' the elements of two arrays in Java.
I have two arrays which contain integers and i wanna add them. I dont want to use immutable variables. I prefer do sth like that : a.plus(b);
The problem is when i add 2 arrays with different length.It tries to add the elements of b to a, but if b has a bigger length it flags an error "ArrayIndexOutOfBoundsException".
I can understand why that's happening. But how can i solve this?
How can i expand array a? :/
public void plus(int[] b)
{
int maxlength = Math.max( this.length, b.length );
if (maxlength==a.length)
{
for (int i = 0; i <= maxlength; i++)
{
a[i] = a[i] + b[i]; //ArrayIndexOutOfBoundsException error
}
}
}
i <= maxlength replace this with i < maxlength.
Your array index is starting at zero, not at one.
So the length of the array is one less than the end index of the array.
When you use <= you are trying to go one element after the last element in your array, Hence the exception.
Also you got to check the length of array b. If length of array b is smaller than a, you will end up facing the same exception.
int maxlength = Math.min( this.length, b.length ); is more appropriate.
Or incase if you don't want to miss out any elements in either of the arrays while adding, ArrayList is the answer for you. ArrayList is the self expanding array you are looking for.
Here is how you can do that -
// First ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
// Second ArrayList
ArrayList<Integer> b = new ArrayList<Integer>();
b.add(1);
b.add(2);
b.add(3);
b.add(4);
int maxlength = Math.max(a.size(), b.size());
// Add the elements and put them in the first ArrayList in the corresponding
// position
for (int i = 0; i < maxlength; i++) {
if (i < a.size()) {
if (i < b.size()) {
int j = a.get(i);
a.set(i, j + b.get(i));
}
} else {
a.add(i, b.get(i));
}
}
for (int j : a) {
System.out.println(j);
}
How can i expand array a?
Don't use arrays if you need variable-size data structures. Use Lists.
How about this:
private int[] a;
/**
* Adds the specified array to our array, element by element, i.e.
* for index i, a[i] = a[i] + b[i]. If the incoming array is
* longer, we pad our array with 0's to match the length of b[].
* If our array is longer, then only the first [b.length] values
* of our array have b[] values added to them (which is the same
* as if b[] were padded with 0's to match the length of a[].
*
* #param b the array to add, may not be null
*/
public void plus(final int[] b)
{
assert b != null;
if (a.length < b.length) {
// Expand a to match b
// Have to move a to a larger array, no way to increase its
// length "dynamically", i.e. in place.
final int[] newA = new int[b.length];
System.arraycopy(a, 0, newA, 0, a.length);
// remaining new elements of newA default to 0
a = newA;
}
for (int i = 0; i < b.length; i++)
{
a[i] = a[i] + b[i];
}
}
Another version:
private ArrayList<Integer> aList;
public void plusList(final int[] b)
{
assert b != null;
if (aList.size() < b.length) {
aList.ensureCapacity(b.length);
}
for (int i = 0; i < b.length; i++)
{
if (i < aList.size()) {
aList.set(i, aList.get(i) + b[i]);
} else {
aList.add(b[i]);
}
}
}
Edit: Here's the full class with sample run from data in comments
public class AddableArray {
private int[] a;
public AddableArray(final int... a) {
this.a = a;
}
/**
* Adds the specified array to our array, element by element, i.e.
* for index i, a[i] = a[i] + b[i]. If the incoming array is
* longer, we pad our array with 0's to match the length of b[].
* If our array is longer, then only the first [b.length] values
* of our array have b[] values added to them (which is the same
* as if b[] were padded with 0's to match the length of a[].
*
* #param b the array to add, may not be null
*/
public void plus(final int[] b)
{
assert b != null;
if (a.length < b.length) {
// Expand a to match b
// Have to move a to a larger array, no way to increase its
// length "dynamically", i.e. in place.
final int[] newA = new int[b.length];
System.arraycopy(a, 0, newA, 0, a.length);
// remaining new elements of newA default to 0
a = newA;
}
for (int i = 0; i < b.length; i++)
{
a[i] = a[i] + b[i];
}
}
int[] get() {
return a;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("a[] = [ ");
for (int i = 0; i < a.length; i++) {
if (i > 0) sb.append(", ");
sb.append(a[i]);
}
sb.append(" ]");
return sb.toString();
}
public static void main (final String[] args) {
final AddableArray myAddableArray = new AddableArray(1,2,3);
System.out.println("Elements before plus(): ");
System.out.println(myAddableArray.toString());
final int b[]={1,2,3,4};
myAddableArray.plus(b);
System.out.println("Elements after plus(): ");
System.out.println(myAddableArray.toString());
}
}
Sample run:
Elements before plus():
a[] = [ 1, 2, 3 ]
Elements after plus():
a[] = [ 2, 4, 6, 4 ]
maxlength is the max between the size of a[] and b[], so in a loop from 0 to maxlength, you will get an ArrayIndexOutOfBoundsException when i exceeds the min of the size of a[] and b[].
Try this:
public void plus(int[] b)
{
Polynomial a = this;
int[] c;
int maxlength;
if (a.length>b.length) {
c=a;
maxlength=a.length;
} else {
c=b;
maxlength=b.length;
}
int ca, cb;
for (int i = 0; i < maxlength; i++)
{
if (i<this.length)
ca=a[i];
else
ca=0;
if (i<b.length)
cb=b[i];
else
cb=0;
c[i] = ca + cb;
}
}
Try replacing:
for (int i = 0; i <= maxlength; i++)
with:
for (int i = 0; i < maxlength; i++)