今天貼的是老師上一次上課,在課堂上給我們練習的部分,原意是將一個List中的內容打亂,每次執行結果都會出現不同的順序;老師使用了Collections中的shuffle方法,簡單地解決了這個問題,然而老師給我們時間練習無非也是讓我們思考屬於自己的方式。
底下分享我自己寫的部分,另外也歡迎平時有光顧我網誌的讀者,可以在底下留言自己的寫法。^-^
第22行是老師所使用的方法,而第28行到第35行是我自己上課時寫的,想法就是來自於洗牌時,我們都會將牌組抽起來疊到最上面那堆,藉由不斷地交換來達到洗牌的動作,所以我用For迴圈尋訪每個元素,將每個元素都隨機和後面的元素做交換。
程式碼:
// Using method toArray.
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
public class s11967046
{
// constructor creates LinkedList, adds elements and converts to array
public s11967046()
{
String colors[] = { "black", "blue", "yellow" };
LinkedList< String > links =
new LinkedList< String >( Arrays.asList( colors ) );
links.addLast( "red" ); // add as last item
links.add( "pink" ); // add to the end
links.add( 3, "green" ); // add at 3rd index
links.addFirst( "cyan" ); // add as first item
//→→→使用Java內建的函數shuffle←←←
Collections.shuffle(links);
// get LinkedList elements as an array
colors = links.toArray( new String[ links.size() ] );
//洗牌,將每次執行結果調換
String re = "";
for(int i = 0 ; i<colors.length ; i++){
int b = (int)(Math.random()*colors.length);
re=colors[i];
colors[i]=colors[b];
colors[b]=re;
}
System.out.println( "colors: " );
for ( String color : colors )
System.out.println( color );
} // end UsingToArray constructor
public static void main( String args[] )
{
new s11967046();
} // end main
} // end class UsingToArray
網誌管理員已經移除這則留言。
回覆刪除