Numbers in descending order in Java using if/else only - java

How can I create a java program using only if / else to order 3 numbers in descending order. I can not use for processes or array. Numbers are entered by the user.
Here's what i have so far. What should i do, is the user enters two integers that are the same? The code can only display one output.
import java.util.Scanner;
public class DescendingOrder
{
public static void main(String [] args)
{
//variable dec.
int a;
int b;
int c;
Scanner kbd = new Scanner(System.in);
//user prompt
System.out.println("Please enter three integers");
a=kbd.nextInt();
b=kbd.nextInt();
c=kbd.nextInt();
//program output
if (a>=b && b>=c && a>=c)
{
System.out.println("a b c");
}
if (a>=c && c>=b && a>=b )
{
System.out.println("a c b");
}
if (b>=a && a>=c && b>=c)
{
System.out.println("b a c");
}
if (b>=c && c>=a && b>=c)
{
System.out.println("b c a");
}
if(c>=a && a>=b && c>=b)
{
System.out.println("c a b");
}
if (c>= b && b>=a && c>=a)
{
System.out.println("c b a");
}
}
}

A simpler way you can do it is
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
if (b < c)
{
int temp = b;
b = c;
c = temp;
}
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
System.out.println(a + " " + b + " " + c);
If two numbers are the same it doesn't really matter, as 90 45 45 is the same as 90 45 45. (In the case of your code as written, however, you are correct in noticing that it does matter. You could fix this by changing all your if statements except the first one into else-if)

This question seems to be a thought exercise so consider this answer an alternative to the other correct answers for your consideration. Here my enterprise-y solution.
Step 0, refactor your code to make it testable and stub out the method that will do the actual work:
import static java.lang.System.in;
import static java.lang.System.out;
import java.util.Scanner;
public class DescendingOrder {
public static final void main(final String... args) { // unavoidable use of an array, please don't dock points
try (final Scanner kbd = new Scanner(in)) { // always close your Closeables
final int a = kbd.nextInt();
final int b = kbd.nextInt();
final int c = kbd.nextInt();
final DescendingOrder calculator = new DescendingOrder();
out.println(calculator.order(a, b, c));
}
}
public String order(final int a, final int b, final int c) {
return null;
}
}
Step 1, write a unit test:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class DescendingOrderTest {
private DescendingOrder orderer;
#Before
public void setUp() throws Exception {
orderer = new DescendingOrder();
}
#Test
public final void testOrderABC() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE); // don't forget the edge cases
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
#Test
public final void testOrderACB() {
final String result = orderer.order(13, 5, 8);
assertEquals("13 8 5", result);
}
#Test
public final void testOrderBAC() {
final String result = orderer.order(4, 8, 2);
assertEquals("8 4 2", result);
}
#Test
public final void testOrderBCA() {
final String result = orderer.order(-8, -2, -4); // don't forget negative numbers
assertEquals("-2 -4 -8", result);
}
#Test
public final void testOrderCAB() {
final String result = orderer.order(1, -5, 5);
assertEquals("5 1 -5", result);
}
#Test
public final void testOrderCBA() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE);
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
#Test
public final void testAllSame() {
final String result = orderer.order(53, 53, 53);
assertEquals("53 53 53", result);
}
}
Step 2, iteratively implement order until your tests pass:
public String order(final int a, final int b, final int c) {
if (a > b && a > c) {
return a + " " + order(b, c);
} else if (b > a && b > c) {
return b + " " + order(a, c);
}
return c + " " + order(a, b);
}
protected String order(final int x, final int y) {
if (x > y) {
return x + " " + y;
}
return y + " " + x;
}
It might not be the most computationally efficient, but I kept the method sizes small so it is clear what the code is meant to accomplish. I also do not need to scan through six scenarios to see that it is correct. If I assume that order( int, int ) is correct, then I only need to work through three scenarios to see that order( int, int, int ) is correct.
Obviously, this is overkill. But those constraints would never really exist.

