Counting how many times a loop runs - java

If we have a loop like this
for(int i=0; i<n; i+=2)
{
total+=1;
}
I assume there is one instruction in the header, and it executes one instruction in the body so the total number of instruction is (n-0)/2*1+1 (last condition). Is it the right way to do it? How would you count it?
Also, how about this?
for(int i=1; i<n; i*=2)
{
total+=1;
}
If n = 20, i goes like 1,2,4,8,16, and I'm not sure how to calculate it

Just write them out on paper and look for a pattern. For your first example:
for(int i=0; i<n; i+=2)
n i's total
0 [] 0
1 [0] 1
2 [0] 1
3 [0,2] 2
4 [0,2] 2
5 [0,2,4] 3
6 [0,2,4] 3
and so on..
That is floor((n+1)/2) (or integer division).
The second one; we can see it's going to be related to log2 just by examination, so let's compare the counts with log2(n) to see if we can find a pattern:
for(int i=1; i<n; i*=2)
n i's total log2(n)
1 [] 0 ---
2 [1] 1 1
3 [1,2] 2 1.58
4 [1,2] 2 2
5 [1,2,4] 3 2.32
6 [1,2,4] 3 2.58
7 [1,2,4] 3 2.81
8 [1,2,4] 3 3
9 [1,2,4,8] 4 3.17
10 [1,2,4,8] 4 3.32
11 [1,2,4,8] 4 3.46
12 [1,2,4,8] 4 3.58
13 [1,2,4,8] 4 3.70
14 [1,2,4,8] 4 3.81
15 [1,2,4,8] 4 3.91
16 [1,2,4,8] 4 4
17 [1,2,4,8,16] 5 4.09
Looking at this and thinking about it for a moment we can see it is floor(1+log2(n-1)), with special cases for n=0 (total=0) and n=1 (total=0).
The thought process in that last one is: we have to "shift" the log2 column down one to make it line up with the total column (hence log2(n-1)), and we have to add 1 to it to make the values match.

Related

For loop always runs one less time then it should, due to two lines of code that appear unrelated to the for loop

Edit: For some reason my code works as intended in an online compiler. But in eclipse, the exact same code has the following problem.
I am working on a Kattis Problem called Electrical Outlets.
On the first line of input will be the number of test cases (n). On the next n lines, each line will start with an integer k, which is the number of power strips that will follow on the line. The rest of the line will contain how many outlets each of these power strips contain. Here is my code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<Integer> outlets = new ArrayList<>();
int testCases = scnr.nextInt();
int stripCount;
int appliances = 0;
for (int i = 0; i < testCases; i++) {
stripCount = scnr.nextInt();
for (int j = 0; j < stripCount; j++) {
outlets.add(scnr.nextInt());
appliances += outlets.get(j);
}
System.out.print("\nNumber of outlets: " + (appliances - (outlets.size() - 1)));
System.out.print("\n" + i);
outlets.clear();
appliances = 0;
}
}
Now for some reason, the outer for loop always runs one less time then it should.
Here is a sample input
3
3 2 3 4
10 4 4 4 4 4 4 4 4 4 4
4 10 10 10 10
And expected output
Number of outlets: 7
Number of outlets: 31
Number of outlets: 37
However, my output is
Number of outlets: 7
Number of outlets: 31
Similarly, for input
5
5 4 3 2 5 6
4 3 2 2 3
7 4 4 4 4 4 4 4
5 4 3 3 4 4
8 9 9 9 9 9 9 9 9
I expect an output of
Number of outlets: 16
Number of outlets: 7
Number of outlets: 22
Number of outlets: 14
Number of outlets: 65
But receive an output of
Number of outlets: 16
Number of outlets: 7
Number of outlets: 22
Number of outlets: 14
If I comment out the following two lines contained within for loop(int j)
for (int j = 0; j < stripCount; j++) {
//outlets.add(scnr.nextInt());
//appliances += outlets.get(j);
}
And add print(i), the for loop iterates as many times as it should.
Kattis validates your code by inspecting your program's standard output. If even a single character is different than the judge expects, your submission will fail, and Kattis will only report "Wrong answer" without any reason, actual/expected diff or other diagnostics.
Therefore, it's critical to pay close attention to the expected output format in the problem description and sample test cases.
For the first sample input, we're given:
3
3 2 3 4
10 4 4 4 4 4 4 4 4 4 4
4 10 10 10 10
And the expected output is:
7
31
37
But your output is different:
Number of outlets: 7
0
Number of outlets: 31
1
Number of outlets: 37
2
This contains unnecessary "Number of outlets: " prefixes as well as an i for each test case. Sure, to a human, this is fine, but Kattis' runner program isn't smart enough to understand that you basically got it right.
Removing the i print and changing your result print to match what Kattis is asking for passes the submission tests:
System.out.println(appliances - (outlets.size() - 1));
As for the missing last line, you're probably not flushing that final buffer in the IDE. Either add a final newline or press Enter manually if you have interactive capabilities. This appears to be an environment misunderstanding, not a code problem.

