Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java ME (J2ME) > shuffle


Автор: dorogoyIV 23.7.2007, 13:13
в J2ME я не нашел метода shuffle(), который есть в SE. Random не подходит, потому, что нужно перемешать некоторый диапазон значений, что бы они не повторялись.
как это делается?
неужели применять Random и проверять - было значение или нет? smile 

Автор: math64 23.7.2007, 14:57
Нужно брать исходники shuffle() из SE и переписывать их для ME
Код

Random rnd = new Random();
void shuffle(Object[] arr) {
  for (int i=size; i>1; i--)
    swap(arr, i-1, nextInt(i));
  }
}
void swap(Object[] arr, int i, int j) {
  Object o = arr[i];
  arr[i] = arr[j];
  arr[j] = o;
}
int nextInt (int i) {
  // В CLDC 1.0 нет rnd.nextInt(i)
  return (int)((((long)rnd.nextInt()&0xFFFFFFFF)*i)>>32);
}


Автор: nagliyvred 23.7.2007, 15:18
Я не совсем понял что не должно повторяться - индексы переставляемых элементов? Ну так пройдитесь по всей коллекции линейно. Именно так собсно метод shuffle() в SE и реализован:
Код

/**
     * Randomly permute the specified list using the specified source of
     * randomness.  All permutations occur with equal likelihood
     * assuming that the source of randomness is fair.<p>
     *
     * This implementation traverses the list backwards, from the last element
     * up to the second, repeatedly swapping a randomly selected element into
     * the "current position".  Elements are randomly selected from the
     * portion of the list that runs from the first element to the current
     * position, inclusive.<p>
     *
     * This method runs in linear time.  If the specified list does not
     * implement the {@link RandomAccess} interface and is large, this
     * implementation dumps the specified list into an array before shuffling
     * it, and dumps the shuffled array back into the list.  This avoids the
     * quadratic behavior that would result from shuffling a "sequential
     * access" list in place.
     *
     * @param  list the list to be shuffled.
     * @param  rnd the source of randomness to use to shuffle the list.
     * @throws UnsupportedOperationException if the specified list or its
     *         list-iterator does not support the <tt>set</tt> operation.
     */
    public static void shuffle(List<?> list, Random rnd) {
        int size = list.size();
        if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
            for (int i=size; i>1; i--)
                swap(list, i-1, rnd.nextInt(i));
        } else {
            Object arr[] = list.toArray();

            // Shuffle array
            for (int i=size; i>1; i--)
                swap(arr, i-1, rnd.nextInt(i));

            // Dump array back into list
            ListIterator it = list.listIterator();
            for (int i=0; i<arr.length; i++) {
                it.next();
                it.set(arr[i]);
            }
        }
    }


Автор: dorogoyIV 23.7.2007, 16:02
Цитата

Я не совсем понял что не должно повторяться - индексы переставляемых элементов?

например:
Код

List list=new ArrayList(); // это тоже для SE
list.add(1);
list.add(2);
list.add(3);
// перемешиваем, что бы 1,2 и 3 не повторялись
// в SE можно так:
// Collections.shuffle(list);
// в МЕ так сразу не сделаешь

буду пробовать код  math64

Автор: math64 24.7.2007, 13:52
Код

/** Получить массив перетасованных целых чисел от 1 до n. */
int[] shuffle(int n) {
  int[] arr = new int[n];
  for (int i = size; i > 0; i--) {
    arr[i - 1] = i;
  }
  for (int i=size; i>1; i--) {
    int j = nextInt(i);
    int tmp = arr[j];
    arr[j] = arr[i-1];
    arr[i-1] = tmp;
  }
}


Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)