我需要做这个问题:
”准备一个 int i 变量的矩形数组(具有随机自然正维度) 用区间 [0,10) 中的随机值填充它。创建并显示从以下位置创建的新板 通过从每一行中删除重复项(仅留下一个)来输入数组 每个值的出现)。 ”
我不被允许使用任何库
我尝试将重复项更改为间隔 [0,10) "1337" 之外的数字,例如, 然后删除所有“1337”以为会更容易,但我有越界例外
主要功能:
System.out.println("Zadanie 2");
int size = (int)(Math.random()*10);
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = (int)(Math.random()*10);
}
}
removeDuplicates2D(arr);
System.out.println(Arrays.deepToString(arr));
我的removeDuplicates2D函数:
public static void removeDuplicates2D(int[][] tab) {
int column = 0, row = 0;
while (column != tab.length-1 || row != tab.length-1){
if (column == 0 && row == 0){
column++;
continue;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if(tab[i][j] == tab[row][column]){
tab[row][column] = 1337; // will change all duplicates to 1337
}
}
}
if(++column == tab.length-1){
row++;
column = 0;
}
}
}
公共类RemoveDuplicates2DArray {
public static void main(String[] args) {
System.out.println("Zadanie 2");
int size = (int)(Math.random() * 10);
int[][] arr = new int[size][size];
// Fill array with random values in the range [0,10)
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = (int)(Math.random() * 10);
}
}
removeDuplicates2D(arr);
// Display modified array after removing duplicates
for (int i = 0; i < arr.length; i++) {
System.out.println(Arrays.toString(arr[i]));
}
}
public static void removeDuplicates2D(int[][] tab) {
for (int i = 0; i < tab.length; i++) {
int[] row = tab[i];
for (int j = 0; j < row.length; j++) {
for (int k = j + 1; k < row.length; k++) {
if (row[j] == row[k]) {
row[k] = -1; // Replace duplicates with -1 (outside [0,10) range)
}
}
}
// Shift elements to remove duplicates marked as -1
int index = 0;
for (int j = 0; j < row.length; j++) {
if (row[j] != -1) {
row[index++] = row[j];
}
}
// Fill the rest with 1337 (outside [0,10) range)
while (index < row.length) {
row[index++] = 1337;
}
}
}
}
对于以下 6x8 桌子
[4, 3, 2, 5, 2, 4, 3, 0]
[3, 7, 4, 8, 3, 7, 8, 7]
[9, 4, 5, 0, 6, 7, 3, 0]
[0, 2, 3, 1, 5, 3, 7, 7]
[7, 8, 3, 9, 4, 9, 7, 4]
[8, 2, 8, 4, 0, 0, 1, 1]
以下是去除重复的结果。
[4, 3, 2, 5, 0]
[7, 8]
[9, 6]
[1]
[]
[]
详情
[0-9)
的位置指示该值是否已被看到。该值是它自己的索引。itemCount
。该计数将用于为首次看到的值创建新行。一旦找到给定行的重复项
itemCount
1337
public static void removeDuplicates2D(int[][] tab) {
int[] dups = new int[10];
for (int row = 0; row < tab.length; row++) {
int itemCount = 0;
int[] currentRow = tab[row];
for (int col = 0; col < currentRow.length; col++) {
int index = currentRow[col];
if (dups[index] != 0) {
currentRow[col] = 1337;
} else {
itemCount++;
dups[index] = 1;
}
}
int[] newRow = new int[itemCount];
for (int k = 0, i = 0; i < currentRow.length; i++) {
if (currentRow[i] != 1337) {
newRow[k++] = currentRow[i];
}
}
tab[row] = newRow;
}
}