2010年2月20日 星期六

程式設計(Delphi) - 英文單字重新排列 (Mix-up Vocabulary)

因為兒子的寒假作業, 有一大題是英文單字的重組, 範圍是他上一學期的英文課本內的單字, 有點簡單的單字很容易就猜出來, 但是一些比較少用到的單字, 真的是想破頭也不知道, 課本又有上百頁的內容, 翻到呆掉. 所以寫了一個小程式, 可以重新列單字的字母順序, 這樣看到眼熟的拼法就可以比較快的找的答案. 未來要改善的話, 應再搭配英文字期進行查表, 可以更有效率. 不過這是應急用的程式, 先將就一下吧.

程式碼如下:





unit UMain;

interface

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

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    MemoResult: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  sl : TStringList ;  // 存放可能的排列方式
  iTotal : integer ;  // 排列方式的計數器

// 使用 rescursive 進行排列, 不要輸入長度超過 8 的字串, 8!=40320種排列已經看呆了
// 傳入值: p: 尚未使用的字串, q:準備輸出的已排列字串
procedure remap(p, q : string) ;
var
  i, iLen : integer ;
begin
  if p='' then
    begin
    sl.Add(q) ;
    inc(iTotal) ;
    end ;

  iLen:=length(p) ;
  for i:= 1 to iLen do
    remap(copy(p,1,i-1)+copy(p,i+1,iLen-i), q+copy(p,i,1)) ;
end ;

procedure TForm1.Button1Click(Sender: TObject);
begin
  // 初始化
  sl:=TStringList.Create ;
  iTotal:=0 ;
  memoResult.Lines.Clear ;
  
  // 要重組的字串放在 edit1.text 中傳入
  remap(Edit1.Text,'') ;
  
  // 顯示可能的排列方式個數
  caption:=inttostr(iTotal) ;
  
  // 列出所有的排列方式
  memoResult.Lines.AddStrings(sl);
  
  // free memory
  sl.free ;
end;

end.





沒有留言:

張貼留言