Cannot figure out how to get Pascal Triangle In Java - java

I am supposed to get this series
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
NOTE:The spaces mentioned have to be present it should have the exact same output as i have mentioned
I tried this:
class pattern_19
{
static void main()
{
int i,j;
int s=1;
System.out.println(s);
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
s=s*11;
}
System.out.println(s);
s=1;
}
}
}
MY OUTPUT:
11
121
1331
14641
161051
1771561
This did not work any help will be appreciated

Your code would not compile because your main method was not defined correctly. This is one thing but not the main reason why you were getting an unexpected output.
Your s variable represent one integer on each line.
What you'll have to do from there is split your int and print each one of the digits seperately.
Here is a correction, I used an enhanced loop and a charArray to print the digits seperately but there are other ways to achieve this of course (using a loop and integer division works also or modify the way you find s).
Solution
public static void main(String[] args) {
int i, j;
int s = 1;
System.out.println(s + " ");
for (i = 1; i <= 6; i++) {
for (j = 1; j <= i; j++) {
s = s * 11;
}
for (char c : String.valueOf(s).toCharArray()) System.out.print(c + " ");
System.out.println();
s = 1;
}
}
PS : Multiplying by 11 wont work when you'll need numbers with a length of 2. I'll edit my answer right now.
Here is the algorithm solution
public static void main(String[] args) {
int rows = 6;
int[][] triangle = new int[rows][rows];
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) {
if (j == 0) triangle[i - 1][j] = 1;
else triangle[i - 1][j] = triangle[i - 2][j - 1] + triangle[i - 2][j];
System.out.print(triangle[i - 1][j] + " ");
}
System.out.println();
}
}

I finally also got an alternative to do the same here it goes
public class PascalTriangle {
public static void main() {
int rows = 6;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}

Now this one is working properly .

Related

How to print a 2D array in java

Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it.
When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed.
`Random rand = new Random();
int min = 2, max = 10;
// a random number of rows and columns
int a = (int)(Math.random() * (max - min + 1)) + min;
// the location of the starting point.
int row_start = rand.nextInt(a);
int col_start = rand.nextInt(a);
// the location of the ending point.
int row_end = rand.nextInt(a);
int col_end = rand.nextInt(a);
int [][] M = new int [a][a];
public void create() {
//empty: 0; grass: 1; sand: 2; water: 3; wall: 4.
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
M[i][j] = rand.nextInt(5);
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
System.out.print(" " +M[i][j] + "\t");
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
}
if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
}
}
System.out.print("\n");
}
}`
the output looks like this:
1 0 4 0
2 {S} 1 2 2
4 4 {E} 0 3
2 0 3 3
the 2 and 3 shouldn't appear there.
The problem is that you always print m[i][j].
What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print m[i][j].
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
} else if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
} else {
System.out.print(" " +M[i][j] + "\t");
}

I am trying to make an hourglass in java as ASCII art who's height is controlled by a variable that I can change

My code looks like this:
public class HourGlass{
public static final int x = 5;
public static void wall(){
System.out.println("|\"\"\"\"\"\"\"\"\"|");
}
public static void top(){
for (int i = 1;i<=x;i++){
for (int j =1; j<=i; j++){
System.out.print(" ");
}
System.out.print("\\");
for (int k = 1; k <= 9-2*i ;k++){
System.out.print(":");
}
System.out.print("/\n");
}
}
public static void bottom(){
for (int i = 1;i <= x; i++){
for (int j = 1; j<= 5-i; j++){
System.out.print(" ");
}
System.out.print("/");
for (int k = 1; k <= 2*i-1; k++){
System.out.print(":");
}
System.out.print("\\\n");
}
}
public static void main(String[] args){
wall();
top();
bottom();
wall();
}
}
And I get this:
|"""""""""|
\:::::::/
\:::::/
\:::/
\:/
\/
/:\
/:::\
/:::::\
/:::::::\
/:::::::::\
|"""""""""|
How would I go about fixing this and making the bottom and top scale? I have tried to figure out how to solve this issue but I am rather stuck and have not found anything.
This code could be made less rigid, however, this was not your question. In order to make the top and bottom match, you need to ignore the top row where colons do not appear.
I changed your x variable to a capital X, because it is a constant, and made a couple tweeks to your top() and wall() code.
public static final int X = 5;
public static void wall() {
System.out.println("|\"\"\"\"\"\"\"\"\"\"\"|");
}
public static void top() {
for (int i = 1; i <= X + 1; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print("\\");
for (int k = 1; k <= 9 - 2 * (i - 1); k++) {
System.out.print(":");
}
System.out.print("/\n");
}
}
Hope this helps
I always find these exercises to be easier to code if there is a method for creating a string with a repeated character. There are other ways to write it, but here is one way to do this with minimal code, using a recursive method:
private static String repeat(char c, int count) {
return (count == 0 ? "" : c + repeat(c, count - 1));
}
E.g. if you call repeat('*', 5) it returns *****
With that available, you can easily print an hourglass. I was a bit unsure what the center of the hourglass should be, so here is two methods.
Hourglass with even number of colons
public static void printHourGlassEven(int size) {
System.out.println('|' + repeat('"', size * 2) + '|');
for (int i = 1; i <= size; i++)
System.out.println(repeat(' ', i) + '\\' + repeat(':', (size - i) * 2) + '/');
for (int i = size; i >= 1; i--)
System.out.println(repeat(' ', i) + '/' + repeat(':', (size - i) * 2) + '\\');
System.out.println('|' + repeat('"', size * 2) + '|');
}
Test
printHourGlassEven(5);
Output
|""""""""""|
\::::::::/
\::::::/
\::::/
\::/
\/
/\
/::\
/::::\
/::::::\
/::::::::\
|""""""""""|
Hourglass with odd number of colons
public static void printHourGlassOdd(int size) {
System.out.println('|' + repeat('"', size * 2 - 1) + '|');
for (int i = 1; i < size; i++)
System.out.println(repeat(' ', i) + '\\' + repeat(':', (size - i) * 2 - 1) + '/');
System.out.println(repeat(' ', size) + 'X');
for (int i = size - 1; i >= 1; i--)
System.out.println(repeat(' ', i) + '/' + repeat(':', (size - i) * 2 - 1) + '\\');
System.out.println('|' + repeat('"', size * 2 - 1) + '|');
}
Test
printHourGlassOdd(5);
Output
|"""""""""|
\:::::::/
\:::::/
\:::/
\:/
X
/:\
/:::\
/:::::\
/:::::::\
|"""""""""|

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

Ascii Art with Java - Creating a square/rectangle with different symbolled edges

I'm working to printout ascii art which takes two integers entered from the console then displays a rectangle or square from those two integers (the then dimensions). But the corners need to be a different symbol then the main symbol... yet the trick is that the short side has to have only 1 or 2 of the original symbols on it (due to odd or even.)
Here are two examples:
6x9:
001111100
011111110
111111111
111111111
011111110
001111100
9x6:
001100
011110
111111
111111
111111
111111
111111
011110
001100
I've gotten this far (since the console only goes from 0 to 9 right?)
What would need to be added to take in account the corners?
Would an If statement work or something else?
And yes, I know this is only for the "square". How would I add a second dimension? Can I get some help?
class Main {
public static void printSquare(int size) {
if(size > 9) {
size = 9;
}
int line = 1;
while (line <= size) {
int width = size;
int i = 1;
while (i <= width) {
System.out.print("*");
i = i + 1;
}
System.out.println(); // Newline
line = line + 1;
}
}
}
You need to simply tell it that the three corner symbols are different.
Scanner keys = new Scanner(System.in);
int x = 0;
int y = 0;
public void getInput() {
x = keys.nextInt();
y = keys.nextInt();
createart();
}
public void createart() {
System.out.print("00");
int counter = 0;
while (counter < x - 4) {
System.out.print(1);
counter++;
}
System.out.println("00");
counter = 0;
System.out.print("0");
while (counter < x - 2) {
System.out.print(1);
counter++;
}
System.out.print("0");
counter = 0;
int counter2 = 0;
while (counter < y - 4) {
System.out.println("");
while (counter2 < x) {
System.out.print(1);
counter2++;
}
counter++;
}
System.out.println("");
counter = 0;
while (counter < x - 2) {
System.out.print(1);
counter++;
}
counter = 0;
System.out.println("0");
System.out.print("00");
while (counter < x - 4) {
System.out.print(1);
counter++;
}
System.out.print("00");
}
Simple logic.

Can't find the error in my code for number 4 of project euler

I am trying to solve the following problem:
Find the largest palindrome made from the product of two 3-digit numbers.
I have the following Java code:
public static void main(String[] args) {
int a = 999, b = 999;
for(int i = 100; i <= a; i++) {
for(int j = 100; j <= b; j++) {
checkPalindrome(i*j, i, j);
}
}
}
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = false;
int j = s.length()-1;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j))
break;
j -= i;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
I'm still lacking the change of the "palindrome" variable but at the moment if I run it I get a String index out of range on line 28 which is the j -= i I just don't understand why this is happening I mean, I get that the difference is resulting in a number lower than 0 but I can't figure out WHY it happens. Could someone please explain me?
Your method can be improved like this. The condition in for loop i<=j reduced number of iterations too.
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = false;
int j = s.length()-1;
for(int i = 0; i <= j; i++){
if(s.charAt(i) != s.charAt(j))
break;
j --;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
Hope this helps.
I think you want j-- not j -= i. Especially since i starts at 0.
change your code to:
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = true;
int j = s.length()-1;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j))
palindrome = false;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
You're incrementing i - you want to decrement j - you DON'T want to do j -= i.
Otherwise for a string of length 5, you'd get:
i = 0, j = 4
i = 1, j = 4
i = 2 , j = 3
i = 3 , j = 1
i = 4, j = -2
Though if it's giving an index out of range message, you're running a different version of the code - j -= i can't possibly generate that.

Categories