Game of Life with Scala and Functional Programming
up vote
0
down vote
favorite
I have been doing OOP and imperative programming my whole career but I wanted to dabble in Scala along with functional programming. Rather than writing Java like code in Scala I wanted to try a more functional approach. I decided to try a simple Kata with Scala, Game of Life. The following is what I came up with. I admit I am very much stuck in OOP/imperative mindset. I am not sure if this is the best approach for Scala, or functional programming. I avoided functions that mutate objects, and favor returning a new copy. I was unsure what the best approach is with functional programming to ensure objects can't be created in an invalid state. Is there a way I can make my code more aligned with idiomatic Scala and functional programming.
package io.jkratz.katas.gameoflife
import scala.util.Random
case class Board(grid: Array[Array[Int]]) {
require(grid != null, "grid cannot be null")
require(!isJagged(grid), "grid cannot be jagged")
require(isValid(grid), "grid contains invalid values, 0 and 1 are the only valid values")
val rows: Int = {
grid.length
}
val columns: Int = {
grid(0).length
}
def evolve(): Board = {
val newGrid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
newGrid(i)(j) = getNextCellState(i,j)
}
}
Board(newGrid)
}
private def getNextCellState(i:Int, j: Int): Int = {
var liveCount = 0
val cellValue = grid(i)(j)
for (x <- -1 to 1; y <- -1 to 1) {
if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
// do nothing, out of bounds
} else {
liveCount += grid(i + x)(j + y)
}
}
liveCount -= cellValue
if (cellValue.equals(Board.CELL_ALIVE) && (liveCount < 2 || liveCount > 3)) {
Board.CELL_DEAD
} else if (cellValue.equals(Board.CELL_DEAD) && liveCount == 3) {
Board.CELL_ALIVE
} else {
cellValue
}
}
private def isJagged(grid: Array[Array[Int]]): Boolean = {
var valid = true
val size = grid(0).length
grid.foreach(row => if (row.length.equals(size)) valid = false)
valid
}
private def isValid(grid: Array[Array[Int]]): Boolean = {
var valid = true
for (i <- grid.indices; j <- grid(0).indices) {
val x = grid(i)(j)
if (x != 0 && x != 1) {
valid = false
}
}
valid
}
}
object Board {
val CELL_DEAD = 0
val CELL_ALIVE = 1
val DEFAULT_ROWS = 10
val DEFAULT_COLUMNS = 10
def random(rows: Int = DEFAULT_ROWS, columns: Int = DEFAULT_COLUMNS): Board = {
val grid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
grid(i)(j) = Random.nextInt(2)
}
}
Board(grid=grid)
}
def prettyPrint(board: Board): Unit = {
val grid = board.grid
for (i <- grid.indices) {
for (j <- grid(0).indices) {
if (grid(i)(j) == 0) print(" - ") else print(" * ")
}
println()
}
}
}
And my main entry point.
package io.jkratz.katas.gameoflife
object Life {
def main(args: Array[String]): Unit = {
val state0 = Board.random(5,5)
println("State 0")
Board.prettyPrint(state0)
val state1 = state0.evolve()
println("State 1")
Board.prettyPrint(state1)
}
}
functional-programming scala game-of-life
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
up vote
0
down vote
favorite
I have been doing OOP and imperative programming my whole career but I wanted to dabble in Scala along with functional programming. Rather than writing Java like code in Scala I wanted to try a more functional approach. I decided to try a simple Kata with Scala, Game of Life. The following is what I came up with. I admit I am very much stuck in OOP/imperative mindset. I am not sure if this is the best approach for Scala, or functional programming. I avoided functions that mutate objects, and favor returning a new copy. I was unsure what the best approach is with functional programming to ensure objects can't be created in an invalid state. Is there a way I can make my code more aligned with idiomatic Scala and functional programming.
package io.jkratz.katas.gameoflife
import scala.util.Random
case class Board(grid: Array[Array[Int]]) {
require(grid != null, "grid cannot be null")
require(!isJagged(grid), "grid cannot be jagged")
require(isValid(grid), "grid contains invalid values, 0 and 1 are the only valid values")
val rows: Int = {
grid.length
}
val columns: Int = {
grid(0).length
}
def evolve(): Board = {
val newGrid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
newGrid(i)(j) = getNextCellState(i,j)
}
}
Board(newGrid)
}
private def getNextCellState(i:Int, j: Int): Int = {
var liveCount = 0
val cellValue = grid(i)(j)
for (x <- -1 to 1; y <- -1 to 1) {
if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
// do nothing, out of bounds
} else {
liveCount += grid(i + x)(j + y)
}
}
liveCount -= cellValue
if (cellValue.equals(Board.CELL_ALIVE) && (liveCount < 2 || liveCount > 3)) {
Board.CELL_DEAD
} else if (cellValue.equals(Board.CELL_DEAD) && liveCount == 3) {
Board.CELL_ALIVE
} else {
cellValue
}
}
private def isJagged(grid: Array[Array[Int]]): Boolean = {
var valid = true
val size = grid(0).length
grid.foreach(row => if (row.length.equals(size)) valid = false)
valid
}
private def isValid(grid: Array[Array[Int]]): Boolean = {
var valid = true
for (i <- grid.indices; j <- grid(0).indices) {
val x = grid(i)(j)
if (x != 0 && x != 1) {
valid = false
}
}
valid
}
}
object Board {
val CELL_DEAD = 0
val CELL_ALIVE = 1
val DEFAULT_ROWS = 10
val DEFAULT_COLUMNS = 10
def random(rows: Int = DEFAULT_ROWS, columns: Int = DEFAULT_COLUMNS): Board = {
val grid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
grid(i)(j) = Random.nextInt(2)
}
}
Board(grid=grid)
}
def prettyPrint(board: Board): Unit = {
val grid = board.grid
for (i <- grid.indices) {
for (j <- grid(0).indices) {
if (grid(i)(j) == 0) print(" - ") else print(" * ")
}
println()
}
}
}
And my main entry point.
package io.jkratz.katas.gameoflife
object Life {
def main(args: Array[String]): Unit = {
val state0 = Board.random(5,5)
println("State 0")
Board.prettyPrint(state0)
val state1 = state0.evolve()
println("State 1")
Board.prettyPrint(state1)
}
}
functional-programming scala game-of-life
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I have been doing OOP and imperative programming my whole career but I wanted to dabble in Scala along with functional programming. Rather than writing Java like code in Scala I wanted to try a more functional approach. I decided to try a simple Kata with Scala, Game of Life. The following is what I came up with. I admit I am very much stuck in OOP/imperative mindset. I am not sure if this is the best approach for Scala, or functional programming. I avoided functions that mutate objects, and favor returning a new copy. I was unsure what the best approach is with functional programming to ensure objects can't be created in an invalid state. Is there a way I can make my code more aligned with idiomatic Scala and functional programming.
package io.jkratz.katas.gameoflife
import scala.util.Random
case class Board(grid: Array[Array[Int]]) {
require(grid != null, "grid cannot be null")
require(!isJagged(grid), "grid cannot be jagged")
require(isValid(grid), "grid contains invalid values, 0 and 1 are the only valid values")
val rows: Int = {
grid.length
}
val columns: Int = {
grid(0).length
}
def evolve(): Board = {
val newGrid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
newGrid(i)(j) = getNextCellState(i,j)
}
}
Board(newGrid)
}
private def getNextCellState(i:Int, j: Int): Int = {
var liveCount = 0
val cellValue = grid(i)(j)
for (x <- -1 to 1; y <- -1 to 1) {
if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
// do nothing, out of bounds
} else {
liveCount += grid(i + x)(j + y)
}
}
liveCount -= cellValue
if (cellValue.equals(Board.CELL_ALIVE) && (liveCount < 2 || liveCount > 3)) {
Board.CELL_DEAD
} else if (cellValue.equals(Board.CELL_DEAD) && liveCount == 3) {
Board.CELL_ALIVE
} else {
cellValue
}
}
private def isJagged(grid: Array[Array[Int]]): Boolean = {
var valid = true
val size = grid(0).length
grid.foreach(row => if (row.length.equals(size)) valid = false)
valid
}
private def isValid(grid: Array[Array[Int]]): Boolean = {
var valid = true
for (i <- grid.indices; j <- grid(0).indices) {
val x = grid(i)(j)
if (x != 0 && x != 1) {
valid = false
}
}
valid
}
}
object Board {
val CELL_DEAD = 0
val CELL_ALIVE = 1
val DEFAULT_ROWS = 10
val DEFAULT_COLUMNS = 10
def random(rows: Int = DEFAULT_ROWS, columns: Int = DEFAULT_COLUMNS): Board = {
val grid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
grid(i)(j) = Random.nextInt(2)
}
}
Board(grid=grid)
}
def prettyPrint(board: Board): Unit = {
val grid = board.grid
for (i <- grid.indices) {
for (j <- grid(0).indices) {
if (grid(i)(j) == 0) print(" - ") else print(" * ")
}
println()
}
}
}
And my main entry point.
package io.jkratz.katas.gameoflife
object Life {
def main(args: Array[String]): Unit = {
val state0 = Board.random(5,5)
println("State 0")
Board.prettyPrint(state0)
val state1 = state0.evolve()
println("State 1")
Board.prettyPrint(state1)
}
}
functional-programming scala game-of-life
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
I have been doing OOP and imperative programming my whole career but I wanted to dabble in Scala along with functional programming. Rather than writing Java like code in Scala I wanted to try a more functional approach. I decided to try a simple Kata with Scala, Game of Life. The following is what I came up with. I admit I am very much stuck in OOP/imperative mindset. I am not sure if this is the best approach for Scala, or functional programming. I avoided functions that mutate objects, and favor returning a new copy. I was unsure what the best approach is with functional programming to ensure objects can't be created in an invalid state. Is there a way I can make my code more aligned with idiomatic Scala and functional programming.
package io.jkratz.katas.gameoflife
import scala.util.Random
case class Board(grid: Array[Array[Int]]) {
require(grid != null, "grid cannot be null")
require(!isJagged(grid), "grid cannot be jagged")
require(isValid(grid), "grid contains invalid values, 0 and 1 are the only valid values")
val rows: Int = {
grid.length
}
val columns: Int = {
grid(0).length
}
def evolve(): Board = {
val newGrid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
newGrid(i)(j) = getNextCellState(i,j)
}
}
Board(newGrid)
}
private def getNextCellState(i:Int, j: Int): Int = {
var liveCount = 0
val cellValue = grid(i)(j)
for (x <- -1 to 1; y <- -1 to 1) {
if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
// do nothing, out of bounds
} else {
liveCount += grid(i + x)(j + y)
}
}
liveCount -= cellValue
if (cellValue.equals(Board.CELL_ALIVE) && (liveCount < 2 || liveCount > 3)) {
Board.CELL_DEAD
} else if (cellValue.equals(Board.CELL_DEAD) && liveCount == 3) {
Board.CELL_ALIVE
} else {
cellValue
}
}
private def isJagged(grid: Array[Array[Int]]): Boolean = {
var valid = true
val size = grid(0).length
grid.foreach(row => if (row.length.equals(size)) valid = false)
valid
}
private def isValid(grid: Array[Array[Int]]): Boolean = {
var valid = true
for (i <- grid.indices; j <- grid(0).indices) {
val x = grid(i)(j)
if (x != 0 && x != 1) {
valid = false
}
}
valid
}
}
object Board {
val CELL_DEAD = 0
val CELL_ALIVE = 1
val DEFAULT_ROWS = 10
val DEFAULT_COLUMNS = 10
def random(rows: Int = DEFAULT_ROWS, columns: Int = DEFAULT_COLUMNS): Board = {
val grid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
grid(i)(j) = Random.nextInt(2)
}
}
Board(grid=grid)
}
def prettyPrint(board: Board): Unit = {
val grid = board.grid
for (i <- grid.indices) {
for (j <- grid(0).indices) {
if (grid(i)(j) == 0) print(" - ") else print(" * ")
}
println()
}
}
}
And my main entry point.
package io.jkratz.katas.gameoflife
object Life {
def main(args: Array[String]): Unit = {
val state0 = Board.random(5,5)
println("State 0")
Board.prettyPrint(state0)
val state1 = state0.evolve()
println("State 1")
Board.prettyPrint(state1)
}
}
functional-programming scala game-of-life
functional-programming scala game-of-life
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 2 hours ago
jkratz55
101
101
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
jkratz55 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
jkratz55 is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209873%2fgame-of-life-with-scala-and-functional-programming%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
jkratz55 is a new contributor. Be nice, and check out our Code of Conduct.
jkratz55 is a new contributor. Be nice, and check out our Code of Conduct.
jkratz55 is a new contributor. Be nice, and check out our Code of Conduct.
jkratz55 is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209873%2fgame-of-life-with-scala-and-functional-programming%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown