按顺序查找下一个数字的算法

时间:2013-02-19 13:37:10

标签: javascript jquery

序列:1,2,3,...... 10 公式:x = n + 1

假设序列是一个数组,并且在给定的时间序列中,前三个索引上包含1,3,5,其中包含0

现在下一个数字应该是2,并且数组将在前四个索引上包含1,2,3,5,其中包含0

现在下一个数字应为4,并且数组将在前五个索引中包含1,2,3,4,5,其中包含0

现在下一个数字应为6,并且数组将在前六个索引中包含1,2,3,5,6,其中包含0

function findNextNumber(numArry) {
    var number = 1;
    var tempArray = new Array();
    for (i = 0; i < 10; i++) {
        tempArray[i] = "E";
    }
    $.each(numArry, function () {
        if (this != 0) {
            tempArray[this] = "F"
        }
    });
    $.each(tempArray, function (index) {
        if (this == "E") {
            number = index + 1;
            return false;
        }
    });
    return number;
}

2 个答案:

答案 0 :(得分:1)

    

    function nextHole(array,until) {
      this.array=array;
      this.lastIndex=0;
      this.lastItem=0;
      this.until=until;
      this.loopFinished=false;
      this.done=false;
      this.reset = function(){
          this.lastIndex=0;
          this.lastItem=0;
          this.done=false;
          this.loopFinished=false;
      }

      this.getNext = function(){

        if (this.done){
            return null;
        }

        if (!this.loopFinished){                
            for(loop=this.lastIndex;loop<this.array.length ;loop++){
                if (this.array[loop]!=this.lastItem+1){

                    this.lastItem++;
                    this.lastIndex=loop;
                    if (this.lastItem>until)
                        break;


                    return this.lastItem;
                }else{
                    this.lastItem=this.array[loop];
                }

            }

        }
        this.loopFinished=true;
        if (this.lastItem < this.until){
            return (++this.lastItem);
        }
        this.done=true;
        return null;
      }

    }


    var h = new nextHole([1,2,5,6,7,15],10);
    while(true){
        var n = h.getNext();
        if (n == null){
            break;
        }else{
            console.log(" yield: "+n);
        }
    }


    h.reset();
    while(true){
        var n = h.getNext();
        if (n == null){
            break;
        }else{
            console.log(" yield: "+n);
        }
    }



</script>

答案 1 :(得分:0)

我错了还是仅仅是以下内容?

function formula(n){ return n+1; }
var sequence = [1,3,5,0,0,0,0,0,0,0];
var i=0;
function findNextNumber() {
    for (; i<10; i++) {
        var x = formula(i);
        if (sequence[i] != x) {
            sequence.splice(i, 0, x); // insert x here
            sequence.length = 10; // chop of rest
            return x;
        }
    }
    // else
    return null/undefined/whatever;
}

> findNextNumber()
2
> findNextNumber()
4
> findNextNumber()
6
> findNextNumber()
7
> findNextNumber()
8
> findNextNumber()
9
> findNextNumber()
10
> findNextNumber()
whatever