У меня возникли проблемы с преобразованием букв из ключа в их алфавитном порядке в строчном кодировании строк.
Если, например, мы берем слово "плод" в качестве нашего ключа, оно должно перевести на следующую последовательность чисел: " 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)"
Я не знаю, хотите ли вы сделать это внутри функции или после того, как результат был возвращен.
В любом случае, следующее должно выполнить эту работу:
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]
Отображать символы в алфавитном порядке
[].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>