All pastes #616990 Raw Edit

FischerRandomGenerator.java

public java v1 · immutable
·published 2007-07-12 23:27 UTC
rendered paste body
public class FischerRandomGenerator{	/**	 * Generate the FEN for a Fischer Random starting position.	 * The position is formatted as a String; for example,	 * the FEN for the classical chess starting position is	 * "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"	 */	public static String fen()	{		String white = generate();		String black = white.toLowerCase();		String fen = black + "/pppppppp/8/8/8/8/PPPPPPPP/" + white + " w KQkq - 0 1";		white = null; black = null;		return fen;	}			/**	 * Generate a Fischer Random starting position.	 * The position is formatted as an all-caps String; for example,	 * the classical chess position would be "RNBQKBNR".	 */	public static String generate()	{		char[] pieces = new char[8];				//Place the dark-squared bishop		int darkBPos = (2 * rand(1, 4)) - 1; // 1, 3, 5, or 7		pieces[darkBPos - 1] = 'B';				//Place the light-squared bishop		int lightBPos = (2 * rand(1, 4)); // 2, 4, 6, or 8		pieces[lightBPos - 1] = 'B';				//Place the queen.		int queenIndex = nthNullValue(rand(1, 6), pieces);		pieces[queenIndex] = 'Q';				//Place the knights.		int knightIndex = nthNullValue(rand(1, 5), pieces);		pieces[knightIndex] = 'N';				knightIndex = nthNullValue(rand(1, 4), pieces);		pieces[knightIndex] = 'N';				//Place the a-side rook		pieces[ nthNullValue(1, pieces) ] = 'R';				//Place the king		pieces[ nthNullValue(1, pieces) ] = 'K';				//Place the h-side rook		pieces[ nthNullValue(1, pieces) ] = 'R';				//Make sure there are no more null values!		assert( nthNullValue(1, pieces) == -1 );				//Done.		return String.copyValueOf(pieces);	}		/**	 * returns a random int n such that low <= n <= high	 */	private static int rand(int low, int high)	{		if (low >= high)		{			throw new IllegalArgumentException("High must be > Low!");		}				int diff = high - low;				int n = low + ( ((int)(Math.random() * diff)) % diff );				return n;	}		/**	 * Returns the index of the nth null value in an array.	 * If there are fewer than n null values, returns -1.	 */	private static int nthNullValue(int n, char[] pieces)	{		int nullPos = -1;		int currPos = 0;				try		{			for (int count = 0; count < n; )			{				if (pieces[currPos] == 0)				{					nullPos = currPos;					count++;				}			currPos++;			}		}		catch (ArrayIndexOutOfBoundsException e) { nullPos = -1; }				return nullPos;	}		public static void main(String[] args)	{		System.out.println(fen());	}}