How to use recursion technique on the following code? - java

static void nLines(int n) {
for (int i= 0; i < n; i++) {
System.out.println(i);
}
}

You can recurse on n.
static void nLines(int n) {
if( n <= 0) {
return;
} else {
int x = n - 1;
nLines(x);
System.out.println(x);
}
}
You call the function like so:
nLines(n);

Here is a recursive function to print n lines:
static void nLinesRecursive(int n) {
int next = n - 1;
if (next >= 0) {
nLinesRecursive(next);
System.out.println(next);
}
}

Try this.
static void nLines(int n) {
if (--n < 0) return;
nLines(n);
System.out.println(n);
}
public static void main(String[] args) {
nLines(3);
}
output:
0
1
2

Related

Editing and adding the sum of java arrys

I am trying to iterate over an array and add the sum of the array except the number 13 and the number after it.
Example
[1,1,1,1,13,2] = [1,1,1,1,0,0] = 4
this is what I have so far the main things I need to know is how do I check if the array has a number 13 in it and how do I change it to a 0
public static int sum13(int[] nums) {
for(int i=0; i < nums.length; i++) {
if(nums.indexOf(i) == 13) {
}
}
}
public static void main(String[] args) {
//this is the main method
int[] a = {1,2,3,13,4};
sum13(a);
}
}
You can try this , to skip adding all number when you get 13 in your array :
public static int sum13(int[] nums) {
int sum = 0;
for(int i=0; i < nums.length; i++) {
if(nums[i] == 13) {
break;
}
sum += nums[i];
}
return sum;
}
public static void main(String[] args) {
//this is the main method
int[] a = {1,2,3,13,4};
System.out.println(sum13(a));
}
Try this.
public static int sum13(int[] nums) {
return IntStream.of(nums).takeWhile(i -> i != 13).sum();
}

Not able to find possible solutions for N-Queens puzzle

I am trying to find all possible solutions for N-Queens puzzle. I have to print single queen on each row, and no two queens should be adjacent to each other like no one or more queens diagonally, no one or more queens in a same row, no one or more queens in a same column.
I have written the algorithm and think that most part of it is correct, but the solutions are not getting printed. I don't understand why. I have spent a lot of time on this.
Any help will be appreciated.
Following is my code:
public class NQueens {
int[] x;
public NQueens(int n) {
x = new int[n];
} // CONSTRUCTOR
public void printQueens(int[] x) {
int N = x.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (x[i] == j) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
//Promising method
public boolean canPlaceQueen(int r, int c) {
for (int i = 0; i < r; i++) {
if (x[i] == c || (i - r) == (x[i] - c) ||(i - r) == (c - x[i]))
{
return false;
}
}
return true;
}
//permute method
public void placeNqueens(int r, int n) {
for (int c = 0; c < n; c++) {
if (canPlaceQueen(r, c)) {
x[r] = c;
if (validSol(r,n)) {
printQueens(x);
} else {
placeNqueens(r + 1, n);
}
}
}
}
public boolean validSol(int r, int n){
if(r== n) {
return true;
}
else {
return false;
}
}
public void callplaceNqueens() {
placeNqueens(0, x.length);
}
public static void main(String args[]) {
NQueens Q = new NQueens(8);
Q.callplaceNqueens();
}
}
Your code looks fine. It is only missing a key check in the validSol method.
Change the validSold method to the following and your code should work fine.
public boolean validSol(int r, int n){
if(r== n-1) {
return true;
}
else {
return false;
}
}
Let me know if this works for you.

How to print number and "*" combination in java

My program is as below:
package simplemirror;
public class simple {
public static void main (String arg[]){
for( int i = 1; i <= 3; i++ ){
for( int j = 0; j < i; j++ ){
System.out.print(i+"*");
}
System.out.println("");
}
}
}
Above program output is as below:
1*
2*2*
3*3*3*
I need output as below:
1
2*2
3*3*3
2*2
1
this code will work try this.............:)
public class simple {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n;
n=3;
for(int i=1;i<2*n;i++){
if(i<=n){
for(int j=1;j<i;j++){
System.out.print(i+"*");
}
System.out.println(i);
}
else{
for(int j=i+1;j<2*n;j++){
System.out.print(2*n-i+"*");
}
System.out.println(2*n-i);
}
}
}
}
try
public static void main(String[] args) {
int limit=5;
int rows=limit+(limit-1);
int center=(int) Math.ceil(((double)rows/2));
boolean centerReached=false;
for(int i=1;i<=limit&&i>0;){
for(int j=1;j<=i;j++){
System.out.print(i);
if(i==j)
continue;
System.out.print("*");
}
if(center==i)
centerReached=true;
if(centerReached)
i--;
else
i++;
System.out.println();
}
}
ouptut
1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4
3*3*3
2*2
1
EDIT:
It's been a while, and I have learned a few things.
You can use streams!
private static void print(int num) {
IntStream.concat(
IntStream.iterate(1, (i) -> ++i).limit(num),
IntStream.iterate(num - 1, (i) -> --i).limit(num).limit(num - 1))
.boxed()
.map(i -> Stream.generate(i::toString).limit(i).collect(Collectors.joining("*")))
.forEach(System.out::println);
}
Please don't ask such question here. Ans to your question may be looks like follows but once again don't ask such questions here.
public class simple {
public static void main (String arg[])
{
for( int i = 1; i <= 3; i++ ){
for( int j = 0; j < i; j++ ){
if(j== i-1)
{
System.out.print(i);
}
else
{
System.out.print(i+"*");
}
}
System.out.println("");
}
}
}

