Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

js switch statement follows a pattern

I have a switch statement with 33 cases, each corresponding to a column in a 2d array. The values in the array is the row that will be transitioned too. Is there a cleaner way to write this? each case follows the pattern for letter in alphabet dfarow = [dfarow][n+1]

function FEN2datumType(fen, dfa) {    

//                 alpabet length 33                            
// exampleDFA = [[1, 0, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0]], 
//              [[1, 1, 2, 2, 1, 0, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0]],
//              [[2, 1, 2, 2, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2]]

dfarow = 0; // start state
for (char in fen) { 
  switch (char) {
    case "r":      //alpabet 0
      dfarow = dfa[dfarow][0];
      break;
    case "n":
      dfarow = dfa[dfarow][1];
      break;
    case "b":
      dfarow = dfa[dfarow][2];
      break;
    case "q":
      dfarow = dfa[dfarow][3];
      break;
    case "k":
      dfarow = dfa[dfarow][4];
      break;
    case "p":
      dfarow = dfa[dfarow][5];
      break;
.....etc...

this is the first DFA I have written, I open to suggestions.
my alphabet is a FEN string (Forsyth–Edwards Notation chess) 33 possible chars. exampleDFA has 3 transition states and I have not implemented an accepting state (I was thinking of putting an identifier in the 34th column of the DFA array i.e. if (dfa[dfarow][34] == 1) //accept)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create object for the alphabet:

var alphabet = { r:0, n:1, b:2, .... }

and then you can call alphabet object in for loop:

for (char in fen) { 
  dfarow = dfa[dfarow][alphabet[char]];
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading