Magic Square program Java with array - java

I want to program a Magic Square wherein the utilization of arrays is at place but when i want to run it, it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MagicSquare.main(MagicSquare.java:6)
What should I do? It would show
4 9 2 7 1 6
3 5 7 not 3 5 7
8 1 6 4 9 2
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = Integer.parseInt(args[3]);
if (n % 2 == 0) throw new RuntimeException("n must be odd");
int[][] magic = new int[n][n];
int row = n-1;
int col = n/2;
magic[row][col] = 1;
for (int i = 2; i <= n*n; i++) {
if (magic[(row + 1) % n][(col + 1) % n] == 0) {
row = (row + 1) % n;
col = (col + 1) % n;
}
else {
row = (row - 1 + n) % n;
}
magic[row][col] = i;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (magic[i][j] < 10) System.out.print(" ");
if (magic[i][j] < 100) System.out.print(" ");
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
}
What else should I add or take away from this program?

According to your program, need to provide 4 arguments when running. ex: If class name is Test:
java Test 1 1 1 3
Result:
4 9 2
3 5 7
8 1 6

Related

Java - printing unique number sequences

I have been trying to find a way to print an inverted pyramid that has a certain number sequence. The sequence needed is as follows as well as what I currently have.
The prompt asked to write a method that takes two numbers and create an inverted pyramid with the first row having a length of the first integer and starting with the number entered second. Then only have the sequence start at 1 after 9 is reached.
Needed: Currently Have:
1 2 4 7 2 7 4 1 2 3 4 5 6 7
3 5 8 3 8 5 8 9 1 2 3 4
6 9 4 9 6 5 6 7 8 9
1 5 1 7 1 2 3 4
6 2 8 5 6 7
3 9 8 9
1 1
static int plotTriangle(int a, int b){
int num = b;
for (int row = a; row >= 0; row--){
for (int i = a; i - row >= 0; i--){
System.out.print(" ");
num += (num+a-row);
num -= 2;
}
for (int i = 0; i <= row; i++){
num++;
while (num >= 10){
num -= 9;
}
System.out.print(num + " ");
}
System.out.println();
}
return 0;
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter length: ");
int l = in.nextInt();
System.out.print("Enter Start: ");
int s = in.nextInt();
int triangle = plotTriangle(l, s);
}
Try this:
public static void main(String[] args) {
int length = 7;
int[][] numbers = new int[length][length];
int count = 1;
for(int i = 0; i < numbers.length; ++i) {
for(int j = 0; j < (i+1); ++j) {
numbers[i][j] = count++;
if(count > 9)
count = 1;
}
}
for(int i = 0; i < numbers.length; ++i) {
for(int j = 0; j < numbers.length; ++j) {
if(numbers[j][i] == 0)
System.out.print(" ");
else
System.out.print(numbers[j][i]);
System.out.print(" ");
}
System.out.println();
}
}
This will give you your result. Note that I didn't include the dynamic part with the scanner. I used the length and the start-number as constants.
Explanation:
In the first loop I am basically just storing the numbers in an array. And in the second loop this array is printed in a different order.

Display a box of increasing number with order

