From 53fa92eef615752a73d2bc346b21a787c7b46b18 Mon Sep 17 00:00:00 2001 From: Jake Francis <53124107+jakefrancis@users.noreply.github.com> Date: Tue, 19 Jan 2021 12:47:49 -0500 Subject: [PATCH] Condense this.rules function The this.rules function was condensed in a similar manner suggested by the java implementation comment above the this.rules function. The previous implementation assigned the binary values backwards, i.e. 7 == index0, 6 === index1, etc. This condensed version assigns them in order. I wasn't sure if this was intentional, it appears the ruleset is randomized so from my understanding this won't make a difference. --- .../CA.js | 22 ++++++------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/chp07_CA/Exercise_7_01_WolframCA_randomizedrules/CA.js b/chp07_CA/Exercise_7_01_WolframCA_randomizedrules/CA.js index 779bcac8..de88ff9b 100644 --- a/chp07_CA/Exercise_7_01_WolframCA_randomizedrules/CA.js +++ b/chp07_CA/Exercise_7_01_WolframCA_randomizedrules/CA.js @@ -59,22 +59,14 @@ function CA(r) { }; // Implementing the Wolfram rules - // This could be condensed probably, here is java way - /*int rules (int a, int b, int c) { - String s = "" + a + b + c; - int index = Integer.parseInt(s, 2); - return ruleset[index]; - }*/ this.rules = function(a, b, c) { - if (a == 1 && b == 1 && c == 1) return this.ruleset[0]; - if (a == 1 && b == 1 && c === 0) return this.ruleset[1]; - if (a == 1 && b === 0 && c == 1) return this.ruleset[2]; - if (a == 1 && b === 0 && c === 0) return this.ruleset[3]; - if (a === 0 && b == 1 && c == 1) return this.ruleset[4]; - if (a === 0 && b == 1 && c === 0) return this.ruleset[5]; - if (a === 0 && b === 0 && c == 1) return this.ruleset[6]; - if (a === 0 && b === 0 && c === 0) return this.ruleset[7]; - return 0; + // First convert our values to a binary string + const binaryString = '' + a + b + c + // Then convert the binary string to an integer + // The 2 lets parseInt know the string is binary + const index = parseInt(binaryString, 2) + // Return next generation state + return this.ruleset[index] }; // The CA is done if it reaches the bottom of the screen