Numbers Won't Increment - java

First my call back to increment I know is not correct. I am not sure what to do. I need increment to use temp when it hits that case that requires that call back. I can't change increment to pass a parameter into it because the graders test script wont allow for it. The second problem is that it wont increment any input. For instance if you just call increment on the number 23 it just returns 23. The test script for the grader looks something like this:
public class TestBigNaturalSimple {
public static void main(String[] args) {
BigNatural b1 = new BigNatural(); // default constructor
BigNatural b2 = new BigNatural(23); // one-argument int constructor
BigNatural b3 = new BigNatural("346"); // one-argument String constructor
BigNatural b4 = new BigNatural(b2); // one-argument BigNatural
// constructor
b1.increment();
b3.decrement();
System.out.println(b1.toString()); // should print out 1
System.out.println(b4.toString()); // should print out 23
}
}
My code is:
public class BigNatural {
private String num;
public BigNatural(String input) {
num = input;
}
public BigNatural(BigNatural input) {
num = input.toString();
}
public BigNatural(Integer input) {
num = input.toString();
}
public BigNatural() {
Integer i = 0;
num = i.toString();
}
public void increment() {
Integer first = 0;
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if (num.length() > 1)
{
if (last < 9) {
last++;
}
else
{
if (num.length() >= 2)
{
last = 0;
String temp = new String(num.substring(0, num.length()-2));
increment();
}
else
{
last++;
}
}
}
else
{
if (last < 9)
{
last++;
}
else
{
last = 0;
first = 1;
}
}
String t = last.toString();
if (first > 0)
{
String x = first.toString();
num.concat(x);
}
num.concat(t);
}
public void decrement() {
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if(num.length() > 1)
{
if(last == 0)
{
String temp = new String(num.substring(0, num.length()-2));
decrement();
}
else
{
last--;
}
}
else
{
if(last > 0)
{
last--;
}
else
{
last = 0;
}
}
String t = last.toString();
num.concat(t);
}
public String toString() {
return num;
}
}

That has to be the most complicated way to increment a number I have ever seen. ;) I assume you have to do it that way.
From what I can see you don't change num anywhere. I would expect this to be obvious if you used a debugger. ;)
Try using num = num.concat(t) if you expect num to change.
Note: String is immutable so you cannot change it, you can only replace it.
EDIT: Here is a version provided for your own interest. Your professor will know you didn't write this, so don't copy it. ;)
public void increment() {
num = increment(num);
}
private static String increment(String s) {
if (s.length() <= 0) return "1";
char ch = s.charAt(s.length() - 1);
String top = s.substring(0, s.length() - 1);
return ch < '9' ? top + ++ch : increment(top) + '0';
}

Strings are immutable in Java. Hence, the code
num.concat(t);
in your increment method will not do what you expect.

First, apply the rule don't repeat yourself:
to increment is to add 1
to decrement is to add -1
Thus you simply need to write on function that takes a number as input and add it to your BigNatural:
public void increment() {
add(1);
}
public void decrement() {
add(-1);
}
private void add(int i) {
// Your homework here ...
// You will have only one function to debug and correct, not 2
}
Second: as pointed in other answers, num.concat(t); does not do what you expect, you'll need num = num.concat(t);. Always refer to the Java documentation when you use a function you don't know. If you don't have an editor that allows you to debug your programs, I strongly suggest you get one: Eclipse for instance but other editors might be better as learning tool. The added benefit is that the tools will format the code for you, warn you about lots of mistakes, ...

Related

Trying to solve the derivative of a given equation from the user using ArrayList

