我有一个数组,假设: LRU_frame[] = {4,1,0,3}
我有一个随机()函数,它输出一个随机数。如果随机数n包含在数组LRU_frame中,那么,n应该在LRU_frame上,其他一切都必须相应地向下移动。
例如,如果随机()给我一个0,新的LRU_frame[] = {0,4,1,3}
另一个例子,如果随机()给我一个3,新的LRU_frame[] = {3,4,1,0}
对于任何数组大小,在其中包含任意数量的元素,如何做到这一点?
我知道如何通过在LRU_frame上添加一个新元素来转换数组,但不知道如何根据需要重新组织数组。
这是我到目前为止的代码,让我们假设char a是用来使用和重新组织数组的随机数(已转换为char)。
public static void LRU_shiftPageRef(char a) {
for (int i = (LRU_frame.length - 2); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
发布于 2014-04-01 11:59:03
您有一个好主意,您只需要找到a
元素在数组中的位置,然后从它开始循环,而不是从LRU_frame.length
开始。
int index = -1;
// find the positon of 'a' in the array
for (int i = 0; i <= (LRU_frame.length - 1); i++) {
if (LRU_frame[i] == a) {
index = i;
break;
}
}
// if it is present, do roughly the same thing as before
if (index > -1) {
for (int i = (index - 1); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
但是,如果您可以使用ArrayLists
,它会变得容易得多。
// declaration
ArrayList<Integer> LRU_frame = new ArrayList<Integer>();
...
if (LRU_frame.contains(a)) {
LRU_frame.remove((Integer) a);
LRU_frame.add(0, a);
}
发布于 2014-04-01 12:13:40
我想这可能是你想要的:
public static void LRU_shiftPageRef(char a) {
int index = indexOf(a);
if (index == -1) {
//not currently in array so create a new array 1 bigger than existing with a in newArray[0] or ignore depending on functionality required.
} else if (index > 0) {
//Set first entry as a and shift existing entries right
char insertChar = a;
char nextChar = LRU_frame[0];
for (int i =0; i < index; i++) {
LRU_frame[i] = insertChar;
insertChar = nextChar;
nextChar = LRU_frame[i+1];
}
LRU_frame[index] = insertChar;
} else {
//do nothing a is already at first position
}
}
public static int indexOf(char a) {
for (int i=0; i < LRU_frame.length; i++) {
if (LRU_frame[i] == a) {
return i;
}
}
return -1;
}
发布于 2014-04-01 12:04:57
使用Arrays.sort(LRU_frame);
对整个数组进行排序,或使用Arrays.sort(LRU_frame, fromIndex, toIndex));
对数组的一部分进行排序。
Arrays
类还有其他有用的方法,如copyOfRange
。
https://stackoverflow.com/questions/22795436
复制相似问题