我应该写一个程序,用K 1s打印出所有可能的N位序列,其余的(N-K)将是0s。还应该有一个计数器,指示最后有多少个序列。
在我的情况下,N = 9且K = 3,因此程序应编写如下内容:
111000000
110100000
...
101100000
101010000
...
000000111
Total: 84
到目前为止,我的代码看起来像这样
// N bits and K 1s
import java.util.ArrayList;
import java.util.Arrays;
public class Sequence {
public static void main(String[] args) {
ArrayList<int[]> all = new ArrayList<>();
int counter = 0;
int first = 0;
int second;
int third;
for (int i = first; i < 9; i++) {
int[] sequence = {0, 0, 0, 0, 0, 0, 0, 0, 0};
// the 1st "1"
sequence[i] = 1;
second = i + 1;
for (int j = second; j < 9; j++) {
int[] seq2 = sequence;
// the 2nd "1"
seq2[j] = 1;
third = j + 1;
for (int l = third; l < 9; l++) {
int[] seq3 = seq2;
// the 3rd "1"
seq3[l] = 1;
all.add(seq3);
counter++;
seq3[l] = 0;
third++;
}
second++;
}
first++;
}
for (int[] sequences : all) {
System.out.println(Arrays.toString(sequences));
}
System.out.println("Total: " + counter);
}
}
但它似乎没有做到,我也不知道为什么。该代码在Java中,我为9位序列使用了9个整数数组的ArrayList。
你几乎是对的。
您的问题在这里:
int[] seq2 = sequence;
和这里 :
int[] seq3 = seq2;
这些分配意味着您只有一个数组不断更改并添加到输出列表中。
将它们更改为:
int[] seq2 = Arrays.copyOf(sequence, sequence.length);
和 :
int[] seq3 = Arrays.copyOf(seq2, seq2.length);
还要删除这一行(由于每次迭代都会创建一个新数组,因此无需清除l
th元素):
seq3[l] = 0;
您将获得以下输出:
[1, 1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 0, 1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 1, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 1, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 1, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 1, 0]
[1, 1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 1, 1, 0, 0, 0, 0, 0]
[1, 0, 1, 0, 1, 0, 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