我有以下陣列:[1,2,3,4,5,6,7,8,9]
我必須根據組和步驟引數回傳以下值
例如:
組 = 3; 步驟 = 3;
[
[1,2,3],
[4,5,6],
[7,8,9],
[1,2,3]
]
組 = 3; 步驟 = 2;
[
[1,2,3],
[3,4,5],
[5,6,7],
[7,8,9],
[9,1,2],
[2,3,4],
[4,5,6],
[6,7,8],
[8,9,1],
[1,2,3]
]
組 = 3; 步驟 = 4;
[
[1,2,3],
[5,6,7],
[9,1,2],
[4,5,6],
[8,9,1],
[3,4,5],
[7,8,9],
[2,3,4],
[6,7,8],
[1,2,3]
]
到目前為止,我有這個代碼片段(在 Java 中):
public static String[][] arrayOfArrays(String[] arr, int step, int group) {
int size = (arr.length / step) 1;
String[][] list = new String[size][group];
int start = 0;
for (int i = 0; i < size; i ) {
for(int j = 0; j < group; j ) {
list[i][j] = arr[start];
start ;
}
if(start == arr.length) {
start = 0;
}
}
return list;
}
我是演算法新手,我想了解我應該如何開始思考以解決問題?
謝謝
uj5u.com熱心網友回復:
我想說你首先要弄清楚的是你想要回傳的結果串列有多大。從我從上面的示例中可以看出,您不斷添加大小組串列,直到第一行與最后一行匹配。一旦我們知道了大小,那么我們就可以準確地創建一個具有適當大小的陣列來填充我們的資料,然后回傳它。
public static int[][] arrayOfArrays(int[] arr, int step, int group) {
int size = 0; // Keeps track of how many rows we got
int c = 1;
// Figure out the size by counting by offset till we come back to starting with 1
// Each time we count a full list add how many rows it would take
// to add that full list. Once we get back to starting with 1
// Just add that final row
while(true)
{
// Move number counter by how many indexes we will have moved in a list length
c = step*(arr.length/group);
// Because it wraps, lets do a modulo operation by the length of the array
c %= arr.length;
// Lets add how many rows we would have created this loop
size = arr.length/group;
if(c == 1) // Are we back to one as a first element in the row
{
size =1; // Add one more for that final row
break;
}
}
// Now that we know size, lets make our array
int[][] list = new int[size][group];
// Stuff the array with data until we are done
c = 1; // Reset our counter to 1
for(int r = 0; r < size; r )
{
for(int g = 0; g < group; g )
{
list[r][g] = c;
c = (c%arr.length) 1; // Index and loop through the list
}
}
return list;
}
uj5u.com熱心網友回復:
在這里也沒有太多經驗,但我會嘗試提供幫助,因為它看起來很有趣。我使用了您的代碼并將回傳的陣列更改為整數陣列以匹配您的示例。
編輯:感謝@RoyceIrving的回答,我理解了有多少內部陣列背后的邏輯。我現在相信我的解決方案可以滿足您的需求。
看一看:
public static int[][] arrayOfArrays(int[] arr, int step, int group) {
int size = (arr.length % step == 0) ? step 1 : arr.length 1;
int[][] list = new int[size][group];
for (int i = 0; i < size; i ) {
int stepper = (step*i) % arr.length;
for(int j = 0; j < group; j ) {
list[i][j] = arr[stepper];
stepper ;
if (stepper == arr.length) {
stepper = 0;
}
}
}
return list;
}
注意主要變化:
- 大小取決于給定的陣列(arr)是否除以給定的步驟(step)。如果是,則size等于step 1。否則,它等于陣列長度 ( arr.length ) 1。
- 變數“stepper”作為每個內部陣列的正確起點(根據給定的“step”)。此變數用于將正確的數字添加到陣列中,并在達到陣列長度時重置為 0。添加了一個模數以防止過大。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/388156.html
上一篇:在SQLServer中使用FORJSONAUTO的問題
下一篇:感知器演算法混亂
