Matrix output issue java - java

Heres my code that displays i get no errors at all and it works but i have a little output issue with my thing
// Lab13TEXT03st.java
// This is the student starting version of the Lab13 assignment.
// Testing <main> methods are provided for the 80-point and 100-point versions.
// This means that this version will not compile as provided.
import java.util.ArrayList;
public class Lab13TEXT03st
{
public static void main(String[] args)
{
System.out.println("\nLAB26A 80-POINT VERSION\n");
Matrix m2 = new Matrix(3, 5, 100);
//m2.displayMatrix("Matrix m2 3 X 5 Display");
System.out.println();
int count = 100;
System.out.println("Matrix m1 Default Display"); //
System.out.println("Matrix has no elements"); //
System.out.println("");
int pos = 0;
for (int r = 0; r < m2.getRows(); r++)
{
//System.out.println("r = " + r); //
for (int c = 0; c < m2.getCols(); c++)
{
m2.setValue(r,c,count, pos);
pos++;
count++;
//System.out.println("r = " + r + " c = " + c + " and count = " + count); //
}
//System.out.println(""); //
}
m2.displayMatrix("Matrix m2 3 x 5 Consecutive Integers Display");
System.out.println();
Matrix m3 = new Matrix(3,3,100);
m3.displayMatrix("Matrix m3 3 X 3 Initialized to 100 Display");
System.out.println();
}
}
class Matrix {
private ArrayList list; // one-dimensional array stores matrix values
private int listSize; // total number of elements in the matrix
private int numRows; // number of rows in the matrix
private int numCols; // number of cols in the matrix
public Matrix(int r, int c, int value){
list = new ArrayList();
numRows = r;
numCols = c;
listSize = r * c;
//for(int i = 0; i < listSize; i++)
// list.add(new Integer(value));
}
public int getRows(){
return numRows;
}
public int getCols(){
return numCols;
}
public int getSize()
{
return listSize;
}
public int getValue(int r, int c)
{
int rowLength = getRows();
int colLength = getCols();
//System.out.println("r in get = " + r);
int position = (r * colLength) + c;
//int position = ((r + 1) * rowLength) - rowLength + c; // one to multi-dimensional array index conversion
//System.out.print("Pos get = " + position + "; ");
return ((Integer)list.get(position)).intValue();
}
public void setValue(int r, int c, int value, int pos)
{
int rowLength = getRows();
//int colLength = getCols();
//int position = ((r + 1) * rowLength) - rowLength + c; // one to multi-dimensional array index conversion
//System.out.println("Pos set = " + position + "; ");
list.add(pos,new Integer(value));
}
public void displayMatrix(String str)
{
System.out.println(str);
for(int j = 0; j < getRows(); j++){
for(int i = 0; i < getCols(); i++){
System.out.print(getValue(j, i) + " ");
}
System.out.println("");
}
}
}
My output is wrong and i need some help please
I get no errors... here is my output
LAB26A 80-POINT VERSION
Matrix m1 Default Display
Matrix has no elements
Matrix m2 3 x 5 Consecutive Integers Display
100 101 102 103 104
105 106 107 108 109
110 111 112 113 114
Matrix m3 3 X 3 Initialized to 100 Display
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at Matrix.getValue(Lab13TEXT03st.java:128)
at Matrix.displayMatrix(Lab13TEXT03st.java:147)
at Lab13TEXT03st.main(Lab13TEXT03st.java:49)
Process completed.
It needs to output like this though:
LAB13TEXT03 80-POINT VERSION
Matrix m1 Default Display
Matrix has no elements
Matrix m2 3 X 5 Display
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Matrix m2 3 X 5 Consecutive Integers Display
100 101 102 103 104
105 106 107 108 109
110 111 112 113 114
Matrix m3 3 X 3 Initialized to 100 Display
100 100 100
100 100 100
100 100 100
Please help

The second matrix (m3) fails because you haven't initialized it yet, as you did with m2. You never wrote something along the lines m3.setValue(...) in the code. Alternatively, for initializing the matrix with a default value, you need to uncomment these lines in the constructor of Matrix:
for(int i = 0; i < listSize; i++)
list.add(new Integer(value));

Related

Select two equally-sized disjoint subarrays, A and B, that maximise the sum (A_1*B_k + A_2*B_(k-1) ... + A_k*B_1), k = |A| = |B|

A food fest is organised at the JLN stadium. The stalls from different states and cities have been set up. To make the fest more interesting, multiple games have been arranged which can be played by the people to win the food vouchers.One such game to win the food vouchers is described below:
There are N number of boxes arranged in a single queue. Each box has an integer I written on it. From the given queue, the participant has to select two contiguous subsequences A and B of the same size. The selected subsequences should be such that the summation of the product of the boxes should be maximum. The product is not calculated normally though. To make the game interesting, the first box of subsequence A is to be multiplied by the last box of subsequence B. The second box of subsequence A is to be multiplied by the second last box of subsequence B and so on. All the products thus obtained are then added together.
If the participant is able to find the correct such maximum summation, he/she will win the game and will be awarded the food voucher of the same value.
Note: The subsequences A and B should be disjoint.
Example:
Number of boxes, N = 8
The order of the boxes is provided below:
1 9 2 3 0 6 7 8
Subsequence A
9 2 3
Subsequence B
6 7 8
The product of the subsequences will be calculated as below:
P1 = 9 * 8 = 72
P2 = 2 * 7 = 14
P3 = 3 * 6 = 18
Summation, S = P1 + P2 + P3 = 72 + 14 + 18 = 104
This is the maximum summation possible as per the requirement for the given N boxes.
Tamanna is also in the fest and wants to play this game. She needs help in winning the game and is asking for your help. Can you help her in winning the food vouchers?
Input Format
The first line of input consists of the number of boxes, N.
The second line of input consists of N space-separated integers.
Constraints
1< N <=3000
-10^6 <= I <=10^6
Output Format
Print the maximum summation of the product of the boxes in a separate line.
Sample TestCase 1
input
8
1 9 2 3 0 6 7 8
output
104
my code is this it is passing only one test can anyone tell me what is wrong and i don't have other test cases since they r hidden
import java.util.Scanner;
import java.util.*;
public class Main {
static class pair {
int first, second;
public pair(int first, int second) {
this.first = first;
this.second = second;
}
}
static int getSubarraySum(int sum[], int i, int j) {
if (i == 0)
return sum[j];
else
return (sum[j] - sum[i - 1]);
}
static int maximumSumTwoNonOverlappingSubarray(int arr[], int N,
int K) {
int l = 0, m = 0;
int a1[] = new int[N / 2];
int a2[] = new int[N / 2];
int prod = 0;
int[] sum = new int[N];
sum[0] = arr[0];
for (int i = 1; i < N; i++)
sum[i] = sum[i - 1] + arr[i];
pair resIndex = new pair(N - 2 * K, N - K);
int maxSum2Subarray =
getSubarraySum(sum, N - 2 * K, N - K - 1)
+ getSubarraySum(sum, N - K, N - 1);
pair secondSubarrayMax =
new pair(N - K, getSubarraySum(sum, N - K, N - 1));
for (int i = N - 2 * K - 1; i >= 0; i--) {
int cur = getSubarraySum(sum, i + K, i + 2 * K - 1);
if (cur >= secondSubarrayMax.second)
secondSubarrayMax = new pair(i + K, cur);
cur = getSubarraySum(sum, i, i + K - 1)
+ secondSubarrayMax.second;
if (cur >= maxSum2Subarray) {
maxSum2Subarray = cur;
resIndex = new pair(i, secondSubarrayMax.first);
}
}
for (int i = resIndex.first; i < resIndex.first + K; i++) {
a1[l] = arr[i];
l++;
}
for (int i = resIndex.second; i < resIndex.second + K; i++) {
a2[m] = arr[i];
m++;
}
for (int i = 0; i < m; i++) {
if (a1[i] != 0 || a2[i] != 0) {
prod = prod + a1[i] * a2[m - (i + 1)];
}
}
return prod;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int k = 0;
int arr[] = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
int l = arr.length;
int ar[] = new int[a / 2];
for (int i = 1; i <= a / 2; i++) {
ar[k] = maximumSumTwoNonOverlappingSubarray(arr, l, i);
k++;
}
Arrays.sort(ar);
System.out.println(ar[k - 1]);
}
}
Here's an O(n^2) time, O(1) space solution.
Lets write all O(n^2) multiples in a matrix. For example:
Input {1, 2, 3, -4, 5, 6}
1 2 3 -4 5 6
1 x 2 3 -4 5 6
2 x 6 -8 10 12
3 x -12 15 18
-4 x -20 -24
5 x 30
6 x
Now pick any indexes (i, j), i ≠ j, say (0, 5).
j
1 2 3 -4 5 6
i 1 x 2 3 -4 5 6
2 x 6 -8 10 12
3 x -12 15 18
-4 x -20 -24
5 x 30
6 x
Now imagine we wanted to find the best subarray where i was first, then second, then third, etc. of a valid selection. In each iteration, we would increment i and decrement j, such that we move on the diagonal: 6, 10, -12, each time adding the multiple to extend our selection.
We can do this on each of the diagonals to get the best selection starting on (i, j), where i is first, then second, then third, etc.
Now imagine we ran Kadane's algorithm on each of the diagonals from northeast to southwest (up to where the xs are where i = j). Complexity O(n^2) time. (There's Python code in one of the revisions.)
Here is the code
n=int(input())
l=[]
res=0
l=list(map(int,input().split()))
re=[]
while(True):
if(len(l)==2):
pass
break
else:
n1=l[1]
n2=l[-1]
re.append(n1*n2)
l.remove(n1)
l.remove(n2)
for i in re:
res=res+i
print(res)
#include <iostream>
#include <cassert>
using namespace std;
template<class T> inline void umax(T &a,T b){if(a<b) a = b ; }
template<class T> inline void umin(T &a,T b){if(a>b) a = b ; }
template<class T> inline T abs(T a){return a>0 ? a : -a;}
template<class T> inline T gcd(T a,T b){return __gcd(a, b);}
template<class T> inline T lcm(T a,T b){return a/gcd(a,b)*b;}
typedef long long ll;
typedef pair<int, int> ii;
const int inf = 1e9 + 143;
const ll longinf = 1e18 + 143;
inline int read()
{
int x;scanf(" %d",&x);
return x;
}
const int N = 20001;
int n;
int a[N];
void read_inp()
{
n = read();
assert(1 <= n && n <= 20000);
for(int i = 1; i <= n; i++)
{
a[i] = read();
assert(abs(a[i]) <= int(1e6));
}
}
int main()
{
#ifdef KAZAR
freopen("f.input","r",stdin);
freopen("f.output","w",stdout);
freopen("error","w",stderr);
#endif
read_inp();
ll ans = -longinf;
for(int i = 1; i <= n; i++)
{
{
int l = i - 1, r = i;
ll best = 0ll, cur = 0ll;
while(l >= 1 && r <= n)
{
ll val = (ll)a[l] * a[r];
cur += val;
umin(best, cur);
umax(ans, cur - best);
--l;
++r;
}
}
{
int l = i - 1, r = i + 1;
ll best = 0ll, cur = 0ll;
while(l >= 1 && r <= n)
{
ll val = (ll)a[l] * a[r];
cur += val;
umin(best, cur);
umax(ans, cur - best);
--l;
++r;
}
}
}
printf("%lld\n",ans);
return 0;
}
Here is the code
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int dp[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j==i)
dp[i][j]=0;
else if(j<i)
dp[i][j]=0;
else
dp[i][j]=arr[i]*arr[j];
}
}
cout<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<dp[i][j]<<" ";
cout<<endl;
}
cout<<endl;
//find max sum diagonal
long long int global_sum=0;
//get sum of diagonal increasing i
for(int i=0;i<n;i++)
{
long long int curr_sum=0;
int j=i;
int k=n-1;
while(k>=0 && j<n){
curr_sum+=dp[j][k];
k--;
j++;
}
if(curr_sum>global_sum) global_sum=curr_sum;
}
//get sum with decreasing i
for(int i=n-1;i>=0;i--){
long long int curr_sum=0;
int j=i;
int k=0;
while(k<n && j>=0){
curr_sum+=dp[j][k];
j--;
k++;
}
if(curr_sum>global_sum) global_sum=curr_sum;
}
cout<<global_sum;}
This code passes the testcase you gave and other testcases i tried myself. Its O(n^2) complexity.

