亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

排列算法打印出部分錯誤消息

排列算法打印出部分錯誤消息

慕村9548890 2021-08-20 18:35:58
我正在嘗試制作一個置換算法。出于某種原因,它返回部分錯誤消息,我不明白為什么以及如何停止它。當我添加另一個 else if 語句時,問題消失了,但我想知道為什么。`function permutations(string) {  var result = [ ];  if ( string.length === 0) {    var error = "nothing to output"; // for some reason it puts one letter into the array    return error;  } else if (string.length === 1) { //this loop somehow fixes it?    return string;  } else {    for (var i = 0; i < string.length; i++) {      var firstChar = string[i];      var otherChar = string.substring(0, i) + string.substring(i + 1);      var otherPermutations = permutations(otherChar);      for (var j = 0; j < otherPermutations.length; j++) {        result.push(firstChar + otherPermutations[j]);      }    }    return result;  }}console.log(permutations("abc"));//prints ["abc", "acb", "bac", "bca", "cab", "cba"] when I add extra loop.//when I remove extra else if, it prints (102) ["abcn", "abco", "abct", "abch", "abci", "abcn", "abcg", "abc ", "abct", "abco", "abc ", "abco", "abcu", "abct", "abcp", "abcu", "abct", "acbn", "acbo", "acbt", "acbh", "acbi", "acbn", "acbg", "acb ", "acbt", "acbo", "acb ", "acbo", "acbu", "acbt", "acbp", "acbu", "acbt", "bacn", "baco", "bact", "bach", "baci", "bacn", "bacg", "bac ", "bact", "baco", "bac ", "baco", "bacu", "bact", "bacp", "bacu", "bact", "bcan", "bcao", "bcat", "bcah", "bcai", "bcan", "bcag", "bca ", "bcat", "bcao", "bca ", "bcao", "bcau", "bcat", "bcap", "bcau", "bcat", "cabn", "cabo", "cabt", "cabh", "cabi", "cabn", "cabg", "cab ", "cabt", "cabo", "cab ", "cabo", "cabu", "cabt", "cabp", "cabu", "cabt", "cban", "cbao", "cbat", "cbah", "cbai", "cban", "cbag", "cba ", "cbat", "cbao", "cba ", "cbao", "cbau", "cbat", "cbap", …]`
查看完整描述

1 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

出于某種原因,它返回部分錯誤消息,我不明白為什么


那是因為您的錯誤消息otherPermutations在調用者中變成了,并且它迭代了它的元素(它確實期望一個數組......)。不要return錯誤,throw他們。


如何阻止它?


您已經找到了一種方法,字符串長度為 1 的基本情況(盡管您最好返回一個數組)。但實際上空字符串應該是你的基本情況:結果應該是一個包含單個空字符串的數組。


function permutations(string) {

  var result = [];


  if (string.length === 0) {

    result.push("");

  // } else if (string.length === 1) { // not necessary

  //  result.push(string);

  } else {

    for (var i = 0; i < string.length; i++) {

      var firstChar = string[i];

      var otherChars = string.slice(0, i) + string.slice(i + 1);

      var otherPermutations = permutations(otherChars);


      for (var j = 0; j < otherPermutations.length; j++) {

        result.push(firstChar + otherPermutations[j]);

      }

    }

  }

  return result;

}


查看完整回答
反對 回復 2021-08-20
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號