• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shuffling array of ints

 
russell lloyd
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing a method for a CS assignment that is supposed to take in an array of ints and return the array shuffled. I read elsewhere on these boards where someone explained how to do this but with strings. I tried to follow their code making the appropriate changes for ints but I am having a problem.




the code works fine as long as original doesn't contain 0's but if it does then it results in an infinite loop I was wondering how I could maybe modify the code so that it could avoid this
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here's a slightly different approach

 
Kenneth Albertson
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by russell lloyd:
The code works fine as long as original doesn't contain 0's but if it does then it results in an infinite loop I was wondering how I could maybe modify the code so that it could avoid this


The general problem is that you are using the output array elements to hold two separate pieces of information: a not-set-yet flag, and the new value. To do this, the not-set-flag value has to be a value that won't occur in the input array.

If that isn't possible, the algorithm can't work. (You need an extra data structure for the not-set-yet flags.) If it is possible, you need to pre-initialize the output array with the not-set-yet value.
[ September 20, 2005: Message edited by: Kym Thompson ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic