This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scn = new Scanner(System.in); | |
int arr1[]=new int[10],arr2[]=new int [10]; | |
Set<Integer> set = new TreeSet<Integer>(); | |
for(int i=0;i<10;i++) | |
arr1[i]=scn.nextInt(); | |
for(int i=0;i<10;i++) | |
arr2[i]=scn.nextInt(); | |
for(int i=0;i<10;i++){ | |
for(int j=0;j<10;j++){ | |
set.add(arr1[i]+arr2[j]); | |
} | |
} | |
ArrayList<Integer>list=new ArrayList<Integer>(set); | |
for(int i=0;i<list.size();i++){ | |
if((i)%10==0&&i!=0) | |
System.out.println(); | |
if((i)%10!=0) | |
System.out.print(" "); | |
System.out.print(list.get(i)); | |
} | |
System.out.println(); | |
} | |
/*題目:[C_AR118-易] 硬幣組合方法一 | |
作者:1010 | |
時間:西元 2017 年 3 月 */ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scn = new Scanner(System.in); | |
int c, count = 0, num1[] = new int[10], num2[] = new int[10], ans[] = new int[100]; | |
for (int i = 0; i < 10; i++) | |
num1[i] = scn.nextInt(); | |
for (int i = 0; i < 10; i++) | |
num2[i] = scn.nextInt(); | |
Arrays.sort(num1); | |
Arrays.sort(num2); | |
for (int i = 0; i < 10; i++) { | |
for (int j = 0; j < 10; j++) { | |
ans[i * 10 + j] = num1[i] + num2[j]; | |
} | |
} | |
Arrays.sort(ans); | |
boolean b = false; | |
for (int i = 0; i < 100; i++) { | |
if (count == 10 && b) { | |
System.out.println(); | |
count = 0; | |
} | |
for (c = i + 1; c < 100; c++) | |
if (ans[i] == ans[c]) | |
break; | |
if (c == 100) { | |
if (count != 0) | |
System.out.print(" "); | |
System.out.print(ans[i]); | |
count++; | |
b = true; | |
} else | |
b = false; | |
} | |
System.out.println(); | |
} | |
/*題目:[C_AR118-易] 硬幣組合方法二 | |
作者:1010 | |
時間:西元 2017 年 3 月 */ | |
} |
用雙迴圈就能算出所有組合了,但這邊要記住相加結果重複就不用再印出來了
Java有個很好用的容器較TreeSet,他不但可以做排序而且若遇到相同的數值會直接合併(捨去),簡單來說TreeSet是個集合它裡面幫你做好排序而且所有值不會重複具有唯一性
至於要怎麼把集合Set的值呼叫出來,這時就需要一個容器ArrayList的方式儲存集合裡的值才能去取得集合裡的資料
最後注意輸出是每十個為一行,每行最後一個不空白,最後結束還要換行!
ps.至於第二種寫法是大二時寫的單純只用到陣列輸出時再逐一判斷是否有重複(非常浪費時間,屬於笨方法)
沒有留言:
張貼留言