How to add two int array values together? - java

I am trying to add two int arrays together to get a sum. The first array contains 0000000000000000123456789 and the second array contains 0001111111111111111111111. The sum should be 1111111111111234567900. Also I'm trying to do this without BigInteger or BigDecimal.
for(int i=0; i<number1.length;i++){
add= number1[i]+number2[i];
if(plus>=10){
sum[i-1]+=add/10;
sum[i] = add%10;
}else{
sum[i]=add;
}
}
The output that is produced at the moment is 00011111111111112345678100. How can I fix my code so that the 8 becomes a 9?

This kinda works. I can think of a couple of cases where something like this would break, like if the arrays were like {9,9,9} and {9,9,9}, result would be {9,9,8} instead of {1,9,9,8}. It's a minor fix that is being left as an activity to the reader.
public static void main(String []args){
int[] number1 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9};
int[] number2 = {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int carry = 0, sum = 0;
int[] result = new int[number1.length];
for (int i = number1.length - 1; i >= 0 ; i--) {
sum = number1[i] + number2[i] + carry;
result[i] = sum%10;
carry = sum/10;
}
// [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 9, 0, 0]
System.out.println(Arrays.toString(result));
}

Try this
int[] number = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9};
int[] number2 = {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] result = new int[number.length+1];
int carry = 0;
for (int i = number.length - 1; i >= 0; i--) {
result[i+1] = number[i] + number2[i] + carry;
if (result[i+1] > 9) {
carry = result[i+1] - 9;
result[i+1] -= 10;
}
else {
carry = 0;
}
}
System.out.println(Arrays.toString(result));

This code should work for properly carrying numbers greater than 10 to the next up and keep the lower numbers!
int[] result = new int[number1.length+1];
for (int i=number1.length-1; i>=0;i--){
result[i+1] = number1[i] + number[i] + result[i+1];
if(result[i+1] >= 10){
result[i+1] -= 10; // it could never be more than 20 so this is ok and if it is 10 than it will still carry over to the next
result[i] = 1; // the ten carried to the next one
}
}
Similar to Seek Addo's answer, but avoids the errors found in his code that prevent the application from properly carrying the numbers.
This is the most compact way I could think to do it, and should yield the proper answers of
[1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,9,0,0] or 1111111111111234567900

The accepted answer is not good. This is my version of it (support for different array sizes):
public static int[] sumIntArrays(int[] n1, int[] n2) {
int n1Size = n1.length - 1, n2Size = n2.length - 1, indexSum = n1Size > n2Size ? n1Size + 2 : n2Size + 2, slack = 0, s;
int[] sum = new int[indexSum];
while (true) {
if (n1Size < 0 && n2Size < 0)
break;
s = (n1Size < 0 ? 0 : n1[n1Size--]) + (n2Size < 0 ? 0 : n2[n2Size--]) + slack;
if (s > 9) {
sum[--indexSum] = s % 10;
slack = s / 10;
} else {
sum[--indexSum] = s;
slack = 0;
}
}
if (slack != 0)
sum[0] = slack;
return sum;
}

Related

Can I assign each element in a list to a separate variable?

I have a list of 16 numbers, and I want them set as variables n1-n16. I'm looking for something similar to How to assign each element of a list to a separate variable?, but for java.
My code is:
public void setVar()
{
//x = 16;
cardNumR = cardNum;
reversed = 0;
while(cardNumR != 0) {
digit = cardNumR % 10;
reversed = reversed * 10 + digit;
cardNumR /= 10;
}
ArrayList<Long> nums = new ArrayList<Long>(x);
for (int x = 16; x > 0; x--)
{
nums.add(reversed % 10);
reversed -= (reversed % 10);
reversed /= 10;
length = nums.size();
if (length == 16)
{
System.out.println(nums);
}
}
}
which gets me a result of:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
I want to take each of these elements and set n1 = 1, n2 = 2, n3 = 3 so on and so forth such that n16 = 6. I want to be able to do this at the end:
(2*n1) + n2 + (2*n3) + n4 + (2*n5) + n6 + (2*n7) + n8 + (2*n9) + n10 + (2*n11) + n12 + (2*n13) + n14 + (2*n15) + n16
Is there a way I can do this with a loop so that I don't have to do it one by one?
You don't need so many variables. Use a loop instead:
int sum = 0;
for(int i = 0; i < nums.size(); i++) {
if(i % 2 == 0) {
// odd index
sum += 2 * nums.get(i);
} else {
// even index
sum += nums.get(i);
}
}
Well I would just use an array
int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
or a list for that:
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6);
and apply the following formula:
Arrays
int result = 0;
for(int i = 0; i < array.length; i++) {
result += (i % 2 == 0) ? 2 * array[i] : array[i];
}
or if you want to avoid the use of the modulus (%) operation:
int result = 0
for(int i = 0; i < array.length; i+=2)
result += 2 * array[i];
for(int i = 1; i < array.length; i+=2)
result += array[i];
Lists
int result = 0;
for(int i = 0; i < nums.size(); i++) {
result += (i % 2 == 0) ? 2 * nums.get(i) : nums.get(i);
}
without the modulus operation :
int result = 0
for(int i = 0; i < nums.size(); i+=2)
result += 2 * nums.get(i);
for(int i = 1; i < nums.size(); i+=2)
result += nums.get(i);
Java Streams:
int result = IntStream.range(0, nums.size())
.mapToLong(i -> (i % 2 == 0) ? 2 * nums.get(i) : nums.get(i))
.sum();

