Creating multiplication table by looping in Java - java

I was tasked to make a multiplication table from 1-10 but I was not satisfied with my code, it seems to be long:
for (int i = 1; i <= 10; i++)
{
System.out.println("1x" + i + " = " + i + "\t" + "2x" + i + " = " + (2*i)
+ "\t" + "3x" + i + " = " + (3*i) + "\t" + "4x" + i + " = " + (4*i)
+ "\t" + "5x" + i + " = " + (5*i) + "\t" + "6x" + i + " = " + (6*i)
+ "\t" + "7x" + i + " = " + (7*i) + "\t" + "8x" + i + " = " + (8*i)
+ "\t" + "9x" + i + " = " + (9*i) + "\t" + "10x" + i + " = " + (10*i));
}
Output:
1x1 = 1 2x1 = 2
1x2 = 2 2x2 = 4
etc.

Try something like
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.println(i + "x" + j + "=" (i*j));
}
}
so you have an inner and an outer loop, controlling what you want multiplied and what you want it multiplied by.
To be more explicit you could (should?) rename i and j as multiplier and multiplicand

This will format the table how you have it in your example code, and uses two loops:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i + "x" + j + "=" + (i * j) + "\t");
}
System.out.println();
}
The outer loop controls the rows in the multiplication table and the inner loop controls the columns in the multiplication table. System.out.println() signifies moving into a new row of the table

You could use two loops:
for (int i = 1; i <= 10; i++)
{
for (int j = i; j <= 10; j++)
{
System.out.println(i + "x" + j + "=" + (i*j));
}
}

for (int i = 1; i <= 10; i++)
{
for(int j=1; j<10; j++){
System.out.println(j+"x"+i+"="+(j*i)+"\t");
}
System.out.println("\n");
}

import java.util.Scanner;
public class TableMultiplication {
public static void main(String[] args) {
int table,count,total;
//Reading user data from console
Scanner sc = new Scanner(System.in);
//reading data for table
System.out.println("Enter Your Table:");
table = sc.nextInt();
//reading input for how much want to count
System.out.println("Enter Your Count to Table:");
count = sc.nextInt();
//iterate upto the user required to count and multiplay the table and store in the total and finally display
for (int i = 1; i < count; i++) {
total = table*i;
System.out.println(table+"*"+i+"="+total);
}//for
}//main
}//TableMultiplication

import java.util.Scanner;
public class P11 {
public static void main(String[] args) {
Scanner s1=new Scanner(System.in);
System.out.println("Enter a value :");
int n=s1.nextInt();
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
{
System.out.println(i+"x"+j+ "="+(i*j)+"\t");
}
}
}
}

Related

how to split number into pieces with remaining part

I want to split any number to any identical pieces and the last remaining but not dividable piece will be the last piece. I wrote this code but I know that it should be more simple way to do this :) For example; 7500 divided by 2000 and the last modulus part will be the last part. Any suggestions?
public class MyClass {
public static void main(String args[]) {
int x =7500;
int y = 2000;
int lastPartCount = 0;
String result = new String();
if(x%y != 0){
lastPartCount = x%y;
}
int newx = x-lastPartCount;
for(int i=1; i<=(newx/y); i++){
if(i == 1){//first member
result = "part " + i + ": 0-" + y*i;
}else
{
result = "part " + i + ": " + (y*(i-1)) + "-" + y*i;
}
System.out.println(result);
if(i == (newx/y)){//last member
result = "part " + (i+1) + ": " + (y*(i)) + "-" + x;
System.out.println(result);
}
}
}
}
the result is like this:
part 1: 0-2000
part 2: 2000-4000
part 3: 4000-6000
part 4: 6000-7500
You can simplify your code like the following:
public static void main(String args[]) {
int x = 7500;
int y = 2000;
for (int i = 0; i < x/y; i++) {
System.out.println("Part " + (i+1) + ": " + y*i + " - " + y*(i+1));
}
if (x%y != 0) {
System.out.println("Part " + ((x/y)+1) + ": " + (x/y)*y + " - " + x);
}
}
(x/y)*y) is not equal to x since you divide integers, so (x/y)*y is actually the same as the "next" i of the for-loop.
You can also try the below code:
private void test() {
int x = 7500;
int y = 2000;
int j = 0;
int newX = x;
while (newX > y) {
System.out.println("Part " + (j + 1) + " = " + y * j++ + " - " + y * j);
newX -= y;
}
System.out.println("Part " + (j + 1) + " = " + j * y + " - " + x);
}
Alternative approach using two variables in your for loop and Math.min():
int x = 7500;
int y = 2000;
for (int i = 0, p = 1; i < x; i += y, p++) {
System.out.printf("Part %d: %d - %d%n", p, i, Math.min(i+y,x));
}

