Java Integer Pyramid - java

I'm working on an assignment that asks a user to input an integer between 1-15 and then displays an integer pyramid for the number of rows they selected.
I have everything working, but if the number enters an integer greater than 10, I'm getting tripped up by the extra space needed for a double digit number. I've attached my code below. If anyone could provide a little help it would be greatly appreciated.
int lines = input.nextInt();
for (int row = 1; row <= lines; row++)
{
for (int column = 1; column <= lines - row; column++)
{
System.out.print(" ");
}
for (int num = row; num >= 1; num--)
{
System.out.print((num>=10)?+num:" "+num);
}
for (int num = 2; num <= row; num++)
{
System.out.print((num>=10)?+num:" "+num);
}
System.out.println();
}
With my current code, if the user entered 13, it would produce the following output:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 910
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
I just need to figure out how to get the extra space for the double digit integers. The desired output would be:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12

It looks like you have chosen to do this the (slightly) harder way.
The easy way would be to reserve three spaces for each number (so that single digit numbers would have two spaces between them).
What you have chosen to do is variable spacing depending on the actual length of the numbers in each column. The first step is to change your output statements to the following:
System.out.print(" "+num);
So you will always print one space between numbers on each row. If you run that, you'll notice that it almost works except the top part of the triangle is misaligned. To fix that, you'll have to adjust your
System.out.print(" ");
statement so that the number of spaces it prints in each column depends on the value of the number that will appear in each column later on. To do this, you'll have to work out some arithmetic involving column and lines, to choose between " " (two spaces) and " " (three spaces). It's straightforward but I'll let you work out the details.
It is possible to further extend this idea to support 100 lines or more, but it's not clear that you need that capability.

I was interested in solving this, so wrote a simple solution for your task. Seems to work for any lines value.
public static void main(String[] args) {
int lines = 100;
for (int row = 1; row <= lines; row++) {
for (int i = 0; i < calculateOffset(row, lines); i++) {
System.out.print(" ");
}
System.out.print(row);
for (int num = row-1; num >= 1; num--) {
System.out.print(" " + num);
}
for (int num = 2; num <= row; num++) {
System.out.print(" " + num);
}
System.out.println();
}
}
private static int calculateOffset(int row, int totalRows) {
return calculateSpace(totalRows) - calculateSpace(row);
}
private static int calculateSpace(int columnsCount) {
int categoryLowest = 1;
int categoryHighest = 9;
int categoryDigits = 1;
int charactersUsed = 0;
while (categoryLowest <= columnsCount) {
int categoryItems = Math.min(categoryHighest, columnsCount) - categoryLowest + 1;
int numbersCharacters = categoryDigits * categoryItems;
int spacesCharacters = (categoryItems - 1);
boolean previousCategoryIncluded = categoryLowest > 1;
int spaceBetweenCategoriesPresent = previousCategoryIncluded ? 1 : 0;
charactersUsed += numbersCharacters + spacesCharacters + spaceBetweenCategoriesPresent;
categoryHighest = categoryHighest * 10 + 9;
categoryLowest *= 10;
categoryDigits++;
}
return charactersUsed;
}

