Get the next sequence in an arithmetic or geometric progression - java

I want to make an application that takes a sequence of 3 numbers per line to produce and stops when it reaches a sequence of zeros and then prints if it's an arithmetic progression or geometric progression and the next number in the series.
Example input:
4 7 10
2 6 18
0 0 0
should output
AP 13
GP 54
here is my code I wanna know what's wrong with it and what are the possibilities that won't work with my code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
static String s="";
public static void main (String[] args) throws IOException
{
String c;
String a[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
c= br.readLine();
a = c.split(" ");
if(c.charAt(0)!='0'){
calc(a[1], a[2]);
}
}while((c.charAt(0))!='0');
printer(s);
}
public static void calc(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
if(y%x==0){
s += "GP" +" " + (y*(y/x)) + "z";
return;
}else{
s += "AP" + " " + (y + (y-x)) + "z";
return;
}
}
public static void printer(String s){
String p= "";
for(int i =0;i<=s.length()-1;i++){
if(s.charAt(i)!='z'){
p+= s.charAt(i);
}else{
System.out.println(p);
p= "";
}
}
}
}

Your problem it that you discover progression type incorrectly. For example, 0 4 8 is obviously AP, but your algorithm will say it is GP. Another example: 8 4 2 is GP, but 2%4 will return false, saying it is AP. Also, you don't proceed cases when offered sequence is not progression at all.
It is absolutely clear that all 3 numbers should be involved. Suppose that integer numbers a, b, c form AP or GP, and you need to discover which progression it is. Simple math can be used:
If they form AP, then a + c = b + b. Next element is c + c - b
If they form GP, then a * c = b * b. Next element is c * c / b
(Please notice how + is changed to *, and - to /, when you switch from AP to GP).

Your code works on the assumption that if two consecutive numbers of a 3 number series is divisible, the series is a GP and that if it's not, it has to be an AP. This assumption is wrong. There are many cases in which it will not be true, such as a series 0,3,6. It is an AP, not a GP. So instead of sending 2 parameters to the function calc(), you should send all three numbers as parameters, and check as follows:
if((a+c)==(2*b))
{//AP
}
else if((a*c)==(b*b))
{//GP
}
These above are the proper check for Arithmetic and Geometric progressions. Also while checking if the inputs are all 0, you are only checking for the first element. Instead you have to see if all three of the elements are 0. Your code might not work in the case of 0,3,6 or 0,2,4 or 0,1,2. So instead you have to check like this:
int flag=0;
for(int i=0;i<3;i++)
if(Integer.parseInt(a[i]))
flag=1;
if(flag==1)
{//continue prog
}
else
{//Terminate prog as input is 0,0,0
}

Related

calculator Java adding numbers

So, my question is, how do I turn this make my calculator app be able to take input like this, 100 * 2 / 2 + 5 and make it return the sum of it?
or maybe even somehow make it use ( ) brackets..?
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number: ");
String input = scanner.nextLine();
System.out.println("Enter number 2: ");
String input2 = scanner.nextLine();
System.out.println("Enter operator ");
String op = scanner.nextLine();
int intEnter1 = Integer.parseInt(input.toString());
int intEnter2 = Integer.parseInt(input2.toString());
if (op.contains("+")) {
System.out.println(intEnter1 + intEnter2);
}
if (op.contains("-")) {
System.out.println(intEnter1 - intEnter2);
}
if (op.contains("*")) {
System.out.println(intEnter1 * intEnter2);
}
if (op.contains("/")) {
double intEnter1Double = (double) intEnter1;
double intEnter2Double = (double) intEnter2;
System.out.println(intEnter1Double / intEnter2Double);
}
}
}
There is also a very good library for evaluating math expressions called exp4j.
You can do something like this:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
You have to convert your expression to Reverse Polish notation.
The idea is to transform complex expression to such form that it will be possible to calculate the result using the following algorithm:
expression is parsed from left to right
numbers are pushed to stack
if an operator occured, the correspondent amount of numbers a popped
from stack (1 for unary operator, 2 for binary) and the operation is performed on them
For example, given the input:
5 + ((1 + 2) × 4) − 3
the notation will as following:
5 1 2 + 4 × + 3 −
I found a library that makes that evaluate expressions. You can try this.
http://javaluator.sourceforge.net/en/home/
Double value = new DoubleEvaluator().evaluate(expression);
But this library make all work for you and maybe you want to do by yourself the algorithm no?

Pascal's Triangle Formatting

