My calculator isn't calling upon variables properly - java

I'm writing a calculator in java that has memory to store variables. It shows the list of variables properly, adds and subtracts, and defines variables, but whenever I try to do something like a = b + 1, it treats b as if it is 0, giving 'a' a value of 1.
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
ArrayList<String> variables = new ArrayList<>();
while(scan.hasNextLine())
{
String line = scan.nextLine();
String[] tokens = line.split(" ");
if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var"))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==1)
{
if(variables.contains(tokens[0]))
{
printAnswer(values.get(variables.indexOf(tokens[0])));
}
else if(!line.equals("quit"))
{
int width = 4 + tokens[0].length();
System.out.printf("%" + width + "s is not defined\n", tokens[0]);
}
break;
}
if(tokens.length==3)
{
value = Integer.parseInt(tokens[2]);
printAnswer(value);
if(variables.contains(tokens[0]))
{
values.set(variables.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
variables.add(tokens[0]);
}
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value, variables, values);
printAnswer(value);
if(variables.contains(tokens[0]))
{
values.set(variables.indexOf(tokens[0]), value);
}
else
{
values.add(value);
variables.add(tokens[0]);
}
break;
}
else if(tokens[i].charAt(0) == '-')
{
value = subtraction(tokens, value);
printAnswer(value);
if(variables.contains(tokens[0]))
{
values.set(variables.indexOf(tokens[0]), value);
}
else
{
values.add(value);
variables.add(tokens[0]);
}
break;
}
else if(i==tokens.length-1)
{
System.out.println("No operation");
break;
}
}
}
if(Character.isDigit(tokens[0].charAt(0)))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==1)
{
value = Integer.parseInt(tokens[0]);
printAnswer(value);
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value, variables, values);
printAnswer(value);
}
else if(tokens[i].charAt(0) == '-')
{
value = subtraction(tokens, value);
printAnswer(value);
}
}
}
if(line.equals("clear"))
{
clear(variables, values);
}
if(line.equals("var"))
{
variableList(variables, values);
}
else if(line.equals("quit"))
{
System.exit(0);
}
}
}
public static int addition(String[] a, int b, ArrayList<String> c, ArrayList<Integer> d)
{
for(String item : a)
{
int i=0;
if(Character.isDigit(item.charAt(0)))
{
int val = Integer.parseInt(item);
b = b + val;
i++;
}
else if(Character.isLetter(item.charAt(0)) && i!=0)
{
int val = d.get(c.indexOf(item));
b = b + val;
}
}
return b;
}
public static int subtraction(String[] a, int b)
{
int i=0;
for(String item : a)
{
if(Character.isDigit(item.charAt(0)))
{
int val = Integer.parseInt(item);
if(i==0)
{
b = b + val;
i++;
}
else
{
b = b - val;
}
}
}
return b;
}
public static void clear(ArrayList<String> a, ArrayList<Integer> b)
{
a.clear();
b.clear();
}
public static void variableList(ArrayList<String> a, ArrayList<Integer> b)
{
for(int i=0; i<a.size(); i++)
{
int width = 4 + a.get(i).length();
System.out.printf("%" + width + "s: %d\n", a.get(i), b.get(i));
}
}
public static void printAnswer(int a)
{
int width = 3;
Integer valueToString = a;
String valueString = valueToString.toString();
for(int j=0; j<=valueString.length(); j++)
{
width++;
}
System.out.printf("%" + width + "d\n",a);
}
Main problem is within the addition method

I could explain to you why your program is setting 'a' to 1 when you enter the command "a + b + 1", but this will not really help you. You need to take a hard look at your code, step through it a bit, and see if you can structure it more logically, because right now it is just a bunch of statements strung together that do not actually define any meaningful behavior. Writing comments and using more meaningful variable names helps a lot.
A few notes on this:
Never in your loop do you check for the '=' sign. This means that the commands:
"a = b + 1"
"a + b + 1"
...get processed exactly the same way, assigning a value of 1 to 'a'
Your addition and subtraction methods do not account for position whatsoever. This means that the first operator encountered is applied to all tokens in the string. I.e:
"a c + d - 3 - - x 5"
...is exactly the same as:
"a c + d + + + 3 5 x"
(Note that both of these strings are utter nonsense)
Try using a debugger to step through your code and see what it is doing. That will help you a lot.

