Anuncio

Colapsar
No hay ningún anuncio todavía.

¿Cómo se podría crear un algoritmo/programa para esta aplicación?

Colapsar
X
 
  • Filtro
  • Hora
  • Mostrar
Borrar todo
nuevos mensajes

  • #16
    Re: ¿Cómo se podría crear un algoritmo/programa para esta aplicación?

    Buenas noches,
    Estoy recien llegado a este foro del que he tenido conocimiento buscando por internet solución al problema de un algoritmo para hallar los números colindantes (o vecinos) en una matriz determinada, de manera que devuelva el número de grupos de colindantes y la composición de cada uno de ellos.
    El caso es que creo que es un problema que escapa a mis conocimientos matemáticos y por eso busco ayuda.
    Quiero elaborar un programa que tenga que contemple entre otras esta función que comento y he dado con este hilo que es exactamente lo que busco.
    El problema es que yo programo en Delphi y no tengo ni papa de mathlab ni de mathcad que es lo que se ha tratado aqui.
    Llevo un par de dias dandole vueltas a estos códigos y nada….
    Me he decidido a intentar una traducción a delphi pero como os comento se me hace muy cuesta arriba y queria saber si podríais echarme una mano con la traducción.


    Os pongo aqui lo que llevo, que aunque compila sin errores el programa casca al ejecutarlo (ya me lo imaginaba yo según escribia las líneas, je,je).


    El código lo he intentado realizar con el pase de argumentos tal y como figura en los ejemplos mathlab y mathcad (sin exito, claro) pero al leer sobre las "componendas" que habia que hacer en mathcad con el tema del pase de argumentos me he decidido a realizarlo sin ellos en la mayoria de los casos, y utilizo variables globales a la función en la que he realizado el código. Las funciones vecinos y generar lista estan declaradas en la sección de variables por lo que acceden también a las variables globales M y V entre otras.


    También y por simplicidad (o eso creo) en la función Vecinos, he sustituido el primer bucle anidado (donde figura la función on error en el codigo mathcad) por la función PrepararMatriz que se supone que pone a ceros toda la matriz y la llena con los 6 numeros que previamente he cargado en la variable V.


    En fin…. si necesitais mas aclaraciones pues aqui estoy.


    Ahí va el código.


    Muchas gracias de antemano :-)

    Código:
    procedure TForm1.bProcesar;
    type
      TMatriz = array of array of integer;  // Defino el tipo de matriz de dos dimensiones
    
    
    var                    // Aqui vienen las variables globales
      nelem: Integer;
      M: TMatriz;
      V: array[0..5] of integer;
      L: array of integer;            // Esta variable la he declarado para contener los grupos de  colindantes
    
    
      Procedure PrepararMatriz;        // Función para llenar la matriz con ceros y luego completarla con los numeros a evaluar
      var
        q: Integer;
      begin
          for q := low(V) to high(V) do
          begin
            if v[q] in [ 1.. 9] then M[0, q mod 10] := v[q];
            if v[q] in [10..19] then M[1, q mod 10] := v[q];
            if v[q] in [20..29] then M[2, q mod 10] := v[q];
            if v[q] in [30..39] then M[3, q mod 10] := v[q];
            if v[q] in [40..49] then M[4, q mod 10] := v[q];
          end;
      end;
    
    
      Procedure GenerarLista(fila, columna: Integer);    // He obviado el resto de parámetros porque la función puede acceder a las variables M y V directamente
      var
        f,c: Integer;
      begin
            Inc(nelem);
            L[nelem]:=M[columna,fila];
            M[columna,fila]:=0;
            for f:=fila-1 to fila+1 do
              for c:=columna-1 to columna+1 do
                if (f=fila) and (c=columna) then
                  GenerarLista(f,c);
      end;
    
    
      Procedure vecinos;
      var
        nli, f, c: Integer;
        vAux:String;
      begin
            PrepararMatriz;
            nelem:=0;
            nli:=0;
            for f := 0 to 9 do
              for c := 0 to 4 do
                if M[c,f]<>0 then
                begin
                  Inc(nli);
                  GenerarLista(f,c);
                  Vecinos;
                end;
      end;
    
    
    begin // Comienza el programa
          // Cargar vector de numeros a evaluar
          V[0]:=1; v[1]:=12; v[2]:=13; v[3]:=30; v[4]:=31; v[5]:=48;
          // Dimensionar e inicializar matriz 5x10
          SetLength(M, 5, 10);
          SetLength(L,100);
          vecinos;
    
    
    end;

    Comentario


    • #17
      Re: ¿Cómo se podría crear un algoritmo/programa para esta aplicación?

      En este momento no te puedo responder apropiadamente pues estoy sin internet (le he quitado prestado el teléfono a mi hija para usar su conexión y no me puedo tardar mucho). Aunque no conozco Delphi, el código es suficientemente parecido como para darme cuenta de que tu rutina [FONT=courier new]GenerarLista[/FONT] no hará nada útil, pues la llamas cuando no deberías hacerlo. En mi programa hay dos instrucciones if que en forma lógica son una sola pregunta... la escribí dividida para no hacer la pregunta muy larga. La primera instrucción if, que es la que tu escribiste en tu rutina, esencialmente ordena a mi programa ejecutar inmediatamente el siguiente ciclo del for, saltándose la pregunta siguiente (que sería superflua); puedes simular lo mismo cambiando tu pregunta a [FONT=courier new]if (f<>fila) or (c<>columna) then[/FONT] y anidando el segundo if dentro del primero.

      Lo demás no lo puedo mirar por ahora, sorry. Saludos,

      Al
      Última edición por Al2000; 13/10/2013, 03:07:50. Motivo: Corregir error en el if sugerido
      Don't wrestle with a pig in the mud. You'll both get dirty, but the pig will enjoy it. - Parafraseando a George Bernard Shaw

      Comentario


      • #18
        Re: ¿Cómo se podría crear un algoritmo/programa para esta aplicación?

        Hola Al,
        Gracias por responder,
        precisamente ayer por la tarde le di otra vuelta al código y creo que ya funciona (al menos las pruebas que realicé), tiene una estructura parecida a la que tu has escrito aunque hay definidas algunas variables globales que tu utilizas como argumentos en las funciones. Delphi si permite modificar el valor de los argumentos anteponiendo el termino 'var' a la variable de la función.
        Este es el código del programa completo:

        Código:
        [FONT=Courier]unit fPrinc; [/FONT]
        
        [FONT=Courier]interface [/FONT]
        
        [FONT=Courier]uses [/FONT]
        [FONT=Courier]  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, [/FONT]
        [FONT=Courier]  Dialogs, StdCtrls; [/FONT]
        
        [FONT=Courier]type [/FONT]
        [FONT=Courier]  TMatriz = Array of Array of Integer; [/FONT]
        
        [FONT=Courier]  TForm1 = class(TForm) [/FONT]
        [FONT=Courier]    Button1: TButton; [/FONT]
        [FONT=Courier]    M1: TMemo; [/FONT]
        [FONT=Courier]    procedure Button1Click(Sender: TObject); [/FONT]
        [FONT=Courier]  private [/FONT]
        [FONT=Courier]    { Private declarations } [/FONT]
        [FONT=Courier]  public [/FONT]
        [FONT=Courier]    { Public declarations } [/FONT]
        [FONT=Courier]  Procedure Generar_Lista(var vM: TMatriz; var vL: Array of Integer; columna, fila: Integer; var nelem: Integer); [/FONT]
        [FONT=Courier]  Procedure Vecinos(var vM: TMatriz); [/FONT]
        [FONT=Courier]  Procedure ImprimirResultados(vL: Array of Integer); [/FONT]
        [FONT=Courier]end; [/FONT]
        
        [FONT=Courier]var [/FONT]
        [FONT=Courier]  Form1: TForm1; [/FONT]
        
        [FONT=Courier]  M: TMatriz; [/FONT]
        [FONT=Courier]  L: Array of Integer; [/FONT]
        [FONT=Courier]  nl: Integer; [/FONT]
        
        [FONT=Courier]implementation [/FONT]
        
        [FONT=Courier]{$R *.dfm} [/FONT]
        
        [FONT=Courier]procedure TForm1.Button1Click(Sender: TObject); [/FONT]
        [FONT=Courier]var [/FONT]
        [FONT=Courier]  i,j,c,f: Integer; [/FONT]
        [FONT=Courier]  vAux: String; [/FONT]
        [FONT=Courier]begin [/FONT]
        [FONT=Courier]    SetLength(M,5,10); [/FONT]
        [FONT=Courier]    SetLength(L,6); [/FONT]
        [FONT=Courier]   // Llenar matriz con valores de numeros a evaluar [/FONT]
        [FONT=Courier]   //   M[1,1]:=11; M[2,2]:=22; M[2,3]:=23; M[3,2]:=32; M[3,6]:=36; M[3,7]:=37; [/FONT]
        [FONT=Courier]   M[0,1]:=1;  M[0,2]:=2; M[1,0]:=10; M[2,4]:=24; M[2,5]:=25; M[4,2]:=42; [/FONT]
        [FONT=Courier]   Vecinos(M); [/FONT]
        [FONT=Courier]end; [/FONT]
        
        
        [FONT=Courier]Procedure TForm1.Vecinos(var vM: TMatriz); [/FONT]
        [FONT=Courier]var [/FONT]
        [FONT=Courier]  i,c,f: Integer; [/FONT]
        [FONT=Courier]  vAux: String; [/FONT]
        [FONT=Courier]begin [/FONT]
        [FONT=Courier]    for f := 0 to 9 do [/FONT]
        [FONT=Courier]     for c := 0 to 4 do [/FONT]
        [FONT=Courier]     begin [/FONT]
        [FONT=Courier]          if vM[c,f]<>0 then [/FONT]
        [FONT=Courier]          begin [/FONT]
        [FONT=Courier]            nl:=-1; // El array comienza en el 0 no en el 1 [/FONT]
        [FONT=Courier]            for i := 0 to high(L)do L[i]:=0; [/FONT]
        [FONT=Courier]            Generar_Lista(vM,L,c,f,nl); [/FONT]
        [FONT=Courier]            ImprimirResultados(L); [/FONT]
        [FONT=Courier]            Vecinos(M); [/FONT]
        [FONT=Courier]          end; [/FONT]
        [FONT=Courier]     end; [/FONT]
        [FONT=Courier]end; [/FONT]
        
        
        [FONT=Courier]Procedure TForm1.Generar_Lista(var vM: TMatriz; var vL: Array of integer; columna, fila: Integer; var nelem: Integer); [/FONT]
        [FONT=Courier]var [/FONT]
        [FONT=Courier]  c,f: Integer; [/FONT]
        [FONT=Courier]begin [/FONT]
        [FONT=Courier]     Inc(nelem); [/FONT]
        [FONT=Courier]     vL[nelem]:=vM[columna,fila]; [/FONT]
        [FONT=Courier]     vM[columna,fila]:=0; [/FONT]
        [FONT=Courier]     for f := fila-1 to fila + 1 do [/FONT]
        [FONT=Courier]     begin [/FONT]
        [FONT=Courier]        for c := columna -1 to columna + 1 do [/FONT]
        [FONT=Courier]            if ( (f>=0) and (f<=9) ) and ( (c>=0) and (c<=4)) and (vM[c,f]<>0) then [/FONT]
        [FONT=Courier]              Generar_Lista(vM,vL,c,f,nelem); [/FONT]
        [FONT=Courier]     end; [/FONT]
        [FONT=Courier]end; [/FONT]
        
        [FONT=Courier]Procedure TForm1.ImprimirResultados(vL: Array of integer); [/FONT]
        [FONT=Courier]var [/FONT]
        [FONT=Courier]  i:Integer; [/FONT]
        [FONT=Courier]  vAux: String; [/FONT]
        [FONT=Courier]begin [/FONT]
        [FONT=Courier]   vAux:=''; [/FONT]
        [FONT=Courier]   for i := 0 to high(L) do [/FONT]
        [FONT=Courier]       vAux:=vAux+IntToStr(vL[i])+','; [/FONT]
        [FONT=Courier]   M1.lines.add(vAux); [/FONT]
        [FONT=Courier]end; [/FONT]
        
        [FONT=Courier]end.[/FONT]
        Última edición por paquechu; 13/10/2013, 04:39:41.

        Comentario

        Contenido relacionado

        Colapsar

        Trabajando...
        X