Outer Loop isn't working (java)

I'm trying read a set of numbers from a file and then isolate the lines in between the first line (which lets us know how many lines will need to be worked on, in this case, 5) and the seventh line (mind you that this is just an example, the range of the lines will is subject to change) so that I can populate a list in the format of (0 1 98, 0 2 5, ...,4 3 15). Right now my code manages to get (0 1 98, 0 2 5, 0 3 16, 0 4 16) added into the list but not the rest. I'm not sure what I've done wrong. Any help would be much appreciated.
Example input:
5
0 1 98 2 5 3 16 4 16
1 0 13 2 47 3 3 4 40
2 0 71 1 51 3 43 4 30
3 0 20 1 94 4 46
4 0 1 1 10 2 28 3 15
2
2 3
2
0 1
public static void t() {
List<String> L = new ArrayList();
try {
BufferedReader f = new BufferedReader(new FileReader("graph.txt"));
String s = f.readLine();
int nodes = Integer.parseInt(s);
int c = -1;
int c1 = 2;
int c2 = 3;
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}
for (int i = 0; i < L.size(); i++) {
System.out.println(L.get(i));
}
} catch (Exception ex) {
System.out.println(ex);
}
}
You just need to reset your C variables within the outer loop.
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
// Declare the variables here, otherwise code is the same
int c = -1;
int c1 = 2;
int c2 = 3;
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}

