Tic-tac-toe: Difference between revisions

394 bytes removed ,  14 days ago
→‎J: Remove trivial exposition.
m (→‎{{header|J}}: place sample output before exposition)
(→‎J: Remove trivial exposition.)
Tags: Mobile edit Mobile web edit
Line 6,696:
outcome=: (' wins'echo@,~'.XO'{~-@turn)`(echo@'tie')@.(1:i.~won,full)
ttt=: outcome@([F.(show@move[_2:Z:won+.full))@(10{._1)@prompt
 
</syntaxhighlight>
 
Output:
<pre> ttt 0
ttt 0
enter a move (1–9) each turn; you're X's
1 2 3
Line 6,757 ⟶ 6,755:
X O O
 
X wins</pre>
</pre>
 
This version is stateless, purely functional, and tacit. CPU selects a random open position. The <code>turn</code> and <code>board</code> verbs extract the turn/board from the state vector. The board is represented by a vector of -1's, 0’s and 1’s, which index into the character vector '.XO' when it’s time to display the board.
 
Encoding data with numbers this way allows the convenience of e.g. being able to simply check whether the absolute value of the sum across a given line is 3, indicating a win.
 
<pre>
]M=: 0 1 _1{~?3 3$3
0 _1 _1
_1 1 1
_1 1 0
M{'.XO'
.OO
OXX
OX.
</pre>
 
This is a stateless, purely functional, tacit approach. CPU selects a random open position. The <code>turn</code> and <code>board</code> verbs extract the turn/board from the vector which represents the game state. The verb <code>open</code> tests whether the selected position is available on the board. Fold (<code>F.</code>) is used because <code>Until=:<tt>{{</tt>u^:(-.@:v)^:_<tt>}}</tt></code> would've quit upon receiving invalid input, as the argument would be unchanged between that iteration and the next.
 
=={{header|Java}}==
35

edits