No idea why you chose the logic like that. However, intuitively, this is what I am going to do:
1 find mid point location (you can simply contruct the last line and find the mid-point)
2 a function to construct a line, by simply do (psuedo-code):
String getLine(int num) {
String result = "";
for (int i = num; i > 0; i--) {
result = result + i + " ";
}
for (int i = 2; i <= num; i++) {
result = result + i + (i == num? "" : " ");
}
return result;
}
3 do a loop to print each line:
int midPoint = .....; //
for (i=0; i < num; i++) {
String line = getLine(i+1);
print (midPoint - mid point of line) spaces;
print line
}
Update:
Have briefly tested, looks good to me:
public static String getLine(int num) {
String result = "";
for (int i = num; i > 0; --i) {
result = result + i + " ";
}
for (int i = 2; i <= num; ++i) {
result = result + i + (i == num ? "" : " ");
}
return result;
}
public static void main(String[] args) {
int num = 15;
int midPoint = getLine(num).length()/2 + 1;
for (int i = 0; i < num; ++i) {
String line = getLine(i+1);
int noPrefix = midPoint - (line.length()+1)/2 ;
for (int j = 0; j < noPrefix; ++j) {
System.out.print(" ");
}
System.out.println(line);
}
}
result :
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Late to the party, but here's a solution using StringBuilder and printing it out only at the end.
The idea is to calculate the amount of padding required based on the String equivalent of the current value.
Note: The solution is not efficient (with all the conversion to String), but it can be used for any input value.
Working Example:
import java.util.Scanner;
public class IntegerPyramid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter # of lines: ");
int numLines = sc.nextInt();
StringBuilder sb = new StringBuilder();
System.out.println();
for(int row = 1; row <= numLines; row++) {
for(int num = -numLines; num <= numLines; num++) {
if(num == -1 || num == 0)
continue;
int value = Math.abs(num);
int padding = String.valueOf(value).length() + 1;
if(value <= row) {
// Print numbers
sb.append(String.format(("%" + padding + "d"), value));
}
else {
// Print spaces
sb.append(String.format(("%" + padding + "s"), ""));
}
}
sb.append("\n");
}
System.out.println(sb.toString());
sc.close();
}
}
Output:
Enter # of lines: 6
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Enter # of lines: 15
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

You've got the conditional backwards, believe it should be
System.out.print((num >= 10) ? " " + num : num)
Easier to understand
System.out.print((num < 10) ? num : num : " " + num)

Related

half pyramid inverted with matrix pattern

how to create a half pyramid inverted with matrix pattern like this with loop?
expected output
5 5 5 5 5 4 3 2 1
5 4 4 4 4 3 2 1
5 4 3 3 3 2 1
5 4 3 2 2 1
5 4 3 2 1
my code like this
public static void main(String[] args) {
int N = 5;
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
int min = i < j ? i : j;
System.out.print(N - min + 1 + " ");
}
for (int k = N-1; k >=1; k --) {
System.out.print(k + " ");
}
System.out.println();
}
}
and my output like this
5 5 5 5 5 4 3 2 1
5 4 4 4 4 4 3 2 1
5 4 3 3 3 4 3 2 1
5 4 3 2 2 4 3 2 1
5 4 3 2 1 4 3 2 1
Your nested loops needs to be 3 deep:
Loop over the rows:
5 5 5 5 5 4 3 2 1 ┐
5 4 4 4 4 3 2 1 ┤
5 4 3 3 3 2 1 ┤ Loop 1
5 4 3 2 2 1 ┤
5 4 3 2 1 ┘
Loop over the number values:
┌─────┬─┬─┬─┐ Loop 2
┌───┴───┐
5 5 5 5 5 4 3 2 1
5 4 4 4 4 3 2 1
5 4 3 3 3 2 1
5 4 3 2 2 1
5 4 3 2 1
└─┴─┴─┴─┘ Loop 2
Loop over the repeats of a number value:
┌─────...
┌─┬─┼─┬─┐ Loop 3
5 5 5 5 5 4 3 2 1
5 4 4 4 4 3 2 1
5 4 3 3 3 2 1
5 4 3 2 2 1
5 4 3 2 1
Good luck coding that, since it looks like an assignment that you need to complete.
Since I can't leave a simple challenge like that alone, here is a solution. I added logic so it can handle pyramid sizes above 9, and then compressed the code to obscure it a bit.
static void printHalfPyramidInverted(int n) {
String f, fmt = " %" + Integer.toString(n).length() + "d";
for (int k, j, i = n; i > 0; i--, System.out.println())
for (f = fmt.substring(1), j = n; j > 0; j--)
for (k = (i == j ? j : 1); k > 0; k--, f = fmt)
System.out.printf(f, j);
}
Output (size 5)
5 5 5 5 5 4 3 2 1
5 4 4 4 4 3 2 1
5 4 3 3 3 2 1
5 4 3 2 2 1
5 4 3 2 1
Output (size 9)
9 9 9 9 9 9 9 9 9 8 7 6 5 4 3 2 1
9 8 8 8 8 8 8 8 8 7 6 5 4 3 2 1
9 8 7 7 7 7 7 7 7 6 5 4 3 2 1
9 8 7 6 6 6 6 6 6 5 4 3 2 1
9 8 7 6 5 5 5 5 5 4 3 2 1
9 8 7 6 5 4 4 4 4 3 2 1
9 8 7 6 5 4 3 3 3 2 1
9 8 7 6 5 4 3 2 2 1
9 8 7 6 5 4 3 2 1
Output (size 15)
15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 14 14 14 14 14 14 14 14 14 14 14 14 14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 13 13 13 13 13 13 13 13 13 13 13 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 12 12 12 12 12 12 12 12 12 12 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 11 11 11 11 11 11 11 11 11 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 10 10 10 10 10 10 10 10 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 9 9 9 9 9 9 9 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 8 8 8 8 8 8 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 7 7 7 7 7 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 6 6 6 6 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 5 5 5 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 4 4 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 3 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
You could start constructing from bottom and notice how middle is changed (added i at i times).Each line is assembled from right to left.(adapted properly on the end) Using additional data structure can make some task easier.
public class TestPyramid {
public static void main(String[] args) {
int N = 6;
int next = N;
List<String> list = new ArrayList<String>();
for(int i=1;i<=N;i++)
{
List<Integer> line=new ArrayList<Integer>();
for(int j=1;j<=N;j++)
{
//middle
if(next-N+2==j)
{
for(int k=1;k<next-N+1;k++)
{
line.add(i);
}
}
line.add(j);
}
if(i==N)
{
for(int k=1;k<next-N+1;k++)
{
line.add(i);
}
}
next++;
String adaptedLine = line.stream().map(t->String.valueOf(t)).collect(Collectors.joining(" "));
StringBuilder sb = new StringBuilder(adaptedLine);
list.add(sb.reverse().toString());
}
Collections.reverse(list);
list.forEach(System.out::println);
}
}
Output:
6 6 6 6 6 6 5 4 3 2 1
6 5 5 5 5 5 4 3 2 1
6 5 4 4 4 4 3 2 1
6 5 4 3 3 3 2 1
6 5 4 3 2 2 1
6 5 4 3 2 1
Note: If N>=10 then reverse line should be adapted properly since 10 is 01 in current version
String adaptedLine = line.stream().
sorted(Collections.reverseOrder()).
map(t>String.valueOf(t)).
collect(Collectors.joining(" "));

TRIANGLE ALGORITHM [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
1
2 3
4 5 4
3 2 1 2
3 4 5 4 3
I want to make a triangle like that. I have tried making the triangle and the numbers but the numbers doesn't fit the triangle so the output isn't as expected. Please help.
Example input: n = 5;
1) This is the code to make the triangle.
int k = 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j <= i) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
2) This is the code to make the numbers.
int k = 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i % 2 == 0) {
if (k == 5) {
break;
}
System.out.print(k + " ");
k++;
} else if (i % 2 != 0) {
if (k == 1) {
break;
}
System.out.print(k + " ");
k--;
}
}
}
We need to print a number of rows, with each row printed having the same number of values as the row number. If we were printing *'s, it would be easy:
static void printTriangle(int rowCount) {
for (int row = 1; row <= rowCount; row++) {
for (int i = 0; i < row; i++)
System.out.print("* ");
System.out.println();
}
}
printTriangle(5)
*
* *
* * *
* * * *
* * * * *
Instead of printing *'s, we want the values to come from a repeating sequence of 1 2 3 4 5 4 3 2 ....
The sequence is 8 long, so if we take an ever-increasing number a, starting at 0, and calculate remainder when dividing by 8, i.e. b = a % 8, we get a repeating sequence of 0 1 2 3 4 5 6 7 .... If we then calculate distance from 4, using c = Math.abs(4 - b), we get 4 3 2 1 0 1 2 3 .... If we subtract that from 5, i.e. d = 5 - c, we get 1 2 3 4 5 4 3 2 ..., i.e. the desired sequence.
static void printTriangle(int rowCount) {
int a = 0;
for (int row = 1; row <= rowCount; row++) {
for (int i = 0; i < row; i++) {
int b = a % 8;
int c = Math.abs(4 - b);
int d = 5 - c;
System.out.print(d + " ");
a++;
}
System.out.println();
}
}
The code can be reduced to:
static void printTriangle(int rowCount) {
for (int seq = 0, row = 1; row <= rowCount; row++) {
for (int i = 0; i < row; i++, seq++)
System.out.print((5 - Math.abs(4 - seq % 8)) + " ");
System.out.println();
}
}
printTriangle(10)
1
2 3
4 5 4
3 2 1 2
3 4 5 4 3
2 1 2 3 4 5
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
4 3 2 1 2 3 4 5 4 3
For the advanced version, we can make the max value printed be dynamic too:
static void printTriangle(int rowCount, int maxValue) {
String fmt = "%" + String.valueOf(maxValue).length() + "s ";
for (int row = 1, seq = 0; row <= rowCount; row++) {
for (int i = 0; i < row; i++, seq++)
System.out.printf(fmt, (maxValue - Math.abs(maxValue - 1 - seq % (maxValue * 2 - 2))));
System.out.println();
}
}
printTriangle(5, 5)
1
2 3
4 5 4
3 2 1 2
3 4 5 4 3
printTriangle(20, 14)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 13
12 11 10 9 8 7
6 5 4 3 2 1 2
3 4 5 6 7 8 9 10
11 12 13 14 13 12 11 10 9
8 7 6 5 4 3 2 1 2 3
4 5 6 7 8 9 10 11 12 13 14
13 12 11 10 9 8 7 6 5 4 3 2
1 2 3 4 5 6 7 8 9 10 11 12 13
14 13 12 11 10 9 8 7 6 5 4 3 2 1
2 3 4 5 6 7 8 9 10 11 12 13 14 13 12
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6
7 8 9 10 11 12 13 14 13 12 11 10 9 8 7 6 5
4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 13
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 10 11 12 13 14 13 12 11 10 9 8 7 6 5 4 3 2 1 2

