Loop 2 dimentional array to determine best case

Can you figure this out???
I've got a 2 dimitional array with trips and units and I need to find the best trip to unit matches that will result in the least amount. The number of elements of each is not constant but for this example I will show 4 each.
Here's my table..
     U1     U2     U3     U4
T1     50     75     100     0
T2     100     125     0     75
T3     30     45     55     100
T4     40     55     0     90
Here are all posible combinations that need to be checked with there resulting values.
T1     U1     U1     U1     U1     U1     U1
T2     U2     U2     U3     U3     U4     U4
T3     U3     U4     U2     U4     U2     U3
T4     U4     U3     U4     U2     U3     U2
Amt     325     275     185     205     170     235
T1     U2     U2     U2     U2     U2     U2
T2     U1     U1     U3     U3     U4     U4
T3     U3     U4     U1     U4     U1     U3
T4     U4     U3     U4     U1     U3     U1
Amt     320     275     195     215     180     245
T1     U3     U3     U3     U3     U3     U3
T2     U1     U1     U2     U2     U4     U4
T3     U2     U4     U1     U4     U1     U2
T4     U4     U2     U4     U1     U2     U1
Amt     335     355     345     365     260     260
T1     U4     U4     U4     U4     U4     U4
T2     U1     U1     U2     U2     U3     U3
T3     U2     U3     U1     U3     U1     U2
T4     U3     U2     U3     U1     U2     U1
Amt     145     210     155     220     85     85
The lowest amount is 85 which can be reached two differnt ways.
My question is how can I create a loop using a set amount of indexes (even though the # of elements might change) to search through all posible combinations?

I think this might be what you're after, provided your matrixes are 4x4 5x5 6x6 etc
I've included a commented out 5x5, for testing
as written, this will only work up to 9x9, any more and additional code is required to separate the Integer.parseInt's to 10,11 etc
class CombinationsMatrix
  private static int lowestCombo;
  private static boolean firstCombo = true;
  private static int matrix[][] = {{50,75,100,0},{100,125,0,75},
                                   {30,45,55,100},{40,55,0,90}};
  /*private static int matrix[][] = {{50,75,100,0,1000},{100,125,0,75,1000},
                                   {30,45,55,100,1000},{40,55,0,90,1000},
                                   {10,20,30,40,1000}};*/
  public static void main(String args[])
    String numbers = "";
    for(int i=0; i<matrix.length;i++) numbers += i;
    getCombos("",numbers);
    System.out.println("lowest combo = "+lowestCombo);
    System.exit(0);
  private static void getCombos(String str1, String str2)
    int i = str2.length()-1;
    if(i < 1)
      String str3 = str1+str2;
      int thisCombo=0;
      for(int x = 0; x < str3.length(); x++)
        thisCombo += matrix[x][Integer.parseInt(str3.substring(x,x+1))];
      System.out.println(thisCombo);
      if(firstCombo)
        lowestCombo = thisCombo;
        firstCombo = false;
      else if(thisCombo < lowestCombo) lowestCombo = thisCombo;
    else
      for(int ii = 0; ii <= i; ii++)
        getCombos(str1 + str2.substring(ii,ii+1), str2.substring(0, ii) +
                                  str2.substring(str2.length() - (i-ii)));
}

Similar Messages

  • Multi-dimentional array

    I have an multi dimentional array
    it has 5 columns and 8 rows
    A B C D E
    F G H I J
    K L M N O
    P Q R S T
    U V W X Y
    etc
    if i remove the row beginning [1][0]
    how can I get all the ones passed that row to shuffle up to fill the gap?
    A B C D E
    K L M N O
    P Q R S T
    U V W X Y
    ends up as
    A B C D E
    K L M N O
    P Q R S T
    U V W X Y
    Code would be lovely, I am new to this programming lark and I am not sure i like it :'(

    This is something done best (as previously suggested) with collections. Look into the tutorial and APIs for ArrayList and such. However, if you need to use arrays, here is a program that does (rather poorly I would think...)
    public class MultiArrayTest {
        public static void printData(char[][] data, int numRows, int numCols) {
             for (int r = 0; r < numRows; r++) {
                  for (int c = 0; c < numCols; c++){
                       System.out.print("" + data[r][c] + " ");
                  System.out.println(" ");
              System.out.println(" ");
        public static int deleteRow(char[][] data, int row, int maxRows, int maxCols) {
             for (int r = (row-1); r < (maxRows-1); r++){
                  for (int c = 0; c < maxCols; c++) {
                       data[r][c] = data[r+1][c];
             return maxRows-1;
         public static void main(String[] args) {
              char[][] data = { {'A', 'B', 'C', 'D', 'E'},
                                 {'F', 'G', 'H', 'I', 'J'},
                                 {'K', 'L', 'M', 'N', 'O'},
                                 {'P', 'Q', 'R', 'S', 'T'},
                                 {'U', 'V', 'W', 'X', 'Y'} };
              int maxRows = 5;
              int maxCols = 5;
              printData(data, maxRows, maxCols);
              maxRows = deleteRow(data,3,maxRows,maxCols);
              printData(data, maxRows, maxCols);
    }

  • Looping through an array to pass out the variable to Scanner

    I'm trying to get an array of files which end .list in a particular directory and then scan each one for an email address and at the moment print it out. As I understand it Scanner doesn't read from File but will from a String. However each time I try putting it into a String, I get an error as the code tries to pass the full array to it rather than the file names.
    What would be the best way of looping through the array so that each time Scanner gets a new path name applied to it?
    import java.io.*;
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.regex.*;
    import java.io.File;
    public class FindEmail {
         public static void main(String[] args) throws IOException {
              File userDir = new File("M:\\foo\\bar");
            FileFilter listfilter = new fileFinder();
            File[] foundarray = userDir.listFiles(listfilter);
            for (File i: foundarray) {
              Scanner s = new Scanner(new File(foundarray));
            try {
            Pattern p = Pattern.compile("([\\w+|\\.?]+)\\w+@([\\w+|\\.?]+)\\.(\\w{2,8}\\w?)");
            String str = null;
                 while ( (str = s.findWithinHorizon(p, 0)) != null ){
                     System.out.println(str);
            } finally {
               if (s != null) {
                  s.close();
                }//if
            }//finally
            }//for
         } //main
    }//class
    //class to find the list files
    class fileFinder implements FileFilter {
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".list");
    }

    The error that I got was
    Exception in thread "main" java.io.FileNotFoundException: [M:\foo\MAIN\BEDEWORK.LIST, M:\foo\MAIN\BEDEWORKSPRIVATE.LIST, M:\foo\MAIN\DONNA-NEW.LIST, M:\foo\MAIN\DONNA-NEWER.LIST, M:\foo\MAIN\DONNA-TEST.LIST] (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at org.stfc.bedework.FindEmail.main(FindEmail.java:17)At the time I had the code:
    FileFilter listfilter = new fileFinder();
               File[] foundarray = userDir.listFiles(listfilter);
               String name = Arrays.toString(foundarray);
               for (int i=0; i<name.length(); i++) {
              Scanner s = new Scanner(new File(name));

  • EDI Output ZB00 not getting determined in case of Split Deliveries.

    Hello All,
    A very Good Morning to you,
    Hope you are doing good,
    We have come across one critical Issue where the EDI Output ZB00 Dispatch Advice is not getting determined in case of few Split Deliveries in PROD.
    Issue : On a daily basis our Client is generating Split Delivery Process used for some specific customers only.
    These specific customers we are maintaining in ZPARAMS Table. The Flow of the Process is as below.
    Sales Order -->Parent Delivery ZLF--> Split Delivery ZLS--> Invoice ZF2.
    First the Sales Order ZOR is created through VA01 or EDI.
    This ZOR is processed via ZVL10A to create parent delivery ZLF.
    Once the parent delivery ZLF is created an Outbound IDoc SHPOD gets triggered which goes to the Distribution Centre Technicolor UK to check the confirmed qty and materials that needs to be delivered.
    Once the Quantity is verified and confirmed from DC an Inbound IDoc SHCON interface SAP.
    This Inbound SHPCON IDoc checks the entry in ZPARAMS for that customer. If the entry is found it creates one more Split Delivery ZLS doing picking and post Goods Issue in one step. This is the point where the ZB00 output is determined automatically in ZLS Delivery and processed successfully immediately.
    After that the Normal Invoice ZF2 is created.
    We have given the process flow details in the attachment along with Functional Modules used by the EDI Team.
    Now the Issue we are currently facing on a daily basis in PRD Out of the Total Count of ZLS Deliveries in few of ZLS Deliveries ZB00 Output is not getting determined at all which is causing a huge revenue loss. For remaining ZLS Deliveries it is getting determined correctly and processed.For Split Delivery we have only 2 Customers.
    We would like to know why this is happening in case of only few ZLS Deliveries.
    As a work around we have just write one program for these disputed deliveries where it will go in VL02N of these deliveries and save it without doing any changes. This will make ZB00 determined and processed immediately.
    We have even check the scenario in Quality Client no Issues at all. It is getting determined and processed successfully for all the test cases we created.
    Please could you help us on this so that we can fix this critical Issue.
    Many Thanks,
    Farhan.

    if QA system works correct
    you probably need to find the difference between it and PRD client.
    I guess it is a huge job.
    but who does if not you?
    because you have  a lot of custom things included coding
    also request abaper.

  • Could any one please help me to select the best case for my iPhone 6plus gold?

    HI All!
    Could someone please tell me which is the best case for my new iPhone 6 plus gold. I do not want to lose the beauty of the gold back finish of my 6 plus.
    THanks and Regards
    Aneesh

    Hello, I just bought the same phone and didn't want a hard case so I ordered this case from Amaon.
    ZVE® Full-body Protection Case,iPhone 6 Plus Case, [iphone6 plus wallet Case] Apple iPhone 6 Plus Case 5.5 Inch [Slim] Leather Wallet Cover with S
    Sold by: Zwallet

  • I want to create an array that goes into a case structure where each element in the array is an individual case and gets done in order

    I want to create an array that goes into a case structure where each element in the array is an individual case and gets done in order. Any ideas, I've been playing with the idea but have had no luck, is this even possible?

    Hi,
    Please check it out the attached Vi.. Is this you need?
    Sasi.
    Certified LabVIEW Associate Developer
    If you can DREAM it, You can DO it - Walt Disney
    Attachments:
    Event.vi ‏11 KB

  • What is the best case to get for my new Macbook Pro

    I just bought a new 15" Pro over the phone last week and according to the tracking it should be here by Wednesday.  I am extremely excited and cannot wait to get my new machine (my first mac).  But my question is, I want to protect it, what is the the best option, best case, or best sleeve, in order to protect my new investment?
    Thank you in advance for any comments.

    I saw this today when researching the same thing
    Mouse over the pictures for a side view.
    http://www.radtech.us/Products/MacTruck.aspx
    (no comp)

  • Looping through javabean array in jsp?

    Hello,
    In my servlet, I created an ArrayList of objects and pass these to a jsp page using:
    req.setAttribute("bean", uploadList);
    The ArrayList contains objects of the FileBean class, with a getIndex, and getDate methods.
    Could any possibly demonstrate how to loop through the ArrayList in the jsp and display the FileBean object values in a html table?
    To display the values of a javabean in jsp pages I normally have to use for example, requestScope.bean.getMethod();
    Thanks

    No, that would be requestScope.bean.attributename, if your getter method has the same name as the attribute you are getting.
    To loop through an array you have to use the c:forEach tag. Check google for "jstl foreach example", there are loads of examples.

  • Best Case - Saving Design Studio in BI Launchpad or Netweaver?

    Hello all
    what will be the Best Case to save a Design Studio? We are using to deploy the Netweaver Portal.
    Would it be better to save it to the Netweaver and transport as like a WAD and publish with a iView? Or
    would it be better to save it to to BO Launchpad, promote it and publish with a the Open Document Method?
    Any Answers would be great!
    Thank you.
    Adrian

    I think this depends on the end user requirements
    When you publish to the BI launchpad, then the Design Studio application is easily deployed to BI Mobile, which is one of the key features of Design Studio - "mobilize your dashboards"
    For that consideration alone, I prefer deploying to the launchpad

  • Looping over an array avoiding scriptlets

    Hello,
    I want to loop over an array avoiding java scriptlets. Here is the code I would like to "clean".
    <%
    int rowCol=0;
    for(int i=0; i<countryArray.length; i++){
    rowCol++;
    Country country = (Country)countryArray;
    out.println("<tr " + ((rowCol%2==0)?("class=\"evenRow\""):("class=\"oddRow\"")) + ">");
    out.println("<td class=\"countryName\">" country.getName() "</td>");
    out.println("<td class=\"countryCapital\">" country.getCapital() "</td>");
    out.println("<td class=\"number\">" + country.getFormattedLandArea() + "</td>");
    out.println("<td class=\"number\">" country.getFormattedPopulation() "</td>");
    out.println("<td class=\"number\">" country.getFormattedGdp() "</td>");
    out.println("<td class=\"number\">" country.getFormattedGdp_per_head() "</td>");
    out.println("<td><a class=\"more\" href=\"pais.jsp?countryID=" + country.getId() + "\">m?s...</a></td>");
    out.println("</tr>");
    %>
    Can anyone give me some guidelines please?
    Thanks in advance,
    Julien.

    you mean this:
    <%
    int rowCol=0;
    for(int i=0; i<countryArray.length; i++){
      rowCol++;
      Country country = (Country)countryArray;
    %>
    <tr class="<%= rowCol%2==0? "evenRow" : "oddRow" %>">
    <td class="countryName"><%= country.getName() %></td>
    <td class="countryCapital"><%= country.getCapital() %></td>
    <td class="number"><%= country.getFormattedLandArea() %></td>
    <td class="number"><%= country.getFormattedPopulation() %></td>
    <td class="number"><%= country.getFormattedGdp() %></td>
    <td class="number"><%= country.getFormattedGdp_per_head() %></td>
    <td><a class="more" href="pais.jsp?countryID=<%= country.getId() %>">m?s...</a></td>
    </tr>
    <%
    %>

  • What's the best case for an iPhone 5?

    Best case to protect an iPhone 5 without it looking like a tank?

    I use an orange Ballistic Smooth case for my white iPhone 5. It's has a drop rating of 5ft. I also use a SPG HD screen protector.

  • Best Case and Why?

    So I am getting the official apple case sometime by the end of the week depending on delivery etc... I have been debating if it's the best case etc... I've heard the case is okay, but does not protect that well and gets dirty easily. I really like the dodo case, but the 4-6 week wait is a long time since I have travel much sooner.. I so far have resisted from getting a screen protector but am considering it.
    What case do you use and why?

    Marc Chow wrote:
    For those with the Apple Case are you able to hold it upright with one hand easily? I do like the idea of having it slight tipped on my lap so I can type on it etc...
    Yes, in fact I keep the cover folded back in the tilt position when I am reading a book or doing anything where I have to hold up the iPad. When you fold the cover back and put it in the slot for the tilt, it is very solid. If you can imagine this, I put the thick part on the left side so I have about a 2 inch binding to grab onto with my left hand when I hold up the iPad, very comfortable and doesn't feel flimsy at all. Come to think of it, I keep the cover folded back about 90% of the time I am using the iPad, didn't plan that, it has just become comfortable for me to use it that way.

  • Best Case and Protective film?

    Thinking of upgrading from my original iphone and want to know the best case and film to get for the iphone 4
    I came across a leather case from United SGP Genuine Leather Grip for iPhone 4
    (http://www.ilounge.com/index.php/reviews/entry/united-sgp-genuine-leather-grip-f or-iphone-4/)
    But leaning towards something that will simply protect the phone from scratches, etc.
    Thanks in advance!

    The two best cases are probably the BALLASTIC CASE and the OTTERBOX. Tom

  • Review: iSkin Revo a Leader Among Best Cases

    After reading the hundreds of posts about cases--good and bad--I think I concur that the one of the best cases so far is the Revo from iSkin.
    The difference is: iSkin really put a lot of thought into their product. The combination of rubber along the edges and light, cool neoprene along the back (where the phone heats up) is just smart engineering. The non-glare film causes the crystal clear image to become a bit grainy, but I'm going to try it for a while. The beauty here is that iSkin did not require me to wet down the film to make it stick. They use an advanced 3m material that I can take off and put back on any time I want. And it cleans up easily.
    The thing I'm most surprised about is the visor. It's a plastic screen protector that pops into place as part of the overall case design. To use the phone, you just pop it off and stick it on the back in the same way. I thought this would be a pain in the butt, but it's actually not bad at all, and allows me to worry less about where the iPhone is landing in my pocket or in the car. I'm giving this case an A to date. I'm still eager to see what's on the horizon.
    As for the other two cases: the film from Bestskinever will never touch my iPhone. I refuse to bring water to the phone no matter how "ok" anyone says it is. The second case was from InCase. Yep, it can scratch the bezel. If you keep it clean, it can still be worth it, but who wants to do all that work? I'm interested to see how the iSkin does when it comes to scratches.
    Any other iSkin users? What kind of experience are you having?

    I just received mine today. The shipping was incredible - I ordered on Monday (when their CS center was supposedly closed for some holiday) and it with the 3-6 day shipping it was on my doorstep around 11:30 this morning. Putting it on was a breeze and it doesn't seem like it'll stretch like the incase does. I couldn't get the privacy screen on without air bubbles and I didn't like how the screen looked with it on so I took it off. I should note, though, that even with that on top of the Crystal Film that I have the touchscreen still worked fine. The privacy screen isn't as smooth as the Crystal Film or the touchscreen itself, which may bug some poeple. The plastic screen protector doesn't seem to hold too well on my case, so I'm going without it. This is my favorite non-hard-case by far, I just wish it had a belt clip.

  • Best case for ipad mini and Logitech wireless keyboard that opens like a book?

    What is a good case that holds both of these that opens like a book? In other words it is not a sleeve, it poems with ipad mini on one side and my Bluetooth keyboard on the other????

    There's likely no "best case" for any device. What works great for some will be detested by others. I can only tell you what I personally use and how it works. My own personal iPads (my wife and my 8 year old son have their own iPads with differing case needs) are pretty much relegated to indoor use. My mini 2 uses the standard-issue Apple Smart Cover. The back is protected (mainly from scratching & dings) by a clear plastic (polycarbonate) shell (purchased at Best Buy, Rocketfish brand) that is Smart Cover compatible (has the proper cutout for the Smart Cover hinge to contact the device properly). This combination works very well for me personally because there are many times when I do not want the Smart Cover on the device, flopping around & in my way...it's easily pulled off of the device when I need it off while the back shell stays on. You can't do that with the Smart Case. This works well enough for me on the mini 2 so I'm adopting the same for my Air 2.

Maybe you are looking for