Need help shifting latin square in Java - java

I'm currently making a latin square that starts with a user-set number but for simplicity's sake I'll exclude Scanner code.
public static void main(String[] args){
int first = 2; // starting integer on square
int order = 4; //max integer
String space = new String(" ");
for (int row = 0; row < order; row++)
{
for (int column = 0; column < order; column++)
{
for (int shift = 0; shift < order; shift++)
{
int square = ((column+(first-1)) % order + 1); //this makes a basic square with no shifting
int latin = square+shift; //this is where my code becomes a mess
System.out.print(latin + space);
}
System.out.println();
}
}
}
}
Which prints out:
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
It's so close, considering the fact that it does start with my pre-determined first digit and it's printing only 4 integers.
The problem I'm running into is the fact that it's going further than my order integer and that it's printing double the rows.
Any idea what I can do to fix this?
For reference, this is what I want it to print:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4

It seems that the innermost loop for (int shift...) is redundant and it causes duplication of the output, the latin value should be calculated using row parameter:
public static void main(String args[]) {
int first = 2; // starting integer on square
int order = 4; //max integer
String space = " ";
for (int row = 0; row < order; row++) {
for (int column = 0; column < order; column++) {
int latin = (row + column + first - 1) % order + 1;
System.out.print(latin + space);
}
System.out.println();
}
}
Output:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4

Related

Fill an integer array with a series of number that is a string (java)

Im trying to write the following program, where i have a string that a number is generated possibly like 37 digits.
Is it possible to fill an array that i know the length but not the rows because the string can be anything.
String number; //110034043312132121220023020423340432 but can be any big number that is converted to a string
System.out.println("Give length in a form of a string: ");
String input= scan.nextLine(); //abcdefg
int length = input.length(); //this means i get 6 back.
And save this in a character array where i know the length from input.lenght() and i dont know the rows
A B C D E F G
1 1 0 0 3 4 0
4 3 3 1 2 1 3
2 1 2 1 2 2 0
0 2 3 0 2 0 4
2 3 3 4 0 4 3
2
I know the answer might be something stupid simple but please be coder noob friendly. Thanks
The solution may be as follows:
Use input.length as the max number of columns in the resulting 2D array
Calculate the number of rows in the resulting 2D array nums / cols, adding one extra row if there's a remainder.
The last row in the result may be jagged: contain less than cols elements.
String number = "110034043312132121220023020423340432"; // but can be any big number that is converted to a string
System.out.println("Give length in a form of a string: ");
String input= "ABCDEFG" ; //scan.nextLine(); //abcdefg
int cols = input.length(); // columns in the resulting array
int nums = number.length(); // total count of numbers
int rows = nums / cols + (nums % cols == 0 ? 0 : 1);
int[][] result = new int[rows][]; // the result may be jagged
for (int i = 0; i < rows - 1; i++) {
result[i] = new int[cols];
}
result[rows - 1] = new int[nums % cols == 0 ? cols : nums % cols];
for (int i = 0; i < nums; i++) {
int r = i / cols;
int c = i % cols;
result[r][c] = number.charAt(i) - '0';
}
// print the result
System.out.println(input.replaceAll(".", "$0 ")); // print header with spaces between columns
for (int[] row : result) {
System.out.println(Arrays.toString(row)
.replaceAll("[^\\s\\d]", "") // remove brackets and comma from output
);
}
Output:
A B C D E F G
1 1 0 0 3 4 0
4 3 3 1 2 1 3
2 1 2 1 2 2 0
0 2 3 0 2 0 4
2 3 3 4 0 4 3
2
To do this, you might be able to use a list instead.
ArrayList<int[]> list = new ArrayList<int[]>();
and in each line, you can add a new array into the list.
If you want the final result to be a 2d array, you can easily convert a list to an array.
public static char[][] createMatrix(String num, String title) {
int totalRows = (int)Math.ceil((double)num.length() / title.length());
char[][] matrix = new char[totalRows + 1][title.length()];
for (int i = 0; i < matrix[0].length; i++)
matrix[0][i] = title.charAt(i);
for (int i = 0, row = 1, col = 0; i < num.length(); i++) {
matrix[row][col++] = num.charAt(i);
if (col == matrix[row].length) {
row++;
col = 0;
}
}
return matrix;
}