Maximum number of pairs

I need to find out the maximum number of pairs of 1's and 0's that can be found by just altering a single number in a given array.
For example:
If my input is {1,0,0,1,0,0}, here at index position 3 if I replace 1 with 0 then I will get 4 pairs i.e the arrays becomes {1,0,0,0,0,0}, and the pairs are (1,2), (2,3), (3,4), (4,5).
But if I replace index position 0 from 1 to 0 then the array is {0,0,0,1,0,0} here I will get only 3 pairs i.e (0,1), (1,2), (4,5)
I need a program that returns maximum number of pairs possible for a given input array. In this case the program should give 4 as result.
Here the array contains only 1's and 0's.
Here is my program:
public class Program {
public static void main(String[] args) {
Program program = new Program();
int[] a = { 1, 0, 0, 1, 0, 1 };
int response = program.calculate(a);
System.out.println(response);
}
int calculate(int[] input) {
if(input == null || input.length == 0) {
return -1;
}
int length = input.length;
int result = 0;
for (int i = 0; i < length - 1; i++) {
if (input[i] == input[i + 1]) {
result = result + 1;
}
}
int temp = 0;
for (int i = 0; i < length - 1; i++) {
int count = 0;
if (i > 0) {
if (input[i - 1] != input[i]) {
count = count + 1;
} else {
count = count - 1;
}
}
if (i < length - 1) {
if (input[i + 1] != input[i]) {
count = count + 1;
} else {
count = count - 1;
}
}
temp = Math.max(temp, count);
}
return result + temp;
}
}
I was told the program is having some bugs but I was not able to find out where the issue is. I tried passing various values to this program but it is still working without issues. Can you please help me with some combination of inputs for which this program fails.
Well, it seems to be failing for
{ 0, 0, 0, 0, 0, 0, 1}; -> 5 but not {0, 1}; -> 1
{ 1, 0, 1}; -> 2
{ 1, 1, 1}; -> 2
{ 1,0,0,0,0,1,1,0,0,0}; -> 7

Java: How to implement 3 sum?

