Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

How to find the shortest identical consecutive subarray in an array with Pascal

1 Answer

0 votes
program ShortestIdenticalProgram;

type
  TIntArray = array[1..128] of Integer;

procedure shortest_identical_consecutive_subarray(
  var arr: TIntArray; n: Integer;
  var bestStart, bestLen: Integer);
var
  i: Integer;
  currentStart, currentLen: Integer;
begin
  if n = 0 then
  begin
    bestStart := 0;
    bestLen := 0;
    Exit;
  end;

  bestStart := 1;
  bestLen := n;

  currentStart := 1;
  currentLen := 1;

  for i := 2 to n do
  begin
    if arr[i] = arr[i - 1] then
      Inc(currentLen)
    else
    begin
      if currentLen < bestLen then
      begin
        bestLen := currentLen;
        bestStart := currentStart;
      end;
      currentStart := i;
      currentLen := 1;
    end;
  end;

  { Check last run }
  if currentLen < bestLen then
  begin
    bestLen := currentLen;
    bestStart := currentStart;
  end;
end;

var
  lst: TIntArray;
  n, i: Integer;
  startPos, lengthPos: Integer;

begin
  { Example list }
  n := 20;
  lst[1] := 3; lst[2] := 3; lst[3] := 3;
  lst[4] := 7; lst[5] := 7; lst[6] := 7; lst[7] := 7; lst[8] := 7;
  lst[9] := 2; lst[10] := 2;
  lst[11] := 5; lst[12] := 5; lst[13] := 5; lst[14] := 5;
  lst[15] := 9; lst[16] := 9; lst[17] := 9; lst[18] := 9; lst[19] := 9; lst[20] := 9;

  shortest_identical_consecutive_subarray(lst, n, startPos, lengthPos);

  Write('Shortest identical consecutive subarray: ');
  for i := startPos to startPos + lengthPos - 1 do
    Write(lst[i], ' ');
  WriteLn;
end.




(*
run:

Shortest identical consecutive subarray: 2 2 

*)

 



answered 3 hours ago by avibootz
...