Старый 25.08.2013, 21:03   #1   
Registered User
 
Сообщений: 1,114
Регистрация: 23.06.2007
Возраст: 56

Hopkroft вне форума Не в сети
Перемешать массив

Народ, есть натуральный ряд от 1 до n.
Т.е. 1,2,3,4 и так далее.
необходимо его перемешать. Разные варианты пересмотрел, вот пример кода.

Код:
import java.util.*;

public class ShuffleArray {
    private static Random random = new Random();

    static int generateRandom(int n) {
        return Math.abs(random.nextInt()) % n;
    }
 
	 // взял из Википедии
	public static void shuffle (int[] array) {
	     int n = array.length;
	     while (n > 1) {
	         int k =random.nextInt(n--); //decrements after using the value
	         int temp = array[n];
	         array[n] = array[k];
	         array[k] = temp;
	     }
	 }
	
	 // то что первое в голову пришло
	public static void myShuffle(int[] array) {
		int middle =  array.length/2;
		int temp, RandIndex;
		
		for (int ind=array.length-1; ind>middle; ind-- ){
			RandIndex=generateRandom(middle);
			temp=array[ind];
			array[ind]=array[RandIndex];
			array[RandIndex]=temp;
		}

	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final int count = 20;
		
		int[] arr= new int[count];
		int[] arr2= new int[count];
		int index=0;

		System.out.println("Source array");
		for (index=0; index<count; ++index){
			arr[index]=index+1;
			arr2[index]=index+1;
			System.out.print(arr[index]+" ");
		}
	
		
		//Собственное моё творение
		myShuffle (arr);
		//то что взял из википедии
		shuffle (arr2);
			
		System.out.println();
		System.out.println("Array after shuffle");
		for (index=0; index<count; ++index){
			System.out.print(arr[index]+" ");
		}
		System.out.println();
		for (index=0; index<count; ++index){
			System.out.print(arr2[index]+" ");
		}	
	

	}
}
Цитата:
Результат
Source array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Array after shuffle
20 13 15 4 17 16 7 8 18 12 11 14 2 10 3 6 19 9 5 1
18 15 4 5 1 17 19 11 16 13 10 3 6 7 14 20 8 12 9 2
Кто -нибудь сталкивался с подобной задачей?
 
Старый 25.08.2013, 21:51   #2   
highly mean
 
Сообщений: 1,128
Регистрация: 26.05.2011
Возраст: 35

silly вне форума Не в сети
http://docs.oracle.com/javase/7/docs...a.util.List%29

Ня?
 
Старый 25.08.2013, 21:56   #3   
Registered User
 
Сообщений: 1,114
Регистрация: 23.06.2007
Возраст: 56

Hopkroft вне форума Не в сети
silly, ну можно и так
 
Поиск в теме: 



Быстрый переход:

  Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения
BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd. Перевод: zCarot
Support by DrIQ & Netwind