Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Contar numeros repetidos en un ListBox (https://www.clubdelphi.com/foros/showthread.php?t=53516)

byfali 22-02-2008 17:17:59

Contar numeros repetidos en un ListBox
 
Hola que tal, tengo un problema que no puedo resolver.
Tengo un ListBox con una serie de numeros entre los cuales hay numeros repetidos. No soy capaz de hacer un codigo que me separes los numeros repetidos y la cantidad de repeticiones de dichos numeros.

Ejemplo: Tengo 1,2,58,2,3,1,8,1
El codigo que busco me deberia de indicar los siguiente:

Del numero 1 hay 3 repeticiones.
Del numero 2 hay 2 repeticiones.

Espero que me podais ayudar. Gracias.

maeyanes 22-02-2008 17:29:23

Hola!

Y que llevas avanzado hasta el momento? En que parte del código tienes problemas?

O deseas que te demos el código completo para resolver tu problema?



Saludos...

byfali 22-02-2008 17:37:21

Estoy clavado. No se me ocurre como puedo hacerlo.
Puedo recorrer el ListBox Item po Item pero no se me ocurre como separar los numeros repetidos.

maeyanes 22-02-2008 17:54:33

Hola...

Tienes varias opciones... usar un arreglo, o un TList... o hasta un TStringList:

O puedes copiar la lista a otra nueva y ordenarla y luego contar mientras no cambie el número:

Código Delphi [-]
var
  TempList: TStringList;
  OutPutList: TStringList;
  CurrentNumber: string;
  CurrentNumberCount: Integer;
  I: Integer;

begin
  TempList := TStringList.Create;
  // Copiamos la lista del TListBox a una temporal
  TempList.Assign(ListBox1.Items);
  // Ordenamos la lista para hacer más fácil el conteo
  TempList.Sort;  
  OutPutList := TStringList.Create;
  // Inicializamos la variable para obtener el primer número
  CurrentNumber := '';
  for I := 0 to Pred(TempList.Count) do
  begin
    // Si hay cambio de número, guardamos el total de ocurrencias y seguimos con el otro numero
    if CurrentNumber <> TempList[i] then
    begin
      if CurrentNumber <> '' then
        OutPutList.Add(Format('Del número %s hay %d repeticiones', [CurrentNumber, CurrentNumberCount]);
      CurrentNumber := TempList[i];
      CurrentNumberCount := 1
    end
    else
      Inc(CurrentNumberCount)
  end
end;

Este código lo hice al aire y no está probado, por lo que podría tener errores; pero te podría dar una idea de como hacerlo...



Saludos...

byfali 23-02-2008 10:01:22

Gracias maeyanes tu codigo es lo que yo necesitaba funciona bien. Lo adaptare a mis necesidades.


La franja horaria es GMT +2. Ahora son las 07:12:53.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi