在行换位密码中将键中的字母转换为字母顺序时遇到麻烦。
例如,如果我们将单词“ fruit”作为关键字,则应将其转换为以下数字序列:“ 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)”
答案 0 :(得分:0)
我不知道您是否要在函数内 或返回结果后执行此操作。
无论哪种方式,都应该执行以下操作:
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]
答案 1 :(得分:0)
将字符映射到字母索引
l1 <- "<p><strong>Which piece can be rotated to match the display figure?</strong></p>\n\n<p><strong><img alt=\"\" src=\"/bundles/pppp/files/display2d_12-2.jpg\" style=\"width: 256px; height: 256px;\" /></strong></p>\n"
l2 <- "<p><strong>Which piece can be rotated to match the display figure?</strong></p>\n\n<p><strong><img alt=\"\" src=\"/bundles/pppp/files/display2d_8-2.jpg\" style=\"width: 256px; height: 256px;\" /></strong></p>\n"
l3 <- c(l1,l2)
# grab everything in between display and jpg
inner <- str_extract(string = l3, pattern = "(?<=display).*(?=jpg)")
# then paste back display and jpg
paste0('display', inner, 'jpg')
[].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])
)