Generating integers of form 2^n - 1 with for loop - java

I have an assignment that asks me to write a for loop inside a method that will output this sequence:
1 3 7 15 31 ... 255
I know that the pattern is to multiply the number by two then add one (or just to add the exponents of 2 to each number so 1 + 2 = 3 + 4 = 7 + 8 = 15 etc.) but I don't know how exactly to make a loop that'll output that sequence all the way up to 255.
I would just like an example or explanation to guide me a little bit, I don't want anyone to actually give me the exact code I need. Here's what I've done so far:
public static void methodOne() {
for (int j = 1; j <= 255; j *= 2) {
}
}
I tried to use another for loop within the for loop above but it didn't work well, and I'm not sure if that's the right thing to do. I basically want to take j and have it multiplied by two and then add 1 to get the next number in the sequence.

As you noted, the sequence is to double the previous number and add one. Just have your for loop progress like that, and print the number in each iteration:
for (int j = 1; j <= 255; j = (j * 2) + 1) {
System.out.println(j);
}

As is howework, will leave you something to think:
for x in 2:8 range
result = 2^x -1

this is the most succinct form I could think of that uses only additions ( + ) over 1 single tracking variable:
jot 100 |
mawk '$++NF = _+=_++' CONVFMT='%.f' # mawk-1
gawk '$++NF = _+=_++' # gawk, mawk-2, nawk, etc
1 1
2 3
3 7
4 15
5 31
6 63
7 127
8 255
9 511
10 1023
11 2047
12 4095
13 8191
14 16383
15 32767
16 65535
17 131071
18 262143
. . .
30 1073741823
31 2147483647
32 4294967295
33 8589934591
34 17179869183
35 34359738367
36 68719476735
if you wanna go all the way to 2^1023 - 1 without using a big-int library (tested and confirmed working for mawk-1, mawk-2, gawk 5.2.0, and nawk):
jot 1023 |
mawk '$++NF = (((___+=___++)%((_+=_^=_<_)+_*_*_)^_^_)%_ ||
index(___,"e") < (length(___) < _^_^_--)) \
? ___ : sprintf("%.*s%d", -_+(__ = length(_=\
sprintf("%.f",___))),_,substr(_,__)-!!__)' \
CONVFMT='%.16g'
31 2147483647
279 9713344461128645354597309534117594533212034195260697606259062048
69452142602604249087
527 4393470502483590217588416511412091659052438592091715462012456613
8787476373744998733584381700233309151854696392905477491437580723
1981865204004737810631363657727
775 1987223158144907436990693745232003270728814101909371662257986608
6733452194385624145035243633006674917766242952923277737038996224
5646696242104868771205271185818170236930668787910433956560844600
937633663896795708000114284397288455405567
1023 8988465674311579538646525953945123668089884894711532863671504057
8866337902750481566354238661203768010560056939935696678829394884
4072083112464237153197370621888839467124327426381511098006230470
5972654147604250288441907534117123144073695655527041361858167525
5342293149119973622969239858152417678164812112068607

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.

Finding all percentage combinations on multiple values

I currently have a problem where I have an end result and the values that contribute to it, but I don't know what the weighting of each value is to the final result.
A simplified example: 11555 + -34.65 + 350 = 26
I don't know how to calculate the weighting mathematically, it has been suggested I use linear regression and a formula for Ordinary least squares. This is a bit beyond me to be honest and I was looking at an alternative solution.
What I propose to do, as I have a lot of sample data, is to use a brute force method over the values, where I use use a percentage of each value to contribute to the result, and compare and keep the percentages that provide the smallest difference.
What I'm struggling with is, how do I cover all percentage combinations for all values?
For example on 3 values the percentages would be something like this.
v1 v2 v3 %
98 1 1 = 100
97 2 1 = 100
96 2 2 = 100
95 3 2 = 100
94 3 3 = 100
.
.
.
4 48 48 = 100
3 49 48 = 100
2 49 49 = 100
1 50 49 = 100
I hope this explanation is clear enough and I'd be grateful of any help you can give. I'm writing the program in Java.
you can get all possible combinations with this code
for ( int i = 98; i > 0; i-- ) {
for ( int j = 1; j+i < 100; j++ ) {
int k = 100 - i - j;
//do stuff with i,j,k
}
}

Modulus division when first number is smaller than second number

I apologize if this is a simple question but I'm having trouble grasping the concept of modulus division when the first number is smaller than the second number. For example when 1 % 4 my book says the remainder is 1. I don't understand how 1 is the remainder of 1 % 4. 1 / 4 is 0.25. Am I thinking about modulus division incorrectly?
First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics.
That said, you need to think in terms of integer-only division, as if there were no fractional values. Think of it as storing items that cannot be divided: you can store zero items of size 4 in a storage of overall capacity one. Your remaining capacity after storing the maximum number of items is one. Similarly, 13%5 is 3, as you can fit 2 complete items of size 5 in a storage of size 13, and the remaining capacity is 13 - 2*5 = 3.
If you divide 1 by 4, you get 0 with a remainder of 1. That's all the modulus is, the remainder after division.
I am going to add a more practical example to what "Jean-Bernard Pellerin" already said.
It is correct that if you divide 1 by 4 you get 0 but, Why when you do 1 % 4 you have 1 as result?
Basically it is because this:
n = a / b (integer), and
m = a % b = a - ( b * n )
So,
a b n = a/b b * n m = a%b
1 4 0 0 1
2 4 0 0 2
3 4 0 0 3
4 4 1 0 0
5 4 1 4 1
Conclusion: While a < b, the result of a % b will be "a"
Another way to think of it as a representation of your number in multiples of another number. I.e, a = n*b + r, where b>r>=0. In this sense your case gives 1 = 0*4 + 1. (edit: talking about positive numbers only)
I think you are confused between %(Remainder) and /(Division) operators.
When you say %, you need to keep dividing the dividend until you get the remainder 0 or possible end. And what you get in the end is called Remainder.
When you say /, you divide the dividend until the divisor becomes 1. And the end product you get is called Quotient
Another nice method to clear things up,
In modulus, if the first number is > the second number, subtract the second number from the first until the first number is less than the second.
17 % 5 = ?
17 - 5 = 12
12 % 5 = ?
12 - 5 = 7
7 % 5 = ?
7 - 5 = 2
2 % 5 = 2
Therefore 17 % 5, 12 % 5, 7 % 5 all give the answer of 2.
This is because 2 / 5 = 0 (when working with integers) with 2 as a remainder.

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));

Simple division in Java - is this a bug or a feature?

I'm trying this simple calculation in a Java application:
System.out.println("b=" + (1 - 7 / 10));
Obviously I expect the output to be b=0.3, but I actually get b=1 instead.
What?! Why does this happen?
If I write:
System.out.println("b=" + (1 - 0.7));
I get the right result, which is b=0.3.
What's going wrong here?
You're using integer division.
Try 7.0/10 instead.
You've used integers in the expression 7/10, and integer 7 divided by integer 10 is zero.
What you're expecting is floating point division. Any of the following would evaluate the way you expected:
7.0 / 10
7 / 10.0
7.0 / 10.0
7 / (double) 10
Please do not take this as an answer to the question. It is not, but an advice related to exploiting the difference of int and float. I would have put this under a comment except that the answer box allows me to format this comment.
This feature has been used in every respectable programming language since the days of fortran (or earlier) - I must confess I was once a Fortran and Cobol punch card programmer.
As an example, integer division of 10/3 yields integer value 3 since an integer has no facility to hold fractional residual .3333.. .
One of the ways we (old time ancient programmers) had been using this feature is loop control.
Let's say we wish to print an array of 1000 strings, but we wish to insert a line break after every 15th string, to insert some prettyfying chars at the end of the line and at the beginning of the next line. We exploit this, given that integer k is the position of a string in that array.
int(k/15)*15 == k
is true only when k is divisible by 15, an occurrence at a frequency of every 15th cell. Which is akin to what my friend said about his grandfather's dead watch being accurate twice a day.
int(1/15) = 0 -> int(1/15)*15 = 0
int(2/15) = 0 -> int(2/15)*15 = 0
...
int(14/15) = 0 -> int(14/15)*15 = 0
int(15/15) = 1 -> int(15/15)*15 = 15
int(16/15) = 1 -> int(16/15)*15 = 15
int(17/15) = 1 -> int(17/15)*15 = 15
...
int(29/15) = 1 -> int(29/15)*15 = 15
int(30/15) = 2 -> int(30/15)*15 = 30
Therefore, the loop,
leftPrettyfy();
for(int k=0; k<sa.length; k++){
print(sa[k]);
int z = k + 1;
if ((z/15)*15 == z){
rightPrettyfy();
leftPrettyfy();
}
}
By varying k in a fanciful way in the loop, we could print a triangular printout
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
That is to demonstrate that, if you consider this a bug, this "bug" is a useful feature that we would not want to be removed from any of the various languages that we have used thus far.
I find letter identifiers to be more readable and more indicative of parsed type:
1 - 7f / 10
1 - 7 / 10f
or:
1 - 7d / 10
1 - 7 / 10d
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
Take attention with the parentheses !

Categories