简体   繁体   English

Javascript:使用for循环和子字符串的递归函数示例-无法弄清楚我要去哪里

[英]Javascript: Example of recursive function using for loops and substring - can't figure out where I'm going wrong

I'm currently working on coderbyte's medium challenge entitled "Permutation Step." 我目前正在从事coderbyte的中等挑战,名为“置换步骤”。

The goal is to take user input, num, and to return the next number greater than num using the same digits So, for example, if user input is 123, then the number 132 should be returned. 目标是获取用户输入num,并使用相同的数字返回下一个大于num的数字 。例如,如果用户输入为123,则应返回数字132。 If user input is 12453, then 12534 should be returned... 如果用户输入为12453,则应返回12534 ...

Anywho, I have a correct model answer created by someone (probably a genius, cuz this stuff is pretty hard) and I'm trying to figure out how the answer works, line for line by having an example play out (I'm keeping it simple and playing out the function with user input 123). 任何人,我都有一个人创建的正确模型答案(可能是一个天才,因为这很困难),我试图通过一个示例来逐行说明答案的工作原理(我一直在简单易用,并通过用户输入123播放该功能)。

The answer has 2 functions, but the 1st function used is what I'm currently trying to work out... 答案有2个功能,但是使用的第一个功能是我目前正在尝试的功能...

The relevant code is: 相关代码为:

var PermutationStep1 = function(num) { 
  var num1 = num.toString();
  var ar = [];
  //return num1;
  if (num1.length < 2) {
   return num; 
  } else {
     for(var i = 0; i < num1.length; i++) { 
       var num2 = num1[i];
       var num3 = num1.substr(0,i) + num1.substr(i+1, num1.length -1);
       var numAr = PermutationStep1(num3);
       for(var j = 0; j < numAr.length; j++) {
         ar.push(numAr[j] + num2);
       }
      }
     ar.sort(function(a,b) {return a-b});
     return ar;  
   }
}

Again, I'm trying to work thru this function with the inputted num as 123 (num = 123). 再次,我尝试通过此函数使用输入的num作为123(num = 123)进行工作。

I'm pretty sure that this function should output an array with multiple elements, because the 2nd function merely compares those array elements with the original user input (in our case, 123), and returns the next greatest value. 我非常确定该函数应该输出包含多个元素的数组,因为第二个函数仅将这些数组元素与原始用户输入(在我们的示例中为123)进行比较,并返回下一个最大值。

So in our case, we should probably get an array, named 'ar', returned with a host of 3 digit values. 因此,在我们的情况下,我们可能应该得到一个名为“ ar”的数组,该数组返回一个包含3位数字的值。 But for some reason, I'm getting an array of 2 digit values. 但是由于某种原因,我得到了一个2位数的数组。 I can't seem to isolate my mistake and where I'm going wrong. 我似乎无法隔离我的错误以及我要去哪里。 Any help with where, specifically, I'm going wrong (whether it be the recursion, the use of substring-method, or the concating of strings together, whatever my problem may be) would be appreciated... 特别是在我出问题的地方提供的任何帮助(无论是递归,子字符串方法的使用还是字符串的合并,无论我遇到什么问题)都将受到赞赏...

Here's some of my work so far: 到目前为止,这是我的一些工作:

PS1(123) / num1 = 123
i = 0; 
num2 = (num1[i]) = '1'; 
num3 = (num1.substr(0, 0) + num1.substr(1, 2)) = ('0' + '23') = '23'

PS1(23)
i = 0; 
num2 = '2'; 
num3 = '3'

PS1(3) -> numAr = 3 (since num1 is less than 2 digits, which is the recursion base case?)

(So take 3 into the 2nd for loop)...
ar.push(numAr[j] + num2) = ar.push('3' + '1') = 31
ar = [31] at this point

And then I go through the initial for-loop a couple more times, where i = 1 and then i = 2, and I eventually get....
ar = [31, 32, 33]...

But I'm thinking I should have something like ar = [131, 132, 133]? 但是我想我应该有类似ar = [131,132,133]的东西吗? I'm not sure where I'm going wrong so please help. 我不确定我要去哪里错,请提供帮助。 Because the answer is correctly spit out by this function, the correct answer being 132. 因为此功能正确地吐出了答案,所以正确答案是132。

Note: if you need the 2nd part of the model answer (ie the 2nd function), here it is: 注意:如果您需要模型答案的第二部分(即第二功能),则为:

var arr = [];

function PermutationStep(num1) {
    arr.push(PermutationStep1(num1));
    var arrStr = arr.toString();
    var arrStrSpl = arrStr.split(",");
   //return arrStrSpl;
    for(var p = 0; p < arrStrSpl.length; p++) {
        if(arrStrSpl[p] > num1) {
            return arrStrSpl[p];
        }
    }
    return -1;
}

