I am trying to write a program that sums up the total of two large numbers. I used two arrays for the numbers to sum up and the third array to store the result of the summation, But I am getting the wrong output, would you check?
Here is my method:
public static int [] sumBigInt(int [] A, int [] B, int n)
{
int sumPerCol = 0;
int carriedValue = 0;
int[] totalArray = new int[A.length + 1];
for(int i = A.length - 1; i >= 0; i--)
{
sumPerCol = A[i] + B[i] + carriedValue;
if( i == 0)
totalArray[i] = carriedValue;
else if(sumPerCol >= 10)
{
carriedValue = sumPerCol / 10;
totalArray[i] = sumPerCol % 10;
}
else
{
totalArray[i] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
return totalArray;
}
**** In main, I am not getting the correct output:
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(TwoTo_n(8));
int[] arrayA = {6,9,4,6,9,1,8,9,3,5,6};
int[] arrayB = {5,9,6,4,3,1,6,7,6,9,5};
int[] arrayTest = new int[arrayA.length + 1];
for (int i = 0; i < arrayTest.length; i++)
arrayTest[i] = sumBigInt(arrayA, arrayB, 14)[i];
for (int i = 0; i < arrayTest.length; i++)
System.out.print(arrayTest[i] + " ");
}
Here is the output I get :
1 9 1 1 2 3 5 7 0 5 1 0
The output should be:
1 2 9 1 1 2 3 5 7 0 5 1 => now the digit in position 1 disappears :(
There is ONE digit missing; that digit should be added at position zero in my final array, but its not showing up.
Thank you
Your code is almost correct. In order to fix it, think what happens to carriedValue after you finish the loop:
When the loop ends, and carriedValue is zero, your program returns the correct value
When the loop ends, and carriedValue is one, the most significant digit of the result gets dropped.
All you need to do to fix this is to "shift" digit positions in your totalArray by one, and assign carriedValue to the top digit after the end of the loop:
for(int i = A.length - 1; i >= 0; i--) {
sumPerCol = A[i] + B[i] + carriedValue;
if(sumPerCol >= 10) {
carriedValue = sumPerCol / 10;
totalArray[i+1] = sumPerCol % 10;
} else {
totalArray[i+1] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
totalArray[0] = carriedValue;
Note the use of totalArray[i+1] in place of totalArray[i]. This is because your method automatically extends the number of significant digits by one. You could change this behavior by re-allocating the array and copying data into it only when carriedValue is non-zero.
Demo.
Related
I created simple decimal to binary method like this :
public static int[] convertDectoB(int number, int size) {
int binary[] = new int[size];
for (int a = number; a > 0 && size > 0; size--, a = a / 2) {
binary[size - 1] = a % 2;
}
return binary;
}
I asked user to enter numbers like that :
"Enter numbers : "
4-2-7.
The aim is convert these 3 numbers into a binary and print it :
1 0 0
0 1 0
1 1 1
I also created numberFinder method to extract integers into the String that user entered :
public static int[] numberFinder(String numbers, int size) {
int numaraa[] = new int[size];
int a = 0;
for (int i = 0; i < numaraa.length; i++) {
for (; a < numbers.length(); a++) {
if (numbers.charAt(i) == '-')
i++;
else if (a == 0) {
if (Character.isDigit(numbers.charAt(a)))
numaraa[i] += numbers.charAt(a);
}
else {
if (Character.isDigit(numbers.charAt(a)))
numaraa[i] += numbers.charAt(a);
}
}
}
return numaraa;
}
In the end , I created 2D array and I wanna implement these binary values :
for (int i = 0; i < mainarray.length; i++) {
for (int j = 0; j < mainarray[i].length; j++) {
mainarray[i][j] = ?
}
}
}
But I can't implement all binary values for each array block.
If you need to make your own toBinaryString() method there are a lot of examples online, such as borrowing the logic from this answer Print an integer in binary format in Java:
public static String intToString(int number) {
StringBuilder result = new StringBuilder();
for(int i = 2; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
}
return result.toString();
}
Note: I modified this method to only hold 3 digit binary codes, so the highest integer it can convert is 7. However if you want to convert larger integers, say up to 16, or 32, you'll need to increase the counter in the for-loop, which I'll leave that for you to decide.
For each line in the user input, split it on the hyphen character '-':
codes = line.split("-");
ListofCourses.addAll(Arrays.asList(codes));
...
Then call this method on your ListofCourses:
for(int r = 0; r < ListofCourses.size(); r++){
System.out.println(intToString(Integer.parseInt(ListofCourses.get(r))));
}
ListofCourses.clear();
Then should get expected output. Here's demo:
Ron's Copy
Enter 3 collections of course codes one collection per line
4-2-7
Size: 3 Sorted: [4, 2, 7]
100
010
111
I am having trouble trying to figure this out. I need to create an application that displays the index numbers 0-101, and also stores the sum of each individual index numbers digits. for example:
INDEX---------GENERATED NUMBER
0--------------------0
1--------------------2
2--------------------4
3--------------------6
And so on. Index 17 would store 25, because 17 + 1 + 7 = 25.
I've got the list of index numbers down pact..
public class ArrayPractice {
public static void main(String[] args)
{
int sum = 0;
int[] arrayNumber = new int[102];
for(int i = 0; i < arrayNumber.length; i++){
arrayNumber[i] = i;
int add = i % 10;
sum += add;
i /= 10;
System.out.println(i);
}
}
}
I also understand that to get the sum of the digits, you have to modulus 10 and then divide by 10, 17 % 10 = 7, 17 / 10 = 1 7 + 1 = 8 + 17(index) = 25.
I just keep failing to get this to work within a loop. Any help would be greatly appreciated.
Will also explain, since you have 3 digit numbers it's not enough to divide by 10 once. You have to do it until it's bigger than 0, so for 100, you get 0, 0, 1. Which is why a while loop is best, since you don't know when it will end. This works for any integer.
Just remember, for loops are meant to be used when you know when your loop has to end.
While loop is used when you don't know when you will end, well you know when but not when it will happen.
EDIT: Just saw you have to add the index itself, 17 = 1 + 7 + 17. Fixed that.
int current;
int[] array = new int[102];
int sum;
for(int i = 0; i < array.length; i++){
current = i;
sum = 0;
while(current != 0){
sum += current % 10;
current = current/10;
}
array[i] = sum+i;
}
for(int i = 0; i < array.length; i++){
System.out.println("Index " + i + " :" + array[i]);
}
The problem with your code is it just sums up the last digit of the number, it won't work for numbers having digits greater than 2, you have to loop through all the digits and keep adding them to the number.
for(int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = i;
int tmp = arrayNumber[i];
// summing up digits
while(tmp > 0) {
arrayNumber[i] += tmp%10; //extracting right-most digit
tmp /= 10; // removing the right-most digit
}
System.out.println(i , arrayNumber[i]);
}
I think you're pretty close, but you'll most likely want to use another variable (other than i your iterator) to modify -- otherwise your iterator will continuously get messed with. You'll also want to continue doing the mod/divide operation until your initial number is 0 (i.e. you've processed all the digits). You'll also want to reset your sum for each pass through the for loop.
Here's my example code:
int[] arrayNumber = new int[102];
for (int i = 0; i < arrayNumber.length; i++) {
int sum = i;
int startingNumber = i;
while (startingNumber > 0) {
sum += startingNumber%10;
startingNumber /= 10;
}
arrayNumber[i] = sum;
System.out.println(i + " " + sum);
}
I apologize for my english. So far I got this code that sort an array. The user input 10 numbers and after that, the program makes the sorting. But what I want is that every time the user inputs a number, the program immediately makes the sort. How can I do that?
For example, if I input 5 and then 3, immediately takes the 3 to the first position. And then if I put 2, immediately take it to the first position and sort the others (2,3,5). Then if I put 1, takes it to the first position, sorting the others(1,2,3,5) and so on.
import java.util.Scanner;
public class Nine{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for(int i = 0; i < 10; i++){
System.out.print("Número: ");
num[i] = input.nextInt();
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
System.out.println();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10 - i - 1; j++){
if(num[j+1] < num[j]){
temp = num[j+1];
num[j+1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
}
}
Now I have this code and it works. It does what I wanted to do. But to me it's a little bit complicated. I'm still a beginner. I understand what it does but is there a better way to do it. An easier way? Thanks
import java.util.Scanner;
public class practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int n = 0, l = 0, t = 0;
for(int i = 0; i < num.length; i++){
System.out.print("Número: ");
n = input.nextInt();
l = 0;
while(num[l] < n && l < i){
l = l + 1;
}
t = i;
while(t > l){
num[t] = num[t - 1];
t = t - 1;
}
num[l] = n;
for(int temp : num){
System.out.print(temp + " ");
}
System.out.println();
}
}
}
here you go
public class TestProgram {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for (int b = 0; b < 10; b++) {
System.out.println("Número: ");
num[b] = input.nextInt();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i - 1; j++) {
if (num[j + 1] < num[j]) {
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for (int k = 0; k < 10; k++) {
System.out.println(num[k] + " ");
}
}
}
}
To do this create a sort method which you can call to sort an array then return a new sorted array. Next every time a user inputs run a for loop which will create an array with the current amount entered. While entering just use i+1. Finally, with the new array call the sort method and the sorted array will be returned and you can do as you wish with the new array.
You make things more difficult for yourself using an array but assuming you want to start with an array of size 10 filled with 0s (so 0 is not a valid input) the basic algorithm is to go through the currently sorted array and if the current value is less than the indexed value move all the values in the sorted array to the right and insert the current value at the current index. As others have already mentioned for larger datasets this is very inefficient but for an array of size 10 it's not a big deal.
int current = input.nextInt();
for (int j = 0; j < sorted.length; j++) {
if (sorted[j] == 0) {
sorted[j] = current;
break;
}
if (current < sorted[j]) {
for (int k = sorted.length - 1; k > j; k--) {
sorted[k] = sorted[k - 1];
}
sorted[j] = current;
break;
}
}
Here's what the output at each iteration would look like for the input 5, 3, 2, 1, 4, 10, 20, 15, 13, 5:
5 0 0 0 0 0 0 0 0 0
3 5 0 0 0 0 0 0 0 0
2 3 5 0 0 0 0 0 0 0
1 2 3 5 0 0 0 0 0 0
1 2 3 4 5 0 0 0 0 0
1 2 3 4 5 10 0 0 0 0
1 2 3 4 5 10 20 0 0 0
1 2 3 4 5 10 15 20 0 0
1 2 3 4 5 10 13 15 20 0
1 2 3 4 5 5 10 13 15 20
I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]
I am trying to write a program that generates all the subsets of an entered set in java. I think i nearly have it working.
I have to use arrays (not data structures)
The entered array will never be greater than 20
Right now when i run my code this is what i get:
Please enter the size of A: 3
Please enter A: 1 2 3
Please enter the number N: 3
Subsets:
{ }
{ 1 }
{ 1 2 }
{ 1 2 3 }
{ 2 3 }
{ 2 3 }
{ 2 }
{ 1 2 }
this is the correct number of subsets (2^size) but as you can see it prints a few duplicates and not some of the subsets.
Any ideas where I am going wrong in my code?
import java.util.Scanner;
public class subSetGenerator
{
// Fill an array with 0's and 1's
public static int [] fillArray(int [] set, int size)
{
int[] answer;
answer = new int[20];
// Initialize all elements to 1
for (int i = 0; i < answer.length; i++)
answer[i] = 1;
for (int a = 0; a < set.length; a++)
if (set[a] > 0)
answer[a] = 0;
return answer;
} // end fill array
// Generate a mask
public static void maskMaker(int [] binarySet, int [] set, int n, int size)
{
int carry;
int count = 0;
boolean done = false;
if (binarySet[0] == 0)
carry = 0;
else
carry = 1;
int answer = (int) Math.pow(2, size);
for (int i = 0; i < answer - 1; i++)
{
if (count == answer - 1)
{
done = true;
break;
}
if (i == size)
i = 0;
if (binarySet[i] == 1 && carry == 1)
{
binarySet[i] = 0;
carry = 0;
count++;
} // end if
else
{
binarySet[i] = 1;
carry = 1;
count++;
//break;
} // end else
//print the set
System.out.print("{ ");
for (int k = 0; k < size; k++)
if (binarySet[k] == 1)
System.out.print(set[k] + " ");
System.out.println("}");
} // end for
} // maskMaker
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
int[] set;
set = new int[20];
int size = 0;
int n = 0;
// take input for A and B set
System.out.print("Please enter the size of A: ");
size = scan.nextInt();
if (size > 0)
{
System.out.print("Please enter A: ");
for (int i = 0; i < size; i++)
set[i] = scan.nextInt();
} // end if
System.out.print("Please enter the number N: ");
n = scan.nextInt();
//System.out.println("Subsets with sum " + n + ": ");
System.out.println("Subsets: ");
System.out.println("{ }");
maskMaker(fillArray(set, size), set, n, size);
} // end main
} // end class
The value of i always goes from 0 to N-1 and then back to 0. This is not useful to generate every binary mask you need only one time. If you think about it, you need to move i only when you have generate all possible masks up to i-1.
There is a much easier way to do this if you remember every number is already internally represented in binary in the computer and everytime you increment it Java is doing the adding and carrying by itself. Look for bitwise operators.