How do i fix the angle of my mathematical triangle of squares?

I need to fix my output as shown at the bottom, i have code that outputs the correct math values
but it does not output the correct angle that is expected of the example output that i have provided below. ( I know this is pretty simple for most of you stack users but im a beginner in java and this is something that confuses me ). I have not come up with any ideas on what i can do to fix this issue and put in the correct angle.
Instructions:
-Write a program using a Scanner that asks the user for a number
n between 1 and 9 (inclusive).
-The program prints a triangle with n rows.
-The first row contains only the square of 1, and it is right-justified.
-The second row contains the square of 2 followed by the square of 1,
and is right justified.
-Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2
and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console
1
4 1
9 4 1
16 9 4 1
Code:
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int i = 1 ; i <=n; i++) {
for (int j = n-i; j >=1; j--) {
System.out.print("");
}
for (int k = i; k <= n; k++ ) {
System.out.print(" " + i * i);
}
System.out.println(" ");
}
scan.close();
}
}
My output:
Please enter a number between 1 and 9 inclusive: 4
1 1 1 1
4 4 4
9 9
16
Here is a short and simple variant.
for (int row = 1; row <= n; row ++) {
for (int col = n; col >= 1; col--) {
if (col <= row) {
System.out.print(String.format("%2d ", col * col));
} else {
System.out.print(" ");
}
}
System.out.println();
}
Here is the output generated for input 9:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
49 36 25 16 9 4 1
64 49 36 25 16 9 4 1
81 64 49 36 25 16 9 4 1
TL;DR; Use a pen and paper for annoying logic problems.
The easiest way to do a problem like this is to write out the locations you're printing in terms of the variables you are iterating through. An extra variable, col helps us keep track of the current column opposite of the direction we are iterating from.
We can notice that the number just corresponds to the column position, squared, if we were counting columns from right to left.
We can also notice that the number of blank spaces is equal to n - one less than the current row iteration (since that starts at 0).
1
4 1
9 4 1
16 9 4 1
All of that nonsense aside, we can use String.format() to make the output even for double digit numbers.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int i = n; i > 0; i--) {
int col = 4;
// Print spaces
for (int j = 0; j < (i-1); j++) {
System.out.print(" ");
col--;
}
// Print numbers
for (int j = (i-1); j < n; j++) {
System.out.print(String.format("%2d", col*col) + " ");
col--;
}
System.out.println();
}
scan.close();
}
I have used the code you guys provided and it had some logical issues when inputting a number past 4 it would not square the triangle correctly and would only create the shape. I have solved the issue by adding a while loop and editing the for loops and not it outputs correctly.
Incorrect output:
Please enter a number between 1 and 9 inclusive: 8
9
4 9
1 4 9
0 1 4 9
1 0 1 4 9
4 1 0 1 4 9
9 4 1 0 1 4 9
16 9 4 1 0 1 4 9
Correct Code Given:
import java.util.Scanner;
public class AverageGrades {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int row = 1; row <= n; row ++) {
for (int col = n; col >= 1; col--) {
if (col <= row) {
System.out.print(String.format("%2d ", col * col));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
My Code:
import java.util.Scanner;
public class TriangleTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Number between 1 and 9 : ");
int n = scan.nextInt();
while(n < 0 || n > 9)
{
System.out.print("Please enter a valid value between 1 and 9 :");
n = scan.nextInt();
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= n*2-(i + i); j++)
{
System.out.print(" ");
}
for(int l = i + 1; l > 0; l--)
{
int r = l*l;
System.out.print(r + " ");
}
System.out.println("\n");
}
scan.close();
}
}
Correct Output:
Enter Number between 1 and 9 : 10
Please enter a valid value between 1 and 9 :9
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
49 36 25 16 9 4 1
64 49 36 25 16 9 4 1
81 64 49 36 25 16 9 4 1

