Help implementing a simple minimax algorithm

Okay Im making a minimax algorithm for Tic Tac Toe to try to learn some basics of it but I hit a wall
protected int winValue(int indexOne, int indexTwo)
    int[][] tempBoard = new int[3][3];
    int winValue;
    for(int i = 0; i < 3 ; i++)
      for(int b = 0; b < 3; b++)
        tempBoard[i] = ticTacToeBoard;
if(Player == false)
{tempBoard[indexOne][indexTwo] = 1;}
else if(Player == true)
{tempBoard[indexOne][indexTwo] = 2;}
for(int i = 0; i < 8; i++)
int one = tempBoard[winGameChecks[i][0][0]][winGameChecks[i][0][1]];
int two = tempBoard[winGameChecks[i][1][0]][winGameChecks[i][1][1]];
int three = tempBoard[winGameChecks[i][2][0]][winGameChecks[i][2][1]];
if(one != 0 && one == two && three == two)
Win = true;
if(Win == true)
winValue = -1;
Win = false;
else if(block(indexOne,indexTwo) == 0)
winValue = 0;
else
winValue = 1;
return winValue;
Okay
win game checks is basically all the possible wins for victory in tic tac toe
protected int[][][] winGameChecks =
        { {0,0},{0,1},{0,2} },
        { {0,0},{1,0},{2,0} },
        { {0,0},{1,1},{2,2} },
        { {0,1},{1,1},{2,1} },
        { {0,2},{1,2},{2,2} },
        { {1,0},{1,1},{1,2} },
        { {2,0},{2,1},{2,2} },
        { {2,0},{1,1},{0,2} }
  };TictacToeboard is the actual board from rows 0-2 and colums 0-2