As part of my AP computer science project, I decided to get a polynomial from a user and it will be able to find the derivative of the equation using the power rule.
For example, if the user enters 2X^3+5x^2 it should output 6x^2+10x^1, so the coefficient and degree multiplied together and then the degree is just minus one. This is what I have so far but it's giving me a lot of errors, and tried following the code but don't see anything wrong with it. Thanks for your help.
import java.util.ArrayList;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
//input of polynomial
System.out.println("Enter polynomial:");
Scanner sc = new Scanner(System.in);
String polynomialEquation = sc.nextLine();
//A string array list is created with the polynomial
ArrayList<String> equationArr = new ArrayList<String>();
for (int i = 0; i<polynomialEquation.length(); i++) {
equationArr.add(polynomialEquation.substring(i, i+1));
}
ArrayList<String> intStrings = new ArrayList<String>();
//separate the numbers from the list
for(int i =0; i<equationArr.size(); i++) {
if (equationArr.get(i).equals("1") || equationArr.get(i).equals("2") || equationArr.get(i).equals("3") ||equationArr.get(i).equals("4") ||equationArr.get(i).equals("5") ||
equationArr.get(i).equals("6") || equationArr.get(i).equals("7") || equationArr.get(i).equals("8") || equationArr.get(i).equals("9") || equationArr.get(i).equals("0"))
{
String addVal = equationArr.get(i);
intStrings.add(addVal);
equationArr.remove(i);
}
}
//convert string integers to integers
ArrayList<Integer> deriveInt = new ArrayList<Integer>(intStrings.size());
for (String myInt : intStrings)
{
deriveInt.add(Integer.valueOf(myInt));
}
//derive coefficiants
for (int i = 0; i<deriveInt.size()-1;i +=2) {
deriveInt.set(i, deriveInt.get(i)*deriveInt.get(i+1));
}
//derive exponent
for(int i = 1; i< deriveInt.size(); i +=2) {
deriveInt.set(i,deriveInt.get(i)-1);
}
//convert integer back to string
ArrayList<String> stringDerive = new ArrayList<String>();
for (Integer myInt2 : deriveInt)
{
stringDerive.add(String.valueOf(myInt2));
}
//get the signs from the original equation
ArrayList<String> sign = new ArrayList<String>();
for(int i =0; i<equationArr.size(); i++) {
if(equationArr.get(i).equals("+") || equationArr.get(i).equals("-")) {
sign.add(equationArr.get(i));
}
}
int totalSize = stringDerive.size() * 2 + equationArr.size();
for (int i = 0; i<totalSize-1; i=+2) {
int countSign= 0;
System.out.print(stringDerive.get(i));
System.out.print("x^");
System.out.print(stringDerive.get(i+1));
System.out.print(equationArr.get(countSign));
}
}
}
Polynomials are composed of monomials. In your example these are 2X^3 and 5x^2. One of approach to solving your problem is writing the Monom class and Polynom class. I'll give you a skeleton so you can practice.
public class Helper {
private class Monom{
private int coefficient;
private int degree;
public Monom(int coefficient, int degree){
this.coefficient = coefficient;
this.degree = degree;
}
public Monom(String input){
//TODO parse input. E.g Monom("6x^2) --> this.coefficient = 6...
//TODO validate input
}
public Monom derivate(final Monom monom){
return new Monom(monom.getCoefficient() * monom.getDegree(), monom.getDegree() - 1);
}
public int getCoefficient() {
return coefficient;
}
public int getDegree() {
return degree;
}
#Override
public String toString(){
return this.coefficient + "x^" + this.degree;
}
}
//skeleton
private class Polynom{
private List<Monom> polynom; //holder of monoms
//TODO rest of code including constructors, validate, derivate...
public Polynom(List<Monom> monoms){
this.polynom = monoms;
}
public Polynom derivate(Polynom input){
List<Monom> temp = new ArrayList<>();
for (Monom monom: polynom){
temp.add(monom.derivate(monom));
}
return new Polynom(temp);
}
}
public static void main(String[] args) {
//TODO test code
List<Monom> monoms = new ArrayList<>();
//TODO rest of code like:
// Polynom myPolynom = new Polynom(List<Monom> monoms);
//...
}
}
Like I said, this is just a code you have to upgrade... Good luck.
welcome to Stack Overflow and the wonderful world of programming! On a personal note, I started coding in high school with APCS too :)
Your question is arguably a bit too broad for this site. For example, you mentioned the code is "giving me a lot of errors": a better question would include the inputs you've tried and the specific output you're seeing and what you expected instead. I still want to help you though, so I'll give you some feedback and we can work through a few revisions.
First, I see that you've divided your program into sections using comments. This is a great instinct! You've decomposed the larger problem into smaller problems in a way that communicates your intent.
input of polynomial
A string array list is created with the polynomial
separate the numbers from the list
convert string integers to integers
derive coefficiants
derive exponent
convert integer back to string
get the signs from the original equation
However, it still leaves us with the problem of having a large main method to understand. So for your next revision, you should fix that by breaking it up into smaller methods. You can start by moving each of these "steps" into its own method, then call each of them from main. To help you get started, here's what it would look like with your first "step" extracted:
public class Practice {
public static String readPolynomial() {
System.out.println("Enter polynomial:");
Scanner sc = new Scanner(System.in);
String polynomialEquation = sc.nextLine();
return polynomialEquation;
}
public static void main(String[] args) {
String polynomialEquation = readPolynomial();
//A string array list is created with the polynomial
...
}
}
I think you'll find that this really improves your understanding of both your code and the problem you're trying to solve. Don't be afraid to change the steps based on that new understanding. It's no coincidence that the buggy or unfocused areas of your code are the areas you'll struggle the most to name. Try to focus on the problem, rather than your implementation. For instance, my first step would probably be a combination of your first few. Things like parsing the input String and then converting from Strings to Integer don't have much to do with polynomials or derivatives. So for readPolynomial I would prefer:
public static ArrayList<Integer> readPolynomial() {
The other big benefit of this refactor is that it will be much easier for you to test that each step is working the way you want it to. It gives you much more fine-grained control because you can test each method individually, rather than only being able to test by running the entire program. It will be much easier to isolate, understand, and fix each individual bug.
Another big thing: please provide some more sample inputs! Not only will this help clarify requirements, but we can use them as test cases later.
Here's some functioning code to help you, please don't just take it for granted but read it and understand what is happening. If you have any questions on it please ask. It could use some cleanup but hopefully it's still understandable.
One minor thing to note is that sign is attached to the expressions (as it kinda should be) so you could just + all the expressions together and it would be valid. But if you want to avoid having an answer like 6x^2 + -10y^4 and would rather have 6x^2 - 10y^4 then you'd have to check if the expressions are negative when building the answer with them.
public class Test {
public static void main(String[] args) {
// input requires all constants to be fully resolved
// eg. no '3^2^1^3', instead it should be '9'
// eg. no '5*2x', instead it should be '10x'
// mess around with the input to test
String s = "2x^3+5x^2";
List<DerivableExpression> list = parseDeriveableExpressions(s);
List<DerivableExpression> derivatives = new ArrayList<>();
for(DerivableExpression de : list)
derivatives.add(de.getDerivative());
System.out.println(String.join("+", derivatives)); // 6x^2+10x^1
}
private static List<DerivableExpression> parseDeriveableExpressions(String s) {
// remove all spaces and lowercase everything
s = s.replace(" ", "");
List<DerivableExpression> list = new ArrayList<>();
char var = ' ';
StringBuilder constBuff = new StringBuilder();
StringBuilder powerBuff = new StringBuilder();
boolean parsingPower = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '+' || c == '-') {
if (parsingPower && powerBuff.length() == 0) {
// at the start of the power expression
if (c == '-')
powerBuff.append(c);
} else {
// either not parsing a power or not at the start of the power
// this is a +/- after the power, terminating the expression
parsingPower = false;
int constant = 1;
if (constBuff.length() > 0) {
constant = Integer.parseInt(constBuff.toString());
constBuff.setLength(0);
}
if (var != ' ' && constant != 0) {
int power = 1;
if (powerBuff.length() > 0)
power = Integer.parseInt(powerBuff.toString());
list.add(new VariableExpression(constant, var, power));
} else {
list.add(new ConstantExpression(constant));
}
powerBuff.setLength(0);
var = ' ';
// append the sign for the next expression
if (c == '-')
constBuff.append(c);
}
} else if ('0' <= c && c <= '9') {
if (parsingPower)
powerBuff.append(c);
else
constBuff.append(c);
} else if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) {
if (constBuff.length() == 0 ||
(constBuff.length() == 1 && constBuff.charAt(0) == '-'))
constBuff.append("1");
var = c;
} else if (c == '^') {
parsingPower = true;
}
}
// add the last expression
int constant = 1;
if (constBuff.length() > 0) {
constant = Integer.parseInt(constBuff.toString());
constBuff.setLength(0);
}
if (var != ' ') {
int power = 1;
if (powerBuff.length() > 0) {
power = Integer.parseInt(powerBuff.toString());
powerBuff.setLength(0);
}
list.add(new VariableExpression(constant, var, power));
var = ' ';
} else {
list.add(new ConstantExpression(constant));
}
return list;
}
private static interface DerivableExpression {
public abstract DerivableExpression getDerivative();
}
private static class VariableExpression implements DerivableExpression {
private final int constant;
private final char variable;
private final int power;
public VariableExpression(int constant, char variable, int power) {
this.constant = constant;
this.variable = variable;
this.power = power;
}
#Override public VariableExpression getDerivative() {
return new VariableExpression(constant * power, variable, power - 1);
}
#Override public String toString() { return constant + "" + variable + "^" + power; }
}
private static class ConstantExpression implements DerivableExpression {
private final int constant;
public ConstantExpression(int constant) {
this.constant = constant;
}
#Override public DerivableExpression getDerivative() { return this; }
#Override public String toString() { return Integer.toString(constant); }
}
}