Related

How do you return multiple values from a for loop in Java using a return statement?

I would like to send multiple values from my getMultiples method to my main method using a return statement and no print or println statements.
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n")
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int getMultiples(int a, int b) {
int p = 0;
for (int i = 1; i <= a; i++) {
p = getMultiple(a,i);
}
return (p);
}
}
I have tried putting the return statement in the for loop but it does not work.
In Java as soon as return is encountered in the code, method is removed from execution stack and flow is returned back to calling method. So you can not return multiple values from a method. Rather you should create a list/array and return that as below(array example):
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n");
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p[] = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int[] getMultiples(int a, int b) {
int[] p = new int[a];
for (int i = 1; i <= a; i++) {
p[i-1] = getMultiple(a,i);
}
return p;
}
}

How do I get user input into two separate arrays?

Hi I am having trouble with Scanner to get user input two separate ArrayList. When I run this code I get an IndexOutOfBounds exception after entering the two arrays.
The code adds two binary numbers together using logic of a ripple adder. An example of intended user input would be
Enter A array: 1 0 1 0
Enter B Array: 0 0 0 1
producing: 1 0 1 1
The code works when arrays are hard coded, how can I get the user to enter the arrays?
Code is shown below
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner inputA = new Scanner(System.in);
ArrayList<Integer> aList = new ArrayList<Integer>();
ArrayList<Integer> bList = new ArrayList<Integer>();
int c = 0;
System.out.println("Enter A array");
aList.add(inputA.nextInt());
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
bList.add(inputB.nextInt());
Adder bit1 = new Adder(parseInput(aList.get(3)), parseInput(bList.get(3)), parseInput(c));
Adder bit2 = new Adder(parseInput(aList.get(2)), parseInput(bList.get(2)), bit1.getCout());
Adder bit3 = new Adder(parseInput(aList.get(1)), parseInput(bList.get(1)), bit2.getCout());
Adder bit4 = new Adder(parseInput(aList.get(0)), parseInput(bList.get(0)), bit3.getCout());
if (bit4.getCout() == false) {
System.out.println(bit4.toString() + " " + bit3.toString() + " " + bit2.toString() + " " + bit1.toString());
} else {
System.out.println("overflow!");
}
}
public static boolean parseInput(int i) {
if (i == 1) {
return true;
} else {
return false;
}
}
}
Code for Adder class:
public class Adder {
private boolean a, b, cin, cout, s;
/**
* Full Adder contructor
*/
public Adder(boolean a, boolean b, boolean cin) {
this.a = a;
this.b = b;
this.cin = cin;
s = nand(nand(a, b), cin); //sum bit
cout = or(and(nand(a, b), cin), and(a, b)); // - carry bit
}
/** Half adder constructor */
// public Adder (bloolean a, boolean b) {
//
// this.a = a;
// this.b = b;
//
// s =
//}
/**
* NAND gate
*/
public boolean nand(boolean a, boolean b) {
return a ^ b;
}
/**
* AND gate
*/
public boolean and(boolean a, boolean b) {
return a && b;
}
/**
* OR gate
*/
public boolean or(boolean a, boolean b) {
return a || b;
}
public boolean getCout() {
return cout;
}
public String toString() {
if (s == true) {
return "1";
} else {
return "0";
}
}
public String toStringCout() {
if (cout == true) {
return "1";
} else {
return "0";
}
}
}
Your entire AdderApp class can be simplified and improved to accept any bit length by accepting the input in a slightly different way and then using a for loop to add each bit. The parseInput function can be replaced with a simple boolean comparison:
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter A array");
char[] aIn = input.nextLine().replace(" ", "").toCharArray();
System.out.println("Enter B array");
char[] bIn = input.nextLine().replace(" ", "").toCharArray();
StringBuilder result = new StringBuilder();
Adder bit = new Adder(false, false, false);
for (int i = aIn.length - 1; i >= 0; --i) {
bit = new Adder((aIn[i] == '1'), (bIn[i] == '1'), bit.getCout());
result.append(bit + " ");
}
System.out.println(bit.getCout() ? "overflow!" : result.reverse());
}
}
Scanner.nextInt gets the next integer in the input, and then stops. Each of your lists only contains 1 element.
Use something along these lines instead:
String[] input = inputA.nextLine().split(" ");
for (String s : input)
{
try { aList.add(Integer.parseInt(s)); }
catch(NumberFormatException nfe) { /* handle exception as desired */ }
}
Alternatively, you should be able to use something like:
while (inputA.hasNextInt())
{
aList.add(inputA.nextInt());
}
You should be having a for loop to have an input into your ArrayList.
System.out.println("Enter A array");
for (int i = 0; i < 4; i++) {
aList.add(inputA.nextInt());
}
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
for (int i = 0; i < 4; i++) {
bList.add(inputB.nextInt());
}
The user should input 4 numbers, your one just allow the user to enter 1 number:
int count = 0;
Scanner inputA = new Scanner(System.in);
System.out.println("Enter A array");
while(count < 4){
count++;
aList.add(inputA.nextInt());
}
count = 0;
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
while(count < 4){
count++;
bList.add(inputB.nextInt());
}
If you want to use hasNextInt():
while(inputA.hasNextInt()){
count ++;
aList.add(inputA.nextInt());
if(count == 4){
count = 0;
break;
}
}

