配列が1から配列の長さまでのすべての値を含んでいるかどうかを判断する、より効率的なアルゴリズムの提案を探しています。私が考案した解決策は、Ada2012を使って正しく動作します。配列の配列アルゴリズムの効率
------------------------------------------------------------------
-- Build a function to determine whether an array contains --
-- all the values from 1 through the length of the array. --
------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
procedure Sequence_test is
type Sequence_Array is array(Positive range <>) of Integer;
function Is_Sequence(Item : Sequence_Array) return Boolean is
Flags : Array(Positive range 1..Item'Length) of Boolean := (Others => False);
begin
for Num of Item loop
if Num in Flags'Range then
Flags(Num) := True;
else
exit;
end if;
end loop;
return (for all P of Flags => P = True);
end Is_Sequence;
A : Sequence_Array := (1,2,3,4,5,6);
B : Sequence_Array := (6,5,4,3,2,1);
C : Sequence_Array := (1,1,1,6,6,6);
D : Sequence_Array := (1,2,3,4,6);
E : Sequence_Array := (6,1,5,2,4,3);
F : Sequence_Array := (1,1,1,2,3,4,5,9,10,11);
begin
Put_Line("A is " & Boolean'Image(Is_Sequence(A)));
Put_Line("B is " & Boolean'Image(Is_Sequence(B)));
Put_Line("C is " & Boolean'Image(Is_Sequence(C)));
Put_Line("D is " & Boolean'Image(Is_Sequence(D)));
Put_Line("E is " & Boolean'Image(Is_Sequence(E)));
Put_Line("F slice is " & Boolean'Image(Is_Sequence(F(3..7))));
end Sequence_test;
私のプログラムの出力は
A is TRUE
B is TRUE
C is FALSE
D is FALSE
E is TRUE
F slice is TRUE
要件を少し良く説明できますか? –
例:あなたがインデックス 'i'で' a [abs(a [i]) - 1]> 0ならば 'return false'をチェックするelse' a [abs(a [i]) - 1] * = -1'と反復を続けます。複雑さは 'O(n)' –
です。配列に1から配列の長さまでのすべての値が含まれているかどうかを判断する必要があります。値は任意の順序で指定できますが、すべての値を表す必要があります。たとえば、6要素配列には1..6の値が含まれている必要があります。 –