迭代数组并交换邻居

时间:2017-12-30 23:21:54

标签: javascript arrays algorithm

我有一个BIP39密码,有24个字来恢复我的加密货币钱包。不幸的是,密码短语没有验证(最后一个字是校验和)。密码短语中的所有单词都在可用的BIP39单词列表中,所以我的第一个猜测是我混淆了短语/数组中两个相邻单词的顺序。

我想循环遍历数组中的每个单词,将其与相邻单词交换,运行函数firstDataYear,撤消交换并移动到下一个单词。

示例:

check(phrase)

如果我在数组中包含所有单词,我如何使用JS对其进行编码?

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

  

var words = initialPhrase.split('');

     

for(var i = 0; i< words.length - 1; ++ i){

     

words [i] = words.splice(i + 1,1,words [i])[0];

     

var testPhrase = words.join(''); //你想要的短语

     

words = initialPhrase.split('');

     

}

答案 1 :(得分:1)

包括撤消:

function check(phrase) {
  //custom validator code
  var phraseStr = phrase.join(' ');
  console.log(phraseStr);
  if (phraseStr == 'wordOne wordTwo wordFour wordThree') {
    console.log('valid!');
    return true;
  }
  return false;
}

function getValidPhrase(phrase) {
  for (i=1;i<phrase.length;i++) {
    //swap
    phrase[i] = phrase.splice(i-1, 1, phrase[i])[0];

    if (check(phrase)) {
      return phrase;
    }
    //undo swap
    phrase[i] = phrase.splice(i-1, 1, phrase[i])[0];
  }
  return null;
}

var pp = getValidPhrase(['wordOne', 'wordTwo', 'wordThree', 'wordFour']);

相关问题