indexOne is the row
indexTwo is the colum
This code is to determine the win value of each move, -1 for a win, 0 for a draw or block and 1 for a random move
in my head this seemed to work, but whenever I call the method, it always returns 1
and the method block is this
protected int block(int indexOne, int indexTwo)     //to determine the win value if blocking
  {                         //return 0 if the move is a block, -1 if block failed
    for(int i = 0; i < 8; i++)
      int one = ticTacToeBoard[winGameChecks[0][0]][winGameChecks[i][0][1]];
int two = ticTacToeBoard[winGameChecks[i][1][0]][winGameChecks[i][1][1]];
int three = ticTacToeBoard[winGameChecks[i][2][0]][winGameChecks[i][2][1]];
if(indexOne == three)
if(one != 0 && one == two && three == 0)
{return 0;}
else if(indexOne == one)
if(one != 0 && three == two && one == 0)
{return 0;}
else if(indexOne == two)
if(one != 0 && one == three && two == 0)
{return 0;}
return -1;
if anyone wants to read this through and help me I'd appreciate it

helped a little but now when I try to return the right node with the lowest value, it always gives a random move...
protected void minMoves()
          int winValue;
          ArrayList bestMoves = new ArrayList(0);  //TreeNode of arrays of best moves
          TreeNode temp;
          int row;
          int col;
          for(int i = 0; i < 3; i++)    //makes children with moves remaining
               for(int b = 0; b < 3; b++)
                    if(movesLeft[0] != -1 && movesLeft[0] != -1)
                    row = movesLeft[0];
                    col = movesLeft[1];
                    winValue = winValue(row, col);
                    TreeNode add = new TreeNode(row,col,winValue);
                    computer.addNode(add);
for(int i = 0; i < computer.getLength(); i++)//used for debuggin
temp = new TreeNode((TreeNode)computer);
System.out.println("Cord" + computer.getIndex(i).getRow() + " " + temp.getIndex(i).getCol());
          for(int i = 0; i < computer.getLength(); i++) //go through all the children nodes
          if(computer.getIndex(i).winValue() == -1)
          temp = computer.getIndex(i);
          bestMoves.add(temp);
          else if (computer.getIndex(i).winValue() == 0 && bestMoves.size() == 0)
          temp = computer.getIndex(i);
          bestMoves.add(temp);
          else if (computer.getIndex(i).winValue() == 1 && bestMoves.size() == 0)
          temp = computer.getIndex(i);
          bestMoves.add(temp);
          for(int i = 0; i < bestMoves.size(); i++)
          temp = new TreeNode((TreeNode)bestMoves.get(i));
          System.out.println("Cord" + temp.getRow() + " " + temp.getCol());
          //Now I have an arraylist of the best moves possible
          //Now to pick a random of the best moves.
          Random ranGen = new Random();
          int random = ranGen.nextInt(bestMoves.size());
          temp = new TreeNode((TreeNode)bestMoves.get(random));
          row = temp.getRow();
          col = temp.getCol();
          ticTacToeBoard[row][col] = 2;
          computer = new TreeNode(row, col, winValue(row, col));
          removeUsedMove(row, col);
          OutputBoard();
          //Next Players Turn
          Player = false;
Help please, my head is hurting over this

Similar Messages

  • Looking for a simple example of the Minimax algorithm in java

    Hey everyone,
    I'm currently working on a Gameboy emulator program as a pet project, and for one of the game's I'd like for the enemy AI to use the Minimax algorithm, but I don't have any experience with it (or recursion in general, for that matter). Could anyone maybe post a simple example of how this algorithm works?

    WTF? I'm sure you can find plenty of examples on google. It's on you to take the time to go through them, study them, and, if you still don't understand something, post a clear, concrete question that indicates what you read and what you didn't understand about it.
    As is, you're essentially treating folks here as your research flunkies and saying, "Give me an example that's better than all the ones already easily available to me. Read my mind to know why I didn't like them."

  • I need help reviewing my mini-max algorithm

    Hi,
    I've created a game of chess bottom up - I've been working on it for about one year now. This is a for fun project that I'm working on for pleasure, not a homework assignment or some.
    I have reached the point where I'm interested in making a computer player who makes 'smart' decisions. I read chapter 5 of the AI (Modern Approach) book, and learned how to implement the minimax algorithm. I understand conceptually how it works, and I translated the pseudo code in the book into the following listed at the bottom of the post. I made several observations:
    1) with depth of 1, the algorithm seems to choose the best 'Move' with simple end game scenarios ( i.e. mate in 1 ) when i select depth 1
    2) with a simple mate in 2 scenario, the algorithm doesn't seem to pick the best move with depth of 4 ( look two full moves ahead ).
    Can someone who is perhaps more familiar with minimax take a peek at my code and perhaps offer some suggestions as to why this may be the case? I know my implementation right now is not optimal, since I use a copy constructore to keep track of game states, as opposed to performing a move undo - however, I'm not looking to optimize the algorithm just yet. Any help is appreciated.
        public Move miniMax(Board chess_board, Player opponent, int depth) {
              long time = System.currentTimeMillis();
              examinedNodesCount = 0;
             // calculate a decision using the minimax
            ArrayList legalMoves = getPlayerLegalMoves();
            int highest_seen_value = Integer.MIN_VALUE;
            int lowest_seen_value  = Integer.MAX_VALUE;
            Move best_move = null;
            examinedNodesCount += legalMoves.size();
            for (int i = 0; i < legalMoves.size(); i++ ) {
                int value = 0;
                try {
                     Board b = new Board(chess_board);
                     Player c = new Player(this);
                     Player o = new Player(opponent);
                     Move move = new Move((Move)legalMoves.get(i));
                     c.makeMove(b, o, move);
                     System.out.print("mp: " +move);
                     value = minimaxValue(b, o, c, depth - 1, move);
                     if ( c.playerIdentity == "White") {
                          if (value > highest_seen_value) {
                               highest_seen_value = value;
                               best_move = move;
                     } else {
                        if (value < lowest_seen_value) {
                             lowest_seen_value = value;
                             best_move = move;
                } catch(Exception e){}
                System.out.println();
              time = System.currentTimeMillis() - time;
              Table.ChatPanel p = Table.getChatPanel();
              float time_per_board = (float)time /(float)examinedNodesCount;
              float boards_per_second =  (float)1000 / (float)time_per_board;
              p.writeToDisplay("INFO:\nsearch depth = " +depth+
                        "\n# examined boards: " + examinedNodesCount +
                        "\ntotal time: " +time+ " ms " +
                        "\navg time per board: " + time_per_board + " ms " +
                        "\n# boards per second: " + boards_per_second +
                        "\n move chosen: " +best_move);
            return best_move;
        private static int minimaxValue(
                  Board chess_board,
                  Player current_player,
                  Player opponent_player,
                  int depth,
                  Move m ) {
            int ret_val = 0;
             if (depth == 0 ||
                  current_player.isInCheckMate() ||
                  opponent_player.isInCheckMate()) {
                  ret_val =  Board.evaluateBoard(chess_board, current_player, opponent_player);
                  System.out.print(" with eval of: " +ret_val+ ", ");
             } else if (current_player.getIdentity() == "White") {
                ArrayList legalMoves = current_player.getPlayerLegalMoves();
                int highest_seen_value = Integer.MIN_VALUE;
                examinedNodesCount += legalMoves.size();
                for (int i = 0; i < legalMoves.size(); i++ ) {
                    int value = 0;
                    try {
                         Board b = new Board(chess_board);
                         Player c = new Player(current_player);
                         Player o = new Player(opponent_player);
                         Move move = new Move((Move)legalMoves.get(i));
                         System.out.print("\t=> " +move);
                         c.makeMove(b, o, move);
                         value = minimaxValue(b, o, c, depth - 1, move);
                        if (value > highest_seen_value) {
                            highest_seen_value = value;
                    } catch(Exception e){}
                ret_val = highest_seen_value;
            else {
                ArrayList legalMoves = current_player.getPlayerLegalMoves();
                int lowest_seen_value = Integer.MAX_VALUE;
                examinedNodesCount += legalMoves.size();
                for (int i = 0; i < legalMoves.size(); i++ ) {
                    int value = 0;
                    try {
                         Board b = new Board(chess_board);
                         Player c = new Player(current_player);
                         Player o = new Player(opponent_player);
                         Move move = new Move((Move)legalMoves.get(i));
                         System.out.print("\t=> " +move);
                         c.makeMove(b, o, move);
                         value = minimaxValue(b, o, c, depth - 1, move);
                    } catch(Exception e){}
                    if (value < lowest_seen_value) {
                         lowest_seen_value = value;     
                ret_val = lowest_seen_value;
            return ret_val;
        }

    Eek,
    I found one bug in my program, where i initialize value to 0 instead of the appropriate min or max. That might have done the trick. I'll explore with simple end game scenarios and give an update.

  • Simple encryption algorithm

    Hi there,
    Where can i find a very simple encryption algorithm to allow me to encrypt basic strings?
    It should be simple enough so i can make a version for Java and Cobol.
    Thanks for any help.

    I guess you can implement any encryption algorithm with either language. XOR should suffice... just not ROT13, it'll be a pain with EBCDIC. XOR each byte with some byte you randomly picked.

  • Simple compression algorithm / java & c++ code

    We have a java application that sends data back and forth over the internet to a c++ application. the packet sizes are small (30-250 bytes) but many packets are sent back and forth daily. we will be significantly increasing the number of clients where bandwidth utilization will noticably increase
    If anyone can point me to some code (java & c++) with employs a very simple compression algorithm, preferrably something turnkey like
    compressData(strString);
    uncompressData(strString);
    I have looked but cant find anything that is for java & c++ and what i found I dont know if it is fast enough for my purposes. it needs to be fast since each second 30-50 packets may be sent/received per application
    any recommendations or advice? thank you

    Interesting... i never considered this.... the packets are very small... in fact the 250 byte packets are when i store packets and dump them every 250ms or so. I really can't go any slower than 250ms, so 250-300bytes will cover 98% of all data
    do you know if the packet size is based upon some "standard" of tcp/ip protocol or is it configurable somehow?
    Compression isn't going to help much. I believe 250
    bytes is small enough that it will fit in one TCPIP
    packet. Making it less bytes isn't going to gain you
    much. The actual byte transmission time is going to
    be swamped by network and TCPIP overhead.

  • Help with a simple program.

    I need some help writing a simple program. Can anybody help??
    thanks to all.
    2. HTML Java Source Code Reserved Word Highlighter
    Write a program that inputs a Java source code file and outputs a copy of that file with Java keywords surrounded with HTML tags for bold type. For example this input:
    public class JavaSource
    public static void main ( String[] args )
    if ( args.length == 3 )
    new BigObject();
    else
    System.out.println("Too few arguments.");
    will be transformed into:
    <B>public</B> <B>class</B> JavaSource
    <B>public</B> <B>static</B> <B>void</B> main ( String[] args )
    <B>if</B> ( args.length == 3 )
    <B>new</B> BigObject();
    <B>else</B>
    System.out.println("Too few arguments.");
    In a browser the code will look like this:
    public class JavaSource
    public static void main ( String[] args )
    if ( args.length == 3 )
    new BigObject();
    else
    System.out.println("Too few arguments.");

    Here is something that may get you started...
    import java.io.*; 
    import java.util.*; 
    public class HtmlJava{
         public static void main(String arg[]){
              if(arg.length!=1){
                   System.out.println("Usage java HtmlJava sourceFile");       
              else
                   new HtmlJava(arg[0]);
         HtmlJava(String source){
              try{
                   BufferedReader sourceReader=new BufferedReader(new InputStreamReader(new FileInputStream(source)));
                   BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(source+"Html.txt")));  
                   Vector keywords=new Vector();
                   addKeywords(keywords);
                   String line;
                   StringTokenizer tokenizer=null;
                   String word;
                   while((line=sourceReader.readLine () )!=null){
                        tokenizer=new StringTokenizer(line);
                        while(tokenizer.hasMoreTokens()){
                             word=tokenizer.nextToken();
                             if(keywords.contains(word)){
                                  writer.write(""+word+" ");
                             else{
                                  writer.write(word+" ");
                        writer.write("\r\n");
                   writer.close();
                   sourceReader.close(); 
                   System.out.println("Output File written to "+source+"Html.txt"); 
              catch(Exception ex){
                   ex.printStackTrace();      
         private void addKeywords(Vector keywords){
              keywords.addElement ( "abstract");
              keywords.addElement( "boolean");
              keywords.addElement( "break");
              keywords.addElement( "byte");
              keywords.addElement( "byvalue");
              keywords.addElement( "case");
              keywords.addElement( "cast");
              keywords.addElement( "catch");
              keywords.addElement( "char");
              keywords.addElement( "class");
              keywords.addElement( "const");
              keywords.addElement( "continue");
              keywords.addElement( "default");
              keywords.addElement( "do");
              keywords.addElement( "double");
              keywords.addElement( "else");
              keywords.addElement( "extends");
              keywords.addElement( "false");
              keywords.addElement( "final");
              keywords.addElement( "finally");
              keywords.addElement( "float");
              keywords.addElement( "for");
              keywords.addElement( "future");
              keywords.addElement( "generic");
              keywords.addElement( "goto");
              keywords.addElement( "if");
              keywords.addElement( "implements");
              keywords.addElement( "import");
              keywords.addElement( "inner");
              keywords.addElement( "instanceof");
              keywords.addElement( "int");
              keywords.addElement( "interface");
              keywords.addElement( "long");
              keywords.addElement( "native");
              keywords.addElement( "new");
              keywords.addElement( "null");
              keywords.addElement( "operator");
              keywords.addElement( "outer");
              keywords.addElement( "package");
              keywords.addElement( "private");
              keywords.addElement( "protected");
              keywords.addElement( "public");
              keywords.addElement( "rest");
              keywords.addElement( "return");
              keywords.addElement( "short");
              keywords.addElement( "static");
              keywords.addElement( "super");
              keywords.addElement( "switch");
              keywords.addElement( "synchronized");
              keywords.addElement( "this");
              keywords.addElement( "throw");
              keywords.addElement( "throws");
              keywords.addElement( "transient");
              keywords.addElement( "true");
              keywords.addElement( "try");
              keywords.addElement( "var");
              keywords.addElement( "void");
              keywords.addElement( "volatile");
              keywords.addElement( "while");
    }Hope it helped

  • Need help to find a CRC16 algorithm (according to ISO14443-A)

    Hello,
    Could anyone help me find a description or implementation of the crc algorithm according to ISO-14443-A or ITU-T V.41)
    Regards LnP

    I stumbled on this month-old discussion of using Corel Draw to make fonts, and thought of Adobe Illustrator's little-known ability to behave similarly via the evolving technology of SING glyphlets. Like Corel's Save-As-TTF feature, this only works for one glyph at a time -- not surprising as the idea behind SING glyphlets is to add a few characters to an existing font. The fly in the ointment is that for now this only works for recent East Asian versions. The process is the subject of a demonstration (in English and Chinese) over on the CCJK Type blog
    where I commented that non-CCJK folks would also like to try this out.
    David

  • How to implement a simple node-edge graph?

    Can any one give me some advice on how to implement a simple node-edge graph in a frame? Every node is a rectangle which can be moved by mouse, and every edge is a arc between two nodes.
    Should the node class extend JPanel, and the edge class extend Graphics? and so on?

    It is impossible to generate similar update from OWB.
    Does your table1 contain primary key columns? What is the number of rows in this table?
    The only working solution in this case - use table1 twice in mapping - as source and as target (with UPDATE operation),
    link these operators with primary key columns and specify matching by PK columns.
    Updated column link to Constant operator attribute.
    In this case OWB generate SQL like
    merge table1 a
    using table1 b
    on (a.pk_column=b.pk_column)
    when matched then update set column1=1
    Regards,
    Oleg

  • Help implementing scenario

    Hi again,
    I need help implementing the next scenario (simplified):
    - One material can have N discounts.
    - On ODS A I have 'Material' and 'Customer' as characteristics and 'Amount of the sell' as ratio.
    - On ODS B I have 'Material' and 'Discount Type' as characteristics and 'Amount of discount' as ratio.
    I'm using a MultiProvider for the queries that needs the detail of the discounts.
    How can I create a query that shows the Amount of sell for materials that have discount of type '3' ?
    If i use a filter for discount type '3' I won't get any amount of sell.
    thanks in advance

    Hi Juan,
    you can use a prequery for your problem. That means, you use a Query to fill a variable.
    Build a Query A with material in the rows and a filter with 'Discount Type' = '3'.
    Then define a variable for material with the option for 'processing by' = 'Replacement path'. fill out the other fields and press next. Here select for Query the before defined Query A. now next and finish.
    The last step is to define the query with material and Amount of sells. In this query use the defined variable for material.
    That's it.
    Hope the english is understandable.
    regards
    Alex

  • Pls i need help for this simple problem. i appreciate if somebody would share thier ideas..

    pls i need help for this simple problem of my palm os zire 72. pls share your ideas with me.... i tried to connect my palm os zire72 in my  desktop computer using my usb cable but i can't see it in my computer.. my palm has no problem and it works well. the only problem is that, my  desktop computer can't find my palm when i tried to connect it using usb cable. is thier any certain driver or installer needed for it so that i can view my files in my palm using the computer. where i can download its driver? is there somebody can help me for this problem? just email me pls at [email protected] i really accept any suggestions for this problem. thanks for your help...

    If you are using Windows Vista go to All Programs/Palm and click on the folder and select Hot Sync Manager and then try to sync with the USB cable. If you are using the Windows XP go to Start/Programs/Palm/Hot Sync Manager and then try to sync. If you don’t have the palm folder at all on your PC you have to install it. Here is the link http://kb.palm.com/wps/portal/kb/common/article/33219_en.html that version 4.2.1 will be working for your device Zire 72.

  • Need urgent help in Real Time scheduling algorithm implementation

    I am new to Java Real Time programming. I have faced a problem which is stated below:
    Declare tasks
    for
    if it is schedulable then run the task
    otherwise it is not schedulable
    for
    check priority with respect to deadline.
    select highest priority task
    for
    start higest priority task
    if the task is preemtable
    then switch lowest priority task to highest priority task and stop the lowest priority task
    after completion higest priority task, lowest priority task complete the rest of the work.
    this is actually a pseudocode for real time dynamic scheduling ( rate monotonic scheduling). can anyone please help me develop the code?

    PrinceOfLight wrote:
    I am new to Java Real Time programming.
    this is actually a pseudocode for real time dynamic scheduling Define "real-time" in your context. Most people who use the term don't use it correctly. If you truly mean "real-time," then you'll need real-time Java running on a real-time OS.
    can anyone please help me develop the code?What specific problems are you having? If you have no clue where to start, this site is not a good resource.

  • Drawing and some layout help for a simple control: thin lines and application start

    I am trying to create a new, simple control. The control should act as a grouping marker much like that found in the Mathematica notebook interface. It is designed to sit to the right of a node and draw a simple bracket. The look of the bracket changes depending on whether the node is logically marked open or closed.
    After looking at some blogs and searching, I tried setting the snapToPixels to true in the container holding the marker control as well as the strokewidth but I am still finding that the bracket line is too thick. I am trying to draw a thin line. Also, I am unable to get the layout to work when the test application is first opened. One of the outer brackets is cut-off. I hardcoded some numbers into the skin just to get something to work.
    Is there a better way to implement this control?
    How can I get the fine line drawn as well as the layout correct at application start?
    package org.notebook;
    import javafx.beans.property.BooleanProperty;
    import javafx.beans.property.IntegerProperty;
    import javafx.beans.property.SimpleBooleanProperty;
    import javafx.beans.property.SimpleIntegerProperty;
    import javafx.scene.control.Control;
    * Provide a simple and thin bracket that changes
    * it appearance based on whether its closed or open.
    public class GroupingMarker extends Control {
      private final static String DEFAULT_STYLE_CLASS = "grouping-marker";
      private BooleanProperty open;
      private IntegerProperty depth;
      public BooleanProperty openProperty() { return open; }
      public IntegerProperty depthProperty() { return depth; }
      public GroupingMarker(boolean open) {
      this();
      setOpen(open);
      public GroupingMarker() {
      open = new SimpleBooleanProperty(true);
      depth = new SimpleIntegerProperty(0);
      getStyleClass().add(DEFAULT_STYLE_CLASS);
      // TODO: Change to use CSS directly
      setSkin(new GroupingMarkerSkin(this));
      public boolean isOpen() {
      return open.get();
      public void setOpen(boolean flag) {
      open.set(flag);
      public int getDepth() {
      return depth.get();
      public void setDepth(int depth) {
      this.depth.set(depth);
    package org.notebook;
    import javafx.scene.Group;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.FillRule;
    import javafx.scene.shape.LineTo;
    import javafx.scene.shape.MoveTo;
    import javafx.scene.shape.Path;
    import com.sun.javafx.scene.control.skin.SkinBase;
    * The skin draws some simple lines on the right hand side of
    * the control. The lines reflect whether the control is considered
    * open or closed. Since there is no content, there is no
    * content handling code needed.
    public class GroupingMarkerSkin extends SkinBase<GroupingMarker, GroupingMarkerBehavior> {
      GroupingMarker control;
      Color lineColor;
      double shelfLength;
      double thickness;
      private Group lines;
      public GroupingMarkerSkin(GroupingMarker control) {
      super(control, new GroupingMarkerBehavior(control));
      this.control = control;
      lineColor = Color.BLUE;
      shelfLength = 5.0;
      thickness = 1.0;
      init();
      * Attached listeners to the properties in the control.
      protected void init() {
      registerChangeListener(control.openProperty(), "OPEN");
      registerChangeListener(control.depthProperty(), "DEPTH");
      lines = new Group();
      repaint();
      @Override
      protected void handleControlPropertyChanged(String arg0) {
      super.handleControlPropertyChanged(arg0);
        @Override public final GroupingMarker getSkinnable() {
            return control;
        @Override public final void dispose() {
        super.dispose();
            control = null;
        @Override
        protected double computePrefHeight(double arg0) {
        System.out.println("ph: " + arg0);
        return super.computePrefHeight(arg0);
        @Override
        protected double computePrefWidth(double arg0) {
        System.out.println("pw: " + arg0);
        return super.computePrefWidth(40.0);
         * Call this if a property changes that affects the visible
         * control.
        public void repaint() {
        requestLayout();
        @Override
        protected void layoutChildren() {
        if(control.getScene() != null) {
        drawLines();
        getChildren().setAll(lines);
        super.layoutChildren();
        protected void drawLines() {
        lines.getChildren().clear();
        System.out.println("bounds local: " + control.getBoundsInLocal());
        System.out.println("bounds parent: " + control.getBoundsInParent());
        System.out.println("bounds layout: " + control.getLayoutBounds());
        System.out.println("pref wxh: " + control.getPrefWidth() + "x" + control.getPrefHeight());
        double width = Math.max(0, 20.0 - 2 * 2.0);
        double height = control.getPrefHeight() - 4.0;
        height = Math.max(0, control.getBoundsInLocal().getHeight()-4.0);
        System.out.println("w: " + width + ", h: " + height);
        double margin = 4.0;
        final Path VERTICAL = new Path();
        VERTICAL.setFillRule(FillRule.EVEN_ODD);
        VERTICAL.getElements().add(new MoveTo(margin, margin)); // start
        VERTICAL.getElements().add(new LineTo(margin + shelfLength, margin)); // top horz line
        VERTICAL.getElements().add(new LineTo(margin + shelfLength, height - margin)); // vert line
        if(control.isOpen()) {
        VERTICAL.getElements().add(new LineTo(margin, height - margin)); // bottom horz line
        } else {
        VERTICAL.getElements().add(new LineTo(margin, height-margin-4.0));
        //VERTICAL.getElements().add(new ClosePath());
        VERTICAL.setStrokeWidth(thickness);
        VERTICAL.setStroke(lineColor);
        lines.getChildren().addAll(VERTICAL);
        lines.setCache(true);
    package org.notebook;
    import com.sun.javafx.scene.control.behavior.BehaviorBase;
    public class GroupingMarkerBehavior extends BehaviorBase<GroupingMarker> {
      public GroupingMarkerBehavior(final GroupingMarker control) {
      super(control);
    package org.notebook;
    import javafx.application.Application;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextArea;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    public class TestGroupingMarker extends Application {
      public static void main(String args[]) {
      launch(TestGroupingMarker.class, args);
      @Override
      public void start(Stage stage) throws Exception {
      VBox vbox = new VBox();
      BorderPane p = new BorderPane();
      VBox first = new VBox();
      first.getChildren().add(makeEntry("In[1]=", "my label", 200.0, true));
      first.getChildren().add(makeEntry("Out[1]=", "the output!", 200.0, true));
      p.setCenter(first);
      p.setRight(new GroupingMarker(true));
      vbox.getChildren().add(p);
      vbox.getChildren().add(makeEntry("In[2]=", "my label 2", 100.0, false));
      Scene scene = new Scene(vbox,500,700);
      scene.getStylesheets().add(TestGroupingMarker.class.getResource("main.css").toExternalForm());
      stage.setScene(scene);
      stage.setTitle("GroupingMarker test");
      stage.show();
      protected Node makeEntry(String io, String text, double height, boolean open) {
      BorderPane pane2 = new BorderPane();
      pane2.setSnapToPixel(true);
      Label label2 = new Label(io);
      label2.getStyleClass().add("io-label");
      pane2.setLeft(label2);
      TextArea area2 = new TextArea(text);
      area2.getStyleClass().add("io-content");
      area2.setPrefHeight(height);
      pane2.setCenter(area2);
      GroupingMarker marker2 = new GroupingMarker();
      marker2.setOpen(open);
      pane2.setRight(marker2);
      return pane2;

    The test interfaces are already defined for you - the 3rd party session bean remote/local interfaces.
    It is pretty trivial to create implementations of those interfaces to return the test data from your XML files.
    There are a number of ways to handle the switching, if you have used the service locator pattern, then I would personally slot the logic in to the service locator, to either look up the 3rd party bean or return a POJO test implementation of the interface according to configuration.
    Without the service locator, you are forced to do a little more work, you will have to implement your own test session beans to the same interfaces as the 3rd party session beans.
    You can then either deploy them instead of the 3rd party beans or you can deploy both the test and the 3rd party beans under different JNDI names,and use ejb-ref tags and allow you to switch between test and real versions by changing the ejb-link value.
    Hope this helps.
    Bob B.

  • Implementation of depth-first algorithm

    Hi, I am trying to implement depth-first algorithm.(directed graph, no loops). Here what I have so far.
    //form a one-element stack with the root node.
    Stack st=new st();
    boolean goalflg=false;
    st.push(?)//do I need to clone the value from the tree, if yes, how can I do this? Should it be a Spanning Tree or not?
    //repeat until the first path in the stack terminates at the goal node or the stack is empty
    while(st.size()!=null || goalflg == true){  
    /*-remove the first math from the Stack;create new paths by extending the first path to all neighbors of the terminal node * /
    int temp=st.pop();
    nodeRight=tree.goRight();// I aren't sure nodeLeft=tree.goLeft();
    //reject all new paths with loops (how can I do this?)
    //if the goal is found-success, else -failure     
    if (temp==goalNode)     
    {goalflg=true;}     
    else{        //add the new paths to the front of stack      
    st.push(nodeRight);
    st.push(nodeLeft);     
    Please,please help!
    Sincerely,
    Byryndyk
    P.S. I check out google, but it has mostly the theory about this method. What I am interested is how to make it alive.

    This algorithm for DFS has no constraints on edges as it works purely by inspecting adjacency lists; if a directed edge, e, goes from vertex u to vertex v, then v is adjacent to u, but u is not adjacent to v i.e. you can not travel this edge from v to u.
         public VertexModelInterface[] depthFirstSearch(VertexModelInterface from)
              visited.add(from);
              VertexModelInterface[] adjacencyList = (VertexModelInterface[]) from.getAdjacencyList().toArray(new VertexModelInterface[0]);
              for (int index = 0; index < adjacencyList.length; index++)
                   if (!visited.contains(adjacencyList[index]))
                        depthFirstSearch(adjacencyList[index]);
                   } // end if
              } // end for
              return (VertexModelInterface[]) visited.toArray(new VertexModelInterface[0]);
         } // end depthFirstSearch
    visited is a list containing vertices. Each vertex has an adjacency list containing references to adjacent vertices.
    Hope this helps anyone whos looking for a neat recursive (implicit stack) implementation. I also have implementations for BFS, Cut-Edge-Detection and Fleury's algorithm.
    Kind regards,
    Darren Bishop.
    [email protected]

  • How to implement a simple paragraph system in CQ

    Hi,
    I have some problems in implementing a paragraph system in CQ.
    I have to implement it in CQ 4.2.
    Does any one explain it to me in simple words?
    Thanks a lot in advance, Seboeh

    I found the solution.
    I could implement a paragraph system now.
    I shortly describe the most important things.
    1. the spooler script should not have any carriage return
    2. for a component the spooling works only with following link.
    <img src='<% cc.getPage().getHandle() + ".spool." + cc.getQualident() + ".jsp" %>' width=200px>
    Further on, in the "Component Definitions" for this script only "spool" should be written as globbing. Not "*spool" or "spool*".
    This is also the reason, why we have cc.getQualident() after spool in the img-tag.
    3. Further on it is important for a paragraph system to include the following initialization.
    <%
    Style actstyle = null;
    %>
    <cfc:initComponent cellId="body" componentId="/libs/Components/body">
    <% actstyle = componentContext.getStyle(); %>
    </cfc:initComponent>
    <cfc:includeComponent cellId="body" componentId="/libs/Components/body" />
    <cfc:includeComponent cellId="parsys"
                            componentId="/apps/emb/Components/parsys" />
    4. in side the spooler script, you get the atom by:
                            String[] selectors = cqReq.getSelectors();
                            String qualident = selectors[1] + "." + selectors[2];
                            Container local = (Container) actpage.getElement(qualident);
                          Atom atom = local.getAtom("myImageSrc");
    where "myImageSrc" is the atom.xml content definition.
    The selcorts[2] is either "Single" or somthing like "parsys.0001".
    5. In simple components, you need also this kind of code to initialize a edit bar.
    <%
    ComponentContext cc = (ComponentContext) request.getAttribute("componentContext");
    ComponentInfo ci = cc.getComponentInfo();
    %>
    <cfc:editbar
                            parName="<%= cc.getContainerList() %>"
                            parNum="<%= cc.getContainerLabel() %>"
                            storagePre="<%= cc.getStoragePre() %>"
                            dialogAny="<%= ci.getContentDialog() %>"
    />
    I hope this could help you creating the paragraph system.
    Kind regards, [email protected]

  • Kindly help me out with viterbi algorithm coding....

    Hi everybody,
    V r doing a project on Spread Spectrum image steganography. One of our module is Low Rate ECC.We plan to do it using convolutional codes using viterbi algorithm.we have a problem in implementing it.Please help me out with the coding .

    U would also be requiring Diagram.java
    import java.awt.Color;
    import java.awt.Graphics;
    class Diagram
    Diagram()
    competitors = new int[20][27];
    Letters = "abcdefghijklmnopqrstuvwxyz";
    status = "";
    x = 10;
    y = 70;
    no_letters = 0;
    word_viable = true;
    int[] Get_survivors(String s, int i)
    int ai[] = new int[27];
    float af[][] = Read_prob.reading_bigrams();
    float af1[][] = Read_prob.reading_conf_matrix(i);
    float af2[][] = new float[27][27];
    float af3[][] = new float[27][27];
    int ai1[][] = new int[27][27];
    float af4[] = new float[27];
    for(int l = 0; l < 27; l++)
    af3[0][l] = 0.0F;
    af4[l] = 100000F;
    ai[l] = 0;
    int k = s.length();
    int j = s.charAt(0) - 96;
    if(j < 0)
    j += 32;
    for(int i1 = 1; i1 < 27; i1++)
    af3[0][i1] = -(af[27][i1] + af1[j][i1]);
    float f = 100000F;
    for(int j1 = 1; j1 < k; j1++)
    j = s.charAt(j1) - 96;
    if(j < 0)
    j += 32;
    for(int k1 = 1; k1 < 27; k1++)
    for(int i2 = 1; i2 < 27; i2++)
    af2[k1][i2] = af3[j1 - 1][i2] - (af[i2][k1] + af1[j][k1]);
    if(af2[k1][i2] < af4[k1])
    af4[k1] = af2[k1][i2];
    ai1[j1 - 1][k1] = i2;
    for(int j2 = 1; j2 < 27; j2++)
    af3[j1][j2] = af4[j2];
    af4[j2] = 100000F;
    for(int l1 = 1; l1 < 27; l1++)
    af2[k][l1] = af3[k - 1][l1] - af[l1][27];
    if(af2[k][l1] < f)
    f = af2[k][l1];
    ai[k - 1] = l1;
    j = ai[k - 1];
    for(int k2 = k - 2; k2 >= 0; k2--)
    ai[k2] = ai1[k2][j];
    j = ai[k2];
    Sort_q(af3, k);
    return ai;
    void Sort_q(float af[][], int i)
    boolean flag = false;
    int j = 0;
    float f = 100000F;
    for(int k = 0; k < i; k++)
    for(int l = 0; l < 10; l++)
    for(int i1 = 1; i1 < 27; i1++)
    if(af[k][i1] < f)
    f = af[k][i1];
    j = i1;
    competitors[k][l] = j;
    af[k][j] = 100000F;
    f = 100000F;
    void Table(Graphics g, int i, String s)
    int ai[] = Get_survivors(s, i);
    int ai1[] = new int[20];
    int ai2[] = new int[20];
    no_letters = s.length();
    x = 500 / no_letters - no_letters;
    for(int j1 = 0; j1 < no_letters; j1++)
    x += 35;
    y = 80;
    int l = x;
    int i1 = y;
    boolean flag = false;
    g.setColor(Color.red);
    int j = s.charAt(j1) - 97;
    if(j < 0)
    j += 32;
    g.drawChars(Survivor, j, 1, x + 5, y + 11);
    g.setColor(Color.blue);
    g.drawRect(x, y, 16, 14);
    y += 17;
    for(int k1 = 0; k1 < 10; k1++)
    int k = competitors[j1][k1];
    if(word_viable)
    g.setColor(Color.green);
    g.drawRect(x, y, 16, 14);
    g.setColor(Color.red);
    g.drawChars(Survivor, k - 1, 1, x + 5, y + 11);
    if(k == ai[j1])
    flag = true;
    if(k == j + 1)
    ai1[j1] = l + 17;
    ai2[j1] = i1 + 7;
    } else
    g.setColor(Color.blue);
    g.drawRect(x, y, 16, 14);
    g.setColor(Color.green);
    g.drawRect(l, i1, 16, 14);
    ai1[j1] = x + 17;
    ai2[j1] = y + 7;
    } else
    if(!flag)
    ai1[j1] = l + 17;
    ai2[j1] = i1 + 7;
    y += 17;
    for(int l1 = 0; l1 < no_letters - 1; l1++)
    g.setColor(Color.blue);
    g.drawLine(ai1[l1], ai2[l1], ai1[l1 + 1] - 18, ai2[l1 + 1]);
    g.drawChars(Survivor, ai[l1] - 1, 1, ai1[l1] - 12, y + 17);
    g.drawChars(Survivor, ai[no_letters - 1] - 1, 1, ai1[no_letters - 1] - 12, y + 17);
    void Trellis(Graphics g, int i, String s)
    int ai[] = Get_survivors(s, i);
    int ai1[] = new int[20];
    int ai2[] = new int[20];
    no_letters = s.length();
    x = 500 / no_letters;
    for(int k = 0; k < no_letters; k++)
    x += 35;
    y = 60;
    for(int l = 0; l < 26; l++)
    g.setColor(Color.green);
    if(word_viable)
    int j = Survivor[l] - 96;
    if(ai[k] == j)
    g.setColor(Color.blue);
    ai1[k] = x + 17;
    ai2[k] = y + 7;
    g.drawRect(x, y, 16, 14);
    g.setColor(Color.red);
    g.drawChars(Survivor, l, 1, x + 5, y + 11);
    y += 17;
    for(int i1 = 0; i1 < no_letters - 1; i1++)
    g.setColor(Color.blue);
    g.drawLine(ai1[i1], ai2[i1], ai1[i1 + 1] - 18, ai2[i1 + 1]);
    g.drawChars(Survivor, ai[i1] - 1, 1, ai1[i1] - 12, y + 17);
    g.drawChars(Survivor, ai[no_letters - 1] - 1, 1, ai1[no_letters - 1] - 12, y + 17);
    void delete()
    for(int i = 0; i < no_letters; i++);
    public String status;
    public int competitors[][];
    public String Letters;
    public char Survivor[] = {
    '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', 'z'
    public int x;
    public int y;
    public boolean word_viable;
    public int no_letters;
    private Read_prob r_prob;
    }

Maybe you are looking for

  • Links list to open in new tab

    I have created a links list and added that webpart to a page in office 365 for sharepoint. When the user clicks on a links it needs to be opened in new tab how to impletement. I tried with javascript content editor webpart but it is removing  the  sc

  • Large Set of Rows - Performance

    Hello all. We do have a report (Apex 3.2), where if no filter is defined, loads about 60.000 lines. Running the same query on sqlplus or Sql Developer, the performance is acceptable, but on Apex, it takes several minutes, causing some users to abort

  • IPod update timing out?!

    For the last week since the iOS 4.2 update came out, I've tried downloading it with no success; the file does not process or verify, the network connection times out (Error code is -3259) when the file is totally completed, according to iTunes (missi

  • Select for update timing out

    Hi there when I do a simple select statement like select * from table I recieve all the records without a problem when I add 'for update' like select * from table for update this seems to take a long time (I don't actually get a result) Is there some

  • Problem connecting to two different databases from form

    Hi all, i am using 6i forms which needs to be connected to oracle 9i and 10g databases which is having different ip address(residing in different machines).i can connect to 10g database after configuring tnsnames.ora in my machine but still i cannot