我正试图为下一个问题提出一个解决方案:在OCaml中编写一个函数,该函数具有最长递增子数组的第一个和最后一个索引作为输出。我正在努力修复错误。 到目前为止,我已经写了:
示例:
longest_increasing_subarray [|2;4;6;9;1;5;3;5;0;8;9;13;17|];;
- : (8,12)
到目前为止,这是我的代码:
let longest_increasing_subarray p1 =
let n = Array.length p1
and beg = ref 0
and larg = ref(0,0) in
for i=0 to n-1 do begin
if i=0 then begin
end;
if p1.(i-1)<p1.(i) then
begin
if (snd !larg - fst !larg +1)<((i-1)-(!beg+1)) then
!larg = (!beg,i-1)
!beg = i end;
if (i=n-1) then
begin if (snd !larg-fst !larg +1)<((i)-(!beg)+1) then
!larg := (!beg,i)
end;
end;
done;
!larg;;
答案 0 :(得分:1)
您的代码和方法有一些问题,让我以问答形式突出它们:
如何为引用分配值
正确:
x := v
错误:
x = v
!x = v
!x := v
如何连续进行两次作业
正确:
x := v;
y := p
错误:
x := v
y := p
如何在条件上分支
正确:
if p1.(i - 1) < p1.(i)
then update_indices i;
else reset_indices ();
错误:
if p1.(i - 1) < p1.(i)
then begin update_indices i end
reset_indices ()
如何学习OCaml
如何实现longest_increasing_subarray
功能
Use a recursive function `find_longest` that will have four parameters:
- `p` - the beginning of the longest sequence;
- `q` - the end of the longest sequence;
- `s` - the beginning of the current working hypothesis
- `t` - the end of the current working hypothesis;
- `i` - the array index;
The longest increasing sequence in the array `a` is defined as
`find_longest 0 0 0 0 1`. The `find_longest` has the following definiton:
- if `i >= Array.length a` then the result is
- `(p,q)` if `p - q > t - s`
- `(s,t)` otherwise
- else if `a.(i-1) < a.(i)` then the result is `find_longest p q s i (i+1)`
- else if `q - p < t - s` then the result is `find_longest s t i i (i+1)`
- else the result is `find_longest p q i i (i+1)`