Continue operator doesn't continue the for loop

Trying to continue iterating if (str1Number == str2Number), but the loop stops after incrementing the i variable
String getOldestVersion (String str1, String str2) {
String[] str1Arr = str1.split("\\.");
String[] str2Arr = str2.split("\\.");
String result = "";
int str1Number = 0;
int str2Number = 0;
for (int i = 0; i < str1Arr.length-1; i++) {
str1Number = Integer.valueOf(str1Arr[i]);
str2Number = Integer.valueOf(str2Arr[i]);
if (str1Number > str2Number) {
result = str1;
break;
} else if (str1Number == str2Number) {
i++;
continue;
} else {
result = str2;
break;
}
}
return (result);
}
As said in the comments "using continue as the last statement in a loop doesn't make any sense." why?
because the continue statement is used to bypass the execution of below statements in the current iteration but in your case it's being used as the last statement.
it seems like what you want is if this condition is true --> if (str1Number == str2Number) then you don't want to execute any of the logic in the loop, in which case you can do:
for (int i = 0; i < str1Arr.length-1; i++){ // did you mean i < str1Arr.length ?
str1Number = Integer.valueOf(str1Arr[i]);
str2Number = Integer.valueOf(str2Arr[i]);
if (str1Number == str2Number) // <---- I've moved it to here
continue;
if (str1Number > str2Number) {
result = str1;
break;
} else {
result = str2;
break;
}
}
I've also removed the i++; that was inside the if block as I "assumed" it might have been a typo/mistake.
Since, continue operation itself tell to increase iteration variable - i, you don't need to increase it there. You may simply write:
else if (str1Number == str2Number){
continue;
}
The continue keyword just sends control up to the top of the loop (after executing the increment part of the for construct). The condition is still evaluated though, so it will only continue the loop if the loop condition is satisfied.
Probably, in your case, i < str1Arr.length-1 is false.
Judging from your method's name and its return value, all you want to find is the input string that has the lowest integer as its version identifier in it.
For that, below should suffice. No loops needed at all
public class Foo {
public static void main(String[] args) {
System.out.println(getOldestVersion("abc.12", "abc.14"));
}
public static String getOldestVersion(String v1, String v2) {
return parseInteger(v1) > parseInteger(v2) ? v2 : v1;
}
public static int parseInteger(String input) {
return Integer.valueOf(input.replaceAll("\\D", ""));
}
}
If your input string is something like 12.13.14.15, you could use
public class Foo {
public static void main(String[] args) {
System.out.println(getOldestVersion("12.18", "14.15"));
}
public static String getOldestVersion(String v1, String v2) {
return Stream.of(v1.split("\\.")).mapToInt(Integer::parseInt).min().orElse(Integer.MAX_VALUE) > Stream.of(v2.split("\\.")).mapToInt(Integer::parseInt).min().orElse(Integer.MAX_VALUE)
? v2 : v1;
}
public static int parseInteger(String input) {
return Integer.valueOf(input.replaceAll("\\D", ""));
}
}

