Math Equation Pattern - java

I am creating a pattern that, when user enters the number of rows, prints a triangle with a specific number pattern. I am having a hard time coming up with a mathematical equation that will output this pattern:
I have already written a code that works but not with the pattern that I am wanting to create. Can someone help me?
Here's my code so far:
import java.util.Scanner;
public class trianglePattern {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
for(int i =0;i<rows;i++) {
System.out.format("%"+4*(rows-i+1)+"s","");
for(int j=i+1; j>1; j--)
System.out.format("%4d", j);
for(int j=1; j<=i+1; j++)
System.out.format("%4d", j);
System.out.println();
}
}
}

Switched the loops, added a power function and fiddled a little with the loop indexes:
import java.util.Scanner;
public class trianglePattern {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
for(int i = 0; i < rows; i++) {
System.out.format("%"+4*(rows-i+1)+"s","");
for(int j = 0; j <= i; j++)
System.out.format("%4d", (int) Math.pow(2,j));
for(int j = i - 1; j >= 0; j--)
System.out.format("%4d", (int) Math.pow(2,j));
System.out.println();
}
}
}

Nice problem...
Scanner input = new Scanner(System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<rows; i++) {
list.add(i);
}
for(int i=rows-2; i>-1; i--) {
list.add(i);
}
// I print this here just for your help(delete it afterwards)
for (Integer integer : list) {
System.out.print(((int) Math.pow(2, integer)) + " ");
}
System.out.println("\n");
for(int i=rows; i>=1; i--) {
for (Integer integer : list) {
int number = ((int) Math.pow(2, integer-i+1));
if(number>=1) {
System.out.format("%d\t", ((int) Math.pow(2, integer-i+1)));
} else {
System.out.print(" ");
}
}
System.out.println("\n");
}
(Tip): in the Arraylist list i save all the exponents i need to calculate the last row of the problem.

Try this. The spacing is based on several factors.
The sum of the field widths. Each field width is kept is a list. It is used to reduce the leading space based on the row being printed.
That each column field width is sized for the maximum value in that column. The width for a given column is also maintained in a list. Since the widths are symmetric about the central column, left side formats are also used to print right side values.
Scanner input = new Scanner(System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
List<Integer> fws = new ArrayList<>();
List<String> fmts = new ArrayList<>();
Function<Integer, Integer> fw = r -> (int) (Math
.log10(1 << r)) + 2;
int sumWidths = 0;
for (int r = 0; r < rows; r++ ) {
int f = fw.apply(r);
fws.add(f);
sumWidths += f;
fmts.add("%" + f + "d");
}
rows--;
String pad = " ".repeat(sumWidths);
for (int r = rows; r >= 0; r--) {
System.out.print(pad);
int v = 1;
for (int c = r; c < rows; c++) {
System.out.printf(fmts.get(c), v);
v <<= 1;
}
System.out.printf(fmts.get(rows), v);
for (int c = rows-1; c >= r; c--) {
v >>= 1;
System.out.printf(fmts.get(c), v);
}
System.out.println();
pad = pad.substring(r > 0 ? fws.get(r-1) : pad.length());
}
}

Related

How to create a method in java which prints out the elements of a matrix in shown pattern?

