N-queens with stacks

trying to solve the classic "8-queens" (http://en.wikipedia.org/wiki/Eight_queens_puzzle) problem with a stack, but I can't seem to get it working right. For now, I'm just trying to get it to print out one solution. Here is the code so far. At the moment, it prints out a 6x6 grid for some reason instead of an 8x8, and some of the queens are diagonal from each other. Point out problems or solve it if you can.
import java.util.Stack;
public class Assignment3{
    static int numSol=0;
    static int curCol;
    public static int solve(int n) {
     Stack<Integer> s = new Stack<Integer> ();
     for(int row=0; row<n;row++){
         for(int col=0; col<n;col++){
          if(conflict(row,col,s)==false){
              s.push(col);
              System.out.println(row);
              if (row == (n-1)){
               printSolution(s);
               numSol++;
              break;
          }else{
              if(col==(n-1)){
               row=row-1;
               col=s.pop();
     return numSol;
    public static boolean conflict(int row, int col,Stack<Integer> s){
     boolean conflicts =false;
     for(int pastRow=0; pastRow<s.size(); pastRow++){
         curCol = s.get(pastRow);
         if(curCol == col || curCol-pastRow == col-row || curCol+pastRow == col+row){
          conflicts = true;
          break;
          return conflicts;
    //this method prints out a solution from the current stack
    //(you should not need to modify this method)
    private static void printSolution(Stack<Integer> s) {
     for (int i = 0; i < s.size(); i ++) {
         for (int j = 0; j < s.size(); j ++) {
          if (j == s.get(i))
              System.out.print("Q ");
          else
              System.out.print("* ");
         }//for
         System.out.println();
     }//for
     System.out.println(); 
    }//printSolution()
    public static void main(String[] args) {
     int n = 8;
     if (args.length == 1) {
         n = Integer.parseInt(args[0].trim());
         if (n < 1) {
          System.out.println("Incorrect parameter");
          System.exit(-1);
     int number = solve(n);
     System.out.println("There are " + number + " solutions to the " + n + "-queens problem.");
}

There's little to say apart from general advice. Create tests to exercise your code under new conditions and not requiring direct user interaction. Your code looks reasonably well composed, which should make that easier; the only issue are those static fields -- can you make those local variables instead?
Then add some debugging statements to see where things are going wrong.

Similar Messages

  • Chart - problem with stack

    Hello,
    Ive got 3 problems with stack plots:
    1. In the legend, the first value of table is the last one, why?
    2. Always when i remove one value(in this case i turn off button), the last chart is remove
    3. When I turn off the second button(rest is on), the plot name in legend is doubled.
    Does anyone have an idea what i can do with this?
    thanks for any answers.
    Solved!
    Go to Solution.
    Attachments:
    Desktop.zip ‏24 KB

    Well, you simply need to code it differently.
    Try this:
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    top-levelMOD2.vi ‏13 KB

  • Unable to patch portal with stack 15?

    Hi,
    We got BI system with portal running on windows 2003 server.
    I am trying to patch up portal/jave stack with stack 15.
    After JSPM successfully logged on with SDM and it shows target sp 15 for all components.
    But after i click deployment jspm is giving the following error:
    "<!LOGHEADER[START]/>
    <!HELP[Manual modification of the header may cause parsing problem!]/>
    <!LOGGINGVERSION[1.5.3.7185 - 630]/>
    <!NAME[E:\usr\sap\RAB\DVEBMGS20\j2ee\JSPM\log\log_2008_03_10_06_25_04\OperateSDM_01.LOG]/>
    <!PATTERN[OperateSDM_01.LOG]/>
    <!FORMATTER[com.sap.tc.logging.TraceFormatter(%24d %s: %m)]/>
    <!ENCODING[Cp1252]/>
    <!LOGHEADER[END]/>
    Apr 10, 2008 6:27:30 AM  Info:
    Apr 10, 2008 6:27:30 AM  Info: ==========================================
    Apr 10, 2008 6:27:30 AM  Info: =   Starting to execute command 'ping'   =
    Apr 10, 2008 6:27:30 AM  Info: ==========================================
    Apr 10, 2008 6:27:30 AM  Info: Sending "ping" command to the SDM server...
    Apr 10, 2008 6:27:30 AM  Error: SDM server is running, but authentication failed because of wrong password.
    Apr 10, 2008 6:27:30 AM  Error: Processing error. Return code: 104
    If i click sdm gui tool i can logon with the master password successfully.
    I don't understan why the same password not working with in JSPM.
    Appreciate your help.
    Thx
    Rama

    Hi Rama,
          Try the following steps of SAP Note 701654. you have to change the property admin/password/<SID> as described below. You have to use the working password related to user id - admin/user/<SID>...
          1. Start the Config Tool.
               (Execute <SAPj2eeEngine_install_dir> \configtool\configtool.bat.)
          2. Select the secure store node.
               The configuration for the secure storage in the file system appears.
          3. Select the admin/password/<SID> entry.
          4. Enter the administrator user's new password in the "Value" field and choose "Add".
          5. Choose "File" --> "Apply" to save the data.
               Note: Contrary to the message that appears, you do not need to restart the server or cluster for this change to take effect.
          6. Finally restart SDM server.
    Consider Reward points, if helpful..
    Regards,
    Uday.

  • C3750G IP BASE upgrade to IP SERVICE with stacking four switches

    Dears
       Existing i have 4 x C3750G IP BASE with stacking, now need upgrade to IP service for BGP support.
    Order from reseller PN: CD-3750G=EMI=.
    I want ask need purchasing 4 x "CD-3750G=EMI=" or just purchasing 1 only for 4 x switches. I checked Cisco supportforums C3750G not support license activation.
    Many Thanks
    Wong

    Disclaimer
    The Author of this posting offers the information contained within this posting without consideration and with the reader's understanding that there's no implied or expressed suitability or fitness for any purpose. Information provided is for informational purposes only and should not be construed as rendering professional advice of any kind. Usage of this posting's information is solely at reader's own risk.
    Liability Disclaimer
    In no event shall Author be liable for any damages whatsoever (including, without limitation, damages for loss of use, data or profit) arising out of the use or inability to use the posting's information even if Author has been advised of the possibility of such damage.
    Posting
    My understanding has been the 3750 series will allow you to (legally) run a whole stack with an IPServices image as long as one stack member has a license for IPServices.
    For redundancy, you should have at least two stack members with IPServices, otherwise if the sole IPServices master fails, the whole stack reverts to IPBase.

  • Aperture jumps to wrong picture when working with stacks

    Hello
    I am working with stacks on Aperture 3.3 and Mountain Lion.
    I experience the following annoying bug:
    Each time I take an action on any stack (say adding a picture to the stack, collapsing the stack, extracting a picture from the stack, etc), the action gets completed but the viewer then keeps jumping to another picture in the same event (always the same picture) instead of keeping the cursor on the just acted-upon picture.
    This is really annoying, in particular since I am working on a large event with 2,000 pictures and thus each time this happens I have to scroll back through hundreds of pictures to get back to the one where I was working. In effect this renders the stacks functionality useless.
    I have tried already the various repair/rebuild options for the library, to no avail...
    Any ideas / pointers?
    Many thanks!
    Alex

    Hi mikeleung81
    No one ever responded to my original post;-(
    I have further experimented and read around, improved the situation but have not been able to fully solve, here is specifically where I am at:
    - have observed further problematic symptoms including random ordering of pictures when copying them to albums, crashes when exporting slideshows, etc
    - I have performed multiple time the various repair/rebuild options for the library
    - also moved back my library from an external drive to the iMac hard drive, and created more space on the hard drive which was quite full (moved iTunes db to the external drive)
    - I have also manually degrouped each stack, then re-grouped one by one (I observed a couple of odd behaviours of jumping around on specific stacks while doing this, which tells me that the issue may lie in individually corrupted stacks)
    - ended up with a database that was behaving correctly for a while, but then started to exhibit again same symptoms
    - at this stage I believe issue may be linked to my system being underpowered (memory leakage): 2007 iMac, 2GB of memory to handle 100GB library. I am anxiously awaiting the release of the new iMac to upgrade and hopefully solve...
    Curious about similarities / differences on your side?
    AH

  • Help with Stacks

    This is my first time working with stacks. I am trying to get familiar with using some of the methods from java.util.Stack. Specifically i am trying to set the size of the stack and then, using a for loop, push items onto the stack until the stack has reached its capacity. However I seem to be having some trouble,
    sometimes my output looks like [null,null,null... 0,2,4...] depending on the size, and sometimes (when I change the code to try something else) I just get
    [null,null,null,......]. What I would like to do is populate the stack with numbers [1- whatever the size of the stack is], then on the next iteration of the loop I want it to reach and print that the stack is full.
    import java.util.Stack;
    public class myStack{
    private static Stack stack = new Stack();
    public static void main(String[] args) {
         stack.setSize(5);    
          //System.out.println(stack.size());
          //System.out.println(stack.empty());
          for(int i= 0; i<stack.size(); i++){
              if(!stack.isEmpty()){
                       stack.push(i);
              else{
                   System.out.println("stack is full");
              i+=1;
          System.out.println(stack);

    Why is there no method that tests if the stack is full or has reached its maximum capacity?

  • [CS5.5] issue with stacking order on spreads when pages change

    Have recently had a situation where items on a right hand page have "disappeared" behind an item placed over the reader's spread in a layout using facing pages.
    For example,
    this spread has 3 elements: an item of type per page, both brought to front; and a green background sent to back. all fine so far.
    i have then deleted the last two pages from the file... still going great guns...
    i then delete the first two pages from the file... then the preverbial hits the fan.
    the type on page two is gone! oh no!!! the reality is that the type is now BEHIND the green background.
    I am aware that had the green background been split in two at the spine, the result would be this:
    but it's too late now.
    has anyone else experienced this phenomenon and is it safe to call this a "bug"? anyone wanting to attempt the following steps can download a PDF containing the indesign file as an attachment within the pdf from this url: http://colecandoo.files.wordpress.com/2012/06/spreadfail.pdf
    colly

    Although the green block is, for practical purposes, on both pages, to InDesign, it's really only assigned to the left page of the spread. For example, if you start with this:
    …which has a green box in the background, spanning both pages of each spread, and yellow boxes on odd pages and magenta boxes on odds…
    …and you delete page one, you get this:
    …where the yellow and magenta boxes have switched sides, but notice that the green box that had been across both pages is now only on the odd pages. That's because the green boxes were actually assigned to the even pages, which have now shifted to become the odd pages, and the box stayed with it's page.
    Now, here's what happens when you delete page 2:
    Except for page one, which hasn't moved or changed, the screen shots from removing page one and page two look the same, because I only removed one page at a time. That caused the pages to switch sides.
    Now, here's what happens when you remove pages one and two at the same time:
    This is what you are getting. As best as I can guess, the reason that the green box is above the yellow boxes is because the left page of the spread is higher in stacking order than the page on the right. My guess is that the stacking order of the objects on each page is reaffirmed when pages are deleted. And in this case, I don't think it matters whether you delete them one at a time or two. Here is a screen shot of what it looks like when I delete page one, then delete page two right afterward (actually, since page two had become page one, I had to delete page one the second time to delete the original page two, but you know what I mean):
    This screenshot looks the same as the previous, even though this one had two pages deleted one at a time, and the previous one had two pages deleted together. I can't say whether this is a bug or not, but I assume that the engineers at Adobe didn't choose this behavior on purpose. It's probably a side-effect of some other choice that probably makes perfect sense.
    I think the answer is to either  place objects that span a spread on the master, or to use layers if the master option isn't practical for the job you are doing.

  • Problem with Stacked Bar Chart

    I have a problem with a stacked bar chart in Numbers 09. My chart is a single series with 6 categories. All of the categories have different values. The first 5 categories display correctly. However, the last category does not display in the color its supposed to, but rather shows up as white/background instead of the grey color shown on the legend. However, the value label is displayed in the proper place.
    When I select other chart types (pie, regular bar, or regular column) the category shows up like it's supposed to.
    This is kind of annoying since I would rather use stacked bar instead of a pie chart. Is there an upper limit on the number of values it can display as a stacked bar chart? Is this just a bug? Thanks!

    Here's my result with six values in a single series. I double clicked the last bar to change its colour from the default grey (which was visible) to magenta.
    Numbers 2.0.3, iBook G4, OS X v10.4.11
    (Shot in the dark:) Try double clicking the value label, then changing the order position of this item.
    Regards,
    Barry

  • Problem with Stacked Columns in Business Graphics

    Hi,
    Has anyone used the stacked columns chart type in business graphics?  Am facing a problem with this.
    I am using the SimpleGraphics example demo with 2 dataseries, the values ranging from 0-10.  It works fine if the chart type is Columns (this is default).  When I change the chart type to stacked_columns, the graph goes for a toss.  The y-axis range automatically changes to 0-1 (values as 0, 0.2, 0.4 ... 1.0) and it does not display stacked columns as expected.
    Is there any specific property(s) that need to be set for this chart type?
    Appreciate any quick response.
    cheers,
    Vittal

    Hi friend,
    See the link below it is having the solution of hiding the columns in smart forms
    Hide table columns in smart form?
    Create a table to display your values with 12 col and hide the columns based on the idea provided in the link above.
    I think this will solve your issue if you still have queries please revert back to me i will help you.
    Thanks,
    Sri Hari

  • Using stored parameter from data control class with stacked bar-graph

    Hi folks,
    I'm relatively new to ADF & EJB so I want to apologise in advance if this question seems rudimentary to many of you.
    Edit:  I should have mentioned that I'm using JDeveloper 11.1.1.5
    I'm having a hard time determining how to retrieve the value from a variable to be assigned to a property of the bar graph I'm trying to display on my JSF page.
    I have tried to briefly summarise the logic below for reference.
    I have a data control class (ActivityChart) that includes a method "getActivityDetail" returns a List of custom Objects (ActivityDTO) that are the underlying data for my bar graph.
    public class ActivityChart {
        private Double axisScale;
        public ActivityChart() {
            super();
            axisScale = 0.0;
        public List<ActivityDTO> getActivityDetail(List<String> businessUnits) {
            List<ActivityDTO> returnNewList = new ArrayList<ActivityDTO>();
            List<TransactionDTO> dataList = new ArrayList<TransactionDTO>();
            TransactionSessionBean transBean = lookupTransactionSessionBean();
            if (businessUnits != null && !businessUnits.isEmpty()){
                dataList = transBean.getActivityData(SystemUtil.getCurrentUser(), businessUnits);           
                returnNewList = processTransactions(dataList);
                axisScale = calcAxisScale(returnNewList);
            return returnNewList;
    ...The TransactionDTO object is basically a mirror of the entity object to store the fields from the queried db transactions.
    The ActivityDTO object contains a String value (x-axis label) and 3 Double values for the values required for the bar graph.
    What I'm trying to do is dynamically set the scale for the 2 y-axes (I'm using a dual-axis stacked bar graph) because the auto calculated values are not aligned.
    Right now I've got the two relevant elements of the bar graph hard-coded with a specific axis value:
    <dvt:y1Axis axisMaxAutoScaled="false" axisMaxValue="100.0"/>
    <dvt:y2Axis axisMaxAutoScaled="false" axisMaxValue="100.0"/>.
    The value I want to use for the Y-axis is calculated and stored in the "axisScale" variable in the above class.
    Really at a loss of how to move forward from here.
    Would very much appreciate any guidance/direction offered.
    Thanks,
    Karim
    Edited by: 973742 on Nov 28, 2012 8:12 AM

    Looks like I may have found the answer!
    I had to set up the variable in the bindings for the page and then reference the variable from the binding and add the property inputValue.
    ie. value="#{bindings.axisScale.inputValue}"

  • SVG CHart error ORA-20001 with Stacked Bar Chart HTML DB 1.6.0.00.87

    Hi,
    during I put a How-To into execution (How To Create a Stacked Bar Chart) I'll get the following error code:
    SVG Chart error:ORA-20001:line_Chart error:ORA-20001:
    get_data error:ORA-20001:Parse error:ORA009
    (see http://www.oracle.com/technology/products/database/htmldb/howtos/index.html)
    This Situation occurs when i add a second series to the
    chart. The first series works fine. I've used the following SQL-Statement:
    select null l, sales_month, revenue from (select to_char(o.order_timestamp,'Mon YYYY') sales_month, sum(oi.quantity * oi.unit_price) revenue, to_date(to_char(o.order_timestamp,'Mon YYYY'),'Mon YYYY') sales_month_order from DEMO_PRODUCT_INFO p, DEMO_ORDER_ITEMS oi, DEMO_ORDERS o where o.order_timestamp <= (trunc(sysdate,'MON')-1)and o.order_timestamp > (trunc(sysdate-365,'MON'))and o.order_id = oi.order_id and oi.product_id = p.product_id and p.category = 'Audio' group by to_char(o.order_timestamp,'Mon YYYY') order by sales_month_order);
    Please help.
    Regards
    Detlev

    Well,
    I've just been struggling for a couple of hours with a cluster bar chart giving the same problem.
    The problem is definitely with "ORDER BY".
    I guess the graphing chart is taking the sql query as a string and then does some other manipulation on it which ends abnormally when you include the order by clause.
    I presume that if you embed the query in a
    SELECT * FROM (<actual query with order by>)
    it might mitigate the problem.
    Bye,
    Flavio

  • LIne up Legend entries with stacked chart

    I have an appliction where on the front panel I need to display anywhere from 1 to 16 channels in a stacked waveform plot.  for ease of viewing, I would like the entries in the plot legend to line up with their respective channels in the graphs, similar to the rather crude picture i'm attaching.  The hangup in this is I need to be able to vary the number of charts displayed, 16 max, during runtime.
    In my mind, one option is to go with subpanels and have a panel setup for each number of channels i wish to display.  However, I think this would be easier if it were supported by the Waveform Chart itself.  I'm open to any and all suggestions.  Thanks!!!

    If your plot areas are that narrow you can resize the default plot legend text size to meet the size of one plot window. Like this:
    The number of plot legend lines shown can be adjusted by using Create -> Property Node -> Legend -> Number of Rows.
    Also you can select which plot will be visible/invisible in any given time by using Property Node -> Active Plot and Property Node -> Plot -> Visible combination. 
    Message Edited by Giedrius.S on 02-15-2010 06:40 PM
    Message Edited by Giedrius.S on 02-15-2010 06:45 PM
    While evaluating my code please have in mind that I am a LV novice. Therefore sometimes my code might violate some coding rules that I have to learn about myself. But how else could I do that...
    Chart zoom with "Mouse Over" effect

  • EHP4 installation - problem with stack files

    Hello all,
    I installed ERP 6.0 EHP4 ready and would like to install EHP4 with sapehpi.
    I have a problem with my XML stack files because it contains kernel 69 for all os and db.
    This stack file has been generated in the MOPZ and MOPZ don't ask me to select kernel files.
    I don't see the option Select OS/DB-dependent files in MOPZ.
    Solution Manager version is 7.01 SPS23
    What would be the solution?
    Thanks in advance.
    Best Regards,
    Olivier

    Hello Markus,
    Thanks for your answer.
    I fixed the problem by executing once again the following activity in spro. Really strange because I already did it and got the message that the activation was successfull. Anyway if someone encounter this problem, please do the following:
    1. Perform IMG activity "Configuration of Extended Functions" (IMG Activity Key: SOLMAN_MOPZ_SLM_CONF), which is delivered as of ST400 SP15.
    a) Call transaction code SPRO.
    b) Click button "SAP Reference IMG"
    c) Use CTRL+F and input "Configuration of Extended Functions" to search for the IMG activity
    Noet this: as from ST 400 SP19, use CTRL+F and input "Maintenance Optimizer" to search the IMG activity group, under this group, there is the IMG activity "Configuration".
    d) Perform it.
    e) If this IMG activity is not available due to a low support package level, see SAP Note 1090202 for manual configuration.
    Best Regards,
    Olivier

  • Problem with Stack XML file

    Hello,
    We have an ECC 6 system with EHP 4 SPS 5 and we watn to install a new Technical Usage (IS-OIL, IS-PRA and IS-UT)
    In order to do that I have to supply an xml file created by the MOPZ.
    I created a new MOPZ transaction, in the phaze "Update Options" I selected : Enhancement Package Installation,
    Afterwards I selected in Target Enhancment package stack : SAP ERP Enhanecment Package 4 on NW7.01 - SP Stack 05
    We do not want to upgrade the Stack to a latter one.
    I have selected Oil & Gas with Utilities and continued.
    The Sack XML that was created contained SAP-APPL, SAP-BASIS and SAP-ABA in patch level 8. we do not want to upgrade these components.
    Is there a way to install a new Technical Usage without upgrading these components?
    and if there is how can I create XML file suited for this situation?
    Please Advice,
    Zvi Gilinsky

    Hello,
    There is an equivalence of Support Package levels between EHP stacks and baseline ERP 6 stacks. Note 1064635 has a list of these equivalences.
    In any case, stack 5 for EHP4 of ERP should include stack 5 of NW 701.
    By your description it looks like you are having a Maintenance Optimizer issue. What is the Maintenance Optimizer stack level?
    Best regards,
    Miguel Ariñ

  • Problem with Stacked Percentage Bar

    Hello,
    We are having a lot of trouble with the Stacked Percentage Bar chart. Our chart has 2 series, one for Yes values, and one for No values. The query for each series is a PL/SQL returning a SQL query. Right now, nothing shows up on the graph. It is just an empty area. Here are the queries for the 2 series:
    YES SERIES:
    DECLARE
    tmpSQL varchar2(2000);
    BEGIN
    -- CONSTRUCT SQL STATEMENT
    tmpSQL :=
    'select null link,
    FIELD1 label,
    COUNT(' || :P23_ITEM1 || ') value
    from
    TABLE1, TABLE2
    where
    TABLE1.ID = TABLE2.ID
    AND
    (' || :P23_ITEM1 || ' = 1 ) group by '
    || :P23_ITEM1 || ', FIELD1 ';
    return tmpSQL;
    end;
    NO SERIES
    DECLARE
    tmpSQL varchar2(2000);
    BEGIN
    -- CONSTRUCT SQL STATEMENT
    tmpSQL :=
    'select null link,
    FIELD1 label,
    COUNT(' || :P23_ITEM1 || ') value
    from
    TABLE1, TABLE2
    where
    TABLE1.ID = TABLE2.ID
    AND
    (' || :P23_ITEM1 || ' = 2 ) group by '
    || :P23_ITEM1 || ', FIELD1 ';
    return tmpSQL;
    end;
    We'd appreciate any help.
    Thanks,
    Nora

    Here's my result with six values in a single series. I double clicked the last bar to change its colour from the default grey (which was visible) to magenta.
    Numbers 2.0.3, iBook G4, OS X v10.4.11
    (Shot in the dark:) Try double clicking the value label, then changing the order position of this item.
    Regards,
    Barry

Maybe you are looking for