Nested for loop output not correct - java

for(int c = 1; c <= rows; c++) {
for(int i = 0; i < c; i++) {
System.out.print(++number + " ");
}
}
let us assume that rows = 5 and number = 0 initially. what will be the output?
to me, if rows were 5, the output would be as follows:
1
2
3
4
5
however my teacher has it as: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
and i can't seem to wrap my head around it! can anyone explain why ? i have tried with different numbers as well, for 2, i would get just the number 1,2 but my professor gets 1,2,3

You have two nested loops.
The outer loop iterates from 1 to 5.
The inner loop iterates from 0 to c - 1.
When c == 1, the inner loop iterates from 0 to 0 so number is incremented 1 time.
When c == 2, the inner loop iterates from 0 to 1 so number is incremented 2 times.
When c == 3, the inner loop iterates from 0 to 2 so number is incremented 3 times.
When c == 4, the inner loop iterates from 0 to 3 so number is incremented 4 times.
When c == 5, the inner loop iterates from 0 to 4 so number is incremented 5 times.
In total, number is incremented 1 + 2 + 3 + 4 + 5 == 15 times.
Each time number is incremented, it is also printed, followed by a space. So the loops produce the output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15.

For every row with the inner loop execute System.out.print(++number + " "); this statement total 15(1 + 2 + 3 + 4 + 5) times and every time number value is implemented and print.
Take a look visualization here

The best way to understand this type of problems is dry-run. I am sharing a two step dry-run hoping that will be helpful:
dry-run

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.

Is there a best approach to create four times 1 - 12 blocks through a loop

There is a loop that increments the counter 48 times to write certain values to an Excel file.
In the range 1 - 48, 4 blocks from 1 - 12 are to be written.
Expected example:
1 2 3 4 5 6 7 8 9 10 11 12 - 1 2 3 4 5 6 7 ... and so on (4 times).
I have tried different approaches, if/else, switch/case but here I have not come to any result.
My last approach is an if condition with the modolu operator.
for (int i = 1; i <= 48; i++) {
if (i % 12 != 0) {
for (int j = 1; j <= 12; j++) {
workBook.setNumber(HEADLINE_ROW, i + 6, j);
}
} else {
workBook.setNumber(HEADLINE_ROW, i + 6, 12);
}
}
But with this approach I get 12 12 12 12 and so on.
I recognize the error, but currently have no idea how to solve the problem. The part where data is written to the Excel file is rather unimportant. I am concerned with the logic.
I'm stuck in the logic here and can't get any further. Do you have any ideas or suggestions for improvement on how I can generate four 1 - 12 blocks side by side?
do something like that
python
for i in range(48):
index = i % 12 + 1
# do what ever you want here
print(index)
java
for(int i = 0; i < 48; i++) {
int index = i % 12 + 1;
// do something here
}
I think the pseudo code for what you want would be:
for (int i=1; i <= 48; i++) {
int j = i % 12 + 1; // 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 ...
// do something with i and (j + 1)
}
That is, work with the outer loop counter mod 12, which would give you the sequence 1, 2, ..., 12, four times.

Moving array elements left and right

So as part of the Vector class I'm trying to create, I also want the ability for the user to be able to shift the elements in the array an 'n' number of places depending on what is specified. If the user inputs a number that is larger than the array size, then the elements continue shifting back to the start and moving. An example would be:
1 2 3 4 (shifted 1) => 4 1 2 3
1 2 3 4 (shifted 4) => 1 2 3 4
1 2 3 4 (shifted 5) => 4 1 2 3
I don't have much code so far except:
public Vector shifted(int amount) {
Vector vectorShifted = new Vector(length);
for (int i = 0; i < length; i++);
vectorShifted.elements[i] = this.elements[i + amount]
}
return vectorShifted;
}
However, when I run this program and a number greater than length is entered, an error is displayed. Is there a way of modifying this code in that any number, positive or negative can be inputted and shift the values across?
Just like lazary2 said, you can use the modulo operator %
Change:
vectorShifted.elements[i] = this.elements[i + amount]
to vectorShifted.elements[i] = this.elements[(i + amount) % length]
If you want to use Array:
Integer[] array = {0,1,2,3,4};
Collections.rotate(Arrays.asList(array), 3);
System.out.println(Arrays.toString(array)); //[2, 3, 4, 0, 1]

How can I increment and decrement an integer with the modulo operator