CODE
int rows=3, columns=3, i, j;
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
System.out.print(count);
count++;
}
else
{
System.out.print(" ");
}
}
System.out.print("\n");
}
The following piece of code outputs the following:
OUTPUT
123
4 5
678
What I'm trying to achieve is the following:
123
8 4
765
Basically creating a board game which has to start from one position and end at the same position completing a full circle., in this case a square.
Any Ideas ??
After some experiments, this could work:
public static void printBox(int rows, int columns) {
int sumOfColumns = 2 * columns + rows - 1;
int sumOfRow = 2 * columns + 2 * rows - 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
if (i == 1) {
System.out.printf(String.format("%3d", j));
} else if (j == 1) {
System.out.printf(String.format("%3d", sumOfRow - (i + j - 1)));
} else if (j == columns) {
System.out.printf(String.format("%3d", i + j - 1));
} else if (i == rows) {
System.out.printf(String.format("%3d", sumOfColumns - j));
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
System.out.print("\n");
}
Test case:
public static void main(String[] args) {
printBox(3, 3);
printBox(4, 4);
printBox(3, 4);
}
Result:
1 2 3
8 4
7 6 5
1 2 3 4
12 5
11 6
10 9 8 7
1 2 3 4
10 5
9 8 7 6
Consider creating a 2 dimensional array:
gameBoard[3][3];
then populate that board with the desired values. After the gameboard is complete, you can write another function to print the board.

Empty diamond shape with numbers

So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.
Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:
1
2 2
3 3
2 2
1
Here's my code so far:
public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}
//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}
Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:
public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;
String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}
public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}
Output:
__1
_2_2
3___3
_2_2
__1
You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).
Here is the program for printing empty diamond:
int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for (int i = n; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
System.out.print(" ");
}
System.out.print(upperCount);
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
if (upperCount != 1) {
System.out.print(upperCount);
}
upperCount++;
System.out.print("\n");
}
int lowerCount = n - 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(" ");
}
System.out.print(lowerCount);
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
if (lowerCount != 1) {
System.out.print(lowerCount);
}
lowerCount--;
System.out.print("\n");
}
Do following changes in the Bottom Part of your code:
int lowerCount = n - 1;
for (int i = n - 1; i >= 2; i--) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= lowerCount; j++) {
System.out.print(" ");
}
System.out.print(i);
lowerCount -= 2;
}
You can print an empty diamond shape with numbers using two nested for loops over rows and columns from -n to n. The diamond shape is obtained when iAbs + jAbs == n:
int n = 2;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
2 2
1
You can separately define width and height:
int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
3 3
2 2
1
See also:
• Filling a 2d array with numbers in a rhombus form
• How to print a diamond of random numbers?
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
Alternative solution:
public static void main(String[] args) {
int n = 7;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// edge of the diamond
int edge = Math.abs(i) + Math.abs(j);
// diamond shape with numbers
if (edge == n) System.out.print(n - Math.abs(i) + 1);
// beyond the edge && in chessboard order || vertical borders
else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
System.out.print("*");
// empty part
else System.out.print(" ");
}
System.out.println();
}
}
Output:
** * * 1 * * **
* * * 2 2 * * *
** * 3 3 * **
* * 4 4 * *
** 5 5 **
* 6 6 *
*7 7*
8 8
*7 7*
* 6 6 *
** 5 5 **
* * 4 4 * *
** * 3 3 * **
* * * 2 2 * * *
** * * 1 * * **
See also: How to print a given diamond pattern in Java?
Solution: Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines.
public class EmptyDiamond {
public static void main(String[] args) {
shape(3); // Change n to increase size of diamond
}
public static void shape(int n) {
int max = 2 * n - 1; // length of the diamond - top to bottom
int loop = 0; // with of each loop. initialized with 0
for (int i = 1; i <= max; i++) {
int val = 0;
if (i <= n) {
loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
val = i; // value to be printed in each loop ascending
} else {
loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
val = max - i + 1; // value to be printed in each loop descending
}
for (int j = 1; j <= loop; j++) {
// (value end of loop)
// || (value in the beginning when i <= n)
// || (value in the beginning when i > n)
if (j == loop
|| j == (n - i + 1)
|| j == (n - val + 1)) {
System.out.print(val); // Print values
} else {
System.out.print(" "); // Print space
}
}
System.out.println(); // Print next line
}
}
}
Output when n = 3:
1
2 2
3 3
2 2
1
Stream-only function:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n ? 2*n-i : i)
.mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
.forEach(System.out::println);
}
Example output (printEmptyDiamond(7)):
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
With explainations:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
.mapToObj(i -> " ".repeat(n-i) // leading spaces
+ i // leading number
+ (i>1 ? // only when number is > 1
" ".repeat(2*(i-1)-1) // middle spaces
+ i // trailing number
: ""))
.forEach (System.out::println);
}
I did it for fun, here's the code :
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int num = read.nextInt();
read.nextLine();
//TOP
for(int i = 1;i<=num;i++) {
//LEFT
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
//BOTTOM
for(int i = num-1;i>0;i--) {
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
}
}
And the output :
7
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
Having seen the other answers, there's a whole load of loops I could've skipped. Just decided to wing it at the end and do it as quick as possible.

how can i generate 0's in stair case in 2d array?