Make a print method with for loop Java

The task of exercise is to make a method that will work like in Example.( We must use for loop. But if you know how to do it in another way, it will be also very interesting.) Input number can be any.
Example:
Input: 3
Output:
**1**
*121*
12321
*121*
**1**
My example:
public static void main(String[] args) {
printMatrix(5);
}
public static void printMatrix (int n) {
int d = n +(n-1);
for (int i = 0; i < n ; i++)
{
for(int j = 1; j <=d; j++){
int abs = Math.abs(j-n);
System.out.print(abs>i ? "*" : i-abs+1);
}
System.out.println("");
}
My output:
****1****
***121***
**12321**
*1234321*
123454321
I can't make the next step, to turn it upside down. Dose anybody hava an ideas?
I have solved this exercise, but I think it is not a perfect solution. Does anybody have another way to solve this task?
public static void main(String[] args) {
printMatrix(5);
}
public static void printMatrix (int n) {
int d = n +(n-1);
int k = n*2;
int g = -1;
for (int i = 0; i < d ; i++)
{
if(i<n){
g++;
}
else{k=n*2;
g--;}
for(int j = 1; j <=d; j++){
if (i < n){
int abs = Math.abs(j-n);
System.out.print(abs>i ? "*" : i-abs+1);
}
else{
k--;
int abs = Math.abs(k-n);
System.out.print(abs>g ? "*" : g-abs+1);
}
}
System.out.println("");
}
}
}
Output:
****1****
***121***
**12321**
*1234321*
123454321
*1234321*
**12321**
***121***
****1****

This program I wrote in Java is taking a long time to run ( I haven't seen the results yet)

Can someone help me figure out what is going wrong here? This java program is taking a very long time to run, so long that I haven't seen the result yet.
/* Returns all the factors of a given number */
import java.util.*;
import java.lang.Object;
class factors{
public static ArrayList<Integer> factorList;
public static void get_factors(int num){
factorList = new ArrayList<Integer>();
int i = 2;
while(i < num)
{
if (num%i == 0)
{
factorList.add(i);
i++;
}
}
}
public static void main(String[] args){
int num = 20;
get_factors(num);
for(int i = 0; i < factorList.size(); i++)
{
int element = factorList.get(i);
System.out.println(element);
}
}
}
You increment i only if it is num%i == 0, therefore for i=3 you stop incrementing it and while-loop never ends.
You want this :
if (num%i == 0)
{
factorList.add(i);
}
i++;
Note also, that there is no reason to use while-loop.
This is more logical solution :
public static void get_factors(int num) {
factorList = new ArrayList<Integer>();
for (int i = 2; i < num; i++) {
if (num % i == 0) {
factorList.add(i);
}
}
}
Also, you should consider, if the factorList initialisation should be in get_factors method, I think you should move it into class
class factors{
public static ArrayList<Integer> factorList = new ArrayList<>();
public static void get_factors(int num) {
factorList = new ArrayList<Integer>();
for (int i = 2; i < num; i++) {
if (num % i == 0) {
factorList.add(i);
}
}
}
}
i is not always begin incremented, if you use a for loop the problem is easier to avoid.
public static void get_factors(int num){
factorList = new ArrayList<Integer>();
for(int i = 2; i < num; i++) {
if (num%i == 0) {
factorList.add(i);
}
}
}
The problem is in your loop:
while(i < num)
{
if (num%i == 0)
{
factorList.add(i);
i++;
}
}
if num%i is not equal to zero i will not be incremented and the loop will run again with the same value of i.
So move the i++ out of your if-block:
while(i < num)
{
if (num%i == 0)
{
factorList.add(i);
}
i++;
}
Or better: use a for-loop:
for(int i = 1;i<num;i++) {
if (num%i == 0)
{
factorList.add(i);
}
}

Categories