By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,481 Members | 1,213 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,481 IT Pros & Developers. It's quick & easy.

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

P: 6
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
Jul 1 '08 #1
Share this Question
Share on Google+
3 Replies


acoder
Expert Mod 15k+
P: 16,027
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).
Jul 1 '08 #2

hsriat
Expert 100+
P: 1,654
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.  
  3. //inputs
  4. var position = 2;
  5. var arr = new Array (1,2,3,4,5);
  6.  
  7. //function
  8. var offset = 0;
  9. while (arr[1]) {
  10.     var p = position - offset - 1;
  11.     while (!arr[p])
  12.     p -= arr.length;
  13.     while (arr[p]) {
  14.         offset = arr.length - p - 1;
  15.         arr.splice(p, 1);
  16.         //document.write(arr + '<br>' );
  17.         p += position - 1;
  18.     }
  19. }
  20. document.write ('<br>Answer = ' + arr[0]);
  21. </script>
I didn't find it very easy.

Regards
Jul 1 '08 #3

P: 6
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.  
  3. //inputs
  4. var position = 2;
  5. var arr = new Array (1,2,3,4,5);
  6.  
  7. //function
  8. var offset = 0;
  9. while (arr[1]) {
  10.     var p = position - offset - 1;
  11.     while (!arr[p])
  12.     p -= arr.length;
  13.     while (arr[p]) {
  14.         offset = arr.length - p - 1;
  15.         arr.splice(p, 1);
  16.         //document.write(arr + '<br>' );
  17.         p += position - 1;
  18.     }
  19. }
  20. document.write ('<br>Answer = ' + arr[0]);
  21. </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.
Jul 2 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.