2016-10-30 4 views
0

Je fais le défi algorithmique freecodecamp "Caesars Cipher". J'ai un problème avec mon code. J'essaie de générer une table de recherche en tant qu'objet dynamique et pour une raison quelconque, il ne s'enregistre pas. Lorsque vous faites console.log, il est dit "table de recherche est indéfini". C'est la même chose avec la variable Acode. Si je commente le fichier console.logs alors cela fonctionnera mais il ne cryptera rien à cause de la partie ci-dessous qui vérifie si le caractère de strArr existe dans le lookupTable, sinon il devrait assigner la même valeur à encryptedArr (c'était fait de ne pas chiffrer des virgules, espaces, etc.):JavaScript Dynamiquement créé objet indéfini

strArr.forEach(function(thisArg) { 
    var newValue; 

    if(lookupTable[thisArg] !== undefined) { 
     newValue = lookupTable[thisArg]; 
    } else { 
     newValue = thisArg; 
    } 

    encryptedArr.push(newValue); 

}); 

Ofcourse LookupTable [thisArg] est toujours définie. Voici toute la fonction de la partie ci-dessus ainsi:

function rot13(str) { // LBH QVQ VG! 
 

 
    var strArr; 
 
    var encryptedArr = []; 
 
    var Acode; 
 
    var lookupTable = {}; //this object will contain the mapping of letters 
 
    var encryptedString; 
 

 
    //check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic 
 
    Acode = 'A'.charCodeAt(0); 
 
    console.log(Acode); 
 
    //generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time) 
 
    //this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works 
 

 
    for (i = 0; i < 26; i++) { 
 
    lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((Acode + i) - 13) % 26); 
 
    console.log(lookupTable[String.fromCharCode(Acode + i)]); 
 
    } 
 

 
    //save the string into the array 
 
    strArr = str.split(""); 
 

 
    //change letters into numbers and save into the code array 
 
    strArr.forEach(function(thisArg) { 
 
    var newValue; 
 

 
    if (lookupTable[thisArg] !== undefined) { 
 
     newValue = lookupTable[thisArg]; 
 
    } else { 
 
     newValue = thisArg; 
 
    } 
 

 
    encryptedArr.push(newValue); 
 

 
    }); 
 

 

 
    encryptedString = encryptedArr.join(""); 
 

 

 
    return encryptedString; 
 
} 
 

 
// Change the inputs below to test 
 
rot13("SERR PBQR PNZC"); 
 
console.log(Acode);

ce que je fais mal à la création d'objets LookupTable et avec le bas?

Acode = 'A'.charCodeAt(0); 
+0

'Acode + ((Acode + i) -13)% 26' est faux. Il devrait être 'Acode + ((i + 13)% 26)' – Barmar

+0

Avez-vous essayé 'console.log (lookupTable)'? – Barmar

+0

Pouvez-vous essayer de faire 'console.log (strArr)'? Il semble que le contenu de ce tableau pourrait être différent de ce qui était attendu. – DBWhite

Répondre

1

Il n'y a pas de variable indéfinie. Le problème avec votre code réside dans la façon dont vous calculez les entrées de la table de correspondance. Votre code est la cartographie chaque caractère à lui-même, et non par décalage 13. La formule est correcte

Acode + ((i + 13) % 26) 

Acode est le code ASCII de la lettre, et vous ne devriez pas être compris que lors de l'exécution du déplacement modulaire. Vous voulez juste appliquer le module au décalage du début de l'alphabet après le passage par 13.

function rot13(str) { // LBH QVQ VG! 
 

 
    var strArr; 
 
    var encryptedArr = []; 
 
    var Acode; 
 
    var lookupTable = {}; //this object will contain the mapping of letters 
 
    var encryptedString; 
 

 
    //check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic 
 
    Acode = 'A'.charCodeAt(0); 
 
    // console.log(Acode); 
 
    //generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time) 
 
    //this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works 
 

 
    for (i = 0; i < 26; i++) { 
 
    lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((i + 13) % 26)); 
 
    // console.log(lookupTable[String.fromCharCode(Acode + i)]); 
 
    } 
 

 
    //save the string into the array 
 
    strArr = str.split(""); 
 

 
    //change letters into numbers and save into the code array 
 
    strArr.forEach(function(thisArg) { 
 
    var newValue; 
 

 
    if (lookupTable[thisArg] !== undefined) { 
 
     newValue = lookupTable[thisArg]; 
 
    } else { 
 
     newValue = thisArg; 
 
    } 
 

 
    encryptedArr.push(newValue); 
 

 
    }); 
 

 

 
    encryptedString = encryptedArr.join(""); 
 

 

 
    return encryptedString; 
 
} 
 

 
// Change the inputs below to test 
 
var result = rot13("SERR PBQR PNZC"); 
 
console.log(result);

+0

Encore, c'est bizarre que ça donne des erreurs non définies parce que ça correspond mal mais ça correspond à quelque chose. Eh bien, j'ai été trompé par Ceasars Cipher étant un algortihm 3 soustraction lettre. Merci beaucoup d'avoir montré la bonne solution :) –

+0

Le seul 'undefined' que j'ai vu était de' console.log (Acode) 'en dehors de la fonction, car' Acode' est seulement défini dans la fonction. – Barmar