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);
}
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
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.
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) {
}
}
}