“Code Breaker” in JavaScript

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
3
down vote

favorite












/**
* Math Assignment Decoding w/o Equation
*
* A simple decoder.
*
* @author RepeaterCreeper
* @since 03/21/2018 18:08:00
* @site https://repeatercreeper.me
*/

var codes = [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
tempA = ,
tempB = ;

// Assigning of Letters to key
var letters =
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H',
9: 'I',
10: 'J',
11: 'K',
12: 'L',
13: 'M',
14: 'N',
15: 'O',
16: 'P',
17: 'Q',
18: 'R',
19: 'S',
20: 'T',
21: 'U',
22: 'V',
23: 'W',
24: 'X',
25: 'Y',
26: 'Z',
27: ' ',
28: '!',
29: '?',
30: '@',
;

/**
* All the equations are provided by the checkPossibleEquations function.
*
* @param arrays equations This parameter is a multidimensional array, contains pair of values.
*/
function bruteForce(equations)
var decodedMessage = "",
currentEquation = 0;

equations.forEach(function(data)
decodedMessage += "(" + data[0] + ", " + data[1] +")[";
for (var letterCode = 0; letterCode < codes.length; letterCode++)
for (var letter = 1; letter <= 30; letter++)
var solved = (data[0] * letter) + data[1];
if (codes[letterCode] == solved)
decodedMessage += letters[letter];



decodedMessage += "]";
currentEquation += 1;
);

console.log(decodedMessage);



/**
* Will check all possible equations, that works for AT LEAST two
* values.
*
* @return array Returns all equations that seem to work for TWO values.
*/
function checkPossibleEquations()
var possibleEquations = ;
for (var i = 0; i < tempA.length; i++)
for (var j = 0; j < tempB.length; j++)
if (JSON.stringify(tempA[i]) == JSON.stringify(tempB[j]))
possibleEquations.push(tempA[i]);




return possibleEquations;


/**
* Tries all possible combinations in the range of 1-50 and stores
* in temporary array variable.
*
* Equation: (i * letter) + k
*/
for (var i = 1; i <= 50; i++)
for (var k = 1; k <= 50; k++)
for (var letter = 0; letter < 30; letter++)
var encValPos = (i * letter) + k;
// var encValNeg = i * letter - k;

if (encValPos == codes[0])
var temp = ;
temp.push(i);
temp.push(k);
tempA.push(temp);


if (encValPos == codes[1])
var temp2 = ;
temp2.push(i);
temp2.push(k);
tempB.push(temp2);





bruteForce(checkPossibleEquations());


INTRODUCTION

So, this is basically a math assignment, but I decided to just make a program for it since it will make my life a lot easier. We're basically given a set of code and it tells us to get the equation for it given it says:


Approach


My current approach since it's linear is (i * letter) + j. Basically looping through it and checking if the values match up. If it does pass it in as a "possible" equation. Which will later be used.


GIVEN



Instructions




ACTIVITY #1

Here is a secret message from me. This time see if you can "crack the code" without my giving you the encoding function.

Helpful tips: The encoding function is a linear function. Try looking at the differences between coded numbers to find the encoding function.




Encoded Message




51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131




Character Assignment




1: 'A',

2: 'B',

3: 'C',

4: 'D',

5: 'E',

6: 'F',

7: 'G',

8: 'H',

9: 'I',

10: 'J',

11: 'K',

12: 'L',

13: 'M',

14: 'N',

15: 'O',

16: 'P',

17: 'Q',

18: 'R',

19: 'S',

20: 'T',

21: 'U',

22: 'V',

23: 'W',

24: 'X',

25: 'Y',

26: 'Z',

27: ' ',

28: '!',

29: '?',

30: '@'




QUESTIONS



So, now after seeing all of that. I'm pretty sure there is quite a few improvements that can be done to this script. I've already cleaned it up as much as I can, but this is as far as I got.


Answer to this is:



"Hungry? Grab a Snicker!"







share|improve this question





















  • We can't change how your code works, so the last paragraph is a bit off-topic. Other than that, it looks good.
    – Hosch250
    Mar 22 at 0:50






  • 1




    Also, there are techniques to do this (i.e. see which sentence has words that are in a dictionary). I'd make that a separate program, though.
    – Hosch250
    Mar 22 at 0:50
















up vote
3
down vote

favorite












/**
* Math Assignment Decoding w/o Equation
*
* A simple decoder.
*
* @author RepeaterCreeper
* @since 03/21/2018 18:08:00
* @site https://repeatercreeper.me
*/

var codes = [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
tempA = ,
tempB = ;

// Assigning of Letters to key
var letters =
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H',
9: 'I',
10: 'J',
11: 'K',
12: 'L',
13: 'M',
14: 'N',
15: 'O',
16: 'P',
17: 'Q',
18: 'R',
19: 'S',
20: 'T',
21: 'U',
22: 'V',
23: 'W',
24: 'X',
25: 'Y',
26: 'Z',
27: ' ',
28: '!',
29: '?',
30: '@',
;

/**
* All the equations are provided by the checkPossibleEquations function.
*
* @param arrays equations This parameter is a multidimensional array, contains pair of values.
*/
function bruteForce(equations)
var decodedMessage = "",
currentEquation = 0;

equations.forEach(function(data)
decodedMessage += "(" + data[0] + ", " + data[1] +")[";
for (var letterCode = 0; letterCode < codes.length; letterCode++)
for (var letter = 1; letter <= 30; letter++)
var solved = (data[0] * letter) + data[1];
if (codes[letterCode] == solved)
decodedMessage += letters[letter];



decodedMessage += "]";
currentEquation += 1;
);

console.log(decodedMessage);



/**
* Will check all possible equations, that works for AT LEAST two
* values.
*
* @return array Returns all equations that seem to work for TWO values.
*/
function checkPossibleEquations()
var possibleEquations = ;
for (var i = 0; i < tempA.length; i++)
for (var j = 0; j < tempB.length; j++)
if (JSON.stringify(tempA[i]) == JSON.stringify(tempB[j]))
possibleEquations.push(tempA[i]);




return possibleEquations;


/**
* Tries all possible combinations in the range of 1-50 and stores
* in temporary array variable.
*
* Equation: (i * letter) + k
*/
for (var i = 1; i <= 50; i++)
for (var k = 1; k <= 50; k++)
for (var letter = 0; letter < 30; letter++)
var encValPos = (i * letter) + k;
// var encValNeg = i * letter - k;

if (encValPos == codes[0])
var temp = ;
temp.push(i);
temp.push(k);
tempA.push(temp);


if (encValPos == codes[1])
var temp2 = ;
temp2.push(i);
temp2.push(k);
tempB.push(temp2);





bruteForce(checkPossibleEquations());


INTRODUCTION

So, this is basically a math assignment, but I decided to just make a program for it since it will make my life a lot easier. We're basically given a set of code and it tells us to get the equation for it given it says:


Approach


My current approach since it's linear is (i * letter) + j. Basically looping through it and checking if the values match up. If it does pass it in as a "possible" equation. Which will later be used.


GIVEN



Instructions




ACTIVITY #1

Here is a secret message from me. This time see if you can "crack the code" without my giving you the encoding function.

Helpful tips: The encoding function is a linear function. Try looking at the differences between coded numbers to find the encoding function.




Encoded Message




51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131




Character Assignment




1: 'A',

2: 'B',

3: 'C',

4: 'D',

5: 'E',

6: 'F',

7: 'G',

8: 'H',

9: 'I',

10: 'J',

11: 'K',

12: 'L',

13: 'M',

14: 'N',

15: 'O',

16: 'P',

17: 'Q',

18: 'R',

19: 'S',

20: 'T',

21: 'U',

22: 'V',

23: 'W',

24: 'X',

25: 'Y',

26: 'Z',

27: ' ',

28: '!',

29: '?',

30: '@'




QUESTIONS



So, now after seeing all of that. I'm pretty sure there is quite a few improvements that can be done to this script. I've already cleaned it up as much as I can, but this is as far as I got.


Answer to this is:



"Hungry? Grab a Snicker!"







share|improve this question





















  • We can't change how your code works, so the last paragraph is a bit off-topic. Other than that, it looks good.
    – Hosch250
    Mar 22 at 0:50






  • 1




    Also, there are techniques to do this (i.e. see which sentence has words that are in a dictionary). I'd make that a separate program, though.
    – Hosch250
    Mar 22 at 0:50












up vote
3
down vote

favorite









up vote
3
down vote

favorite











/**
* Math Assignment Decoding w/o Equation
*
* A simple decoder.
*
* @author RepeaterCreeper
* @since 03/21/2018 18:08:00
* @site https://repeatercreeper.me
*/

var codes = [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
tempA = ,
tempB = ;

// Assigning of Letters to key
var letters =
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H',
9: 'I',
10: 'J',
11: 'K',
12: 'L',
13: 'M',
14: 'N',
15: 'O',
16: 'P',
17: 'Q',
18: 'R',
19: 'S',
20: 'T',
21: 'U',
22: 'V',
23: 'W',
24: 'X',
25: 'Y',
26: 'Z',
27: ' ',
28: '!',
29: '?',
30: '@',
;

/**
* All the equations are provided by the checkPossibleEquations function.
*
* @param arrays equations This parameter is a multidimensional array, contains pair of values.
*/
function bruteForce(equations)
var decodedMessage = "",
currentEquation = 0;

equations.forEach(function(data)
decodedMessage += "(" + data[0] + ", " + data[1] +")[";
for (var letterCode = 0; letterCode < codes.length; letterCode++)
for (var letter = 1; letter <= 30; letter++)
var solved = (data[0] * letter) + data[1];
if (codes[letterCode] == solved)
decodedMessage += letters[letter];



decodedMessage += "]";
currentEquation += 1;
);

console.log(decodedMessage);



/**
* Will check all possible equations, that works for AT LEAST two
* values.
*
* @return array Returns all equations that seem to work for TWO values.
*/
function checkPossibleEquations()
var possibleEquations = ;
for (var i = 0; i < tempA.length; i++)
for (var j = 0; j < tempB.length; j++)
if (JSON.stringify(tempA[i]) == JSON.stringify(tempB[j]))
possibleEquations.push(tempA[i]);




return possibleEquations;


/**
* Tries all possible combinations in the range of 1-50 and stores
* in temporary array variable.
*
* Equation: (i * letter) + k
*/
for (var i = 1; i <= 50; i++)
for (var k = 1; k <= 50; k++)
for (var letter = 0; letter < 30; letter++)
var encValPos = (i * letter) + k;
// var encValNeg = i * letter - k;

if (encValPos == codes[0])
var temp = ;
temp.push(i);
temp.push(k);
tempA.push(temp);


if (encValPos == codes[1])
var temp2 = ;
temp2.push(i);
temp2.push(k);
tempB.push(temp2);





bruteForce(checkPossibleEquations());


INTRODUCTION

So, this is basically a math assignment, but I decided to just make a program for it since it will make my life a lot easier. We're basically given a set of code and it tells us to get the equation for it given it says:


Approach


My current approach since it's linear is (i * letter) + j. Basically looping through it and checking if the values match up. If it does pass it in as a "possible" equation. Which will later be used.


GIVEN



Instructions




ACTIVITY #1

Here is a secret message from me. This time see if you can "crack the code" without my giving you the encoding function.

Helpful tips: The encoding function is a linear function. Try looking at the differences between coded numbers to find the encoding function.




Encoded Message




51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131




Character Assignment




1: 'A',

2: 'B',

3: 'C',

4: 'D',

5: 'E',

6: 'F',

7: 'G',

8: 'H',

9: 'I',

10: 'J',

11: 'K',

12: 'L',

13: 'M',

14: 'N',

15: 'O',

16: 'P',

17: 'Q',

18: 'R',

19: 'S',

20: 'T',

21: 'U',

22: 'V',

23: 'W',

24: 'X',

25: 'Y',

26: 'Z',

27: ' ',

28: '!',

29: '?',

30: '@'




QUESTIONS



So, now after seeing all of that. I'm pretty sure there is quite a few improvements that can be done to this script. I've already cleaned it up as much as I can, but this is as far as I got.


Answer to this is:



"Hungry? Grab a Snicker!"







share|improve this question













/**
* Math Assignment Decoding w/o Equation
*
* A simple decoder.
*
* @author RepeaterCreeper
* @since 03/21/2018 18:08:00
* @site https://repeatercreeper.me
*/

var codes = [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
tempA = ,
tempB = ;

// Assigning of Letters to key
var letters =
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H',
9: 'I',
10: 'J',
11: 'K',
12: 'L',
13: 'M',
14: 'N',
15: 'O',
16: 'P',
17: 'Q',
18: 'R',
19: 'S',
20: 'T',
21: 'U',
22: 'V',
23: 'W',
24: 'X',
25: 'Y',
26: 'Z',
27: ' ',
28: '!',
29: '?',
30: '@',
;

/**
* All the equations are provided by the checkPossibleEquations function.
*
* @param arrays equations This parameter is a multidimensional array, contains pair of values.
*/
function bruteForce(equations)
var decodedMessage = "",
currentEquation = 0;

equations.forEach(function(data)
decodedMessage += "(" + data[0] + ", " + data[1] +")[";
for (var letterCode = 0; letterCode < codes.length; letterCode++)
for (var letter = 1; letter <= 30; letter++)
var solved = (data[0] * letter) + data[1];
if (codes[letterCode] == solved)
decodedMessage += letters[letter];



decodedMessage += "]";
currentEquation += 1;
);

console.log(decodedMessage);



/**
* Will check all possible equations, that works for AT LEAST two
* values.
*
* @return array Returns all equations that seem to work for TWO values.
*/
function checkPossibleEquations()
var possibleEquations = ;
for (var i = 0; i < tempA.length; i++)
for (var j = 0; j < tempB.length; j++)
if (JSON.stringify(tempA[i]) == JSON.stringify(tempB[j]))
possibleEquations.push(tempA[i]);




return possibleEquations;


/**
* Tries all possible combinations in the range of 1-50 and stores
* in temporary array variable.
*
* Equation: (i * letter) + k
*/
for (var i = 1; i <= 50; i++)
for (var k = 1; k <= 50; k++)
for (var letter = 0; letter < 30; letter++)
var encValPos = (i * letter) + k;
// var encValNeg = i * letter - k;

if (encValPos == codes[0])
var temp = ;
temp.push(i);
temp.push(k);
tempA.push(temp);


if (encValPos == codes[1])
var temp2 = ;
temp2.push(i);
temp2.push(k);
tempB.push(temp2);





bruteForce(checkPossibleEquations());


INTRODUCTION

So, this is basically a math assignment, but I decided to just make a program for it since it will make my life a lot easier. We're basically given a set of code and it tells us to get the equation for it given it says:


Approach


My current approach since it's linear is (i * letter) + j. Basically looping through it and checking if the values match up. If it does pass it in as a "possible" equation. Which will later be used.


GIVEN



Instructions




ACTIVITY #1

Here is a secret message from me. This time see if you can "crack the code" without my giving you the encoding function.

Helpful tips: The encoding function is a linear function. Try looking at the differences between coded numbers to find the encoding function.




Encoded Message




51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131




Character Assignment




1: 'A',

2: 'B',

3: 'C',

4: 'D',

5: 'E',

6: 'F',

7: 'G',

8: 'H',

9: 'I',

10: 'J',

11: 'K',

12: 'L',

13: 'M',

14: 'N',

15: 'O',

16: 'P',

17: 'Q',

18: 'R',

19: 'S',

20: 'T',

21: 'U',

22: 'V',

23: 'W',

24: 'X',

25: 'Y',

26: 'Z',

27: ' ',

28: '!',

29: '?',

30: '@'




QUESTIONS



So, now after seeing all of that. I'm pretty sure there is quite a few improvements that can be done to this script. I've already cleaned it up as much as I can, but this is as far as I got.


Answer to this is:



"Hungry? Grab a Snicker!"









share|improve this question












share|improve this question




share|improve this question








edited Mar 22 at 11:03









t3chb0t

32.1k54195




32.1k54195









asked Mar 22 at 0:38









RepeaterCreeper

1078




1078











  • We can't change how your code works, so the last paragraph is a bit off-topic. Other than that, it looks good.
    – Hosch250
    Mar 22 at 0:50






  • 1




    Also, there are techniques to do this (i.e. see which sentence has words that are in a dictionary). I'd make that a separate program, though.
    – Hosch250
    Mar 22 at 0:50
















  • We can't change how your code works, so the last paragraph is a bit off-topic. Other than that, it looks good.
    – Hosch250
    Mar 22 at 0:50






  • 1




    Also, there are techniques to do this (i.e. see which sentence has words that are in a dictionary). I'd make that a separate program, though.
    – Hosch250
    Mar 22 at 0:50















We can't change how your code works, so the last paragraph is a bit off-topic. Other than that, it looks good.
– Hosch250
Mar 22 at 0:50




We can't change how your code works, so the last paragraph is a bit off-topic. Other than that, it looks good.
– Hosch250
Mar 22 at 0:50




1




1




Also, there are techniques to do this (i.e. see which sentence has words that are in a dictionary). I'd make that a separate program, though.
– Hosch250
Mar 22 at 0:50




Also, there are techniques to do this (i.e. see which sentence has words that are in a dictionary). I'd make that a separate program, though.
– Hosch250
Mar 22 at 0:50










1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










Very neat project! Good work. You are correct that there are several improvements that can be made.



  1. What is tempA? tempB? From the name I have absolutely no information about what is included in the arrays. Rename them to something useful.


  2. currentEquation in the bruteForce method is not used, get rid of it.


  3. It is helpful to realize that since the key given by your teacher can be shifted to be zero based and represented by an array (j in your resulting equation will just be different from the official answer, and you can easily pad the letters array with an extra character to avoid this).


  4. Avoid hard coding lengths. If the problem description changed and the number of possible letters was doubled, it is very easy to forget to change the hard coded value in bruteForce.


  5. In the initial loop to try all possible combinations, there is no need for temp or temp. You can instead write tempA.push([i, k]).


  6. If available in your environment, prefer let or const to var.


  7. The code currently prints out far more information than is actually useful. As an example: ECACDCA is certainly not the answer to the riddle. I'd recommend filtering the equations to remove anything where the decoded length is not equal to the encoded length.


  8. The process that is currently used to check if an equation is valid is rather difficult to follow. It would be easier to follow if you checked while looping through the first time.


Here's an alternative solution which I believe is a bit easier to follow.






const messages = [
[142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
[51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
];

// To avoid typing out a bunch of quotes
const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

/**
* Helper function to fill an array from 0 to n (exclusive)
* range(5) => [0, 1, 2, 3, 4]
* @param n the length of the resulting array
*/
const range = n => Array.from( length: n ).map((_, i) => i);

const limit = 50;

/*
* If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
* letter = (codedLetter - j) / i
* If letter is not an integer, or is out of bounds of the letters array, the equation
* is not valid.
*/
function solve(message)
console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

for (const i of range(limit))
for (const j of range(limit))
const isValidLetter = code =>
const letter = (code - j) / i;
return Number.isInteger(letter) && letter < letters.length && letter >= 0;


if (!message.every(isValidLetter))
continue;


const decoded = message.map(code => letters[(code - j) / i]).join('');
console.log(`(i = $i, j = $j) -> [$decoded]`);




messages.forEach(solve)

.as-console-wrapper max-height: 100% !important; top: 0; 








share|improve this answer





















    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: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190154%2fcode-breaker-in-javascript%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    Very neat project! Good work. You are correct that there are several improvements that can be made.



    1. What is tempA? tempB? From the name I have absolutely no information about what is included in the arrays. Rename them to something useful.


    2. currentEquation in the bruteForce method is not used, get rid of it.


    3. It is helpful to realize that since the key given by your teacher can be shifted to be zero based and represented by an array (j in your resulting equation will just be different from the official answer, and you can easily pad the letters array with an extra character to avoid this).


    4. Avoid hard coding lengths. If the problem description changed and the number of possible letters was doubled, it is very easy to forget to change the hard coded value in bruteForce.


    5. In the initial loop to try all possible combinations, there is no need for temp or temp. You can instead write tempA.push([i, k]).


    6. If available in your environment, prefer let or const to var.


    7. The code currently prints out far more information than is actually useful. As an example: ECACDCA is certainly not the answer to the riddle. I'd recommend filtering the equations to remove anything where the decoded length is not equal to the encoded length.


    8. The process that is currently used to check if an equation is valid is rather difficult to follow. It would be easier to follow if you checked while looping through the first time.


    Here's an alternative solution which I believe is a bit easier to follow.






    const messages = [
    [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
    [51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
    ];

    // To avoid typing out a bunch of quotes
    const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

    /**
    * Helper function to fill an array from 0 to n (exclusive)
    * range(5) => [0, 1, 2, 3, 4]
    * @param n the length of the resulting array
    */
    const range = n => Array.from( length: n ).map((_, i) => i);

    const limit = 50;

    /*
    * If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
    * letter = (codedLetter - j) / i
    * If letter is not an integer, or is out of bounds of the letters array, the equation
    * is not valid.
    */
    function solve(message)
    console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

    for (const i of range(limit))
    for (const j of range(limit))
    const isValidLetter = code =>
    const letter = (code - j) / i;
    return Number.isInteger(letter) && letter < letters.length && letter >= 0;


    if (!message.every(isValidLetter))
    continue;


    const decoded = message.map(code => letters[(code - j) / i]).join('');
    console.log(`(i = $i, j = $j) -> [$decoded]`);




    messages.forEach(solve)

    .as-console-wrapper max-height: 100% !important; top: 0; 








    share|improve this answer

























      up vote
      0
      down vote



      accepted










      Very neat project! Good work. You are correct that there are several improvements that can be made.



      1. What is tempA? tempB? From the name I have absolutely no information about what is included in the arrays. Rename them to something useful.


      2. currentEquation in the bruteForce method is not used, get rid of it.


      3. It is helpful to realize that since the key given by your teacher can be shifted to be zero based and represented by an array (j in your resulting equation will just be different from the official answer, and you can easily pad the letters array with an extra character to avoid this).


      4. Avoid hard coding lengths. If the problem description changed and the number of possible letters was doubled, it is very easy to forget to change the hard coded value in bruteForce.


      5. In the initial loop to try all possible combinations, there is no need for temp or temp. You can instead write tempA.push([i, k]).


      6. If available in your environment, prefer let or const to var.


      7. The code currently prints out far more information than is actually useful. As an example: ECACDCA is certainly not the answer to the riddle. I'd recommend filtering the equations to remove anything where the decoded length is not equal to the encoded length.


      8. The process that is currently used to check if an equation is valid is rather difficult to follow. It would be easier to follow if you checked while looping through the first time.


      Here's an alternative solution which I believe is a bit easier to follow.






      const messages = [
      [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
      [51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
      ];

      // To avoid typing out a bunch of quotes
      const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

      /**
      * Helper function to fill an array from 0 to n (exclusive)
      * range(5) => [0, 1, 2, 3, 4]
      * @param n the length of the resulting array
      */
      const range = n => Array.from( length: n ).map((_, i) => i);

      const limit = 50;

      /*
      * If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
      * letter = (codedLetter - j) / i
      * If letter is not an integer, or is out of bounds of the letters array, the equation
      * is not valid.
      */
      function solve(message)
      console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

      for (const i of range(limit))
      for (const j of range(limit))
      const isValidLetter = code =>
      const letter = (code - j) / i;
      return Number.isInteger(letter) && letter < letters.length && letter >= 0;


      if (!message.every(isValidLetter))
      continue;


      const decoded = message.map(code => letters[(code - j) / i]).join('');
      console.log(`(i = $i, j = $j) -> [$decoded]`);




      messages.forEach(solve)

      .as-console-wrapper max-height: 100% !important; top: 0; 








      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        Very neat project! Good work. You are correct that there are several improvements that can be made.



        1. What is tempA? tempB? From the name I have absolutely no information about what is included in the arrays. Rename them to something useful.


        2. currentEquation in the bruteForce method is not used, get rid of it.


        3. It is helpful to realize that since the key given by your teacher can be shifted to be zero based and represented by an array (j in your resulting equation will just be different from the official answer, and you can easily pad the letters array with an extra character to avoid this).


        4. Avoid hard coding lengths. If the problem description changed and the number of possible letters was doubled, it is very easy to forget to change the hard coded value in bruteForce.


        5. In the initial loop to try all possible combinations, there is no need for temp or temp. You can instead write tempA.push([i, k]).


        6. If available in your environment, prefer let or const to var.


        7. The code currently prints out far more information than is actually useful. As an example: ECACDCA is certainly not the answer to the riddle. I'd recommend filtering the equations to remove anything where the decoded length is not equal to the encoded length.


        8. The process that is currently used to check if an equation is valid is rather difficult to follow. It would be easier to follow if you checked while looping through the first time.


        Here's an alternative solution which I believe is a bit easier to follow.






        const messages = [
        [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
        [51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
        ];

        // To avoid typing out a bunch of quotes
        const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

        /**
        * Helper function to fill an array from 0 to n (exclusive)
        * range(5) => [0, 1, 2, 3, 4]
        * @param n the length of the resulting array
        */
        const range = n => Array.from( length: n ).map((_, i) => i);

        const limit = 50;

        /*
        * If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
        * letter = (codedLetter - j) / i
        * If letter is not an integer, or is out of bounds of the letters array, the equation
        * is not valid.
        */
        function solve(message)
        console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

        for (const i of range(limit))
        for (const j of range(limit))
        const isValidLetter = code =>
        const letter = (code - j) / i;
        return Number.isInteger(letter) && letter < letters.length && letter >= 0;


        if (!message.every(isValidLetter))
        continue;


        const decoded = message.map(code => letters[(code - j) / i]).join('');
        console.log(`(i = $i, j = $j) -> [$decoded]`);




        messages.forEach(solve)

        .as-console-wrapper max-height: 100% !important; top: 0; 








        share|improve this answer













        Very neat project! Good work. You are correct that there are several improvements that can be made.



        1. What is tempA? tempB? From the name I have absolutely no information about what is included in the arrays. Rename them to something useful.


        2. currentEquation in the bruteForce method is not used, get rid of it.


        3. It is helpful to realize that since the key given by your teacher can be shifted to be zero based and represented by an array (j in your resulting equation will just be different from the official answer, and you can easily pad the letters array with an extra character to avoid this).


        4. Avoid hard coding lengths. If the problem description changed and the number of possible letters was doubled, it is very easy to forget to change the hard coded value in bruteForce.


        5. In the initial loop to try all possible combinations, there is no need for temp or temp. You can instead write tempA.push([i, k]).


        6. If available in your environment, prefer let or const to var.


        7. The code currently prints out far more information than is actually useful. As an example: ECACDCA is certainly not the answer to the riddle. I'd recommend filtering the equations to remove anything where the decoded length is not equal to the encoded length.


        8. The process that is currently used to check if an equation is valid is rather difficult to follow. It would be easier to follow if you checked while looping through the first time.


        Here's an alternative solution which I believe is a bit easier to follow.






        const messages = [
        [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
        [51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
        ];

        // To avoid typing out a bunch of quotes
        const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

        /**
        * Helper function to fill an array from 0 to n (exclusive)
        * range(5) => [0, 1, 2, 3, 4]
        * @param n the length of the resulting array
        */
        const range = n => Array.from( length: n ).map((_, i) => i);

        const limit = 50;

        /*
        * If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
        * letter = (codedLetter - j) / i
        * If letter is not an integer, or is out of bounds of the letters array, the equation
        * is not valid.
        */
        function solve(message)
        console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

        for (const i of range(limit))
        for (const j of range(limit))
        const isValidLetter = code =>
        const letter = (code - j) / i;
        return Number.isInteger(letter) && letter < letters.length && letter >= 0;


        if (!message.every(isValidLetter))
        continue;


        const decoded = message.map(code => letters[(code - j) / i]).join('');
        console.log(`(i = $i, j = $j) -> [$decoded]`);




        messages.forEach(solve)

        .as-console-wrapper max-height: 100% !important; top: 0; 








        const messages = [
        [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
        [51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
        ];

        // To avoid typing out a bunch of quotes
        const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

        /**
        * Helper function to fill an array from 0 to n (exclusive)
        * range(5) => [0, 1, 2, 3, 4]
        * @param n the length of the resulting array
        */
        const range = n => Array.from( length: n ).map((_, i) => i);

        const limit = 50;

        /*
        * If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
        * letter = (codedLetter - j) / i
        * If letter is not an integer, or is out of bounds of the letters array, the equation
        * is not valid.
        */
        function solve(message)
        console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

        for (const i of range(limit))
        for (const j of range(limit))
        const isValidLetter = code =>
        const letter = (code - j) / i;
        return Number.isInteger(letter) && letter < letters.length && letter >= 0;


        if (!message.every(isValidLetter))
        continue;


        const decoded = message.map(code => letters[(code - j) / i]).join('');
        console.log(`(i = $i, j = $j) -> [$decoded]`);




        messages.forEach(solve)

        .as-console-wrapper max-height: 100% !important; top: 0; 





        const messages = [
        [142, 92, 152, 102, 122, 62, 42, 107, 92, 152, 117, 22, 32, 92, 152, 27, 42, 77, 77, 157],
        [51, 103, 75, 47, 91, 119, 135, 127, 47, 91, 23, 27, 127, 23, 127, 95, 75, 55, 31, 63, 39, 91, 95, 131]
        ];

        // To avoid typing out a bunch of quotes
        const letters = '❌ABCDEFGHIJKLMNOPQRSTUVWXYZ !?@'.split('');

        /**
        * Helper function to fill an array from 0 to n (exclusive)
        * range(5) => [0, 1, 2, 3, 4]
        * @param n the length of the resulting array
        */
        const range = n => Array.from( length: n ).map((_, i) => i);

        const limit = 50;

        /*
        * If we assume codedLetter = (letter * i) + j, we can solve this equation for letter.
        * letter = (codedLetter - j) / i
        * If letter is not an integer, or is out of bounds of the letters array, the equation
        * is not valid.
        */
        function solve(message)
        console.log(`Trying to solve [$message.slice(0, 5).join(', '), ...]`);

        for (const i of range(limit))
        for (const j of range(limit))
        const isValidLetter = code =>
        const letter = (code - j) / i;
        return Number.isInteger(letter) && letter < letters.length && letter >= 0;


        if (!message.every(isValidLetter))
        continue;


        const decoded = message.map(code => letters[(code - j) / i]).join('');
        console.log(`(i = $i, j = $j) -> [$decoded]`);




        messages.forEach(solve)

        .as-console-wrapper max-height: 100% !important; top: 0; 






        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Mar 23 at 5:56









        Gerrit0

        2,6601518




        2,6601518






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190154%2fcode-breaker-in-javascript%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Greedy Best First Search implementation in Rust

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            C++11 CLH Lock Implementation