How to rotate a String of space delimited integers in Java? - java

Suppose I have the following String: "10 30 20 12 34". Now I want to rotate the String but keep the first and last integers fixed. So I should get the 3 outputs should be as follows:
10 20 30 12 34
10 30 12 20 34
10 12 20 30 34
Now, I am trying to first convert the String into an int[] array such that it looks like [10, 30,20, 12, 34] and then create another array, get each element of the original array and insert them in the new array.
This is what I have so far:
String[] arr1 = tree.getPreOrder().split(" ");
int[] arr2 = new int[5];
arr2[0] = Integer.parseInt(arr1[0]);
arr2[1] = Integer.parseInt(arr1[3]);
arr2[2] = Integer.parseInt(arr1[2]);
arr2[3] = Integer.parseInt(arr1[1]);
arr2[4] = Integer.parseInt(arr1[4]);
My issue is, how do I now convert arr2 into the format 10 12 20 30 34. I tried to use join() but it doesn't work.
Also, is there a simpler way to do what I'm trying to do as currently, I am hard coding those values.
Thanks
UPDATE
I created a method which basically rotates the middle values now. However, I got into an issue where one randomly generated String was the same as the original and I would like to avoid that. I'm basically trying to generate only exactly 3 variations of the original string if that helps.
Here's my updated code:
static String randomizeAnswer(String ans) {
String[] arr = ans.split(" ");
int arraySize = arr.length;
String firstElement = arr[0];
String lastElement = arr[arraySize - 1];
String[] arr2 = new String[arraySize - 2];
String arr3[] = new String[arraySize];
arr3[0] = firstElement;
for (int i = 0; i < arraySize - 2; i++) {
arr2[i] = arr[i + 1];
}
Collections.shuffle(Arrays.asList(arr2));
for (int j = 0; j < arr2.length; j++) {
arr3[j + 1] = arr2[j];
}
arr3[arraySize - 1] = lastElement;
return String.join(" ", arr3);
}
for int(i = 0; i<3; i++){
System.out.println(randomizeAnswer("10 30 20 12 34"));
}
UPDATE 2
I eventually managed to make a solution which works but the answer by #WJS below is much better.
static String randomizeAnswer(String ans) {
String[] arr = ans.split(" ");
int arraySize = arr.length;
String firstElement = arr[0];
String lastElement = arr[arraySize - 1];
String[] arr2 = new String[arraySize - 2];
String arr3[] = new String[arraySize];
arr3[0] = firstElement;
for (int i = 0; i < arraySize - 2; i++) {
arr2[i] = arr[i + 1];
}
Collections.shuffle(Arrays.asList(arr2));
for (int j = 0; j < arr2.length; j++) {
arr3[j + 1] = arr2[j];
}
arr3[arraySize - 1] = lastElement;
return String.join(" ", arr3);
}
static String[] generateAnswers(String ans) {
String[] answers = new String[5];
answers[0] = ans;
answers[4] = "None of the answers are correct";
for (int x = 0; x < 3; x++) {
while (true) {
String randomAns = randomizeAnswer(ans);
if (Arrays.stream(answers).anyMatch(randomAns::equals)) {
continue;
} else {
answers[x+1] = randomAns;
break;
}
}
}
return answers;
}

