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

Similar Messages

  • Guys!! any one can help me in recursive permutation of integer array!!

    this is the description of my problem:
    We 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 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 , where , then just swap and . This
    will give you the �next� permutation in this case.
    (ii) If the maximal element of the array is in the first position, so ,
    then to find the �next� permutation to the permutation , first find
    the �next� permutation to , and then add 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 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)
    if any one can help me then please help me!! i am stucked at this position to find permutation of the integer array.
    thanks,

    Sure. Why don't you post the code you already have done, and maybe
    someone here can help you with it.

  • Find Intersection of two array elements in Oracle 9i

    How to find intersection of two arrays in pl/sql for Oracle 9i.
    it is feasible in 11g using given code but this code is not working in 9i please help....
    DECLARE
    abc LIST := list(1,2,3,4);
    def LIST := list(4,5,6,7);
    BEGIN
    dbms_output.put_line(format_list(abc MULTISET EXCEPT def));
    END;
    Thanks in advance.... :)

    Argh. Never mind. My coordinates were reversed.
    People that made my data set specified the coordinates as lat/long and I didn't question it. I can now see that Oracle expects long/lat instead, so my example works now.

  • 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 .

  • Summing and Finding Maximum in 2d array

    So I have an 2d array of numbers and I am trying to find the maximum sum of the rows and give back the row number. So far I can get the sum and the maximum number but I need to give back the row number of the maximum value.
    public static void RowSumRow (int[][] table)
          static int sum[] = new int[5];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          System.out.println("The maximal revenue is $" + max + " at region " + region);
        }myMethods.maximumSearch
    public static int maximumSearch(int a[])
         int Max = a[0];
         for (int index=0; index < a.length; index++)
             if(Max < a[index])
              Max = a[index];
            return Max;
       }

    this is correct right?
    (the prarmeter rows is the rows that are to be tested)
    public static void RowSumRow (int[][] table, int rows)
          int sum[] = new int[rows];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          for(int x=0; x < sum.length; x++)
              if (max == sum[x])
                region = x-1;
          System.out.println("The maximal revenue is $" + sum[region] + " at region " + region);
        }This does what I want it to do right? Ive tested a few times and it is working, but is it logically correct?

  • Find row in 2d array

    please help...
    i have 2d array of double and i wanna find specific row an extract to new 2d array.
    My 2d array is:
    100
    31,3
    25,3
    32,1
    25,6
    100
    31,3
    25,3
    32,1
    25,6
    160
    32,4
    25,5
    33,5
    26
    170
    33,2
    25,8
    34,3
    26,2
    100
    33,9
    26
    35,2
    26,4
    160
    32,4
    25,5
    33,5
    26
    160
    32,4
    25,5
    33,5
    26
    100
    31,3
    25,3
    32,1
    25,6
    170
    33,2
    25,8
    34,3
    26,2
    and i wanna find row with numbers 100,160,170 and build new 2d array
    100
    31,3
    25,3
    32,1
    25,6
    160
    32,4
    25,5
    33,5
    26
    170
    33,2
    25,8
    34,3
    26,2
    please help....tnx, tnx
    Solved!
    Go to Solution.

    I guess you should be more specific about your question. If you are planning to find the values that are present in the 1st column then you can use search 1D array and pass the index to index the 2D array so you will get 1D array of row then build the array by finding the element.
    This is what Yamaeda explained
    The best solution is the one you find it by yourself

  • Where do I find the global package array g_fnn for a particular column?

    Hi Everyone,
    I found out from one of the tutorials that when a page is submitted, the value of a column is stored in a global package array.
    Can you tell me where or how I can find out what nn in g_fnn would be for a particular column?
    I was thinking maybe it corresponds to the position of the columns in the Report Column Attributes of the Report Attrutes page.
    This information will help me refer to it in pl/sql code.
    Thanks.
    Emad

    Hi Scott.
    I think I may be able to answer my own question. Ooopps!
    I noticed in the tutorial they refered to the deptno column as g_f09. I noticed in the Region Source under the Region Definition tab that a total of 9 columns were defined in the select statement.
    Is this assumption correct by stating that if the Sal column is the 6th one defined in the select statement, it is g_f06 ?
    Thanks.
    Emad.

  • Finding Mode of an array of numbers.

    I'm having troubles with finding the mode of an array of numbers.
    When the mode is in the middle of the set of numbers, it works, but when it is at the end, it doesnt.
    For example..
    if i had the numbers ...
    2,3,3,4,5,6,6,6 in an array, it would tell me that the mode is 3.
    if i had the numbers...
    2,4,5,5,5,6 in an array, it would tell me that the mode is 5.
    So the first set of numbers, the mode is incorrect, but the second set of numbers is correct.
    The following is my code...
    public static int getMode(int[] list)
    int mode = 0;
    int elements = 0;
    int tempMode = list[0];
    int temp = 1;
    for(int x = 1; x < list.length; x++)
    if(list[x-1] == list[x])
    temp++;
    }else{
    if(temp > elements)
    System.out.println("entered");
    tempMode = list[x-1];
    elements = temp;
    temp = 1;
    }else{
    temp = 1;
    mode = tempMode;
    return mode;
    }

    You need to add another test at the end of the loop:
        public static int getMode(int[] list)
            int mode = 0;
            int elements = 0;
            int tempMode = list[0];
            int temp = 1;
            int x;
            for (x = 1; x < list.length; x++)
                if (list[x - 1] == list[x])
                    temp++;
                else
                    if (temp > elements)
                        tempMode = list[x - 1];
                        elements = temp;
                        temp = 1;
                    else
                        temp = 1;
            if (temp > elements)
                tempMode = list[x - 1];
            mode = tempMode;
            return mode;

  • FINDING MEDIAN FOR AN ARRAY OF INTS WITH EVEN NUMBER OF VALUES

    okie dokie fellas i know this has got to be easy but i hjave been sittin at my comp forever workin on projects that are due and my head isn't all there anymore...could someone please clue me in on how im supposed to write the logic to find the median of an array of integers if the array contains an even number of values...I know I have to average the 2 values on either side but i cant figure it out at all...sorry i know its dumb but thnaks to anyone who helps
    package pgm3deClercqMatt;
    * @author Owner
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class ExamStatistics
         public static void main(String[] args)
              DbConnection db = new DbConnection("pgm3");
              boolean moreRecords;
              String query = "SELECT * FROM pgm3Data ORDER BY ExamGrade";
              ResultSet rs = db.processQuery(query);
              int nbrGrades = 0;
              ResultSetMetaData rsmd = null;
              try
                   rsmd = rs.getMetaData();
              catch(SQLException sqlex)
                   JOptionPane.showMessageDialog(null, "SQLException getting ResultSet data or metadata");
                   System.exit(0);
              int s[] = new int[200];
              DecimalFormat decimal = new DecimalFormat("#,##0.00");
              int n = 0, aboveNinety = 0, numberAboveNinety = 0;
              double sum = 0, avgGrade = 0, medianGrade = 0;
              try
                   moreRecords = rs.next();
                   if(!moreRecords)
                        JOptionPane.showMessageDialog(null, "pgm3Data Result Set is Empty.");
                        System.exit(0);
                   while(moreRecords)
                        s[n] = rs.getInt(1);
                        n++;
                        moreRecords = rs.next();
                   }// end of while loop
                   System.out.println("n = " + n);
                   System.out.println("s[0]= " + s[0]);
                   System.out.println("s[n-1]= " + s[n-1]);
                   //FIND AVERAGE OF ARRAY
                   for(int j=0; j<n; ++j)
                        sum += s[j];
                        avgGrade = sum/n;
                   //FIND NUMBER OF GRADES ABOVE OR EQUAL TO 90
                   for(int j=0; j<n; ++j)
                        if(s[j]>=90)
                             numberAboveNinety++;
                   //FIND MEDIAN EXAM GRADE
                   for(int j=0; j<n ; ++j)
                        if(Math.abs(medianGrade - Math.floor(medianGrade))<1.e-10)
                              medianGrade = s[(j+1)/2];
                        else
                             medianGrade =    <HERE IS WHERE THE PROB IS
              }// end of try block
              catch(SQLException sqlex)
                   JOptionPane.showMessageDialog(null, " SQLException getting ResultSet data or metadata");
                   System.exit(0);
              String output = "";
              output = "Number of Exam Grades: " + n;
              output += "\nHighest Exam Grade: " + maxOfArray(s, n) + "\nLowest Exam Grade: " + minOfArray(s, n)
                        + "\nAverage Grade: " + decimal.format(avgGrade) + "\nNumber of exam grades above 90: "
                        + numberAboveNinety + "\nMedian Exam Grade: " + medianGrade;
              JOptionPane.showMessageDialog(null, output);
              System.exit(0);
         }// end of main
         static int maxOfArray(int z[], int n)
              int j, max = z[0];
              for(j=1; j<n; ++j)
                   if(z[j]>max)
                        max = z[j];     
              return max;
         static int minOfArray(int z[], int n)
              int j, min = z[0];
              for(j=1; j<n; ++j)
                   if(z[j]<min)
                        min = z[j];     
              return min;
    }// end of ExamStatistics
    class DbConnection
         //     class DbConnection creates and manages the db connection,
         //     processes queries, and returns result sets for processing
         private Connection connection = null;
         private String url="jdbc:odbc:";
         private Statement statement;
         private String username = "";
         private String password = "";
         private ResultSet rs;
         private int nbrResultSets = 0;
         //     Constructor Argument is the registered name of the database
         DbConnection(String dbName)
              try
              {// load driver to allow connection to database
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   connection = DriverManager.getConnection ((url+dbName), username, password );
              catch (ClassNotFoundException cnfex)
                   fatalError("ClassNotFoundException on connection attempt");
                   System.exit(0);
              catch (SQLException sqlex )
                   fatalError("SQLException -- Unable to Connect to db");
                   System.exit(0);
         } // end of constructor
         ResultSet processQuery(String query)
         //     process a single SQL query and return the resulting data set
              rs = null;
              try
                   statement = connection.createStatement();
                   rs = statement.executeQuery(query);
              catch (SQLException sqlex)
                   fatalError("SQLException on query or processing");
              return rs;
         void endConnection()
              try
                   connection.close();
              catch (SQLException e)
                   fatalError("SQLException on attempt to close connection");
         //     simple local fatal error handler
         private void fatalError(String msg)
              JOptionPane.showMessageDialog(null,msg);
              System.exit(0);
    } // end of class DbConnection

    sorry to anyone who thinks what i'm doing is a joke
    first of all i'm a student and secondly i'm taking
    java in a summer session so things don't get
    explained as well as they should. And how is this our problem?
    I'm doing the best
    i can. The for loop was because the array that I
    defined to hold 200 values was being filled by a
    database with a supposed unknown number of values but
    less than 200 so i waslooping through to get each
    value and put it in order and the conditional
    statement was supposed to test to see if the incoming
    median was an integer and was in the final write-up
    put into it's own boolean method returning false if
    there was no median and you needed to take the
    average of the next lowest and highest values. BThere's always a median. The definition I sent you tells you what it is.
    But
    thnak you very much to the people that actually help
    on here and don't try to bash people who have put
    effort into writing their code, however shitty it may
    look to them. You can't control what people say about your stuff. Everyone who criticizes your work isn't making a personal attack. They're telling you something that you should be learning from. Your problem is that you can't separate yourself from your work.
    No one knows absolutely everything and
    people who decide to talk down on others when they
    are using this forum as a last resort need to grow
    up.Grow up? That's what you need to do. If you think for a moment that you'll never be criticized once you leave that ivory tower you're sadly mistaken. You need to figure out how to separate yourself from your code.
    %

  • Find transition in data array

    I have an array of temperature data acquired from a CompDAQ 9213 approximate length of 5000 data points.  At some point in time during these 5000 data points, the temperature measurements transition from 25 C to 100C.  There are typically around 100 data points of the 5000  that occur during the transtion.
    How do I parse the  5000  data points and get a subset of measurments that contain only the data points during the transition?  My method is unstable, there are some data sets that get a false subset.
    Attachments:
    Find Transitions.vi ‏39 KB

    Another way to think about this is, if your data remains fairly constant, then you have those transitions, you could simply analyze the array for outliers. The outliers would be the "transitions". As shown below, I have a much smaller data set than yours, but basically the same behavior you describe. Very little code needed.
    Richard

  • Find missing numbers in array

    HI !
    I have an array which holds 999 different numbers between 1-1000
    (which means that 1 number between 1-1000 does not appear in the array).
    I need to find the missing number in one pass and it's easy.
    My question is:
    Do you have any idea how can I find 2 missing numbers in the array ?
    Is it possible ?
    I cant use any data structure and I need to find the missing numbers in one pass.
    Thank you

    Using array.sort() and using another array is out of the question as its inhrently banned in the "i cant use any data structure" so this is
    Homework! tut tut
    ok so far an array with 1 number missing "its easy" yeah, just add em all up and see whats missing.
    for 2 numbers missing you should take a hint from what you are studying in the course ie solving Quadratic Equations..
    shall i make snoopy beg yet??
    naw, ok here goes
    on your 1 permitted pass add up all the mumbers that are there, also have another total for the squares of the numbers
    call the numbers you are looking for A and B
    subtract the first total from what it would be if there were all 1000, call this N
    subtract the second total from what the total of the squares would be if there were all 1000, call this M
    so..
    A+B=N
    solve for B in terms of A
    so..
    B=N-A
    and A^2+B^2=M
    should i quit now???
    no, ok
    substitute B in the second equation, shuffle a bit and..
    2A^2-2NA+N^2-M=0
    recognise the terms of the quadratic and..
    A=(2N +/- (4N^2-8(N^2-M))^.5)/4
    note the +/- plus OR minus will give you 2 results, these will be the 2 missing munbers
    tahh dahh
    See maths does have some use

  • How to find closest value in array?

    Hello all,
    I just want to find the closest value from the string array. Which I attached herer as a image.
    Now, If I want to find value 350 from string array and if it is not in array then in output array there should be display closest value of 350..
    Thank You for support
    Vinal Gandhi
    Kudos are always Welcome.... :-)
    Vinal Gandhi, CLD
    Software Engineer
    Solved!
    Go to Solution.
    Attachments:
    untitled.PNG ‏2 KB

    Hi Vinal G,
    something like the attached comes to my mind.
    Hope it helps 
    Mike
    Message Edited by MikeS81 on 05-12-2010 09:31 AM
    Attachments:
    Closest2Target.PNG ‏8 KB

  • Find index in an array of components

    I have an array of JButtons. Each JButton has an associated ActionListener. My problem is that when one of the buttons are clicked I need the index of the JButton that is clicked to do work inside the Actionlistener.
    How do I get the index of the JButton being pressed?
    JButton[ ] button = new JButton[300];
    for(int i = 0 ; i < 300 ; i++)
    button[i] = new JButton(("Test " + i));
    button.addActionListener(new ActionListener()
    public actionPerformed(ActionEvent evt)
    /** I need to know what the value of i is when this button is pressed **/

    I would think that you could just use the variable i from the loop, like this:
    JButton buttonArray = new JButton[300];
    JButton button;
    for(int i = 0; i < 300; i++)
      button = new JButton("Test"+i);
      button.addActionListener(new ActionListener() {
        public actionPerformed(ActionEvent e)
          int index = i; // here index is the index of the JButton chosen
    hope this helps!
      buttonArray[i] = button;

  • Find and replace several array elements

    I have a 2d array and want to subsitute any negitive value with a marker e.g "**" or any indicator which would be identified easily. I am using Labview 5.1

    Hi,
    The data type of you array is probably numerical. If you haven't already
    done this, the first step would be to convert the data to a character
    data type. This is easy done with 'Number to Decimal String'. Tie the
    output to a 'For Loop' and the search and modify each element in the
    array using a combination of 'Search 1D Array', 'Replace Array Subset',
    and shift registers.
    The first iteration of the 'For Loop' will give you the first index of
    the first '-1' found. Use that index value to replace the the '-1' with
    your '**'. Increment the index and pass it to the shift register to use
    as a starting point for the next interation's search and replace process.
    There may be a more "packaged" way of doing this but I just love For
    Loops.
    Hope this helps ...
    - Kevin
    In article <[email protected]>,
    "Gorelick" wrote:
    > I have a 2d array and want to subsitute any negitive value with a marker
    > e.g "**" or any indicator which would be identified easily. I am using
    > Labview 5.1

  • Finding User Input from Array

    I have an array (3x3) that is made up of clusters. Each cluster has numeric, string controls and indicators.
    What I want to do is determine:
    1. When the Operator makes a change to any of the array elements (easy enough using an event structure)
    2. Determine what element int the cluster has changed.
    So if I have the 3x3 array, made up of clusters (a control string, a ring, and a numeric):
    When the operator changes the ring value, I need to which one changed?
    Was it element 0,0 or element 1,3
    Thanks

    CarmineS wrote:
    When the operator changes the ring value, I need to which one changed?
    I would compare the previous array value to the changed value (equal with compare elements), reshape the resulting boolean array into a 1D array and use the Search 1D Array primitive.  From there, convert your index into the 2D index via the Quotient & Remainder.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

Maybe you are looking for

  • [SOLVED] Ktorrent and magnet links

    I use KDE and try to use the "native" apps for integration and so.... but ktorrent is giving me a hard time when trying to download magnet links (more and more common this days) I click on a magnet link, ktorrent grabs it but never reaches the point

  • Error in break string

    Hi Why my query below did not work I believe that can to be because    LENGTH(REPLACE(REPLACE(REPLACE(TRANSLATE('18;0;119;0.00;18;120;139;1.50;18;140;159;2.00;18;160;199;3.00;18;200;299;4.00;18;300;399;5.00;18;400;#;6.50;19;0;9;150.00;19;10;19;200.00

  • ABOUT THE HR-ABAP

    Hi, i hope every body is doing good. Here i am having the query on payroll. Here i want to retrive the payroll result for india, in the payroll data i want know the wage types which are belogs to infotypes 0008,0014 and 0015. a immediate reply will b

  • Workflow is not moving next level approver

    Dear all, We are in the upgrade from 4.6c to ECC 6.0. When I am executing the workflow it is going successfully to the first approver, depends up on the decision of the approver it should process any one of the four braches. But here my problem  it i

  • System upgrade failure

    I have multilib and multilib-testing enabled, as well as the default testing repos enabled. An attempted upgrade (pacman -Syu) this morning produced this: :: Starting full system upgrade... :: Replace heimdal with core/krb5? [Y/n] Y resolving depende