Change random operator or variable - java

I have an assignment in my programming class. It goes like this, I have to make a program which takes the input of the user how many exercises he wants to do. Then he solves simple calculations with random numbers from 1-10 and with random operators. In the end, it should write how many correct and incorrect ones did he get. It also should write the elapsed time of the task.
I did some work, but when I assign a random value to an operation
int operation = (int)(Math.random()*3)+1;
or to a number a and b
int a = (int)(Math.random()*10);
int b = (int)(Math.random()*10);
I always get the same number and operator when I choose for the second or third time my task (because I use a loop). Is there a way to change the same initialized variable or operator during a program. For example that int a=(int)(Math.Random()*10) is initialized in the beginning as for example as 3, and later when the program loops again to initialize it as a different number, for example 6. Are there any others solutions for my problem?
Here is my whole code, for now:
import java.util.*;
import javax.swing.JOptionPane;
public class RandomChar {
public static void main(String[] args) {
char op= ' ';
int operation = (int)(Math.random()*3)+1;
int a = (int)(Math.random()*10);
int b = (int)(Math.random()*10);
String s;
int correct = 0, incorrect=0;
s = JOptionPane.showInputDialog("How many exercises do you want?");
int num = Integer.parseInt(s);
long tStart = System.currentTimeMillis();
while(num>0){
if(operation==1)
op='+';
else if(operation==2)
op='-';
else if(operation==3)
op='*';
String str1 = JOptionPane.showInputDialog(a+" "+op+" "+b+" = ");
int num1 = Integer.parseInt(str1);
if(op=='+'){
if(a+b==num1)
correct++;
else
incorrect++;
}else if(op=='-'){
if(a-b==num1)
correct++;
else
incorrect++;
}else if(op=='*'){
if(a*b==num1)
correct++;
else
incorrect++;
}
num--;
}
long tEnd = System.currentTimeMillis();
long tOverral = tEnd - tStart;
double elapsedSeconds = tOverral / 1000.0;
System.out.println("Correct: "+correct);
System.out.println("Incorrect: "+incorrect);
System.out.println("Elapsed seconds: "+ elapsedSeconds);
}
}

Simply move the calculation of random numbers and the operator into your while-loop. Actually you calculate them once.
while (num > 0) {
int operation = (int) (Math.random() * 3) + 1;
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
...
}
So you'll have new numbers and operators in any exercise.

Related

Java - beginner code, adding fractions

I have a school project due next week and I'm trying to crack the way to solve this question.
The problem was to develop a program that adds the fractions the user inputs until he types -1.
the input will always be in pair and positive numbers.
Must only use: int, for,while, if, scanner (so no break or arrays)
Preferably with the use of GCD since it's required to println the
reduced sum of fractions
So my questions are this:
can I use a while loop until user types -1 using the scanner?
Is it alright to use the 'while' to let a user type 'infinite' (I am aware that there is no such this in java) number of number until termination?
in the code of the previous question I wrote the common factor for
the equation, how do I write a common factor for an unknown number of
variables
Edit:
here is my code, the problem is, it only runs for 4*n numbers, I need it to be able to run for 2*n numbers: ( like 2/4 or 2/4+1/3+1/2)
Scanner myScanner=new Scanner(System.in);
int a;
int b;
int c;
int d;
int m = a*d + b*c;
int n = b*d;
int r = m%n;
while((a = myScanner.nextInt()) != -1)
{
b = myScanner.nextInt();
c = myScanner.nextInt();
d = myScanner.nextInt();
while (r != 0) {
m=n;
n=r;
r = m%n;
}
m = (a*d + b*c)/n;
n = (b*d)/n;
System.out.println(m);
System.out.println(n);
}
}
A.
It is possible to keep reading input from a scanner until a defined message (in this case pairs of numbers until -1 is entered)
Scanner scanner = new Scanner(System.in);
int num1;
int num2;
while((num1 = scanner.nextInt()) != -1)
{
num2 = scanner.nextInt();
//do stuff with num1 and num2
}
B.
The whole point of A. is to allow variable amounts of input from the user, so unless you have a reason for a hard limit, it should in theory take infinite input
C.
Instead of trying to compute the common factor before you have any numbers, it's easier to compute the common factor as you get the numbers
int newNumerator = numerator1 * denominator2 + numerator2 * denominator1;
int newDenominator = denominator1 * denominator2;
Keeping track of the current numerator and denominator, updating as you get more pairs
This can then have A. be applied to it for infinite input
Scanner scanner = new Scanner(System.in);
int numerator = 0;
int denominator = 0;
int tempNumer = 0;
int tempDenom = 0;
if((numerator = scanner.nextInt()) != -1)
{
denominator = scanner.nextInt();
while((tempNumer = scanner.nextInt()) != -1)
{
tempDenom = scanner.nextInt();
numerator = numerator * tempDenom + tempNumer * denominator;
denominator = denominator * tempDenom;
}
}

recursively add integers from 1^2 to n^2

i'm having some trouble recursively adding integers in java from 1^2 to n^2.
I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop.
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
}//end if
if (n == 1){
return 1;
}//end if
if (n > 1){
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
}//end if
return 0;
}//end method
}//end class
I'm not fully grasping the nature of defining this recursively, as i know that i can get to here:
return (int) (Math.pow(n, 2));
but i can't incorporate the calling of the recurvMath method correctly in order for it to work.
Any help would be appreciated. Thanks!
In general, when trying to solve recursive problems, it helps to try to work them out in your head before programming them.
You want to sum all integers from 12 to n2. The first thing we need to do is express this in a way that lends itself to recursion. Well, another way of stating this sum is:
The sum of all integers from 12 to (n-1)2, plus n2
That first step is usually the hardest because it's the most "obvious". For example, we know that "a + b + c" is the same as "a + b", plus "c", but we have to take a leap of faith of sorts and state it that way to get it into a recursive form.
So, now we have to take care of the special base case, 0:
When n is 0, the sum is 0.
So let's let recurvMath(n) be the sum of all integers from 12 to n2. Then, the above directly translates to:
recurvMath(n) = recurvMath(n-1) + n2
recurvMath(0) = 0
And this is pretty easy to implement:
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
} else {
return recurvMath(n-1) + (n * n);
}
}
Note I've chosen to go with n * n instead of Math.pow(). This is because Math.pow() operates on double, not on int.
By the way, you may also want to protect yourself against a user entering negative numbers as input, which could get you stuck. You could use if (n <= 0) instead of if (n == 0), or check for a negative input and throw e.g. IllegalArgumentException, or even use Math.abs() appropriately and give it the ability to work with negative numbers.
Also, for completeness, let's take a look at the problem in your original code. Your problem line is:
recurvMath((int) ((int) n+Math.pow(n, 2)))
Let's trace through this in our head. One of your int casts is unnecessary but ignoring that, when n == 3 this is recurvMath(3 + Math.pow(3, 2)) which is recurvMath(12). Your number gets larger each time. You never hit your base cases of 1 or 0, and so you never terminate. Eventually you either get an integer overflow with incorrect results, or a stack overflow.
instead of saying:
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
i instead said:
return (int) ((Math.pow(n, 2)+recurvMath(n-1)));
Try this
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 1){
return 1;
}//end if
// More simplified solution
return recurvMath(n-1) + (int) Math.pow(n, 2); // Here is made changes
}//end method
}//end class

Understanding methods. Java code

Write a method that computes the sum of the digits in an integer. Use
the following method header: public static int sumDigits(long n)
Programming problem 5.2. Page 212.
Please forgive my newness to programming. I'm having a hard time understanding and answering this question. Here's what I have so far. Please assist and if you dont mind, explain what I'm doing wrong.
import java.util.Scanner;
public class PP52v2 {
public static void main(String [] args) {
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}//main
public static int sumDigits(long n) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
n = input.nextLong();
int num = (int)(n);
int sum;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}//loop
return sum;
}//sumDigits
}//class
Basically, you should not be handling the user input inside of the method. You should be passing the user input into your method. Other than that, everything looks good. I've made that slight change below:
import java.util.Scanner;
public class PP52v2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
long n = input.nextLong();
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}// main
public static int sumDigits(long n) {
int num = (int) (n);
int sum = 0;
while (num > 0) {
sum += num % 10; // must mod - gives individual numbers
num = num / 10; // must divide - gives new num
}// loop
return sum;
}// sumDigits
}// class
Do the prompt
System.out.println("Enter your digits");
n = input.nextLong();
in your main(String[] args) method because n is not currently declared in the scope of the main method.
public static int sumDigits(int num) {
int sum = 0;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new number
} //End loop
return sum;
}
For one, you should not read in the number within this method, as it accepts the number as a parameter. The method should be invoked after calling long inputNum = input.nextLong(); by using int digitSum = sumDigits((int)inputNum).
When writing a method, you have input, output, and side effects. The goal is to choose the right combination of the three so that the method, and program as a whole, words as expected.
It seems like your method is supposed to take a number as input and return each digit added together into one final sum.
Write A Test
Usually when you program, you come up with some code that uses your imaginary function. This is called a test. For a test, this could work:
System.out.println("123 should be 6: " + sumDigits(123));
Choose A Signature
You've already managed to right the correct signature. Nice!
Implement Method
Here's where you're a bit confused. Read through what every line of code does, and see if it is accomplishing your goal.
// set up a scanner for reading from the command line
// and print a message that you expect digits
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
// read the next long number from the input stream
n = input.nextLong();
Why is this part of your method? You already have the number passed in as the argument n.
// cast the number to an integer
int num = (int)(n);
Again, not sure what this is accomplishing, besides the possibility of a bug for large numbers.
// initialize the sum variable to 0.
int sum;
Would be clearer to explicitly set the sum to 0. int sum = 0;
// add the last digit and truncate the number in a loop
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}
// actually return the calculated sum
return sum;
This seems like the only part of the method you need. Hopefully this helps!
Since the input number can be either positive or negative, you need to convert it to its absolute value to get the sum of digits. Then for each iteration, you add the remainder to the total sum until the quotient is 0.
public static int sumDigits(long n) {
int sum = 0;
long quotient = Math.abs(n);
while(quotient > 0) {
sum += quotient % 10;
quotient = (long) quotient / 10;
}
return sum;
}
Your code works fine for me.
i just changed int sum = sumDigits(n) to int sum = sumDigits(0) since n wasn't declared.
To have it done correctly, you just would have to put your scanner into the main method and pass the result of it (the long value) to your method sumDigits(long n).

How to find the base10 of (x:g)?

I am at the end of my homework, and a little confused on the right way to go for this algorithm. I need to find the base10 of a number:base that user gives.
Basically what my program does is take user input such as, 407:8 or 1220:5 etc.
What I am trying to output is like this.
INPUT: 407:8
OUTPUT: 407 base 8 is 263 base 10
I was thinking of this long stretched out way of doing it but I am sure there is a way easier way to go about it.
Attached is what i have so far. Thanks for looking!!
import javax.swing.JOptionPane; //gui stuff
import java.util.Scanner; // Needed for accepting input
import java.text.*; //imports methods for text handling
import java.lang.Math.*; //needed for math stuff*
public class ProjectOneAndreD //my class + program name
{
public static void main(String[] args) //my main
{
String input1; //holds user input
int val=0, rad=0, check1=0; //holds integer values user gives
and check for : handler
double answer1=0; //holds the answer!
Scanner keyboard = new Scanner(System.in);
//creates new scanner class
do //will continue to loop if no : inputted
{
System.out.println("\t****************************************************");
System.out.println("\t Loading Project 1. Enjoy! "); //title
System.out.println("\t****************************************************\n\n");
input1 = JOptionPane.showInputDialog("INPUT: ","EXAMPLE: 160:2"); //prompts user with msgbox w/ example
System.out.println("Program Running..."); //gives user a secondary notice that everything is ok..
check1=input1.indexOf(":"); //checks input1 for the :
if(check1==-1) //if no : do this stuff
{
System.out.println("I think you forgot the ':'."); //let user know they forgot
JOptionPane.showMessageDialog(null, "You forgot the ':'!!!"); //another alert to user
}
else //otherwise is they remembered :
{
String numbers [] = input1.split(":"); //splits the string at :
val = Integer.parseInt(numbers[0]); //parses [0] to int and assigns to val
rad = Integer.parseInt(numbers[1]); //parses [1] to int and assigns to rad
//answer1 = ((Math.log(val))/(Math.log(rad))); //mathematically finds first base then
//answer1 = Integer.parseInt(val, rad, 10);
JOptionPane.showMessageDialog(null, val+" base "+rad+" = BLAH base 10."); //gives user the results
System.out.println("Program Terminated..."); //alerts user of program ending
}
}while(check1==-1); //if user forgot : loop
}
}
You can use Integer.parseInt(s, radix).
answer = Integer.parseInt(numbers[0], rad);
You parse number in given radix.
It's easy, just replace your commented out logic with this:
int total = 0;
for (int i = 0; val > Math.pow(rad, i); i++) {
int digit = (val / (int) Math.pow(10, i)) % 10;
int digitValue = (int) (digit * Math.pow(rad, i));
total += digitValue;
}
and total has your answer. The logic is simple - we do some division and then modulus to pull the digit out of val, then multiply by the appropriate radix power and add to the total.
Or, if you want to make it a little more efficient and lose the exponentials:
int total = 0;
int digitalPower = 1;
int radPower = 1;
while (val > radPower) {
int digit = (val / digitalPower) % 10;
int digitValue = digit * radPower;
total += digitValue;
digitalPower *= 10;
radPower *= rad;
}
You only have implemented the user interface. Define a method taking two integers (the base and the number to convert) as argument, and returning the converted number. This is not very difficult. 407:8 means
(7 * 8^0) + (0 * 8^1) + (4 * 8^2)
You thus have to find a way to extract 7 from 407, then 0, and then 4. The modulo operator can help you here. Or you could treat 407 as a string and extract the characaters one by one and transorm each of them into an int.