Convert the array to ints. Note that the string values could be rotated without parsing to an int.
String str = "10 30 20 12 34";
int[] vals = Arrays.stream(str.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
The range to rotate
int start = 1;
int end = 4; // exclusive
An array to save the rotated array of values.
String[] results = new String[end - start];
And now rotating them, converting to a string and storing. Note that the previously rotated array needs to be fed back into the method. But that array is not changed because it is copied in the rotate method.
for (int i = 0; i < end - start; i++) {
vals = rotate(vals, start, end);
// convert to String - can't use join since these are not strings.
// this just streams the results, converts to a string, and joins them into
// a single string.
results[i] =
Arrays.stream(vals).mapToObj(v -> Integer.toString(v))
.collect(Collectors.joining(" "));
}
for (String rotated : results) {
System.out.println(rotated);
}
prints
10 20 12 30 34
10 12 30 20 34
10 30 20 12 34
This simply rotates the array one cell to the left within the specified range. It first makes a copy of the original array. Note the end is exclusive.
public static int[] rotate(int[] arr, int start, int end) {
arr = Arrays.copyOf(arr, arr.length);
int v = arr[start];
for (int i = start; i < end-1; i++) {
arr[i] = arr[i+1];
}
arr[end-1] = v;
return arr;
}

Another example:
public static void main(String[] args) {
String treePreOrder = "10 30 20 12 34";
String rot1 = rotateMiddle(treePreOrder);
String rot2 = rotateMiddle(rot1);
System.out.println(treePreOrder);
System.out.println(rot1);
System.out.println(rot2);
}
public static String rotateMiddle(String values) {
String[] arr = values.split(" ");
if (arr.length >= 4) {
String temp = arr[1];
for(int i=1; i<=(arr.length-3); i++) {
arr[i] = arr[i+1];
}
arr[arr.length-2] = temp;
}
return String.join(" ", arr);
}
Output:
10 30 20 12 34
10 20 12 30 34
10 12 30 20 34

Here's my two cents using Java Streams.
private static int[] rotate(int[] array, int count) {
if (array.length >= 0 && array.length <= 2) {
return array;
}
return IntStream.range(0, array.length)
.map(i -> (i == 0 || i == array.length - 1) ? i : (i - 1 + count) % (array.length - 2) + 1)
.map(i -> array[i])
.toArray();
}
This rotates the given array count positions to the right, but leaves the first and last indexes unharmed. For example, when count = 1, the array [10, 30, 20, 12, 34] becomes [10, 12, 30, 20, 34].
If you want to generate an n number of random sequences, you could use the snippet below. This generates arrays which are not equal to the original array.
int array = { … };
int n = 2;
ThreadLocalRandom.current().ints(n, 1, array.length - 2)
.mapToObj(randomInt -> rotate(array, randomInt))
.forEach(result -> System.out.println(Arrays.toString(result)));
// Or, if you want to convert it back to a String:
//.collect(Collectors.mapping(String::valueOf, Collectors.joining(" ")));
Collections::shuffle
Of course, you can also simply shuffle the elements minus the first and last ones using Collections::shuffle and List::subList. This method is generic, so it really does not matter whether the elements are actually integers or not. For instance, a List<String> is yielded with Arrays.asList("10 30 20 12 34".split(" ")).
public static <T> List<T> shuffleMid(List<T> list) {
List<T> newList = new ArrayList<>(list);
do {
Collections.shuffle(newList.subList(1, newList.size() - 1));
} while (newList.equals(list)); // Make sure it is unequal to the original
return newList;
}
The do-while loop makes sure the shuffled list is not equal to the original list. This may be a naive implementation.

String[] array = new String[5];
for(int i = 0; i < 5; i++)
array[i] = i + 1 + "";
//array[0] = 1, array[1] = 2, array[3] = 3, array[4] = 4, array[5] = 5
int first = 0;
int last = array.length - 1;
for(int i = 1; i < array.length / 2; i++){
first = i;
last = array.length - i - 1;
String aux = array[first];
array[first] = array[last];
array[last] = aux;
first++;
last--;
}
for(int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
The output will be: 1 4 3 2 5

To rotate the elements (except the first and last elements) you can use this:
use another helping array:
String in = "10 30 20 12 34";
String[] arr_in = in.split(" ");
String[] arr_out = new String[arr_in.length];
arr_out[0] = arr_in[0];
arr_out[arr_out.length-1] = arr_in[arr_in.length-1];
for(int i=arr_in.length-2, j=1; i>0; i--,j++)
{
arr_out[j] = arr_in[i];
}
// print:
for(int i=0; i<arr_out.length;i++)
{
System.out.println(arr_out[i]);
}
in place :
public static void main(String[] args) {
String in = "10 30 20 12 34";
String[] arr = in.split(" ");
String tmp;
for(int i=arr_in.length-2, j=1; i>(arr_in.length/2); i--,j++)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
// print:
for(int i=0; i<arr.length;i++)
{
System.out.println(arr[i]);
}
}

There most definitely is a better way to leverage other APIs in the JDK... but here is what I came up with.
// shifts by [direction] spaces (-ve and +ve) for left/right. So far so good with not throwing IndexOutOfBoundsExceptions :)
private static int[] shift(int[] values, int direction) {
int[] result = new int[values.length];
for (int i = 0; i < result.length; i++) {
result[i] = values[(values.length + (i + direction % values.length)) % values.length];
}
return result;
}
public static void main(String[] args) {
int[] values = new int[]{101, 1, 2, 3, 100};
int[] middleValues = Arrays.copyOfRange(values, 1, values.length-1);
int[][] allCombos = new int[middleValues.length][values.length];
int shiftPtr = 0;
for (int[] row : allCombos) {
row[0] = values[0];
row[row.length-1] = values[values.length-1];
int[] shifted = shift(middleValues, shiftPtr);
for (int i = 0; i < middleValues.length; i++) {
row[i + 1] = shifted[i];
}
shiftPtr++;
// and print out to test...
System.out.println(Arrays.toString(row));
}
}
And you end up with this output....
> [101, 1, 2, 3, 100]
> [101, 2, 3, 1, 100]
> [101, 3, 1, 2, 100]

Related

Generate even numbers in an int array?

For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}
if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!
Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections

How to find repeating sequence of Integers in an array of Integers in java?

For example if input is:
2 0 6 3 1 6 3 1 6 3 1
then output should be 6 3 1.Need to find the first repetition cycle.
class FindDuplicate
{
void printRepeating(int arr[], int size)
{
int i;
System.out.println("The repeating elements are : ");
for (i = 0; i < size; i++)
{
if (arr[Math.abs(arr[i])] >= 0)
arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
else
System.out.print(Math.abs(arr[i]) + " ");
}
}
public static void main(String[] args)
{
FindDuplicate duplicate = new FindDuplicate();
int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
int arr_size = arr.length;
duplicate.printRepeating(arr, arr_size);
}
}
https://pastebin.com/12bnjzfw
Have used java 8 streams for collection creation.
for (int seqSize = ints.size() / 2; seqSize > 0; seqSize--) { //It should be first cycle. Main priority is biggest sequence
for (int i = 0; i < ints.size() / seqSize; i++) { //Start position of the first block
for (int j = i + seqSize; j < ints.size() - seqSize + 1; j++) {
if (ints.subList(i, i + seqSize).equals(ints.subList(j, j + seqSize))) {
System.out.println("Answer is: " + ints.subList(i, i + seqSize));
return;
}
}
}
}
class FindDuplicate {
static int STRING_LENGTH = 3;
void printRepeating(int arr[], int size) {
int i;
System.out.println("The repeating elements are : ");
String strVal = "";
for (int ii = 0; ii < size; ii++) {
strVal += arr[ii];
}
// strVal now has something we can search with.
for (i = 0; i < size; i++) {
int end = Math.min(size,i+STRING_LENGTH );
String searchString = strVal.substring(i, end);
if (searchString.length() != STRING_LENGTH)
break; // at end of arr, doesn't have length to search
int matchIndex = strVal.indexOf(searchString, i+1);
if (matchIndex != -1) {
String match = strVal.substring(matchIndex, matchIndex + STRING_LENGTH);
System.out.print(match + " ");
break; // done with loop
}
}
}
public static void main(String[] args) {
FindDuplicate duplicate = new FindDuplicate();
int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
int arr_size = arr.length;
duplicate.printRepeating(arr, arr_size);
}
}
Loop through those array elements and cache your elements until you have the same value for example
List list = Arrays.asList(1,2,3);
if(list.contains(element))
//code to check here
you will need get size of your list and based on that check exactly this amount of items if they match if yes then output if not clear cache and start cache from the begging.

Square Array Program

Using java, I am supposed to create a program that stores the square of the numbers 0, 1, 2 & 9 in an ArrayList of 10 elements.
I have created part of the code that displays the numbers and its squares but the program goes straight down with all the numbers and does not look organized. Can someone help me write it out like like this instead:
number: 0 square: 0
number: 1 square: 1
number: 2 square: 4
Code
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int value : temp) {
System.out.println(value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(value);
}
}
You need just one loop like this :
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i] + "\t" + (int)Math.pow(temp[i], 2));
}
}
OutPut
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
If you want to store your results in an ArrayList you can use :
List<int[]> array = new ArrayList<>();//create a List which take an array of int
int arr[] = new int[2];//create a temporary array of 2 elements
for (int i = 0; i < temp.length; i++) {
System.out.println("Number: " + temp[i] + " \tSquare: " + (int) Math.pow(temp[i], 2));
arr[0] = temp[i];//add your number to your array pos 1
arr[1] = (int) Math.pow(temp[i], 2);//add the power to the 2ed position
array.add(arr);//add your array to your list
}
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
// here you are printing all your numbers in the array, so the output will be:
// 0
// 1
// ...
// 9
for (int value : temp) {
System.out.println(value);
}
// after that, you calculate and store them in the same array; so your array now look like this:
// [0,1,4,9,...,81]
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
// here you are printing again your array
// 0
// 1
// 4
// ...
// 81
for (int value : temp) {
System.out.println(value);
}
}
to get your desired outcome, you have to calculate the number before printing everything... one option will be to create another array
int[] square = new int[9];
calculate in the first for loop and save the result in the square array and print them, something like this:
for (int i = 0; i < temp.length; i++) {
square[i] = (int) Math.pow(temp[i],2);
System.out.println("number " + temp[i] + " square: " + square[i]);
}
Assuming the original question which referred to an ArrayList was correct (the OP's example only had an array), and assuming the results are supposed to be stored in the array (per the question), then the following will work:
public static void main(String[] args)
{
// instantiate ArrayList
List<Double> array = new ArrayList<>();
// load the values
for (int i = 0; i < 10; ++i) {
array.add(i, Math.pow(i, 2));
}
// output
for (int i = 0; i < array.size(); ++i) {
System.out.println(String.format("%2d\t%3.0f", i, array.get(i)));
}
}
Output:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
Try this :
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
for (int value : temp) {
System.out.println("number : "value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(" square : " + value + "\n");
}
}

Array method that returns a new array where every number is replicated by “itself” # of times

I am trying to write a method in Java that receives an array and returns a new array where each number is printed that number of times. Here is an example input and output: "1 2 3 0 4 3" ---> "1 2 2 3 3 3 4 4 4 4 3 3 3". I am stuck and my program will not compile. Does anyone see where I am going wrong?
public static int [] multiplicity(int [] nums) {
for (int i = 0 ; i < nums.length ; i++) {
int size = nums.length + 1;
int newNums[] = new int [size];
for (int j = 0 ; j < nums.length ; j++) {
int value = nums[j];
for (int v = 0 ; v < value ; v++) {
newNums[j + v] = value;
}
}
}
return newNums;
}
Your current code does not size your new array correctly, you could fix your compiler errors easily enough like
int size=nums.length+1;
int newNums [] = new int [size];
for (int i=0; i<nums.length; i++)
{
// int size=nums.length+1;
// int newNums [] = new int [size];
But that clearly won't allow you to populate all of your values. Instead (assuming you can't use a dynamic data-type like a Collection), you'll need to iterate the array once to get the final count of elements and then populate your array. Something like,
public static int[] multiplicity(int[] nums) {
// first pass
int count = 0;
for (int num : nums) {
for (int i = 0; i < num; i++) {
count++;
}
}
int[] ret = new int[count];
count = 0;
// second pass
for (int num : nums) {
for (int i = 0; i < num; i++) {
ret[count++] = num;
}
}
return ret;
}
Then you could test it like,
public static void main(String arg[]) {
int[] in = { 1, 2, 3, 0, 4, 3 };
int[] out = multiplicity(in);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.length; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append(out[i]);
}
String expected = "1 2 2 3 3 3 4 4 4 4 3 3 3";
System.out.println(expected.equals(sb.toString()));
}
Output is
true
Once you initialise your int[] newNums, you can't dynamically resize it. Initialising it again will discard the previous array.
Here's another way to solve the problem:
public static int [] multiplicity (int [ ] nums)
{
// create a list to contain the output
List<Integer> newNums = new ArrayList<Integer>();
// for each incoming int
if(nums != null) {
for (final int i : nums)
{
// repeat adding the value
for(int j = 0; j < i; j++) {
newNums.add(i);
}
}
}
// now copy from the List<Integer> to the result int[]
int[] result = new int[newNums.size()];
for(int i=0; i < newNums.size(); i++) {
result[i] = newNums.get(i);
}
// return the result
return result;
}
You can't know the new array size until you explore the whole input array.
So you can
Explore the whole array and compute the lengh, then, re-explore the input array and fill the new. You need only 1 memory allocation (only 1 new int[])
Create a vector and fill it. Then use the .toarray method
Exemple to fill the array (check he had the right size)
int k = 0
for(int i: nums) {
for(int j = 0; j < i; j++) {
newArray[k] = i;
k++;
}
}

