• 请不要在回答技术问题时复制粘贴 AI 生成的内容
paulguo
V2EX  ›  程序员

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

  •  
  •   paulguo · Oct 20, 2012 · 9942 views
    This topic created in 5126 days ago, the information mentioned may be changed or developed.
    假设一个场景:

    有如下结构的一个数组

    [
    {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 replies  •  1970-01-01 08:00:00 +08:00
    ipconfiger
    ipconfiger
    Oct 20, 2012
    1
    python:

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

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

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

    arr.sort (x, y) -> y.a - x.a || x.b - y.b
    imcotton
    imcotton
    Oct 20, 2012
    8
    ActionScript 3

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

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

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

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

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

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

    <script src="https://gist.github.com/3976878.js"> </script>
    ylem
    ylem
    Oct 30, 2012
    33
    呃。。。不太会用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
    ylem
    Oct 30, 2012
    34
    另,回复怎么插入html代码?
    ylem
    ylem
    Oct 30, 2012
    35
    不好意思啊各位,呵呵,我再回复下,试试帖个代码。

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

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

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

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

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

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

    那我也写个……

    sortThat = sortBy $ ((flip compare) `on` (! "a")) `mappend` (compare `on` (! "b"))
    powerx1202
    powerx1202
    Nov 1, 2012
    54
    @levn 哈,诱出高手了,我才刚看到monoid。。
    hpyhacking
    hpyhacking
    Nov 1, 2012
    55
    compare({_A, B1}, {_A, B2}) -> B2 > B1;
    compare({A1, _B1}, {A2, _B2}) -> A1 > A2.

    lists:sort(fun compare/2, List).
    silverbullettt
    silverbullettt
    Nov 1, 2012
    56
    没人用 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
    silverbullettt
    Nov 1, 2012
    57
    我去,缩进被吃了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3173 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 138ms · UTC 11:12 · PVG 19:12 · LAX 03:12 · JFK 06:12
    ♥ Do have faith in what you're doing.