I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.
Related
I need my matrices to look exactly like this.
Here are the two matrices, and the result when added:
2 2 7 4 3 4 3 3 5 6 10 7
4 4 8 8 6 8 5 5 10 12 13 13
1 9 3 7 6 8 6 9 7 17 9 16
2 3 2 9 + 4 4 7 1 = 6 7 9 10
2 9 1 1 9 8 2 5 11 17 3 6
6 1 8 4 4 8 2 2 10 9 10 6
Each number should use 4 positions in the output, and the + and = should be in the middle row, but I can not get the + and = signs to stay for smaller arrays. My problem may be with my if (i == 3 && j == 3) statements.
My code for this part is as follows.
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
// Declares 2-dimensional array the same size as one in parameters
int [][]arraySum = new int [array1.length][array1[0].length];
// Arithmetic characters to be printed when asked for
String add = "+";
String subtract = "-";
String multiply = "*";
String divide = "/";
String remainder = "%";
String equals = "=";
// If arithmetic is addition to print matrices and add them to show result
if (arithmetic == '+') {
// Text for two matrices when added
System.out.print("Here are the two matrices, and the result when added:\n");
// For loop to print array1 + array2 = sum with format
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == 3 && j == 3) {
System.out.printf("%2s", add);
}
}
System.out.print("\t");
// For loop to print out array2 and equals string
for (int k = 0; k < arraySum[i].length; k++) {
System.out.printf("%3s", array2[i][k] + " ");
if (i == 3 && k == 3) {
System.out.printf("%2s", equals);
}
}
System.out.print("\t");
// For loop to print out sum of array1 + array2
for (int l = 0; l < arraySum[i].length; l++) {
System.out.printf("%3s", sum[i][l] + " ");
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
Example of what I get for 3x3 arrays. (should still print + or =).
5 3 5 6 7 4 11 10 9
8 2 9 1 5 5 9 7 14
9 7 3 2 5 1 11 12 4
Try if (i == arraySum.length/2 && j == arraySum[i].length-1).
i and j are never 3 if your matrix is 3x3. If you want + and = in the middle then write something like this:
if (i == arraySum.length / 2 && j == arraySum[i].length - 1)
Replace if (i == 3 && j == 3) { with if (i == (array1 / 2) && j == (array1 / 2)) {
Your problem is that in the for loop, you are adding the addition sign and the equals sign in the 4th row (0,1,2,3). When you only have three rows, it won't print. What you can do to make it in the middle is something like this:
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length + 1; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == Math.ceil(arraySum.length/2) && j == arraySum.length) {
System.out.printf("%2s", add);
}
}
It will print the sign in the middle (height) and at the end (lengthwise) of the array. Just to be careful, it also uses the ceiling function to round up to the next integer.
How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);
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
I need to make this pyramid using nested for loops,
so far all I have figured out is that I need three for loops.
I know how for loops work and have a pretty good grasp on the fundamentals of java, but I have no earthly idea on how this works.
Just wrote this without debug but it should produce this pyramid:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
for(int j = 1; j < pyramidHeight*2;j++){
if( j < pyramidHeight - i || j > pyramidHeight + i ){
System.out.print(" ");
}
else{
System.out.print(i - Math.abs(pyramidHeight - j));
}
System.out.print(" ");
}
System.out.println();
}
With two simple changes you should get your pyramid.
This should work! Note that you have each row counting total 2*i+1 elements where i is your current row number.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int lim = 5;
int spaceLim = lim*2;
for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)
String s = "%" + spaceLim + "s";
System.out.printf(s, "");
if (i == 0){
System.out.print(1);
}
else{
for (int j=0; j<i; j++) {
System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
}
for (int j=i; j>=0; j--){
System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
}
}
System.out.println();
spaceLim -= 2;
}
}
}
The demo of working solution is here - http://ideone.com/J2fcQw
I need to print the following pattern and i almost did with the coding part.
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
Following is the program I tried
public class MyPattern {
public static void main(String[] args) {
for (int i = 0; i <= 7; i++) {
for (int j = 1; j <= 7 - i; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
int n = (int) Math.pow(2.0D, j);
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
}
for (int j = i - 1; j >= 0; j--) {
int n = (int) Math.pow(2.0D, j);
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
}
System.out.print('\n');
}
}
}
When running the program I got the following 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
But I need the output aligned to left (as specified first). Please help.
Well it's clearly caused by this part of code:
for (int j = 1; j <= 7 - i; j++) {
System.out.print(" ");
}
Have you tried running it without it?
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
Could also just be, as it does not matter what n is - it will all just do the same.
System.out.print(" " + n);
Comment the line:
//System.out.print(" ");
In the first for loop.
I hope this code helps you understand a few things.
// Make it ready for the loop, no point calling Math.pow() every loop - expensive
import static java.lang.Math.pow;
public class MyPattern {
public void showTree(int treeDepth) {
// Create local method fields, we try to avoid doing this in loops
int depth = treeDepth;
String result = "", sysOutput = "";
// Look the depth of the tree
for( int rowPosition = 0 ; rowPosition < depth ; rowPosition++ ) {
// Reset the row result each time
result = "";
// Build up to the centre (Handle the unique centre value here)
for( int columnPosition = 0 ; columnPosition <= rowPosition ; columnPosition++ )
result += (int) pow(2, columnPosition) + " ";
// Build up from after the centre (reason we -1 from the rowPosition)
for ( int columnPosition = rowPosition - 1 ; columnPosition >= 0 ; columnPosition-- )
result += (int) pow(2, columnPosition) + " ";
// Add the row result to the main output string
sysOutput += result.trim() + "\n";
}
// Output only once, much more efficient
System.out.print( sysOutput );
}
// Good practice to put the main method at the end of the methods
public static void main(String[] args) {
// Good practice to Create Object of itself
MyPattern test = new MyPattern();
// Call method on object (very clear this way)
test.showTree(5);
}
}
CS student here. I've just received an introduction to loops and I'm not sure I understand them very well. I'm trying to print a triangle of numbers n, such that if n = 4 you'd get something like this:
4
3 7
2 6 9
1 5 8 10
Instead I'm winding up with something like:
4
3 5
Suffice it to say I'm lost. Here's my code:
void drawT3 (int n)
{
int k = 1;
int t = 1;
for (int i=1;i<=n;i++)
{
k = n;
int j;
for (j=1;j<=n-i;j++)
System.out.print(" ");
for (j=1;j<=t;j++)
{
System.out.printf("%3d",k);
k += (n - j);
}
n--;
t++;
System.out.println();
}
}
void printTriangle(int n)
{
// build an auxiliary 2D array
final int t[][] = new int[n][n];
int i = 1;
for (int s = n - 1; s <= 2 * (n - 1); s++)
{
for (int x = s - n + 1; x < n; x++)
{
t[x][s - x] = i++;
}
}
// print the array
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
if (t[x][y] > 0)
{
System.out.printf("%3d", t[x][y]);
}
else
{
System.out.printf(" ");
}
}
System.out.println(); // start new line
}
}
Build an auxiliary 2D array of size n.
Put numbers into array as human will do, from 1 to n, following the diagonals. s in the code represents x + y sum. That sum is constant for every diagonal. In the first diagonal (the longest one) sum is equal to n - 1. In the second diagonal sum is 1 more, n. In the last "diagonal" (bottom right corner) the sum is 2 * (n - 1). That's exactly our loop: for (int s = n - 1; s <= 2 * (n - 1); s++). Having the sum and x we can obtain y with simple subtraction, y = s - x.
Print the array. Each cell of array is initialized with 0 (int's default value). So, if a cell has zero, we just print 3 spaces, to preserve the shape of triangle.
PS. My code was written for "educational purposes" :) To show how it can be done, in easy way. It's not optimized for speed nor memory.
public static void main(String[] args) {
// TODO code application logic here
triangle(4);
}
static public void triangle(int n){
int x = 0;
for (int i = n;i>0;i--){
System.out.print(i + " ");
x = i+n;
for (int j=0;j<n-i;j++){
System.out.print(x - j + " ");
x = x + n -j;
}
System.out.println("");
}
}
Output for 4:
4
3 7
2 6 9
1 5 8 10
Output for 6:
6
5 11
4 10 15
3 9 14 18
2 8 13 17 20
1 7 12 16 19 21
Observe that there are many ways to print out a triangle of numbers as described above, For example, here are two,
// for n=5,
// 1 2 3 4 5
// 6 7 8 9
// 10 11 12
// 13 14
// 15
And
// 5
// 4 9
// 3 8 12
// 2 7 11 14
// 1 6 10 13 15
And since recursion is Fun!
class triangle
{
//Use recursion,
static int rowUR( int count, int start, int depth )
{
int ndx;
if(count<=0) return start;
//-depth?
for (ndx=0;ndx<depth;ndx++)
{
System.out.print(" ");
}
//how many? 5-depth, 5,4,3,2,1
for( ndx=0; ndx<count; ++ndx )
{
System.out.printf("%3d",start+ndx);
}
System.out.printf("\n");
if( count>0 )
{
rowUR( count-1, ndx+start, depth+1 );
}
return ndx;
}
//Use recursion,
static int rowLR( int count, int start, int depth )
{
int ndx, accum;
if( start < count )
rowLR( count, start+1, depth+1 );
for( ndx=0; ndx<depth; ++ndx )
{
System.out.print(" ");
}
accum=start;
//how many? 5-depth, 1,2,3,4,5
for( ndx=0; ndx<(count-depth); ++ndx )
{
System.out.printf("%3d",accum);
accum+=count-ndx;
}
System.out.printf("\n");
return ndx;
}
public static void main(String[] args)
{
int count=4, depth=0, start=1;
System.out.printf("rowUR\n");
rowUR( count=5, start=1, depth=0 );
System.out.printf("rowLL\n");
rowLL( count=5, start=1, depth=0 );
}
};
int n=4,i,j,k,t;
for (i=n;i>=1;i--)
{
t=i;
k=n;
for(j=1;j<i;j++)
System.out.printf(" "); // for leading spaces
System.out.printf("%3d",i); // for first digit(or number) in each row (in your example these are 4,3,2,1)
for(j=i;j<n;j++)
{
t+=k;
System.out.printf("%3d",t);
k--;
}
System.out.print("\n");
}
OUTPUT:
for n=8
8
7 15
6 14 21
5 13 20 26
4 12 19 25 30
3 11 18 24 29 33
2 10 17 23 28 32 35
1 9 16 22 27 31 34 36
http://ideone.com/C1O1GS
make space around numbers according to your need.
PS: I would never suggest to write any pattern code using array unless it is very complicated. array will use extra memory space.