Trouble formatting with 2-dimensional array matrices

I need my matrices to look exactly like this.(with numbers lined up under text)
Here are the two matrices, and the result when added:
2 2 7 4 3 4 3 3 5 6 10 7
4 4 8 8 6 8 5 5 10 12 13 13
1 9 3 7 6 8 6 9 7 17 9 16
2 3 2 9 + 4 4 7 1 = 6 7 9 10
2 9 1 1 9 8 2 5 11 17 3 6
6 1 8 4 4 8 2 2 10 9 10 6
The results I am currently getting look like.
Here are the two matrices, and the result when added:
8 5 6 6 3 8 2 3 11 13 8 9
7 7 4 5 4 9 2 1 11 16 6 6
9 4 4 8 5 1 1 1 14 5 5 9
4 2 7 7 + 7 9 1 3 = 11 11 8 10
4 3 5 3 5 6 8 7 9 9 13 10
4 2 2 1 3 9 5 5 7 11 7 6
As you can see the code for the arrays sum is shifted to the right, and I am not quite sure how to fix this.
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
if (arithmetic == '+') {
// Text for two matrices when added
System.out.print("Here are the two matrices, and the result when added:\n");
// For loop to print array1 + array2 = sum with format
for (int i = 0; i < array1.length; i++) {
// For loop to print out array 1 and add string, if to place +
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%4s", array1[i][j]);
if (i == array1.length / 2 && j == array1[i].length-1) {
System.out.printf("%4s", '+');
}
}
System.out.print("\t");
// For loop to print out array2 and equals string, if to place =
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%2s", array2[i][j] + " ");
if (i == array1.length / 2 && j == array1[i].length-1) {
System.out.printf("%1s", '=');
}
}
System.out.print(" ");
// For loop to print out sum of array1 + array2
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%4s", sum[i][j]);
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
Also a 3x3 array when printed out looks like.
Here are the two matrices, and the result when added:
2 2 7 3 4 3 5 6 8
4 4 8 + 6 8 5 = 7 9 13
1 9 3 6 8 6 7 7
I think this is meant to insure that numbers, when printed, always take up 2 spaces:
System.out.printf("%2s", array2[i][j] + " ");
But because of the added (technically, concatenated) " ", you get a string that is bigger than the %2s field, so there is no padding of short numbers.
Plus, you have code to decide when to print the + & =, but each should be deciding between printing the symbol and printing a space, to keep everything lined up.

How do I make this table 0-9 with loops in Java?

How do I make this table?
This is what should be the outcome:
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 0
2 3 4 5 6 7 8 9 0 1
3 4 5 6 7 8 9 0 1 2
4 5 6 7 8 9 0 1 2 3
5 6 7 8 9 0 1 2 3 4
6 7 8 9 0 1 2 3 4 5
7 8 9 0 1 2 3 4 5 6
8 9 0 1 2 3 4 5 6 7
9 0 1 2 3 4 5 6 7 8
And this is the best I could come up with:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++) {
if (i + j < 10) {
System.out.print(i + j);
} else
System.out.print("x");
}
System.out.println();
}
}
}
I simply can't find a solution how to get numbers running again past 9 with the beginning of 0,1,2,3 etc. My code would generate next:
0123456789
123456789x
23456789xx
3456789xxx
456789xxxx
56789xxxxx
6789xxxxxx
789xxxxxxx
89xxxxxxxx
9xxxxxxxxx
You can do:
System.out.print((i + j) % 10);
To turn 10 into 0, 11 into 1, etc.
Try this:
for (int i=0; i<10; i++) {
for (int j=i; j<i+10; j++) {
System.out.print(j%10);
}
System.out.println();
}
The key here is to use %(modulo) operator.

How to find 3 numbers in all combinations possible that in a sum the result equals n?

