Java: How to sum the elements of two arrays with different lengths - java

I am trying to add the elements of two arrays with different lengths together.
The code below is only for the same length and here is all I have so far.
//for the same lengths
int[]num1 = {1,9,9,9};
int[]num2 = {7,9,9,9};// {9,9,9}
int total = 0, carry = 1;
int capacity = Math.max(num1.length,num2.length);
int []arraySum = new int [capacity];
for (int i = capacity - 1 ; i >= 0; i--)
{
arraySum[i] = num1[i]+ num2[i];
if (arraySum[i] > 9)
{
arraySum[i] = arraySum[i] % 10;
num2[i-1] = num2[i-1] + carry;
}
}
for(int i = 0; i < arraySum.length; i++)
{
System.out.print(arraySum[i]);
}
What should I do if I change the elements in num2 and length to like {9,9,9}?
I know I probably need to put another for-loop as an inside for-loop and control the indices of the array with smaller length but how....?? One more thing... what should I do for those for-loops conditions because num1 and num2 will be eventually INPUTED by the user.
Well, you can tell that the inputs are limited because if num1[0] + num2[0] > 9 the carry has no index to be placed, then it can't be compiled. So, I need to shift the whole array to the right and place the carry from num1[0] + num2[0]. Here is the problem!! Where should I put the shifting code? I am kinda confused.......

Actually, you declare an int[] array with the capacity as Math.max(num1.length, num2.length).
It is not encough. You should set the capacity as Math.max(num1.length, num2.length) +1.
Why?
See if num1 is {1,9,9,9} and num2 is {9,9,9,9}, how can the arraySum to represent the sum {1,1,9,9,8}?
So we need to declare it as below to consider if carry is needed.
int[] arraySum = new int[capacity + 1];
Then when print the sum, check if arraySum[0] is 0 or 1, if it euqals to 0, do not print it in Console.
Modified code for reference is as follows:
package question;
public class Example {
public static void main(String[] args) {
// for the same lengths
int[] num1 = { 1,9,9,9 };
int[] num2 = { 9,9,9,9};// {9,9,9}
// 1999+9999 = 11998, its length is greater than the max
int capacity = Math.max(num1.length, num2.length);
int[] arraySum = new int[capacity + 1];
int len2 = num2.length;
int len1 = num1.length;
if (len1 < len2) {
int lengthDiff = len2 - len1;
/*
* Flag for checking if carry is needed.
*/
boolean needCarry = false;
for (int i = len1 - 1; i >= 0; i--) {
/**
* Start with the biggest index
*/
int sumPerPosition =0;
if (needCarry) {
sumPerPosition = num1[i] + num2[i + lengthDiff] +1;
needCarry = false;
}else
{
sumPerPosition = num1[i] + num2[i + lengthDiff];
}
if (sumPerPosition > 9) {
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
needCarry = true;
}else
{
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
}
}
/**
* Handle the remaining part in nun2 Array
*/
for (int i = lengthDiff - 1; i >= 0; i--) {
/*
* Do not need to care num1 Array Here now
*/
if(needCarry){
arraySum[i + 1] = num2[i]+1;
}else
{
arraySum[i + 1] = num1[i] ;
}
if (arraySum[i + 1] > 9) {
arraySum[i + 1] = arraySum[i + 1] % 10;
needCarry = true;
} else {
needCarry = false;
}
}
/*
* Handle the last number, if carry is needed. set it to 1, else set
* it to 0
*/
if (needCarry) {
arraySum[0] = 1;
} else {
arraySum[0] = 0;
}
} else {
int lengthDiff = len1 - len2;
/*
* Flag for checking if carry is needed.
*/
boolean needCarry = false;
for (int i = len2 - 1; i >= 0; i--) {
/**
* Start with the biggest index
*/
int sumPerPosition = 0;
if (needCarry) {
sumPerPosition = num2[i] + num1[i + lengthDiff] +1;
needCarry = false;
}else
{
sumPerPosition = num2[i] + num1[i + lengthDiff];
}
if (sumPerPosition > 9) {
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
needCarry = true;
}else
{
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
}
}
/**
* Handle the remaining part in nun2 Array
*/
for (int i = lengthDiff - 1; i >= 0; i--) {
/*
* Do not need to care num1 Array Here now
*/
if(needCarry){
arraySum[i + 1] = num1[i]+1;
}else
{
arraySum[i + 1] = num1[i] ;
}
if (arraySum[i + 1] > 9) {
arraySum[i + 1] = arraySum[i + 1] % 10;
needCarry = true;
} else {
needCarry = false;
}
}
/*
* Handle the last number, if carry is needed. set it to 1, else set
* it to 0
*/
if (needCarry) {
arraySum[0] = 1;
} else {
arraySum[0] = 0;
}
}
/*
* Print sum
*
* if arraySum[0] ==1, print 1
*
* Do not print 0 when arraySum[0] ==0
*/
if(arraySum[0] == 1)
{
System.out.print(1);
}
for (int i = 1; i < arraySum.length; i++) {
System.out.print(arraySum[i]);
}
}
}
An example that num1 is {1,9,9,9} and num2 is {9,9,9,9}, the sum result is as follows:
output in Console:
11998