In 2D array we can generate n*n matrix. and how can replace number into 0's replace in the matrix.
public static void main(String[] args) {
int rows = 8;
int coulmns = 4;
int array;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < coulmns; j++) {
System.out.print(i*j+" ");
}
System.out.println("");
}
}
}
output:
1 2 3
2 4 6
3 6 9
4 8 12
5 10 15
6 12 18
7 14 21
how can i replace as 0's in stair case in the form of output:
1 2 (0)
2 (0) 6
(0) 6 9
4 (0) 12
5 10 (0)
6 (0) 18
(0) 14 21
I assume the language is Java as that is the tag specified.
import java.util.*;
import java.lang.*;
import java.io.*;
class StairCase
{
public static void main (String[] args) throws java.lang.Exception
{
int rows = 8;
int coulmns = 4;
int col=3;
int row=1;
int flag=0;
int array;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < coulmns; j++) {
if(col==j && row==i){
System.out.print("(0)");
if(col>1 && col<4 && flag==0){
col--;
if(col==1){
flag=1;
}
row++;
}else{
col++;
if(col==3){
flag=0;
}
row++;
}
}else{
System.out.print(i*j+" ");
}
}
System.out.println("");
}
}
}
Result :
1 2 (0)
2 (0) 6
(0) 6 9
4 (0) 12
5 10 (0)
6 (0) 18
(0) 14 21
In the second for loop try doing this:
for (int j = 1; j < coulmns; j++) {
int number = i*j;
if(i == 3 || i == 7) number = 0;
else if((j == 3 && i == 1) || (j == 3 && i == 5)) number = 0;
else if((j == 2 && i == 2) || (j == 2 && i == 6)) number = 0;
else System.out.print(number + " ");
}
You can also use modulus if you want.
I assume the language is Java as that is the tag specified.
I think the solution will be to use modulus arithmetic.
You want to replace the value in the cell position (4 - row number % 4) with (0). Where (row number % 4) = 0 then the (0)always goes in the second cell. So the code is:
public static void main(String[] args) {
int rows = 8;
int coulmns = 4;
int array;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < coulmns; j++){
if((j == (4 - (i % 4)) || (i % 4 == 0 && j == 2)))
{
System.out.print("0 ");
}
else
{
System.out.print(i*j+" ");
}
}
System.out.println("");
}
}
}

Pascal's Triangle Format [duplicate]

This question already has answers here:
Pascal's triangle 2d array - formatting printed output
(5 answers)
Closed 1 year ago.
The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.
public static void triangle(int maxRows) {
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
}
I need to format the values of the triangle such that it looks like a triangle:
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
I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.
public static long pascalTriangle(int r, int k) {
if (r == 1 || k <= 1 || k >= r) return 1L;
return pascalTriangle(r - 1, k - 1) + pascalTriangle(r - 1, k);
}
This method allows you to find the k-th value of r-th row.
This is a good start, where it's homework, I'll leave the rest to you:
int maxRows = 6;
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
//pre-spacing
for (int j = maxRows - i; j > 0; j--) {
System.out.print(" ");
}
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
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
1 6 15 20 15 6 1
In each row you will need to print:
n spaces
m numbers
n spaces
Your job is to figure out n (which will be zero in the last line) and m based on row number.
[This is more like a comment but I needed more formatting options than comments provide]
You need to print the spaces (like others have mentioned) and also as this is homework I'm leaving it to you but you might want to look at this handy little function
System.out.printf();
Here is a handy reference guide
Also note that you will need to take into account that some numbers are more than 1 digit long!
import java.util.*;
class Mine {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i < n; i++) {
int size = 1;
for (int j = 1; j <= i; j++) {
int a[] = new int[size];
int d[] = new int[size];
for (int k = 1; k <= size; k++) {
a[1] = 1;
a[size] = 1;
for (int p = 1; p <= size; p++) {
d[p] = a[p];
}
if (size >= 3) {
for (int m = 2; m < size; m++) {
a[m] = d[m] + d[m - 1];
}
}
}
for (int y = 0; y < size; y++) {
System.out.print(a[y]);
}
System.out.println(" ");
}
++size;
}
}
}
public class HelloWorld {
public static void main(String[] args) {
int s = 7;
int k = 1;
int r;
for (int i = 1; i <= s; i++) {
int num = 1;
r = i;
int col = 0;
for (int j = 1; j <= 2 * s - 1; j++) {
if (j <= s - i)
System.out.print(" ");
else if (j >= s + i)
System.out.print(" ");
else {
if (k % 2 == 0) {
System.out.print(" ");
} else {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
col++;
}
k++;
}
}
System.out.println("");
k = 1;
}
}
}
Output:
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
You can try this code in java. It's simple :)
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
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();
}
}
}
Output:
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
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Code perfectly prints pascal triangle:
public static void main(String[] args) {
int a, num;
for (int i = 0; i <= 4; i++) {
num = 1;
a = i + 1;
for (int j = 4; j > 0; j--) {
if (j > i)
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j > 0)
num = num * (a - j) / j;
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Categories

Resources