I don't understand the solution of this exercise - java

I am doing an exercise on Practiceit.edu and I have some trouble. The exercise is writing of the following codes:
int total = 25;
for (int number = 1; number <= (total / 2); number++ ) {
total = total - number;
System.out.println(total + " " + number );
}
My output is
24 1
22 2
19 3
15 4
10 5
4 6
-3 7
-11 8
-20 9
-30 10
-41 11
-53 12
because i think that number starts at 1 and finish at 12 (number <= (total / 2)). However, the result is
24 1
22 2
19 3
15 4
10 5
I don't understand this result, so can you help me explain it?

The problem is that you are changing the value of total which will be re-evaluated every-time in your loop
try
int total = 25;
int total2 = total;
for (int number = 1; number <= (total / 2); number++ ) {
total2 = total2 - number;
System.out.println(total2 + " " + number );
}
output
24 1
22 2
19 3
15 4
10 5
4 6
-3 7
-11 8
-20 9
-30 10
-41 11
-53 12

The condition used in the for loop says the number is less than or equal to (half of) total
number <= (total / 2)
The last line where that is true is 10 5
Everything after that doesn’t satisfy the condition.

This is because your total is reducing more and more each time you iterate.
total = total - number;
I.e.:
//1st iteration
25 - 1 = 24; // outputs 24 1
// 2nd iteration
24 - 2 = 22 // outputs 22 2
// 3rd iteration
22 - 3 = 19 // outputs 19 3
// 4th iteration
19 - 4 = 15 // outputs 15 4
// 5th iteration
15 - 5 = 10 // outputs 10 5
Etc.
What are you trying to do?

During the final iteration that is printed, total is 10 and number is 5. Once the for loop continues, number increases by 1 and total decreases to 4. The comparison is made between total = 4 / 2 = 2 and number = 6. This result is not printed since the comparison is already made. Thus, you exit the for loop.

Related

How to find the minimum time taken to eat at least P apple ? Please Help me to optimize the code for this problem

Hi please help me with optimized solution for this question. I am also attaching a potential solution below. I need help to optimize the code in java. The question is given below .
Question :
Varun's team participated in an eating competition at FoodContest in
which they are asked to eat at least P apples. Varun's team consists
of N members where a member i (1 <= i <= N ) takes Arr[i] minutes to
eat a single apple. the task is to find the minimum time to eat
at least P apples.
Note: A member can eat a apple any number of times.
Example
Sample Input:-
n=4, p=10 ,
Arr[i] = {1 ,2 ,3 ,4}
Sample output: 6
Explanation:-
1st member will eat 6 apple , (ie, 1*6)
2nd member will eat 3 apple , (2*3)
3rd member will eat 2 apple , (3*2)
4th member will eat 1 apple , (4*1)
total = 12 ( total > p ) ie, team need atlest 6 min (minimum) to eat atleast 10 apples.
Sample Input:-
n=7 ,p=7 ,
Arr[i] = { 1 ,1 ,1 ,1, 1, 1 ,1 }
Sample Output: 1
Constraints:-
1 <= N <= 10^5
1 <= Arr[i] <= 10
1 <= P <= 10^12
Code: (note: I need help to optimize this code also reduce Time Complexity )
import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long p = Long.parseLong(str[1]);
long [] arr = new long [n];
long max = 1000000000000L ;
for(int i=0; i<n; i++)
{
arr[i] = Long.parseLong(input[i]);
}
for(long j=1;j<=max;j++){
long sum=0;
for(int i=0;i<n;i++){
long rem=j/arr[i];
sum=sum+rem;
if(sum>=p){
System.out.println(j);
return;
}
}
}
}
}
Say input is arr = {1, 2, 3, 4}, p = 60.
Start by calculating the least common denominator (LCD), which in this case is 12.
Now calculate, for each minute in a 12 minute period, how many apples will be eaten:
Time
0
1
2
3
4
5
6
7
8
9
10
11
12
Member 1
0
1
2
3
4
5
6
7
8
9
10
11
12
Member 2
0
0
1
1
2
2
3
3
4
4
5
5
6
Member 3
0
0
0
1
1
1
2
2
2
3
3
3
4
Member 4
0
0
0
0
1
1
1
1
2
2
2
2
3
Total
0
1
3
5
8
9
12
13
16
18
20
21
25
Create an array with the value from the last row, i.e. calculate this array:
int[] total = { 0, 1, 3, 5, 8, 9, 12, 13, 16, 18, 20, 21, 25 };
You don't need to store the intermediate per-member values. They are just shown above for clarity.
We now know that the team eats 25 apples per 12 minute period, so to eat a total of 60 apples, we need at least 2 full rounds. So we calculate:
full rounds = p / 25 = 60 / 25 = 2
apples left = p % 25 = 60 % 25 = 10
time taken = 2 * 12 = 24 minutes
apples eaten = 2 * 25 = 50
Now do a binary search of the calculated array for the remaining apples, choosing the next higher value if an exact match is not found. For the 10 apples remaining, that would be time = 6, total = 12.
Which means we need another 6 minutes to eat another 12 apples, for a total of 62 (50 + 12) apples eaten in 30 (24 + 6) minutes.
Result: 30 minutes.
Now good luck writing the code for this algorithm.

How can I create a java program which makes numbers align-right side?

My purpose is a java app that takes a number from a user. Start 1 and write it to console. Each new line series will increase 1 until the number token from the user. The important thing is to align each line to the right side.
Scanner in = new Scanner(System.in);
int numberOfLines = in.nextInt();
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
System.out.printf(" %d",col);
}
System.out.println();
}
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
when reaching double-digit numbers it is not right-aligned text. I tried to use the if condition in the loop but I could not do it.
Here's a different way to think about it using String concatenation.
You could generate the last row, first, to determine the maximum width that each row must be. Then for each row, you count backwards from the current row number down to 1 so you know the width of just the numbers part. Finally, you prepend the number of spaces needed to make the current row as wide as the last row. Note that is a horribly inefficient use of Strings, but really I'm demonstrating a different algorithm. Making this memory efficient would just make it harder to understand. Also note that the output being rendered correctly is dependent upon the environment in which you are running, and how it displays long strings. Some systems will add a scrollbar, while others may cause the strings to wrap.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Number of rows? ");
int numberOfLines = in.nextInt();
if (numberOfLines >= 1) {
int totalWidth = 0;
// add up the widths of the numbers themselves
for (int number = 1; number <= numberOfLines; number++) {
totalWidth = totalWidth + ("" + number).length();
}
// add in the spaces in-between the numbers
totalWidth = totalWidth + (numberOfLines - 1);
// now generate each row by counting backwards from the current row number
for (int rowNumber = 1; rowNumber<=numberOfLines; rowNumber++) {
String row = "";
for (int i=rowNumber; i>=2; i--) {
row = row + i + " ";
}
row = row + "1";
// prepend the spaces in front to make it as wide as the last row
int paddingLength = totalWidth - row.length();
for(int i=1; i<=paddingLength; i++) {
row = " " + row;
}
// output the row
System.out.println(row);
}
}
else {
System.out.println("Number of rows must be positive!");
}
}
Sample output with 25 rows:
Number of rows? 25
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Your code is doing the job just fine. The one problem you have, is that it stops working properly once you get to numbers that are more than 1 digit large: In your example, the 10 and the 11.
It's actually kind of tricky to fix that - what if I input '120392'?
You have a few options. Each option is more amazing, but also requires more code.
Restrict your input. For example, disallow inputs beyond 99, and assume all numbers have a # of digits equal to the largest allowing numbers (so, 2 digits).
Calculate the # of digits in the input, then assume all numbers have the calculated # of digits.
Just get it right, with the spacing being applied increasing as numbers grow digits.
If you choose the first or second option, you'd get something like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
Note how this has way more spaces than your example (2 spaces in between e.g. every 4 and 3 instead of 1.
So, how? For #1 and #2, you need System.out.printf("%2d"); - this means: print a number, but if it takes fewer than 2 characters to do so, left-pad with spaces.
For #1 you hardcode the '2' (and hardcode a 99 limit; alternatively, hardcode 3 spaces, and a 999 limit). For #2 you get your input and then figure out how many digits that is. Something like String.valueOf(limit).length(); will do that, then you construct the format string using this length.
For #3 you track which number you're not printing in your System.out.print(" "); loop, so that you can still figure out how long the blank space you need to make has to be: If you're not printing a 10, you need 3 spaces. If you're not printing a 500, you'd need 4. If you're not printing a 5, you need 2.
For #2 and #3: printf("%4s", ""); prints 4 spaces. This is what you'd use to ask java to print X number of spaces. You're going to need this for solutions #2 and #3.
This sounds like first-week homework. I think #1 is most appropriate.
In order to make the 2 digits right aligned ,one of the ways would be- after the for loop of 'col' convert each digit to String then reverse it then after that print it . If u don't convert it to String then numbers like 10,20,30,etc would be printed as 1,2,3,etc
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
if(col>9){
COL=Integer.toString(col);
for(int i=COL.length();i>=0;i--)
rev=rev+COL.charAt(i);
System.out.printf(" %d",rev);
}
else
System.out.printf("%d",col);
}
System.out.println();
}

For-loop output explanation needed?

I need an explanation of how the output prints 9(S), 7(S), 5(S) and 3(S).
10 > 3 is correct and goes to y 1 <= 2 which is correct so 2 x 10 - 2 = 18 but the output prints 9. I don't understand the logic here. Why does it print 9(s) instead of 18(s)?
public class Q2{
public static void main(String args[]) {
int x,y;
for(x= 10; x > 3; x = x - 2) {
for(y = 1; y <= 2 * x - 2; y = y + 2)
System.out.print("S");
System.out.print("\n");
}
}
}
Its correct Y <= 18 , but you are incrementing Y by 2, so it gets printed 9 times.
To understand, write down on a piece of paper what the values of your variables will be.
First, write down the values of x:
x: 10 8 6 4
Next, write down the calculated upper boundary value for y, i.e. the result of expression 2 * x - 2:
x : 10 8 6 4
yMax: 18 14 10 6
Last, write down the values of y:
x : 10 8 6 4
yMax: 18 14 10 6
y : 1 1 1 1
3 3 3 3
5 5 5 5
7 7 7
9 9 9
11 11
13 13
15
17
Finally, count the number of y values for each x value, i.e. the number of times S is printed:
x : 10 8 6 4
count: 9 7 5 3
Then realize that the code would have been much easier to understand if it had just been written like this:
for (int count = 9; count >= 3; count -= 2) {
for (int i = 0; i < count; i++) {
System.out.println("S");
}
}
Of course, that wouldn't have taught you what they were trying to teach you, which is:
Conclusion: If you don't understand what the code is doing, follow the logic step by step, and write down what it is doing.

Scanner and while loop addition

I just posted yesterday but I am back with another question, I know the answer to this problem but I'm stuck on how they got it.
import java.util.*;
public class test {
public static void main(String[] args) {
String s = "12 13 14 15 18 16 17 20 2";
Scanner c = new Scanner(s);
int sum = 0;
while(c.nextInt()% 2 == 0)
sum += c.nextInt();
System.out.println(sum);
}
}
The output is 44 but I keep getting 46 on my own. I may be doing it wrong since I am not too familiar on how c.nextInt() works.
I am thinking it goes:
12 % 2 = 0, so add 13
14 % 2 = 0, so add 15
18 % 2 = 0, so add 16
17 % 2 =/= 0, so skip
20 % 2 = 0, so add 2
for a total of = 46
am I missing something?
EDIT: Solved, forgot that loops don't just "skip". I'm dumb
Yes , here answer is 44. Here you are repeating while loop until ( number%2 == 0 ) became FALSE.
in your case :
you are adding 13 + 15 + 16 and the next number to check the while condition is 17
here ( 17%2 == 0 ) is FALSE so condition fails and is not entering into the loop .
here comes the total 44 ( 13 + 15 + 16 )
I hope this will help!
Here is a breakdown going through the loop each time:
c.nextInt() gets 12, 12 % 2 == 0, so this condition is TRUE
sum = 0 and c.nextInt() = 13 so sum += 13 equals 13
Second c.nextInt() gets 14, 14 % 2 == 0, so this condition is TRUE
sum = 13 and c.nextInt() = 15 so sum += 15 equals 28
c.nextInt() gets 18, 18 % 2 == 0, so this condition is TRUE
sum = 0 and c.nextInt() = 16, so sum += 16 equals 44
c.nextInt() gets 17, 17 % 2 == 1, so this condition is FALSE, the loop exits
Print 44
Java while loop is used to execute statement(s) until a condition holds true.If the condition holds false , this while loop will be break out.So
17 % 2 != 0, this while loop will be break out.So sum=44.

If statement inside for loops

for (int i = 0; i < 150; i++) {
if (i % 13 == 0) {
System.out.println("#: " + i);
}
}
I just started learning java yesterday and I'm stuck with for loops statement.
I'm confused about part
if (i % 13 == 0)
variable i is initialized to zero int i = 0 and if you divide zero by 13 the result is 0. There's no remainder. I tried on calculator.
But when I run the program. I get the result like this it keeps adding by 13 how?
#: 0
#: 13
#: 26
#: 39
#: 52
#: 65
#: 78
#: 91
#: 104
#: 117
#: 130
#: 143
What you're seeing is correct; it does appear to be adding 13 every time because your if statement is effectively saying, in plain english:
Display the value of i whenever 13 divides i evenly (leaving no remainder)
So indeed, each of the numbers you're seeing divides evenly, leaving no remainder:
#: 0 // 0 / 13 = 0, no remainder
#: 13 // 13 / 13 = 1, no remainder
#: 26 // 26 / 13 = 2, no remainder
and so on...
The results you are seeing are all of the numbers between 0 and 150 (which you specified on this line: for (int i = 0; i < 150; i++) {) that are multiples (have no remainder) of 13
The first loop adds 1 to the int i for each iteration. It will then check if there is a remainder when divided by 13:
(i % 13 == 0)
Finally, it will print that number if it doesn't have a remainder when divided by 13:
System.out.println("#: " + i);
So the result is essentially all the numbers that are multiples of 13 between 0 and 150.

Categories