Ver Mensaje Individual
  #5  
Antiguo 15-12-2011
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Reputación: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Y bueno, tengo algo de tiempo libre, a ver si jala esto:

Código Delphi [-]
type
  TMatriz = array of array of Integer;

function CuadradoMagico(N: Integer): TMatriz;
var
  D, I, J: Integer;

begin
  // Nos aseguramos que N sea impar
  if not Odd(N)then
    raise Exception.CreateFmt('%d no es un número impar', [N]);

  // Fijamos la dimensión de la matriz
  SetLength(Result, N, N);

  // Limpiamos la matriz
  for I := 0 to N - 1 do
    for J := 0 to N - 1 do
      Result[I, J] := 0;

  // Posición inicial
  I := 0; J := (N - 1) div 2;

  for D := 1 to N*N do
  begin
    Result[I, J] := D;

    // Si la casilla de arriba a la derecha ya está ocupada, bajamos de fila
    if Result[(((I - 1) mod N) + N) mod N, (J + 1) mod N] <> 0 then
      Inc(I)
    else
    // Vamos a la casilla de arriba a la derecha. Si nos salimos del cuadrado
    // entonces nos colocamos en el extremo opuesto
    begin
      I := (((I - 1) mod N) + N) mod N;
      J := (J + 1) mod N;
    end;
  end;
end;

Ejemplo de uso, usando un StringGrid para mostrar los resultados:

Código Delphi [-]
var
  N, I, J: Integer;
  M: TMatriz;

begin
  N := StrToIntDef(Edit1.Text, 3);
  M := CuadradoMagico(N);

  StringGrid1.RowCount := N;
  StringGrid1.ColCount := N;

  for I := 0 to N - 1 do
    for J := 0 to N - 1 do
      StringGrid1.Cells[J, I] := IntToStr(M[I, J]);
end;

// Saludos

Última edición por roman fecha: 15-12-2011 a las 23:03:56.
Responder Con Cita