言語処理100本ノック 第1章: 準備運動 09
09. Typoglycemia
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ.
java
package net.vg4; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class Main { private static String randomize(String str) { List<String> end = Arrays.asList(str.split("")); Random rand = new Random(); for (String s : str.split("")) { int i = rand.nextInt(str.length()); int j = rand.nextInt(str.length()); String x = end.get(i); end.set(i, end.get(j)); end.set(j, x); } return String.join("", end); } private static String getCenter(String str) { return str.substring(1, str.length() - 1); } public static void main(String[] args) { // write your code here String sample = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."; String[] sa = sample.split(" "); List<String> end = new ArrayList<>(); for (String s : sa) { if (s.length() >= 4) { end.add(s.substring(0, 1) + randomize(getCenter(s)) + s.substring(s.length() - 1)); } else { end.add(s); } } System.out.println(end); } }