Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

java - Getting error on nested loop to generate combinations

I am dealing with a vector like this that has other vectors with some text inside it: [['manny','floyd'],['pacman','money','goat'],['mayweather','pacquiao']]

This is how I have declared vectors

Vector<String> one = new Vector<String>();
one.add("hello");
one.add("mellow");
Vector<String> two = new Vector<String>();
two.add("man");
two.add("boy");
two.add("women");

Vector<Vector<String>> bigVector = new Vector<Vector<String>>();
bigVector.add(one);
bigVector.add(two);

I am attempting to generate all possible combo of one word from first vector and one word from second vector such as

manny pacman mayweather
manny pacman pacquiao
manny money mayweather
manny money pacquiao

This is my code so far

for(int i = 0; i<bigVector.size(); i++){
   for(int j=i; j<bigVector.get(i).size; j++){
     for(int x = i + 1; j<bigVector.get(x).size; x++){
       //Print here
    }
  }
}

Every time I try to print something like System.out.println(bigVector.get(i).get(j) + bigVector.get(j+1)) I am getting lots of errors and i am not sure how to proceed.

All i can understand is that the outside loop should select each vector then the second loop inside that should select first element of first vector and second vector and third vector and fourth vector etc..

I would appreciate if someone can show how this is done.

Additional Notes

I am trying to make a generic function so the number of words inside each individual vectors can vary and also the number of vectors inside the big vector can vary which is what is making this problem Difficult

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you don't know how many inner vectors there are, it may be easier to reason with a recursive solution.

static void printWords(List<Vector<String>> bigVector) {
    printWords(bigVector, "");
}
static void printWords(List<Vector<String>> bigVector, String accumulator) {
    if(bigVector.isEmpty()) {
        System.out.println(accumulator);
    }
    else {
        for(String word : bigVector.get(0)) {
            printWords(bigVector.subList(1, bigVector.size()), accumulator + " " + word);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...