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.
Related
I would like to checking if an element is even or odd. What is wrong with my code?
bad operand types for binary operator '%' first type: java.lang.String second type: int, line 16
incompatible types: java.util.ArrayDeque cannot be converted to java.util.ArrayList, line 44
class ArrayExample{
public void printMethod(ArrayList<String> theList){
String value = null;
for (int n=0; n < theList.size(); n++){
value = theList.get(n);
//checking if an element is even or odd
if (value.length % 2 == 0){
System.out.println("even");
System.out.println(value);
} else {
System.out.println("odd");
System.out.println(value);
}}}}
class Calc {
public static void main(String[] args) {
ArrayDeque<String> storeQueue = new ArrayDeque<String>();
for (int i = 0; i < 40; i++) {
Random rand = new Random();
int value = rand.nextInt((40 - 1) + 1) + 1;
String z = new String(new char[value]).replace("\0", "z");
storeQueue.add(z);
System.out.println(storeQueue);
}
ArrayExample samp = new ArrayExample();
samp.printMethod(storeQueue);
}}
I think you can simply using ArrayList instead of ArrayDeque unless you want to perform FIFO operation. Also you might realised that your array is consisted of String, mod operation here should take input as integer. So you can use this random:
Random random = new Random();
int randomInteger = random.nextInt();
Here are the 2 changes required to make the program work:
Change the operands of % operator to Integer (Use value.length in place of value)
Change the argument to printMethod from ArrayDeque type to 'ArrayList' type.
Here is the working solution, with these 2 changes:
// File name: Calc.java
import java.util.*;
class ArrayExample{
public void printMethod(ArrayList<String> theList) {
String value = null;
for (int n=0; n < theList.size(); n++){
value = theList.get(n);
//checking if an element is even or odd
if ((value.length()) % 2 == 0) {
System.out.println("even - " + value);
} else {
System.out.println("odd - " + value);
}
}
}
}
public class Calc {
public static void main(String[] args) {
ArrayDeque<String> storeQueue = new ArrayDeque<String>();
for (int i = 0; i < 40; i++) {
Random rand = new Random();
int value = rand.nextInt((40 - 1) + 1) + 1;
String z = new String(new char[value]).replace("\0", "z");
storeQueue.add(z);
System.out.println(storeQueue);
}
ArrayExample samp = new ArrayExample();
samp.printMethod(new ArrayList<String>(storeQueue));
}
}
Output:
> javac Calc.java
> java Calc
[zzzzzzzzzzzzzzzzzzzz]
[zzzzzzzzzzzzzzzzzzzz, zzzzzz]
[zzzzzzzzzzzzzzzzzzzz, zzzzzz, zzzzzzzzzzzzzzzzzzz]
[zzzzzzzzzzzzzzzzzzzz, zzzzzz, zzzzzzzzzzzzzzzzzzz, zzzzzzzzzzzzzzzzzzzzzzzzzzzz]
...
...
...
even - zzzzzzzzzzzzzzzzzzzz
even - zzzzzz
odd - zzzzzzzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
odd - zzzzzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzz
odd - zzzzzzzzzzzzzzz
odd - zzzzzzzzz
odd - zzzzzzzzzzz
even - zzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzzzzzzzz
odd - zzzzz
even - zzzz
even - zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
In your class ArrayExample method printMethod expect ArrayList as parameter, but in main method you try to pass ArrayDeque which is not compatible with ArrayList.
To resolve this problem you should change parameter declaration in printMethod to ArrayDeque, but still there is a problem becouse ArrayDeque dont have .get method.
I propose to change body of method to foreach loop.
And another bug in this code is you try modulo on String but you need do it on its length. You cannot modulo on text, rather you should use it on text length.
class ArrayExample {
public void printMethod(ArrayDeque<String> theList) {
String value = null;
for (String s : theList) {
if (s.length() % 2 == 0) {
System.out.println("even");
System.out.println(value);
} else {
System.out.println("odd");
System.out.println(value);
}
}
}
}
And you main class can stay the same as you write.
It works - #Gopinath
// File name: Calc.java
import java.util.*;
class ArrayExample{
public void printMethod(ArrayList<String> theList) {
String value = null;
for (int n=0; n < theList.size(); n++){
value = theList.get(n);
//checking if an element is even or odd
if ((value.length()) % 2 == 0) {
System.out.println("even - " + value);
} else {
System.out.println("odd - " + value);
}
}
}
}
public class Calc {
public static void main(String[] args) {
ArrayDeque<String> storeQueue = new ArrayDeque<String>();
for (int i = 0; i < 40; i++) {
Random rand = new Random();
int value = rand.nextInt((40 - 1) + 1) + 1;
String z = new String(new char[value]).replace("\0", "z");
storeQueue.add(z);
System.out.println(storeQueue);
}
ArrayExample samp = new ArrayExample();
samp.printMethod(new ArrayList<String>(storeQueue));
}
}
This is an homework problem
Is there a way tor reverse a number in Java without using any loops? The only solution I can think of is reversing it using String and then casting it back to an integer.
If you want to reverse a number withour using any loop you can use Recursion method call. Following program is doing same
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
} else {
System.out.print(number % 10);
reverseMethod(number / 10);
}
}
public static void main(String args[]) {
int num = 4567;
reverseMethod(num);
}
Even if you were to reverse the number by casting it into a String, you would still need a loop if you want the program to work when having ints of different sizes. If I were to make a method to reverse a number but could not do it with loops, I would probably do it with recursion (which still uses loops indirectly). The code will look something like this:
class Main {
public static void main(String[] args) {
String input = "1234"; // or scanner to take in input can be implemented
System.out.println(Integer.parseInt(reverseInt(input)));
}
public static String reverseInt(String x) {
if (x.length() == 1) {
return x;
} else {
return x.substring(x.length() - 1) + reverseInt(x.substring(0, x.length() - 1));
}
}
}
Hope this helps!
By using reverse() of StringBuilder:
int number = 1234;
String str = String.valueOf(number);
StringBuilder builder = new StringBuilder(str);
builder.reverse();
number = Integer.parseInt(builder.toString());
System.out.println(number);
will print:
4321
if you want reverse method without loop and recursion then use this code
int a=12345;
int b,c,d,e,f;
b=a%10;
c=a%100/10;
d=a%1000/100;
e=a%10000/1000;
f=a%100000/10000;
System.out.println(b+","+c+","+d+","+e+","+f);
you can go like :
public int reverse(int x) {
String o = "";
if (x < 0) {
x *= -1;
String s = Integer.toString(x);
o += "-";
o += new StringBuilder(s).reverse().toString();
}
else {
String s = Integer.toString(x);
o += new StringBuilder(s).reverse().toString();
}
try {
int out = Integer.parseInt(o);
//System.out.println(s);
return out; }
catch (NumberFormatException e) {
return 0;
}
}
This is a solution using recursive method call
public class Tester{
public static int findReverse(int num, int temp){
if(num==0){
return temp;
}else if(num<10){
return temp*10 + num; //up to this is stopping condition
}else{
temp = temp*10 + num%10;
return findReverse(num/10, temp);
}
}
public static void main(String args[]){
int num = 120021;
int reverseNum = findReverse(num, 0);
System.out.println(reverseNum);
if(num == reverseNum)
System.out.println(num +" is a palindrome!");
else
System.out.println(num +" is not a palindrome!");
}
}
This will be fast.
static int reverseNum(int num) {
StringBuilder sb = new StringBuilder(String.valueOf(num));
sb.reverse();
return Integer.parseInt(sb.toString());
}
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");
(I actually don't know how to write this code, I checked internet find it maybe look like this, but when I run it, it didnt work.
For example, input ("College",2). It should output ("College","College"). But it shows cannot read.
I just don't know how to solve this problem.
Please teach me how to write this code.
-------Write a RECURSIVE method called printStr that accepts two parameters: a String s and an int n. This method should return a String containing the String s written n times, separated by a space each time. Assume n >= 1.
For example, calling printStr("Lehman", 2) should return "Lehman Lehman", and calling printStr("The Bronx", 4) should return "The Bronx The Bronx The Bronx The Bronx".
Call your class Homework5_2. In the main method, call your method printStr several times to test it.
import java.util.Scanner;
public class Homework5_2 {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int n = 0;
String s = args[1];
System.out.print(printStr(s,n));
}
public static String printStr(String s, int n){
if (n==0) {
return "";
}
return s + printStr(s, n - 1);
}
Couple of issues with your code. Quoting assignment as you posted it:
"separated by a space"
"Assume n >= 1"
"In the main method, call your method printStr several times to test it."
So, write explicit calls in main(), don't use args. Add the missing space, and don't call or check for 0:
public static void main(String[] args) {
System.out.println('"' + printStr("College", 2) + '"');
System.out.println('"' + printStr("Lehman", 2) + '"');
System.out.println('"' + printStr("The Bronx", 4) + '"');
}
public static String printStr(String s, int n) {
if (n == 1)
return s;
return s + ' ' + printStr(s, n - 1);
}
Added quote ('"') to println() to ensure no extra spaces were added.
Output
"College College"
"Lehman Lehman"
"The Bronx The Bronx The Bronx The Bronx"
Alright, take your homework. But it will be better if you will try harder to do something by yourself.
static int maxn;
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
maxn = scanner.nextInt();
System.out.print(printStr(s, 0));
}
public static String printStr(String s, int n){
if(n == maxn){
return "";
} else if (n != 0){
s = " " + s;
}
return s + printStr(s, n + 1);
}
Not sure whats wrong with your code... just didnt put a space..
public static String printStr(String s, int n) {
if (n == 1) {
return s;
}
return s + " " + printStr(s, n - 1);
}
Add space and give newline at the last of string.
public static String printStr(String s, int n){
if (n==0) {
return "\n";
}
return s+" " + printStr(s, n - 1);
}
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) {
}
}
}