[腾讯面试]洗牌算法

腾讯面试问题:如何对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;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值