formatting a multiplication table with line spacing - java

I'm trying to make a multiplication table which is as big as the user specifies. The problem I'm having is with the format. The output right now prints all the numbers to one line, whereas I want it all on multiple lines on a nice neat table. With it formatted as it is, I can't tell where the \n would go to do so, or if there is another way.
here's my code:
import java.util.*;
public class question2 {
public static void main(String [] args) {
Scanner keyb = new Scanner(System.in);
int i = 0;
while (i<=0 || i>=11) {
System.out.print("please enter an integer between 1 and 10: ");
i = keyb.nextInt();
}
for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
}
}
}
EDIT:
The output for integer 5, prints like this:
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

After the second for loop, add a new line \n:
for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
System.out.println();
}

You should add a newline after the second for loop, and since you print x don't print x * 1. So,
for (int x = 1; x <= i; x++) {
System.out.printf("%4d", x);
for (int y = 2; y <= i; y++) {
System.out.printf("%4d", x * y);
}
System.out.println();
}
or you could eliminate the first print like,
for (int x = 1; x <= i; x++) {
for (int y = 1; y <= i; y++) {
System.out.printf("%-4d", x * y); // and simply for variety, left-aligned
}
System.out.println();
}
or if you are using Java 8+, you might use IntStream like
IntStream.rangeClosed(1, i).forEachOrdered(x -> {
IntStream.rangeClosed(1, i).forEachOrdered(y -> System.out.printf(
"%-4d", x * y));
System.out.println();
});

Try the following. My screen only fits 14 numbers neatly. I make a list (it can house empty space '') and then I start to display the list neatly using the end='\t' argument keyword to create tabs.
n = int(input('Enter a number(max 14): '))
# n = 12
list_x = list(range(1,n + 1))
list_y = list(range(1,n + 1))
list_z = ['',] + list_x
for y in list_y:
list_z.append(y)
for x in list_x:
x = x*y
list_z.append(x)
count = 0
for i in list_z:
print(i, end='\t')
count += 1
if count == (n + 1):
count = 0
print('', end='\n',)

Related

number pattern programs in java

How to print the triangle below:
2 3 5 8 3 8
4 6 9 4 9
7 1 5 1
2 6 2
7 3
4
First you need to start with number 2 and add one to the next one vertically
My code:
int d = 2, n = 6;
for (int line=1; line <= n; line++ ) {
for (int j = 2; j <= line; j++) {
System.out.print(" ");
}
for (int k = line; k <= n; k++) {
System.out.print(d + " ");
d = d + k;
if (d > 9) {
d = d - 9;
}
}
System.out.println();
}
Result:
2 3 5 8 3 8
5 7 1 5 1
7 1 5 1
7 2 7
4 9
6
The pattern is that the value of d has to be calculated initially on every new line based on the value of d in the first instance of the previous line. That is the part that's missed here. You can do that by having a temp variable store the initial value of d on every line and print based on that. I have used a variable tempD here, which can help print the pattern that you require.
int d = 2, n = 6;
int tempD = d - 1;
for (int line = 1; line <= n; line++) {
tempD = tempD + line;
if (tempD > 9) {
tempD = tempD - 9;
}
d = tempD;
for (int j = 2; j <= line; j++) {
System.out.print(" ");
}
for (int k = line; k <= n; k++) {
System.out.print(d + " ");
d = d + k;
if (d > 9) {
d = d - 9;
}
}
System.out.println();
}

For loop in Java for filling up table

