r/dailyprogrammer • u/jnazario 2 0 • Aug 05 '15
[2015-08-05] Challenge #226 [Intermediate] Connect Four
** EDITED ** Corrected the challenge output (my bad), verified with solutions from /u/Hells_Bell10 and /u/mdskrzypczyk
Description
Connect Four is a two-player connection game in which the players first choose a color and then take turns dropping colored discs (like checkers) from the top into a seven-column, six-row vertically suspended grid. The pieces fall straight down, occupying the next available space within the column. The objective of the game is to connect four of one's own discs of the same color next to each other vertically, horizontally, or diagonally before your opponent.
A fun discourse on winning strategies at Connect Four is found here http://www.pomakis.com/c4/expert_play.html .
In this challenge you'll be given a set of game moves and then be asked to figure out who won and when (there are more moves than needed). You should safely assume that all moves should be valid (e.g. no more than 6 per column).
For sake of consistency, this is how we'll organize the board, rows as numbers 1-6 descending and columns as letters a-g. This was chosen to make the first moves in row 1.
a b c d e f g
6 . . . . . . .
5 . . . . . . .
4 . . . . . . .
3 . . . . . . .
2 . . . . . . .
1 . . . . . . .
Input Description
You'll be given a game with a list of moves. Moves will be given by column only (gotta make this challenging somehow). We'll call the players X and O, with X going first using columns designated with an uppercase letter and O going second and moves designated with the lowercase letter of the column they chose.
C d
D d
D b
C f
C c
B a
A d
G e
E g
Output Description
Your program should output the player ID who won, what move they won, and what final position (column and row) won. Optionally list the four pieces they used to win.
X won at move 7 (with A2 B2 C2 D2)
Challenge Input
D d
D c
C c
C c
G f
F d
F f
D f
A a
E b
E e
B g
G g
B a
Challenge Output
O won at move 11 (with c1 d2 e3 f4)
5
u/dohaqatar7 1 1 Aug 05 '15
Can we assume that all moves are valid? Specifically, will the column always match [a-gA-G] and will there always be no more than 6 pieces put in a single collumn?
2
u/curtmack Aug 05 '15 edited Aug 05 '15
Haskell
Why focus around the last-played piece when scanning every possible four-in-a-row takes less than a millisecond anyway?
Fun fact: There are exactly 69 possible four-in-a-rows on a standard Connect 4 board.
Challenge output:
Edit: Fixed move numbering.
Edit 2: Added description
Edit 3: Changed four-in-a-rows to be tuples instead of lists for more type safety, and fixed ⤡ diagonals not being detected.
13
u/skeeto -9 8 Aug 05 '15 edited Aug 05 '15
C, using a bitboard. It checks for the winning condition in parallel across the entire board. Because of this, I don't output the winning slots because the bitboard doesn't actually compute which slots won, only testing if there are 4 consecutive bits.
Each player gets a bitboard (see layout below). The right-hand gutter breaks apart consecutive bits spanning rows, making the bit tests simpler. The initial value has the out-of-bounds bits set so that starting moves have existing bits to fall "against."
Edit: In retrospect, perhaps I should have gone column-major order. This would allow the use of a bsr/clz instruction in
move()so that all game state operations are always constant time, O(1).1
u/jnazario 2 0 Aug 05 '15
here's a random game maker for you to use in testing if you wish.
4
u/fvandepitte 0 0 Aug 05 '15 edited Aug 05 '15
C++,
not happy about the result, it takes why too long to calculate the result, might try again this evening.Results are instantaneous now. Not needing to search trough a grid made it a lot easier and a lot faster. Plus now I know what cells where the winning ones.
Feedback still apriciated
4
u/theonezero Aug 05 '15
Python solution. Checking for a winner works by starting at the newly placed piece and looking forward and backward each of the 4 directions (horizontal, vertical, 2 diagonals) to try and find a sequence of 4.
Output
1
u/mdskrzypczyk Aug 05 '15 edited Aug 06 '15
1
u/Hells_Bell10 Aug 05 '15 edited Aug 05 '15
C++ *edit - cleanup & handled middle insert properly
3
u/Godspiral 3 3 Aug 05 '15 edited Aug 05 '15
in J,
the input 'a' is converted to a pair of column indexes (0 based) that is each player's moves. A 1 or 2 is placed in respective column based on those moves. Player 1 win condition is checked first, so that it will be first printout in case 2 winners occur on same move. Even if a winner is found, all moves are made, and winners announced repeatedly.
Player 1 wins
Player 1 wins
Player 1 wins
To find the move number of winner, count the number of announcements. Player1 had won after the last 3 moves.
for 2nd challenge there is no winner. player 2 has e3
with edited 2nd challenge
Player 2 wins
Player 2 wins
Player 2 wins
Player 2 wins
3
u/cbarrick Aug 06 '15 edited Aug 06 '15
Prolog
Edit: Updated to be way cooler
Solves the problem as a constraint satisfaction problem using reification.
I create a 6x7 grid of constraint satisfaction variables in the domain {0,1}. 0 means player X played in that cell, and likewise 1 means player O played in that cell. Then I create a new constraint satisfaction variable called Winner, also in the domain {0,1}. I constrain Winner such that having four of a kind in a row, column, or diagonal forces it to become that kind. Finally I apply moves until Winner is forced to take a specific value.
It's not necessarily the fastest way to solve this problem. But if I wanted to create an AI to play connect four, this kind of reasoning would be super useful.
The coolest part of the code is definitely this:
Full Program:
3
u/[deleted] Aug 06 '15 edited Aug 06 '15
I decided to do a full visual simulation with HTML canvases and Javascript; the simulation ends as soon as somebody wins.
2
u/glenbolake 2 0 Aug 05 '15
Python 2.7. Very similar approach to /u/theonezero's version. I also print out the final board.
Output:
2
u/dohaqatar7 1 1 Aug 05 '15
Haskell
I used Haskell's State monad to encapsulate the state of the game. All the state logic turned out to be less complicated than I expected but the real annoying part was checking of the games has been won.
2
u/zdveloper Aug 05 '15
package challenge226;
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List;
public class Main {
}
2
u/Zeno_of_Elea Aug 06 '15 edited Aug 06 '15
I've spent an incredible amount of time getting nowhere trying to figure out how to detect diagonal wins in a short amount of code, so here's my solution for horizontal and vertical wins. I've tried to golf it some, but I'm sure it can be golfed more.
Input must be in a string [edited from "one line," a false statement], with moves separated by whitespace characters. Turns do not need to be separated in any particular way. The code outputs the winner, move it won on, row, and then column of the winning move and nothing if there was no victory.
Input followed by output (no challenge input yet):
2
u/FrankRuben Aug 22 '15
Late to the party, but ABAP should be quite rare - and I had to wait for vacation.
ABAP
2
u/Shenkie18 Oct 13 '15 edited Oct 13 '15
Thanks to /u/skeeto I used bitboards as well. Doesn't output the list of the four winning pieces unfortunately.
1
u/[deleted] Aug 05 '15 edited Aug 05 '15
Java. The program prints current state of the board as you type in subsequent moves. It's a little rudimentary, but as long as your input is fairly correct, it should be fine. Also, checking for diagonals ;__;
http://pastebin.com/MKhupyyG
Sample outputs (EDIT: Challenge #2 fix):
http://pastebin.com/Vy3MwNg2
http://pastebin.com/4FCExn1K
1
u/Hiderow Aug 05 '15
C++
Only checks pieces adjacent to the one that was placed last. Takes no noticable time to run. I didn't sort the order of the output.
1
u/HereBehindMyWall Aug 05 '15 edited Aug 05 '15
Python 3 with wholly unnecessary use of co-routines (if that's the right term...)
We don't record the states of individual squares (although we do monitor the heights of each column). Instead, at the very beginning we make a 'dictionary of lines' sending each square to the 'lines' containing it, where each 'line' is actually co-routine counting up how many X's and O's are present.
When a player moves in a particular square, we look up the correponding co-routines and tell each of them to update their totals. If any of the totals hits 4 then the jig is up.
1
u/TornJK Aug 05 '15
Quick and dirty C# Code
1
u/Wiggledan Aug 05 '15
C99. The hardest part was detecting diagonal wins, which I ended up "hard-coding" in. I was trying to make it work for any board size, but I couldn't figure out a good way to do that when checking diagonal lines.
1
u/narcodis Aug 05 '15 edited Aug 05 '15
Java. After dropping a piece (which was surprisingly intuitive), checks every piece on the board for every possible solution, using said piece as the "root" of the sequence of four. Still runs about instantaneously, only because the board is so small. If this were a board of, say, 1000x1000, I doubt it'd be able to run in a reasonable amount of time without a bit of optimization.
Code is kinda all over the place... any feedback would be welcome.
EDIT: added some comments, decided to remove all uses of libraries.
1
u/Godd2 Aug 05 '15
Here's mine in Ruby:
1
u/[deleted] Aug 05 '15 edited Jan 02 '16
1
u/a_Happy_Tiny_Bunny Aug 05 '15 edited Aug 05 '15
Haskell
First time I've used the state monad or state arrays. Surprisingly easy to use after the initial pitfalls.
I think the code is pretty readable, with maybe the exception of some types which I might choose to alias at a later time if I revise my code.
I didn't explicitly try to make the code safe, but it should deal with some kinds of unexpected input (e.g. ignore moves to non-existing columns, or output that no one won if such is the case).
Feedback is appreciated and questions are welcome.
1
u/TheSageMage Aug 06 '15 edited Aug 06 '15
Java solution: https://gist.github.com/NicholasAStuart/38479e3e3cf28366e099
I tried to keep it as abstract as possible, in terms of how long the board can be, so since no row/columns are hard coded, it should be able to handle any arbitrarly board size. I was also able to make it take in a winning size, so for this it's connect four, but if you change the input variable, it could be connect 3, or connect 5.
I wanted to make it such that the connections needed to win was variable too, but I couldn't think straight, so I just hardcoded the patterns since that made more sense.1
u/porkminer Aug 06 '15
In C#. No need to be kind, I'm not a professional.
https://gist.github.com/porkminer/3736e7c56a7718c9f282
Needs to be cleaned up
1
u/carrutstick Aug 06 '15
Haskell
A little late to the party, but I thought this would be a good opportunity to practice using the
STmonad, avoiding rebuilding the board after every move. I dofreezethe board after each move to check my win condition, so I'm not sure whether GHC ends up copying the array anyway, or if it can deduce that I finish all my reads before I start writing to the array again. Of course it also wouldn't be hard to check the win condition inside the monad, but that's just not how I did it for some reason.1
u/[deleted] Aug 06 '15 edited Aug 06 '15
Java
Output:
1
u/mellow_gecko Aug 07 '15 edited Aug 07 '15
Python 3
I'm sure this is quite late but I didn't get a chance until this evening to have a go at it. I used regex to help determine the winner, which I later realised makes it kind of hard to know which coordinates are responsible for a win. However, to make up for this neglected aspect, my code does render the game as text in a terminal, so that's kind of cool, I guess.
I'm something of a beginner so if anyone happens to be reading, any feedback is very welcome :)
1
u/InSearchOfTh1ngs Aug 07 '15
C++ This is my first submission ever, yet I've been a lurker solving a few problems here and there. Kind of a hack job but thought I did some cool things. Have a look and let me know how I did!!
1
u/milliDavids Aug 07 '15
Ruby (more of a game than following the inputs of the challenge)
1
u/[deleted] Aug 07 '15
Super sloppy Ruby that is probably riddled with bugs but it achieves the sample output as well as correct output for other input I made up.
1
u/oceanmotion Aug 08 '15
Java.
I chose to check every possible win on the board as curtmack suggested. I would greatly appreciate any feedback!
1
u/amithgeorge Aug 08 '15
Clojure.
Doesn't use a 2D board. Stores each players placed discs in a set. For each disc in the set, generates all possible horizontally, vertically & diagonally connected disc sequences originating from said disc. Returns first such sequence whose discs have already been placed, ie exists in the set.
https://github.com/amithgeorge/reddit-dailyprogrammer-clojure/blob/master/src/rdp/226_inter.clj
1
u/TheSuperWig Aug 09 '15
C++ included the ability to change the board size and the amount needed to connect. In case you wanted to play Connect 5 (9 by 6 grid according to wiki) or just have a larger board, also checks for a draw. Though I was to lazy to actually write the interactive input part so I just take the input from a vector.
1
u/ReckoningReckoner Aug 11 '15 edited Aug 11 '15
Ruby:
1
u/skav3n Aug 11 '15
Python 3:
1
u/philhartmonic Aug 12 '15
Python:
Output from the input description:
And Output from the challenge input:
1
u/evilrabbit Aug 12 '15
Java in almost < 100 lines. Who said Java was verbose?!
1
u/shayhtfc Aug 14 '15
Ruby.
Adds the piece and then determines whether there are 3 more equal pieces adjacent to it
1
u/linkazoid Aug 17 '15
Ruby
Probably not the most efficient way of doing this, but it works :)
1
u/logicx24 Aug 21 '15
A pretty basic Python solution. I use a 2D array to store game state and DFS to check for the winning condition.
1
u/XxMabezxX Aug 27 '15
Late but thought I'd share anyway, written in java.
}
1
u/stinkytofu415 Aug 28 '15
Python 3:
1
u/ironboy_ Sep 03 '15 edited Sep 03 '15
JavaScript keeping the board in a string, checking for wins using regular expressions:
1
u/Hypersapien Oct 08 '15
C#
Going through some of the older challenges and doing some of the more interesting ones.