Searching through Objects Issue - java

The program is to find all of the words in a text file and count how many times each word is found. Our definition of a "word" will be relatively crude and will be done by splitting the line based on characters that are not alphabetic. I know there are easier ways to go about this but we were required to use a class and a search method like the one I attempted. I can't figure out why it's not incrementing word's that are already in wordList. I believe it's either completely skipping over my if (foundAt >=0, or it's not incrementing it correctly, I'm leaning toward my search method being wrong, but I can't figure out the problem. Any and all help is much appreciated, thanks for your time.
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
int n=0;
WordCount[] wordList= new WordCount[10000];
Scanner words = new Scanner(new File("input.txt"));
while (words.hasNextLine() && n < 10000)
{
String line = words.nextLine();
String[] tokens = line.split("[^\\p{Alpha}]");
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
WordCount word = new WordCount(tokens[i]);
int foundAt = search(wordList, word, n);
if (foundAt >= 0)
{
wordList[foundAt].increment();
}
else
{
wordList[n]=word;
n++;
}
}
}
}
//Arrays.sort(wordList);
String alphabeticFileName = "alphabetic.txt";
String frequencyFilename = "frequency.txt";
PrintWriter output = new PrintWriter(alphabeticFileName);
for (int i=0; i<n;i++)
{
output.println(wordList[i].toString());
}
output.close();
//Sort on frequency somehow
PrintWriter output2 = new PrintWriter(frequencyFilename);
for (int i=0; i < n; i++)
{
output2.println(wordList[i].toString());
}
output2.close();
}
public static int search(WordCount[] list,WordCount word, int n)
{
int result = -1;
int i=0;
while (result < 0 && i < n)
{
if (word.equals(list[i]))
{
result = i;
}
i++;
}
return result;
}
}
class WordCount
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
setWord(aWord);
count = 1;
}
private void setWord(String theWord)
{
word=theWord;
}
public void increment()
{
count=+1;
}
public static void sortByWord()
{
compareByWord = true;
}
public static void sortByCount()
{
compareByWord = false;
}
public String toString()
{
String result = String.format("%s (%d)",word, count);
return result;
}
}
Output:
Peter (1)
Piper (1)
picked (1)
a (1)
peck (1)
of (1)
pickled (1)
peppers (1)
A (1)
peck (1)
of (1)
pickled (1)
peppers (1)

Your increment function is wrong. You've written:
count =+1;
Which only sets the count to one. To increment count by one you put:
count += 1;

Related

Need help converting iterative process to recursive

