Groovy排序彩虹的颜色

时间:2011-10-18 23:47:34

标签: sorting groovy

鉴于彩虹颜色的排序方式如下:ROYGBIV(R =红色,O =橙色,Y =黄色,G =绿色,B =蓝色,I =靛蓝色,V =紫色)我该怎么做?列表:

def partialUnorderedList =["orange", "blue", "red","green"] 

并将其分类为ROYGBIV顺序,结果为:

def  partialOrderedList = ["red", "orange", "green", "blue"]

4 个答案:

答案 0 :(得分:7)

以下是我对这个问题的看法:

def order = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
def input = ["orange", "blue", "red", "green"]

def sorted = input.sort { order.indexOf it }

它使用输入列表中给定元素的引用列表中的索引位置作为排序标准。

答案 1 :(得分:0)

以下是您问题的最简单解决方案:

def a =["red","orange","yellow","green","blue","indigo","violet"]
def input = ["orange", "blue", "red","green"]
list = []
for(i=0;i<input.size();i++)
{
   index =  a.findIndexValues{ it ==  input[i]}.join() as Integer
   list[index] =  input[i]
}
println list.minus(null)

输出:

[red, orange, green, blue]

对于其他输入:

[yellow, red, blue, orange, violet, indigo]

输出:

[red, orange, yellow, blue, indigo, violet]

在上面的代码中使用了findIndexValues

答案 2 :(得分:-1)

如果您不介意拉入另一个库,Google Guava API可能非常适合解决此问题。

def partialUnorderedList = ["orange", "blue", "red", "green"] 
Ordering roygbivOrdering = Ordering.explicit("red", "orange", "yellow", "green", "blue", "indigo", "violet")
def partialOrderedList = roygbivOrdering.sortedCopy(partialUnorderedList)

答案 3 :(得分:-1)

一个简单的解决方案是使用闭包进行比较,如下所示:

def partialUnorderedList =["orange", "blue", "red","green"]

def order = "roygbiv".inject([:]){ map, letter -> map[letter] = map.size(); map}
def sortedList = partialUnorderedList.sort{ a, b ->
    order[a[0].toLowerCase()] <=> order[b[0].toLowerCase()]
}

这将为颜色的第一个字母创建索引的哈希映射。然后排序方法查找第一个方法的索引,并对其进行比较。

这仅适用于您使用唯一的首字母。要对全名进行排序,您可以执行以下操作:

def partialUnorderedList =["orange", "blue", "red","green"]

def order = "red,orange,yellow,green,blue,indigo,violet".split(",").inject([:]){ map, name -> map[name] = map.size(); map}
def sortedList = partialUnorderedList.sort{ a, b ->
    order[a.toLowerCase()] <=> order[b.toLowerCase()]
}