When I try to redefine a variable, I get an index out of bounds error

I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error.
public static void main(String args[])
{
LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
Scanner scan = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
ArrayList<String> variables = new ArrayList<>();
while(scan.hasNextLine())
{
String line = scan.nextLine();
String[] tokens = line.split(" ");
if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var"))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==3)
{
value = Integer.parseInt(tokens[2]);
System.out.printf("%5d\n",value);
if(map.containsKey(tokens[0]))
{
values.set(values.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
}
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value);
System.out.printf("%5d\n",value);
variables.add(tokens[0]);
if(map.containsKey(tokens[0]))
{
values.set(values.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
}
break;
}
else if(i==tokens.length-1 && tokens.length != 3)
{
System.out.println("No operation");
break;
}
}
map.put(tokens[0], value);
}
if(Character.isDigit(tokens[0].charAt(0)))
{
int value = 0;
if(tokens.length==1)
{
System.out.printf("%5s\n", tokens[0]);
}
else
{
value = addition(tokens, value);
System.out.printf("%5d\n", value);
}
}
if(line.equals("clear"))
{
clear(map);
}
if(line.equals("var"))
{
variableList(variables, values);
}
}
}
public static int addition(String[] a, int b)
{
for(String item : a)
{
if(Character.isDigit(item.charAt(0)))
{
int add = Integer.parseInt(item);
b = b + add;
}
}
return b;
}
public static void clear(LinkedHashMap<String,Integer> b)
{
b.clear();
}
public static void variableList(ArrayList<String> a, ArrayList<Integer> b)
{
for(int i=0; i<a.size(); i++)
{
System.out.printf("%5s: %d\n", a.get(i), b.get(i));
}
}
I included the whole code because I'm not sure where the error is arising from.
I'm assuming the error is arising from storing the values in the ArrayLists.
This line:
values.set(values.indexOf(tokens[0]), value);
Is throwing ArrayIndexOutOfBoundsException .
You are looking up in values where your variable name "a" currently exists, apparently to overwrite it.
However, this makes no sense: values is a List of Integer, and therefore it could never contain your variable name "a".
Therefore, List.indexOf(Object) returns -1. When you try to invoke List.set(E, int) passing -1 it will blow up.

what is wrong with this code when dealing with large values of "long"?

