【问题标题】:Does ballerina have support for sorting?芭蕾舞演员是否支持排序?
【发布时间】:2018-06-12 09:19:23
【问题描述】:

需要根据私有变量值对一些芭蕾舞演员对象数组进行排序。我们可以对芭蕾舞演员对象或原始类型数组进行排序吗?有什么功能可以做到吗?

【问题讨论】:

    标签: ballerina


    【解决方案1】:

    目前没有内置的方法可以对数组进行排序。您可以根据需要实现排序功能。

    在 github 中找到了一个可以重复使用的实现 - https://github.com/chamil321/ballerinaCentralWorkSpace/blob/master/sort/impl.bal。但它适用于整数。我认为它指的是https://central.ballerina.io/chamil/sort 包。你可以拉包试试看。

    【讨论】:

    【解决方案2】:

    Ballerina 现在似乎支持排序,但您必须完成所有繁重的工作。即使是简单的值类型。唉。

    不管怎样,这里是一个“按字母顺序排序”的尝试,它包含 json 元素的数组,每个元素都有一个 name 元素 - obvs 也适用于简单的整数或字符串,或者经过一些调整的 woreva:

    json items = [{ name: "aaa" }, { name: "aab" }];
    items.sort(sortItems)
    
    function sortItems(json a, json b) returns int {
        // extract character by character numeric representation of string
        int[] aname = a.name.toString().toCodePointInts();
        int[] bname = b.name.toString().toCodePointInts();
    
        // do character by character comparison
        int i = 0;
        while (i < aname.length() && i < bname.length()) {
            if (aname[i] < bname[i]) { return -1; }
            else if (aname[i] > bname[i]) { return 1; }
            i += 1;
        }
        // if all the characters in the shared length is the same
        // assume the shorter string should come first
        if (aname.length() < bname.length()) { return -1; }
        if (aname.length() > bname.length()) { return 1; }
    
        return 0;
    }
    

    很高兴得到纠正,并且有一种更简单的本地方式来做到这一点。 (数组初始化可能是错误的,没有测试那个位,soz。)

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-30
      • 1970-01-01
      • 2023-04-04
      • 2019-06-02
      • 1970-01-01
      相关资源
      最近更新 更多