I am trying to increment an integer based on a click. How the click happens does not matter so I'll stick to the logic. I am doing this in Java but the logic should be the same all around.
int index = 0;
// then within the click event
//arrySize holds the size() of an ArrayList which is 10
index = (index + 1) % arrySize;
With this logic, every time the user clicks, index will increment by 1. Then its modulo of arrySize causes index to go back to 0 when index matches arrySize
(10 % 10 would make the index go back to 0) Which is great because it's kind of like a loop that goes from 0 to 10 then back to 0 and never over 10.
I am trying to do the same logic but backwards
where based on the click the number will decrement and get to 0 then
goes back to the arrySize instead of -1
How can I achieve this logic?
(index + arraySize - 1) % arraySize
Does what you want.
Starting with Java 8, you can use the Math.floorMod(x, y) method. Quoting its Javadoc (emphasis mine):
The floor modulus is x - (floorDiv(x, y) * y), has the same sign as the divisor y, and is in the range of -abs(y) < r < +abs(y).
System.out.println(Math.floorMod(-1, 5)); // prints 4
So you will have:
index = Math.floorMod(index - 1, arrySize);
You can't have directly -1 % 5 because that will output -1 based on how the operator % operates with negatives numbers.
index = arraySize - ((index + 1) % arrySize)
Use this if you want 1-based indexing. For example if you wanted to step backwards through months where 1 is January.
int previous = ((index - 1 - arraySize) % arraySize) + arraySize
Results
index previous
1 12
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9
11 10
12 11
Example Fiddle

Generating series

I'm looking for an explanation on the following problem
Given an input - array of integers such as 1 2 3 4 I want to produce all of the possible "permutations" which look like this0 0 0 1 , 0 0 0 2, first one goes like this until 0 0 0 4 , next one looks like this 0 0 1 0 and then 0 0 1 1 .I hope you got my point.I have already constructed an iterative algorithm which produces the series but it uses too much memory for an input of size 10, the solution I'm looking for doesn't use recursion. Please note that there are (n + 1)! (0,0,0,0 included) possiblities.
The input is limited to integers and it is always the case that the count of values generated equals the count of the input values.
EDIT
Please note that there might be such a solution here in Stackoverflow but I can't really define a proper name for the problem that's why if anyone has any clue on how to actually name this problem,please do share!
Thanks!
To generate your series you basically do this:
Start with an array containing only zeroes, of the correct length
Iterate, and for each iteration do "basic math" like incrementation of the number, as though each element of the array is a single digit of a larger number.
Basically increment the last number by 1
If this ends up being higher than the max for that position, reset it to 0 and move on to the digit to the left
If it didn't end up being higher than the max, you got a new solution
When the move-on-to-the-digit-to-the-left operation falls off the left end of the array, you're done
Here is a LINQPad solution that demonstrates:
void Main()
{
CountedPermutations(1, 2, 3)
.Select(l => new { a = l[0], b = l[1], c = l[2] })
.Dump();
}
public static IEnumerable<int[]> CountedPermutations(params int[] maxValues)
{
int[] results = new int[maxValues.Length];
yield return results; // the all-zeroes solution
while (true)
{
// Increment to next solution
if (CountedPermutationsMutate(results, maxValues))
{
// make a copy of the array and yield return it
// we make copies so that if the outside code puts everything in a
// collection, we don't just end up with N references to the same array
// with the same values.
yield return results.ToArray();
}
else
break;
}
}
public static bool CountedPermutationsMutate(int[] values, int[] maxValues)
{
int index = values.Length - 1;
bool gotSolution;
while (true)
{
if (values[index] < maxValues[index])
{
// won't overflow this position, so we got a new solution
values[index]++;
gotSolution = true;
break;
}
else
{
// Overflow in this position, reset to 0
// and move on to the next digit to the left
values[index] = 0;
index--;
// If we fell off the left end of the array, we're done
if (index < 0)
{
gotSolution = false;
break;
}
}
}
return gotSolution;
}
This will output:
0 0 0
0 0 1
0 0 2
0 0 3
0 1 0
0 1 1
0 1 2
0 1 3
0 2 0
0 2 1
0 2 2
0 2 3
1 0 0
1 0 1
1 0 2
1 0 3
1 1 0
1 1 1
1 1 2
1 1 3
1 2 0
1 2 1
1 2 2
1 2 3
Consider using iterators to avoid storing of every generated value.

Categories