2016-02-28 58 views
0

我该如何在排序顺序中做到这一点?如何将其变为排序顺序?

此位置分配:https://jsfiddle.net/debhxnqc/27/

的代码是在这里:

Guess: 

<input type="textbox" id="index" value="12"> 
<br/> Get Number: 

<button id="click" onclick="InsertGuess(1000,0,'',0)">Generate</button> 
<div id="guess"></div> 

<script> 

var InsertGuess = function(max, min, finalStr, count) { 
    var str = 'Guessed :'; 
    var guessnum = Math.floor(Math.random() * (max - min + 1) + min); 

    if (document.getElementById('index').value > guessnum) { 
    finalStr = finalStr.concat(guessnum, ' too low <br>'); 
    count = count + 1; 
    return InsertGuess(max, guessnum, finalStr, count); 
    } else if (document.getElementById('index').value < guessnum) { 
    finalStr = finalStr.concat(guessnum, ' too high <br>'); 
    count = count + 1; 
    return InsertGuess(guessnum, min, finalStr, count); 
    } else { 
    count = count + 1; 
    finalStr = finalStr.concat(guessnum, ' Got it !!!<br>'); 
    finalStr = finalStr.concat('It took me ' + count + ' tries '); 
    document.getElementById('guess').innerHTML = finalStr; 
    return; 
    } 
} 


</script> 

笔者获悉,这需要在排序顺序做按下“生成按钮”时。

**Example**: When pressing generate the result would show: 

532 too high 
47 too high 
14 too high 
8 too low 
10 too low 
11 too low 
12 Got it !!! 
It took me 7 tries 

相反,我被告知这需要显示为:

532 too high 
147 too high 
214 too high 
98 too low 
76 too low 
45 too low 
12 Got it !!! 
It took me 7 tries 

在排序顺序。我会怎么做?

+0

使用数组(S),如果你要对它进行排序 – charlietfl

回答

0

var InsertGuess = function(max,min,finalStr,count) { 
 
    var sortedArray = []; 
 
    var guess = function (max,min,finalStr,count) { 
 
    var guessnum = Math.floor(Math.random() *(max-min+1)+min); 
 
    if(document.getElementById('index').value > guessnum){ 
 
     sortedArray.push([guessnum , ' too low <br>']); 
 
     count=count+1; 
 
     return guess(max,guessnum,finalStr,count); 
 
    }else if(document.getElementById('index').value < guessnum) { 
 
     sortedArray.push([guessnum, ' too high <br>']); 
 
     count=count+1; 
 
     return guess(guessnum,min,finalStr,count); 
 
    }else{ 
 
     count=count+1;  
 
     sortedArray.sort(function (a,b) {return b[0] - a[0]}); 
 
     finalStr = finalStr.concat(sortedArray.join('')); 
 
     finalStr = finalStr.concat(guessnum , ' Got it !!!<br>'); 
 
     finalStr = finalStr.concat('It took me '+ count +' tries '); 
 
     document.getElementById('guess').innerHTML= finalStr; 
 
     return ; 
 
    } 
 
    } 
 
    guess(max,min,finalStr,count); 
 
}
Guess: 
 
<input type="textbox" id="index" value="12"> 
 
<br/> Get Number: 
 

 
<button id="click" onclick="InsertGuess(1000,0,'',0)">Generate</button> 
 
<div id="guess"></div>

+1

谢谢改写了!此代码工作得非常出色;我明白你现在是怎么做到的。 –

+0

我刚刚在算法结尾对数据进行了排序,但有一种方法可以使其实际增量。我已经做了一个演示[在这里](http://jsbin.com/puxopo/1/edit?js,output),注意到我仍然在那里排序,因为当猜测较低时,我们必须去无论如何。 – rafaelcastrocouto