okay here is my solution i found it in 20 minutes ;) 好的,这是我的解决方案,我在20分钟内找到了它;)

//---- num should be a Number Object and not a String
function getNextNumber (num)
    {
    var numberStr=num.toString (), l=numberStr.length, i;
    var digits=new Array (), digitA, digitB;
    var weight,lightWeight;
    var valueDifference,biggerValue;

    for (i=l-1;i>-1;i--)
        digits.push (parseInt(numberStr.charAt(i)));   //  345 becomes a0=5 a1=4 a2=3 and we can say that num= a0*10^0+ a1*10^1+ a2*10^2, so the index becomes the decimal weight

    for (weight=1;weight<l;weight++)
        {
        digitA=digits[weight];
        biggerValue=new Array ();

        for (lightWeight=weight-1;lightWeight>-1;lightWeight--)
            {
            digitB=digits[lightWeight];

            if (digitB==digitA) continue;
            valueDifference=(digitA-digitB)*(-Math.pow(10,weight)+Math.pow (10,lightWeight));
            if (valueDifference>0) biggerValue.push(valueDifference);
            }

        if (biggerValue.length>0)
            {
            biggerValue.sort();
            return (biggerValue[0]+num);
            }
        }
    }

I'm sorry the first function i posted was under a mathematical logical mistake and i was to overhasty I thought about it again and now i have the following function which definitley works 对不起,我发布的第一个函数是数学上的逻辑错误,我想彻底改变一下,现在我有了definitley可以使用的以下函数

function getNextNumber (num)
    {
    var numberStr=num.toString (), l=numberStr.length, i;

    var digits=new Array (), lighterDigits, digitAtWeight;
    var weight,lightWeight, lighterDigits_l, value=0;

    for (i=l-1;i>-1;i--)
        digits.push (parseInt(numberStr.charAt(i))); 

    lighterDigits=new Array ();
    lighterDigits.push (digits[0]);

    for (weight=1;weight<l;weight++)
        {
        digitAtWeight=digits[weight];
        lighterDigits_l=lighterDigits.length;


        for (lightWeight=0;lightWeight<lighterDigits_l;lightWeight++)
            {
            if (digitAtWeight<lighterDigits[lightWeight])
                {

                lighterDigits.unshift (lighterDigits.splice (lightWeight,1,digitAtWeight)[0]);
                lighterDigits.reverse ();
                digits=lighterDigits.concat (digits.slice (weight+1,l));
                for (weight=0;weight>l;weight++)
                    value+=Math.pow (10,weight)*digits[weight];
                return value;
                }
            }
        lighterDigits.push (digitAtWeight);
        }       
    return NaN;
    }

this is the solution I figured out for the problem without using a recursive function. 这是我在不使用递归函数的情况下找到的解决方案。 It's passed all the tests on coderbyte. 它已通过coderbyte上的所有测试。 I am still new to this so using recursion is not the first thing I look for. 我对此还很陌生,因此使用递归并不是我要寻找的第一件事。 hope this can help anyone else looking for a solution. 希望这可以帮助其他人寻找解决方案。

function PermutationStep(num) {
  var numArr = (num + '').split('').sort().reverse();
  var numJoin = numArr.join('');
  for (var i = (num + 1); i <= parseInt(numJoin); i++){
    var aaa = (i + '').split('').sort().reverse();
    if (aaa.join('') == numJoin){
    return i;
    }
  }
  return -1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 谁能发现我使用SVG / Javascript函数出错的地方? - Can anyone spot where I'm going wrong with this SVG/Javascript function? 我要改变颜色 <div> 在mouseOver函数上的javascript中。我在哪里出错? - I'm to change color of <div> in javascript on mouseOver function.Where am i going wrong? 我的递归函数在哪里出错? - Where am I going wrong in my recursive function? 我不知道我在使用 getDay() 时做错了什么 - I can't figure out what I'm doing wrong with getDay() 我不知道我的 JavaScript 函数不起作用 - I can't figure out my JavaScript function is not working 循环执行不正确,无法弄清楚我在做什么 - Loop implemented incorrectly, can't figure out what I'm doing wrong Javascript 挑战:循环 - 多个条件 - 卡住,无法弄清楚 - Javascript Challenge: Loops - Multiple Conditions - stuck and can't figure this out 无法计算出Javascript循环 - can't figure Javascript loops 使用JS和SCSS的导航动画,你能告诉我我哪里出错了吗? - Navigation animation using JS and SCSS, can you tell me where I'm going wrong? 遵循教程但无法弄清楚为什么我会收到此消息:“类型'() =&gt; WordArray'.ts(2339) 上不存在属性'子字符串'” - Following a tutorial but can't figure out why I'm getting this message: "Property 'substring' does not exist on type '() => WordArray'.ts(2339)"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM