Speaking of sorting, it is in numerical order and dictionary order, but I investigated other sorts.
Read @ jag_507's * Ruby learning with AtCoder 10 [1st algorithm practice test DoubleCamelCase Sort] * and * AtCoder 1st algorithm practice I tried F-DoubleCamelCase Sort *, but the sorting doesn't work.
sort.rb
a = ["FisH", "DoG", "CaT", "AA", "AaA", "AbC", "AC"]
a.sort
# => ["AA", "AC", "AaA", "AbC", "CaT", "DoG", "FisH"] #Actual return value
["AA", "AaA", "AbC", "AC", "CaT", "DoG", "FisH"] #Expected return value
This article: * [sort command, basics and applications and traps](https://qiita.com/richmikan@github/items/cc4494359b1ac2f72311#-f%E8%BE%9E%E6%9B%B8%E9%A0% 86% E3% 81% AB% E4% B8% A6% E3% 81% B9% E3% 82% 8B) * Is there a -f
option like ~~ Doraemon ~~ Help Google teacher.
Many programming languages, not just * Ruby *, sort by dictionary order
by ASCII code order, so uppercase and lowercase letters are younger.
Therefore, we need a case-insensitive sort.
Ruby
ruby.rb
a = ['a', 'b', 'c', 'd', 'e', 'A', 'B', 'C', 'D', 'E']
p a.sort
# => ["A", "B", "C", "D", "E", "a", "b", "c", "d", "e"]
p a
# => ["a", "b", "c", "d", "e", "A", "B", "C", "D", "E"]
p a.sort{|x, y| x.casecmp(y).nonzero? || x <=> y}
# => ["A", "a", "B", "b", "C", "c", "D", "d", "E", "e"]
p a.sort_by{ |s| [s.downcase, s] }
# => ["A", "a", "B", "b", "C", "c", "D", "d", "E", "e"]
sort_by
from the comment section.
Sorting is performed based on two conditions, the highest priority s.downcase
and the next priority s
.
Pythonpython.py
a = ['a', 'b', 'c', 'd', 'e', 'A', 'B', 'C', 'D', 'E']
print(sorted(a))
# => ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
print(a)
# => ['a', 'b', 'c', 'd', 'e', 'A', 'B', 'C', 'D', 'E']
print(sorted(sorted(a), key=str.lower))
# => ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e']
java.java
List<String> a = Arrays.asList("a", "b", "c", "d", "e", "A", "B", "C", "D", "E");
a.sort(Comparator.naturalOrder());
System.out.println(a); // [A, B, C, D, E, a, b, c, d, e]
a.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(a); // [A, a, B, b, C, c, D, d, E, e]
For *** Java ***, CASE_INSENSITIVE_ORDER
is prepared.
Referenced site
Recommended Posts