Given a matrix of N * M. Find the minimum path sum in matrix. The minimum path is sum of all elements from first row to last row where you are allowed to move only down or diagonally to left or right. You can start from any element in first row.
I've written the code,but what is wrong in my code/logic?
here in my algorithm I am starting from the element of the top row, now I'm going to the second row and algorithm is finding the minimum value and add with the first element and thus it makes way to the bottom(a element can only add with the elment which is under it and also can move diagonally right and left)
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row, column, i, j,temp=0;
System.out.print("Please enter the desire grid dimension: ");
row = sc.nextInt();
column = sc.nextInt();
int array[][] = new int[row][column];
System.out.println("Please enter the desired input:");
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
array[i][j] = sc.nextInt();
}
}
for(i=1;i<row;i++){
for(j=0;j<column;j++){
array[i][j] += Math.min((j==0)?0:array[i-1][j-1],Math.min(array[i-1][j],(j==column-1)?0:array[i-1][j+1]));
}
}
for(i=0;i<row;i++){
for(j=0;j<column;j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
for(j=0;j<column-1;j++){
temp = Math.min(array[row-1][j],array[row-1][j+1]);
}
System.out.println(temp);
}
}
let your input is
1 5 1 5 1* 5
3 3 2 3 3* 4
2 3 4 4 3 2*
2 2 3 2 2* 4
2 2 4 3 4 2*
4 4 4 4 2* 3
your output should be 12,path is marked with(*) 1+3+2+2+2+2=12
I'm getting 3,because after running my algorithm the matrix became
1 5 1 5 1 5
3 4 3 4 4 4
2 6 7 7 7 2
2 4 9 9 4 4
2 4 8 7 8 2
4 6 8 11 4 3
I am not giving you a complete answer. You will learn more from finding out yourself. At the same time this will be more gratifying for you. So I will just guide you slightly on the way and trust you to do the rest yourself. It’s not that hard.
First, however, for other readers to follow what I write I need to give the explanation that you should have given in the question of how your algorithm was supposed to work. You are modifying the matrix in a way so that each cell instead of its original number gets to contain the minimum sum of a path from the top to that cell inclusive. For example:
We see from your matrix after the algorithm has run that the top line is unchanged. This is correct since you can go directly into each cell, so the sum is equal to the original cell value.
In the second line, the second (index 1) cell has been changed from 3 to 4. This is correct since to go to that cell we need to go through 1 or 5 or 1 in the first line. 1 gives the minimal sum, so 1 is added to 3, hence 4.
In the same line, the leftmost cell is unchanged 3. The is incorrect. To get to this cell you also need to go through either 1 or 5 in the first line, so this 3 too should have been changed to 4. I will give you one piece of information: the cell was not forgotten. Your loop assigns a value to the cell, only not the correct value. 1 should have been added, instead 0 was added. Where does this 0 come from? Your turn! Happy debugging.
Related
This is my code:
class Main{
public static void main(String args[]){
System.out.println("Enter the value of N: ");
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int max = 0, min = 0;
if(n1<=50){
for(int i=1;i<=n1;i++){
for(int j=1;j<=n1;j++){
max = n1*i;
min = (max-n1)+1;
if(i%2!=0){
while(max<=min){
System.out.print(max);
max--;
}
}
if(i%2==0){
while(min<=min){
System.out.print(min);
min++;
}
}
}
System.out.println("");
}
}
else
System.out.print("Invalid Value of n1");
}
}
the problem is to print a zigzag matrix like
if we enter n=4 then the output should be like:
4 3 2 1
5 6 7 8
12 11 10 9
13 14 15 16
and if we enter 3 it should come like
3 2 1
4 5 6
9 8 7
now in the above code its going to a infinite loop
Considering it is most likely some kind of a homework, I won't hand you a solution as it takes away the learning process. Instead, I'll just give you some hints.
You need 2 nested for loops, the outer one for rows and the inner one for columns.
Find out what the max and min numbers in a given row are. They are connected to the row number.
If the row number is odd, start with the max number and go down. If it is odd, start from the min number and go up.
Overview
I'm sure this is a simple problem for most of you on here, but I have been struggling with a small spacing problem and was hoping I can learn from someone more experienced. I need to produce a triangle similar to the one below. You can see that the numbers are aligned correctly no matter the length.
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
My Code
Here is what I have so far. It isn't the prettiest, but it seems to give me the correct values at least.
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
My Results
This is the console output when 6 rows are chosen. Everything looks good until row 5 when a 2 digit number (16) appears. What are some efficient ways to align the results properly?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
You calculate length as the number of digits in rows, but it needs to be number of digits in largest number in triangle.
E.g. for rows = 6, largest number is 32, so length should be 2.
For rows = 8, largest number is 128, so length should be 3.
Largest number is 2rows, which in Java means 1 << rows, so change length calculation to:
int length = ("" + (1 << rows)).length();
You are also adding one too many blanks on the left.
Change code to this:
a = rows - 1;
First of all i can recommend to determine the largest number in pyramid. Then count digits in this number. For 8 rows this number is 128, it has 3 digits. According this information we can decide that we need 3+1=4 (including spaces) characters to print every value in pyramid.
After it you have to complete every output number by spaces (from the left) to achive string size of 4 characters.
And the global prefix for every pyramid line will contain (rows - i) * 4 spaces.
I have some question below:
If there is a example database.txt as follow, how do I get the row number of certain number? For example, the number "1" appears in row 1, 3, 5, then i want to build an array which is [a]:[1 0 1 0 0 0 1], the 1 means item "1" appears in that row. Please Help!
Example Database.txt:
1 5
2 7
3 1
4 2
5 3
6 5
7 1
You would want to build a 2 dimensional array.
the array would be for example array[7][2]. Then you would assign the numbers to the following array.
After that you would make a method and have 2 for loops.
1 for loop will track the rows and the other will track columns.
public int arrayMethod(array[][] a)
for(int row=0; row <= a.length; row++){
for(int col=0; col<=a.length-1; col ++){
if(array[row][col]== 1)
{
return 1;
}
else return 0;
}
}
It should be something along the lines of this.
I have the layout for the pyramid set I just can't find out how I would combine or mathematically get the next few numbers. What I need is:
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
My code right now is:
int x = 7;
for (int i =1; i<=x; i++) {
for (int j =1; j<=x-i; j++) {
System.out.print(" ");
}
for (int k=1; k<=i;k++) {
System.out.printf("%2d",k);
}
for(int k=i-1; k>=1;k--) {
System.out.printf("%2d",k);
}
System.out.println(" ");
}
But my output comes out as:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
Sorry if this came out weird; this is my first question ever on this site. How can I modify my code to get the other pyramid?
Firstly, I presume you are trying to compute a Pascal triangle and that when you wrote that the desired output was:
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
you actually mean:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
because otherwise it doesn't make much sense.
Assuming you have made a slight error and the second triangle is the one you want then that is a Pascal's triangle. The rules for computing a Pascal triangle is to add the number above and to the left with the number above and to the right to find the new value.
Image credit Hersfold
You can quite easily write a recursive function that will do this. With a recursive function a good approach is to write your guards and base case, then recurse. This would look like:
private static int calculatePascalNumber(int row, int column)
{
if (row < 1 || column < 1 || column > row) {
return 0;
} else if (column == 1 || row == column) {
return 1;
} else {
return calculatePascalNumber(row - 1, column - 1) +
calculatePascalNumber(row - 1, column);
}
}
These are the rules for this function
if the row or column is less than 1 or the column is wider than the
row these are points outside of the triangle and should return 0
if the column is in one of the end columns (either column equals 1 or the row and column are equal) return 1
otherwise add the two numbers above to the left and the right
You could then call this function within your code that would look like
int x = 7;
for (int row = 1; row <= x; row++) {
for (int j =1; j<=x-row; j++) {
if (j % 2 == 0) {
System.out.print(" ");
} else {
System.out.print(" ");
}
}
for (int column=1; column<=row;column++) {
System.out.printf(" %2d", calculatePascalNumber(row, column));
}
System.out.println(" ");
}
I have revised it a little for formatting, if you wanted to put in further work the ouput formatting would be a good thing to look at.
Finally, it is worth noting performance. If you wanted to run this to compute values on large triangles the number of recursive calls would start making this function go very slowly. A possible way to resolve this would be to cache the results of calls to calculatePascalNumber so that when it is called with parameters it has already computed it returns the value from a hashmap/ array rather than running through all the computations multiple times.
Another option to speed this up for larger triangles is to use this function for calculating a row by itself which could lead to the following code for calculatePascalNumber
private static int calculatePascalNumber(int row, int column)
{
if (row < 0 || column < 0 || column > row) {
return 0;
} else if (column == 1) {
return 1;
} else {
return (calculatePascalNumber(row, column - 1)
* (row + 1 - column)) / (column - 1);
}
}
but what you gain with efficiency you lose with clarity.
I get some number from URL, if the number is b/w 1 to 4 then I want's the result to be 4, .. and number b/w 4 to 8 then I want result 8 ......And so on.
This is my code. and this is get from url in count value.
adltavailable = Integer.parseInt(count.get(i).toString());
for(int x =0; x<adltavailable; x++)
{
c = "Adultavailable";
category.add(c);
}
//Here is assign the table
int k = 0;
int size = category.size();
while(k < size)
{
for(int z=0; z<size; z++)
{
if(category.get(z).equals("Adultavailable"))
{
mycirimgs[k].setBackgroundResource(R.drawable.adultadd);
}
k++;
}
}
I get total seats value from url .And the value is assigned in table.If suppose i got 3 seats means I assign the table in 3 seats is not look like good.But this three seats assign 4 instead of 3.like wise.So I want the result If I get total seats 1 or 2 or 3 or 4 means I assign the table in 4 seats and 5 or 6 or 7 or 8 means I assign the table in 8 seats like wise. Thanks giving ur support.
I get some number from URL, if the number is b/w 1 to 4 then I want's the result to be 4, .. and number b/w 4 to 8 then I want result 8 ......And so on.
To round x to the next multiple of 4, write
(x + 3) & ~3
where + 3 rounds up and & ~3 clears the bottom two bits making it a multiple of 4.
To round up your input to the next multiple of 4, you can try the following:
Integer result;
if (input % 4 == 0) //Input is already a multiple of 4.
{
result = input
}
else // round up
{
result = ((input / 4) + 1)*4
}
Hope this is what you were looking for.