array no delphi (pascal)

20/09/2017

0

Boa noite.

Alguém poderia me ajudar com uma duvida de algoríto em uma aplicação delphi ou lazarus?

Dada um array A de N inteiros, retorna o menor inteiro positivo (maior que 0) que não ocorre em A.

Por exemplo, dado A = [1, 3, 6, 4, 1, 2], a função deve retornar 5.
Jefferson Szyndrowski

Jefferson Szyndrowski

Responder

Post mais votado

20/09/2017

Boa noite, Jefferson

Fiz um pequeno programa que faz o cálculo ao clicar um Button. Segue código da Unit1.pas:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    function ExisteNoArray(const Numero: Integer; var UmArray: array of Integer): Boolean;
  end;

var
  Form1: TForm1;

implementation

uses Math;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  A: array[0..5] of Integer;
  ValorMinimo: Integer;
begin
  A[0] := 1;
  A[1] := 3;
  A[2] := 6;
  A[3] := 4;
  A[4] := 1;
  A[5] := 2;

  // Armazena o menor valor do Array;
  ValorMinimo := A[Low(A)];

  // Garante que o Valor Mínimo seja sempre maior que zero;
  if (ValorMinimo <= 0) then
    ValorMinimo := 1;

  // Percorre o Array verificando se o Valor mínimo existe no Array;
  while (ExisteNoArray(ValorMinimo, A)) do
  begin
    // Incrementa + 1 até chegar ao valor mínimo maior que zero e que não exista em A;
    Inc(ValorMinimo);
  end;

  ShowMessage(' O Valor Mínimo positivo maior que zero e que não ocorre em A é: ' + IntToStr(ValorMinimo));
end;

function TForm1.ExisteNoArray(const Numero: Integer;
  var UmArray: array of Integer): Boolean;
var
  i: Integer;
begin
  Result := False;

  for i := Low(UmArray) to High(UmArray) do
  begin
    if (Numero = UmArray[i]) then
    begin
      Result := True;
      Break;
    end
  end;
end;

end.


Usei o seu Array como exemplo. Teste e veja se funciona.
Espero ter ajudado, abraço!

Felipe Morais

Felipe Morais
Responder

Mais Posts

20/09/2017

Jefferson Szyndrowski

Bom dia Moraissan.

Cara me ajudou bastante, mas daria para fazer essa verificação só em algoritmo puro, no caso sem as funções do Delphi?

Por exemplo, fazer um for para comparar os arrays A e B e gerar um C e dai eu retornar o menor valor desse C?

Desde já agradeço pela ajuda.
Responder

20/09/2017

Felipe Morais

Bom dia,

Ué, pegue o código da function e itere no Array, dá no mesmo! Se o código inicial funcionou, curte lá.
Tente desenvolver o algoritmo, posso ir te ajudando.

Abraços!
Responder

20/09/2017

Jefferson Szyndrowski

program menor_valor;

uses sysutils;

var
example1: array[1..6] of longint = (1, 3, 6, 4,1, 2);
i, j, vmenor, vmaior : integer;
vachou : boolean;

begin
vmaior := 0;
vmenor := 0;

for i:= 1 to 6 do
begin
if example1[i] > vmaior then
vmaior := example1[i];
end;

for i := 1 to vmaior do
begin
vachou := false;
for j := 1 to 6 do
begin
if example1[j] = i then
begin
vachou := true;
break;
end;
end;

if not(vachou) then
begin
vmenor := i;
break;
end;
end;

if vmenor = 0 then
begin
writeln('Menor valor: ', vmaior +1);
readln;
end
else begin
writeln('Menor valor: ', vmenor);
readln;
end;

end.


Consegui fazer assim, porém eu preciso fazer isso dentro da seguinte função:

function solution(A: array of longint; N: longint): longint;
begin
(* write your code in Free Pascal 3.0 *)

end;

O problema é que nunca usei função com array ai estou travado e nao acho exemplo em lugar nenhum.
Responder

20/09/2017

Felipe Morais

Boa tarde, Jefferson

O parâmetro "N" da sua function seria o comprimento do Array, a quantidade de números inteiros armazenados nele?

Quando se usa Array dinâmico, isto é, quando não se sabe o tamanho que vai ocupar inicialmente, é importante lembrar sempre de definir seu tamanho antes de trabalhar com ele. Isto pode ser feito com a procedure SetLength. Antes fazer qualquer coisa dentro da sua function, defina o tamanho do Array, caso contrário o compilador gerará um erro. Um exemplo abaixo da sua função. Estou usando a premissa que "N" seria o tamanho do Array;

function solution(A: array of longint; N: longint): longint;
begin
  SetLength(A, N); // Aqui o Array A recebe comprimento N;

  // Agora transponha o seu código aqui dentro;

end;


Do Help do Delphi (estou usando o Delphi 7):


procedure SetLength(var S; NewLength: Integer);

Sets the length of a string or dynamic-array variable.

S is a Delphi string or dynamic-array variable.

NewLength is the new number of characters or elements in S.

For a short-string variable, SetLength simply sets the length-indicator character (the character at S[0]) to the given value. In this case, NewLength must be a value between 0 and 255.

For a long-string or dynamic-array variable, SetLength reallocates the string or array referenced by S to the given length. Existing characters in the string or elements in the array are preserved, but the content of newly allocated space is undefined. The one exception is when increasing the length of a dynamic array in which the elements are types that must be initialized (strings, Variants, Variant arrays, or records that contain such types). When S is a dynamic array of types that must be initialized, newly allocated space is set to 0 or nil.

For dynamic arrays, SetLength may take more than one length parameter (up to the number of array dimensions). Each parameter specifies the number of elements along a particular dimension.

Following a call to SetLength, S is guaranteed to reference a unique string or array—that is, a string or array with a reference count of one. If there is not enough memory available to reallocate the variable, SetLength raises an EOutOfMemory exception.
Responder

24/09/2017

Jefferson Szyndrowski

consegui resolver da seguinte forma:

function solution(A: array of longint; N: longint): longint;
var
vachou: boolean;
i, menor: integer;
begin
(* write your code in Free Pascal 3.0 *)
// A: array [1..100] : longint;
menor:= 0;
vachou:= true;

while vachou do
begin
inc(menor);
vachou:= false;

for i:= low(A) to high(A) do
begin
if menor = A[i] then
begin
vachou := true;
end;

if vachou then
begin
break;
end;
end;
end;

exit(menor);
end;

Porém por causa do while a performance nao foi mto boa, teria algum jeito de fazer só com um ou dois for's?
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar