我试图更多地了解java中合同的含义。
这是java中两个合约的示例:
*/
* @pre arr != null
* @pre occurrences(4,arr) == occurrences(5, arr)
* @pre arr[arr.length – 1] != 4
* @pre forall 0 <= i < arr.length-2, arr[i] == 4 ==> arr[i+1] != 4
* @post forall 0 <= i < arr.length-1, $prev(arr[i]) == arr[i]
* @post $ret != arr
* @post permutation(arr, $ret)
* @post forall 0 <= i < arr.length-1, arr[i] == 4 ==> $ret[i] == 4
* @post forall 0 <= i < $ret.length-2, $ret[i] == 4 ==> $ret[i+1] == 5
/
第二个:
*/
* @post (arr != null AND
* occurrences(4,arr) == occurrences(5, arr) AND
* arr[arr.length – 1] != 4 AND
* forall 0 <= i < arr.length-2, arr[i] == 4 ==> arr[i+1] != 4)
<== *
* (forall 0 <= i < arr.length-1, $prev(arr[i]) == arr[i] AND
* $ret != arr AND
* permutation(arr, $ret) AND
* $ret.length == arr.length AND
* forall 0 <= i < arr.length-1, arr[i] == 4 ==> $ret[i] == 4 AND
* forall 0 <= i < $ret.length-2, $ret[i]==4 ==> $ret[i+1] == 5)
/
任务是使用这些先决条件更改给定数组,以便在出现任何 4 后出现 5。例如:
fix45({5,4,9,4,9,5}) -> {9,4,5,4,5,9}
fix45({1,4,1,5}) -> {1,4,5,1}
这是我写的(有效):
public static int pos (int[] arr, int k){
while (arr[k]!=5){
k=k+1;
}
return k;
}
public static int[] fix45(int[] arr){
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
}
我的问题: 1. 两份合同有什么区别?2.我真的应该检查前置条件吗?3. 这个“和”是什么意思?4. 我的代码应该如何根据第二份合同进行更改?
感谢你们。