Doubling a Matrix

I've created a two dimensional matrix and populated it with random numbers. I've then printed it out. I need help creating a second matrix that is twice the size of the first, and is populated with the numbers from the first one (which are now 2x2). For example:
Starting Matrix:
3 4
2 1
Doubled Matrix:
3 3 4 4
3 3 4 4
2 2 1 1
2 2 1 1
import java.util.Scanner;
import java.util.Random;
public class MatrixDoubler {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
System.out.println("Enter the size of the matrix");
int size = keyboard.nextInt();
int A[][] = new int[size][size];
for (int row = 0; row < size; ++row) {
for (int col = 0; col < size; ++col) {
A[row][col] = rand.nextInt(10);
}
}
System.out.println("Matrix A:");
printMatrix(A);
int[][] B = doubleMatrix(A);
System.out.println("Matrix B:");
printMatrix(B);
}
private static int[][] doubleMatrix(int[][] A) {
int rows = A.length;
assert(rows > 0);
int cols = A[0].length;
assert(cols > 0);
int B[][] = new int[rows * 2][cols * 2];
for (int row = 0; row < rows * 2; ++row) {
for (int col = 0; col < cols * 2; ++col) {
B[row][col] = A[row / 2][col / 2];
}
}
return B;
}
private static void printMatrix(int[][] M) {
for(int i = 0; i < M.length; i++) {
for(int j = 0; j < M.length; j++) {
System.out.print(M[i][j] + " ");
}
System.out.println();
}
}
}
I'm no sure if that is what you are looking for but try this:
for (int i = 0; i < newMatrix.length; i++) {
for (int j = 0; j < newMatrix.length; j++) {
newMatrix[i][j] = matrix[i/size][j/size];
}
}
Note: This code is surely not the best solution but a fast an easy one. It only works if both dimensions are the same size and it won't work if newMatrix is not exactly two times matrix. If it's always just to "double" a matrix it should work fine.
Output:
If you choose size 2 than it will output:
Enter the size of the matrix
2
The Matrix is
3 5
5 2
The newMatrix is
3 3 5 5
3 3 5 5
5 5 2 2
5 5 2 2
and for size 3 it would be for example
Enter the size of the matrix
3
The Matrix is
4 4 3
5 9 4
7 4 1
The newMatrix is
4 4 4 4 3 3
4 4 4 4 3 3
5 5 9 9 4 4
5 5 9 9 4 4
7 7 4 4 1 1
7 7 4 4 1 1
It's not clear what you are asking but I hope this helps (:
In Java 8 you can handle this pretty easily using maps and collectors. Here is a full example:
public class DoubleMatrix {
public static void main(String[] args) {
List<List<Integer>> startingMatrix = Arrays.asList(
Arrays.asList(3, 4),
Arrays.asList(2, 1)
);
List<List<Integer>> doubleMatrix
= startingMatrix.stream()
.map(innerList -> { //For each list
List<Integer> doubled = innerList.stream()
.map(element -> Arrays.asList(element, element)) //Return a list doubling each element
.flatMap(l -> l.stream()) //Flatten out/join all doubled lists
.collect(Collectors.toList());
return Arrays.asList(doubled, doubled); //Double the list
})
.flatMap(l -> l.stream())
.collect(Collectors.toList()); //Collect into a final list
System.out.println(doubleMatrix);
}
}
This avoids needing to know the size of the list beforehand, and is also tolerant of there being a difference between the width and height of your matrix - simply doubling every element in both directions.

Pyramid Pattern in Java

It was so hard to ask such a newbie question on this advanced site. But after so much tries and even loosing my hope i was forced to bring my self here. I am not been able to print the following pattern:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
But with my tiresome efforts i reached the following:
public static void main(String[] args) {
int num = 1;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print(num + " ");
}
System.out.println();
}
}
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
Here ya go
public static void main(String[] args) {
int max = 6;
int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;
for (int i = 0; i < max; i++) {
for (int j = 1; j < max - i; j++) {
System.out.print(pad(" ", padLength));
}
for (int k = 0; k <= i; k++) {
System.out.print(pad(Math.pow(2, k), padLength));
}
for (int k = i - 1; k >= 0; k--) {
System.out.print(pad(Math.pow(2, k), padLength));
}
System.out.println();
}
}
public static String pad(double d, int l) {
Integer i = (int) d;
return pad(i.toString(), l);
}
public static String pad(String s, int l) {
return String.format("%-" + l + "s", s);
}
Explanation
int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;
Math.pow(2,max) - Gives me maximal number I will have to display
Math.ceil(Math.log10(number + 1)) - I use this to determine length of string representation of specific number. Please refer to wikipedia to check what logarithm is. I add 1 to skip edge case when number is exact power of 10 e.g. log10(10)->1 (this will never occur in task specified in question, it's just for purity of solution). Ceil just rounds number up.
+2 - minimum gap between two numbers is specified example was 2 spaces long so I just add this
You could use here Integer.toString(((int)Math.pow(2, max))).length()+2 but it's not as pretty :)
return String.format("%-" + l + "s", s);
First I build format string that looks like e.g. %-3s, which means print String with minimum length of 3, padding on the right. Second argument is the String I want to print. Refer to documentation
Running example
I find the other answer very overwhelming and dramatic. You don't need much maths and complexity to solve this problem. This might not be the best code but I think it is easy to understand. Not even an explanation is needed, it is a row by row approach, It's good to keep things simple.
public static void main(String[] args) {
// Init
int row = 0;
int maxRows = 6;
int num = 1;
int indent = maxRows - 1;
// Printing loop
while (row < maxRows) {
// Indent
for (int i = 0; i < indent; ++i)
System.out.print(" ");
// Print nums
for (int i = 0; i < num; ++i)
System.out.printf("%4d", (int) Math.pow(2.0, i));
for (int i = num - 2; i >= 0; --i)
System.out.printf("%4d", (int) Math.pow(2.0, i));
// New line
System.out.println("");
// Adjustments
++row;
--indent;
++num;
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1

How do I write a program to output a triangle of numbers in Java?

I need help. My assignment is to write a Java program using nested loops to print out the following output pattern:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
//pattern1
for(int outer=1;outer<=6;outer++) // outer loop controls number of rows
{
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println(); // move the cursor from the end of the current line to the beggiing to the next line
}
//pattern 2
for(int outer =1; outer<=6 ; outer++) //outer loop controls number of rows
{
//3-1 create spaces before numbers.
for(int space=1; space<=6-outer; space++ ) //group controls number of spaces
{
System.out.print(" ");
}
//3-2 print out real numbers.
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println();
}
Those two codes are back to back, but I do not understand how I would make the numbers 2 4 8 16 etc show up, and put them back to back.
What's wrong with my code? Is there a better way of doing this in Java?
A simple version with bit shifting and static column size / padding - could be improved by using Math.getExponent() for dynamically repeating spaces and format %3d ...
public static void f(int n) {
for (int i = 0; i < n; i++) {
for (int l = n - i; l > 0; l--) { // padding for symmetry
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // "left side" of pyramid
System.out.printf("%3d ", 1 << j);
}
for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
System.out.printf("%3d ", 1 << k);
}
System.out.println();
}
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
You're going to use a nested loop with an if statement controlling the output.
This code should help you with your formatting. You'll have to figure out how to add the || so that it flips the triangle and how to format your print statements so it looks like that.
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
}else {
System.out.print("*");
}
}
System.out.println();
}
It will output
*
**
***
****
*****
******
*******
********
public class pyramid
public static void f(int n) {
for (int i = 0; i < n; i++) {
for (int l = n - i; l > 0; l--) { // padding for symmetry
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // "left side" of pyramid
System.out.printf("%3d ", 1 << j);
}
for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
System.out.printf("%3d ", 1 << k);
}
System.out.println();
}
}

Categories