面试问题:如何对10首音乐随机播放?
知识点:洗牌算法。
C++版:
- #include <cstdlib>
- #include <iostream>
- using namespace std;
- int rand(int range_start, int range_end)
- {
- srand((unsigned int)time(NULL));
- return rand()%(range_end - range_start) + range_start;
- }
- void swap(int* a, int* b)
- {
- int* temp;
- *temp = *a;
- *a = *b;
- *b = *temp;
- }
- void shuffle(int a[], int len)
- {
- int shuffle_key;
- for(int i = 0; i< len; i++)
- {
- shuffle_key = rand(0, len);
- swap(a[i], a[shuffle_key]);
- }
- }
- int main(int argc, char *argv[])
- {
- int a[8]={3, 5, 7, 2, 12, 1, 5, 6};
- shuffle(a, 8);
- for(int i = 0; i < 8; i++)
- {
- printf("%d", a[i]);
- }
- system("PAUSE");
- return EXIT_SUCCESS;
- }
Java版:
- import java.util.Random;
- public class agorithm {
- public static void main(String arg[]){
- String[] musicUrl={"/music/1.mp3",
- "/music/2.mp3",
- "/music/3.mp3",
- "/music/4.mp3",
- "/music/5.mp3",
- "/music/6.mp3",
- "/music/7.mp3",
- "/music/8.mp3",
- "/music/9.mp3",
- "/music/10.mp3"};
- shuffle(musicUrl);
- for(String music:musicUrl){
- System.out.println(music);
- }
- }
- public static void shuffle(String[] musicUrl){
- int shuffle_key;
- String temp;
- Random rand = new Random();
- for(int i = 0; i < musicUrl.length; i++){
- shuffle_key = rand.nextInt(musicUrl.length-1);
- temp = musicUrl[i];
- musicUrl[i] = musicUrl[shuffle_key];
- musicUrl[shuffle_key] = temp;
- }
- }
- }