Trying a different approach for Projet Euler Problem 8

So I'm new to Java and I'm trying a different solution for Project Euler Problem 8. In this I have used BigInteger class datatype to store the 1000-digit number but I'm not able to traverse the particular values at any index or multiply it like I'm trying. Although I was able to do it with String, I want to try this method. It would be a great help.
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class newexp{
public static void main(String[] args) {
BigInteger myBigInteger = new BigInteger(
"73167176531330624919225119674426574742355349194934\n" +
"96983520312774506326239578318016984801869478851843\n" +
"85861560789112949495459501737958331952853208805511\n" +
"12540698747158523863050715693290963295227443043557\n" +
"66896648950445244523161731856403098711121722383113\n" +
"62229893423380308135336276614282806444486645238749\n" +
"30358907296290491560440772390713810515859307960866\n" +
"70172427121883998797908792274921901699720888093776\n" +
"65727333001053367881220235421809751254540594752243\n" +
"52584907711670556013604839586446706324415722155397\n" +
"53697817977846174064955149290862569321978468622482\n" +
"83972241375657056057490261407972968652414535100474\n" +
"82166370484403199890008895243450658541227588666881\n" +
"16427171479924442928230863465674813919123162824586\n" +
"17866458359124566529476545682848912883142607690042\n" +
"24219022671055626321111109370544217506941658960408\n" +
"07198403850962455444362981230987879927244284909188\n" +
"84580156166097919133875499200524063689912560717606\n" +
"05886116467109405077541002256983155200055935729725\n" +
"71636269561882670428252483600823257530420752963450\n" +
"\n");
long s = 0;
int n = 1000;
long maxval = 0;
long currval = 1;
for (int i = 13; i <= n; i++){
for (long j = s; j <= 13; j++){
currval *= myBigInteger.valueOf(s);
}
s++;
}
if (maxval < currval){
maxval = currval;
}
System.out.println(maxval);
}
}
You don't really need BigInteger for this. The long's are sufficient to hold the product.
public class BigFib {
public static void main(String[] args) {
String bigNum =
"73167176531330624919225119674426574742355349194934"
+ "96983520312774506326239578318016984801869478851843"
+ "85861560789112949495459501737958331952853208805511"
+ "12540698747158523863050715693290963295227443043557"
+ "66896648950445244523161731856403098711121722383113"
+ "62229893423380308135336276614282806444486645238749"
+ "30358907296290491560440772390713810515859307960866"
+ "70172427121883998797908792274921901699720888093776"
+ "65727333001053367881220235421809751254540594752243"
+ "52584907711670556013604839586446706324415722155397"
+ "53697817977846174064955149290862569321978468622482"
+ "83972241375657056057490261407972968652414535100474"
+ "82166370484403199890008895243450658541227588666881"
+ "16427171479924442928230863465674813919123162824586"
+ "17866458359124566529476545682848912883142607690042"
+ "24219022671055626321111109370544217506941658960408"
+ "07198403850962455444362981230987879927244284909188"
+ "84580156166097919133875499200524063689912560717606"
+ "05886116467109405077541002256983155200055935729725"
+ "71636269561882670428252483600823257530420752963450";
int n = bigNum.length();
int start = 0;
long maxval = 0;
// count from 0 to the length of the string less 13.
for (int i = 0; i < n - 13; i++) {
// now starting at the first character, start taking the product of the
// digits.
long currval = 1;
for (int j = i; j < i+13; j++) {
// subtracting '0' from digit converts it to
// to an 'int'
currval *= (bigNum.charAt(j) - '0');
}
// if the current value is > maxval, assign to maxval
if (maxval < currval) {
maxval = currval;
start = i;
}
}
// now print the maxproduct and the string of digits.
System.out.println(maxval);
System.out.println("digits = " + bigNum.substring(start,start+13));
}
}