The contents of the matrix starts from 1 to the product of rows and columns. The method "scan" should print out as per following:
If the row is entered 4 and column is entered 7, the contents of the matrix should look like the image provided here:
the correct matrix
So far I have tried absolutely noting because I just don't know how to make this possible. I can print in zigzag, spiral but I just have no idea about this one. Please have mercy on me and grant me an insight.
This code currently prints out in a spiral pattern.
How should I modify this "scan" method so it satisfies the aforementioned condition?
import java.util.Scanner;
import java.util.Random;
public class that {
public static void main(String[] args) {
int range;
range = 100;
Scanner scn = new Scanner(System.in);
while(true) {
int m, n;
System.out.println("Enter the number of row: ");
m = scn.nextInt();
System.out.println("Enter the number of column: ");
n = scn.nextInt();
if(m <= 0||n <= 0) break;
int[][] tab = new int[m][n];
generate(tab, range);
scan(tab);
}
scn.close();
}
static int len(int x) { return (""+x).length(); }
static void generate(int[][] tab, int range) {
// Random generation
Random rg = new Random();
for(int i=0; i<tab.length; ++i)
for(int j=0; j<tab[0].length; ++j)
tab[i][j] = rg.nextInt(2*range) - range;
}
static void scan(int[][] tab) {
int m = tab.length;
int n = tab[0].length;
int totalWidth = 0;
int num = 1;
int rowStart = m - 1, rowEnd = 0, colStart = 0, colEnd = n - 1;
// Compute column widths
int[] colw = new int[n];
for(int j=0; j<n; ++j) { // For every column look down
colw[j] = len(j); // (""+j).length();
for(int i=0; i<m; ++i) {
int w = len(tab[i][j]); //("" + tab[i][j]).length();
if(w > colw[j]) colw[j] = w;
}
totalWidth += colw[j];
}
// Printing
int ris = len(m-1); // row index size
System.out.printf("%"+ris+"s ", " ");
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", j);
System.out.println();
System.out.printf("%"+ris+"s+"," ");
for(int j=0; j<totalWidth+n-1; ++j)
System.out.printf("-");
System.out.println();
while (rowStart >= rowEnd && colStart <= colEnd) {
// Print leftmost column from bottom to top
if (colStart <= colEnd) {
for (int i = rowStart; i >= rowEnd; i--) {
tab[i][colStart] = num++;
}
colStart++;
}
// Print top row from right to left
if (rowStart >= rowEnd) {
for (int i = colStart; i <= colEnd; i++) {
tab[rowEnd][i] = num++;
}
rowEnd++;
}
// Print rightmost column from top to bottom
if (colStart <= colEnd) {
for (int i = rowEnd; i <= rowStart; i++) {
tab[i][colEnd] = num++;
}
colEnd--;
}
// Print bottom row from left to right
if (rowStart >= rowEnd) {
for (int i = colEnd; i >= colStart; i--) {
tab[rowStart][i] = num++;
}
rowStart--;
}
}
// Prints the matrix
for(int i=0; i<m; ++i) {
System.out.printf("%"+ris+"d|", i);
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", tab[i][j]);
System.out.println();
}
System.out.println();
}
}

How to Reverse an Int with For Loops

i am having trouble with reversing this code. what i am trying to have as
this is what i have so far but i can't seem to wrap my head around how the third for loop is supposed to be
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //gets the users input
int rows;
int number = 0;
int i = 0;
rows = input.nextInt(); //takes the users input from console
while (rows <= 0) {
System.out.println("INVALID");
rows = input.nextInt();
}
for (int c = 1; c <= rows; c++) {
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number + " ");
//number--;
}
System.out.println();
}
Before running your last loop you should store number in some temp variable:
int temp = number;
for(i = 0; i < c; i++) {
System.out.print(temp-- + " ");
}
As I said in the comment, you need to decrement the number but at the same time need to keep track of the highest values in a line to use it as a starting value in the next iteration. Something like this should work:
public static void main(String[] args) {
int rows;
int number = 0;
int highestValue = 0;
int i = 0;
rows = 5;
for (int c = 1; c <= rows; c++) {
number = highestValue; // reset number to the highest value from previous line
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
highestValue = number; // setting the highest value in line
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number-- + " "); // decrementing
}
System.out.println();
}
Do you have to implement this yourself, because otherwise there are tons of libraries handling arrays.
The steps you have to take are:
Find a way to read the input (integers) in a single line and store them in some kind of container (either an array, or a list).
You may have to isolate what a single integer is (e.g. "1 2 3" is 3 integers, which you want to reverse, while "12 3" is just 2, and you only want to reverse 2).
You need to ensure that your input is valid (e.g. a user may enter "1 a b c")
You need to flip the integers within the container or better copy the original container in reverse order. For this, you only need to iterate over the container's elements and add them to the target container in reverse order
for (Integer in : inputList) {
outputList.addFirst(in);
}
If you only want to print the integers, you don't have to store them in a list, you could just iterate over the container in reverse order.
It seems to bit a pattern program, you can add the number-- in you sysout
public static void main( String[] args )
{
Scanner input = new Scanner(System.in); //gets the users input
int rows;
int number = 0;
int i = 0;
rows = input.nextInt(); //takes the users input from console
while (rows <= 0) {
System.out.println("INVALID");
rows = input.nextInt();
}
for (int c = 1; c <= rows; c++) {
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number-- + " ");
//number--;
}
System.out.println();
}
}
Such type of pattern you can create through collections

