V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
paulguo
V2EX  ›  程序员

[晒代码] 一个实际场景,欢迎各位晒下各种语言的实现~

  •  
  •   paulguo · 2012-10-20 20:03:45 +08:00 · 8170 次点击
    这是一个创建于 4206 天前的主题,其中的信息可能已经有所发展或是发生改变。
    假设一个场景:

    有如下结构的一个数组

    [
    {a: 5, b: 5},
    {a: 6, b: 2},
    {a: 2, b: 7},
    {a: 5, b: 2},
    {a: 1, b: 0},
    {a: 5, b: 1},
    {a: 6, b: 1},
    {a: 2, b: 9}
    ]

    要求按照a的降序优先排列,a相同的情况下,按照b的升序排列。

    排序后的结果应当如下:

    [
    {"a": 6,"b": 1},
    {"a": 6,"b": 2},
    {"a": 5,"b": 1},
    {"a": 5,"b": 2},
    {"a": 5,"b": 5},
    {"a": 2,"b": 7},
    {"a": 2,"b": 9},
    {"a": 1,"b": 0}
    ]
    57 条回复    1970-01-01 08:00:00 +08:00
    ipconfiger
        1
    ipconfiger  
       2012-10-20 20:14:27 +08:00
    python:

    ls.sort(lambda x,y:cmp(x["a"]*10+x["b"],y["a"]*10+y["b"]))
    paulguo
        2
    paulguo  
    OP
       2012-10-20 20:15:42 +08:00   ❤️ 1
    javascript:

    arr.sort(function(x,y){return y.a-x.a||x.b-y.b});
    fwee
        3
    fwee  
       2012-10-20 20:16:37 +08:00
    a.sort{|a,b|r = b[:a] <=> a[:a]; r == 0 ? (a[:b] <=> b[:b]) : r}

    顺便说下1L算法错了
    ipconfiger
        4
    ipconfiger  
       2012-10-20 20:23:08 +08:00
    @fwee 哟西,没看到B生序
    paulguo
        5
    paulguo  
    OP
       2012-10-20 20:23:09 +08:00   ❤️ 1
    1L 的确不对,LS什么语言?
    fwee
        6
    fwee  
       2012-10-20 20:24:37 +08:00
    3# Ruby 忘说了
    clowwindy
        7
    clowwindy  
       2012-10-20 20:31:29 +08:00   ❤️ 3
    coffee

    arr.sort (x, y) -> y.a - x.a || x.b - y.b
    imcotton
        8
    imcotton  
       2012-10-20 20:47:17 +08:00
    ActionScript 3

    arr.sortOn(["a", "b"], [Array.NUMERIC | Array.DESCENDING, Array.NUMERIC])
    binux
        9
    binux  
       2012-10-20 20:49:00 +08:00   ❤️ 5
    python:
    sorted(the_list, key=lambda x: (x['a'], -x['b']))
    mckelvin
        10
    mckelvin  
       2012-10-21 09:49:41 +08:00
    ls真乃神人也
    fwee
        11
    fwee  
       2012-10-21 10:19:16 +08:00   ❤️ 1
    ruby

    a.sort_by{|i| [-i[:a],i[:b]]}
    这是最短的了吧
    Keinez
        12
    Keinez  
       2012-10-21 10:35:09 +08:00
    9楼和11楼好棒!(咱外行居然也看懂了QAQ)
    darkfall
        13
    darkfall  
       2012-10-21 12:19:11 +08:00   ❤️ 2
    C++11
    std::sort(arr.begin(), arr.end(), [](Dict& a, Dict& b) -> bool {
    return (a['a'] == b['a']) ? (a['b'] < b['b']) : (a['a'] > b['a']);
    });
    shiny
        14
    shiny  
       2012-10-21 13:31:38 +08:00
    追求短小的话,PHP 可以是:
    usort($items,function($a, $b){
    return $a['a']==$b['a'] ? bccomp($a['b'],$b['b']) : bccomp($b['a'],$a['a']);
    });

    但是后面谁来维护这程序可能会骂了……
    所以正常项目中我会这么写:

    //兼容个别未开启 bcmath 的环境
    if(!function_exists('bccomp')){
    function bccomp($a,$b){
    if($a==$b){
    return 0;
    } else if($a>$b){
    return 1;
    } else {
    return -1;
    }
    }
    }
    function sort_items($a, $b){
    if($b['a']==$a['a']){
    return bccomp($a['b'],$b['b']);
    } else {
    return bccomp($b['a'],$a['a']);
    }
    }
    luin
        15
    luin  
       2012-10-21 13:38:58 +08:00
    喜欢CoffeeScript,多易读啊
    liuxurong
        16
    liuxurong  
       2012-10-21 15:20:06 +08:00
    喜欢Python,多易读啊
    insub
        17
    insub  
       2012-10-21 22:07:21 +08:00
    喜欢ruby,最易读了啊..........
    alsotang
        18
    alsotang  
       2012-10-21 23:06:24 +08:00
    CoffeeScript +1
    nowgoo
        19
    nowgoo  
       2012-10-21 23:30:03 +08:00
    SQL:

    SELECT a, b FROM t ORDER BY a DESC, b ASC;
    blacktulip
        20
    blacktulip  
       2012-10-21 23:53:06 +08:00
    看了半天还是SQL最易读,一看就懂
    haxe
        21
    haxe  
       2012-10-22 00:20:26 +08:00
    haxe语言实现...权当抛砖引玉,因为本语言排序上没有上面那么强大的原生api,所以手写一个比较函数。为了性能上考虑避免运行时类型检查,定义了这个数组中元素的结构体A,顺便还提供了代码提示功能为维护提供了便利。

    typedef A = {
    var a : Int;
    var b : Int;
    }
    //代码实现
    var arr = [ // type inference
    {a: 5, b: 5},
    {a: 6, b: 2},
    {a: 2, b: 7},
    {a: 5, b: 2},
    {a: 1, b: 0},
    {a: 5, b: 1},
    {a: 6, b: 1},
    {a: 2, b: 9}
    ];
    arr.sort( function( x:A , y:A ):Int
    {
    if ( x.a > y.a )
    return -1;
    else if ( x.a == y.a )
    if ( x.b > y.b)
    return 1;
    else if ( x.b == y.b )
    return 0;
    else
    return -1;
    else
    return 1;
    } );
    clowwindy
        22
    clowwindy  
       2012-10-22 00:22:22 +08:00   ❤️ 1
    既然出现了 SQL,那我贴两个有意思的:

    C#
    var result = list.OrderByDescending(x => x["a"]).ThenBy(x => x["b"]);

    C# with Linq
    var result = from i in list orderby i["a"] descending, i["b"] select i;


    C# 这么有趣的语法特性可惜被微软给糟蹋了。
    zz1956
        23
    zz1956  
       2012-10-22 00:36:25 +08:00
    @binux
    写反了吧
    sorted(the_list, key=lambda x: (-x['a'], x['b']))
    cloudream
        24
    cloudream  
       2012-10-22 03:42:21 +08:00
    list.sortBy( x => ( -x("a"), x("b") ) )

    Scala
    dndx
        25
    dndx  
       2012-10-22 09:45:49 +08:00
    C版本,也就20来行。
    http://gist.github.com/3929214
    chisj
        26
    chisj  
       2012-10-23 10:01:17 +08:00
    http://gist.github.com/3929214

    Object-c 除掉测试用例也就七行。
    chisj
        27
    chisj  
       2012-10-23 10:03:21 +08:00   ❤️ 1
    对不起,请无视上一条回复,第一次用Gist太兴奋复制错了。
    http://gist.github.com/3936202
    tioover
        28
    tioover  
       2012-10-23 10:09:11 +08:00
    壮哉我大Python
    jesse0628
        29
    jesse0628  
       2012-10-29 17:26:39 +08:00
    来一段common lisp吧~

    (sort lst #'> :key #'(lambda (x) (+ (* 10 (getf x :a)) (- 9 (getf x :b)))))
    yinsigan
        30
    yinsigan  
       2012-10-29 17:41:20 +08:00
    @chisj OMG,object-c要打那么多单词,吓死人啊
    ylem
        31
    ylem  
       2012-10-30 06:09:38 +08:00
    @yinsigan 不不,object-c 不吓人,那个只是声明一个array而已。
    ylem
        32
    ylem  
       2012-10-30 06:11:36 +08:00
    @chisj 另外,用两个NSSortDescriptor就可以了。

    <script src="https://gist.github.com/3976878.js"> </script>
    ylem
        33
    ylem  
       2012-10-30 06:12:25 +08:00
    呃。。。不太会用gist。。。直接靠代码:

    NSArray *arr = [NSArray arrayWithObjects:
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:5], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"a", [NSNumber numberWithInt:2], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"a", [NSNumber numberWithInt:7], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:2], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"a", [NSNumber numberWithInt:0], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:1], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"a", [NSNumber numberWithInt:1], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"a", [NSNumber numberWithInt:9], @"b",nil],
    nil];




    NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:@"a" ascending:NO];
    NSSortDescriptor *hireDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"b" ascending:YES];
    NSArray *sortDescriptors = @[ageDescriptor, hireDateDescriptor];
    NSArray *sortedArray = [arr sortedArrayUsingDescriptors:sortDescriptors];

    NSLog(@"after sort the arr is:%@", sortedArray);
    ylem
        34
    ylem  
       2012-10-30 06:29:56 +08:00
    另,回复怎么插入html代码?
    ylem
        35
    ylem  
       2012-10-30 06:33:30 +08:00
    不好意思啊各位,呵呵,我再回复下,试试帖个代码。

    https://gist.github.com/3976878
    ylem
        36
    ylem  
       2012-10-30 06:33:52 +08:00
    。。。。。
    ylem
        37
    ylem  
       2012-10-30 06:35:19 +08:00
    我错了,再原谅我一次。。。

    https://gist.github.com/3976878.js
    ylem
        38
    ylem  
       2012-10-30 06:40:57 +08:00
    好吧。。大家继续。。。
    lwjefSub
        39
    lwjefSub  
       2012-10-30 06:56:41 +08:00
    lwjefSub
        40
    lwjefSub  
       2012-10-30 06:56:58 +08:00
    去掉s
    ylem
        41
    ylem  
       2012-10-30 07:22:11 +08:00
    谢谢ls的。。。我试下

    http://gist.github.com/3976878
    chisj
        42
    chisj  
       2012-10-30 12:28:24 +08:00
    @yinsigan 是的,那个block就是算法,单词确实要打很多,所以不可能用vim之类编辑器来写代码,用xcode的话会有很好的代码提醒,但是函数名不适合记忆。
    当然有时候选择少了也是一种幸福啊。
    plprapper
        43
    plprapper  
       2012-10-30 17:46:08 +08:00
    shell

    sort -k2nr -k4n
    egen
        44
    egen  
       2012-10-30 18:34:30 +08:00
    目测最易懂的是sql,最糟糕的是objc
    andy12530
        45
    andy12530  
       2012-10-30 19:08:34 +08:00
    2L用原生函数,壮载我大JS
    infinte
        46
    infinte  
       2012-10-30 19:37:08 +08:00
    moescript

    list.soty (x, y) => (x.a - y.a) or (x.b - y.b)
    infinte
        47
    infinte  
       2012-10-30 19:37:24 +08:00
    抱歉错个字……
    jiyinyiyong
        48
    jiyinyiyong  
       2012-10-30 19:40:11 +08:00
    `a` 赋值了那个数组的话:

    ```livescript
    a |> (.sort -> &0.b - &1.b) |> (.sort -> &1.a - &0.a) |> console.log
    ```
    Cwind
        49
    Cwind  
       2012-10-30 19:47:32 +08:00
    objc声明array用新语法可以简洁点:
    NSArray *array = @[@{@"a":@5,@"b":@5},@{@"a":@6,@"b":@2},...];
    moonranger
        50
    moonranger  
       2012-10-30 21:24:06 +08:00
    来个Clojure版:

    (def data
    [{:a 5 :b 5}
    {:a 6 :b 2}
    {:a 2 :b 7}
    {:a 5 :b 2}
    {:a 1 :b 0}
    {:a 5 :b 1}
    {:a 6 :b 1}
    {:a 2 :b 9}])

    (println (sort-by #(+ (* -10 (:a %)) (:b %)) data))
    moonranger
        51
    moonranger  
       2012-10-30 21:25:47 +08:00
    P.S. 向所有Java程序员推荐Clojure
    powerx1202
        52
    powerx1202  
       2012-10-31 23:59:25 +08:00
    在学haskell,写个naive的。。
    List.sortBy (\x y -> let xa = fromJust $ Map.lookup 'a' x; xb = fromJust $ Map.lookup 'b' x; ya = fromJust $ Map.lookup 'a' y; yb = fromJust $ Map.lookup 'b' y in if xa == ya then xb `compare` yb else ya `compare` xa) ar
    levn
        53
    levn  
       2012-11-01 08:21:04 +08:00
    @powerx1202

    那我也写个……

    sortThat = sortBy $ ((flip compare) `on` (! "a")) `mappend` (compare `on` (! "b"))
    powerx1202
        54
    powerx1202  
       2012-11-01 20:35:37 +08:00
    @levn 哈,诱出高手了,我才刚看到monoid。。
    hpyhacking
        55
    hpyhacking  
       2012-11-01 22:09:22 +08:00
    compare({_A, B1}, {_A, B2}) -> B2 > B1;
    compare({A1, _B1}, {A2, _B2}) -> A1 > A2.

    lists:sort(fun compare/2, List).
    silverbullettt
        56
    silverbullettt  
       2012-11-01 22:30:02 +08:00
    没人用 Scheme?

    (define lst (list (s 5 5) (s 6 2)
    (s 2 7) (s 5 2) (s 1 0)
    (s 5 1) (s 6 1) (s 2 9)))

    (define-struct s (a b))

    (sort lst
    (lambda (x y)
    (if (= (s-a x) (s-a y))
    (< (s-b x) (s-b y))
    (> (s-a x) (s-a y))))))

    其实这是 Racket~
    silverbullettt
        57
    silverbullettt  
       2012-11-01 22:30:51 +08:00
    我去,缩进被吃了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2979 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 13:35 · PVG 21:35 · LAX 06:35 · JFK 09:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.