Author: Russell Reagan
Date: 23:40:16 02/23/05
Go up one level in this thread
On February 22, 2005 at 08:35:07, Andrew Wagner wrote: >Hi all. >I got sidetracked this morning by an interesting chess programming problem. It >took me a couple hours, but I think I have a working algorithm -- haven't tested >yet though. Anyway, I got to wondering if others would approach it the same way. >So I thought I'd make a little competition of it. Post your code here, and I'll >pick the program I like best and shower praise and adulation on its author. If >people like this challenge, maybe I'll do one each month or something. Anyway, >here's the one I did this morning: >There are 64 x 63 = 4032 ways to put a black knight and white knoght both on a >chess board. Write a program -- from scratch -- to generate FENs for each of >these positions. The FENs should look something like: Nn6/8/8/8/8/8/8/8 w - - 0 >1. > >I think my code will wind up weighing in at around 60-70 lines of C. Can you do >better? Here's my attempt in 22 lines of C++ code. If you want to generate all FENs for a different piece set, just change the "Nn" string at the top of main(). I've been thinking about a solution in Python, and it might be possible in less than 10 lines of (real) code, but it's tricky and makes my brain hurt to think about it :) #include <algorithm> #include <iostream> #include <string> std::string fen (std::string s) { for (int i = 64; i >= 8; i -= 8) s.insert(i, "/"); for (;;) { size_t start = s.find_first_of("-"); size_t end = s.find_first_not_of("-", start); if (start == std::string::npos) break; s.replace(start, end - start, 1, '0' + end - start); } s.erase(s.end() - 1); return s; } int main () { std::string s = "Nn"; s.resize(64, '-'); std::sort(s.begin(), s.end()); do { std::cout << fen(s) << " w - - 0 1" << std::endl; } while (std::next_permutation(s.begin(), s.end())); return 0; }
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.