I wrote an utility class to encode numbers in a custom numeral system with base N. As any self-respecting Java programmer I then wrote a unit test to check that the code works as expected (for any number I could throw at it).
It turned out, that for small numbers, it worked. However, for sufficiently large numbers, the tests failed.
The code:
public class EncodeUtil {
private String symbols;
private boolean isCaseSensitive;
private boolean useDefaultSymbols;
private int[] symbolLookup = new int[255];
public EncodeUtil() {
this(true);
}
public EncodeUtil(boolean isCaseSensitive) {
this.useDefaultSymbols = true;
setCaseSensitive(isCaseSensitive);
}
public EncodeUtil(boolean isCaseSensitive, String symbols) {
this.useDefaultSymbols = false;
setCaseSensitive(isCaseSensitive);
setSymbols(symbols);
}
public void setSymbols(String symbols) {
this.symbols = symbols;
fillLookupArray();
}
public void setCaseSensitive(boolean isCaseSensitive) {
this.isCaseSensitive = isCaseSensitive;
if (useDefaultSymbols) {
setSymbols(makeAlphaNumericString(isCaseSensitive));
}
}
private void fillLookupArray() {
//reset lookup array
for (int i = 0; i < symbolLookup.length; i++) {
symbolLookup[i] = -1;
}
for (int i = 0; i < symbols.length(); i++) {
char c = symbols.charAt(i);
if (symbolLookup[(int) c] == -1) {
symbolLookup[(int) c] = i;
} else {
throw new IllegalArgumentException("duplicate symbol:" + c);
}
}
}
private static String makeAlphaNumericString(boolean caseSensitive) {
StringBuilder sb = new StringBuilder(255);
int caseDiff = 'a' - 'A';
for (int i = 'A'; i <= 'Z'; i++) {
sb.append((char) i);
if (caseSensitive) sb.append((char) (i + caseDiff));
}
for (int i = '0'; i <= '9'; i++) {
sb.append((char) i);
}
return sb.toString();
}
public String encodeNumber(long decNum) {
return encodeNumber(decNum, 0);
}
public String encodeNumber(long decNum, int minLen) {
StringBuilder result = new StringBuilder(20);
long num = decNum;
long mod = 0;
int base = symbols.length();
do {
mod = num % base;
result.append(symbols.charAt((int) mod));
num = Math.round(Math.floor((num-mod) / base));
} while (num > 0);
if (result.length() < minLen) {
for (int i = result.length(); i < minLen; i++) {
result.append(symbols.charAt(0));
}
}
return result.toString();
}
public long decodeNumber(String encNum) {
if (encNum == null) return 0;
if (!isCaseSensitive) encNum = encNum.toUpperCase();
long result = 0;
int base = symbols.length();
long multiplier = 1;
for (int i = 0; i < encNum.length(); i++) {
char c = encNum.charAt(i);
int pos = symbolLookup[(int) c];
if (pos == -1) {
String debugValue = encNum.substring(0, i) + "[" + c + "]";
if (encNum.length()-1 > i) {
debugValue += encNum.substring(i + 1);
}
throw new IllegalArgumentException(
"invalid symbol '" + c + "' at position "
+ (i+1) + ": " + debugValue);
} else {
result += pos * multiplier;
multiplier = multiplier * base;
}
}
return result;
}
#Override
public String toString() {
return symbols;
}
}
The test:
public class EncodeUtilTest {
#Test
public void testRoundTrip() throws Exception {
//for some reason, numbers larger than this range will not be decoded correctly
//maybe some bug in JVM with arithmetic with long values?
//tried also BigDecimal, didn't make any difference
//anyway, it is highly improbable that we ever need such large numbers
long value = 288230376151711743L;
test(value, new EncodeUtil());
test(value, new EncodeUtil(false));
test(value, new EncodeUtil(true, "1234567890qwertyuiopasdfghjklzxcvbnm"));
}
#Test
public void testRoundTripMax() throws Exception {
//this will fail, see above
test(Long.MAX_VALUE, new EncodeUtil());
}
#Test
public void testRoundTripGettingCloserToMax() throws Exception {
//here we test different values, getting closer to Long.MAX_VALUE
//this will fail, see above
EncodeUtil util = new EncodeUtil();
for (long i = 1000; i > 0; i--) {
System.out.println(i);
test(Long.MAX_VALUE / i, util);
}
}
private void test(long number, EncodeUtil util) throws Exception {
String encoded = util.encodeNumber(number);
long result = util.decodeNumber(encoded);
long diff = number - result;
//System.out.println(number + " = " + encoded + " diff " + diff);
assertEquals("original=" + number + ", result=" + result + ", encoded=" + encoded, 0, diff);
}
}
Any ideas why things start failing when the values get large? I also tried BigInteger, but it did not seem to make a difference.
You're using floating point maths in your encodeNumber method, which makes your code rely on the precision of the double type.
Replacing
num = Math.round(Math.floor((num-mod) / base));
with
num = (num - mod) / base;
Makes the tests pass. Actually
num = num / base;
Should work just as well (thought experiment: what is 19 / 10 when / is integer division?).
You have a conversion to double in your code, which could be generating strange results for large values.
num = Math.round(Math.floor((num-mod) / base));
that would be my first port of call.

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}

Categories

Resources