I am trying to convert the following iterative code:
int rows = 3;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
for (int j = 0; j < rows-i; j++)
{
System.out.print("-");
}
System.out.println();
}
with the output:
---
*--
**-
***
to recursive code. This is for an assignment. I created the iterative code in hopes of being able to figure out how to directly convert it to recursive. Here's my effort of that:
public void stringY(int star, int count){
if (star > 0){
System.out.print("*");
stringY(star - 1, count);
}
}
public void stringX(int dash,int count){
if (dash == -1) {
return;
}else if (dash < count){
System.out.print("-");
stringX(dash - 1, count);
} else if (dash == count){
stringX(dash - 1, count);
}
}
public void printPattern(int n) {
if (n == -1){
return;
} else {
printPattern(n-1);
stringY(n, n);
stringX(n, n);
System.out.println();
}
}
My issue here is that while I get the output I am looking for with regard to the "*" part of the pattern, I have absolutely no clue how to get the "-" part of the pattern. Now being that this is an assignment I don't want any solutions, but any pointers in the right direction are absolutely welcome. I should note that my two requirements are: 1) I have to complete my assignment entirely without using loops and 2) I can use as many helper methods as I need, but the main calling method (printPattern) must stay public void and must continue to only accept integers. Further clarification: The other two methods in the recursive code block are helper methods I created.
First let m = number of '*' to print and let n = number of '-' to print
For each recursion, increment m by 1 and decrement n by 1.
public static void main(String[] args) {
printPattern(3);
}
public static void printPattern(int n) {
printing(n, n);
}
//Variable size basically represent the number of columns
public static void printing(int n, int size) {
//stop condition
if(n == -1)
return;
//m is the number of * to print
int m = size - n;
printAsterisk(m);
//n is the number of - to print
printHyphen(n);
System.out.println();
printing(n - 1, size);
}
public static void printAsterisk(int m) {
if(m == 0)
return;
System.out.print('*');
printAsterisk(m - 1);
}
public static void printHyphen(int n) {
if(n == 0)
return;
System.out.print('-');
printHyphen(n - 1);
}
Think of it this way, they are all just loops doing some work. All you need is theoretically one recursive function that calls itself till the passed value.
void loop(int i, int till, Worker doThis) {
if (i>=till) return;
doThis.work(i);
loop(i+1, till, doThis);
}
Worker is just an interface,
public interface Worker {
void work(int index);
}
Now we need to pass the work that needs to be done. There are three loops, hence three calls to the loop function.
final int rows = 3;
// outer loop
loop(0, rows+1, new Worker() {
public void work(int index) {
// Stars
loop(0, index, new Worker() {
public void work(int index) {
System.out.print("*");
}
});
// Dashes
loop(0, rows-index, new Worker() {
public void work(int index) {
System.out.print("-");
}
});
System.out.println();
}
});
I would start by extracting then STAR and DASH,
private static final String DASH = "-";
private static final String STAR = "*";
Next, I would write a method to repeat a String a given number of times. Also, I would use a StringBuilder (here I've done it recursively)
private static StringBuilder repeat(StringBuilder sb, String str, int n) {
if (n > 0) {
sb.append(str);
repeat(sb, str, n - 1);
}
return sb;
}
Next, a private recursive method to print the pattern based on StringBuilder
private static void printPattern(StringBuilder sb, int s) {
System.out.println(sb);
int p = sb.indexOf(DASH, s);
if (p > -1) {
sb.replace(p, p + DASH.length(), STAR);
printPattern(sb, s + STAR.length());
}
}
And finally the public method
public static void printPattern(int n) {
printPattern(repeat(new StringBuilder(), DASH, n), 0);
}

Reading data from Csv File

How to find sequence of missing number from a CSV file using java Program?
I was using Arraylist taking some numbers into consideration.
I want to read entire CSV file Data And find the missing sequences on numbers.I have near about 1,00,000 records in the file.
Program:-
public class MissingNumber {
public static long count = 0;
public static int position = 0;
public static boolean flag = false;
public static void main(String[] args) {
long a[] = {1054023,1054024,1054025,1054026,1054027,1054028,1054029,1054030,1054031,1054032,1054748,1054749,1054750,1054751,
1054752,1054753,1054754,1054755,1054756,1054757,1054758,1055297,1055298,1055299,1055300,1055301,1055302,1055303,1055304,
1055305,1055306,1055307,1055308,1055309,1056868,1057170,1057461,1057563,1057627,1057628,1057629,1057630,1057631,1057632,
1057633,1057634,1057635,1057636,1057637,1057652,1057653,1057654,1057656,1057657,1057661,1057662,1057663,1057664,1057665,
1057672,1057673,1057674,1057675,1057678,1057682,1057683,1057685,1057686,1057687,1057690,1057691,1057692,1057695,1057696,
1057697,1057698,1057699,1057701,1057702,1057705,1057706,1057707,1057708,1057710,1057712,1057718,1057722,1057729,1057730,
1057731,1057732,1057733,1057734,1057735,1057736,1057738,1057739,1057740,1057741,1057742,1057743,1057744,1057745,1057746,
1057747,1057748,1057749,1057750,1057751,1057752,1057753,1057754,1057755,1057756,1057757,1057758,1057759,1057762,1057763,
1057764,1057765,1057766,1057767,1057768,1057769,1057773,1057774,1057778,1057779,1057780,1057781,1057782,1057783,1057784,
1057785,1057786,1057787,1057788,1057789,1057790,1057791,1057792,1057793,1057794,1057795,1057796,1057797,1057798,1057799,
1057800,1057801,1057802,1057803,1057804,1057805,1057806,1057807,1057808,1057809,1057810,1057811,1057825,1057826,1057827,
1057829,1057838,1057843,1057857,1057858,1057859,1057860,1057861,1057862,1057863,1057864,1057865,1057866,1057867,1057868,
1057869,1057870,1057871,1057872,1057873,1057874,1057875,1057876,1057884,1057885,1057886,1057887,1057888,1057889,1057890,
1057891,1057892,1057893,1057894,1057895,1057896,1057897,1057898,1057899,1057900,1057901,1057902,1057903,1057905,1057906,
1057907,1057908,1057909,1057910,1057911,1057912,1057913,1057914,1057915,1057916,1057917,1057918,1057919,1057920,1057921};
findMissingNumbers(a, position);
}
private static void findMissingNumbers(long a[], int position) {
if (position == a.length - 1)
return;
for (; position < a[a.length - 1]; position++) {
if ((a[position] - count) != position)
{
System.out.println("position"+position);
System.out.println("Missing Number: " + (position + count));
flag = true;
count++;
break;
}
}
if (flag) {
flag = false;
findMissingNumbers(a, position);
}
}
}
I assume your array is already sorted. If so itreate through and find the missing nrs like you were doing it manually; compare two neighbors and if the difference is more than one print the numbers missing. something like this:
public class MissingNumber {
public static void main(String[] args) {
long a[] = {1,2,3,5,9,11,23,24,25,26,27,28,39}; //try first on small arrays
findMissingNumbers(a);
}
private static void findMissingNumbers(long a[]) {
for(int i = 0; i<a.length-1; i++){
if(a[i+1]- a[i] > 1){
System.out.println("missing nr at index: " + (i+1));
System.out.println("missing nrs");
for (int j = 1;j<a[i+1]-a[i];j++){ // for ex. if a[i] = 13 and a[i+1]= 17 difference is 4 and there are 3 missing nrs.
System.out.println(a[i]+j);
}
}
}
}
}
And to easily read from csv file i recomend opencsv

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

Find test-case for which code does't work

I submitted one code in code chef but it's giving wrong answer even if it's correct
can anybody help me to identify that please.
I have tried so many inputs and calculated manually and they are correct so why they gave me wrong answer.
so,anybody who can find the TEST Case which give incorrect output by this code ?.
Here is Problem definition.
import java.util.Scanner;
import java.lang.Math;
class Codechef {
static int get(int n,int i,int digit)
{
int p;
p=(int)Math.pow(10,i-1);
n=n/p;
return n%10;
}
static boolean check_pal(int n)
{
int digit;
digit=(int) (Math.log10(n)+1);
int a=0,b=0,i,j,p;
int sum=0;
for(i=1,j=digit-1 ; i<=digit ; i++,j-- )
{
a=get(n,i,digit);
sum+=a*Math.pow(10,j);
}
if(sum==n)
return true;
else
return false;
}
static int reverse(int n)
{
int digit;
digit=(int) (Math.log10(n)+1);
int a=0,b=0,i,j,p;
int sum=0;
for(i=1,j=digit-1 ; i<=digit ; i++,j-- )
{
a=get(n,i,digit);
sum+=a*Math.pow(10,j);
}
return n+sum;
}
public static void main(String[] args) {
try{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n<10 || n>999){
System.out.println("NONE");
return;
}
boolean c;
for(int i=1 ; i<=100 ; i++)
{
c=check_pal(n);
if(c==true)
{
System.out.println(n);
return;
}
n=reverse(n);
}
System.out.println("NONE");
}
catch(Exception e)
{
System.out.println("NONE");
}
}
}
Here is one more output.
for 99 it gives 99 and which is correct as it's palindrome.
For 89 (or 98 for that matter), your code returns "NONE", although you reach the answer 8813200023188 after only 24 steps.
Another case is that for 177 and 276 you should get 8836886388 instead of NONE
I didn't debug your code, I just wrote a program that does the same, and compared the output my program gave to the one your program gave. Since you just requested a testcase, that should suffice :) My gutfeeling is that you overflow... an int is not large enough to hold the answer in all cases.
Happy bughunting.
Edit (on Request) with my code.
I didn't change your code, except that I extracted your logic into a getResult(integer) methode so that I could bypass the scanning of the input and simply return a string as result. It prints out all the differences between our versions. I used BigInteger as the type to hold my results.
public class Main {
public static void main(String[] args) {
Main m = new Main();
for (int i=10; i < 1000; i++) {
String myResult = null;
String hisResult = null;
try {
myResult = m.getResultAsString(i);
} catch (Exception e){
System.out.println("Your code threw an exception for " + i);
}
try{
hisResult = Codechef.getResult(i);
} catch (Exception e){
System.out.println("His code threw an exception for " + i);
}
if (myResult != null && hisResult != null && ! myResult.equals(hisResult)) {
System.out.println("For " + i + " you have " + myResult + " but he has " + hisResult);
}
}
}
public String getResultAsString(int inputNumber) {
BigInteger res = getResultAsBigInteger(new BigInteger(""+inputNumber));
if (res != null) {
return res.toString();
} else {
return "NONE";
}
}
public BigInteger getResultAsBigInteger(BigInteger inputNumber) {
int numberOfSteps = 0;
BigInteger currentValue = inputNumber;
while (numberOfSteps < 101 && ! isPalindrome(currentValue)) {
numberOfSteps++;
currentValue = currentValue.add(reverseDigits(currentValue));
}
return numberOfSteps < 101 ? currentValue : null;
}
public boolean isPalindrome(BigInteger number) {
return number.equals(reverseDigits(number));
}
public BigInteger reverseDigits(BigInteger input) {
String inputString = input.toString();
String output = "";
for (int i = inputString.length() - 1; i >= 0; i--)
{
output += inputString.charAt(i);
}
return new BigInteger(output);
}
}
There is an overflow error in your code.
for input 89 it's not working as #Yves V. said
Suggestion is to use BigInteger class of lang.Match it will be useful to eliminate this overflow error.

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