Brute Force Algorithm w/Java Passing String Error

后端 未结 1 1051
猫巷女王i
猫巷女王i 2020-12-22 02:49

I think this may be a very simple solution but I am not too sure.

I am trying to create an array of characters, sort through them by incrementing a particular index

相关标签:
1条回答
  • 2020-12-22 03:46

    Hope this helps you solve the problem. As for right now, your keyGen() is equivalent to the following code:

    public String keyGen() {
        return "!!!!!!!!";
    }
    

    because you return the value as soon as you enter the innermost for loop. Maybe you want to change the method to return a List<String> and add your strings in the innermost for loop to that list, and return that list after all of the for loops? This way you could iterate through the list in your main method.


    If I have counted correct, there are 93^8 = 5.595.818.096.650.401 different strings. It was bad advice to store all those in a list. Dukeling noted in the comments, that it would be better to use a custom Iterator<String> for that.


    EDIT

    Here's an implementation of such an iterator:

    import java.util.Arrays;
    import java.util.Iterator;
    
    public class BruteForceIterator implements Iterator<String> {
    
        private char min, max;
    
        private char[] current;
    
        private char[] last;
    
        private int reachedLast = 0;
    
        public BruteForceIterator(char min, char max, int length) {
            this.min = min;
            this.max = max;
            current = new char[length];
            Arrays.fill(current, min);
            last = new char[length];
            Arrays.fill(last, max);
        }
    
        @Override
        public boolean hasNext() {
            return reachedLast < 2;
        }
    
        @Override
        public String next() {
            String str = new String(current);
            for(int i = current.length - 1; i >= 0; i--) {
                char next = following(current[i]);
                current[i] = next;
                if (next != min) {
                    break;
                }
            }
            if (Arrays.equals(current, last) || reachedLast > 0) {
                reachedLast++;
            }
            return str;
        }
    
        private char following(char in) {
            if (in < max) {
                return (char) (in + 1);
            } else {
                return min;
            }
        }
    
        @Override
        public void remove() {
            throw new UnsupportedOperationException("No with me, sir!");
        }
    
        public static void main(String[] args) {
            BruteForceIterator bit = new BruteForceIterator('a', 'c', 3);
            while (bit.hasNext()) {
                System.out.println(bit.next());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题