It's quite simpe actually. Inside your loop, check that the current index is valid for both array, and replace the value to add by 0 in case of an invalid index:
int value1 = (i < num1.length) ? num1[i] : 0;
int value2 = (i < num2.length) ? num2[i] : 0;
arraySum[i] = value1 + value2;
EDIT: I didn't understand that you wanted to right-align the arrays and not left-align them. The simplest solution is probably to write and read everything in the arrays in reverse order. So if the numbers are 456 and 7658, the first array would contain 6, 5, 4 and the second one would contain 8, 5, 6, 7.

Here is more performance centric solution:
public class SumArrays {
public static void main(String[] args) {
int[] num1 = {1, 9, 9, 9};
int[] num2 = {7, 9, 9, 9, 9, 9, 9};
int[] biggerArray = num1.length > num2.length ? num1 : num2;
int[] smallerArray = num1.length <= num2.length ? num1 : num2;
int[] summedArray = new int[biggerArray.length];
System.arraycopy(biggerArray, 0, summedArray, 0, biggerArray.length);
for (int i = 0; i < smallerArray.length; i++) {
summedArray[i] += smallerArray[i];
}
for (int i = 0; i < summedArray.length; i++) {
System.out.println(summedArray[i]);
}
}
}

You can use an ArrayList instead of an array and implement a normal addition method to it:
public static ArrayList<Integer> sum(int[] arr, int[] arr2) {
ArrayList<Integer> al = new ArrayList<>();
int i = arr.length - 1;
int j = arr2.length - 1;
int c = 0;
while (i >= 0 && j >= 0) {
int temp = arr[i] + arr2[j] + c;
if (temp >= 10) {
int r = temp % 10;
al.add(0, r);
c = temp / 10;
} else {
al.add(0, temp);
c = 0;
}
i--;
j--;
}
if (i < 0 && j >= 0) {
while (j >= 0) {
al.add(0, arr2[j] + c);
c = 0;
j--;
}
} else if (j < 0 && i >= 0) {
while (i >= 0) {
al.add(0, arr[i] + c);
c = 0;
i--;
}
} else
al.add(0, c);
return al;
}

for kicks, here is an alternative:
int[] num1 =
{ 1, 9, 9, 9 };
int[] num2 =
{ 7, 9, 9, 9 };
//convert the int array to a string
StringBuilder sb = new StringBuilder(num1.length);
for (int i : num1)
{
sb.append(i);
}
String sNum1 = sb.toString();
System.out.println(sNum1);
StringBuilder sb2 = new StringBuilder(num2.length);
for (int i : num2)
{
sb2.append(i);
}
String sNum2 = sb2.toString();
System.out.println(sNum2);
try
{
//parse the string to an int
int iNum1 = Integer.parseInt(sNum1);
int iNum2 = Integer.parseInt(sNum2);
//add them together
int sum = iNum1 + iNum2;
String sSum = Integer.toString(sum);
System.out.println(sSum);
// convert num back to array
int[] sumArray = new int[sSum.length()];
for (int i = 0; i < sSum.length(); i++)
{
sumArray[i] = sSum.charAt(i) - '0';
System.out.println(sumArray[i]);
}
}
catch (Exception e)
{
// couldnt parse ints
}

Related

How do i make it so every number that is next to a zero divides by two?

Everything I have tried so far divides the code by 2 and it does it twice for some reason.
CSP-ARRAY
An array inhabitant represents cities and their respective populations. For example, the following arrays shows 8 cities and their respective populations:[3, 6, 0, 4, 3, 2, 7, 1]Some cities have a population of 0 due to a pandemic zombie disease that is wiping away the human lives. After each day, any city that is adjacent to a zombie-ridden city will lose half of its population.Write a program to loop though each city population and make it lose half of its population if it is adjacent (right or left) to a city with zero people until all cities have no humans left.
package Arrays;
public class Project {
public static void main(String[] args){
int i = 0;
boolean hi = false;
boolean hi1 = false;
boolean hi2 = false;
boolean hi3 = false;
boolean hi4 = false;
boolean hi5 = false;
boolean hi6 = false;
boolean hi7 = false;
int[] a = {3, 6, 0, 4, 3, 2, 7, 1};
if(a[0]==0) {
hi=true;
}
if(a[1]==0) {
hi1=true;
}
if(a[2]==0) {
hi2=true;
}
if(a[3]==0) {
hi3=true;
}
if(a[4]==0) {
hi4=true;
}
if(a[5]==0) {
hi5=true;
}
if(a[6]==0) {
hi6=true;
}
if(a[7]==0) {
hi7=true;
}
int z=1;
while(hi!=false || hi1!=false || hi2!=false || hi3!=false || hi4!=false || hi5!=false || hi6!=false || hi7!=false) {
if(hi=true){
a[1]=a[1]/2;
}
if(hi1=true){
a[0]=a[0]/2;
a[2]=a[2]/2;
}
if(hi2=true){
a[1]=a[1]/2;
a[3]=a[3]/2;
}
if(hi3=true){
a[2]=a[2]/2;
a[4]=a[4]/2;
}
if(hi4=true){
a[3]=a[3]/2;
a[5]=a[5]/2;
}
if(hi5=true){
a[4]=a[4]/2;
a[6]=a[6]/2;
}
if(hi6=true){
a[5]=a[5]/2;
a[7]=a[7]/2;
}
if(hi7=true){
a[6]=a[6]/2;
}
System.out.println("Day "+i+": ["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+"] ");
i++;
}
}
}
I think it is pretty simple. Just go through the array and check previous and next value.
public static void calc(int[] arr) {
for(int i = 1; i < arr.length; i++)
if(arr[i] > 0 && arr[i - 1] == 0)
arr[i] /= -2;
for(int i = arr.length - 2; i >= 0; i--)
if(arr[i] < 0)
arr[i] = -arr[i];
else if(arr[i] > 0 && arr[i + 1] == 0)
arr[i] /= 2;
}
I am also new to Java, but here is my attempt.
import java.util.Arrays;
public class Project {
public static void main(String[] args) {
int[] a = {3, 6, 0, 4, 3, 2, 7, 1};
zombieApocalypse(a);
}
public static void zombieApocalypse(int[] array) {
boolean keepGoing = true;
int j = 1;
while (keepGoing) {
int[] arrayCopy = array;
//first element
if (array[0] == 0) {
arrayCopy[1] = array[1] / 2;
}
//element in the middle
for (int i = 1; i < array.length - 1; i++) {
if (array[i] == 0) {
arrayCopy[i - 1] = array[i - 1] / 2;
arrayCopy[i + 1] = array[i + 1] / 2;
}
}
//last element
if (array[array.length - 1] == 0) {
arrayCopy[array.length - 1] = array[array.length - 1] / 2;
}
System.out.println("Day " + j);
//copies clone back to original array
array = arrayCopy;
System.out.println(Arrays.toString(array));
j++;
int counter = 0;
//for each element checking if every city is zero
for (int element : array) {
counter = counter + element;
}
//if each element value in every city is zero, we stop
if (counter == 0) {
keepGoing = false;
}
}
}
}
This is what you were going for.
import java.util.Arrays;
public class Project {
public static void main(String[] args) {
int i = 0;
boolean hi = false;
boolean hi1 = false;
boolean hi2 = false;
boolean hi3 = false;
boolean hi4 = false;
boolean hi5 = false;
boolean hi6 = false;
boolean hi7 = false;
int[] a = {3, 6, 0, 4, 3, 2, 7, 1};
//the line of code below this comment is never used ever, what is it for?
int z = 1;
while ((((!hi || !hi1) || (!hi2 || !hi3)) || (!hi4 || !hi5)) || (!hi6 || !hi7)){
if (hi) {
a[1] = a[1] / 2;
}
if (hi1) {
a[0] = a[0] / 2;
a[2] = a[2] / 2;
}
if (hi2) {
a[1] = a[1] / 2;
a[3] = a[3] / 2;
}
if (hi3) {
a[2] = a[2] / 2;
a[4] = a[4] / 2;
}
if (hi4) {
a[3] = a[3] / 2;
a[5] = a[5] / 2;
}
if (hi5) {
a[4] = a[4] / 2;
a[6] = a[6] / 2;
}
if (hi6) {
a[5] = a[5] / 2;
a[7] = a[7] / 2;
}
if (hi7) {
a[6] = a[6] / 2;
}
System.out.println("Day " + i + Arrays.toString(a));
i++;
/*if you want to update the boolean values after they are changed, then you have to include it within the block of code
that is changing it. (if they are outside of this block of code, how will they ever update?)
*/
if (a[0] == 0) {
hi = true;
}
if (a[1] == 0) {
hi1 = true;
}
if (a[2] == 0) {
hi2 = true;
}
if (a[3] == 0) {
hi3 = true;
}
if (a[4] == 0) {
hi4 = true;
}
if (a[5] == 0) {
hi5 = true;
}
if (a[6] == 0) {
hi6 = true;
}
if (a[7] == 0) {
hi7 = true;
}
}
}
}
For each day iteration, you find the cities that have 0 population and push those indices to an array and let's name this array "indices". Then loop through this array and divide the population half only neighbor of these indices. I write in javascript.
const inhabitants = (Arr) => {
let day = 0;
let A = Arr;
// allEqual checks if the all elements in array is 0
// when allEqual is true loop is over
const allEqual = (arr) => arr.every((v) => v === arr[0]);
while (!allEqual(A)) {
// find the array[i]= 0 and push the "i" in indices
let indices = [];
for (let i = 0; i < A.length; i++) {
if (A[i] === 0) {
indices.push(i);
}
}
// just divide the neighbor elements of element 0
for (let j = 0; j < indices.length; j++) {
if (indices[j] > 0) {
A[indices[j] - 1] = Math.floor(A[indices[j] - 1] / 2);
}
if (indices[j] + 1 < A.length) {
A[indices[j] + 1] = Math.floor(A[indices[j] + 1] / 2);
}
}
day++;
console.log(`population on day ${day}`, A);
}
};

