JavaScript Rip Transposition Cipher - как преобразовать ключ в числа столбцов - PullRequest
0 голосов
/ 11 октября 2018

У меня возникли проблемы с преобразованием букв из ключа в их алфавитный порядок в Шифре транспонирования строк.

Если, например, в качестве ключа мы используем слово "фрукт" , он должен переводиться в следующую последовательность чисел: " 6 (f) 18 (r) 21 (u) 9 (i) 20 (t) "

Мне удалось добиться этого с помощью этой функции:

function filterKey(key) {
    var result = [];
    for (var i = 0; i < key.length; i++) {
        var c = key.charCodeAt(i);
        result.push((c - 65) % 32);
    }
    return result;
}

У меня вопрос: как преобразовать приведенную выше последовательность чисел в номера столбцов?

Как это: "6(f) 18 (r) 21 (u) 9 (i) 20 (t) " -> " 1 (f) 3 (r) 5 (u) 2 (i) 4 (t)"

Ответы [ 2 ]

0 голосов
/ 11 октября 2018
  1. Отображение символов в алфавитные индексы

    [].map.call ("fruit", c => c.charCodeAt (0)^96) //[6, 18, 21, 9, 20]

Чтобы переместить ваше сообщение с заданным ключом

function trnsps (key, msg) {
 let {map}=[],_l,_n=0;
 //Build the lookup indices from the key
 let _key = key 
     .split('') //Split the key
     .sort()    //Sort it alphabetically
     .map ((l,i) => key.indexOf (l)) //map it to the original index
     .map (n => {
           let r=_l==n?n+ ++_n:n+(_n=0); 
           _l=n;
           return r
      }) //increase the index for every consecutive character
 //Map the alphabetical indices to characters
 msg = map.call (msg, c => typeof c=="number"?String.fromCharCode(c^96):c)
//Encode the input with the given key
 let enc = map.call (msg, (c,i) => (
  msg[_key[i]] 
));
//Map the message to column indexes
 return msg.map (c => -~enc.indexOf (c));
}

trnsps("fruit", "fruit");
trnsps ("fruit", [6,18,21,9,20])
trnsps ("frooot", "fruit")
console.log (
    trnsps ("froot", [6,18,21,9,20])
)
<script>
    function trnsps (key, msg) {
     let {map}=[],_l,_n=0;
     //Build the lookup indices from the key
     let _key = key 
         .split('') //Split the key
         .sort()    //Sort it alphabetically
         .map ((l,i) => key.indexOf (l)) //map it to the original index
         .map (n => {
               let r=_l==n?n+ ++_n:n+(_n=0); 
               _l=n;
               return r
          }) //increase the index for every consecutive character
     //Map the alphabetical indices to characters
     msg = map.call (msg, c => typeof c=="number"?String.fromCharCode(c^96):c)
    //Encode the input with the given key
     let enc = map.call (msg, (c,i) => (
      msg[_key[i]] 
    ));
    //Map the message to column indexes
     return msg.map (c => -~enc.indexOf (c));
    }
</script>
0 голосов
/ 11 октября 2018

Я не знаю, хотите ли вы сделать это внутри функции или после того, как результат был возвращен.

В любом случае, следующее должно делать эту работу:

var key = "fruit";
var result = key.split("").map(function(x) {return (x.charCodeAt(0) - 65) % 32}); // (one-liner for your function)
var sorted = result.slice(0).sort(function(a, b) {return a - b});
var columnNumbers = result.map(function(x) {
    var index = sorted.indexOf(x);
    sorted[index] = 0; // reset value in case of duplicate chars
    return index + 1;
});
console.log(columnNumbers);

Обратите внимание, что он предназначен для работы с дублирующимися буквами в ключе.

Например, "froot" выдаст [1, 4, 2, 3, 5]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...