Last number standing problem: extract number at specified position in array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thesinnerishere
    New Member
    • Jul 2008
    • 6

    Last number standing problem: extract number at specified position in array

    this is regarding the last number standing problem.
    it requires the number in an array to be extracted at a specified position .
    then the array needs to traverse through the right position of the extracted number until there's the last number in the array. that number is the answer.
    for eg.
    if the specified position is 2
    then in the array 1,2,3,4,5

    it should go this way
    1,3,4,5
    1,3,5
    3,5
    3 ---.the answer
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    What have you tried so far? Please post your code.

    Please remember to provide a meaningful Title for any threads started (see the FAQ entry Use a Good Thread Title).

    Comment

    • hsriat
      Recognized Expert Top Contributor
      • Jan 2008
      • 1653

      #3
      Code:
      <script type="text/javascript">
      
      //inputs
      var position = 2;
      var arr = new Array (1,2,3,4,5);
      
      //function
      var offset = 0;
      while (arr[1]) {
      	var p = position - offset - 1;
      	while (!arr[p])
      	p -= arr.length;
      	while (arr[p]) {
      		offset = arr.length - p - 1;
      		arr.splice(p, 1);
      		//document.write(arr + '<br>' );
      		p += position - 1;
      	}
      }
      document.write ('<br>Answer = ' + arr[0]);
      </script>
      I didn't find it very easy.

      Regards

      Comment

      • thesinnerishere
        New Member
        • Jul 2008
        • 6

        #4
        Originally posted by hsriat
        Code:
        <script type="text/javascript">
        
        //inputs
        var position = 2;
        var arr = new Array (1,2,3,4,5);
        
        //function
        var offset = 0;
        while (arr[1]) {
        	var p = position - offset - 1;
        	while (!arr[p])
        	p -= arr.length;
        	while (arr[p]) {
        		offset = arr.length - p - 1;
        		arr.splice(p, 1);
        		//document.write(arr + '<br>' );
        		p += position - 1;
        	}
        }
        document.write ('<br>Answer = ' + arr[0]);
        </script>
        I didn't find it very easy.

        Regards





        thank you for the help. the concept of offset helped a lot.
        thank you very much.

        Comment

        Working...