Thursday, February 21, 2013

Compress Int to BaseN encode / decode using LINQ

// This does not "pad" values
string Encode(long inp, IEnumerable<char> map) {
    Debug.Assert(inp >= 0, "not implemented for negative numbers");

    var b = map.Count();
    // value -> character
    var toChar = map.Select((v, i) => new {Value = v, Index = i}).ToDictionary(i => i.Index, i => i.Value);
    var res = "";
    if (inp == 0) {
      return "" + toChar[0];
    }
    while (inp > 0) {
      // encoded least-to-most significant
      var val = (int)(inp % b);
      inp = inp / b;
      res += toChar[val];
    }
    return res;
}

long Decode(string encoded, IEnumerable<char> map) {
    var b = map.Count();
    // character -> value
    var toVal = map.Select((v, i) => new {Value = v, Index = i}).ToDictionary(i => i.Value, i => i.Index);      
    long res = 0;
    // go in reverse to mirror encoding
    for (var i = encoded.Length - 1; i >= 0; i--) {
      var ch = encoded[i];
      var val = toVal[ch];
      res = (res * b) + val;
    }
    return res;
}

void Main()
{
    // for a 48-bit base, omits l/L, 1, i/I, o/O, 0
    var map = new char [] {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
        'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
        'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
        'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't',
        'u', 'v', 'x', 'y', 'z', '2', '3', '4',
    };
    var test = new long[] {0, 1, 9999999999, 4294965286, 2292964213, 1000000000};
    foreach (var t in test) {
        var encoded = Encode(t, map);
        var decoded = Decode(encoded, map);
        Console.WriteLine(string.Format("value: {0} encoded: {1}", t, encoded));
        if (t != decoded) {
            throw new Exception("failed for " + t);
        }
    }
}

Wednesday, February 2, 2011

C# Delegate 委派 使用方法

記住先 

http://rfid-fantasy.blogspot.com/2009/07/c-delegate.html


之前講到委派 (Delegate),當時不清楚做法。查了一些資料後,大概了解它是一個代理者的角色,代替你執行你要執行的方法。例如說你可以手動打開電視開關來收看電視,也可以利用電視遙控器 (代理者) 來幫你執行打開電視的工作。
Read more »

Thursday, December 9, 2010

Try order the text in int form in MSSQL

seems mssql does not have anything try catch situation
when we want to sort a string column containing integer / double

e.g.
If we sort, 1, 5, 23. it will becomes
1
23
5

however, we can perform that using Convert(column, int). But ..... if there is a row which is a non numeric integer, then a error will be happened....

Read more »

Labels:

Wednesday, December 8, 2010

ZPAD

因為ADSENSE 再一次REJECT 了REQUEST
所以良久沒有UPDATE 了

前幾日手痕買了ZPAD 同一個藍牙GPS
今朝醒來時, 突然間覺得 好唔抵,點解唔買IPAD .....


LOL .......

Sunday, November 21, 2010

Galaxy S capture Screen 方法 (Android)

在Galaxy S 度capture screen

按住BACK, 然後按HOME

就會有個toast box 寫住螢幕己擷取

然後在Internal SD -> Screen Capture 中找到的了

如果你不是 Galaxy S 用家, 而又用到, 請REPLY

Labels: , ,