How can I use values stored in an array to another method to do a calculation?

static void diceRoll(int[] val) {
for (int i=0;i<6;i++) {
int roll1 = (int) ((Math.random() * 1000 % 6 + 1));
int roll2 = (int) ((Math.random() * 1000 % 6 + 1));
int roll3 = (int) ((Math.random() * 1000 % 6 + 1));
int roll4 = (int) ((Math.random() * 1000 % 6 + 1));
int total =0;
if ((roll1 < roll2) && (roll1 < roll3) && (roll1 < roll4)) {
total= roll2 + roll3 + roll4;
} else if ((roll2 < roll1) && (roll2 < roll3) && (roll2 < roll4)) {
total= roll1 + roll3 + roll4;
} else if ((roll3 < roll1) && (roll3 < roll2) && (roll3 < roll4)) {
total = roll1 + roll2 + roll4;
} else if ((roll4 < roll1) && (roll4 < roll2) && (roll4 < roll3)) {
total = roll1 + roll2 + roll3;
}
}
}
static void calculateBonus(int[] bonusVal){
int bonus=0;
int[] val= new int[6];
for (int i=0;i<6;i++)
for(int j=0;j<6;j++)
if (val[i] > 10 && val[i] != 11) {
bonusVal[j] = (val[i] - 10) / 2;
} else if (val[i] < 10) {
bonusVal[j] = ((val[i] / 2) - 5);
} else if (val[i] == 10 || val[i] == 11) {
bonusVal[j] = 0;
}
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
//Declaring variables
int level;
String choice = null;
//Getting the Level value
System.out.println("Enter the Level value :");
level = sc.nextInt();
while ((level<=0)||(level>20)){
System.out.println("Invalid input.Please enter a number between 1-20.");
System.out.println("Enter the Level value : ");
level = sc.nextInt();
}
do{
int[] val= new int[6];
int _str= val[0];
int con= val[1];
int dex= val[2];
int _int= val[3];
int wis= val[4];
int _cha= val[5];
int [] bonusVal=new int[6];
int bonus1= bonusVal[0];
int bonus2= bonusVal[1];
int bonus3= bonusVal[2];
int bonus4= bonusVal[3];
int bonus5= bonusVal[4];
int bonus6= bonusVal[5];
//Printing the Level
System.out.println("\n\n\n\n\nLevel : [ "+level+" ]");
//Displaying out put
System.out.println("_Str : ["+_str+" ]"+"["+bonus1+"]");
System.out.println("Dex : ["+dex+" ]"+"["+bonus2+"]");
System.out.println("Con : ["+con+" ]"+"["+bonus3+"]");
System.out.println("Int : ["+_int+" ]"+"["+bonus4+"]");
System.out.println("Wis : ["+wis+" ]"+"["+bonus5+"]");
System.out.println("_Cha : ["+_cha+" ]"+"["+bonus6+"]");
//Calculating the Hit points
double hp = (((Math.random()*1000 %6+1)+bonus3)*level);
//Print the Hit points
System.out.println("HP : ["+hp+"]");
//Give the chance to re-roll or continue
System.out.println("Type r if you want to re-roll or any other character if you want to continue :");
choice = sc.next();
}
while (choice.equals("r"));;
}
}
I think i had made mistakes in the second method .I want to figure out how can i use above stored values in the array to calcuate bonus and store the values for bonus in another array.This is the program i have so far.I still didnt got the output i neede.I need to get 6 values from dice roll method and store them in an array.and then i want to call the values to calculate bonus and store those bonus values in another array.
I think you want to do something like below. I haven't compiled the code, let me know if you face any issues in compiling.
static int[] calculateBonus(int[] val) {
int[] bonusVal = new int[val.length];
for(int j=0; j < val.length; j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonusVal;
}
You need to return an array from the first method to start with, right now it doesn't work with an array at all.
Change it to the below to return an array and have a new array variable
static int[] diceRoll() {
final int rolls = 6;
int[] result = new int[rolls];
//the for loop...
at the end of the for loop you store the value in the array and then at the end return the array so the end of the method will look like
result[i] = total;
}
return result;
}
The calculateBonus will use this returned array as input and it will also work internally with an array and not an int as you have now. I also added that it will return an array.
static int[] calculateBonus(int[] val){
int count = val.length;
int[] bonus = new int[count];
for(int j=0;j<count;j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonus;
}
A simple run
public static void main(String[] args) {
int[] values = diceRoll();
int[] bonus = calculateBonus(values);
for(int i=0; i<bonus.length; i++) {
System.out.println(bonus[i]);
}
}
Update
Below is a new version of the two methods that addresses the questions I asked in the comment and also clean up the code some.
Main difference is that I use a ArrayList in the diceRole method and that calculateBonus now uses double.
static int[] diceRoll() {
int[] result = new int[6];
for (int i=0;i<6;i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < 4; j++) {
list.add(new Integer((int) ((Math.random() * 1000 % 6 + 1))));
}
Collections.sort(list); //list is now in ascending order
int total =0;
for (int j = 1; j < list.size(); j++) {
total += list.get(j).intValue();
}
result[i] = total;
}
return result;
}
static double[] calculateBonus(int[] val) {
int count = val.length;
double[] bonus = new double[count];
for(int j=0;j<count;j++) {
double value = 0.0;
if (val[j] > 11) {
value = (val[j] - 10.0) / 2.0;
} else if (val[j] < 10.0) {
value = ((val[j] / 2.0) - 5.0);
}
bonus[j] = value;
}
return bonus;
}

How to increment integer Array values?

I am designing a problem in which I have to use an int array to add or subtract values. For example instead of changing 100 to 101 by adding 1, I want to do the same thing using the int array. It work like this:
int[] val = new int[3];
val[0] = 1;
val[1] = 0;
val[2] = 0;
val[2] += 1;
so, If I have to get a value of 101, I will add 1 to val[2].
The only problem I have is finding a way to make int array work like how adding and subtracting from an ordinary integer data set works.
Is this possible using a for loop or a while loop?
Any help will be appreciated!
Here's your homework:
public static int[] increment(int[] val) {
for (int i = val.length - 1; i >= 0; i--) {
if (++val[i] < 10)
return val;
val[i] = 0;
}
val = new int[val.length + 1];
val[0] = 1;
return val;
}
Make sure you understand how and why it works before submitting it as your own work.
Solution of this problem is designed by using String
You can refer to this method which will return sum of 2 nos having input in String format.
Input String should contain only digits.
class Demo {
public static String add(String a1, String b1) {
int[] a = String_to_int_Array(a1);
int[] b = String_to_int_Array(b1);
int l = a.length - 1;
int m = b.length - 1;
int sum = 0;
int carry = 0;
int rem = 0;
String temp = "";
if (a.length > b.length) {
while (m >= 0) {
sum = a[l] + b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
l--;
}
while (l >= 0) {
sum = a[l] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
l--;
}
if (carry > 0) {
temp = carry + temp;
}
} else {
while (l >= 0) {
sum = a[l] + b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
l--;
}
while (m >= 0) {
sum = b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
}
if (carry > 0) {
temp = carry + temp;
}
}
return temp;
}
public static int[] String_to_int_Array(String s) {
int arr[] = new int[s.length()], i;
for (i = 0; i < s.length(); i++)
arr[i] = Character.digit(s.charAt(i), 10);
return arr;
}
public static void main(String a[]) {
System.out.println(add("222", "111"));
}
}
Quick & dirty:
static void increment(int[] array){
int i = array.length-1;
do{
array[i]=(array[i]+1)%10;
}while(array[i--]==0 && i>=0);
}
Note the overflow when incementing e.g. {9, 9}. Result is {0, 0} here.
public static void increment() {
int[] acc = {9,9,9,9};
String s="";
for (int i = 0; i < acc.length; i++)
s += (acc[i] + "");
int i = Integer.parseInt(s);
i++;
System.out.println("\n"+i);
String temp = Integer.toString(i);
int[] newGuess = new int[temp.length()];
for (i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
printNumbers(newGuess);
}
public static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
If someone is looking for this solution using JavaScript or if you can translate it to java, here's your optimum solution:
function incrementArr(arr) {
let toBeIncrementedFlag = 1, // carry over logic
i = arr.length - 1;
while (toBeIncrementedFlag) {
if (arr[i] === 9) {
arr[i] = 0; // setting the digit as 0 and using carry over
toBeIncrementedFlag = 1;
} else {
toBeIncrementedFlag = 0;
arr[i] += 1;
break; // Breaking loop once no carry over is left
}
if (i === 0) { // handling case of [9,9] [9,9,9] and so on
arr.unshift(1);
break;
}
i--; // going left to right because of carry over
}
return arr;
}

Check Credit Card Validity using Luhn Algorithm

I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
2 * 2 = 4
2 * 2 = 4
4 * 2 = 8
1 * 2 = 2
6 * 2 = 12 (1 + 2 = 3)
5 * 2 = 10 (1 + 0 = 1)
8 * 2 = 16 (1 + 6 = 7)
4 * 2 = 8
Now add all single-digit numbers from Step 1.
4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number.
6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Sum the results from Step 2 and Step 3.
37 + 38 = 75
If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.
Simply, my program always displays valid for everything that I input. Even if it's a valid number and the result of sumOfOddPlace and sumOfDoubleEvenPlace methods are equal to zero. Any help is appreciated.
import java.util.Scanner;
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count - 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
You can freely import the following code:
public class Luhn
{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
}
Link reference: https://github.com/jduke32/gnuc-credit-card-checker/blob/master/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
Google and Wikipedia are your friends. Instead of long-array I would use int-array. On Wikipedia following java code is published (together with detailed explanation of Luhn algorithm):
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
You should work on your input processing code. I suggest you to study following solution:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
I took a stab at this with Java 8:
public static boolean luhn(String cc) {
final boolean[] dbl = {false};
return cc
.chars()
.map(c -> Character.digit((char) c, 10))
.map(i -> ((dbl[0] = !dbl[0])) ? (((i*2)>9) ? (i*2)-9 : i*2) : i)
.sum() % 10 == 0;
}
Add the line
.replaceAll("\\s+", "")
Before
.chars()
If you want to handle whitespace.
Seems to produce identical results to
return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(cc);
From Apache's commons-validator.
There are two ways to split up your int into List<Integer>
Use %10 as you are using and store it into a List
Convert to a String and then take the numeric values
Here are a couple of quick examples
public static void main(String[] args) throws Exception {
final int num = 12345;
final List<Integer> nums1 = splitInt(num);
final List<Integer> nums2 = splitString(num);
System.out.println(nums1);
System.out.println(nums2);
}
private static List<Integer> splitInt(int num) {
final List<Integer> ints = new ArrayList<>();
while (num > 0) {
ints.add(0, num % 10);
num /= 10;
}
return ints;
}
private static List<Integer> splitString(int num) {
final List<Integer> ints = new ArrayList<>();
for (final char c : Integer.toString(num).toCharArray()) {
ints.add(Character.getNumericValue(c));
}
return ints;
}
I'll use 5 digit card numbers for simplicity. Let's say your card number is 12345; if I read the code correctly, you store in array the individual digits:
array[] = {1, 2, 3, 4, 5}
Since you already have the digits, in sumOfOddPlace you should do something like
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i = 1; i < array.length; i += 2) {
result += array[i];
}
return result;
}
And in sumOfDoubleEvenPlace:
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
for (int i = 0; i < array.length; i += 2) {
result += getDigit(2 * array[i]);
}
return result;
}
this is the luhn algorithm implementation which I use for only 16 digit Credit Card Number
if(ccnum.length()==16){
char[] c = ccnum.toCharArray();
int[] cint = new int[16];
for(int i=0;i<16;i++){
if(i%2==1){
cint[i] = Integer.parseInt(String.valueOf(c[i]))*2;
if(cint[i] >9)
cint[i]=1+cint[i]%10;
}
else
cint[i] = Integer.parseInt(String.valueOf(c[i]));
}
int sum=0;
for(int i=0;i<16;i++){
sum+=cint[i];
}
if(sum%10==0)
result.setText("Card is Valid");
else
result.setText("Card is Invalid");
}else
result.setText("Card is Invalid");
If you want to make it use on any number replace all 16 with your input number length.
It will work for Visa number given in the question.(I tested it)
Here's my implementation of the Luhn Formula.
/**
* Runs the Luhn Equation on a user inputed CCN, which in turn
* determines if it is a valid card number.
* #param c A user inputed CCN.
* #param cn The check number for the card.
* #return If the card is valid based on the Luhn Equation.
*/
public boolean luhn (String c, char cn)
{
String card = c;
String checkString = "" + cn;
int check = Integer.valueOf(checkString);
//Drop the last digit.
card = card.substring(0, ( card.length() - 1 ) );
//Reverse the digits.
String cardrev = new StringBuilder(card).reverse().toString();
//Store it in an int array.
char[] cardArray = cardrev.toCharArray();
int[] cardWorking = new int[cardArray.length];
int addedNumbers = 0;
for (int i = 0; i < cardArray.length; i++)
{
cardWorking[i] = Character.getNumericValue( cardArray[i] );
}
//Double odd positioned digits (which are really even in our case, since index starts at 0).
for (int j = 0; j < cardWorking.length; j++)
{
if ( (j % 2) == 0)
{
cardWorking[j] = cardWorking[j] * 2;
}
}
//Subtract 9 from digits larger than 9.
for (int k = 0; k < cardWorking.length; k++)
{
if (cardWorking[k] > 9)
{
cardWorking[k] = cardWorking[k] - 9;
}
}
//Add all the numbers together.
for (int l = 0; l < cardWorking.length; l++)
{
addedNumbers += cardWorking[l];
}
//Finally, check if the number we got from adding all the other numbers
//when divided by ten has a remainder equal to the check number.
if (addedNumbers % 10 == check)
{
return true;
}
else
{
return false;
}
}
I pass in the card as c which I get from a Scanner and store in card, and for cn I pass in checkNumber = card.charAt( (card.length() - 1) );.
Okay, this can be solved with a type conversions to string and some Java 8
stuff. Don't forget numbers and the characters representing numbers are not the same. '1' != 1
public static int[] longToIntArray(long cardNumber){
return Long.toString(cardNumber).chars()
.map(x -> x - '0') //converts char to int
.toArray(); //converts to int array
}
You can now use this method to perform the luhn algorithm:
public static int luhnCardValidator(int cardNumbers[]) {
int sum = 0, nxtDigit;
for (int i = 0; i<cardNumbers.length; i++) {
if (i % 2 == 0)
nxtDigit = (nxtDigit > 4) ? (nxtDigit * 2 - 10) + 1 : nxtDigit * 2;
sum += nxtDigit;
}
return (sum % 10);
}
private static int luhnAlgorithm(String number){
int n=0;
for(int i = 0; i<number.length(); i++){
int x = Integer.parseInt(""+number.charAt(i));
n += (x*Math.pow(2, i%2))%10;
if (x>=5 && i%2==1) n++;
}
return n%10;
}
public class Creditcard {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String cardno = sc.nextLine();
if(checkType(cardno).equals("U")) //checking for unknown type
System.out.println("UNKNOWN");
else
checkValid(cardno); //validation
}
private static String checkType(String S)
{
int AM=Integer.parseInt(S.substring(0,2));
int D=Integer.parseInt(S.substring(0,4)),d=0;
for(int i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
d++;
}
if((AM==34 || AM==37) && d==15)
System.out.println("AMEX");
else if(D==6011 && d==16)
System.out.println("Discover");
else if(AM>=51 && AM<=55 && d==16)
System.out.println("MasterCard");
else if(((S.charAt(0)-'0')==4)&&(d==13 || d==16))
System.out.println("Visa");
else
return "U";
return "";
}
private static void checkValid(String S) // S--> cardno
{
int i,d=0,sum=0,card[]=new int[S.length()];
for(i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
card[d++]=S.charAt(i)-'0';
}
for(i=0;i<d;i++)
{
if(i%2!=0)
{
card[i]=card[i]*2;
if(card[i]>9)
sum+=digSum(card[i]);
else
sum+=card[i];
}
else
sum+=card[i];
}
if(sum%10==0)
System.out.println("Valid");
else
System.out.println("Invalid");
}
public static int digSum(int n)
{
int sum=0;
while(n>0)
{
sum+=n%10;
n/=10;
}
return sum;
}
}
Here is the implementation of Luhn algorithm.
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "4071690065031703";
System.out.println(checkLuhn(cardNum));
}
}
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "8112189875";
System.out.println(checkLuhn(cardNum));
}
}
Hope it may works.
const options = {
method: 'GET',
headers: {Accept: 'application/json', 'X-Api-Key': '[APIkey]'}
};
fetch('https://api.epaytools.com/Tools/luhn?number=[CardNumber]&metaData=true', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

how to factor a number java

I need to factorize a number like 24 to 1,2,2,2,3. My method for that:
static int[] factorsOf (int val) {
int index = 0;
int []numArray = new int[index];
System.out.println("\nThe factors of " + val + " are:");
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
numArray1 [index] = i;
index++;
}
}
return numArray;
}
however, it is not working. Can anyone help me for that?
You have a few errors, you cannot create int array without size. I used array list instead.
static Integer[] factorsOf(int val) {
List<Integer> numArray = new ArrayList<Integer>();
System.out.println("\nThe factors of " + val + " are:");
for (int i = 2; i <= Math.ceil(Math.sqrt(val)); i++) {
if (val % i == 0) {
numArray.add(i);
val /= i;
System.out.print(i + ", ");
}
}
numArray.add(val);
System.out.print(val);
return numArray.toArray(new Integer[numArray.size()]);
}
Full program using int[] according to your request.
public class Test2 {
public static void main(String[] args) {
int val = 5;
int [] result = factorsOf(val);
System.out.println("\nThe factors of " + val + " are:");
for(int i = 0; i < result.length && result[i] != 0; i ++){
System.out.println(result[i] + " ");
}
}
static int[] factorsOf(int val) {
int limit = (int) Math.ceil(Math.sqrt(val));
int [] numArray = new int[limit];
int index = 0;
for (int i = 1; i <= limit; i++) {
if (val % i == 0) {
numArray[index++] = i;
val /= i;
}
}
numArray[index] = val;
return numArray;
}
}
public int[] primeFactors(int num)
{
ArrayList<Integer> factors = new ArrayList<Integer>();
factors.add(1);
for (int a = 2; num>1; )
if (num%a==0)
{
factors.add(a);
num/=a;
}
else
a++;
int[] out = new int[factors.size()];
for (int a = 0; a < out.length; a++)
out[a] = factors.get(a);
return out;
}
Are you looking a more faster way?:
static int[] getFactors(int value) {
int[] a = new int[31]; // 2^31
int i = 0, j;
int num = value;
while (num % 2 == 0) {
a[i++] = 2;
num /= 2;
}
j = 3;
while (j <= Math.sqrt(num) + 1) {
if (num % j == 0) {
a[i++] = j;
num /= j;
} else {
j += 2;
}
}
if (num > 1) {
a[i++] = num;
}
int[] b = Arrays.copyOf(a, i);
return b;
}
Most of the approaches suggested here have 0(n) time complexity. This can be easily resolved using binary search approach with 0(log n) time complexity.
What do you basically are looking for is called Prime Factors (although 1 is not considered among prime factors).
//finding any occurrence of the no by binary search
static int[] primeFactors(int number) {
List<Integer> al = new ArrayList<Integer>();
//since you wanted 1 in the res adn every no will be divided by 1;
al.add(1);
for(int i = 2; i< number; i++) {
while(number%i == 0) {
al.add(i);
number = number/i;
}
}
if(number >2)
al.add(number);
int[] res = new int[al.size()];
for(int i=0; i<al.size(); i++)
res[i] = al.get(i);
return res;
}
Say input is 24, we keep dividing the input by 2 till all multiples of 2 are gone, the increase i to 3
Here is a link to the working code: http://tpcg.io/AWH2TJ
A Working example
public class Main
{
public static void main(String[] args)
{
System.out.println(factorsOf(24));
}
static List<Integer> factorsOf (int val) {
List<Integer> factors = new ArrayList<Integer>();
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
factors.add(i);
}
}
return factors;
}
}
Rework an algorithm for working with big numbers using BigInteger class. Try this:
import java.math.BigInteger;
class NumbersFactorization {
public void printPrimeNumbers(String bigNumber) {
BigInteger number = new BigInteger(bigNumber);
for (BigInteger i = BigInteger.TWO; i.compareTo(number) <= 0; i = i.add(BigInteger.ONE)) {
while(number.remainder(i) == BigInteger.ZERO) {
System.out.print(i + " ");
number = number.divide(i);
}
}
if (number.compareTo(BigInteger.TWO) > 0) System.out.println(number);
}
}
You just missed one step in if. Following code would be correct:
System.out.println("\nThe factors of " + val + " are:");
You can take a square root of val for comparison and start iterator by value 2
if(val % i == 0)
{
numArray1 [index] = i;
val=val/i; //add this
index++;
}
but here you need to check if index is 2,it is prime.

Categories