I am trying to print 122333221 using recursion if n is 3.But i am not able to solve it.We have given the number we have to print the series using recursion.For example if n = 3 then it should print 122333221.
public static void print(int n){
if(n < 1 ){
return;
}
print(n-1);
for(int i = 1; i <= n; i++){
System.out.print(n);
}
}
public static void main(String[] args) {
print(3);
}
You have to use the normal technique of keeping track of your state through parameters by defining a public method which uses a private method with extra parameters.
// Repeats n n times.
private static void repeat(int n) {
for (int i = 0; i < n; i++) {
System.out.print(n);
}
}
private static void print(int n, int v) {
if (n == v) {
// Just once for the deepest level.
repeat(n);
} else {
// Wrap the inner print ...
repeat(n);
// Recurse with the next higher value.
print(n + 1, v);
// ... end the wrap.
repeat(n);
}
}
public static void print(int n) {
System.out.print(n+": ");
print(1, n);
System.out.println();
}
public void test(String[] args) {
for (int i = 1; i <= 9 ; i++) {
print(i);
}
}
a possible solution will be n is the number of the different digits you have , while you need to print each digit times its value, so if n = 1
result =1
n =2 result 1221
n = 3, result 122333221
n = 4, result 1223334444333221
The implemenation is not hard , the base case is the number = n and its printed n times and you always print recursivly unless you reached n, the first call is always
solve(n, 1,1);
The implementation:
public void solve(int n, int numberOfPrints, int num) {
if(numberOfPrints == 0 && n ==num )
return ;
if(numberOfPrints == 0 )
solve(n, num+1,num+1);
System.out.print(num);
solve(n, numberOfPrints-1, num);
if(num == n)
return;
System.out.print(num);
}
public static void PrintSeries(int seriesNum, int currentNum, bool movingForward)
{
if(movingForward && currentNum < seriesNum)
{
PrintNum(currentNum);
PrintSeries(seriesNum, currentNum + 1, true);
}
else if(movingForward && currentNum == seriesNum)
{
PrintNum(currentNum);
PrintSeries(seriesNum, currentNum - 1, false);
}
else
{
if(currentNum > 0)
{
PrintNum(currentNum);
}
if(currentNum - 1 > 0)
{
PrintSeries(seriesNum, currentNum - 1, false);
}
}
}
public static void PrintNum(int num)
{
for(int x = 0; x < num; x++)
{
System.out.print(num);
}
}
Related
public class Nodigeven {
static int even=0;
static int count=0;
static int findnodigeven(int[] arr) {
for(int i=0;i<arr.length;i++) {
while(arr[i]!=0) {
arr[i]= arr[i]/10;
count++;
}
if(count%2==0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = {122,255,133,14,15,16};
System.out.println(findnodigeven(arr));
}
}
am getting wrong output i.e : 1 .. can you tell me where i am going wrong here in the code
As far as I can tell you have two errors. The first is that you did not reset count to 0 for each iteration of the loop. The second is that you did not check the special case of 0 in the array. 0 is a single digit and thus odd. But since you never enter the while loop, count will remain 0 and even will be incremented.
public class Nodigeven {
static int findnodigeven(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int count = 0;
// check for 0 value and skip.
if (arr[i] == 0) {
continue;
}
while (arr[i] != 0) {
arr[i] = arr[i] / 10;
count++;
}
if (count % 2 == 0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
If you're interested you and do this without explicitly counting the digits. Use Math.log10() to get the count, again skipping 0 since the log of 0 is undefined. The number of digits in a decimal number N is Math.log10(N)+1. You can use the conditional operator to add 1 or 0 as appropriate to the parity count.
public class Nodigeven {
static int even = 0;
static int findnodigeven(int[] arr) {
int even = 0;
for (int i = 0; i < arr.length; i++) {
even += arr[i] != 0 &&
(int) (Math.log10(arr[i])+1) % 2 == 0
? 1 : 0;
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
I am writing a bin packing program in one dimension. I want only one possible bin. So it does not include a lot of bin its only one. This program is only searching quad groups and explode if quad groups are not equal to the searching number. I want to search every possible group that is bigger than quads.
In example we have 60 60 50 40 45 35 25 15 and we are looking for summing equal to 180 and answer is 60 60 45 15 that's fine but if we search 250 it will not working.
Can you help me?
That's the link for program https://github.com/omerbguclu/BinPacking1D
That's the code for the algorithm o array is the numbers, a array is the location of answers
public BinPacking() {
}
public void binpack(ArrayList<Integer> o, ArrayList<Integer> a, int wanted) {
int sum = 0;
if (wanted > 0) {
control(o, a, wanted);
if (is) {
return;
}
for (int i = 0; i < o.size(); i++) {
sum += o.get(i);
summing(o, a, wanted - sum, i + 1);
if (is) {
a.add(i);
return;
}
for (int j = i; j < o.size(); j++) {
if (i != j) {
sum += o.get(j);
summing(o, a, wanted - sum, j + 1);
if (is) {
a.add(i);
a.add(j);
return;
}
sum -= o.get(j);
}
}
sum -= o.get(i);
// "/////////////*******************////////////////////");
}
if (wanted != sum) {
System.out.println("There is not an answer with quad summing method");
}
}
}
public void summing(ArrayList<Integer> o, ArrayList<Integer> a, int wanted, int loop) {
int sum = 0;
if (loop < o.size() && wanted > 0) {
for (int i = loop; i < o.size(); i++) {
if (wanted == o.get(i)) {
a.add(i);
is = true;
return;
}
for (int j = loop; j < o.size(); j++) {
if (i != j) {
sum = o.get(i) + o.get(j);
if (wanted != sum) {
sum = 0;
} else {
a.add(i);
a.add(j);
is = true;
return;
}
}
// System.out.println("///////////////////////////////////");
}
}
System.out.println("There is not an answer with binary summing method");
}
}
public void control(ArrayList<Integer> o, ArrayList<Integer> a, int wanted) {
for (int i = 0; i < o.size(); i++) {
if (o.get(i) == wanted) {
a.add(i);
is = true;
break;
}
}
}
There is a pretty well established and efficient mechanism for getting every possible combination of a set of objects. Essentially you treat membership of the combination as a BitSet which represents whether each member of the set is in the combination. Then visiting every combination is just visiting every BitSet combination.
Here's how I tend to implement it:
public class Combo<T> implements Iterable<List<T>> {
private final List<T> set;
public Combo(List<T> set) {
this.set = set;
}
public Iterator<List<T>> iterator() {
BitSet combo = new BitSet(set.size());
return new Iterator<List<T>>() {
public boolean hasNext() {
return combo.cardinality() < set.size();
}
public List<T> next() {
int i = 0;
while (combo.get(i))
combo.clear(i++);
combo.set(i);
return combo.stream().mapToObj(set::get).collect(Collectors.toList());
}
};
}
}
So your solution would become:
for (List<Integer> combo: new Combo<>(...)) {
if (combo.size >= 4 && combo.stream.reduce(0, Integer::sum) == total)
....
}
A hackier version of the same idea would be:
for (long l = 0; l < 1 << (input.size() - 1); l++) {
List<Integer> combo = BitSet.valueOf(new long[]{l}).stream()
.mapToObj(input::get).collect(Collectors.toList());
if (combo.stream().mapToInt(n -> n).sum() == total) {
System.out.println(combo);
}
}
I just want to print an array from [0,0,0,0] to [9,9,9,9] using recursion.
Firstly , I wrote the code as follows:
public class PrintNumber {
public static void main(String[] args) {
int N = 4;
int[] number = new int[N];
PrintNumber printNumber = new PrintNumber();
printNumber.printNum(number,0);
}
public void printNum(int[] number, int bit) {
if (bit == number.length ) {
System.out.println(Arrays.toString(number));
return;
}
for (int i = 0; i < 10; i++) {
number[bit] = i;
/******** something goes wrong here ********/
printNum(number, ++bit);
/******** something goes wrong here ********/
}
}
}
as you can see , there not too much code , but it didn't work.
So I debugged my code and I found out ++bit (the last line of the code) should be written as bit+1. Then , it works well.
But I am really confused , why is that? ++bit and bit+1 are both to increase the bit by 1 , why it doesn't work for ++bit and it works for bit+1 ?
Thanks a lot .
There is a difference between ++bit and bit + 1. The expression ++bit desugars into what is essentially bit = bit + 1*. So your line becomes.
printNum(number, bit = bit + 1);
So the actual value of the variable bit is changing, and since you call this in a loop, the value is going to keep increasing, which is not desired. Eventually, you get an ArrayIndexOutOfBoundsException when bit becomes too big for the array.
* It actually probably desugars into a more efficient JVM instruction, but semantically, it should be equivalent.
This is a workable solution.
import java.util.Arrays;
public class TestTest {
private static int N = 4;
private static int MAX = 10;
public static void main(String[] args) {
int[] number = new int[N];
TestTest printNumber = new TestTest();
printNumber.printNum(number,0);
}
public void printNum(int[] number, int bit) {
System.out.println(Arrays.toString(number));
if (bit == MAX ) {
return;
}
for (int i = 0; i < N; i++) {
number[i] = bit;
}
printNum(number, ++bit);
}
}
There was several problems:
You mixed loop and recurection.
Wrong array sizes
Wrong array values
Wrong print if-case
Wrong function exit.
This code yeilds stackoverflow exception. but it works for N = 3:
public class TestTest {
private static int N = 3;
private static int MAX = 10;
public static void main(String[] args) {
int[] number = new int[N];
TestTest printNumber = new TestTest();
printNumber.printNum(number);
}
public void printNum(int[] number) {
System.out.println(Arrays.toString(number));
// if (bit == MAX) {
// return;
// }
boolean exit = true;
for (int i = 0; i < N; i++) {
if (number[i] != MAX - 1) {
exit = false;
}
}
if (exit) {
return;
}
number[N - 1]++;
for (int i = N - 1; i >= 0; i--) {
if (number[i] == MAX) {
if (i > 0) {
number[i - 1]++;
number[i] = 0;
}
}
}
printNum(number);
}
}
Loop solution:
public class TestTest {
private static int N = 4;
private static int MAX = 10;
public static void main(String[] args) {
int[] number = new int[N];
TestTest printNumber = new TestTest();
// printNumber.printNum(number);
printNumber.printNumLoop(number);
}
private void printNumLoop(int[] number) {
while(true) {
System.out.println(Arrays.toString(number));
number[N - 1]++;
for (int i = N - 1; i >= 0; i--) {
if (number[i] == MAX) {
if (i > 0) {
number[i - 1]++;
number[i] = 0;
}
}
}
boolean exit = true;
for (int i = 0; i < N; i++) {
if (number[i] != MAX - 1) {
exit = false;
}
}
if (exit) {
System.out.println(Arrays.toString(number));
break;
}
}
}
public void printNum(int[] number) {
// if (bit == MAX) {
// return;
// }
boolean exit = true;
for (int i = 0; i < N; i++) {
if (number[i] != MAX - 1) {
exit = false;
}
}
if (exit) {
return;
}
number[N - 1]++;
for (int i = N - 1; i >= 0; i--) {
if (number[i] == MAX) {
if (i > 0) {
number[i - 1]++;
number[i] = 0;
}
}
}
printNum(number);
}
}
I have to write a boolean method that checks if a number n is a circular prime, using only integer computations, so no Strings. I wrote two other methods that have to be included.
boolean isPrime(int n) {
if (n < 1) {
return false;
} else if (n == 1 || n == 2) {
return true;
} else if (n % 2 != 0) {
for (int i = 3; i < n; i+=2) {
if (n % i == 0) {
return false;
}
}
return true;
} else {
return false;
}
}
This checks if the number is a prime.
int largestPowerOfTen(int n) {
for (int i = 1; i < n * 10; i*=10) {
if (n / i == 0) {
return i / 10;
}
}
return 1;
}
This returns the largest power of ten of the number. For instance, 23 would return 10, 704 would return 100, etc.
I had the idea to put every digit into an array and move the digits around from there, but I'm stuck at the moving part.
boolean isCircularPrime(int n) {
ArrayList<Integer> k = new ArrayList<Integer>();
int i = 0;
while (n != 0) {
k.add(n % 10);
n /= 10;
i++;
}
//???
}
So how do I move the digits around?
Assuming a "circular prime number" is a number that is a prime number for all rotations of the digits...
You can't just rotate the number, because zeroes won't be conserved.
First break up the number into an array - each digit of the number an element of the array. Use n % 10 to find the last digit, then n /= 10 until n == 0.
Create a method the generates a number from the array with a specified starting index. This is the crux of the problem, and here's some code:
private static int generate(int[] digits, int index) {
int result = 0;
for (int i = 0; i < digits.length; i++) {
result = result * 10 + digits[(index + i) % digits.length];
}
return result;
}
Then loop over every possible starting index for your digits and check if it's prime.
The remaining code I leave to the reader...
import java.util.Scanner;
class CircularPrime
{
public boolean prime(int n)
{
int lim=n,count=0;
for(int i=1;i<=lim;i++)
{
if(n%i==0)count++;
}
if(count==2)
return true;
else
return false;
}
public int circlize(int n)
{
int len,x,y,circle;
len=(""+n).length();
x=n/(int)Math.pow(10,len-1);
y=n%(int)Math.pow(10,len-1);
circle=(y*10)+x;
return circle;
/**
Another way using String
String str = Integer.toString(n);
String arr = str.substring(1)+str.charAt(0);
int a = Integer.parseInt(arr);
return a;
**/
}
public void check(int n)
{
int a=n;
boolean flag=true;
System.out.println("OUTPUT:");
do
{
if(!(prime(a)))
{
flag=false;
break;
}
a=circlize(a);
System.out.println(a);
}while(a!=n);
if(flag)System.out.println(n+" IS A CIRCULAR PRIME");
else System.out.println(n+" IS NOT A CIRCULAR PRIME");
}
public static void main(String ar[])
{
CircularPrime obj = new CircularPrime();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
obj.check(n);
}
}
I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five.
1 + 2 + 3 + 4 + 5 = 15
The current code always returns 0, how can the amount each time the n?
public class t {
public static void main(String[] args) {
System.out.println(num(5));
}
public static int num(int n) {
int sum = 0;
sum += n;
if (n == 0)
return sum;
return num(n - 1);
}
}
thank you.
Instead of setting the sum to 0 you can -
Do this:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
The problem is you set the sum always 0.
public static void main(String[] args) {
System.out.println(num(5, 0));
}
public static int num(int n, int sum) {
if (n == 0) {
return sum;
}
sum += n;
return num(n - 1, sum);
}
public static int withRecursion(List<Integer> list) {
int size = list.size();
int a=0;
if(list.isEmpty() == true) {
return 0;
}else {
a = a + list.get(0) + withRecursion(list.subList(1, size));
return a;
}
}