|
28.10.2006, 16:40 | #1 |
Участник
|
Dynamics AX Geek: Using lists & listIterators - 8 queens example
Источник: http://AxGeek.spaces.live.com/Blog/c...DB13!147.entry
============== <div><div>I am not using lists a lot, because I find it too restrictive not to be able to move back in the list. Also, I find it annoying that end() moves beyond the last element, not to the last element. Nevertheless, there are some uses for lists and I want to give an example how it can be used. The example is a puzzle: How do you place eight queens on a chessboard, so they can not beat each other? The algorithm below is a brute force approach to the problem: Find a place for the next queen, place it. If it was the 8th queen, save solution. If the queen could not be placed, undo last move, try next possible field and so forth. The problem can be solved nicely using iteration or recursion. I like recursion. I am using two lists. The first one is for the current solution. All placed queens are placed in this list. It basically is a simple stack. All elements are added to the start of the list. To undo a move, the first element is deleted. The second list is a list of lists, a list of all solutions that worked out. To access the contents you need an iterator similar to sets and maps. You can see those in the last block, when solutions are output via the infolog. static void eightQueens(Args _args) { int board[64]; int found; str solution; list listAllSolution = new list(types::Class); list listOneSolution = new list(types::String); listIterator li_OneSolution = new listIterator(listOneSolution); listIterator li_AllSolution = new listIterator(listAllSolution); int board(int _row, int _col, int _upd = 0) { if (_row < 1 || _row > 8 || _col < 1 || _col > 8) return -1; else board[(_row-1)*8+_col] += _upd; return board[(_row-1)*8+_col]; } void updateBoard(int _row, int _col, int _upd) { int i; ; <font face="Courier New" size=2><span lang=DA style="font-size:10pt;font-family:'Courier New'"> for (i=1;i |
|