i want devide matrix into four sub-blocks equally by vertically and horizontallty in java (Here, we suppose that m and nare even numbers) .
for example we have matrix:
1 2 3 4 5 6
7 8 9 1 2 8
1 2 3 4 5 6
4 5 6 7 8 9
1 4 7 2 5 8
3 6 9 7 2 5
I want to display the last block that is:
7 8 9
2 5 8
7 2 5
how i can resolve this problem in java.
Iterate over the lower-right part of the matrix. Here is an example for a square matrix. I am sure you will be able to make it more generic for non-square quadrants or to get other quadrants than the lower-right one.
public int[][] getQuadrantOfSquareMatrix(int[][] matrix) {
int newDimension = matrix.length / 2;
int[][] toReturn = new int[newDimension][newDimension];
for (int i = 0; i < newDimension; i++) {
for (int j = 0; j < newDimension; j++) {
toReturn[i][j] = matrix[i + newDimension][j + newDimension];
}
}
return toReturn;
}
I am trying to implement in Eclipse Java Levenshtein distance on the following two strings:
I took the idea from Wikipedia, but I don't know why my output is wrong, I need help to find my mistake/s.
"kruskal"
"causal"
package il.ac.oranim.alg2016;
public class OPT {
public static void main(String[] args)
{
char[] t={'k','r','u','s','k','a','l'};
char[] s={'c','a','u','s','a','l'};
for (int i=0;i<=s.length;i++)
{
for (int j=0;j<=t.length;j++)
System.out.print(LevenshteinDistance(s,t)[i][j]+" ");
System.out.println();
}
}
private static int[][] LevenshteinDistance(char s[], char t[])
{
// d is a table with m+1 rows and n+1 columns
int[][] d=new int[s.length+1][t.length+1];
for (int i=0;i<=s.length;i++)
d[i][0] = i; // deletion
for (int j=0;j<=t.length;j++)
d[0][j] = j; // insertion
for (int j=1;j<t.length;j++)
{
for (int i=1;i<s.length;i++)
{
if (s[i] ==t[j])
d[i][j]=d[i-1][j-1];
else
d[i][j] = Math.min(Math.min((d[i-1][ j] + 1),
(d[i][j-1] + 1)),
(d[i-1][j-1] + 1)) ;
}
}
return d;
}
}
My output:
0 1 2 3 4 5 6 7
1 1 2 3 4 4 5 0
2 2 1 2 3 4 5 0
3 3 2 1 2 3 4 0
4 4 3 2 2 2 3 0
5 5 4 3 3 3 2 0
6 0 0 0 0 0 0 0
The output should be:
0 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 2 3 4 5 5 6
3 3 3 2 3 4 5 6
4 4 4 3 2 3 4 5
5 5 5 4 3 3 3 4
6 6 6 5 4 4 4 3
If you reread the specifications, you will find there are two errors:
on the wikipedia, they use indices ranging from 1 to (and including n), a string starts at index i=1 according to Wikipedia where it is i=0 in Java; and
the weights are not updated correctly:
if (s[i] ==t[j])
d[i][j]=d[i-1][j-1];
In the specifications, this should be the minimum of d[i-1][j]+1, d[i][j-1]+1 and d[i-1][j-1]. It is not guaranteed that d[i-1][j-1] is the lowest value, so you should effectively calculate it.
If one takes these mistakes into account, one can modify the table update algorithm (changes on comment //):
for (int j=1;j<=t.length;j++) { //use <= instead of <
for (int i=1;i<=s.length;i++) { //use <= instead of <
if (s[i-1] ==t[j-1]) //use i-1 and j-1
d[i][j] = Math.min(Math.min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]); //use the correct update
else
d[i][j] = Math.min(Math.min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]+1);
}
}
I am writing a Java algorithm which gets each of six players in a game to roll a dice and the highest roll takes the first turn and so on. I have already written the dice rolling method which takes in a map of players in the form of <String playerName, Player player>, and gets each player to roll the dice, where player is a class storing many player attributes necessary for the game.
The problem I am having trouble overcoming when ordering the players is that if two players roll the same number, they then roll again in order to see who goes ahead of the other. Here is an example scenario:
Position: Player (number rolled)
1: Tom (5)
2: Jerry (4)
=3: Jack (3)
=3: Jill (3)
5: Harry (2)
6: Ron (1)
So Jack and Jill roll again. Jack rolls a 6 and Jill rolls a 3. Jack is now in 3rd position and Jill in 4th.
Any strategy I have began to write quickly becomes seemingly overly complicated and very untidy and difficult to read. This is due to having to check if there are any duplicate rolls at any number, all while storing every roll in the correct order, allowing for two or more positions if there is a duplicate roll.
Can anyone come up with a neat structure in which this order can be determined and stored?
Each instance of Player, has a nextPlayer variable that will point to the player in the position after them. It would probably be best to also store numberRolled in the class too. Any players who roll the same number can be stored in a new map and then passed into the rollDice method again.
EDIT
Thanks to Andy Turner, here is my solution:
private Player[] playerOrder = new Player[ModelConstants.NUM_PLAYERS_PLUS_NEUTRALS];
playerOrder = getPlayerOrder();
Player[] getPlayerOrder() {
Player[] players = ModelConstants.PLAYERS.values().toArray(new Player[ModelConstants.PLAYERS.size()]);
String[] playerNames = ModelConstants.PLAYERS.keySet().toArray(new String[ModelConstants.PLAYERS.size()]);
getPlayerOrder(playerNames, players, 0, players.length);
return players;
}
void getPlayerOrder(String[] playerNames, Player[] players, int start, int end) {
// Get all players between players[start] (inclusive) and
// players[end] (exclusive) to re-roll the dice.
for (int i = start; i < end; ++i) {
players[i].setDiceNumberRolled(rollDice(playerNames[i], players[i]));
}
// Sort this portion of the array according to the number rolled.
Arrays.sort(players, start, end, new Comparator<Player>() {
#Override public int compare(Player a, Player b) {
return Integer.compare(a.getDiceNumberRolled(), b.getDiceNumberRolled());
}
});
for (int i = 0; i < playerNames.length; i++) {
playerNames[i] = HashMapUtilities.getKeyFromValue(ModelConstants.PLAYERS, players[i]);
}
// Look for players who rolled the same number.
int i = start;
while (i < end) {
// Try to find a "run" of players with the same number.
int runStart = i;
int diceNumberRolled = players[runStart].getDiceNumberRolled();
i++;
while (i < end && players[i].getDiceNumberRolled() == diceNumberRolled) {
i++;
}
if (i - runStart > 1) {
// We have found more than one player with the same dice number.
// Get all of the players with that dice number to roll again.
addMessageToLog(MessageType.INFO, "There has been a tie." , 2000);
tiedPlayers = true;
getPlayerOrder(playerNames, players, runStart, i);
tiedPlayers = false;
}
}
}
private int rollDice(String playerName, Player player) {
int numberRolled = 0;
if (player.getPlayerType().equals(PlayerType.HUMAN)) {
boolean diceRolled = false;
while (!diceRolled) {
String message = ", roll the dice";
if (tiedPlayers == true) {
message += " again.";
}
else {
message += ".";
}
String userInput = getCommand(playerName + message, "Invlaid command. Type \"Roll Dice\" or something similar.", 2000);
if (userInput.equalsIgnoreCase("Roll Dice") || userInput.equalsIgnoreCase("roll the dice") || userInput.equalsIgnoreCase("Roll")) {
numberRolled = dice.rollDice();
diceRolled = true;
}
else {
addMessageToLog(MessageType.ERROR, "Invlaid command. Type \"Roll Dice\" or something similar.", 0);
}
}
}
else {
String message = " is now rolling the dice";
if (tiedPlayers == true) {
message += " again...";
}
else {
message += "...";
}
addMessageToLog(MessageType.INFO, playerName + message, 2000);
numberRolled = dice.rollDice();
}
player.setDiceNumberRolled(numberRolled);
addMessageToLog(MessageType.SUCCESS, playerName + " rolled a " + numberRolled, 1000);
addDicePanel(numberRolled);
return numberRolled;
}
private void setPlayerOrder() {
for (int i = 0; i < playerOrder.length; i++) {
if (i == (playerOrder.length - 1)) {
playerOrder[i].setNextPlayer(playerOrder[0]);
}
else {
playerOrder[i].setNextPlayer(playerOrder[i + 1]);
}
}
activePlayer = playerOrder[0];
}
private void changePlayer() {
activePlayer = activePlayer.getNextPlayer();
}
There are 2 ways to deal with this.
1) The simple thing is to forget the "dice-roll". Generate 32 random (one int) bits for each player and use that for ordering. If they happen to match pick whatever player you want. It's going to be so rare that it doesn't really matter (1 in 4 billion that you get 2 numbers to be the same).
2) If you want to stick to dice-roll. Create a function that takes a list of players, rolls the dice internally and returns the correctly ordered one. Whenever you have equal rolls call create a smaller list with the players that are equals and call the function recursively to give you the ordering of those players. When it returns copy it in the result and continue. You can prove mathematically that it's highly unlikely(read impossible) that this will result in an infinite loop.
To organize stuff, try to create a separate method for each "action" you need - one method for rolling the dice, another to find duplicates, and another to sort. here are the steps:
Roll dice for all players, store in a List
Find duplicates
For all duplicates, repeat step 1 and 2 until no duplicates are found.
Sort the players.
3 methods. 4 steps. logically executed to do what you need.
public int rolldice(Player player);
public List<Player> findDuplicates (List<Player> players);
public void sortPlayers(List<Player> players);
you can already work with these 3 methods. Hope this helps
You can put all of the players into an array - the order of the players in an array can be used to indicate the order of play.
Get them all to pick a dice roll; then sort them by the number they rolled (using a custom comparator).
Now, look for 2 or more players that rolled the same number - these are next to each other because the array is sorted. Now, you can recursively call the same logic to get just those players to re-roll, but only on the portion of the array where those players had the same dice roll.
For example:
Player[] getPlayerOrder() {
Player[] players = playerMap.values().toArray(new Player[playerMap.size()]);
getPlayerOrder(players, 0, players.length);
return players;
}
void getPlayerOrder(Player[] players, int start, int end) {
// Get all players between players[start] (inclusive) and
// players[end] (exclusive) to re-roll the dice.
for (int i = start; i < end; ++i) {
// Logic to roll dice...
players[i].setDiceNumberRolled(...);
}
// Sort this portion of the array according to the number rolled.
Arrays.sort(players, start, end, new Comparator<Player>() {
#Override public int compare(Player a, Player b) {
return Integer.compare(b.getDiceNumberRolled(), a.getDiceNumberRolled());
}
});
// Look for players who rolled the same number.
int i = start;
while (i < end) {
// Try to find a "run" of players with the same number.
int runStart = i;
int diceNumberRolled = players[runStart].getDiceNumberRolled();
++i;
while (i < end && players[i].getDiceNumberRolled() == diceNumberRolled) {
++i;
}
if (i - runStart > 1) {
// We have found more than one player with the same dice number.
// Get all of the players with that dice number to roll again.
getPlayerOrder(players, runStart, i);
}
}
}
My attemp would be to let everyone roll the dice and just store it without any sort. Then check for duplicates and let the players who got the same numbers roll again. Afterwards when every Player rolled and nothig duplicate anymore just use some Sort Algorithm. Simplest one for that would be BubbleSort since you have no time issue when sorting. Check out this enter link description here
The iterative solution not as simple as I first thought!
I originally posted a solution using primitive int arrays for players & dice.
But this was needlessly complex to code. Easier by far to use composite class, PlayerDice. An array of such objects can be sorted using Arrays.sort(...) method for desired range of the array according to the compareTo(.) method defined for PlayerDice.
You have to be careful to store the end index when some of a group of players tied on the same dice again tie after a roll-off. These I put into a stack - except where the entire group of tied players throw the same dice on a roll-off.
The overall finish condition is when there are no ties and the start-index is greater than the end-index.
package snakesAndLadders;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Stack;
public class PlayOrderTest6
{
private final static int numPlayers = 16;
private PlayerDice[] playersDice = new PlayerDice[numPlayers];
/** Composite class to enable sorting of players according to dice they throw.*/
public static class PlayerDice implements Comparable<PlayerDice>
{
private int player;
private int dice;
public PlayerDice(int player, int dice)
{
this.player = player;
this.dice = dice;
}
public int getPlayer()
{
return player;
}
public void setPlayer(int player)
{
this.player = player;
}
public int getDice()
{
return dice;
}
public void setDice(int dice)
{
this.dice = dice;
}
public String toString()
{
return "Player# " + player + " | Dice: " + dice;
}
#Override
public int compareTo(PlayerDice pd)
{
// Default comparison is on basis of dice value descending:
return pd.getDice() - this.dice;
}
}
/** Main method basically runs the getPlayOrder(.) method for the number of
players involved in this game, i.e. the attribute players. */
public static void main(String[] args)
{
int[] playOrder = new int[numPlayers]; // Holds final play order
// Initialize playerDice array and give each player a number between 1 .. players :
for(int i = 0; i < numPlayers; i++)
{
playersDice[i] = new PlayerDice(i + 1, 1);
playOrder[i] = i + 1;
}
// Generate the order of play by rolling dice & re-rolling for tied players :
getPlayOrder(playersDice);
// Extract play order :
for(int i = 0; i < numPlayers; i++)
playOrder[i] = playersDice[i].getPlayer();
System.out.println("\n\nFinal Player Order is : " + Arrays.toString(playOrder));
}
public static void getPlayOrder(PlayerDice[] p)
{
int start = 0, // Start index of unsorted PlayerDice array
end = numPlayers - 1; // End index of unsorted PlayerDice array
Integer[] sdInds = new Integer[2]; // For start & end indices of first group of tied players.
Stack<Integer> endStack = new Stack<Integer>(); // Holds end index when a dice-roll to sort a tie produces another tie.
while (start < numPlayers && end > start)
{
// Roll dice for players in index range between start & end :
for(int i = start; i < end + 1; i++)
p[i].setDice( (int) (6 * Math.random() + 1));
// Output player/dice values :
System.out.print("\n\nPlayer Order:\t\t");
for(int i = 0; i < numPlayers; i++)
System.out.print(p[i].getPlayer() + "\t");
System.out.print("\nDice Rolled:\t\t");
for(int i = 0; i < numPlayers; i++)
System.out.print(p[i].getDice() + "\t");
// Sort players between start & end indices by their dice number descending :
Arrays.sort(p, start, end + 1); // Uses PlayerDice compareTo(.) method, i.e. by dice value descending.
// Output player/dice values :
System.out.print("\n\nSorted Player Order:\t");
for(int i = 0; i < numPlayers; i++)
System.out.print(p[i].getPlayer() + "\t");
System.out.print("\nSorted Dice Rolled:\t");
for(int i = 0; i < numPlayers; i++)
System.out.print(p[i].getDice() + "\t");
// Find first group of players (from leftmost element of p) on the same dice :
sdInds[0] = -1;
sdInds[1] = -1;
findTiedPlayers(p, start, end, sdInds);
System.out.print("\nsdInds[0]: " + sdInds[0]);
System.out.print("\nsdInds[1]: " + sdInds[1]);
// Where tied players are found ...
if (sdInds[0] != -1)
{ // Re-set start and end indices and re-roll dice to sort the tied group :
start = sdInds[0];
if (sdInds[1] != end)
{
endStack.push(end); // Keeps priority of tied players over those on lower first dice roll
end = sdInds[1];
}
}
else // Where no ties, reset start & end indices till ties found or all players sorted.
while (sdInds[0] == -1 && end >= start)
{
start = end + 1;
if(!endStack.isEmpty())
end = endStack.pop();
else
break; // When no more players to be checked !
// Get indices of first tied group in remaining players :
sdInds[0] = -1; // Initializing start- ...
sdInds[1] = -1; // ... and end-indices before tie search.
findTiedPlayers(p, start, end, sdInds);
if (sdInds[0]!= -1) // If ties found, adjust start & end indices before tie-breaker roll
{
start = sdInds[0];
endStack.push(end); // Store old end index
end = sdInds[1];
}
}
System.out.print("\nstart: " + start);
System.out.print("\nend: " + end);
}
}
/** Method to find first group of tied players in an array holding player & dice data.
* #param pt - a PlayerDice array;
* #param st - an int holding the start index of the range of pt being examined;
* #param en - an int holding the end index of the range of pt being examined;
* #param tInds - an int array holding the start & end index of the
first group of tied players.
This parameter also acts as a return parameter since it's a reference type,
tInds[0] holding the index of the first tied player and tInds[1] the index of
the last. Where no ties are found, both tInds elements retain their received
values of -1 which signifies no ties. */
public static void findTiedPlayers(PlayerDice[] pt, int st, int en, Integer[] tInds)
{
for(int i = st; i < en; i++)
{
for(int j = i + 1; j < en + 1; j++)
if (pt[i].getDice() == pt[j].getDice())
{
tInds[0] = i;
tInds[1] = j;
}
if (tInds[0] != -1) // First group of tied players found ...
break; // ... finish search !
}
}
}
OUTPUT:
Player Order: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Dice Rolled: 4 4 6 5 2 1 3 6 1 3 4 4 1 2 1 3
Sorted Player Order: 3 8 4 1 2 11 12 7 10 16 5 14 6 9 13 15
Sorted Dice Rolled: 6 6 5 4 4 4 4 3 3 3 2 2 1 1 1 1
sdInds[0]: 0
sdInds[1]: 1
start: 0
end: 1
Player Order: 3 8 4 1 2 11 12 7 10 16 5 14 6 9 13 15
Dice Rolled: 5 6 5 4 4 4 4 3 3 3 2 2 1 1 1 1
Sorted Player Order: 8 3 4 1 2 11 12 7 10 16 5 14 6 9 13 15
Sorted Dice Rolled: 6 5 5 4 4 4 4 3 3 3 2 2 1 1 1 1
sdInds[0]: -1
sdInds[1]: -1
start: 3
end: 6
Player Order: 8 3 4 1 2 11 12 7 10 16 5 14 6 9 13 15
Dice Rolled: 6 5 5 2 6 1 1 3 3 3 2 2 1 1 1 1
Sorted Player Order: 8 3 4 2 1 11 12 7 10 16 5 14 6 9 13 15
Sorted Dice Rolled: 6 5 5 6 2 1 1 3 3 3 2 2 1 1 1 1
sdInds[0]: 5
sdInds[1]: 6
start: 5
end: 6
Player Order: 8 3 4 2 1 11 12 7 10 16 5 14 6 9 13 15
Dice Rolled: 6 5 5 6 2 4 4 3 3 3 2 2 1 1 1 1
Sorted Player Order: 8 3 4 2 1 11 12 7 10 16 5 14 6 9 13 15
Sorted Dice Rolled: 6 5 5 6 2 4 4 3 3 3 2 2 1 1 1 1
sdInds[0]: 5
sdInds[1]: 6
start: 5
end: 6
Player Order: 8 3 4 2 1 11 12 7 10 16 5 14 6 9 13 15
Dice Rolled: 6 5 5 6 2 5 1 3 3 3 2 2 1 1 1 1
Sorted Player Order: 8 3 4 2 1 11 12 7 10 16 5 14 6 9 13 15
Sorted Dice Rolled: 6 5 5 6 2 5 1 3 3 3 2 2 1 1 1 1
sdInds[0]: -1
sdInds[1]: -1
start: 7
end: 9
Player Order: 8 3 4 2 1 11 12 7 10 16 5 14 6 9 13 15
Dice Rolled: 6 5 5 6 2 5 1 2 6 3 2 2 1 1 1 1
Sorted Player Order: 8 3 4 2 1 11 12 10 16 7 5 14 6 9 13 15
Sorted Dice Rolled: 6 5 5 6 2 5 1 6 3 2 2 2 1 1 1 1
sdInds[0]: -1
sdInds[1]: -1
start: 10
end: 11
Player Order: 8 3 4 2 1 11 12 10 16 7 5 14 6 9 13 15
Dice Rolled: 6 5 5 6 2 5 1 6 3 2 4 6 1 1 1 1
Sorted Player Order: 8 3 4 2 1 11 12 10 16 7 14 5 6 9 13 15
Sorted Dice Rolled: 6 5 5 6 2 5 1 6 3 2 6 4 1 1 1 1
sdInds[0]: -1
sdInds[1]: -1
start: 12
end: 15
Player Order: 8 3 4 2 1 11 12 10 16 7 14 5 6 9 13 15
Dice Rolled: 6 5 5 6 2 5 1 6 3 2 6 4 5 4 5 5
Sorted Player Order: 8 3 4 2 1 11 12 10 16 7 14 5 6 13 15 9
Sorted Dice Rolled: 6 5 5 6 2 5 1 6 3 2 6 4 5 5 5 4
sdInds[0]: 12
sdInds[1]: 14
start: 12
end: 14
Player Order: 8 3 4 2 1 11 12 10 16 7 14 5 6 13 15 9
Dice Rolled: 6 5 5 6 2 5 1 6 3 2 6 4 6 2 5 4
Sorted Player Order: 8 3 4 2 1 11 12 10 16 7 14 5 6 15 13 9
Sorted Dice Rolled: 6 5 5 6 2 5 1 6 3 2 6 4 6 5 2 4
sdInds[0]: -1
sdInds[1]: -1
start: 16
end: 15
Final Player Order is : [8, 3, 4, 2, 1, 11, 12, 10, 16, 7, 14, 5, 6, 15, 13, 9]
I was just wondering, is it possible to change the direction of depth first search? I have to find the path from the starting node to the goal node. Here's how my depth first search result looks like. 0 5 7 8 9 10 6 4 1 3 2 11. The starting node is 0 and my goal node is 1. The path I want is 0 5 4 1. Does direction really matters in depth first search?
Here's my code:
public void performIterativeDFS(Graph G, int node, int goal) {
ArrayBasedStack arrayStack = new ArrayBasedStack();
arrayStack.push(node);
visited[node] = true;
while (!arrayStack.isEmpty()) {
int n = arrayStack.pop();
System.out.print(n + " ");
for (int w : G.adjList(n)) {
if (!visited[w]) {
visited[w] = true;
arrayStack.push(w);
if (w == goal) {
goal = w;
System.out.print(" Goal Found: ");
}
}
}
}
}
Structure:
11 3
2 3
0 3
1 4
5 4
5 7
6 7
7 8
8 9
9 10
0 5
DFS randomly selects a direction whenever a choice is possible and continues in that direction, marking previous positions, until it hits a roadblock. I am not sure how and why you would control that direction. However, If you are looking for the shortest path use Breadth first search(BFS) to do that. It will systematically explore nearby nodes before moving ahead and will give you the most optimal path.
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.