Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

package quizz;

import java.util.ArrayList;

public class Main {

public int[] sum(int[] op1, int[] op2) {

int[] bigger = op1.length <= op2.length ? op2 : op1;


int[] smaller = op1.length > op2.length ? op2 : op1;
int[] result = new int[bigger.length];
int offset = Math.abs(smaller.length - bigger.length);

int addUp = 0;
int sum = 0;

//add up the ends of the array


for (int i = smaller.length-1; i >= 0 ; i--) {
if(addUp != 0){
sum += 1;
addUp = 0;
}
sum += smaller[i] + bigger[i+offset];
if(sum / 10 >= 1){
addUp = 1;
sum %= 10;
}
result[i+offset] = (sum);
sum = 0;
print(result);
}

//Copy the rest of array an calculate stuff


for (int i = bigger.length - smaller.length - offset; i >=0 ; i--) {
result[i] = bigger[i] ;
System.out.println(bigger[i]);
if(addUp != 0){
result[i] += 1;
addUp = 0;
}

// if(result[i] / 10 >= 1){


// addUp = 1;
// result[i] %= 10;
// }
print(result);

}
// int finalNumber = bigger[0];

// result[0] = (finalNumber);
return result;
}

// public static void main(String[] args) {


// System.out.println("Checking input...");
//
// int[] op1 = {2,2, 1, 7, 8};
// int[] op2 = {5, 9, 6};
//
// Main bn = new Main();
// int[] rez = bn.sum(op1, op2);
// int[] correct = {2, 7, 7, 4};
// System.out.println(noToString(op1) + " + " + noToString(op2) +
// " = " + noToString(rez) + " C: " + noToString(correct));
// }

private static String noToString(int[] no) {


StringBuilder sb = new StringBuilder();
for(int i = 0; i < no.length; i++) {
sb.append(no[i]);
}
return sb.toString();
}

private void print(int[] no) {


for(int i = 0; i < no.length; i++) {
System.out.print(no[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


int noTests = 6;

int[][] op1 = {{0}, {9, 9}, {9}, {2, 1, 7, 8},


{5, 0, 5, 0, 5}, {1, 0, 8, 6, 7, 8, 9, 4, 2, 3, 4}};
int[][] op2 = {{1, 0, 1}, {1}, {9, 9, 9, 9}, {5, 9, 6},
{5, 5, 0, 5, 0}, {3, 4, 2, 8, 9, 7, 9, 2, 3, 4, 9}};
int[][] correct = {{1, 0, 1}, {1, 0, 0}, {1, 0, 0, 0, 8}, {2, 7, 7, 4},
{1, 0, 5, 5, 5, 5}, {4, 5, 1, 5, 7, 6, 8, 6, 5, 8, 3}};

int total = 0;
for (int i = 0; i < noTests; i++) {
System.out.println("Test " + (i+1) + ":");
String op1S = noToString(op1[i]);
String op2S = noToString(op2[i]);

Main bn = new Main();


int[] rez = bn.sum(op1[i], op2[i]);

String rezS = noToString(rez);


String correctS = noToString(correct[i]);
System.out.println(op1S + " + " + op2S + " = " + rezS + " C: " +
correctS +
"......" + (rezS.equals(correctS) ? "OK" : "WRONG"));
System.out.println();

total += rezS.equals(correctS) ? 1 : 0;
}

System.out.println("Your total score is: " + total + " / " + noTests);


System.out.println(total > 3 ? "You passed! Hurray! :)" : "Sorry.. :(");
}

You might also like