Find duplicated elements in a matrix

Introduction
I'm doing some homework where we are tasked for making a game of finding pairs.
I made a matrix and filled it with letters as such:
Display
----------------
C H F E
G F D D
E C H B
A B G A
Right now I'm currently testing the display method which uses an empty matrix and fills it with the given input (row_1, col_1, row_2, col_2, gameMatrix)
Problem
While creating a "cheat/test function" to test my display method. I encounter some trouble with finding the position of both A's (or any other letter).
This is my try at such method:
Code
public static void PlayMeBoi(String[][] gameMatrix)
{
int row_1 = 0;
int col_1 = 0;
int row_2 = 0;
int col_2 = 0;
for (int i = 0; i < gameMatrix.length; i++)
{
for (int j = 0; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_1 = i;
col_1 = j;
break;
}
}
}
for (int i = (row_1+1); i < gameMatrix.length; i++)
{
for (int j = (col_1+1); j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
Turn(row_1, col_1, row_2, col_2, gameMatrix);
}
Notes about the code
I'm working with String not char
Turn is the function which evaluates if a letter equals a letter (if "A".equals("A"))
The (row_1+1) and (col_1+1) it's my thought at "if I haven't found my letter previously, then the second 'for' will handle the rest of the matrix)
gameMatrix is the matrix where all the letters are loaded
Question
I want to be able to find the position of both "A" or any other letter inside the matrix. As of now, I'm not getting my desired result with my current idea
Feel free to comment about the code as much as you can. I might post it on GitHub later on for those who are interested or find anything useful in it.
Thanks for the interest in this question.
The second for is wrong. let's look at your example matrix:
C H F E
G F D D
E C H B
A B G A
If you're looking for the value D you'll find it first at row = 1 and col = 2. then in the second for you only runs from row = 2 and col = 3 which means in practice you'll iterate only over the right down cells from the position you found, which in this example will result in only 2 cells instead of 9 (marked in *):
C H F E
G F D D
E C H *B*
A B G *A*
So in the second for what you should do is continue the search from the same row and the next column:
for (int i = row_1; i < gameMatrix.length; i++)
{
// In the first row starting from the next cell, in the next rows start
// from column 0
int j = i == row_1 ? col_1 + 1 : 0;
for (; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
if I haven't found my letter previously, then the second 'for' will
handle the rest of the matrix
Correct, but what exactly is the rest of the matrix?
If the 1st A is found in row = 1 and col = 1, is the rest of the matrix every item with indices > 1. This would leave out items with indices (1,2) and (2,1) and (1,3) etc.
There are other issues also.
When you put a break inside a nested loop it only breaks form the nested loop and not the outer.
Here's a solution I came up with, maybe it's not optimal but I think it works:
public static void PlayMeBoi(String[][] gameMatrix) {
int row_1 = -1;
int col_1 = -1;
int row_2 = -1;
int col_2 = -1;
boolean found = false;
for (int i = 0; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 0; j < gameMatrix[0].length; j++) {
if ("A".equals(gameMatrix[i][j])) {
row_1 = i;
col_1 = j;
found = true;
break;
}
}
}
if (!found) {
System.out.println("Not Found");
return;
}
found = false;
for (int i = 1; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 1; j < gameMatrix[0].length; j++) {
if (i * gameMatrix[0].length + j > row_1 * gameMatrix[0].length + col_1) {
if ("A".equals(gameMatrix[i][j])) {
row_2 = i;
col_2 = j;
found = true;
break;
}
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
if (!found) {
System.out.println("Second Not Found");
return;
}
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
}

Getting min and max values from an array - Java

import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
int[] sales;
sales = getSales();
printSales(sales);
printSummary(sales);
}
private static int[] getSales() {
Scanner input = new Scanner(System.in);
int[] temp;
System.out.print("Enter the number of salespeople: ");
temp = new int[input.nextInt()];
for (int i = 0; i < temp.length; i++) {
System.out.print("Enter sales for salesperson " +
(i + 1) + ": ");
temp[i] = input.nextInt();
}
return temp;
}
private static void printSales(int[] s) {
System.out.println();
System.out.println("Salesperson Sales");
System.out.println("----------- -----");
for (int i = 0; i < s.length; i++) {
System.out.printf("%6d%12d\n", i + 1, s[i]);
}
}
private static void printSummary(int[] s) {
int sum = 0;
int max_sale = 0; // Salesperson with the most sales
int min_sale = 0; // Salesperson with the least sales
for (int i = 0; i < s.length; i++) {
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
}
System.out.println();
System.out.println("Total sales: " + sum);
System.out.println("Average sales: " + (double)sum / s.length);
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
}
}
The purpose of the application is to take the number of salespeople as input, along with their sales and then display individual sales, total sales, and average. That is working fine, but it's also supposed to display which salesperson had the max and minimum sales and what they were (lines 51 - 54). At the moment, any time the max is greater than the number of salespeople I get an ArrayIndexOutOfBoundsException and for whatever reason can't figure it out.
1 - Modify your for loop to get the max and min without modifying the array
2 - Try to print max and min instead of printing sum[max] and some[min] (which can throws IndexOutOfBoundsException)
3 - min_sale should be greater than 0, actually a value enough large (because you can have only positive values in your array)
To summarize :
int sum = 0;
int max_sale = Integer.MIN_VALUE; // Salesperson with the most sales
int min_sale = Integer.MAX_VALUE; // Salesperson with the least sales
for (int i = 0; i < s.length; i++){
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[i];
else if (s[i] < min_sale)
min_sale = s[i];
}
System.out.println("Salesperson " +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " +
" had the minimum sale with " +
min_sale);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
Here you are trying to assign the value in s[1] to max_sales. whereas you should be assigning max_sale = i. and the if condition should be
if(s[i] > s[max_sale] )
Updated code:
for (int i = 0; i < s.length; i++)
{
sum = (s[i] + sum);
// Finds the index of the sales person with best sales
if (s[i] >= s[max_sale])
max_sale = i;
// If this sales person is not the best, then check if he is last
else if (s[min_sale] > s[i])
min_sale = i;
}
the specific problem that's causing your error is here,
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
you're using your result as though it were an index
change it to the following
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
min_sale);

Nested For Loop and specific array element searching

I have a question on the method and process of how to look at these generated arrays.
Basically I want to create an array of [a,b,c,(a+b+c)] and as well as a second array of [d,e,f,(d+e+f)] and if the third element in array1 and array2 are the same, display the arrays to strings.
int num = 10;
for(int a = 0; a < num; a++){
for(int b = 0; b < num; b++){
for(int c = 0; c < num; c++){
if(a<=b && b<=c){
arrayOne[0] = a;
arrayOne[1] = b;
arrayOne[2] = c;
arrayOne[3] = (a+b+c);
}
}
}
}
for(int d = 0; d < num; e++){
for(int e = 0; e < num; e++){
for(int f = 0; f < num; f++){
if(d<=e && e<=f){
arrayTwo[0] = d;
arrayTwo[1] = e;
arrayTwo[2] = f;
arrayTwo[3] = (f -(d+e));
}
}
}
}
as you can see I am beyond stump.I am not quite sure where i can get each iteration of the arrays and compare the values by matching the sums in each array and as well as displaying the respective array they are in. Thank you all in advanced.
If I understand your question correctly if a=1, b=3, c=4 and d=2, e=3, f=3 you'd like to print something along the lines of 1 + 3 + 4 = 8 = 2 + 3 + 3. First, what you're doing right now is creating two arrays like Floris described in the comment. What you want to do is store all the values in one array of arrays, as follows:
int max; \\ To determine the value of max see the edit below.
int array[][] = new int[max][num];
int index = 0;
for (int a=0; a < num; a++) {
for (int b=a; b < num; b++) {
for (int c=b; c < num; c++) {
array[index][0] = a;
array[index][1] = b;
array[index][2] = c;
array[index][3] = a + b + c;
index++;
}
}
}
for (int i = 0; i < max; i++) {
for (int j = i; j < max; j++) {
if (array[i][3] == array[j][3]) {
string outString = array[i][0] + " + " + array[i][1] + " + " + array[i][2] + " = " + array[i][3] + " = " + array[j][0] + " + " + array[j][1] + " + " + array[i][2];
System.out.println(outString);
}
}
}
You can see that I improved performance by starting b from a and c from b since you are throw out all the values where b < a or c < b. This also should eliminate the need for your if statement (I say should only because I haven't tested this). I needed to use an independent index due to the complexities of the triple nested loop.
Edit 2: Ignore me. I did the combinatorics wrong. Let An,k be the number of unordered sets of length k having elements in [n] (this will achieve what you desire). Then An,k = An-1,k + An,k-1. We know that An,1 = n (since the values are 0, 1, 2, 3, 4, ..., n), and A1,n = 1 (since the only value can be 11111...1 n times). In this case we are interested in n= num and k = 3 , so plugging in the values we get
A_num,3 = A_num-1,3 + A_num,2
Apply the equation recursively until you come to an answer. For example, if num is 5:
A_5,3 = A_4,3 + A_5,2
= A_3,3 + A_4,2 + A_4,2 + A_5,1
= A_3,3 + 2(A_4,2) + 5
= A_2,3 + A_3,2 + 2(A_3,2) + 2(A_4,1) + 5
= A_2,3 + 3(A_3,2) + 2(4) + 5
= A_1,3 + A_2,2 + 3(A_2,2) + 3(A_3,1) + 2(4) + 5
= 1 + 4(A_2,2) + 3(3) + 2(4) + 5
= 1 + 4(A_1,2) + 4(A_2,1) + 3(3) + 2(4) + 5
= 1 + 4(1) + 4(2) + 3(3) + 2(4) + 5
= 5(1) + 4(2) + 3(3) + 2(4) + 5
It looks like this may simplify to (num + (num - 1)(2) + (num - 2)(3) + ... + (2)(num - 1) + num) which is binomial(num, num) but I haven't done the work to say for sure.
int givenNumber = 10;
int []arrayOne = new int [4];
int []arrayTwo = new int [4];
int count = 0;
for ( int i = 0; i < givenNumber; i ++)
{
for ( int x = 0; x < givenNumber; x ++ )
{
for ( int a = 0; a < givenNumber; a++ ){
arrayOne[0] = (int)(a * java.lang.Math.random() + x);
arrayOne[1] = (int)(a * java.lang.Math.random() + x);
arrayOne[2] = (int)(a * java.lang.Math.random() + x);
arrayOne[3] = (int)(arrayOne[0]+arrayOne[1]+arrayOne[2]);
}
for ( int b = 0; b < givenNumber; b++ ){
arrayTwo[0] = (int)(b * java.lang.Math.random() + x);
arrayTwo[1] = (int)(b * java.lang.Math.random() + x);
arrayTwo[2] = (int)(b * java.lang.Math.random() + x);
arrayTwo[3] = (int)(arrayTwo[0]+arrayTwo[1]+arrayTwo[2]);
}
if (arrayOne[3] == arrayTwo[3])
{
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayOne[a] + " + ");
} System.out.print(arrayOne[2] + " = " + arrayOne[3] + " = ");
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayTwo[a] + " + ");
} System.out.print(arrayTwo[2]);
System.out.println("\n");
count += 1;
}
}
}
if (count == 0)
System.out.println(
"\nOops! you dont have a match...\n" +
"Please try running the program again.\n");

Categories