I have a program that finally works to print pascal's triangle, kind of.
For whatever reason when it prints, it prints all the rows correctly as you would assume, but at the end of each row where it should just stop at one the last whole row is pasted. I'll give an example.
Instead of just this:
Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
121
1331
14641
It prints this:
Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
1211
1331211
14641331211
Those extra tidbits on the end are not supposed to be there. I have no idea why there are there. Any help is much appreciated.
"Yes, it is supposed to use recursion, and no, I can't change that."
Here is my code:
import java.util.Scanner;
public class pascalsTriangle {
public static int rows;
public static String list = "";
public static String line = "1";
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the row number up to which Pascal's triangle has to be printed: ");
rows = scan.nextInt();
System.out.println("Rows to print: " + rows);
scan.close();
if (rows == 1)
System.out.println("1");
else {
System.out.println(print(1, rows));
}
}
public static String print(int largest, int row) {
if (row < 1)
return "1";
else{
list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
}
return list;
}
public static String curLine(int n, int k, int last) {
if(n > k && n != 0){
line = Integer.toString(last) + curLine(n, k + 1, last*(n - k)/(k + 1));
}
return line;
}
}
When your program moves to put together the next line of the triangle, your String variable line needs to be reset back to just "1". What's happening is that when your program moves to the next line, line is still the previous line of numbers, and it adds the triangle onto that. Notice how the "extra tidbit" on the last line: 14641'331211' matches up with the row above it: 1'331211'
Alternatively you could work-around this using a substring by changing your line:
list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
To:
list = print(1, row - 1) + "\n" + curLine(row, 0, 1).substring(0,row+1);
And that will solve your problem entirely

Dr Java Help inputted equation not working

//In the following lines of code the user is asked to enter a length to determine the volume of a regular icosahedron, however, when entered the programm always outputs 0.0 as the answer for the volume???
import java.io.*; //allows I/o statements
class VolumeIcosahedron //creating the 'volumeIcosahedron' class
{
//allows strings with exceptions to IO = input/output
public static void main (String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(
new InputStreamReader (System.in)); //system input/ output
String stringNum; // the number string
double V; // integer with decimals volume
int L; // integer required length
//System output
System.out.println("Hello, what is the required length");
stringNum = myInput.readLine();
L = Integer.parseInt(stringNum);
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
System.out.println("The volume of the regular Icosahedron is " + V);
}
}
Because 5/12 in integer equals 0 so it always results in 0.
Try with 5.0 to force the division without involving integer division.
V = 5.0/12 *(3.0 + Math.sqrt(5))*(L*L*L);
I think this is the offending line:
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
5/12 returns an int (whole number), which is always truncated down to 0, hence 0 * anything will return 0.
Change it to this, using the letter d to signify that these numbers are of type double:
V = 5d/12d *(3 + Math.sqrt(5))*(L*L*L);
The reason is that you are using integer inside the calculation.
With integer, you should see the division as an euclidean operation, ie a = bq + r.
So in your program, 5/12 will always return 0 (5 = 0 * 12 + 5).
If you change the line to be like this (replacing every integer by double):
V = 5.D/12.D *(3.D + Math.sqrt(5.D))*(L*L*L);
Then the result will be different.

Rounding doubles to the nearest whole number in Java?

How do I round my numbers of output += Math.pow(baseUno, powernumber)+ " "; to the nearest whole number?
They always give me an output of, for example, 1.0 or 2.0. How do you round these so that they would simply result as 1 and 2?
import javax.swing.*;
import java.text.*;
import java.util.*;
public class level7Module1
{
public static void main(String[] args)
{
String base, power, output = " "; //user inputs, and the output variable
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations
DecimalFormat noDigits = new DecimalFormat("0");
// oneDigit.format(variablename)
base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: \nPress 'q' to quit."); //User input
if (base.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0); //quits
}
baseUno = Integer.parseInt(base);
// basenum = noDigits.format(baseUno);
if (baseUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (baseUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things
//that would fit on my monitor :)
power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.\nPress 'q' to quit.");
if (power.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0);
}
powerUno = Integer.parseInt(power);
// powernum = noDigits.format(powerUno);
if (powerUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (powerUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going.
{
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above.
}
JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs
}
}
To the simplest approach change this line :
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);
to
JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
just type caste the result to int

Sets using bit strings in Java trouble

public class BitStringOperations3
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
int setA = 0;
int setB = 0;
int elementsSetA = 0;
int elementsSetB = 0;
System.out.println ("How many integers are in set A?");
elementsSetA = in.nextInt ();
while (elementsSetA > 9 || elementsSetA < 0)
{
System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
elementsSetA = in.nextInt();
}
System.out.println ("How many integers are in set B?");
elementsSetB = in.nextInt ();
while (elementsSetB > 9 || elementsSetB < 0)
{
System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
elementsSetB = in.nextInt();
}
for (int i = 1; i <= elementsSetA; i++)
{
System.out.println ("Please enter integer number " + i + " in set A: ");
setA = add(setA, in.nextInt() );
}
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = add(setB, in.nextInt () );
}
}
public static boolean setContainsValue (int set, int value)
{
boolean setContainsValue = (set & maskForValue) != 0;
return true;
}
public static int addValueToSet (int set, int newValue)
{
set = set | maskForValue;
return set;
}
public static void printSet (int set, int value)
{
int mask = 1;
System.out.print ("{");
for (int i = 0; i<= 9; i++)
{
if(( mask & set ) == 1)
System.out.print(i + " " );
int maskForValue = 1 << value;
set >>= 1; //set = (set >> 1);
}
System.out.println ("} ");
}
}
I am having trouble with an assignment for school. We are given the universal set U = {0-9}. I have to gather user input for both sets, and then use bit strings (we are not allowed to use the Set or HashSet classes in java) to store the sets and perform operations on them, such as complement, Set A union Set B and such. I know how to do those, but my code does not convert Sets A and B into the memory correctly and therefore, I cannot perform any operations on them. Help will be gladly appreciated! Thanks in advance. :)
Edit 1:
Alright, I read your ideas and tried to implement them as good as I could, and I have given the result above. This program really pushes me out of my comfort zone and I really appreciate all the help.
First of all, do yourself a favour and create helper methods. Then concentrate only on making them correct:
public static boolean contains(int set, int value) {
//return true if value bit is 1 in set
}
public static int add(int set, int newValue) {
//add newValue to set and return it
}
Afterwards you can express your logic more clearly:
if ( contains(set, 1) ) {
//print 1
}
Some general hints:
Don't use Math.pow() as that is made for floating-point numbers. To get a power of 2 as an integer, use bit shifting:
int maskForValue = 1 << value;
To check if a certain bit is set, find the mask for that bit and use &. This zeros out all bits except for the bit you're checking.
boolean setContainsValue = (set & maskForValue) != 0;
To set a bit in a bit field, find the mask for that bit and use |. This ensures that that bit becomes 1.
set = set | maskForValue;
Edit
As to your direct problem, take a look at this:
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = in.nextInt ();
}
You're overwriting setA and setB every time. In the end, setA and setB will contain the last value the user specified. Then later, you do this:
for (int i = 0; i <=9; i++)
setB |= (int)pow(2.0, i-1);
Which just ignores the user's input and overwrites all bits 0-9 (though in an unsafe way!). So of course what the user inputs is irrelevant.
Get rid of the latter for loops and then store the input like this (using the helper methods I described above):
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = add(setB, in.nextInt());
}
Edit 2
You seem to be having problems understanding where I'm coming from with my idea of these "helper" methods. If this is the first time you've worked with methods that have parameters, sorry for clouding up the issue. But they allow you to focus on getting one piece of functionality working at a time. I'll expand on what I mean more here:
public static boolean setContainsValue(int set, int value) {
//return true if the bit string (or bit set) represented by the "set" parameter
//contains the value stored in the "value" parameter
//see the FIRST and SECOND bullet points above for how to do this
}
public static int addValueToSet(int originalSet, int valueToAdd) {
//add the value stored in the "valueToAdd" parameter to the set represented by the
//"originalSet" parameter and return the result
//see the FIRST and THIRD bullet points above for how to do this.
}
I'll even write some tests for you too. The methods above haven't been implemented properly until at least all of the following print true:
int set = 0;
System.out.println( ! contains(set, 1) ); //make sure set doesn't contain 1
set = addValueToSet(set, 1);
System.out.println( contains(set, 1) ); //make sure set now contains 1
System.out.println( !contains(set, 2) ); //make sure set doesn't contain 2
set = addValueToSet(set, 2);
System.out.println( contains(set, 1) ); //make sure set still contains 1
System.out.println( contains(set, 2) ); //make sure set now contains 2
First, you need a class (this is object-oriented programming, right?) to contain the "DigitSet".
public DigitSet {
private BitSet digits;
public DigitSet() {
// digits contains one bit for each digit
digits = new BitSet(10);
}
... rest of DigitSet code goes here, like ...
/**
* Check if this set contains a particular digit.
*/
public boolean contains(int value) {
// check to see if value is a valid input (0-9)
// look in digits to see if the "right" bit is set.
}
public void set(int value) {
// check to see if value is a valid input (0-9)
// set the "right" bit in digits to 1.
}
public void clear(int value) {
// check to see if value is a valid input (0-9)
// set the "right" bit in digits to 0.
}
public DigitSet union(DigitSet other) {
// construct a "new" output DigitSet.
// Walk through all of the digits in "this" set
// if a digit is set in this set, set it in the output set.
// Walk through all of the digits in the "other" set
// if a digit is set in the other set, set it in the output set.
}
public String toString() {
// return a display string based on the set "digit" bits
}
}
Then the rest is just input handling and "perform the operation"
public static void main(String[] args) {
DigitSet first = new DigitSet();
// read in the values for the first digit set, for each value
// set the digit in first like so
first.set(value);
DigitSet second = new DigitSet();
// read in the values for the second digit set, for each value
second.set(value);
DigitSet result = first.union(second);
System.out.println("Result: " + result.toString());
}

Categories

Resources