Is there a way of not generating the same number with the method I'm using?

I have to print a bingo board by using a 2D array and the method I'm using makes logical sense but I can't seem ti figure out why it's still generating same numbers. Any thoughts? I've tried the arraylist but it's a 1D array, if theres a probability it can be a 2D can someone please help.
*****Updated, so i used a bit of everything and I'm still jammed.
package bingo.arrays.assignment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class bingoooooooooooooo {
public static void main(String[] args) {
int[][] card = new int[5][5];
display1(card);
}
public static void display1(int[][] card) {
int[] colm = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
int v = 1, z = 15;
int x = 10000;
List l = new ArrayList();
for (int i : colm) {
l.add(i);
}
Collections.shuffle(l);
//do {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
boolean numberFound = false;
while (!numberFound) {
int number1 = (int) (Math.random() * z) + v;
if (!checkNumber(number1, card, j)) {
break;
}
card[i][j] = number1;
System.out.print("|" + card[i][j]);
}
// if (card[i][j] > 25) {
// x++;
// }
}
v = v + 15;
z = z + 15;
System.out.println(" ");
}
//}while (true);
}
public static boolean checkNumber(int number, int[][] card, int j) {
for(int a = 0; a <= j; a++) {
if(card[i][a] == number) return false;
}
return true;
}
}
Basically, you have overlapping ranges, the number can fall within the range of 0 to z plus v. What's happening is a number is been generate in the very low range, but v isn't large enough to move it beyond the range of the previous set
For example...
z == 130, v == 13
(0.289 * 130) + 31 = 68
(0.304 * 130) + 31 = 70
(0.934 * 130) + 31 = 152
(0.85 * 130) + 31 = 141
(0.902 * 130) + 31 = 148
z == 145, v == 13
(0.731 * 145) + 46 = 152
(0.672 * 145) + 46 = 143
(0.016 * 145) + 46 = 48
(0.292 * 145) + 46 = 88
(0.35 * 145) + 46 = 96
You can see that numbers in both sets are overlapping with each other. The problem only gets worse as z get's larger, as it has more scope to generate overlapping numbers.
Now, I'm sure there's some really awesome mathamtical forumal you could use, but I'm to lazy (and dumb) for that, instead, I'd use a Set of some kind to generate a random series of 25 numbers. This will ensure that each value is unique
public static void display1(int[][] card) {
// Create the set
Set<Integer> numbers = new HashSet<>(5 * 5);
// Keep looping until we get 25 numbers
while (numbers.size() < 5 * 5) {
// Generate a random number
numbers.add((int)Math.round(Math.random() * 100));
}
// This is just because I'm lazy...
List<Number> listOfNumbers = new ArrayList<>(numbers);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
// Assign the value to the array...
card[i][j] = (int)listOfNumbers.remove(0);
}
}
// Add just for printing...you could do this in the previous loop
// but I just wanted to keep it clean...
for (int i = 0; i < card.length; i++) {
for (int j = 0; j < card[i].length; j++) {
System.out.printf("|%3d", card[i][j]);
}
System.out.println("|");
}
}
Which will print something like...
| 0| 2| 71| 9| 74|
| 16| 22| 87| 24| 28|
| 93| 30| 33| 40| 41|
| 42| 49| 50| 51| 52|
| 55| 56| 59| 60| 63|
Now, if you aren't to attached to the array, you can use something like...
int index = (row * 5 + col);
to calculate the index offset into the List for a given row/col
for (int i = 0; i < card.length; i++) {
for (int j = 0; j < card[i].length; j++) {
int index = (i * 5 + j);
System.out.printf("|%3d", listOfNumbers.get(index));
}
System.out.println("|");
}
Your problem seems to be you are only checking the previous number.
You need to loop through all of the numbers in the current section like this:
boolean numberFound = false;
while(!numberFound) {
int number1 = (int) (Math.random() * z) + v;
if(!checkNumber(number1, card, j)) break;
card [i][j]=number1;
System.out.print("|" + card[i][j]);
}
public static boolean checkNumber(int number, int[][] card, int j) {
for(int a = 0; a <= j; a++) {
if(card[i][a] == number) return false;
}
return true;
}

Pascal's triangle positioning

I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it.
Program 1
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
Program 2
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
int x = 1;
while (x < row - 1) {
System.out.print(" ");
x++;
}
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
x = i;
while (x < row - 1) {
System.out.print(" ");
x++;
}
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1 //(Notice this line is incorrectly positioned)
When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here:
import java.io.IOException;
import java.util.Scanner;
public class Main {
static double fact(int n) {
double result = 1;
for (double i = 1; i <= n; i++)
result *= i;
return result;
}
static double combine(int n, int r) {
return ((fact(n)) / (fact(n - r) * fact(r)));
}
static void pascalTriangle(int n) {
int n2 = n;
for (int i = 0; i < n; i++) {
for (int space = 8 * (n2 - 1); space >= 0; space--) {
System.out.printf(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%14.0f", combine(i, j));
System.out.printf(" ");
}
System.out.println();
n2--;
}
}
public static void main(String[] args)
throws IOException, InterruptedException {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Lines(n): ");
int n = sc.nextInt();
pascalTriangle(n);
System.out.println("Press any key to exit! ");
sc.nextByte();
}
}
Try this ...
Results:
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
1 7 21 35 35 21 7 1
import java.util.*;
public class HelloWorld {
static int binCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static void pascalTriangle(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j <= i; j++)
System.out.print(HelloWorld.binCoeff(i, j) + " ");
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Results: ");
HelloWorld.pascalTriangle(8);
}
}
/**
* #author Ranjith
*/
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i;
int x;
int n = 15; //number of rows
String newLine = System.getProperty("line.separator");
for (i = 0; i < n; i++) { //loop to adjust spacing
x = i;
while (x < n - 1) {
System.out.print(" ");
x++;
}
fib(i); //fibonacci function is called
System.out.print(newLine);
}
}
public static void fib(int num) { //fibonacci function
int[] febo = new int[100];
febo[0] = 0;
febo[1] = 1;
for (int i = 2; i < num; i++) {
febo[i] = febo[i - 1] + febo[i - 2];
}
for (int i = 0; i < num; i++) {
System.out.print(febo[i] + " ");
}
}
}
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5 8 13
0 1 1 2 3 5 8 13 21
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column.
arr[i][j] = arr[i][j-1] + arr[i-1][j];
Then you can position it in the upper left corner as follows:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8
1 3 6 10 15 21 28
1 4 10 20 35 56
1 5 15 35 70
1 6 21 56
1 7 28
1 8
1
Try it online!
public static void main(String[] args) {
int n = 9;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
// formatted output
for (int[] row : arr) {
for (int el : row) {
// formatting as a number with a trailing space
System.out.printf("%2d ", el); // two-digit number
// System.out.printf("%3d ", el); // three-digit number
// System.out.printf("%4d ", el); // four-digit number
}
System.out.println();
}
}
See also:
• Pascal's triangle 2d array - formatting printed output
• Print Pascal's Triangle
class pascal {
static void main(int n) {
int a[][] = new int[n][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
a[0][1] = 1;
int k = 5;
int p = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < n + 1; j++) {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
for (int i = 0; i < a.length; i++) {
for (p = n + -i; p > 0; p--) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
System.out.print(a[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Printing all Possible nCr Combinations in Java

I'm trying to print out all possibilities of nCr, which are the combinations when order doesn't matter. So 5C1 there are 5 possibilities: 1 , 2, 3, 4, 5. 5C2 there are 10 possibilities: 1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5.
I made functions that print what I want for r = 2, r = 3, and r = 4, and I sort of see the pattern, but I cant seem to make a working method for variable r:
public void printCombinationsChoose2(int n, int k) //for when k = 2
{
for (int a = 1; a < n; a++)
{
for (int b = a + 1; b <= n; b++)
{
System.out.println("" + a + " " + b);
}
}
}
public void printCombinationsChoose3(int n, int k) //for when k = 3
{
for (int a = 1; a < n - 1; a++)
{
for (int b = a + 1; b < n; b++)
{
for (int c = b + 1; c <= n; c++)
{
System.out.println("" + a + " " + b + " " + c);
}
}
}
}
public void printCombinationsChoose4(int n, int k) //for when k = 4
{
for (int a = 1; a < n - 2; a++)
{
for (int b = a + 1; b < n - 1; b++)
{
for (int c = b + 1; c < n; c++)
{
for (int d = c + 1; d <= n; d++)
{
System.out.println("" + a + " " + b + " " + c + " " + d);
}
}
}
}
}
public void printCombinations(int n, int k) //Doesn't work
{
int[] nums = new int[k];
for (int i = 1; i <= nums.length; i++)
nums[i - 1] = i;
int count = 1;
while (count <= k)
{
for (int a = nums[k - count]; a <= n; a++)
{
nums[k - count] = a;
for (int i = 0; i < nums.length; i++)
System.out.print("" + nums[i] + " ");
System.out.println();
}
count++;
}
}
So I think the layout of my last method is right, but I'm just not doing the right things, because when I call printCominbations(5, 2), it prints
1 2
1 3
1 4
1 5
1 5
2 5
3 5
4 5
5 5
when it should be what I said earlier for 5C2.
Edit
The last example was bad. This is a better one to illustrate what it's doing wrong: printCombinations(5, 3) gives this:
1 2 3
1 2 4
1 2 5
1 2 5
1 3 5
1 4 5
1 5 5
1 5 5
2 5 5
3 5 5
4 5 5
5 5 5
How do I get it to be:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
How about this:
public class Test {
public static void main(final String[] args) {
print_nCr(7, 4);
}
public static final void print_nCr(final int n, final int r) {
int[] res = new int[r];
for (int i = 0; i < res.length; i++) {
res[i] = i + 1;
}
boolean done = false;
while (!done) {
System.out.println(Arrays.toString(res));
done = getNext(res, n, r);
}
}
/////////
public static final boolean getNext(final int[] num, final int n, final int r) {
int target = r - 1;
num[target]++;
if (num[target] > ((n - (r - target)) + 1)) {
// Carry the One
while (num[target] > ((n - (r - target)))) {
target--;
if (target < 0) {
break;
}
}
if (target < 0) {
return true;
}
num[target]++;
for (int i = target + 1; i < num.length; i++) {
num[i] = num[i - 1] + 1;
}
}
return false;
}
}
The key to this solution for me was to look at the problem as a numbering system and you want to increase a number by one and every time you reach an upper bound, you just carry the excess to the left one and ... You just need to implement the increasing algorithm correctly...
The first point where your code deviates from the expectation is here:
...
1 2 5
1 2 5 <-- first bad output
1 3 5
...
So ask yourself three things:
What should have happened in that line of code with the given state of the variables?
Why doesn't do my code exactly that?
What must be changed to achieve that?
The answer for the first part is like this:
It should have incremented the 2 to 3 and it should have set the following numbers to
4, 5, ... similar to the initialisation of nums.
The second and third part is your part again.
BTW: When you come back because you need more help, please explain in detail what you have deduced so far and clean up and shorten the question quite a bit.
OK... What is the solution when we know we need loops, but not the number of them?? RECURSION...
You need to use a recursive implementation. Have this in mind: ANYTIME, you need loops but the number of the nested loops can only be known at runtime, based on the specific parameters of the problem, you should use recursive methods... I'll give you some time to try it yourself, I'll be back to give you the final implementation...
I have done it in c++
#include <iostream>
using namespace std;
#define ARR_LIMIT 100
int arr[ARR_LIMIT];
void _ncr(int N,int R, int n,int r , int start )
{
if(r>0)
{
for(int i = start ; i <= start + (n-r); i++)
{
arr[R-r] = i;
_ncr(N,R,N-i, r-1, i+1 );
}
}
else
{
for(int i=0;i<R;i++)
{
cout << arr[i] << " ";
if(i==R-1)
cout<<"\n";
}
}
}
void ncr(int n,int r)
{
//Error checking of parameters
bool error = false;
if( n < 1)
{
error = true;
cout<< "ERROR : n should be greater 0 \n";
}
if( r < 1)
{
error = true;
cout<< "ERROR : r should be greater 0 \n";
}
if(r > n)
{
error = true;
cout<< "ERROR : n should be greater than or equal to r \n";
}
// end of Error checking of parameters
if(error)
return;
else
_ncr(n,r,n,r,1);
}
int main()
{
int n,r;
cout << "Enter n : ";
cin >> n;
cout << "Enter r : ";
cin >> r;
ncr(n,r);
return 0;
}
The layout of function printCombination() seems wrong. The while loop will iterate two times, for count = 1 and count = 2.
When count = 1, only values in nums[0][here] will change, since in this case k - count = 1.
Hence,
1,2
1,3
1,4 and
1,5.
And when count = 2, only values in nums[here][1] will change, since here k - count = 0.
Hence
1,5
2,5
3,5
4,5 and
5,5

Categories