Let's say i have a table format in Java
0 1 2
|_E_|____|____| 0
|___|____|____| 1
Where the numbers at the top are the index of the column and the numbers on the side are the index of the row. A function:
add_at(x,y)
takes two arguments x and y which is the x coordinate and y coordinate. I'm trying to fill up the table using a for loop for which it begins from the position 0,1 which is
0 1 2
|_E_|__x_|____| 0
|___|____|____| 1
marked with x, followed by 0,2
0 1 2
|_E_|__x_|__x_| 0
|___|____|____| 1
proceeding with
0 1 2
|_E_|__x_|__x_| 0
|_x_|____|____| 1
0 1 2
|_E_|__x_|__x_| 0
|_x_|__x_|____| 1
0 1 2
|_E_|__x_|__x_| 0
|_x_|__x_|__x_| 1
until the table is filled except for the location 0,0 which is marked by E.
int max_row = 1; //maximum row length is 1
int max_col = 2; //maximum column length is 2
for (int x = 0; x<=max_row; x++) {
for (int y = 1; y<max_col; y++) {
this.add_at(x,y)
}
}
I'm a beginner at Java and I'm pretty sure the for loop i wrote is wrong in a way where i wanted the output to be. Would appreciate some help on this.
Change y to be initialised to zero (i.e. populate all rows) and add a special condition for (0,0).
Also, both conditions should use <=.
int max_row = 1; //maximum row length is 1
int max_col = 2; //maximum column length is 2
for (int x = 0; x <= max_row; x++) {
for (int y = 0; y <= max_col; y++) {
if (x == 0 && y == 0) continue;
this.add_at(x,y);
}
}
You can do as following, and u can change the code according to your needs:
public class Table {
public static void main(String[] args) {
int maxRow = 4; //maximum row length is 4
int maxCol = 5; //maximum column length is 5
for (int x = 0; x<maxRow; x++) {
for (int y = 0; y<maxCol; y++) {
if (x==0 && y==0){
System.out.print("| |");
continue;
}
add_at(x, y);
}
System.out.println();
}
}
public static void add_at(int x, int y) {
System.out.print("|x|");
}
}
The result will be like:
| ||x||x||x||x|
|x||x||x||x||x|
|x||x||x||x||x|
|x||x||x||x||x|
You can see the screenshot from the output:
I hope the code helps you

Rotating sequential numbers to right

Its easy enough to rotate numbers to the left. I would do the following:
int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
for(int j = 0; j < numberCount; j++)
{
System.out.print((i+j) % numberCount + " ");
}
System.out.println();
}
In this example the following would be printed:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
How would you do the same thing, but rotating the numbers to the right?
The answer was obvious once I thought about it-- to move a number left, you add to it, so to move right, you subtract from it. I thought the formula would be significantly changed, so I was thinking of formulas that were much more complicated than the solution turned out to be.
// ensures mod is positive
int mod(int a, int b)
{ return (a%b+b)%b; }
int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
for(int j = 0; j < numberCount; j++)
{
System.out.print(mod((j-i), numberCount) + " ");
}
System.out.println();
}

Java creation of a spiral [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Looping in a spiral
I'm creating a program to populate a 3 by 3 matrix. I want to result in something looking like this
5 4 3
6 1 2
7 8 9
As you have probably noticed it is a spiral.
Now the algorithm I'm using is this: I have a 2-d array where the values represent the coordinates of the number. First I assign that every number coordinate in this array will have a value of 10. Then starting at 9 I decrease my x coordinate and assign the value of the coordinate to currentnum - 1 until it reaches the end or its value is not 10; Then I do the same thing except I increase the value of Y; Then decrease the value of x; Then of Y;
The reason I assign 10 to every number is so like it acts as a road for my program. Since current num will never exceed 9. If the value of a square is 10 it is like a green light. If it is not 10 meaning a value has been assigned to that square it breaks out of it.
Here is my code, please note it is written in Java
public class spiral {
/**
* #param args
*/
public static void main(String[] args) {
int spiral [] [] = new int[3][3];
for(int i = 0; i <= 2; i++){
for(int j = 0; j <= 2; j++){
spiral[i][j] = 10;
}
}
//0 is x value, 1 is y value
spiral[0][0] = 9;
int x = 1;
int y = 1;
int counter = 1;
int currentnum = 9;
int gridsquare = 3;
for(int i = 0; i <= 8; i++){
if(counter == 5){
counter = 1;
}
if(counter == 1){
System.out.println(x + " " + y);
for(int j = 0;j <= 1;j++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
x += 1;
}
else{
y += 1;
break;
}
}
}
if(counter == 2){
for(int k = 0; k <= 0; k++){
System.out.print(x + " " + y);
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
y += 1;
}
else{
x -= 1;
break;
}
}
}
if(counter == 3){
for(int z = 0; z <= 0; z++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
x -= 1;
}
else{
y -= 1;
break;
}
}
}
if(counter == 4){
for(int b = 0; b <= 0; b++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
y -= 1;
}
else{
x += 1;
break;
}
}
}
counter++;
}
System.out.print(currentnum);
}
}
I'm getting this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at spiral.main(spiral.java:44)
Since I'm new to Java would someone please suggest a posible fix for this. Also if you see any problems with my algorithm please do inform me.
You do not need to pre-fill with 10: zero works just as well.
I think the best approach to solving the spiral is to think of how you do it manually: start in a corner, and go horizontally until you hit non-zero or an edge of the array. Then you turn right. Stop when the current number goes past N*N.
Now let's look at what each part of the algorithm means:
Starting in the corner means setting x=0 and y=0.
Going in a straight line means x=x+dx, y=y+dy, where either dx or dy is zero, and dy or dx is 1 or -1.
Turning right means assigning dx to dy and -dy to dx.
Here is how it looks in the code:
int current = 1;
// Start in the corner
int x = 0, y = 0, dx = 1, dy = 0;
while (current <= N*N) {
// Go in a straight line
spiral[x][y] = current++;
int nx = x + dx, ny = y + dy;
// When you hit the edge...
if (nx < 0 || nx == N || ny < 0 || ny == N || spiral[nx][ny] != 0) {
// ...turn right
int t = dy;
dy = dx;
dx = -t;
}
x += dx;
y += dy;
}
You've incremented x or y to 3 which is past the end of one of your arrays.
Step through your program with the debugger or add System.out.println statements before each if (counter) to find out where you're doing this.

Printing all Possible nCr Combinations in Java

I'm trying to print out all possibilities of nCr, which are the combinations when order doesn't matter. So 5C1 there are 5 possibilities: 1 , 2, 3, 4, 5. 5C2 there are 10 possibilities: 1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5.
I made functions that print what I want for r = 2, r = 3, and r = 4, and I sort of see the pattern, but I cant seem to make a working method for variable r:
public void printCombinationsChoose2(int n, int k) //for when k = 2
{
for (int a = 1; a < n; a++)
{
for (int b = a + 1; b <= n; b++)
{
System.out.println("" + a + " " + b);
}
}
}
public void printCombinationsChoose3(int n, int k) //for when k = 3
{
for (int a = 1; a < n - 1; a++)
{
for (int b = a + 1; b < n; b++)
{
for (int c = b + 1; c <= n; c++)
{
System.out.println("" + a + " " + b + " " + c);
}
}
}
}
public void printCombinationsChoose4(int n, int k) //for when k = 4
{
for (int a = 1; a < n - 2; a++)
{
for (int b = a + 1; b < n - 1; b++)
{
for (int c = b + 1; c < n; c++)
{
for (int d = c + 1; d <= n; d++)
{
System.out.println("" + a + " " + b + " " + c + " " + d);
}
}
}
}
}
public void printCombinations(int n, int k) //Doesn't work
{
int[] nums = new int[k];
for (int i = 1; i <= nums.length; i++)
nums[i - 1] = i;
int count = 1;
while (count <= k)
{
for (int a = nums[k - count]; a <= n; a++)
{
nums[k - count] = a;
for (int i = 0; i < nums.length; i++)
System.out.print("" + nums[i] + " ");
System.out.println();
}
count++;
}
}
So I think the layout of my last method is right, but I'm just not doing the right things, because when I call printCominbations(5, 2), it prints
1 2
1 3
1 4
1 5
1 5
2 5
3 5
4 5
5 5
when it should be what I said earlier for 5C2.
Edit
The last example was bad. This is a better one to illustrate what it's doing wrong: printCombinations(5, 3) gives this:
1 2 3
1 2 4
1 2 5
1 2 5
1 3 5
1 4 5
1 5 5
1 5 5
2 5 5
3 5 5
4 5 5
5 5 5
How do I get it to be:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
How about this:
public class Test {
public static void main(final String[] args) {
print_nCr(7, 4);
}
public static final void print_nCr(final int n, final int r) {
int[] res = new int[r];
for (int i = 0; i < res.length; i++) {
res[i] = i + 1;
}
boolean done = false;
while (!done) {
System.out.println(Arrays.toString(res));
done = getNext(res, n, r);
}
}
/////////
public static final boolean getNext(final int[] num, final int n, final int r) {
int target = r - 1;
num[target]++;
if (num[target] > ((n - (r - target)) + 1)) {
// Carry the One
while (num[target] > ((n - (r - target)))) {
target--;
if (target < 0) {
break;
}
}
if (target < 0) {
return true;
}
num[target]++;
for (int i = target + 1; i < num.length; i++) {
num[i] = num[i - 1] + 1;
}
}
return false;
}
}
The key to this solution for me was to look at the problem as a numbering system and you want to increase a number by one and every time you reach an upper bound, you just carry the excess to the left one and ... You just need to implement the increasing algorithm correctly...
The first point where your code deviates from the expectation is here:
...
1 2 5
1 2 5 <-- first bad output
1 3 5
...
So ask yourself three things:
What should have happened in that line of code with the given state of the variables?
Why doesn't do my code exactly that?
What must be changed to achieve that?
The answer for the first part is like this:
It should have incremented the 2 to 3 and it should have set the following numbers to
4, 5, ... similar to the initialisation of nums.
The second and third part is your part again.
BTW: When you come back because you need more help, please explain in detail what you have deduced so far and clean up and shorten the question quite a bit.
OK... What is the solution when we know we need loops, but not the number of them?? RECURSION...
You need to use a recursive implementation. Have this in mind: ANYTIME, you need loops but the number of the nested loops can only be known at runtime, based on the specific parameters of the problem, you should use recursive methods... I'll give you some time to try it yourself, I'll be back to give you the final implementation...
I have done it in c++
#include <iostream>
using namespace std;
#define ARR_LIMIT 100
int arr[ARR_LIMIT];
void _ncr(int N,int R, int n,int r , int start )
{
if(r>0)
{
for(int i = start ; i <= start + (n-r); i++)
{
arr[R-r] = i;
_ncr(N,R,N-i, r-1, i+1 );
}
}
else
{
for(int i=0;i<R;i++)
{
cout << arr[i] << " ";
if(i==R-1)
cout<<"\n";
}
}
}
void ncr(int n,int r)
{
//Error checking of parameters
bool error = false;
if( n < 1)
{
error = true;
cout<< "ERROR : n should be greater 0 \n";
}
if( r < 1)
{
error = true;
cout<< "ERROR : r should be greater 0 \n";
}
if(r > n)
{
error = true;
cout<< "ERROR : n should be greater than or equal to r \n";
}
// end of Error checking of parameters
if(error)
return;
else
_ncr(n,r,n,r,1);
}
int main()
{
int n,r;
cout << "Enter n : ";
cin >> n;
cout << "Enter r : ";
cin >> r;
ncr(n,r);
return 0;
}
The layout of function printCombination() seems wrong. The while loop will iterate two times, for count = 1 and count = 2.
When count = 1, only values in nums[0][here] will change, since in this case k - count = 1.
Hence,
1,2
1,3
1,4 and
1,5.
And when count = 2, only values in nums[here][1] will change, since here k - count = 0.
Hence
1,5
2,5
3,5
4,5 and
5,5

Categories