[晒代码] 一个实际场景,欢迎各位晒下各种语言的实现~ - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
请不要在回答技术问题时复制粘贴 AI 生成的内容
paulguo

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

  •  
  •   paulguo 2012 年 10 月 20 日 9304 次点击
    这是一个创建于 4935 天前的主题,其中的信息可能已经有所发展或是发生改变。
    假设一个场景:

    有如下结构的一个数组

    [
    {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 日
    python:

    ls.sort(lambda x,y:cmp(x["a"]*10+x["b"],y["a"]*10+y["b"]))
    paulguo
        2
    paulguo  
    OP
       2012 年 10 月 20 日   1
    Javascript:

    arr.sort(function(x,y){return y.a-x.a||x.b-y.b});
    fwee
        3
    fwee  
       2012 年 10 月 20 日
    a.sort{|a,b|r = b[:a] <=> a[:a]; r == 0 ? (a[:b] <=> b[:b]) : r}

    顺便说下1L算法错了
    ipconfiger
        4
    ipconfiger  
       2012 年 10 月 20 日
    @fwee 哟西,没看到B生序
    paulguo
        5
    paulguo  
    OP
       2012 年 10 月 20 日   1
    1L 的确不对,LS什么语言?
    fwee
        6
    fwee  
       2012 年 10 月 20 日
    3# Ruby 忘说了
    clowwindy
        7
    clowwindy  
       2012 年 10 月 20 日   3
    coffee

    arr.sort (x, y) -> y.a - x.a || x.b - y.b
    imcotton
        8
    imcotton  
       2012 年 10 月 20 日
    ActionScript 3

    arr.sortOn(["a", "b"], [Array.NUMERIC | Array.DESCENDING, Array.NUMERIC])
    binux
        9
    binux  
       2012 年 10 月 20 日   5
    python:
    sorted(the_list, key=lambda x: (x['a'], -x['b']))
    mckelvin
        10
    mckelvin  
       2012 年 10 月 21 日
    ls真乃神人也
    fwee
        11
    fwee  
       2012 年 10 月 21 日   1
    ruby

    a.sort_by{|i| [-i[:a],i[:b]]}
    这是最短的了吧
    Keinez
        12
    Keinez   2012 年 10 月 21 日
    9楼和11楼好棒!(咱外行居然也看懂了QAQ)
    darkfall
        13
    darkfall  
       2012 年 10 月 21 日   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  
    PRO
       2012 年 10 月 21 日
    追求短小的话,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 日
    喜欢CoffeeScript,多易读啊
    liuxurong
        16
    liuxurong  
       2012 年 10 月 21 日
    喜欢Python,多易读啊
    insub
        17
    insub  
       2012 年 10 月 21 日
    喜欢ruby,最易读了啊..........
    alsotang
        18
    alsotang  
       2012 年 10 月 21 日
    CoffeeScript +1
    nowgoo
        19
    nowgoo  
       2012 年 10 月 21 日
    SQL:

    SELECT a, b FROM t ORDER BY a DESC, b ASC;
    blacktulip
        20
    blacktulip  
       2012 年 10 月 21 日
    看了半天还是SQL最易读,一看就懂
    haxe
        21
    haxe  
       2012 年 10 月 22 日
    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 日   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 日
    @binux
    写反了吧
    sorted(the_list, key=lambda x: (-x['a'], x['b']))
    cloudream
        24
    cloudream  
       2012 年 10 月 22 日
    list.sortBy( x => ( -x("a"), x("b") ) )

    Scala
    dndx
        25
    dndx  
       2012 年 10 月 22 日
    C版本,也就20来行。
    http://gist.github.com/3929214
    chisj
        26
    chisj  
       2012 年 10 月 23 日
    http://gist.github.com/3929214

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

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

    <script src="https://gist.github.com/3976878.js"> </script>
    ylem
        33
    ylem  
       2012 年 10 月 30 日
    呃。。。不太会用gist。。。直接靠代码:

    NSArray *arr = [SArray 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 日
    另,回复怎么插入html代码?
    ylem
        35
    ylem  
       2012 年 10 月 30 日
    不好意思啊各位,呵呵,我再回复下,试试帖个代码。

    https://gist.github.com/3976878
    ylem
        36
    ylem  
       2012 年 10 月 30 日
    。。。。。
    ylem
        37
    ylem  
       2012 年 10 月 30 日
    我错了,再原谅我一次。。。

    https://gist.github.com/3976878.js
    ylem
        38
    ylem  
       2012 年 10 月 30 日
    好吧。。大家继续。。。
    lwjefSub
        39
    lwjefSub  
       2012 年 10 月 30 日
    lwjefSub
        40
    lwjefSub  
       2012 年 10 月 30 日
    去掉s
    ylem
        41
    ylem  
       2012 年 10 月 30 日
    谢谢ls的。。。我试下

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

    sort -k2nr -k4n
    egen
        44
    egen  
       2012 年 10 月 30 日
    目测最易懂的是sql,最糟糕的是objc
    andy12530
        45
    andy12530  
       2012 年 10 月 30 日
    2L用原生函数,壮载我大JS
    infinte
        46
    infinte  
       2012 年 10 月 30 日
    moescript

    list.soty (x, y) => (x.a - y.a) or (x.b - y.b)
    infinte
        47
    infinte  
       2012 年 10 月 30 日
    抱歉错个字……
    jiyinyiyong
        48
    jiyinyiyong  
       2012 年 10 月 30 日
    `a` 赋值了那个数组的话:

    ```livescript
    a |> (.sort -> &0.b - &1.b) |> (.sort -> &1.a - &0.a) |> console.log
    ```
    Cwind
        49
    Cwind  
       2012 年 10 月 30 日
    objc声明array用新语法可以简洁点:
    NSArray *array = @[@{@"a":@5,@"b":@5},@{@"a":@6,@"b":@2},...];
    moonranger
        50
    moonranger  
       2012 年 10 月 30 日
    来个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 日
    P.S. 向所有Java程序员推荐Clojure
    powerx1202
        52
    powerx1202  
       2012 年 10 月 31 日
    在学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 月 1 日
    @powerx1202

    那我也写个……

    sortThat = sortBy $ ((flip compare) `on` (! "a")) `mappend` (compare `on` (! "b"))
    powerx1202
        54
    powerx1202  
       2012 年 11 月 1 日
    @levn 哈,诱出高手了,我才刚看到monoid。。
    hpyhacking
        55
    hpyhacking  
       2012 年 11 月 1 日
    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 月 1 日
    没人用 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 月 1 日
    我去,缩进被吃了
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     947 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 121ms UTC 22:57 PVG 06:57 LAX 15:57 JFK 18:57
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86