how to count many times a character occurs in a string without using s loop

the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");

Constructor and method

For my project I have a question that says newGenerationNumber an integer. If the argument passed as the parameter is less than zero, set the generationNumber instance variable to zero. Otherwise assign newGenerationNumber to the generationNumber instance variable. I'm confused on how to start this. My code I out is
Private int generationNumber
Then I made a if
If (generationNumber >0)
generationNumber = generationNumber
I'm confused if this is right and if I need to make a else
generationNumber = newGenerationNumber;
if (generationNumber < 0) {
generationNumber = 0;
}
else it stays the way it is
An if...else is a good choice here, but not the only one.
int generationNumber;
public Guppy (int newGenerationNumber) {
if (newGenerationNumber > 0) {
generationNumber = newGenerationNumber;
} else {
generationNumber = 0;
}
}
Instance int primitives have the value of 0 by default. This means that you could leave the else part and only check if it's positive.
It says if the newGenerationInstance parameter (argument) is less than 0.
So I'd probably use the conditional operator (x ? y : z):
public Guppy(int newGenerationInstance) {
this.generationInstance = newGenerationInstance < 0 ? 0 : newGenerationInstance;
}
or alternately you can use if/else if you prefer:
public Guppy(int newGenerationInstance) {
if (newGenerationInstance < 0) {
this.generationInstance = 0;
} else {
this.generationInstance = newGenerationInstance;
}
}
for the simple solution, i would write the code like below
public class NewNumberGenerationClass {
//instance variable because you can access this with the instance of the class
private int NewGenerationNumber;
public NewNumberGenerationClass(int i){
setNewGenerationNumber(i);
}
//setting value before getting it
public void setNewGenerationNumber(int i)
{
if(i < 0)
{
this.NewGenerationNumber = 0;
}
else
{
this.NewGenerationNumber = i;
}
}
//access vaule using get method
public int getNewGenerationNumber()
{
return this.NewGenerationNumber;
}
public static void main(String[] args){
NewNumberGenerationClass s = new NewNumberGenerationClass(-5);
NewNumberGenerationClass s1 = new NewNumberGenerationClass(5);
System.out.println(s.getNewGenerationNumber());
System.out.println(s1.getNewGenerationNumber());
}
}

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