I am working on a homework assignment, and I have completely exhausted myself. I'm new to programming, and this is my first programming class.
this is the problem:
Consider the following recursive function in Collatz.java, which is related to a famous unsolved problem in number theory, known as the Collatz problem or the 3n + 1 problem.
public static void collatz(int n) {
StdOut.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) collatz(n / 2);
else collatz(3*n + 1);}
For example, a call to collatz(7) prints the sequence
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
as a consequence of 17 recursive calls. Write a program that takes a command-line argument N and returns the value of n < N for which the number of recursive calls for collatz(n) is maximized. Hint: use memoization. The unsolved problem is that no one knows whether the function terminates for all positive values of n (mathematical induction is no help because one of the recursive calls is for a larger value of the argument).
I have tried several things: using a for loop, trying to count the number of executions with a variable incremented each time the method executed, and hours of drudgery.
Apparently, I'm supposed to use an array somehow with the memoization. However, I don't understand how I could use an array when an array's length must be specified upon initiation.
Am I doing something completely wrong? Am I misreading the question?
Here is my code so far. It reflects an attempt at trying to create an integer array:
public class Collatz2 {
public static int collatz2(int n)
{
StdOut.print(n + " ");
if (n==1) {return 1;}
else if (n==2) {return 1;}
else if (n%2==0) {return collatz2(n/2);}
else {return collatz2(3*n+1);}
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
StdOut.println(collatz2(N));
}
}
EDIT:
I wrote a separate program
public class Count {
public static void main(String[] args) {
int count = 0;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
count++;
}
StdOut.println("count is " + count);
}
}
I then used piping: %java Collatz2 6 | java Count
and it worked just fine.
Since you are interested in the maximum sequence size and not necessarily the sequence itself, it is better to have collatz return the size of the sequence.
private static final Map<Integer,Integer> previousResults = new HashMap<>();
private static int collatz(int n) {
int result = 1;
if(previousResults.containsKey(n)) {
return previousResults.get(n);
} else {
if(n==1) result = 1;
else if(n%2==0) result += collatz(n/2);
else result += collatz(3*n + 1);
previousResults.put(n, result);
return result;
}
}
The memoization is implemented by storing sequence sizes for previous values of n in Map previousResults.
You can look for the maximum in the main function:
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int maxn=0, maxSize=0;
for(int n=N; n>0; n--) {
int size = collatz(n);
if(size>maxSize) {
maxn = n;
maxSize = size;
}
}
System.out.println(maxn + " - " + maxSize);
}
The trick here is to write a recursive method where an argument is the value you want to "memoize". For instance, here is a version of a method which will return the number of steps needed to reach 1 (it supposes that n is greater than or equal to 1, of course):
public int countSteps(final int n)
{
return doCollatz(0, n);
}
public static int doCollatz(final int nrSteps, final int n)
{
if (n == 1)
return nrSteps;
final int next = n % 2 == 0 ? n / 2 : 3 * n + 1;
return doCollatz(nrSteps + 1, next);
}
If you were to record the different steps instead, you'd pass a List<Integer> as an argument and .add() to it as you went through, etc etc.
Related
Using recursion, If n is 123, the code should return 4 (i.e. 1+3). But instead it is returning the last digit, in this case 3.
public static int sumOfOddDigits(NaturalNumber n) {
int ans = 0;
if (!n.isZero()) {
int r = n.divideBy10();
sumOfOddDigits(n);
if (r % 2 != 0) {
ans = ans + r;
}
n.multiplyBy10(r);
}
return ans;
}
It isn't clear what NaturalNumber is or why you would prefer it to int, but your algorithm is easy enough to follow with int (and off). First, you want the remainder (or modulus) of division by 10. That is the far right digit. Determine if it is odd. If it is add it to the answer, and then when you recurse divide by 10 and make sure to add the result to the answer. Like,
public static int sumOfOddDigits(int n) {
int ans = 0;
if (n != 0) {
int r = n % 10;
if (r % 2 != 0) {
ans += r;
}
ans += sumOfOddDigits(n / 10);
}
return ans;
}
One problem is that you’re calling multiplyBy on n and not doing anything with the result. NaturalNumber seems likely to be immutable, so the method call has no effect.
But using recursion lets you write declarative code, this kind of imperative logic isn’t needed. instead of mutating local variables you can use the argument list to hold the values to be used in the next iteration:
public static int sumOfOddDigits(final int n) {
return sumOfOddDigits(n, 0);
}
// overload to pass in running total as an argument
public static int sumOfOddDigits(final int n, final int total) {
// base case: no digits left
if (n == 0)
return total;
// n is even: check other digits of n
if (n % 2 == 0)
return sumOfOddDigits(n / 10, total);
// n is odd: add last digit to total,
// then check other digits of n
return sumOfOddDigits(n / 10, n % 10 + total);
}
Hy guys, for some reason my greedy coins change program does not work. The function should return with the minimum amount of coins you can change a value and there is an array as well which includes the coins you can use for this. My program does not show anything an I dont know why.
public class Main {
public static int coinChangeGreedy(int[] coins, int n) {
int result = 0;
while (n != 0)
{
for (int i=coins.length - 1 ; i>=0 ; i--)
{
if (coins[i] <= n)
{
n = n - coins[i];
result++;
}
}
}
return result;
}
public static void main(String[] args)
{
int[] coins = {1, 2, 5};
int n = 11;
coinChangeGreedy(coins, n);
}
}
Well, at first - you are not printing anything - you just run the function.
Second - you have a bit of a flaw in your code. You see - if you find a coin that works, you shouldn't go to the next coin, but see if that one "fits" again.
In your example with n=11. You have 5 as the first one and then move to 2. But you should actually try the 5 again (prevent the for loop from going to the next element). See the example:
public static int coinChangeGreedy(int[] coins, int n) {
int result = 0;
while (n != 0) {
for (int i=coins.length - 1 ; i>=0 ; i--) {
if (coins[i] <= n) {
n = n - coins[i];
System.out.println("Adding " +coins[i]);
i++; //neutralizing i-- with i++.
result++;
}
}
}
return result;
}
Not you'll see that 5 is taken twice.
P.s. - if you are assuming that the coin array will be ascending.
And to print it, you just go:
System.out.println("Total coins needed: " +coinChangeGreedy(coins, n));
Additionally - if you want to keep track of coins used, you can store them in an ArrayList every time it is chosen. list.add(coins[i]). And of course you declare and initialize thatlist` at the beggining.
This exercise required us to write a program for counting the number of candies the poor kids can get. The question is shown below:
You are requested to write a Java program to help these poor kids to answer this question. To generalize the solution, your program should be able to accept different values of n and m as input, where n = 10 and m = 2 in this question. To avoid infinite number of answers, you may assume that each candy has exactly one foil and it is not allowed to cut the foils.
And I follow the hints given to write the program using the provided formula and java recursion.
import java.util.Scanner;
public class MyFirstClass{
public static void main(String args[]){
Scanner a=new Scanner(System.in);
int n=0,m=0;
n = a.nextInt();
m = a.nextInt();
System.out.println("Candy " +n+" "+ m + " n="+ n+";m="+m+";No. of Candies="+total(n,m));
}
static int sum=0;
static int total(int n, int m)
{
int sum1=n;
sum1+=candy(n,m);
return sum1;
}
static int candy(int n,int m){
if((n+n%m)/m>1){
sum+=n/m+candy((n+(n%m))/m,m);
}
return sum;
}
}
However, when I set n=10 and m=2, the calculated total number of candies is less than the actual total number of candies by 1. What is the problem of my program? Thank you!
For your candy function:
static int candy(int n,int m){
if((n+n%m)/m>1){
sum+=n/m+candy((n+(n%m))/m,m);
}
return sum;
}
How does it even compile when sum is undefined?
In any case, the candy function needs to check the boundary condition of of when the first paramater is 0 or 1. And I'll assume negative numbers aren't valid input either.
int candy(int n, int m) {
if ((n <= 1) || (m == 0)) {
return 0;
}
return n/m + candy( ((n+n%m)/m), m);
}
And since it's "tail recursion", you can implement the entire thing with a while loop:
int candy(int n, int m) {
int result = 0;
while ((n > 1) && (m != 0))
{
result += n/m;
n = (n+n%m)/m;
}
return result;
}
The problem I'm trying to solve comes from ProjectEuler.
Some integers have following property:
n + reverse(n) = a number consisting entirely of odd digits.
For example:
14: 14 + 41 = 55
Numbers starting or ending with 0 aren't allowed.
How many of these "reversible" numbers are there below 10^9?
The problem also gives a hint:
there are 120 such numbers below 1000.
I'm quite new to Java, and I tried to solve this problem by writing a program that checks all the numbers up to a billion, which is not the best way, I know, but I'm ok with that.
The problem is that my program gives out a wrong amount of numbers and I couldn't figure out why! (The code will most likely contain some ugly things, feel free to improve it in any way)
int result = 0;
boolean isOdd = true;
boolean hasNo0 = true;
public int reverseNumber(int r) //this method should be working
{ //guess the main problem is in the second method
int n = 0;
String m = "";
if (r % 10 == 0) { hasNo0 = false; }
while (r > 0){
n = r % 10;
m = String.valueOf(m+n);
r /= 10;
}
result = Integer.parseInt(m);
return result;
}
public void isSumOdd(int max)
{
int number = 1;
int sum = 0;
Sums reverseIt = new Sums();
int amount = 0;
while (number <= max)
{
sum = reverseIt.reverseNumber(number) + number;
while (sum > 0)
{
int x = sum % 10;
if (x % 2 == 0) { isOdd = false; }
sum /= 10;
}
if (isOdd && hasNo0) { amount++; }
number++;
isOdd = true;
hasNo0 = true;
}
System.out.println(amount);
}
Called by
Sums first = new Sums();
first.reversibleNumbers(1000000000);
The most important problem in your code is the following line:
sum = reverseIt.reverseNumber(number) + number;
in isSumOdd(int max) function. Here the reverseIt object is a new instance of Sums class. Since you are using Sums member data (the boolean variables) to signal some conditions when you use the new instance the value of these member variables is not copied to the current caller object. You have to change the line to:
sum = this.reverseNumber(number) + number;
and remove the Sums reverseIt = new Sums(); declaration and initialization.
Edit: Attempt to explain why there is no need to instantiate new object instance to call a method - I've found the following answer which explains the difference between a function and a (object)method: https://stackoverflow.com/a/155655/25429. IMO the explanation should be enough (you don't need a new object because the member method already has access to the member data in the object).
You overwrite odd check for given digit when checking the next one with this code: isOdd = false;. So in the outcome you check only whether the first digit is odd.
You should replace this line with
idOdd = idOdd && (x % 2 == 0);
BTW. You should be able to track down an error like this easily with simple unit tests, the practice I would recommend.
One of the key problems here is that your reverseNumber method does two things: check if the number has a zero and reverses the number. I understand that you want to ignore the result (or really, you have no result) if the number is a multiple of 10. Therefore, you have two approaches:
Only send numbers into reverseNumber if they are not a multiple of 10. This is called a precondition of the method, and is probably the easiest solution.
Have a way for your method to give back no result. This is a popular technique in an area of programming called "Functional Programming", and is usually implemented with a tool called a Monad. In Java, these are implemented with the Optional<> class. These allow your method (which always has to return something) to return an object that means "nothing at all". These will allow you to know if your method was unable or unwilling to give you a result for some reason (in this case, the number had a zero in it).
I think that separating functionnalities will transform the problem to be easier. Here is a solution for your problem. Perhaps it isn't the best but that gives a good result:
public static void main(final String [] args) {
int counter = 0;
for (int i = 0; i < 20; i++) {
final int reversNumber = reverseNumber(i);
final int sum = i + reversNumber;
if (hasNoZeros(i) && isOdd(sum)) {
counter++;
System.out.println("i: " + i);
System.out.println("r: " + reversNumber);
System.out.println("s: " + sum);
}
}
System.out.println(counter);
}
public static boolean hasNoZeros(final int i){
final String s = String.valueOf(i);
if (s.startsWith("0") || s.endsWith("0")) {
return false;
}
return true;
}
public static int reverseNumber(final int i){
final StringBuilder sb = new StringBuilder(String.valueOf(i));
return Integer.parseInt(sb.reverse().toString());
}
public static boolean isOdd(final int i){
for (final char s : String.valueOf(i).toCharArray()) {
if (Integer.parseInt(String.valueOf(s))%2 == 0) {
return false;
}
}
return true;
}
the output is:
i: 12
r: 21
s: 33
i: 14
r: 41
s: 55
i: 16
r: 61
s: 77
i: 18
r: 81
s: 99
4
Here is a quick working snippet:
class Prgm
{
public static void main(String args[])
{
int max=(int)Math.pow(10, 3); //change it to (10, 9) for 10^9
for(int i=1;i<=max;i++)
{
if(i%10==0)
continue;
String num=Integer.toString(i);
String reverseNum=new StringBuffer(num).reverse().toString();
String sum=(new Long(i+Long.parseLong(reverseNum))).toString();
if(sum.matches("^[13579]+$"))
System.out.println(i);
}
}
}
It prints 1 number(satisfying the condition) per line, wc is word count linux program used here to count number of lines
$javac Prgm.java
$java Prgm
...//Prgm outputs numbers 1 per line
$java Prgm | wc --lines
120
I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)