How can I find the stop and start index for a Java vector?

I have a vector that looks like this:
y =
Columns 1 through 19:
1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2
Columns 20 through 38:
2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4
Columns 39 through 57:
4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 6
Columns 58 through 67:
6 6 6 6 6 6 6 6 6 6
The vector y is always start at 1 and be counted up. You see that there are lots of same numbers. It's the classes for the samples.
Here we have 1 1 1 1 1 1 1 1 1 1 1 1 = 12 samples for class number 1.
We have 2 2 2 2 2 2 2 2 2 2 2 = 11 samples for class number 2.
My problem here is that I want to find start and stop for every class. For example: Class 1 begins always at index 0 and ends, in this case, at index 11.
Class 2 begins directly after class 1 ends.
Question:
I'm using EJML (Effient Java Matrix Library) and I'm planning to use this function:
C = A.extractMatrix(1,4,2,8)
Which is equal to this MATLAB code:
C = A(2:4,3:8)
But I need to find the start and stop indexes from this y vector. In what index does e.g class 3 stops and starts? Do you have any smart ideas how to do that?
Sure, I could use a for-loop, to do this, but for-loops in Java is quite slow because I'm going to have a very very large y vector.
Suggestions?
Edit:
Here is an suggestion. Is that good, or could it be done better?
private void startStopIndex(SimpleMatrix y, int c, Integer[] startStop) {
int column = y.numCols();
startStop[0] = startStop[1] + 1; // Begin at the next class
for(int i = startStop[0]; i < column; i++) {
if(y.get(i) != c) {
break;
}else {
startStop[1] = i;
}
}
}
Assuming that we are calling the method from:
Integer[] startStop = new Integer[2];
for(int i = 0; i < c; i++) {
startStopIndex(y, c, startStop);
}
If you want to do it faster then binary search is your friend. Threw this together really quick and it does things in O(log n) time, where as a linear search does it in O(n). It's pretty basic and assumes your data looks pretty much like you describe it. Feed it weird data and it will break.:
int[] breakPoints(int[] arr, int low, int high){
int[] rtrn = new int[high];
for(int i=low;i<high;i++){
rtrn[i]=binarySearch(arr, i, 0, arr.length-1);
}
return rtrn;
}
int binarySearch(int[] arr, int k, int start, int end){
int mid = (start+end)/2;
if(mid==arr.length){
return -1;
}
if(arr[mid]==k && arr[mid+1]==k+1){
return mid+1; //or just mid if you want before breakpoint
}
if(arr[mid]<=k){
return binarySearch(arr, k, mid+1, end);
}
return binarySearch(arr, k, start, mid-1);
}
You'd call it like this:
int[] data = {1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,5,5,6,6,6,6};
int[] bp = breakPoints(data,1,6);
//return 0, 3, 8, 13, 16, 18
I think there is a name for this, but I can't remember what it might be, but you start looking for the next boundary with an accelerating search, and use a binary search after that.
You know the numbers are in ascending order, and there are potentially a lot of the same number, so you start by checking the next element. But instead of keep going 1 step at a time, you accelerate and step 2, 4, 8, 16, ... until you find a higher number.
Once you've found a higher number, you've gone too far, but the last step had the initial number, so you know the boundary is somewhere between the last two steps, and you then apply a binary search for the boundary.
Once you've fund the boundary, you start over stepping 1, 2, 4, ... for the next boundary.
If you expect most numbers to have about the same number of occurrences, you could keep a running average count, and make the first step with that average, to get a running start.
I'll leave it to you to actually code this.
The below is in MATLAB. the for loop will go through each unique value stored in x1 and then find the first and last occurrence of that value.
x = [ 1 1 1 2 2 3 3 3 3 3 4 4 4 4 5 5 5 ]
x1 = unique(x)'
for k1 = 1:length(x1)
x1(k1,2:3) = [find(x == x1(k1,1),1,"first"), find(x == x1(k1,1),1,"last")];
end
the above code yields x1 to be a 3 column matrix
1 1 3
2 4 5
3 6 10
4 11 14
5 15 17

Using nested for loops to print numbers (java)

