I need to write a method that adds the two last elements of two arrays together and add the sum on another array. But if the two elements are more than 10, then I would need to carry that number to the next array.
This program should be similar to what an odometer does.
Here is my sample code.
int [] sum(int []number1, int []number2)
{
int [] total;
int carry = 0;
for ( int k = numbers1 - 1; k >= 0; k++)
{
sum = number1[k] + number2[k] + carry;
carry = sum/10;
total[k] = sum
}
return total;
}
An example output would be:
0 1 2 3 4
0 8 9 9 9
4 5 7 0 3
5 4 7 0 2
So the top array is just a visual aid that tells where the position for the number is.
The program is suppose to add the next two arrays together. i.e. 9 + 3 = 12
Since 12 is above 9, it carries over the 10 to the next set of arrays, that is why the third array only has a 2 in its place, and that is why the next array is 9 + 0 = 0; because the 10 was carried over.
I am not sure why my code won't work. I don't get the right numbers. Could anyone give any hints or solution to the problem?
-Thanks
I assume numbers1 is the number of elements in the array.
In this case it should be k-- instead of k++ because you are starting from the last element and moving backword.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So, I have an array of 7 numbers, 0-6. I want to loop through it for a certain amount of times and stop at a certain index or number. For instance, the program starts at 0 and I want to loop it 12 times and have the program output 4. Another instance, the program starts at index 2 and loops 10 times. The output should be index 5. How do I do this and is it possible?
You could use a simple loop that controls how you cycle through the array.
Example:
int arr[]; // Our array
int t; // How much to cycle through the array
/**
* Some code to set a value for t and fill arr
**/
int index = 0; // The final index. Initally 0 to prevent undefined case t <= 0
for (int i = 0; i < t; ++i) {
if (index == arr.lenght) {index = -1;} // -1 so whe don't need to have an else clause
++index;
}
If you want to start in a position different than 0 in the array just create some code to set index before the loop and remember to check if index is less than the array lenght
I think you are looking for the modulo % operator. This allows you to skip the loop and immediately land on the final index entry. This operation is constant and should be preferred if you dont have to actually cycle through the indeces until you land on the final number.
For you two examples you can see two print statements for each case:
class Main {
public static void main(String[] args) {
int arr[] = {0,1,2,3,4,5,6};
int n = arr.length;
int t = 12;
//case 1
System.out.println(arr[t%n]);
//case 2
int index = 2;
t = 10;
System.out.println((t + index)%n);
}
}
"If the program (iterations) starts at 0 (index) and I want to
loop it 12 times and have the program output 4".
Okay, I get that. You start your count as literal 1 from index 0:
1 2 3 4 5 6 7 8 9 10 11 12 (on the 12th iteration starting from Index 0)
-------------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (element value at index)
-------------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (array index)
"Another instance, the program starts at index 2 and loops 10
times. The output should be index 5".
This one confuses me:
1 2 3 4 5 6 7 8 9 10 (on the 10th iteration starting from Index 2)
-----------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (element value at index)
-----------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (array index)
The output should be index 4 as well, not index 5.
Anyway, here's another way this can be accomplished:
int startIndex = 0; // The INDEX value to start iterations from.
int loopNumOfTimes = 12; // The literal number of desired iterations.
int[] array = {0, 1, 2, 3, 4, 5, 6}; // The Integer Array (length 7).
int counter = 0; // A counter used to count literal iterations.
int i; // Decalred outside of loop so its value can be used.
// Iterate through the Array
for (i = startIndex; i < array.length; i++) {
counter++; // Increment counter.
// Have we reached the desire number of iterations?
if (counter == loopNumOfTimes) {
// Yes...Break out of loop.
break;
}
/* Reset the 'for' loop if we've reached actual array length (length minus 1).
i++ in the 'for' loop is automatically applied once the first iteration is
complete and every iteration thereafter as long as 'i' remains less than
the literal length of the array. Because we are applying a value change to
'i' so as to start the loop form 0 again (a loop reset) the i++ will be
immediately be applied which takes 'i' to 1 istead of the desired 0. This
is no good so we set 'i' to -1 that way when i++ is applied 'i' is set to
0 and iterations start again from that index value. */
if (i == (array.length - 1)) {
i = -1;
}
}
// Display the Array element value located at index 'i'.
System.out.println(array[i]);
In the above code you can see that the Start Index (startIndex) is 0 and the Desired Number Of Loops (iterations) held in the loopNumOfTimes variable is 12. The output to console window will be: 4.
If you change the startIndex value to 2 and the loopNumOfTimes value to 10 then the console window output will be: 4.
The task is to find lost element in the array. I understand the logic of the solution but I don't understand how does this formula works?
Here is the solution
int[] array = new int[]{4,1,2,3,5,8,6};
int size = array.length;
int result = (size + 1) * (size + 2)/2;
for (int i : array){
result -= i;
}
But why we add 1 to total size and multiply it to total size + 2 /2 ?? In all resources, people just use that formula but nobody explains how that formula works
The sum of the digits 1 thru n is equal to ((n)(n+1))/2.
e.g. for 1,2,3,4,5 5*6/2 = 15.
But this is just a quick way to add up the numbers from 1 to n. Here is what is really going on.
The series computes the sum of 1 to n assuming they all were present. But by subtracting each number from that sum, the remainder is the missing number.
The formula for an arithmetic series of integers from k to n where adjacent elements differ by 1 is.
S[k,n] = (n-k+1)(n+k)/2
Example: k = 5, n = 10
S[k,n] = 5 6 7 8 9 10
S[k,n] = 10 9 8 7 6 5
S[k,n] = (10-5+1)*(10+5)/2
2S[k,n] = 6 * 15 / 2
S[k,n] = 90 / 2 = 45
For any single number missing from the sequence, by subtracting the others from the sum of 45, the remainder will be the missing number.
Let's say you currently have n elements in your array. You know that one element is missing, which means that the actual size of your array should be n + 1.
Now, you just need to calculate the sum 1 + 2 + ... + n + (n+1).
A handy formula for computing the sum of all integers from 1 up to k is given by k(k+1)/2.
By just replacing k with n+1, you get the formula (n+1)(n+2)/2.
It's simple mathematics.
Sum of first n natural numbers = n*(n+1)/2.
Number of elements in array = size of array.
So, in this case n = size + 1
So, after finding the sum, we are subtracting all the numbers from array individually and we are left with the missing number.
Broken sequence vs full sequence
But why we add 1 to total size and multiply it to total size + 2 /2 ?
The amount of numbers stored in your array is one less than the maximal number, as the sequence is missing one element.
Check your example:
4, 1, 2, 3, 5, 8, 6
The sequence is supposed to go from 1 to 8, but the amount of elements (size) is 7, not 8. Because the 7 is missing from the sequence.
Another example:
1, 2, 3, 5, 6, 7
This sequence is missing the 4. The full sequence would have a length of 7 but the above array would have a length of 6 only, one less.
You have to account for that and counter it.
Sum formula
Knowing that, the sum of all natural numbers from 1 up to n, so 1 + 2 + 3 + ... + n can also be directly computed by
n * (n + 1) / 2
See the very first paragraph in Wikipedia#Summation.
But n is supposed to be 8 (length of the full sequence) in your example, not 7 (broken sequence). So you have to add 1 to all the n in the formula, receiving
(n + 1) * (n + 2) / 2
I guess this would be similar to Missing Number of LeetCode (268):
Java
class Solution {
public static int missingNumber(int[] nums) {
int missing = nums.length;
for (int index = 0; index < nums.length; index++)
missing += index - nums[index];
return missing;
}
}
C++ using Bit Manipulation
class Solution {
public:
int missingNumber(vector<int> &nums) {
int missing = nums.size();
int index = 0;
for (int num : nums) {
missing = missing ^ num ^ index;
index++;
}
return missing;
}
};
Python I
class Solution:
def missingNumber(self, nums):
return (len(nums) * (-~len(nums))) // 2 - sum(nums)
Python II
class Solution:
def missingNumber(self, nums):
return (len(nums) * ((-~len(nums))) >> 1) - sum(nums)
Reference to how it works:
The methods have been explained in the following links:
Missing Number Discussion
Missing Number Solution
This is the problem to be solved:
John is assigned a new task today. He is given an array A containing N integers. His task is to update all elements of array to some minimum value x , that is, A[i] = x; 1 <= i <= N; such that sum of this new array is strictly greater than the sum of the initial array.
Note that x should be as minimum as possible such that the sum of the new array is greater than the sum of the initial array.
Input Format:
First line of input consists of an integer N denoting the number of elements in the array A.
Second line consists of N space separated integers denoting the array elements.
Output Format:
The only line of output consists of the value of x.
Sample Input:
5
12345
Sample Output:
4
Explanation:
Initial sum of array= 1 + 2 + 3 + 4 + 5 = 15
When we update all elements to 4, sum of array = 4 + 4 + 4 + 4 + 4 = 20 which is greater than 15.
Note that if we had updated the array elements to 3, sum = 15 which is not greater than 15. So, 4 is the minimum value to which array elements need to be updated.
** ==> Here is my code. How can I improve it? or What is the problem in this code? **
import java.util.Scanner;
public class Test2 {
public static void main(String []args){
Scanner s=new Scanner(System.in);
int check=0, sum=0, biggest=0;
int size=s.nextInt();
if(size>=1 && size<=100000) {
int[] arr=new int[size];
for(int i=0; i<size; i++){
int temp=s.nextInt();
if(temp>=1 && temp<=1000) {
arr[i] = temp;
biggest=biggest > temp ? biggest:temp;
sum=sum+temp;
}
else break;
}
for(int i=1; i<biggest; i++){
check=(size*i)>sum ? i:0;
}
System.out.print(check);
}
else System.err.print("Invalid input size");
}
}
Issue:
for(int i=1; i<biggest; i++){
check=(size*i)>sum ? i:0;
}
There are 2 problems with this, hence it doesn't work. They are as follows-
(size*i)>sum ? i - The problem statement states that it needs minimum possible sum greater than sum of array of elements. Your code blindly assigns i to check without checking the minimality.
check=(size*i)>sum ? i:0 - So, even if you had come across some integer previously, you lost it because you assigned it to 0 if the condition is not satisfied.
I will share my idea of how would I go about this.
Approach 1
Sum all elements like you did.
Now, take average of elements - sum / size of the array. Let's say we store it in a variable average.
Print average + 1 as your answer, as that is the value that could give you minimum possible sum > sum of array itself.
Time Complexity: O(n), where n is size of the array.
Space Complexity: O(1)
Approach 2
Sum all elements like you did.
Calculate min and max for the array and store it in variables, say mini and maxi.
Now, do a binary search between mini and maxi and keep checking the minimum sum > sum criteria.
In this process, you will have variables like low, mid and high.
low = mini,high = maxi
while low <= high:
mid = low + (high - low) / 2
If mid * size <= sum,
low = mid + 1
else
high = mid - 1
Now, print low as your answer.
Let range = maxi - mini.
Time Complexity: O(n) + O(log(range)) = O(n) asymptotically, where n is size of the array.
Space Complexity: O(1)
Not sure if I completely followed what your attempt was, but there should be a pretty straightfoward solution. You know the size of the array and you can easily iterate through the array to get the value of the elements stored in it. All you need to do to find your min x is to take sumOfArray/size of array and then add one to the result to make your result higher.
In your example 15/5=3. 3+1 = 4 so that's your answer. If the numbers summed to 43, 43/5 = 8 r 3, so your answer is 9 (9*5=45). Etc.
When trying some other test cases, then the results are wrong. Try:
Input:
5
1 1 1 1 5
Expected Output: 2 Actual Output: 4
and
Input:
5
5 5 5 5 5
Expected Output: 6 Actual Output: 0
I can't understand the logic behind getMedian method. How exactly median is evaluated, what is the connection between count of elements and sum of elements? Appreciate if someone could explain it's logic.
public static void main(String[] args) {
Random r = new Random();
int[] ar = r.ints(0, 100).limit(9).toArray();
int k = ar.length;
int[] count = getCounts(ar);
double median = getMedian(count, k);
System.out.println(median);
}
private static int[] getCounts(int[] ar) {
int[] count = new int[100];
for (int i = 0; i < ar.length; i++) {
count[ar[i]]++;
}
return count;
}
private static double getMedian(int[] count, int d) {
int sum = 0;
for (int i = 0; i < count.length; i++) {
sum += count[i];
if (2 * sum < d)
continue;
else if (2 * sum == d)
return (2 * i + 1) / 2.0;
else
return i * 1.0;
}
return -1.0;
}
There is a relation because it is a frequency table. You are thinking it differently but let me give you an example.
1 1 1 3 3 4 4 4 5 5 5 5 if this is the array then the frequency table would be :-
1 3 4 5
- - - -
3 2 3 4
So this is median.
So now I am adding every element count and asking us the question, where does the median lie? or where is that indexm which if I consider I will cover the middle element?
Now here I am checking if sum > d/2 then it's done. We found the median.else if it is less then I still have to traverse other elements to get to the middle of the array. And if it is sum==d/2 then we have found it but we have to send the correct position. And we simply send the one in the lower middle (happens in case like 1,1,1,1).
Walk through
1 1 1 3 3 4 4 4 5 5 5 5
Now I check if I traverse all set of 1's where I am? I covered 3 elements. But it's not the half of the total numbers(6).
Now add number of 3's. 5. This is also not.
Now I add number of 4's, So 8 elements I covered. So I covered more than half of number of elements. So median lies here.
More detailed explanation:
You are asked to find the median of an array of 10 integers.
[1 2 3 4 5 6 7 8 9]
Then median is in element at position floor(9/2)=4, which is 5 Right?
[1 1 2 2 3 3 4 4 5]
Where is the median element at position floor(9/2)=4, which is 3. Right?
So now think this,
1 2 3 4 5
2 2 2 2 1
Now you will try to find the floor(9/2) th element here starting from beginning. And that's why you need to find the sum of the frequencies and all.
Hope you get it?
Correct algorithm
What you need to do is :-
N = number of elements.
F[] = frequency array
so if N is odd
find the element at floor(N/2)-th place and median is that element.
else
find the element at floor((N-1)/2) and floor(N/2) th position and return their average.
Finding the element is simple:
Find( F[], p) // find the element at position p
{
p=p+1
for i in [0..|F|]
cumulative+=F[i]
if cumulative == p
return this element.
else cumulative >p
return this element
}
Full Disclosure: Homework.
Explanation: I cant understand my teacher.
Problem:
Write a method called printSquare that takes in two integer
parameters, a min and a max, and prints the numbers in the range from
min to max inclusive in a square pattern. The square pattern is
easier to understand by example than by explanation, so take a look at
the sample method calls and their resulting console output in the
table below. Each line of the square consists of a circular sequence
of increasing integers between min and max. Each line prints a
different permutation of this sequence. The first line begins with
min, the second line begins with min + 1, and so on. When the
sequence in any line reaches max, it wraps around back to min. You
may assume the caller of the method will pass a min and a max
parameter such that min is less than or equal to max
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
This is what I have so far, apologies but I have trouble with for loops.
for(int i = 0; i < row; i++)
{
for(int d = 0; d < row; d++)
{
System.out.print(d+1);
}
System.out.println(i);
}
I know I used row twice, but its the only way i can get the compiler to form a square shape with the loop. Does anyone even remotely understand what i'm trying to do? :/
This is actually a nice mathematical problem. Assume:
int side = to - from + 1; /// the size/width of the square.
the value at any point in the square (row, col) is:
from + ((row + col) % side)
you should be able to put that in your loops and "smoke it".
Edit based on comment asking for explanation.
The trick is to loop through all the positions in the 'matrix'. Given that the matrix is square, the loops are relatively simple, just two loops (nested) that traverse the system:
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
... magic goes here....
}
}
Now, in this loop, we have the variables row and col which represent the cell in the matrix we are interested in. The value in that cell needs to be proportional to the distance it is from the origin..... let me explain.... If the origin is the top left (which it is), then the distances from the origin are:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
The distance is the sum of the row and the column...... (rows and columns start counting from 0).
The values we put in each matrix are limited to a fixed range. For the above example, with a square of size 5, it could have been specified as printSquare(1,5).
The value in each cell is the from value (1 in this example) plus the distance from the origin... naively, this would look like:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
here the values in the cell have exceeded the limit of 5, and we need to wrap them around... so, the trick is to 'wrap' the distances from the origin..... and the 'modulo' operator is great for that. First, consider the original 'origin distance' matrix:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
if we instead populate this matrix with 'the remainder of the distance when dividing by 5' (the modulo 5, or %5) we get the matrix:
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
Now, if we add this 'modulo' result to the from value (1), we get our final matrix:
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
in a sense, all you need to know is that the value at each cell is:
the from value plus the remainder when you divide the 'distance' by the width.
Here's the code I tested with:
public static final String buildSquare(final int from, final int to) {
final StringBuilder sb = new StringBuilder(side * side);
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
sb.append( from + ((row + col) % side) );
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(buildSquare(1, 5));
System.out.println(buildSquare(3, 9));
System.out.println(buildSquare(5, 5));
System.out.println(buildSquare(0, 9));
System.out.println(buildSquare(0, 3));
}
Since this is homework, I'll just give a hint.
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
Here's one way to do it.
Create the first number twice in an array. Taking the printSquare(1, 5) example, create an int array of 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.
Use a loop to loop through the array, starting with element zero and ending with element 4, and another loop to display 5 digits (max - min + 1).
try this
int i,j,k;
for(i=min;i<=max;i++) {
for(j=i;j<=max;j++) {
System.out.print(j);
}
for(k=min;k<i;k++){
System.out.print(k);
}
System.out.println();
}
you can try
loop from min value to max value and put all the numbers in an array
now loop again from min value to max value
each time print the array and do a circular shift (for circular shift you can find lot of example in SO)
I think #rolfl's solution is the cleanest. I'd recommend going with that.
You can find another simple solution by observing that each output in your "square" simply shifts the first element to the end the list of numbers. To imitate this, you can put all the numbers from min to max in a data structure like LinkedList or ArrayDeque where you can easily add/remove items from both ends, then you'd print the contents in order, and shift the first entry to the end. E.g., coll.addLast(coll.removeFirst()). If you repeat that process max - min + 1 times, you should get the desired output.
no array no problem you can easily solve.
it work with any range of number.
static void printSquare(int min, int max){
int len = max - min + 1;
int copy_min = min, permanent_min = min;
for(int i = 0; i < len; i++){
for(int j = 0; j< len; j++){
if(min > max)
if(min % len < permanent_min)
System.out.print((min % len )+ len);
else
System.out.print(min % len);
else
System.out.print(min);
min++;
}
min = ++copy_min;
System.out.println();
}
}
public static void printSquare(int min, int max) {
for (int i = min; i <= (max -min)+min; i++) {
for( int j =i; j <= max ; j++) {
System.out.print(j);
}
for (int j1= min; j1<= i * 1 - 1; j1++) {
System.out.print(j1);
}
System.out.println();
}
}