I am working in an Authomata and need three numbers that suumed equal n
For example, if n = 2 the numbers I need are:
200
020
002
110
101
011
It doesn´t matter if the combination are repeated.
If n = 3 I need:
300
030
003
210
201
021
120
012
102
111
So I read thar this was similar to the partition in the theory of numbers but I can get the particular case where only 3 numbers give me the target value (n). (The code is from a example I get here)
package automata2;
import java.util.ArrayList;
/**
*
* #author jaime
*/
public class Automata2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int N = 14;
partition(N);
}
public static void partition(int n) {
partition(n, n, "");
}
public static void partition(int n, int max, String prefix) {
if (n == 0) {
System.out.println(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--) {
partition(n-i, i, prefix + " " + i);
}
}
}
But I only need al the combinations with three digits, not all since 14 until 1 1 1 1 1 1 1 1 1 1 1 1 1 1
The algorithm is like this to generate the numbers. This code will generate all nos.
public class main1 {
public static void main(String args[]) {
int N = 5, n1, n2, n3;
for (n1 = 0; n1 <= N; n1++) {
for (n2 = 0; n2 <= N; n2++) {
for (n3 = 0; n3 <= N; n3++) {
if ( (n1+n2+n3)==N ) {
System.out.println(n1 + " " + n2 + " " + n3);
}
}
}
}
}
}
what you can do is instead of System.out.println(n1+" "+n2+" "+n3), you can store the numbers in an array list then arrange the list.
One solution is to check number of numbers is three and then print it
public static void main(String[] args) {
int N = 14;
partition(N);
}
public static void partition(int n) {
partition(n, n, "");
}
public static void partition(int n, int max, String prefix) {
// added condition here
if (n == 0 && prefix.trim().split(" ").length == 3) {
System.out.println(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--) {
partition(n-i, i, prefix + " " + i);
}
}
Output :
12 1 1
11 2 1
10 3 1
10 2 2
9 4 1
9 3 2
8 5 1
8 4 2
8 3 3
7 6 1
7 5 2
7 4 3
6 6 2
6 5 3
6 4 4
5 5 4
Using nested loops - only for 3 number solution
int N = 14;
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= N; j++) {
for (int k = 0; k <= N; k++) {
if (i + j + k == N) {
System.out.println(i + " " + j + " " + k);
}
}
}
}
Output :
0 0 14
0 1 13
0 2 12
0 3 11
0 4 10
0 5 9
0 6 8
0 7 7
0 8 6
0 9 5
0 10 4
0 11 3
0 12 2
0 13 1
0 14 0
1 0 13
1 1 12
1 2 11
1 3 10
1 4 9
1 5 8
1 6 7
1 7 6
1 8 5
1 9 4
1 10 3
1 11 2
1 12 1
1 13 0
2 0 12
2 1 11
2 2 10
2 3 9
2 4 8
2 5 7
2 6 6
2 7 5
2 8 4
2 9 3
2 10 2
2 11 1
2 12 0
3 0 11
3 1 10
3 2 9
3 3 8
3 4 7
3 5 6
3 6 5
3 7 4
3 8 3
3 9 2
3 10 1
3 11 0
4 0 10
4 1 9
4 2 8
4 3 7
4 4 6
4 5 5
4 6 4
4 7 3
4 8 2
4 9 1
4 10 0
5 0 9
5 1 8
5 2 7
5 3 6
5 4 5
5 5 4
5 6 3
5 7 2
5 8 1
5 9 0
6 0 8
6 1 7
6 2 6
6 3 5
6 4 4
6 5 3
6 6 2
6 7 1
6 8 0
7 0 7
7 1 6
7 2 5
7 3 4
7 4 3
7 5 2
7 6 1
7 7 0
8 0 6
8 1 5
8 2 4
8 3 3
8 4 2
8 5 1
8 6 0
9 0 5
9 1 4
9 2 3
9 3 2
9 4 1
9 5 0
10 0 4
10 1 3
10 2 2
10 3 1
10 4 0
11 0 3
11 1 2
11 2 1
11 3 0
12 0 2
12 1 1
12 2 0
13 0 1
13 1 0
14 0 0
One by one checking with skipping unnecessary partitions.
public static void main(String[] args) {
int n =14;
ArrayList<String> temp = partition(n);
for (int z =0; z<temp.size(); z++){
System.out.println(temp.get(z));
}
}
public static ArrayList<String> partition(int n){
ArrayList<String> out = new ArrayList<String>();
int a=0, b=0, c=0;
for (c=n; c>=0; c--){
for(int j =a; j<=n;j++){
if((c+j)>n){
j=n+1;
continue;
}
for (int i=b;i<=n; i++){
int p=c+j+i;
if (p>n) i=n+1;
if(p==n){
String s = Integer.toString(c)+" "+ Integer.toString(j)+" "+ Integer.toString(i);
out.add(s);
}
}
}
}
return out;
}
Out put:
14 0 0
13 0 1
13 1 0
12 0 2
12 1 1
12 2 0
11 0 3
11 1 2
11 2 1
11 3 0
10 0 4
10 1 3
10 2 2
10 3 1
10 4 0
9 0 5
9 1 4
9 2 3
9 3 2
9 4 1
9 5 0
8 0 6
8 1 5
8 2 4
8 3 3
8 4 2
8 5 1
8 6 0
7 0 7
7 1 6
7 2 5
7 3 4
7 4 3
7 5 2
7 6 1
7 7 0
6 0 8
6 1 7
6 2 6
6 3 5
6 4 4
6 5 3
6 6 2
6 7 1
6 8 0
5 0 9
5 1 8
5 2 7
5 3 6
5 4 5
5 5 4
5 6 3
5 7 2
5 8 1
5 9 0
4 0 10
4 1 9
4 2 8
4 3 7
4 4 6
4 5 5
4 6 4
4 7 3
4 8 2
4 9 1
4 10 0
3 0 11
3 1 10
3 2 9
3 3 8
3 4 7
3 5 6
3 6 5
3 7 4
3 8 3
3 9 2
3 10 1
3 11 0
2 0 12
2 1 11
2 2 10
2 3 9
2 4 8
2 5 7
2 6 6
2 7 5
2 8 4
2 9 3
2 10 2
2 11 1
2 12 0
1 0 13
1 1 12
1 2 11
1 3 10
1 4 9
1 5 8
1 6 7
1 7 6
1 8 5
1 9 4
1 10 3
1 11 2
1 12 1
1 13 0
0 0 14
0 1 13
0 2 12
0 3 11
0 4 10
0 5 9
0 6 8
0 7 7
0 8 6
0 9 5
0 10 4
0 11 3
0 12 2
0 13 1
0 14 0
import java.util.Scanner;
public class ExampleMinNumber {
public static void main(String args[])
{
System.out.println("enter number which comibnation of sum you want");
Scanner input=new Scanner(System.in);
int num=input.nextInt();
for(int i=0;i<=3;i++)
{
int sum=0;
for(int j=0;j<=3;j++)
{
for(int k=0;k<=3;k++)
{
sum=i+j+k;
if(sum==num)
{
System.out.println(+i+""+j+""+k);
}
}
}
}
input.close();
}
}

Categories

Resources