2

How could i write this c# IEnumerable in java?

    public class Generator
    {
        private char[] characters;

        public Generator(char[] characters)
        {
            this.characters = characters;
        }

        public IEnumerable<string> GetStrings(int totalDigit)
        {
            if (totalDigit > 0)
            {
                foreach (char c in characters)
                {
                    foreach (string next in GetStrings(totalDigit - 1))
                    {
                        yield return c + next;
                    }
                }
            }
            else
            {
                yield return string.Empty;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int maxDigit = 2;
            char[] characters = "abc".ToCharArray();
            Generator generator = new Generator(characters);
            for (int i = 1; i <= maxDigit; i++)
            {
                Console.WriteLine(i +" Digit");
                foreach(string word in generator.GetStrings(i))
                {
                    Console.WriteLine(word);
                }
            }

        }
    }

output

1 Digit
a
b
c
2 Digit
aa
ab
ac
ba
bb
bc
ca
cb
cc
Press any key to continue . . .

i am trying to make word list generator in java, but i could not write this c# enurable in java. i have try a lot to read documentation, tutorials, Q&A in StackOverflow and uses iterable, iterator in java but still no result i hope you could help me

Thanks

J.Smile
  • 41
  • 6
  • 1
    This might help your https://stackoverflow.com/questions/2352399/yield-return-in-java – Nongthonbam Tonthoi May 25 '20 at 01:41
  • 1
    I don't know a Java answer, but you can see what C# compiles to [here](https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEAsBuWsQGZlkQGFEBvWRCxcygBwCcBLANwEMAXAU0QGMALFugG0Auj350W3TnQDOiALyIAdgFcANmswxKVbZVzJUiALIAKAJSlqOigDMA9nQ6TeiU6zqJWaxAyWIAcQ42AGU2RiUAcxlTAFZzc2sbMj0bGxQATncWNXMtNIoAXyTi1N0dAxQcAB4UeAA+QOCwiOjTPzZENns2HIARBkiGNkSylILfWzdu3rUBoc7G+FGJ8YnKBycXNz4BHl9/XYkpDlkV9Yo1i51N5z43OuUOAA9OvybQ8L82mf7B4cQAFpEBAEklrlYyhCKhAIMgAOz7ADUT1e+WhRXBBVKExxBQ4ahkHCxlxJ6VhCOQEHgADoAKIAWxobAAnui0njMTBCkA==). – ProgrammingLlama May 25 '20 at 01:41
  • 1
    Can you show us your iterable code that isn't working? IEnumerable is a pretty loaded class in C#; why that class? If the actual goal is an endless of lazily generated elements, Iterable is likely the correct approach. Iterable is pretty limited in Java though, so it might help to understand your use case. – Charlie Jun 02 '20 at 06:19

0 Answers0