表題のような関数をjavaで作成したいと考えています。
文字列xに対して降順となる数値もしくは文字列aを返す関数です。
f(x) = a
ただし、文字列xがx2>x1(x2.compareTo(x1)>0)のとき、aは降順、つまり、a2<a1となる数値か、もしくは、a2.compareTo(a1)<0となるような文字列を求めたいです。
例えば、以下になるような数値もしくは文字列を返す関数です。
f("1") = 10 だとすると、f("2") = 9
f("a") = 5 だとすると、f("b") = 4
右辺は順序が降順になっていれば自由な値で構いません。
これは、入力値を関数内でソートするようなものではなく、関数は複数回呼ばれますが、その値が結果的に降順になるというものです。
例えば、xがlongの最大値よりも小さい数字の場合、関数は以下のように書けます。
java.lang.Long.MAX_VALUE-Long.parseLong(x)
これを、xが文字列の場合でも求めたいのです。
そもそもの要件として、昇順しかソートできないKVSで降順を実現するために、降順用に項目を1つ追加し、降順の値を格納してそれをKVSの機能で昇順ソートすることで降順を実現したいというものです。
ヒントをもらって実装してみましたがダメでした。
java
1import java.util.ArrayList; 2import java.util.Collections; 3import java.util.Comparator; 4import java.util.HashMap; 5import java.util.List; 6import java.util.Map; 7import java.util.Map.Entry; 8 9public class DescTest { 10 11 public static void main(String[] args) { 12// String[] src = {"a", "b", "A", "abc", "def", "ab", "abcd", "あいうえお", "かきくけこ"}; 13 String[] src = {"a", "b", "c", "d", "e", "f", "g", "h", "i"}; 14 Map<Integer,String> dist = new HashMap<Integer,String>(); 15 16 for(int i=0;i<src.length;i++) { 17 dist.put(i, DescTest.decKey(src[i])); 18// dist.put(i, src[i]); 19 } 20 21 List<Map.Entry<Integer,String>> entries = 22 new ArrayList<Map.Entry<Integer,String>>(dist.entrySet()); 23 Collections.sort(entries, new Comparator<Map.Entry<Integer,String>>() { 24 25 @Override 26 public int compare( 27 Entry<Integer,String> entry1, Entry<Integer,String> entry2) { 28 return (entry1.getValue()).compareTo(entry2.getValue()); 29 } 30 }); 31 32 for (Entry<Integer,String> s : entries) { 33 System.out.println("s.getKey() : " + s.getKey()); 34 System.out.println("s.getValue() : " + src[s.getKey()]); 35 } 36 } 37 38 public static String decKey(String s) { 39 char[] c = s.toCharArray(); 40 int v = c[0]; 41// System.out.print("c="+v+" "); 42 for(int i = 0; i < c.length; i++) { 43 c[i] = (char)(65535 - c[i]); 44 } 45 return c.toString(); 46 } 47 48}
結果(降順にならない)
s.getValue() : b s.getKey() : 4 s.getValue() : e s.getKey() : 8 s.getValue() : i s.getKey() : 6 s.getValue() : g s.getKey() : 0 s.getValue() : a s.getKey() : 7 s.getValue() : h s.getKey() : 3 s.getValue() : d s.getKey() : 2 s.getValue() : c s.getKey() : 5 s.getValue() : f
よろしくお願いします。
回答5件
あなたの回答
tips
プレビュー