Hello good people of StackOverflow community , currently I am facing a problem and I need your advice/help.
I have written a code where it will take user input for Test Cases and for each Test Cases my program will execute and will provide the result.
Also for each Test Cases I am taking some other values from user as well
For ex
Code
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-->0){
long K = sc.nextLong();
if (K >= 2 && K <= (10 ^ 12)) {
int d0 = sc.nextInt();
int d1 = sc.nextInt();
//some additional code
}
}
All the variable i.e. K , d0 , d1 are taking the input for the first time but for the second time d0 and d1 aren't taking any values and instead the values are getting stored in variable K(for T > 1) and I am not sure why?!
for ex - The values for T = 3
The corresponding values for K , d0 and d1 when T = 3 are 5 3 0
T = 2 are 17 6 7
here the values of d0 and d1 are not getting stored instead it is getting stored in K only such that K = 17 and then K = 6 and end of loop (since T = 0 )
Thanks in advance!
10 ^ 12 is not what you expect it to be.
^ is the bitwise-xor operator.
The operator will logically compare each bit of 10 to 12 and will output a 1 at given bit if there is exactly one of the two input bits is 1 (and therefore the other is 0).
10 in binary is 0b1010
12 in binary is 0b1100
therefore 10 xor 12 is 0b0110 which is 6 in decimal
In order to calculate 10 to the power of 12 use Math.pow(10,12)
I'm currently working on a Travelling salesman problem and i'm having trouble generating random paths with the same start and end value
This is my current path(path of cities visited)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 38 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 14 39 40 41 42 43 44 45 46 47 48 49 50 51 0
See how the last node arrives back at 0(TSP logic)
Now i'm trying to shuffle this array randomly because random start points generate better results then others However I know how to shuffle the array using Collections but that would shuffle every value randomly
Basically i'm trying to create a method to shuffle an array randomly WITH THE EXCEPTION THE START and END VALUES must be the same and every number must be distinct 0-51
This is my current code, it basically shuffles the array and sets the last index to the first index
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
ar[ar.length-1]=ar[0];
}
however this is giving me duplicate values for some reason
Could you not remove the start and end position, shuffle the array, and then add the start and end position again?
I'm learning java and have some misunderstanding about array elements:
import java.util.Random;
class One {
public static void main (String[]args) {
Random R1 = new Random();
int mat [] = new int [6];
for ( int chance =0; chance<99; chance++ ) {
++mat[1+R1.nextInt(5)];
}
System.out.println("M\tNumber");
for(int M =1;M <mat.length;M++) {
System.out.println(M + "\t" + mat[M]);
}
}
}
And after running this code I got something like:
M Number
1 30
2 15
3 17
4 23
5 14
I did a lot of attempts and usually Number <=20, which is a bit confusing for me cause I assighn chance <99 hence I asume it should be a bigger number in general. Could you point on my mistake?
I think there is no mistake.
It is very likely that numbers will be about 20 because:
You repeat the following sequence 99 times:
1. Get one random(one of six) element from array.
2. Increase element value (plus one).
Let's assume (of course it doesn't) that random method works in the way it gets for 99 execution :
20 times value 0
20 times value 1
20 times value 2
20 times value 3
20 times value 4
19 times value 5
So we get:
20 in first array element
20 in second array element
and so on...
So, to get bigger number you need to decrease array length or change condition in for loop to bigger "chance" number (in your case: for ( int chance =0; chance<200; chance++ ) ).
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
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));