廢人廢語

點一下上面的發言可能有驚喜?

Wednesday, November 30, 2011

Programming 小筆記

小知識
關於整數 (http://en.wikipedia.org/wiki/Integer_(computer_science))

32bit
signed -21xxxxxxxx - 21xxxxxxxx (10 digits)
unsigned  0 - 4xxxxxxxxx (10 digits)

64bit
signed: -92xxxx - 92xxxx (19 digits)
unsigned: 0 - 18xxxxxx ... (20 digits)

http://en.wikipedia.org/wiki/Factorial
The values 12! and 20! are the largest factorials that can be stored in, respectively, the 32 bit and 64 bit integers commonly used in personal computers.

12 ! = 479 001 600
13 ! = 6 227 020 800 ←OUT 32bit
20 ! = 2 432 902 008 176 640 000

C
沒Passing reference, 這是C++的
void function(int& a)

Pass struct as parameter
小心它會pass-by-value
這時發現C++真好...

%這個 operator ....
-5 % 8 會給你 -5 而不是3,小心
因為這東西我花了2個小時...



C++
沒static class
近似的為 namespace

Java
5 % 3 = 2
-5 % 3 = -2
5 % -3 = 2
-5 % -3 = -2
全部取決於被除數

StringBuilder not thread-safe
StringBuffer thread-safe

static methods overriding - 小心會出事
說明的例子
BaseClass SubClass 都有 getStaticLongId() (static method) 和 getInstanceLongId()
BaseClass 還有getStaticStringId() getInstanceStringId() (上面的long的 toString() )

之後在Main內
SubClass subClassInstance = new SubClass();  定義了一個 SubClass 的 Object
但叫出 SubClass.getStaticStringId() 時卻叫出了 BaseClass的 getStaticLongId() 的 toString() 而不是已"Override"掉的 SubClass的 getStaticLongId()
Compiler 不知會不會警告

討論串說明的原因: This is because static methods are not virtual.
Java 全部 method 都是默認 virtual , 除了 static 和 final 的
找到這串的原因是想寫一個 IEnDecryptor , 它是一個 interface , 有 encrypt() 和 decrypt() 兩個"static" method
可惜的是 interface method 不允許 static (默認為 public , static) , 結果就變成一個只有 encrypt() 和 decrypt() 的 interface class
但寫 subClass時 (AES, ShiftCipher類的東東) , 該些 method 不能加上 static
看來唯一可行的方法是放棄 interface , 直接造一個 EnDecryptor 的 package, 裏面放各種 AES, DES, ShiftCipher, MD5, SHA-1 ... 等的 class

Javascript
-5 % 3 = -2
餘數的處理和 Java一樣

single thread
沒有sleep() 和wait(), 所以要用 Handler, setTimeout() , clearTimeout()
在loop中用 timeOut要小心, 例如 for loop 中 5,4,3,2,1 地減去i , 每次也去 setTimeout() 去 alert(i)
結果會看到5個0, 因為發動 event時只會讀當時的 i 的值

自己的做法
var sec = 10000 / 1000; 
(function countdown()
{
timerEvent = setTimeout(function() 
{
  if (sec > 0 )
  {
  --sec;
document.getElementById('counter').innerText = sec ;
countdown() ;

  }
}, 1000 );
}
)();

每1秒才叫一次 countdown(), 每次 countdown() 才減掉 sec , 而 countdown() 完結時會叫回自己, 用一個 if 去停止

另一類似的function

function startPlaySound(level)
{
var levelCounter = 0;
(function playSound() 
{
setTimeout(function() 
{
if (levelCounter < answer[level].length) 
{
var wavSrc = answer[level][levelCounter];

var player = document.getElementById('player');
player.src = wavSrc;
player.play();

++levelCounter;

playSound();
}
}, SOUNDINTERVAL );
}
)();

}

跟之前的例子差不多, 都是叫回自己叫不斷增加 levelCounter , 留意的是 wavSrc 每 loop 一次也會造出新的 wavSrc , setTimeout 時不用擔心指向同一 variable 的問題

No comments:

Post a Comment