Java Beginners

Moderators: zibadian
Number of threads: 1233
Number of posts: 2675

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Help in Array- radom number without duplicate elements Posted by John_Shok on 1 Oct 2010 at 3:33 PM
say we have,
int a[]=int a[5];

how do we fill 5 elements i.e 1,2,3,4,5 randomly in a[i](where i=0..4). using for loop.
example
a[0]=4
a[1]=2;
a[2]=3;
a[3]=5
a[4]=1

I was practicing arrays. I came up with this thought but i couldn't figure it out. I can fill random number using for loop, but random number generates duplicate number.I was trying to figure out without duplicate number..
Thank you
Report
Re: Help in Array- radom number without duplicate elements Posted by anthrax11 on 3 Oct 2010 at 3:30 AM
You could fill the array with numbers 1...5. Then generate two random numbers 0...4 and exchange the elements at those random positions. This could be done several times.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.