生活随笔
收集整理的這篇文章主要介紹了
                                
把1,2,3,4,5,6,7,8,9九个数分成三组,各个数字使用一次
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
 
                                
                            
                            
                            前幾天找工作,筆試下面這道題:
 把1,2,3,4,5,6,7,8,9共九個數分成三組構成排列a1a2a3,a4a5a6,a7a8a9,而且每個數字使用有且僅有一次,構成的排列之比為3:2:1,求輸出所有的排列組合。
 
方法一:
 顯然a1a2a3,a4a5a6,a7a8a9在[123, 987]內,進一步就是a1a2a3在[123,329],遍歷即可
 
public static void test1(){long e1 = System.currentTimeMillis();for(int i = 123; i <= 329; i ++){if(match(i, 2*i, 3*i)){System.out.println(i + "	" + 2*i + "	" + 3*i);}}long e2 = System.currentTimeMillis();System.out.println("time:" + (e2 - e1));
}public static boolean match(int first, int second, int third) {List<Integer> list = Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0);int index = -1;String str = first +  "" + second +  "" + third;for(int i = 0; i < str.length(); i ++){//遍歷每一個字符,在list中記錄對應字符出現的次數index = Integer.parseInt(str.substring(i, i + 1)) - 1;//index為零則是取到字符0,需要過濾掉if(index < 0 || index > 8){//過濾return false;}if(list.get(index) >= 1){return false;}else{list.set(index, list.get(index) + 1);}}return true;
}
 
結果:
192	384	576
219	438	657
273	546	819
327	654	981
time:1
 
方法二:
 使用正則表達式過濾
 
public static void test1() {long e1 = System.currentTimeMillis();Pattern pattern = Pattern.compile(//不重復字符組成的九位數"([1-9])"+ "(?!\\1)([1-9])"+ "(?!\\1|\\2)([1-9])"+ "(?!\\1|\\2|\\3)([1-9])"+ "(?!\\1|\\2|\\3|\\4)([1-9])"+ "(?!\\1|\\2|\\3|\\4|\\5)([1-9])"+ "(?!\\1|\\2|\\3|\\4|\\5|\\6)([1-9])"+ "(?!\\1|\\2|\\3|\\4|\\5|\\6|\\7)([1-9])"+ "(?!\\1|\\2|\\3|\\4|\\5|\\6|\\7|\\8)([1-9])$");String str = "";Matcher match = null;for (int i = 123; i <= 329; i++) {if (3 * i >= 1000) {break;}str = Integer.toString(i * 1000000 + i * 2 * 1000 + 3 * i);match = pattern.matcher(str);if (match.matches())System.out.println(i + " " + 2 * i + " " + 3 * i);}long e2 = System.currentTimeMillis();System.out.println("time:" + (e2 - e1));
}
 
結果:
192	384	576
219	438	657
273	546	819
327	654	981
time:3
                            
總結
                            
                                以上是生活随笔為你收集整理的把1,2,3,4,5,6,7,8,9九个数分成三组,各个数字使用一次的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。