I'm studying the 3 Sum to implement it on my own, and came across the following implementation with the rules:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
And implementation (sorts the array, iterates through the list, and uses another two pointers to approach the target):
import java.util.*;
public class ThreeSum {
List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<>();
for (int i=0; i<num.length-2; i++) {
if (i==0 || (i>0 && num[i] != num[i-1])) { //HERE
int lo = i+1;
int hi = num.length-1;
int sum = 0 - num[i];
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
res.add(Arrays.asList(num[i], num[lo], num[hi]));
while (lo < hi && num[lo] == num[lo+1]) lo++; //HERE
while (lo < hi && num[hi] == num[hi-1]) hi--; //HERE
lo++; hi--;
} else if (num[lo] + num[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}
//Driver
public static void main(String args[]) {
ThreeSum ts = new ThreeSum();
int[] sum = {-1, 0, 1, 2, -1, -4};
System.out.println(ts.threeSum(sum));
}
}
And my question is (located where commented: //HERE), what's the reason for checking num[i] != num[i-1], num[lo] == num[lo+1], and num[hi] == num[hi-1]? Supposedly they are supposed to skip the same result, but what does that mean? Examples would really help.
Thank you in advance and will accept answer/up vote.
Imagine you have {-1,-1,0,1,2,4} and considering triplet num[0], num[2], num[3] (-1,0,1).
lo=0 here. To exclude triplet num[1], num[2], num[3] with the same values, we should increment lo and pass over duplicate
This will prevent the list to have duplicate triplet.
For example, with you test :
int[] sum = {-1, 0, 1, 2, -1, -4};
will be sorted like :
sum = {-4, -1, -1, 0, 1, 2};
You see that you have -1 twice. Without these test, you would test twice if -1 = 0 + 1. This is not usefull so the algo simply search the next different value.
You could remove duplicate in the sorted List to prevent these test.
Thanks to MBo, we can't remove duplicate since we can have triplet with same value (but with different index)
All the three sentences is used to avoid the duplicate output.
Consider a sorted list {-2, -2 , 1, 1}
If there is no checking for num[i] != num[i-1], the output of the program would be(-2, 1, 1)and(-2, 1, 1), which are two duplicate triplets.
The checking for num[lo] != num[lo + 1]and num[hi] != num[hi - 1] are for the same reason.
Consider a sorted list
{-2,-1,-1,0,3}
If there is no checking for num[lo], you will get (-2,-1,3) and (-2,-1,3) as the output.
Still, I want to recommend a better solution for this problem. You can numerate the sum of two numbers in the list and find the 3rd number by hash or binary search. It will helps you to gain a O(n^2logn) time complexity rather than O(n^3). (I was wrong, the time complexity of this algorithm is O(n^2), sorry for that.)
Following program finds pairs of three integer with O(N*2)
Sort the input Array
and iterate each element in for loop and check for sum in program which is developed for Two sum.
Two sum in linear time after sorting ->
https://stackoverflow.com/a/49650614/4723446
public class ThreeSum {
private static int countThreeSum(int[] numbers) {
int count = 0;
for (int i = 0; i < numbers.length; i++) {
int front = 0, rear = numbers.length - 1;
while (front < rear) {
if (numbers[front] + numbers[rear] + numbers[i] == 0) {
System.out.printf(String.format("Front : {%d} Rear : {%d} I : {%d} \n", numbers[front],
numbers[rear], numbers[i]));
front++;
rear--;
count++;
} else {
if (Math.abs(numbers[front]) > Math.abs(numbers[rear])) {
front++;
} else {
rear--;
}
}
}
}
return count;
}
public static void main(String[] args) {
int[] numbers = { 1, 3, 5, 7, 12, 16, 19, 15, 11, 8, -1, -3, -7, -8, -11, -17, -15 };
Arrays.sort(numbers);
System.out.println(countThreeSum(numbers));
}
}
It's worked with any NSum (3Sum, 4Sum, 5Sum, ...) and quite fast.
public class ThreeSum {
private static final int RANDOM_RANGE = 20;
private Integer array[];
private Integer arrayIndex[];
private int result[];
private int bagLength;
private int resultIndex = 0;
private void generateData(int size) {
array = new Integer[size];
Random random = new Random();
for (int i = 0; i < size; i++) {
array[i] = random.nextInt(RANDOM_RANGE) - (RANDOM_RANGE/2);
}
}
private void markArrayIndex(int size) {
arrayIndex = new Integer[size];
for (int i = 0; i < size; i++) {
arrayIndex[i] = i;
}
}
private void prepareBeforeCalculate(int size, int sumExpected, int bagLength) {
this.bagLength = bagLength;
result = new int[bagLength];
generateData(size);
markArrayIndex(size);
}
void calculate(int size, int sumExpected, int bagLength) {
prepareBeforeCalculate(size, sumExpected, bagLength);
Arrays.sort(arrayIndex, (l, r) -> array[l].compareTo(array[r]));
System.out.println(Arrays.toString(array));
long startAt = System.currentTimeMillis();
if (sumExpected > 0) findLeft(sumExpected, 0, 0, array.length);
else findRight(sumExpected, 0, 0 - 1, array.length - 1);
System.out.println("Calculating in " + ((System.currentTimeMillis() - startAt) / 1000));
}
private void findLeft(int total, int indexBag, int left, int right) {
while (left < array.length && array[arrayIndex[left]] < 0 && indexBag < bagLength) {
navigating(total, arrayIndex[left], indexBag, left, right);
left++;
}
}
private void findRight(int total, int indexBag, int left, int right) {
while (right >= 0 && array[arrayIndex[right]] >= 0 && indexBag < bagLength) {
navigating(total, arrayIndex[right], indexBag, left, right);
right--;
}
}
private void navigating(int total, int index, int indexBag, int left, int right) {
result[indexBag] = index;
total += array[index];
if (total == 0 && indexBag == bagLength - 1) {
System.out.println(String.format("R[%d] %s", resultIndex++, toResultString()));
return;
}
if (total > 0) findLeft(total, indexBag + 1, left + 1, right);
else findRight(total, indexBag + 1, left, right - 1);
}
private String toResultString() {
int [] copyResult = Arrays.copyOf(result, result.length);
Arrays.sort(copyResult);
int iMax = copyResult.length - 1;
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(array[copyResult[i]]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
}
public class ThreeSumTest {
#Test
public void test() {
ThreeSum test = new ThreeSum();
test.calculate(100, 0, 3);
Assert.assertTrue(true);
}
}

Find elements in array whose sum is equal to 10 - Java

I want to find all the pairs of numbers from an array whose sum is equal to 10, and am trying to improve upon this bit of code here:
for (int j = 0; j < arrayOfIntegers.length - 1; j++)
{
for (int k = j + 1; k < arrayOfIntegers.length; k++)
{
int sum = arrayOfIntegers[j] + arrayOfIntegers[k];
if (sum == 10)
return j + "," + k;
}
}
However, I'm having trouble moving through the array. Here's what I have so far:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = arrayOfIntegers[0];
int right = (arrayOfIntegers[arrayOfIntegers.length - 1]);
while (left < right)
{
int sum = left + right;
if (sum == 10) //check to see if equal to 10
{
System.out.println(left + "," + right);
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
Try this code by passing the value of the sum and array in which you want to find the pair of elements equals to a given sum using one for loop
private void pairofArrayElementsEqualstoGivenSum(int sum,Integer[] arr){
List numList = Arrays.asList(arr);
for (int i = 0; i < arr.length; i++) {
int num = sum - arr[i];
if (numList.contains(num)) {
System.out.println("" + arr[i] + " " + num + " = "+sum);
}
}
}
You need to capture the values as well as the indexes:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = 0;
int right = arrayOfIntegers.length - 1;
while (left < right)
{
int leftVal = arrayOfIntegers[left];
int rightVal = (arrayOfIntegers[right]);
int sum = leftVal + rightVal;
if (sum == 10) //check to see if equal to 10
{
System.out.println(arrayOfIntegers[left] + "," + arrayOfIntegers[right]);
right --;
left++;
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
output:
[0, 2, 3, 4, 5, 6, 7, 10]
0,10
3,7
4,6
This is sample code with javascrypt. Someone can use it
var arr = [0, 5, 4, 6, 3, 7, 2, 10]
var arr1 = arr;
for(var a=0; a<arr.length;a++){
for(var b=0; b<arr.length; b++){
if(arr[a]+arr[b]===10 && a!==b){
console.log(arr[a]+" + "+arr[b])
arr.splice(a,1);
}
}
}
Java - Using single loop
public static void findElements() {
List<Integer> list = List.of(0, 5, 4, 6, 3, 7, 2, 10);
for (int i = 0; i < list.size(); i++) {
int sum = 0;
if (i < list.size() - 1) {
sum = list.get(i) + list.get(i + 1);
if (sum == 10) {
System.out.println("Element: " + list.get(i) + "," + list.get(i + 1));
}
} else {
if (list.get(i) == 10) {
System.out.println("Element: " + list.get(i));
}
}
}
}

My for-loops seem to be invisible

I'm trying to make a program calculate the first four perfect numbers. It compiles, but when I run the program, the for-loops seem to be invisible. Like when I look at the debugger, it looks like the for-loops are just skipped over and the variables don't exist.
public static void main(String[] args)
{
int pNum = 2; // starting number to check
int sum = 0;
for (int count = 1; count <= 4; count++)
{
for (int factor = 1; factor < pNum; factor++)
{
if (pNum % factor == 0)
sum += factor;
}
if (pNum == sum)
{
System.out.println(pNum + " is a perfect number.");
count++;
}
pNum++; sum = 0;
}
}
count = 1, pNum = 2, sum = 0
factor = 1, sum = 0
count = 2, pNum = 3, sum = 0
factor = 1, sum = 0
factor = 2, sum = 1
count = 3, pNum = 4, sum = 0
factor = 1, sum = 0
factor = 2, sum = 1
factor = 3, sum = 3
count = 4, pNum = 5, sum = 0
factor = 1, sum = 0
factor = 2, sum = 1
factor = 3, sum = 1
factor = 4, sum = 1
I think your debugger is acting up, try a printoutput to check if the loop works
for(int count = 1; count <= 4; count++){
System.out.println("count:"+count);

Categories