Error trying to sum two different length arrays

I'm trying to make it so the elements of each array are added together to get a sum, regardless if one array is larger than the other. This is the error I'm getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
The error is linked to line 13 or 23 depending on which array is bigger in my test class.
( pickedList[i] = listA[i] + listB[i]; are the error lines)
Edit: The code works if the arrays have the same number of elements, but when one is larger it crashes.
public static int[] AddArray(int[] listA, int[] listB)
{
int aLen = listA.length;
int bLen = listB.length;
int[] pickedList = null;
//if array 1 is longer, make picklist have same number of elements then add
//both array elements together
if (aLen >= bLen)
{ pickedList = new int[aLen];
for( int i = 0; i < aLen; i ++)
{
pickedList[i] = listA[i] + listB[i];
}
}
//if array 2 is longer, make picklist have same number of elements then add
//both array elements together
else
{
pickedList = new int[bLen];
for( int i = 0; i < bLen; i ++)
{
pickedList[i] = listA[i] + listB[i] ;
}
}
return pickedList;
}
}
Your error is very simple:
if (aLen >= bLen)
{ pickedList = new int[aLen];
for( int i = 0; i < aLen; i ++)
{
pickedList[i] = listA[i] + listB[i];
you have that.
If alen is longer than blen, then if your forloop goes up to the length of a, you'll get an error because you have listB[i] - you're trying to access elements of B that just aren't there.
Let me make this clearer. Let's say array a has a length of 5, and array b has a length of 3. a is bigger than b, so you loop through i from 0 to 5. Everything will be fine fine for i = 0, i = 1, i = 2, but once you get to i = 3, there is no listB[i], because list B only has an elemnet in the 0, 1, and 2 position, so you get the error that you got.
I hope that helps. Good luck :)
I would use Math.max(int,int) to get the max length. Then declare the new array, then iterate the length adding the elements like
public static int[] addArray(int[] listA, int[] listB) {
int aLen = listA.length;
int bLen = listB.length;
int len = Math.max(aLen, bLen);
int[] pickedList = new int[len];
for (int i = 0; i < len; i++) {
if (i < aLen && i < bLen) {
pickedList[i] = listA[i] + listB[i];
} else if (i < aLen) {
pickedList[i] = listA[i];
} else {
pickedList[i] = listB[i];
}
}
return pickedList;
}
For your first if statement you have aLen >= bLen Then you loop for the length of aLen in a for loop. Inside this for loop, you try to access the elements of listB at index i. However, since listA is longer, the element listB[i] will not exist as the length of listA is longer than the length of listB.
public static int[] AddArray(int[] listA, int[] listB)
{
int smallList[], bigList[], sums[];
int pos;
if (listA.length >= listB.length) {
smallList = listB;
bigList = listA;
} else {
smallList = listA;
bigList = listB;
}
sums = new int[bigList.length];
for (pos=0; pos < smallList.length; ++pos) {
sums[pos] = smallList[pos] + bigList[pos];
}
for (; pos < bigList.length; ++pos) {
sums[pos] = bigList[pos];
}
return sums;
}
If two arrays are
arr1 = [1, 2, 3, 4, 5]
arr2 = [6, 7, 8]
The we can use lower length of two arrays as loop condition (ind < lower_length) to get rid from exception. eg,
int array1_length = arr1.length; // 5
int array2_length = arr1.length; // 3
Then we can get lower limit such ways
int limit = (array1_length > array2_length) ? array2_length : array1_length;
or
int limit = Math.max(array1_length, array2_length);
Then can use the limit in for loop, eg,
for(int ind = 0; ind < limit; ind++){
//sum = arr1[ind] + arr2[ind];
}
I hope it will help you deeply.
try this:
public static int[] AddArray(int[] listA, int[] listB)
{
int aLen = listA.length;
int bLen = listB.length;
int[] pickedList = null;
int i,j;
//if array 1 is longer, make picklist have same number of elements then add
//both array elements together
if (aLen >= bLen)
{ pickedList = new int[aLen];
for( i = 0; i < bLen; i ++)
{
pickedList[i] = listA[i] + listB[i];
}
for( j = i; j < aLen; j++) // listB exhaust so add remaining elements of listA to pickedList
{
pickedList[j] = listA[j] ;
}
}
//if array 2 is longer, make picklist have same number of elements then add
//both array elements together
else
{
pickedList = new int[bLen];
for( i = 0; i < aLen; i ++)
{
pickedList[i] = listA[i] + listB[i] ;
}
for( j = i; j < bLen; j ++)// listA exhaust so add remaining elements of listB to pickedList
{
pickedList[j] = listB[j];
}
}
return pickedList;
}

Categories