I am trying to use nested for loops (java) to print out the following:
331
330
322
311
300
222
111
and I am having some trouble. So far I have:
for(int a = 3; a >=0; a--)
{
for(int b = 3; b>=0; b--)
{
for(int c = 2; c>=0; c--)
{
System.out.println(a + " "+ b +" "+ c);
}
}
}
but that prints out something more like this:
3 3 2
3 3 1
3 3 0
3 2 2
3 2 1
3 2 0
3 1 2
3 1 1
3 1 0
3 0 2
3 0 1
3 0 0
2 3 2
2 3 1
2 3 0
2 2 2
2 2 1
2 2 0
2 1 2
What is wrong with my code? How can I get it to print out the first sequence, not the second? I'm pretty sure it has something to do with the middle loop, but I'm really not sure.
Thanks!
If you have nested for loops, unless you set the limits on the inner loops based on the values of the variables in the outer loops, the pattern generated by the inner loops (second and third numbers, in this case) is gonna be the same in each iteration of the outer loop.
I can't code right now, but it seems to me that if you set b to run from a to zero, instead of from 3 to zero you might get a little closer to what you want.
But still, since it seems there isn't a pattern in what you want to get, it's hard to think of an algorithm to print them. What do these numbers mean?

creating a number pattern with day number

Okay so I need to make a number pattern with day numbers for example: 1 - monday, 2 - tuesday, 3 - wednesday until 7 - sunday. If I put an input "n" I would get the following:
n=4
1 2 3 4
n=7
1 2 3 4 5 6 7
n=12
1 2 3 4 5 6 7 1 2 3 4 5
I've succeeded making this program if n<=14 but if n>14 I get:
n=17
1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 10
when it should be:
n=17
1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3
this is my code
for (x=1;x<=n;x++){
System.out.print(x+" ");
if (x==7){
for (x=1;x<=(n-7);x++)
System.out.print(x+" ");
break;
}
}
thanks in advance
Try this instead:
for (int i = 0; i < n; i++)
System.out.print(i % 7 + 1 + " ");
Whenever you want to have that "repeating" behavior, where a sequence of numbers goes up to a certain value and then restarts, use the % operator and a bit of modular arithmetic to achieve the desired effect. For n = 17 the above will print:
1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3

Need help coming up with a Cake sorting algorithm in Java