Out of bounds exception in matrix multiplication [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I wrote this code.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the rows \"then\" columns of the first array: ");
int a = console.nextInt();
int b = console.nextInt();
int[][] arr1 = new int[a][b];
System.out.println("Please enter the rows \"then\" columns of the second array: ");
int c = console.nextInt();
int d = console.nextInt();
int[][] arr2 = new int[c][d];
if (b != c) {
System.out.println("these two matrices can't be multiplied!!");
} else {
int[][] mult = new int[a][c];
System.out.println("Please enter the elements of the first array : ");
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
arr1[i][j] = console.nextInt();
}
}
System.out.println("Please enter the elements of the second array : ");
for (int i = 0; i < c; i++) {
for (int j = 0; j < d; j++) {
arr2[i][j] = console.nextInt();
}
}
int sum = 0;
for (int i = 0; i < a; i++) {
for (int j = 0; j < d; j++) {
for (int k = 0; k < c; k++) {
sum += arr1[i][k] * arr2[k][j];
mult[i][j] = sum;
}
sum = 0;
}
}
for(int i=0;i<a;i++){
for(int j=0;j<d;j++) {
System.out.print(mult[i][j] + " ");
}
System.out.println("");
}
}
}
}
and when I run it, it says java.lang.ArrayIndexOutOfBoundsException.
I don't know why, Thanks for helping.
From what I see, here might be the problem: int[][] mult = new int[a][c], it should be new int[a][d]
P/s: Would be nicer if you can format the first part of your code

Loop not giving me desired matrix output

I am trying to display an array of numbers in a square matrix that increases by 1 in a snake pattern. Cant get right output. User inputs row/columns and matrix is displayed. Look at photo below. I have also attempted if statements for even/odd rows with modulo but still getting same output. (Bear with me, I am new to this, sorry about format or if I'm missing information)
http://imgur.com/a/ZDhFw
import java.util.Scanner;
public class A3_Q2 {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int i = 0;
int number = 1;
while (i < arraySize)
{
for (int j = 0; j < arraySize; ++j)
{
pattern[i][j] = number;
System.out.printf("%3d", pattern[i][j]);
number++;
}
System.out.println("");
++i;
for (int j = arraySize-1; j >= 0; --j)
{
pattern[i][j] = number;
System.out.printf("%3d", pattern[i][j]);
number++;
}
System.out.println("");
++i;
}
}
}
I've changed your code so that it works. As you already mentioned, you can use the modulo operator here.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int number = 1;
for(int i=0;i<arraySize;i++){
if(i%2==0){
for(int j=0;j<arraySize;j++){
pattern[i][j]=number;
number++;
}
}
else{
for(int j=arraySize-1;j>=0;j--){
pattern[i][j]=number;
number++;
}
}
for(int j=0;j<arraySize;j++){
System.out.printf("%3d", pattern[i][j]);
}
System.out.println();
}
}
EDIT: Tested this in IDE to make sure it works.
You first need to have have an initial value for pattern[i][j].
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < arraySize; j++) {
pattern[i][j] = arraySize*i + j + 1;
}
}
You need to then have a condition that will print out the numbers in ascending order when i is even, and descending when i is odd.
for (int i = 0; i < arraySize; i++) {
if (i % 2 == 0) {
for (int j = 0; j < arraySize; j++) {
System.out.printf("%3d", pattern[i][j]);
}
} else {
for (int j = arraySize - 1; j >= 0; j--) {
System.out.printf("%3d", pattern[i][j]);
}
}
System.out.println();
}

Making Tree with Nested Loops

So, for my programming class, our teacher tasked us with making a tree out of *'s and other random characters. There has to be a star at the top of the tree that increases in size every so often, depending how large the user wants the tree. For some reason, if the number the user enters is greater than 15, the bottom half is too far to the right. I tried changing my code, but then everything less than 15 is too far the right. How can I get that to work?
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int a = scan.nextInt();
int b = 0;
int c = 0;
int d = 0;
if ( a >= 12){
d = 1;
} else {
d = 0;
}
//Top Half of Star
for (int i = 0; i < a / 4; i++) {
for (int j = i; j < a; j++){
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++){
System.out.print("*");
b = b + 1;
}
System.out.println("");
}
//Bottom Half of Star
for (int i = 1; i < a/4; i++){
for (int j = d; j < a; j++){
System.out.print(" ");
}
for (int j = c; j < b/3; j++){
System.out.print("*");
}
c = c + 2;
d = d - 1;
System.out.println("");
I think this is what you're looking for, if you're defining the size as the number of rows.
import java.util.Scanner;
public class NestedTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int size = scan.nextInt(); // Get the size of the tree
for (int i = 0; i < size; i++) {
int spaces = size - i;
for (int s = 0; s < spaces; s++) { // Print spaces
System.out.print(" ");
}
for (int r = 0; r <= i; r++) { // Print stars
System.out.print("* ");
}
System.out.print("\n"); // new line
}
}
}

Categories

Resources