java - 如何将powerSet的内容保存到Java中的二维数组中
问题描述
我正在尝试将从一维数组获得的 PowerSet 的内容保存到二维数组中。我尝试在“if”语句中分配数组中的值,但我得到的索引完全错误
int[] set = new int[]{2,4,5,8}
int powSetLength = (int) Math.pow(2,set.length);
int[][] powSet = new int[powSetLength][];
for (int i = 0; i<powSetLength; i++){
for (int j = 0; j<set.length; j++){
if ((i & (1<<j))>0) {
powSet[i] = new int[] //here needs to be the length corresponding to the subset
powSet[i][j] = set[j]; //I know this is wrong but my idea was to assign each number of a subset into the 2d array
}
}
}
解决方案
由于您的内部数组是可变长度的,因此您可能希望使用内部数组java.util.ArrayList<Integer>
。像这样的东西:
int[] set = new int[]{2,4,5,8};
int powSetLength = (int) Math.pow(2,set.length);
List<Integer>[] powSet = new List[powSetLength];
for (int i = 0; i<powSetLength; i++){
for (int j = 0; j<set.length; j++){
if ((i & (1<<j))>0) {
// If the `i`'th powerSet isn't initialized yet: create an empty ArrayList:
if(powSet[i] == null)
powSet[i] = new ArrayList<>();
// And add the current set-value to the List:
powSet[i].add(set[j]);
}
}
}
System.out.println(Arrays.toString(powSet));
之后,您的列表数组将包含以下 powerset:
[null, [2], [4], [2, 4], [5], [2, 5], [4, 5], [2, 4, 5], [8], [2, 8], [4, 8], [2, 4, 8], [5, 8], [2, 5, 8], [4, 5, 8], [2, 4, 5, 8]]
推荐阅读
- python - 如果数据有噪声,如何有效衡量神经网络的性能
- c# - NuGet 找不到已安装的软件包:但允许我使用未安装的软件包
- powerbi - Power BI:DAX 公式 - 在组 ID 上构建总和
- ansible - 我的主机和相应的主机变量作为 JSON 输入给出。如何在 Playbook 中使用它们
- symfony-3.4 - 注释 "@Doctrine\ORM\Mapping\column":$status 不存在,或无法自动加载
- google-maps - 如何创建 ExtJS 谷歌地图?
- css - 将 fontawesome 图标与 flexbox 垂直对齐
- python - Python Pandas concat 股票数据返回 NaN 值
- typescript - 如何在 express.js 中为 2 个文件分隔我的路由器?
- python - 如何在 python 中将长文本文件写入终端,使其从文件开头显示?