I think your code was fine you were just printing wrong. You have to understand that a,b,c are variable of type int. when you use the + operator with two ints it performs an addition. If you use the + operator with an int and with a string it produces a concatenation. The int 'calls' to string turning the int into a string which produces String + String = concatenation.
Anyways, I think this is what you wanted. Let me know if this is what you wanted.
import java.util.Scanner;
public class Stackoverflow
{
public static void main(String [] args)
{
//variable dec.
int a;
int b;
int c;
Scanner kbd = new Scanner(System.in);
//user prompt
System.out.println("Please enter three integers");
a=kbd.nextInt();
b=kbd.nextInt();
c=kbd.nextInt();
//program output
if (a>=b && b>=c && a>=c)
{
System.out.println(a+" "+b+" "+c);
}
if (a>=c && c>=b && a>=b )
{
System.out.println(a+" "+c+" "+b);
}
if (b>=a && a>=c && b>=c)
{
System.out.println(b+" "+a+" "+c);
}
if (b>=c && c>=a && b>=c)
{
System.out.println(b+" "+c+" "+a);
}
if(c>=a && a>=b && c>=b)
{
System.out.println(c+" "+a+" "+b);
}
if (c>= b && b>=a && c>=a)
{
System.out.println(c+" "+b+" "+a);
}
}
}

Related

Making a recursive method to print a text in java

I have to make a program which works like this. first it gets a number from input and then it gets (number) * strings.
for example:
2
a b
or
3
x1 x2 x3
then in the output it prints something like this:
Math.max(a, b)
or
Math.max(x1, Math.max(x2, x3))
I want to make Math.max method syntax with this code. I hope you understood!
Another Sample Input & output:
Input =
4
a b c d
Output =
Math.max(a, Math.max(b, Math.max(c, d)))
can someone help me?
The code I've wrote for it, can you suggest me some changes to make it better?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] r = new String[n];
for (int i = 0; i < n; i++) {
r[i] = input.next();
}
printmax(r);
}
public static int i = 0 , j = 0;
public static boolean last = false;
public static void printmax(String [] r){
if (last == true) {
System.out.print(r[r.length - 1]);
while (j < r.length - 1){ System.out.print(")");
j++;
}
}
if (r.length == 2) System.out.print("Math.max(" +r[0] + ", " + r[1] + ")");
if (r.length > 2) {
while (i < r.length -1) {
if (i == r.length -2) last = true;
System.out.print("Math.max(" + r[i] + ", ");
i++;
printmax(r);
}
}
}
}
You can use the following code to achieve the above, here m calling maxElement() function recursively to achieve somthing like this Math.max(a, Math.max(b, Math.max(c, d)))
public static void main(String args[]){
int length = 2; //here read the input from scanner
String[] array = {"a", "b"}; //here read this input from scanner
String max = maxElement(array,0,length);
System.out.println(max);
}
public static String maxElement(String[] start, int index, int length) {
if (index<length-1) {
return "Math.max(" + start[index] + ", " + maxElement(start, index+1, length)+ ")";
} else {
return start[length-1];
}
}
Output:
Math.max(a, b)
You need to do something like this.
First you define a function maxElement which takes your variable array as a parameter.
public static maxElement(String[] variables) {
return maxElementBis(variables,0);
}
Then you call a second function : maxElementBis which takes an additional argument which represents the index of the variable we are processing.
public static String maxElementBis(String[] variables, int index) {
if (variables.length < 2)
return "not enought variables";
if (variables.length - index == 2)
return "Math.max("+ variables[index]+","+variables[index + 1]+")";
return "Math.max("+ variables[index]+","+maxElementBis(variables,index + 1)+")";
}
If the array contains less than two variables you cannot do what you want.
If you only have two variables left, this is your stop condition and you can directly return Math.max(v1,v2).
Otherwise you recursively call your function maxElementBis.

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;
}
}

My calculator isn't calling upon variables properly

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.

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