Permutation

Hello,
Below is permutation generator method,
no output has same no. twice or more in one line, i.e. each no. occurs only once in a line
public int[] nextPermutation(int n)
      int[] p = new int[n];
      for (int i = 0; i < n; i++)
         p[i] = i + 1; //contain 1...10.
      int pSize = n; // max = 10
      int[] r = new int[n]; //size = 10
      for (int i = 0; i < n; i++)
      {  int pos = generator.nextInt(pSize);         
         r[i] = p[pos]; // call made to random index in a array of size n to store nos. in r[i]
//I CAN'T get whats the MAIN ROLE of the two statements below
         p[pos] = p[pSize - 1]; //overwrites already stored ints with some other nos.
         pSize--; //
      return r;
   }

i just want to know the "purpose" of those two
statements. pleaseOh, thanks for clarifying. The purpose of those two statements is to set the value of p[pos] to the value of p[pSize - 1], then decrement the pSize variable by one.
>
thanks if replies ASAPHope this helps.

Similar Messages

  • Permutations of non-sequential string in C

    Hi,
    I'm just learning C now and am trying to get my head around this permutation pickle I'm in.  I can pretty simply write code that will give all permutations of N number of letters from A-z.  E.g., if N = 4, it will print out AAAA AAAB .... zzzz. This is pretty simple iteratively or recursively with a counter.
    now, however, I want to enter in a string that does not neccessary contain letters in sequence, and find all the possible relevant permutations of that string.  E.g. I input a string of BEHP, and  I want to find all the permutations of this combination.  I don't want BBBB, BBBE, etc., I want BEHP, BHPE, BPHE, etc. 
    I think my current approach is severely limited by the counter method, as it's giving permutations that are just not relevant.
    Also, can someone please confirm the maths on this.  If I have a string of 3 letters, ABC, the number of possible combinations is 3! right? 3 factorial?
    Thanks

    I don't know C, but have a couple of logic-based suggestions.  I believe you are right in your permutations calculation of 3!.  To solve your problem of combinations, could you do something like put each character into an array (which is ordered by index) and then use a similar technique to the one you used for the other set of letters but base it on the index number?

  • Finding Permutations of an Array

    I was hoping I could get a little help on finding a way to cycle through an array and print all of the permutations of its elements. I have a short example of what I am trying to do. If someone could fill in the blank, I could understand how to use it in future programs.
    The goal of the code below is to write a line to line, comma delimited listing of the elements of an int array 1 through 5. The order of the output does not matter to me, I'd just like to try and get all 120 permutations listed into a new file passed as an arg. I've tried thinking of how to switch the elements around, but I don't know the most efficient way of doing so. Any help would be appreciated.
    // PermutationTest.java: Create a comma delimited text file of permutations of an array
    import java.io.*;
    public class PermutationTest {
    /** Main method: args[0] is the output file **/
    public static void main(String[] args) {
    // Declare print stream
    PrintWriter pw = null;
    // Check usage
    if (args.length != 1) {
    System.out.println("Usage: java PermutationTest file");
    System.exit(0);
    File tempFile = new File(args[0]);
    if (tempFile.exists()) {
    System.out.println("The file " + args[0] +
    " already exists, delete it, rerun the program");
    System.exit(0);
    // int array
    int[] permArray = {1, 2, 3, 4, 5};
    // Write data
    try {
    // Create data output stream for tempFile
    pw = new PrintWriter(new FileOutputStream(tempFile), true);
    * loop/sort of some kind to generate permutation *
    // After finding a permutation, print a comma delimited output and repeat until all 120 permutations were written.
    pw.println(permArray[0] + "," + permArray[1] + "," + permArray[2] + "," + permArray[3] + "," + permArray[4]);
    catch (IOException ex) {
    System.out.println(ex.getMessage());
    finally {
    // Close files
    if (pw != null) pw.close();
    }

    Given a current permutation of a not necessarily unique sequence
    p[0] p[1] p[2] ... p[n-1], the next permutation can be found as follows:
    1) find a largest i such that p[ i ] < p[ i+1 ]; if no such i can be found, stop;
    2) find a largest j > i such that p[ i ] < p[ j ]; such a j can always be found;
    3) swap elements p[ i ] and p[ j ]
    4) reverse the tail p[ i+1 ]... p[ n-1 ].
    Repeat the steps above until step 1) fails.
    kind regards,
    Jos

  • Finding Permutations using perms in MathScript throws Memory is full error

    I'm using the perms Mathscript function to find possible permutations of single digit numbers in an array.  According to the perms function help it will accept 15 elements or fewer.  I can feed this function up to 9 elements but when I try 10 I get the error - LabVIEW:  Memory is full.  I've increased the Virtual Memory per the suggestion in the Why do I get "Memory is Full" Error KB. 
    The error occurs when Windows Task manager reaches 628 M no matter what I change my Virtual Memory to.  I do have 2 GB of RAM in my computer.  Any suggestions?
    Thanks,
    Message Edited by CactusCoder on 11-14-2008 11:02 PM
    Message Edited by CactusCoder on 11-14-2008 11:04 PM
    Solved!
    Go to Solution.
    Attachments:
    pirm.vi ‏16 KB

    This is expected. With N=10, the final matrix will be 10!x10, or about 36Million elements of DBL. Each contains 8 bytes, bringing the footprint to ~290MB for a single copy of the expected output matrix.
    Looking at the memory use of the VI for N=9, it is already 100MB, so it looks like there are about 4 copies of the final array in memory. No wonder N=10 is impossible.
    I would recommend to implements this in plain LabVIEW (wires and loops) with a U8 datatype, you'll probably be able to go higher than 9.
    Don't forget that 15 is unrealistic, because the array dimensions are I32, but the array size will be N!. This means you don't have enough rows for e.g. N>12 anyway.
    Do you have a good reason that you need such huge arrays?
    LabVIEW Champion . Do more with less code and in less time .

  • Help me for getting the specific permutation set  in java

    input is a specific range(int) and a key
    output is : specific permutation of the number (int),,,,,,,,,, which includes all the number from the input range.........
    Example
    List function_name(starting no.,ending no.,key)
    starting no. and ending no. specify the range................ and this function return the specific combination of all no. in the range........and having exact as much elements as this range contains........
    like starting no. 0.
    ending no. 10
    output
    1,8,2,4,6,9,3,7,5,0,10
    please suggest the solution as soon as possible..........
    thanx in advance......

    I think in your last thread http://forum.java.sun.com/thread.jspa?threadID=5118424 about this topic you were given a link for the Stored Procedure chapter of the JDBC tutorial. Did you read it?

  • How To Do Permutations (help)

    Hey All,
    I am doing to applet for compute and display all the possible permutations for a word in a recursive way. I am at a lost at how to do this, some hints would be helpful.
    Example:
    The word eat has 6 permutations:
    eat
    eta
    aet
    ate
    tea
    tae
    Later,
    Iceman

    guess you guys are in the same class, how about you talk to each other.. http://forum.java.sun.com/thread.jsp?forum=31&thread=365381&tstart=15&trange=15

  • [svn:osmf:] 10248: Fix a few bugs related to the interaction between IPlayable, IPausable, and ITemporal within a SerialElement, specifically around ensuring that the transition from child to child happens in the various permutations of these traits .

    Revision: 10248
    Author:   [email protected]
    Date:     2009-09-14 16:45:00 -0700 (Mon, 14 Sep 2009)
    Log Message:
    Fix a few bugs related to the interaction between IPlayable, IPausable, and ITemporal within a SerialElement, specifically around ensuring that the transition from child to child happens in the various permutations of these traits.  Introduce a helper class for managing this logic, as it can happen in both CompositePlayableTrait and CompositeTemporalTrait.  This lays the groundwork for a MediaElement which only implements IPlayable (e.g. to ping a tracking server) working within a serial composition.  Beef up unit tests so that these cases don't get broken in the future.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/.flexLibProperties
        osmf/trunk/framework/MediaFramework/org/openvideoplayer/composition/CompositePlayableTrai t.as
        osmf/trunk/framework/MediaFramework/org/openvideoplayer/composition/CompositeTemporalTrai t.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/openvideoplayer/composition/TestSerialEle ment.as
    Added Paths:
        osmf/trunk/framework/MediaFramework/org/openvideoplayer/composition/SerialElementTransiti onManager.as

    Hi,
    Found a note explaining the significance of these errors.
    It says:
    "NZE-28862: SSL connection failed
    Cause: This error occurred because the peer closed the connection.
    Action: Enable Oracle Net tracing on both sides and examine the trace output. Contact Oracle Customer support with the trace output."
    For further details you may refer the Note: 244527.1 - Explanation of "SSL call to NZ function nzos_Handshake failed" error codes
    Thanks & Regards,
    Sindhiya V.

  • Generate Permutations of array recurssive function.

    Producing consecutive permutations.Need to develop a method that lists one by one all permutations of the numbers 1, 2, �, n (n is a positive integer).
    (a) Recursive method . Given a verbal description of the algorithm listing all permutations one by one, you are supposed to develop a recursive method with the following header:
    public static boolean nextPermutation(int[] array)
    The method receives an integer array parameter which is a permutation of integers 1, 2, �, n. If there is �next� permutation to the permutation represented by the array, then the method returns true and the array is changed so that it represents the �next� permutation. If there is no �next� permutation, the method returns false and does not change the array.
    Here is a verbal description of the recursive algorithm you need to implement:
    1. The first permutation is the permutation represented by the sequence (1, 2, �, n).
    2. The last permutation is the permutation represented by the sequence (n, �, 2, 1).
    3. If n a ,...,a 1 is an arbitrary permutation, then the �next� permutation is produced by
    the following procedure:
    (i) If the maximal element of the array (which is n) is not in the first position of the array, say i n = a , where i > 1, then just swap i a and i-1 a . This will give you the �next� permutation in this case.
    (ii) If the maximal element of the array is in the first position, so 1 n = a , then to find
    the �next� permutation to the permutation ( ,..., ) 1 n a a , first find the �next�
    permutation to ( ,..., ) 2 n a a , and then add 1 a to the end of thus obtained array of (n-1) elements.
    (iii) Consecutively applying this algorithm to permutations starting from (1, 2, �, n),you will eventually list all n! possible permutations. The last one will be (n, �, 2, 1).For example, below is the sequence of permutations for n = 3 , listed by the described algorithm:
    (0 1 2) ; (0 2 1) ; (2 0 1) ; (1 0 2) ; (1 2 0) ; (2 1 0)
    Please help...i have done the iterative one..but unable to figure out the recursive..
    Thank you in advance..
    Please help

    Thanks for your reply...it would be great if a code is provided..i am try to do but this not working here is my code
    * Permutations.java
    * Created on April 25, 2006, 12:42 PM
    package javaapplication1;
    * @author ismail
    public class Permutations {
        // print N! permutation of the elements of array a (not in order)
        public static boolean nextPermutation(int a[]) {
            int N = a.length;
            int[] t = new int[N];
          /* for (int i = 0; i < N; i++)
               t[i] = a;*/
    return(perm2(a, N));
    private static boolean perm2(int [] a, int n) {
    int i=n-1;
    // start from last but 2
    for (; i>0; i--) if (a[i]<a[i+1]) break;
    if (i <0) return false;
    for (int j = 0; j < n; j++) {
    swap(a, j, n-1);
    perm2(a, n-1);
    // swap(a, j, n-1);
    return true;
    // swap the characters at indices i and j
    private static void swap(int[] a, int i, int j) {
    int c;
    c = a[i]; a[i] = a[j]; a[j] = c;
    private static final int num = 3; // number of elements to permutate
    private static int [] a = new int[num]; // permutations array
    private static int qkCounter = 0; // Counter for Quick sort
    private static int mrgCounter = 0; // Counter for Merge sort
    private static int qkSum = 0; // Total sum for Quick sort
    private static int mrgSum = 0; // Total sum for Merge sort
    public static void main(String s[]){
    int count=1;
    int [] qkArray = new int[num]; // Quick Sort array
    int [] mrgArray = new int[num]; // Merge Sort array
    int avgQuick = 0;
    int avgMerge = 0;
    // Initialize array
    for(int i=0;i<num;i++){
    a[i]=i;
    // call nextPermutation to generate possible permutations - iterative method
    for (int j=0; nextPermutation(a);j++){
    count++; // Count number of records
    // print the permutation array
    for(int i=0;i<num;i++){
    System.out.print(a[i]);
    not working means-- it keeps on printing 012

  • Permutations of ABCDEF where A is before D

    I am trying to get started writing the code for finding the permutations of ABCDEF where A comes before D. I would appreciate any help on getting started with this project.

    generate all the permutations of BCDEF
    prepend them all with Aor, for fun:
    for every permutation of ABCEF, insert a D at all indeces after the A.
    and for some more fun, use recursion.

  • Printing all permutations

    Hi,
    My sister is a CS student, and she currently learns recursion. She's got an exercise is to write a program that gets an array of integers and recursively prints all of its permutations (all elements in all possible orders).
    For example, if the input array is {1, 2}, the program should print this:
    1 2
    2 1
    The code was not too difficult to write, and it works now. The exercise has a second requirement, though, that the output of our program should be identical to the output of the school solution. That is, it's not enough that we print all permutations, we must do it the same order as they do.
    And that's where we're kind of stuck, because the order of the output in the school solution is not the same as ours, and we're unsure how to modify our code reproduce their output.
    For example, for input array {1, 2, 3}, our code would print
    1 2 3
    1 3 2
    2 1 3
    2 3 1
    3 1 2
    3 2 1
    whereas the school solution would print
    1 2 3
    1 3 2
    2 1 3
    2 3 1
    3 2 1 //last 2 lines come in reverse order
    3 1 2
    More (off site) examples
    {1, 2, 3, 4}: http://rafb.net/p/I2DMPZ57.nln.html
    {1, 2, 3, 4, 5}: http://rafb.net/p/EkQoJ668.nln.html
    {1, 2, 3, 4, 5, 6}: http://rafb.net/p/RVBtVf67.nln.html
    If somebody can identify a pattern in the school solution, please give us a hint as to how we should match it with our code.
    The relevant part of our code is here: http://rafb.net/p/4oEsMB53.nln.html
    Thanks

    thanks for your input.
    its always good to have something to kick start you into thinking again :). rather than starting blankly and tugging your hair.
    anyway .. unfortunately none of the workarounds seemed to work out. they did seem to be describing a slightly different problem though - one where the text appears but the window does not scroll .. i don't get any text at all until the end (and then it does scroll).
    i tried it out with a standard TextArea and got the scrolling, the problem is it is much slower than when i run it at the command prompt, and it slows down further. is this anything to do with its running lower on memory (as cmd prompt discards most of the data as it generates more), so do i need to fix that first to cure this, or is it a problem with the TextArea. and will it be a problem with any component i choose to print out on? i guess if it is ill just have to scrap that idea.
    thanks again
    btw - u are right, it shouldve been long - i'd corrected it since i posted the code .. sorry

  • Permutations of a 6! numerically

    I'm trying to build a VI that lets me use the letters A B C D E F and arrange them in all permutations (so 720 different orders - 6!)
    i've tried doing it with simple N-loop structures, but i'm a bit rusty.
    the output would ideally be a 2D word matrix of
    ABCDEF
    ABCDFE
    etc......
    help!!
    Solved!
    Go to Solution.

    @Mike - yeah ran it on my other computer, it just does the 'how many permutations are there' calculation
    thats not what i'm after, i'm after each of the permutations themselves.
    so lets say we have A B C D E and F
    so it could start:-
    ABCDEF
    ABCDFE
    ABCEDF
    ABCEFD
    and so on, its a simple enough sequence its just laborious to type out 720 lines of it manually,
    and i'f i move onto 7,8 or 9 letters gets longer and longer.

  • Internal table permutations: for experts

    Hi all,
    i have an internal table with 10 values.
    I want to have all permutations. There are 10! possibilities.
    How can i calculate this?
    regards

    I'm not sure about what you need...It could something like this???
    TYPES: BEGIN OF ty_table,
           value TYPE string,
           END OF ty_table.
    DATA: t_table TYPE STANDARD TABLE OF ty_table
          WITH HEADER LINE.
    DATA: counter TYPE sy-tabix,
          count TYPE sy-tabix,
          value TYPE string,
          perm TYPE string.
    FIELD-SYMBOLS: <fs_table> LIKE LINE OF t_table.
    DO 10 TIMES.
      counter = counter + 1.
      t_table-value = counter.
      APPEND t_table.
    ENDDO.
    LOOP AT t_table ASSIGNING <fs_table>.
      CLEAR count.
      value = <fs_table>-value.
      CONCATENATE perm value
      INTO perm SEPARATED BY '-'.
      DO 10 TIMES.
        count = count + 1.
        READ TABLE t_table INDEX count.
        IF value NE t_table-value.
          CONCATENATE perm t_table-value
          INTO perm SEPARATED BY '-'.
          CONDENSE perm NO-GAPS.
        ENDIF.
      ENDDO.
      SHIFT perm LEFT DELETING LEADING '-'.
      WRITE:/ perm.
      CLEAR perm.
    ENDLOOP.
    Result...
    1-2-3-4-5-6-7-8-9-10
    2-1-3-4-5-6-7-8-9-10
    3-1-2-4-5-6-7-8-9-10
    4-1-2-3-5-6-7-8-9-10
    5-1-2-3-4-6-7-8-9-10
    6-1-2-3-4-5-7-8-9-10
    7-1-2-3-4-5-6-8-9-10
    8-1-2-3-4-5-6-7-9-10
    9-1-2-3-4-5-6-7-8-10
    10-1-2-3-4-5-6-7-8-9
    Greetings,
    Blag.

  • Please Help - Permutations using recursion..

    Please some body help me in generating permutaions using recursion..exact guidelines are as follows..
    Producing consecutive permutations.Need to develop a method that lists one by one all permutations of the numbers 1, 2, �, n (n is a positive integer).
    (a) Recursive method . Given a verbal description of the algorithm listing all permutations one by one, you are supposed to develop a recursive method with the following header:
    public static boolean nextPermutation(int[] array)The method receives an integer array parameter which is a permutation of integers 1, 2, �, n. If there is �next� permutation to the permutation represented by the array, then the method returns true and the array is changed so that it represents the �next� permutation. If there is no �next� permutation, the method returns false and does not change the array.
    Here is a verbal description of the recursive algorithm you need to implement:
    1. The first permutation is the permutation represented by the sequence (1, 2, �, n).
    2. The last permutation is the permutation represented by the sequence (n, �, 2, 1).
    3. If n a ,...,a 1 is an arbitrary permutation, then the �next� permutation is produced by
    the following procedure:
    (i) If the maximal element of the array (which is n) is not in the first position of the array, say i n = a , where i > 1, then just swap i a and i-1 a . This will give you the �next� permutation in this case.
    (ii) If the maximal element of the array is in the first position, so 1 n = a , then to find
    the �next� permutation to the permutation ( ,..., ) 1 n a a , first find the �next�
    permutation to ( ,..., ) 2 n a a , and then add 1 a to the end of thus obtained array of (n-1) elements.
    (iii) Consecutively applying this algorithm to permutations starting from (1, 2, �, n),you will eventually list all n! possible permutations. The last one will be (n, �, 2, 1).For example, below is the sequence of permutations for n = 3 .
    Please help...i have trying this for long time
    plesae help...i apreciate your time..and help..thank you

    public class Permu {
        public static boolean nextPermutation(int a[]) {
                return(permute(a, 0));
        public static boolean permute(int v[], int start) {
             int n = v.length;
             if (start == (n - 1)) {       //if its the end of the sequence genereated then print them
                count++;
                //print(v,n);
                return false;
            } else {
                for (int i = start; i < n; i++) { //swap the start element with the ith element to get n first sequeces
                    int temp = v[start];
                    v[start] = v;
    v[i] = temp;
    permute(v, start + 1);
    //of the n the first is kept constant the same is applied for the rest sequence
    //int tmp = v[i];
    v[i] = v[start];
    v[start] = temp;
    return true;
         public static void main(String[] args) {
    int v[] = {1, 2};//this is the array which should contain the items      to be permuted
    do{
    for(int i=0;i<2;i++)
    System.out.print(v[i]);
    System.out.println();
    }while(nextPermutation(v));
    [i]Output:
    123
    123
    123
    123
    123
    This is exact code i am trying to run...pls someone help me out...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How can I create list of permutations

    Hi Everyone,
    I need to create a 2 d array which will contain all of the permutations of a 1d input array, specifically, I have a 1 d array of colour boxes and I want to return a 2 d array of colour boxes.  This is too mathematical for me!  Is there a combination of functions that will help me achieve this?  From my days at college I remember something about factorials, but as for coding it...
    If anyone has any suggestions I would be very grateful.
    Thank you,
    Michael.
    Solved!
    Go to Solution.

    Assuming that all colors in the input array are unique, here's a simple algorithm (LabVIEW 8.5). (see also)
    The permutation algorithm is from wikipedia:
    For every number k, with 0 = k < n!, the following algorithm generates a unique permutation of the initial sequence sj, j = 1, ..., n:
    function permutation(k, s) {
         for j = 2 to length(s) {
            swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
            k := k / j;        // integer division cuts off the remainder
         return s;
    NOTE: Indexing in LabVIEW starts at 0, so the code is changed accordingly.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    permutate.PNG ‏19 KB
    permutate.vi ‏13 KB

  • Algorithm for generating permutations without repetition

    Hy,
    I want to generate all the permutations for a list of n objects and I do that by making a tree having the children the elements in the list, and the children for the first node the elements in the list except that node etc.. After that I make a depth-first search and make a list with all the paths to the nodes situated at a certain level p. The algorithm works fine if n = 10 and p =3 for example because there are 10!/7! paths generated. Unfortunately the list of objects can have 30 elements and the level p can be 15.. so the algorithm doesn't help me in this case. I want to ask if anyone has any ideas about how can the algorithm be improved to work better (less than 1 minute) for the later case.
    Thanks

    bluedragonfly wrote:
    I want to know if there is another way to do things..and of course not the impossibleThe only thing you have asked for is 2.03e20 permutations. We don't know how you intend to process the permutations and even if we could guess what you are doing then just processing 2.03e20 anythings is just about impossible.
    So, how do we know "if there is another way to do things" ?

  • Sorting permutations

    Hello. I was hoping if someone could help me with this. i have a two dimensional table , with elements such as {{1,2,3,4,6,7,9},{4,6,7,8,9,10,11},{1,2,3,5,6,8,12}}. now i wanted to search for permutations of the lenght i chose. if i type 3, it will return combination 1 2 3, and that it appears twice. i got this to work, but only on a small number of elements. it stops working for more of them. if someone would be willing to help, i'll gladly post the source code.

    Hello. I was hoping if someone could help me with this. i have a two dimensional table , with elements such as {{1,2,3,4,6,7,9},{4,6,7,8,9,10,11},{1,2,3,5,6,8,12}}. now i wanted to search for permutations of the lenght i chose. if i type 3, it will return combination 1 2 3, and that it appears twice. i got this to work, but only on a small number of elements. it stops working for more of them. if someone would be willing to help, i'll gladly post the source code.

Maybe you are looking for