2016年4月16日 星期六

函數(_Decimal2Binary):十進位轉二進位


緣起於某位參加我課程的同學來信問我的問題:要如何以最佳化的方式測試各種不同出場方法的組合可能?(實際內容就不在這邊贅述了)。一開始,我們用了 Switch... case 的方式去做,透過 case 的數值來做最佳化,以最佳化的方式去做,是為了大量測試。但這只能得擇一的測試結果。於是,我想到了可以用二進位的方式來做!

我們可以指定一個參數值,用這個參數值去跑最佳化,但把參數值轉換成二進位表示,然後以二進位表示中,逐位數的 0 與 1 作為待測試出場方法的...開關。這樣做,就可以大量測試各種你想得到的出場方法去做組合,甚至把各種出場方法內使用不同的參數一併做測試了。於是,我們就需要一個把十進位轉成二進位的函數了。



自己做一個函數( _Decimal2Binary ),傳回文字類型。至於函數程式碼我就不解釋,請自行研究。網路上也能輕易的 Google 到這樣的演算法。本函數的第一個參數是十進位數值的輸入,第二個參數是轉換後輸出的總位數(前面補0)。
input: DecimalNumber(Numeric), outputDigits(Numeric);
array: quotinet[](0), remainder[](0);
var: j(0), bits(0), content(""), fillZero("");


if DecimalNumber>1 then begin

  for j= 1 to 5000 begin

    array_setmaxindex(quotinet, j+1);
    array_setmaxindex(remainder, j+1);
    
    if j=1 then
      quotinet[1]= floor(DecimalNumber / 2)
    else  
      quotinet[j]= floor(quotinet[j-1] / 2);

    if j=1 then
      remainder[1]= Mod(DecimalNumber, 2)
    else
      remainder[j]= Mod(quotinet[j-1], 2);

    bits= j;  
    if quotinet[j]<2 then break;

  end;

  content="";
  for j= 1 to bits begin
    content= NumToStr( remainder[j], 0) + content;
  end;

end;  


fillZero="";
for j= 1 to outputDigits-StrLen(content)-1 begin
  fillZero= fillZero+"0";
end; 


if DecimalNumber>1 then
  _Decimal2Binary= fillZero + "1" + content
else
  _Decimal2Binary= fillZero + NumToStr( DecimalNumber, 0);


讓我們來測試一下這個函數的效果:


至於,怎麼用這個東西去建立大量測試多種出場"方法"的組合?等待後篇吧 ^_^。另外,用來測試出場方法,可不可以用來測試進場方法,甚至利用進場方法的"組合"?請看:http://www.yctseng.net/2016/04/blog-post_24.html

熱門文章