OK here is what I have to do
As an employee of MCI (Mammoth Cakes Incorporated), it is your job to create extremely large
layered birthday cakes. A layered birthday cake is made by taking small circular cakes layers and
stacking them on top of each other.
To perform your job, you stand in front of a big conveyor belt
while layers of varying sizes pass in front of you. When you see one you like, you may take it off the
conveyor belt and add it to your cake.
You may add as many layers to your cake as you would like,
as long as you follow these rules:
Once a layer is added to your cake it cannot be moved. (It messes up the icing.) Thus, layers
can only be added to the top of your cake.
Each layer passes in front of you only once. You may take it or leave it. If you take it, you
must add it to the top of your cake. If you leave it, it will move on down the conveyor belt,
never to return.
Each layer in your cake must be at least as small as the layer below. You cannot place a
larger layer on top of a smaller one.
You will be told in advance the diameters (in inches) of the layers coming down the conveyor belt.
Your job is to create the tallest cake possible using those layers.
For example, suppose the following list represents the diameters of the layers coming down the
conveyor belt: 8 16 12 6 6 10 5
Suppose you take the first layer (with a diameter of 8”) for your cake. That means you may not take the second layer (since you already have a layer of size 8”, and 16” > 8”). Similarly, you could not
take the third layer, but you could take the fourth layer (since 6” < 8”).
Following that, you could
also take the fifth layer (the rule is simply that the layer on top cannot be larger; it can be the same
size). Proceeding in this fashion we can create a cake with a height of 4 layers: 8 6 6 5
However, if we had let the first layer go on by and started with the second layer, we could create a
cake with a height of 5: 16 12 6 6 5
Your program will process multiple input sets, one per line. Each line will begin with an integer N,
followed by N positive integers representing the sizes of the cake layers in the order that they will be
arriving on the conveyor belt. N will always be a non-negative integer, 0 N 100,000. Each layer
will have a diameter between 1 and 100,000, inclusive. A line where N = 0 marks the end of the
input
Sample Input
7 8 16 12 6 6 10 5
10 45 25 40 38 20 10 32 25 18 30
10 10 9 8 7 6 5 4 3 2 1
0
Sample Output
5
6
10
Question: Find the tallest layer of Cakes
Here is what I have written so far:
import java.io.*;
import java.util.*;
public class cake
{
private static String line;
private static ArrayList storage = new ArrayList();
private static Integer highestStack = 0;
public static void main(String [] args)throws IOException
{
FileReader fin = new FileReader("cake.in");
BufferedReader infile = new BufferedReader(fin);
FileWriter fout = new FileWriter("cake.out");
BufferedWriter outfile = new BufferedWriter(fout);
line = infile.readLine();
do
{
String[] temp = line.split(" ");
String number;
for(int j = temp.length-1; j!=0; j--)
{
if(Integer.parseInt(temp[j]) <= Integer.parseInt(temp[j-1]))
{
highestStack++;
}
}
storage.add(highestStack);
// Collections.sort(storage);
line = infile.readLine();
}while(!line.equals("0"));
infile.close();
outfile.close();
}
}
As I commented on several answers totally missing the point, this is a Dynamic Programming problem.
Now that you added the constraints, it is clear that a Dynamic Programming solution running in O(n^2) is the way to go, and the fact that N won't go above 100 000 makes it easy to solve using DP (and probably very hard to solve using non-DP algos).
At every moment, you have to ask yourself "What is the best I can do up to 'x'".
Here's how it looks like for you first example :
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 (Best we can do using pieces: 5 )
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 (Best we can do using pieces: 5 10 )
0 0 0 0 0 1 2 2 2 2 2 2 2 2 2 2 2 (Best we can do using pieces: 5 10 6 )
0 0 0 0 0 1 3 3 3 3 3 3 3 3 3 3 3 (Best we can do using pieces: 5 10 6 6 )
0 0 0 0 0 1 3 3 3 3 3 3 4 4 4 4 4 (Best we can do using pieces: 5 10 6 6 12 )
0 0 0 0 0 1 3 3 3 3 3 3 4 4 4 4 5 (Best we can do using pieces: 5 10 6 6 12 16 )
0 0 0 0 0 1 3 3 4 4 4 4 4 4 4 4[5] (Best we can do using pieces: 5 10 6 6 12 16 8 )
Tallest cake as a height of: 5
The way to read a line above is easy. Let's take the first line for example:
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
It means that the tallest cake we can make that has a base of anywhere from 5 to 16 is made of one element (our first piece, the '5').
Then we get the piece '10', and we get the line:
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2
It means that the tallest cake we can make from 5 to 9 will have one element (our '5') and that from 10 to 16 we can stuff two pieces (5 and 10).
And you repeat like that, with up to 100 000 elements if you want.
On my computer a full 100 000 solution takes less than 20 seconds to be solved using Dynamic Programming.
Here's the code solving your problems and outputting the above. I added output statements on purpose so that you can see what is going on (it will only look pretty with relatively small numbers that said, it is really just to get what is going on with the algorithm).
public static void main( String[] args ) {
doIt( new int[] {8,16,12,6,6,10,5} );
doIt( new int[] {0, 45, 25, 40, 38, 20, 10, 32, 25, 18, 30} );
doIt( new int[] {10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1} );
}
public static void doIt( int[] r ) {
final int[] a= new int[r.length];
int max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
max = Math.max( max, a[i] );
a[(a.length-1)-i] = r[i];
}
final int[] s = new int[max+1];
for (int i = 0; i < a.length; i++) {
final int size = a[i];
s[size]++;
for (int j = size+1; j < s.length; j++) {
s[j] = Math.max( s[j-1], s[j] );
}
for (int j = 0; j < s.length; j++) {
System.out.print( " " + ((s[j]) > 9 ? "" : " ") + s[j] );
}
System.out.print( " (Best we can do using pieces: " );
for (int k = 0; k <= i; k++) {
System.out.print( a[k] + " " );
}
System.out.println( ")" );
}
System.out.println( "Tallest cake as a height of: " + s[s.length-1] );
}
I'm not certain what you're asking, exactly.. So, I'll give you some general hints.
Look into the Stack data structure, instead of an ArrayList. Push a layer onto the stack, and then use peek to check the diameter of the topmost layer of your cakestack against the current item in the conveyor.
If the goal is to find the tallest possible cake, a naive approach would be to simply apply the above algorithm by starting with the first layer in the conveyor, continuing to the end, and recording the ultimate height (stack.size()). Then repeat with the second item in the conveyor as your base, and then the third, and so on, comparing the resulting height against the recorded max at the conclusion of each loop.
Let's walk through the process. Each time we encounter a layer on the assembly line, we make a decision: use this layer or not? The best result overall is the better of the following two outcomes:
We use this layer, and build on top of it the tallest cake using the remaining layers not larger than this layer.
We don't use this layer, and build the tallest cake using any of the remaining layers.
We can model this simply with recursion - pseudocode:
tallest(remaining_layers, base_size) = # set base_size = infinity the first time
max(
first_layer + tallest(other_layers, size(first_layer)),
tallest(other_layers, base_size)
)
where first_layer = first(remaining_layers),
other_layers = rest(remaining_layers)
However, that won't cut it by itself, since we're supposed to use dynamic programming.
The idea is that we're recursively calling tallest with other_layers both times. Wouldn't it be nice if we could call it once, and have all the information we need?
What information do we need? Well, if we had the tallest cake using the remaining layers for any base size, we'd be set: we just pick the tallest cake that can fit on the current layer, and see if that makes an improvement versus the tallest cake overall. But here's the trick: even if it doesn't make an improvement, we may still gain information. The idea is to have a list of the most "efficient" (smallest base) cakes for each size.
Our process will therefore be as follows:
Set up a list of cakes, with one cake in it that has zero layers.
# There will be, at all times, one cake in the list of any given height.
# Starting at zero instead of one makes the iteration neater.
For each layer on the conveyor belt, working **backwards** from the last:
Find the tallest cake in the list that fits on this layer.
Construct the cake 'c' consisting of that cake on top of this layer.
If there is already a cake in the list of the same height as 'c':
If the other cake has a smaller base, throw 'c' away. # It didn't help.
Otherwise, remove the other cake from the list. # 'c' is better.
If we still have 'c', add it to the list.
The tallest possible cake for the input is now the tallest one in the list.
This input sequence is tricky:
10 45 25 40 38 20 10 32 25 18 30
A simplistic approach that only skips lead-in layers would find these [cakes]:
[10] 45 25 40 38 20 10 32 25 18 30
10 [45 25] 40 38 20 10 32 25 18 30
10 45 [25] 40 38 20 10 32 25 18 30
10 45 25 [40 38 20 10] 32 25 18 30 <-- naive tallest, 4
10 45 25 40 [38 20 10] 32 25 18 30
10 45 25 40 38 [20 10] 32 25 18 30
10 45 25 40 38 20 [10] 32 25 18 30
10 45 25 40 38 20 10 [32 25 18] 30
10 45 25 40 38 20 10 32 [25 18] 30
10 45 25 40 38 20 10 32 25 [18] 30
10 45 25 40 38 20 10 32 25 18 [30]
The rules of the game allow you to skip any layer, though, not just the lead ones, and so the correct tallest cake in this case would be:
10 [45] 25 [40] [38] 20 10 [32] [25] [18] 30
Or written out with only the selected layers:
45 40 38 32 25 18
The problem you're trying to solve is a dynamic programming question (albeit a simple one).
Algorithm
public static int findMaxHeight(int[] layers) {
int[] max = new int[layers.length];
for(int i=layers.length - 1; i >= 0; i--) {
int localMax = 0;
for(int j=0; j < layers.length; j++) {
if(layers[j] < layers[i]) {
if(max[j] > localMax) {
localMax = max[j];
}
}
}
max[i] = localMax + 1;
}
int height = 0;
for(int i=0; i < max.length; i++) {
if(max[i] > height) {
height = max[i];
}
}
return height;
}
Step By Step
As a step through of how this works, consider:
8 16 12 6 6 10 5
Since we are going in reverse order,
5 10 6 6 12 16 8
Starting with 5, there are smaller than 5 values from []:
5 10 6 6 12 16 8
1
From [5], max[5] = 1 so 1+1
5 10 6 6 12 16 8
1 2
And so on...
5 10 6 6 12 16 8
1 2 2 3 4 5 4
Then we find out max of the list [1, 2, 2, 3, 4, 5, 4], which is 5.
And, as explained above, this is the correct answer to the provided example that he stepped through in the problem description.
How It Works
The algorithm works by taking saving the maximum value for each layer. The question explains that, for any given layer, it can stack only cakes less than or equal to its diameter. Therefore, the maximum of any given layer will always be the maximum of a layer of equal or less size which follows it on the belt plus 1 (counting the layer itself). If there are no layers that can be stacked onto it, we know that the max for this layer is 1.
Actually is very simple, it goes like this:
int[] layers = new int[] {x1,x2,x3...xn};
int[] count = new int[layers.length];
for(int i = 1; i < layers.length; i++)
{
for(int j = i+1 ; j < layers.length; j++)
{
if ( layers[j] >= layers[i]) count[i]++;
}
}
answer = Collections.max(Arrays.asList(count));

Categories