I've been having some trouble with a homework assignment for my Java class. In it, we're supposed to take in an integer between 1 and 13 and display three different triangles consisting of numbers. For example, if I were to enter 5, the result would be:
Triangle 1
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Triangle 2
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Triangle 3
5
4 9
3 8 12
2 7 11 14
1 6 10 13 15
I've already got the first Triangle going fine, but my big concern is the second triangle. I haven't attempted the third one yet. The other thing is that my Professor is picky about what method we use in creating the project. In other words, we can only use what he has taught us. He told us to use the System.out.printf("%3d", n) statement to space out the characters and we have to create them within a separate class.
The code for the first triangle is as follows:
void triangle1(int n)
{
int k = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < 1; j++)
{
System.out.printf("%3d", n);
k += 1;
}
System.out.println();
}
}
So, pretty much, I need to follow that standard to create the other two triangles, but I'm really stuck on the second one and I don't know where to start. Any help will be much appreciated!
Here is the way I would approach it.
Programs print one line at a time, you cannot print half a line then start to print another line.
With that being said, you should recognize the pattern in the triangles.
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
You have the first number n, then you see the next row starts with n + 1. The next number starts in the row is (n + 1) + t where t = 4. There is a pattern there.
The third row follows the same pattern.
The first number is (n + 1) then you can calculate the others by + (t - 1)
This can be done with a for loop, like you did in the first time.
For the last triangle you can use the same process, just change the signs and t would equal something different.
Algorithm writing is all about identifying patterns.
If you look closely, you'll see there's a repeating pattern between each number and the one that follows on a given line.
3 7 10 => [3 & 7 differ by 4][7 & 10 differ by 3]
4 8 11 13 => [4 & 8 differ by 4][8 & 11 differ by 3][11 & 13 differ by 2]
5 9 12 14 15 => [... differ by 4][... by 3][... by 2][... by 1]
You can use that information to make the second triangle. I'll leave the rest to you. I hope that helps!
Seems you are a CS-Student, thus I will not present a finished solution. I'll give you some hints how I would solve this.
This is what the print statement has to do:
for i=1 j=0 print 1
for i=2 j=0 print 2
for i=2 j=1 print 6
for i=3 j=0 print 3
for i=3 j=1 print 7
for i=3 j=2 print 10
Find a formula that calculates the correct output from i and j, its a simple linear combination.
Related
I'm trying to understand question and solving it using java.
But first I'm not able to understand properly.
Here is the question:
You are given an array a of length n and an integer c.
The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.
Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.
Input
The first line contains integers n and c (1 ≤ n, c ≤ 100 000).
The second line contains n integers ai (1 ≤ ai ≤ 109) — elements of a.
Output
Output a single integer — the smallest possible sum of values of these subarrays of some partition of a.
Examples
inputCopy
3 5
1 2 3
output
6
inputCopy
12 10
1 1 10 10 10 10 10 10 9 10 10 10
output
92
inputCopy
7 2
2 3 6 4 5 7 1
output
17
inputCopy
8 4
1 3 4 5 5 3 4 1
output
23
In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.
My Understanding:
1) Partition is being being done within continuous numbers. Correct ?
2) What is the significance of Integer c in input ?
3) How is being done in third example ? I mean after having subarrays, How 13 came out from second subarray ?
Can anyone help me to understand the question ? I can write code myself.
I'm working in Java. Given a matrix NxM, I need to find all possible paths through the array. It is only allowed to go diagonally up or down, or go to the right. An example 4x4 matrix:
3 5 7 9
2 4 6 8
9 3 7 5
6 8 2 4
The numbers in the matrix can be any arbitrary value. I would like to generate all possible routes through the matrix, starting in one of the four numbers in the first column. It is only allowed to move Northeast, East, and Southeast. An example route:
3-5 7 9
\
2 4 6-8
9 3 7 5
6 8 2 4
So all routes consist of M numbers. I'm using a 2D array to hold this NxM matrix. Some more possible paths are:
3 4 6 5
3 5 6 9
9 4 7 4
9 3 6 9
Is there a way to easily generate all paths in Java?
Any help is much appreciated!
Probably you can use three methods for doing this and call them recursively.
goNortEast(); Search for an element to the index [N-1][M+1] if N>0, else there will be no element NOrtEast of the current element, if element exists this will also lead to a new path.
goEast(); Each element can go East by index [N][M+1];
goSouthEast(); Search for element at index [N+1][M+1] if the element exists, this will also lead to a new path,
Call these three methods on each element starting from [0][0], then [1][0] and so on.
for [0][0], it will call goNorthEast[]- will not satisfy condition goEast();-index[0][1] and goSouthEast(); index[1][1] now call the same three methods of these elements.
At the end you will get all possible paths from the element you started.
I need an array of 15 elements with random numbers (1-15). I should enter a value at a specific location, but the values after my selected location should go on by one location. ex: I have
1 12 3 8 9 3 5 4 4 10 3 7 7 2 1 and I want to insert the number "5" at location 3 and now I should have 1 12 5 3 8 9 3 5 4 4 10 3 7 7 2 .
You have an idea?
Thanks in advance.
Use a ArrayList as suggested in the comments. When you have to use a array you can take something like
for (int i = array.length - 2; i >= position; i--)
array[i+1] = array[i];
array[position] = value;
with position the index of the array you want to change and value the value to insert.
I had a question on a test - I got it wrong, but I don't know why?
Question: An array of integers is to be sorted from biggest to smallest using an insertion sort. Assume the array originally contains the following elements:
5 9 17 12 2 14
What will it look like after the third pass through the for loop?
17 9 5 12 2 14
17 12 9 5 2 14 - Correct answer
17 12 9 5 14 2
17 14 12 9 5 2
9 5 17 12 2 14
In an insertion sort, I thought the source array is untouched; I felt, at the third pass, the destination array would be incomplete.
How did the test arrive at this answer?
Basically, after n passes of insertion sort, the first n+1 elements are sorted in the correct order and the rest are untouched. As you can see in the alternatives, the correct answer is the only one that fulfills that. Every step is only inserting relative to the already sorted numbers, so each step one extra number is correctly sorted.
Step 0 (Original, 5 assumed sorted)
5 9 17 12 2 14
Step 1, takes the 9 and puts it in the correct place before 5 (result, 9 5 sorted)
9 5 17 12 2 14
Step 2, takes the 17 and puts it in the correct place before 9 (result 17 9 5 sorted)
17 9 5 12 2 14
Step 3, takes the 12 and puts it in the correct place after 17 and before 9 (result 17 12 9 5sorted)
17 12 9 5 2 14
Insertion sort is typically done in-place. After k iterations the first k + 1 elements are sorted, hence the answer you've shown above.
I'm trying to do this contest exercise about graphs:
XPTO is an intrepid adventurer (a little too temerarious for his own good) who boasts about exploring every corner of the universe, no matter how inhospitable. In fact, he doesn't visit the planets where people can easily live in, he prefers those where only a madman would go with a very good reason (several millions of credits for instance). His latest exploit is trying to survive in Proxima III. The problem is that Proxima III suffers from storms of highly corrosive acids that destroy everything, including spacesuits that were especially designed to withstand corrosion.
Our intrepid explorer was caught in a rectangular area in the middle of one of these storms. Fortunately, he has an instrument that is capable of measuring the exact concentration of acid on each sector and how much damage it does to his spacesuit. Now, he only needs to find out if he can escape the storm.
Problem
The problem consists of finding an escape route that will allow XPTO to escape the noxious storm. You are given the initial energy of the spacesuit, the size of the rectangular area and the damage that the spacesuit will suffer while standing in each sector.
Your task is to find the exit sector, the number of steps necessary to reach it and the amount of energy his suit will have when he leaves the rectangular area. The escape route chosen should be the safest one (i.e., the one where his spacesuit will be the least damaged). Notice that XPTO will perish if the energy of his suit reaches zero.
In case there are more than one possible solutions, choose the one that uses the least number of steps. If there are at least two sectors with the same number of steps (X1, Y1) and (X2, Y2) then choose the first if X1 < X2 or if X1 = X2 and Y1 < Y2.
Constraints
0 < E ≤ 30000 the suit's starting energy
0 ≤ W ≤ 500 the rectangle's width
0 ≤ H ≤ 500 rectangle's height
0 < X < W the starting X position
0 < Y < H the starting Y position
0 ≤ D ≤ 10000 the damage sustained in each sector
Input
The first number given is the number of test cases. Each case will consist of a line with the integers E, X and Y. The following line will have the integers W and H. The following lines will hold the matrix containing the damage D the spacesuit will suffer whilst in the corresponding sector. Notice that, as is often the case for computer geeks, (1,1) corresponds to the upper left corner.
Output
If there is a solution, the output will be the remaining energy, the exit sector's X and Y coordinates and the number of steps of the route that will lead Rodericus to safety. In case there is no solution, the phrase Goodbye cruel world! will be written.
Sample Input
3
40 3 3
7 8
12 11 12 11 3 12 12
12 11 11 12 2 1 13
11 11 12 2 13 2 14
10 11 13 3 2 1 12
10 11 13 13 11 12 13
12 12 11 13 11 13 12
13 12 12 11 11 11 11
13 13 10 10 13 11 12
8 3 4
7 6
4 3 3 2 2 3 2
2 5 2 2 2 3 3
2 1 2 2 3 2 2
4 3 3 2 2 4 1
3 1 4 3 2 3 1
2 2 3 3 0 3 4
10 3 4
7 6
3 3 1 2 2 1 0
2 2 2 4 2 2 5
2 2 1 3 0 2 2
2 2 1 3 3 4 2
3 4 4 3 1 1 3
1 2 2 4 2 2 1
Sample Output
12 5 1 8
Goodbye cruel world!
5 1 4 2
Basically, I think we have to do a modified Dijkstra, in which the distance between nodes is the suit's energy (and we have to subtract it instead of suming up like is normal with distances) and the steps are the ....steps made along the path. The pos with the bester binomial (Energy,num_Steps) is our "way out".
Important : XPTO obviously can't move in diagonals, so we have to cut out this cases.
I have many ideas, but I have such a problem implementing them...
Could someone please help me thinking about this with some code or, at least, ideas?
Am I totally wrong?
Since this is a contest problem, I'll just give a small hint:
In this example, it's the nodes that have weight, not the edges. One way of converting such a graph to the usual kind is to replace each node with two nodes, an in node and an out node, and a directed edge from in to out with weight equal to the original node's weight. Then for each directed edge in the original graph, put a directed edge from the out node of one to the in node of the next.
Your idea sounds good - go with it.
By the way, when working these problems, try to work out the implementation for yourself. It rarely helps to simply see someone else's implementation. Ask for help on the algorithm if you need to, but implement it yourself.
You don't have to treat this with any unconventional conversions like you said (subtracting instead of adding, etc).
The shortest path from one node to another is one that minimizes the total damage to the suit along the way, regardless of whether or not this journey will kill you.
Just find the shortest path from START to EXIT, summing up edge weights as is usual Dijkstra approach, and then consider if this shortest path is feasible for the given suit power. If it isn't, then Goodbye cruel world!.
If you insist on pruning the search once you know that you can definitely not reach the EXIT, then adding it after the above implementation is trivial: as you're expanding your search horizon in your Dijkstra search, if even going to the next closest node to expand from kills you, then the rest of search space also will, so you can just abort and Goodbye cruel world!.
As for the graph itself, conceptually this is what you want. The vertices of the directed graph consists of all nodes in the grid, plus an artificial EXIT node.
All edge nodes have a directed edge to EXIT; the weight of these edges is 0
All neighboring (non-diagonal) node have directed edges between them
From node n1 to n2, the weight of the edge (i.e. the cost damage of travelling from n1 to n2) is the damage incurred by staying at node n2 (let's call this damageAt[n2], which you get from D matrix in input).
So minimum total amount of damage that one must sustain to go from START to EXIT is damageAt[START] + costOf(shortestPathBetween(START, EXIT)).
In summary, this approach:
Only requires standard Dijkstra implementation
Requires only very small modification to add pruning
Requires only very simple transformation from the input grid to the directed graph