You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Gilles (JIRA)" <ji...@apache.org> on 2014/11/03 13:08:33 UTC

[jira] [Commented] (MATH-1161) Feature request: shuffle algorithms for generic types

    [ https://issues.apache.org/jira/browse/MATH-1161?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=14194487#comment-14194487 ] 

Gilles commented on MATH-1161:
------------------------------

I'm not sure that Commons Math would be the best place for utilities of this kind (the vast majority of CM algorithms focus on primitives).

You could implement what you need as follows using {{shuffle(int)}} from CM:
{code}
    public static <T> void shuffle(T[] list) {
        final int len = list.length;

        // Shuffle indices.
        final int[] indexList = natural(len);
        shuffle(indexList);

        // Create shuffled list.
        final List<T> out = new ArrayList<T>(len);
        for (int i = 0; i < len; i++) {
            out.add(list[indexList[i]]);
        }

        // Modify original list.
        for (int i = 0; i < len; i++) {
            list[i] = out.get(i);
        }
    }
{code}

But, of course, this is already longer (and less efficient) than what you proposed...
The alternative would be to have duplicate codes in CM (one for an {{int[]}} and one for a generic {{T[]}}), which is not a good solution IMO for a feature that has no use within the library.

If you feel otherwise, you should post your arguments to the "dev" ML.


> Feature request: shuffle algorithms for generic types
> -----------------------------------------------------
>
>                 Key: MATH-1161
>                 URL: https://issues.apache.org/jira/browse/MATH-1161
>             Project: Commons Math
>          Issue Type: Wish
>    Affects Versions: 3.3
>            Reporter: Mark
>            Priority: Minor
>
> The current shuffle algorithm works on int[]. I often need something more generic for arbitrary array types.
> Example:
> {code}
> import java.util.Random;
> public class Shuffle<T> {
>     private static final Random rnd = new Random();
>     // Implementing Fisher–Yates shuffle
>     public void shuffle(T[] ar) {
>         for (int i = ar.length - 1; i > 0; i--) {
>             int index = rnd.nextInt(i + 1);
>             T a = ar[index];
>             ar[index] = ar[i];
>             ar[i] = a;
>         }
>     }
> }
> {code}



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)