Execution of a for statement within a recursive function

Asked 1 years ago, Updated 1 years ago, 68 views

import java.util.ArrayList; import java.util.Scanner;

public class Anagram {

public static void ana(ArrayList<String> ar, ArrayList<String> sub)
{
    if(ar.size()>1)
    {
        for(int i = 0; i < ar.size(); i++)
        {
            System.out.println ("Run");
            sub.add(ar.get(i));
            ar.remove(i);
            ana(ar, sub);
        }
    }
    else if(ar.size() == 1)
    {
        sub.add(ar.get(0));
        System.out.println(sub);
        return;
    }
}

public static void main(String[] args) {
    // // TODO Auto-generated method stub
    ArrayList<String> ar = new ArrayList<String>();
    ArrayList<String> sub = new ArrayList<String>();
    Scanner a = new Scanner(System.in);
    Scanner b = new Scanner(System.in);
    System.out.println ("Please enter the number of characters to enter :");
    int count = a.nextInt();
    for(int i = 0; i < count; i++)
    {
        ar.add(b.nextLine());
    }

    ana(ar, sub);
}

}

I'm going to make an Anagram using a recursive function. But if you do this, it's executed when the for statement in the method is zero, and it's only done once, and it's not repeated after that. I didn't know how to repeat this. I ask for your help me. <

java recursion for

2022-09-22 13:29

1 Answers

import java.util.ArrayList; import java.util.Scanner;

public class Anagram {

    public void Func(ArrayList<String> ar, ArrayList<String> sub, int size)
    {     
        if(size == 0)
        {
            System.out.println(sub);
            return;
        }

        System.out.println ("Run");

        sub.add(ar.get(0));
        ar.remove(0);

        Func(ar, sub, size-1);
    }

    public static void main(String[] args) {
        Anagram ana = new Anagram();
        ArrayList<String> ar = new ArrayList<String>();
        ArrayList<String> sub = new ArrayList<String>();
        Scanner a = new Scanner(System.in);
        Scanner b = new Scanner(System.in);

        System.out.println ("Please enter the number of characters to enter :");

        int count = a.nextInt();
        for(int i = 0; i < count; i++)
        {
            ar.add(b.nextLine());
        }

        ana.Func(ar, sub, ar.size());
    }
}

I'm not sure what you want


2022-09-22 13:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.