1// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
2// Copyright (C) 2013 - Samuel Gougeon <sgougeon@free.fr>
3//
4// Copyright (C) 2012 - 2016 - Scilab Enterprises
5//
6// This file is hereby licensed under the terms of the GNU GPL v2.0,
7// pursuant to article 5.3.4 of the CeCILL v.2.1.
8// This file was originally licensed under the terms of the CeCILL v2.1,
9// and continues to be available under such terms.
10// For more information, see the COPYING file which you should have received
11// along with this program.
12
13function rep = %grand_perm(N, V)
14    // Returns N random permutations of V's components.
15    // V may be a scalar, a row or column vector, a matrix, or an hypermatrix.
16    // All data types are supported: Integers, reals, complexes, strings, polynomes..
17    // if V is a row, permutations are returned as N rows
18    // if V is a column, permutations are returned as N columns
19    // if V is a matrix or a true hypermatrix, permutations are returned
20    // through an additional dimension of size N.
21
22    // Author : Samuel Gougeon - 2010
23    // Version: 1.2
24    // Software: Scilab and related
25    //
26    // Tests:
27    // with a row of reals:
28    // m = grand(1, 6, "uin", 0, 10)
29    // grand_perm(3, m)
30    // // with a column of reals:
31    // grand_perm(4, m')
32    // // with a matrix of reals:
33    // M = grand(2, 5, "uin", 0, 10)
34    // grand_perm(3, M)
35    // // with strings:
36    // grand_perm(5, ["a" "b" "c" "d"])
37    // // with polynomes:
38    // p = (m'-%z)^2
39    // grand_perm(3, p)
40
41    s = size(V);
42    L = prod(s);
43
44    if L == 1 then
45        rep = V(ones(1, N));
46    else
47        //[tmp, k] = gsort(rand(L, N), "r", "i");
48        k = grand(N, "prm", (1:L).'); // Faster for large L
49        if length(s) < 3 then
50            if s(1) == 1 then
51                rep = matrix(V(k), [s(2) N]).';
52            elseif s(2) == 1 then
53                rep = matrix(V(k),[s(1) N]);
54            else
55                rep = matrix(V(k), [s N]);
56            end
57        else
58        rep = matrix(V(k), [s N]); end
59    end
60
61endfunction
62