Counting trailing zeros of numbers resulted from factorial

I'm trying to count trailing zeros of numbers that are resulted from factorials (meaning that the numbers get quite large). Following code takes a number, compute the factorial of the number, and count the trailing zeros. However, when the number is about as large as 25!, numZeros don't work.
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double fact;
int answer;
try {
int number = Integer.parseInt(br.readLine());
fact = factorial(number);
answer = numZeros(fact);
}
catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static double factorial (int num) {
double total = 1;
for (int i = 1; i <= num; i++) {
total *= i;
}
return total;
}
public static int numZeros (double num) {
int count = 0;
int last = 0;
while (last == 0) {
last = (int) (num % 10);
num = num / 10;
count++;
}
return count-1;
}
I am not worrying about the efficiency of this code, and I know that there are multiple ways to make the efficiency of this code BETTER. What I'm trying to figure out is why the counting trailing zeros of numbers that are greater than 25! is not working.
Any ideas?
Your task is not to compute the factorial but the number of zeroes. A good solution uses the formula from http://en.wikipedia.org/wiki/Trailing_zeros (which you can try to prove)
def zeroes(n):
i = 1
result = 0
while n >= i:
i *= 5
result += n/i # (taking floor, just like Python or Java does)
return result
Hope you can translate this to Java. This simply computes [n / 5] + [n / 25] + [n / 125] + [n / 625] + ... and stops when the divisor gets larger than n.
DON'T use BigIntegers. This is a bozosort. Such solutions require seconds of time for large numbers.
You only really need to know how many 2s and 5s there are in the product. If you're counting trailing zeroes, then you're actually counting "How many times does ten divide this number?". if you represent n! as q*(2^a)*(5^b) where q is not divisible by 2 or 5. Then just taking the minimum of a and b in the second expression will give you how many times 10 divides the number. Actually doing the multiplication is overkill.
Edit: Counting the twos is also overkill, so you only really need the fives.
And for some python, I think this should work:
def countFives(n):
fives = 0
m = 5
while m <= n:
fives = fives + (n/m)
m = m*5
return fives
The double type has limited precision, so if the numbers you are working with get too big the double will be only an approximation. To work around this you can use something like BigInteger to make it work for arbitrarily large integers.
You can use a DecimalFormat to format big numbers. If you format your number this way you get the number in scientific notation then every number will be like 1.4567E7 this will make your work much easier. Because the number after the E - the number of characters behind the . are the number of trailing zeros I think.
I don't know if this is the exact pattern needed. You can see how to form the patterns here
DecimalFormat formater = new DecimalFormat("0.###E0");
My 2 cents: avoid to work with double since they are error-prone. A better datatype in this case is BigInteger, and here there is a small method that will help you:
public class CountTrailingZeroes {
public int countTrailingZeroes(double number) {
return countTrailingZeroes(String.format("%.0f", number));
}
public int countTrailingZeroes(String number) {
int c = 0;
int i = number.length() - 1;
while (number.charAt(i) == '0') {
i--;
c++;
}
return c;
}
#Test
public void $128() {
assertEquals(0, countTrailingZeroes("128"));
}
#Test
public void $120() {
assertEquals(1, countTrailingZeroes("120"));
}
#Test
public void $1200() {
assertEquals(2, countTrailingZeroes("1200"));
}
#Test
public void $12000() {
assertEquals(3, countTrailingZeroes("12000"));
}
#Test
public void $120000() {
assertEquals(4, countTrailingZeroes("120000"));
}
#Test
public void $102350000() {
assertEquals(4, countTrailingZeroes("102350000"));
}
#Test
public void $1023500000() {
assertEquals(5, countTrailingZeroes(1023500000.0));
}
}
This is how I made it, but with bigger > 25 factorial the long capacity is not enough and should be used the class Biginteger, with witch I am not familiar yet:)
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number : ");
long number = in.nextLong();
long numFactorial = 1;
for(long i = 1; i <= number; i++) {
numFactorial *= i;
}
long result = 0;
int divider = 5;
for( divider =5; (numFactorial % divider) == 0; divider*=5) {
result += 1;
}
System.out.println("Factorial of n is: " + numFactorial);
System.out.println("The number contains " + result + " zeroes at its end.");
in.close();
}
}
The best with logarithmic time complexity is the following:
public int trailingZeroes(int n) {
if (n < 0)
return -1;
int count = 0;
for (long i = 5; n / i >= 1; i *= 5) {
count += n / i;
}
return count;
}
shamelessly copied from http://www.programcreek.com/2014/04/leetcode-factorial-trailing-zeroes-java/
I had the same issue to solve in Javascript, and I solved it like:
var number = 1000010000;
var str = (number + '').split(''); //convert to string
var i = str.length - 1; // start from the right side of the array
var count = 0; //var where to leave result
for (;i>0 && str[i] === '0';i--){
count++;
}
console.log(count) // console shows 4
This solution gives you the number of trailing zeros.
var number = 1000010000;
var str = (number + '').split(''); //convert to string
var i = str.length - 1; // start from the right side of the array
var count = 0; //var where to leave result
for (;i>0 && str[i] === '0';i--){
count++;
}
console.log(count)
Java's doubles max out at a bit over 9 * 10 ^ 18 where as 25! is 1.5 * 10 ^ 25. If you want to be able to have factorials that high you might want to use BigInteger (similar to BigDecimal but doesn't do decimals).
I wrote this up real quick, I think it solves your problem accurately. I used the BigInteger class to avoid that cast from double to integer, which could be causing you problems. I tested it on several large numbers over 25, such as 101, which accurately returned 24 zeros.
The idea behind the method is that if you take 25! then the first calculation is 25 * 24 = 600, so you can knock two zeros off immediately and then do 6 * 23 = 138. So it calculates the factorial removing zeros as it goes.
public static int count(int number) {
final BigInteger zero = new BigInteger("0");
final BigInteger ten = new BigInteger("10");
int zeroCount = 0;
BigInteger mult = new BigInteger("1");
while (number > 0) {
mult = mult.multiply(new BigInteger(Integer.toString(number)));
while (mult.mod(ten).compareTo(zero) == 0){
mult = mult.divide(ten);
zeroCount += 1;
}
number -= 1;
}
return zeroCount;
}
Since you said you don't care about run time at all (not that my first was particularly efficient, just slightly more so) this one just does the factorial and then counts the zeros, so it's cenceptually simpler:
public static BigInteger factorial(int number) {
BigInteger ans = new BigInteger("1");
while (number > 0) {
ans = ans.multiply(new BigInteger(Integer.toString(number)));
number -= 1;
}
return ans;
}
public static int countZeros(int number) {
final BigInteger zero = new BigInteger("0");
final BigInteger ten = new BigInteger("10");
BigInteger fact = factorial(number);
int zeroCount = 0;
while (fact.mod(ten).compareTo(zero) == 0){
fact = fact.divide(ten);
zeroCount += 1;
}
}

Categories