Hi,

I need to select 5 distinct random numbers out of 20 in my java program.

I am able to select 5 random numbers,

But I want these 5 numbers to be distinct,,,i.e. unique

for e.g.

I dont want them to be like these 5,6,9,6,1 because 6 is repeated

I want unrepeated,distinct 5 numbers please ,,help

Recommended Answers

All 11 Replies

int[] number = new int[10];
int[] outnum = new int[10];
int l = 0;
int k;
int newNum;

Scanner scan = new Scanner(System.in);
for(int i = 0; i < 10; i++) {
System.out.print("Enter number: ");
newNum = scan.nextInt();  // read next number
k = 0;
while (k < l) {
if(newNum == outnum[k]) { // check if already there
l--;
break;    // no need to check the other
}
k++;
}
outnum[k] = newNum; //Either overwrites or adds a new number in the end of the array.
l++;
}

har58, you should make plan beforehand. For example,
(1) pre-store 20 existing random nmbers in an array.
(2) when executing program store the distinct 5 random numbers in another array one by one.

Should we start with the following code as clues:

public class RandomNumSelected{  
 
 int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    	.....
    	 
      }
}

comments: The random numbers vary in a range. For example, from 0 to 255 [0,255]
You may generate by:
(1) the static method rand() in Math class.
(2) Create a instance of the class Random:
Random ran = new Random();
int n = ran.nextInt(256);

commented: Thanks +1

@har58 if you already have code why don't you post it so we can see it and help you with what you already have instead of redoing it?

@musthafa.aj nice attempt but you misunderstand question

her58, perter_budo is right. Since you said "I am able to select 5 random numbers,.." you must have some code. How do you select?

I didnot post code,because I thought it might discourage someone to answer me,as the code is lengthy,,,

package login;

import java.awt.*; 

import java.awt.event.*; 

import javax.swing.*;

import java.sql.*;

import java.util.Random;


public class Student implements ActionListener
{

	private static String Previous = "Previous";

	private static String Next = "Next";

	private static String Close= "Close";

	

	
	JButton btnstart =new JButton("Start");

	JButton btnprevious =new JButton("Previous");

	JButton btnnext =new JButton("Next");

	JButton btnclose =new JButton("Close");
	
	
	
	JLabel lblrule=new JLabel("Instructions:");

	JLabel lblrule1=new JLabel("1) After 20 minutes the test would be automatically closed");

	JLabel lblrule2=new JLabel("2) You can close the test whenever you want by clicking  on close button");

	JLabel lblrule3=new JLabel("3) To start the test,click on start button ");


	JLabel lblque=new JLabel("");
	
	JRadioButton radop1=new JRadioButton("");

	JRadioButton radop2=new JRadioButton("");

	JRadioButton radop3=new JRadioButton("");

	JRadioButton radop4=new JRadioButton("");

	
	
	ButtonGroup bg=new ButtonGroup();

	

	public JPanel p1 = new JPanel();

	public JPanel p2 = new JPanel();

	CustomPanel panel = new CustomPanel();

	Color lemon=new Color(255,246,143);
	

	Student()
	{
		p1.setLayout(null);

		p1.setBackground(lemon);

		p1.setEnabled(false);

		p1.setVisible(false);



		p2.setLayout(null);

		p2.setBackground(lemon);

		p2.setEnabled(false);

		p2.setVisible(false);


		
		p1.add(lblrule); 

		p1.add(lblrule1); 

		p1.add(lblrule2); 

		p1.add(lblrule3); 

		p1.add(btnstart);



		p2.add(lblque);

		p2.add(btnnext);
		
		p2.add(btnprevious);

		p2.add(btnclose);

		p2.add(radop1);

		p2.add(radop2);

		p2.add(radop3);

		p2.add(radop4);

		bg.add(radop1);

		bg.add(radop2);

		bg.add(radop3);

		bg.add(radop4);
		
		 
			
		p1.add(panel);

		panel.setBounds(250,300,600,105);

		p1.setBounds(20,170,750,500);

		p2.setBounds(20,170,700,600);




		lblrule.setBounds(40,100,250,25);

		lblrule1.setBounds(40,150,410,25);

		lblrule2.setBounds(40,200,430,25);

		lblrule3.setBounds(40,250,410,25);

		btnstart.setBounds(145,300,90,25);

		
		
		lblque.setBounds(100,100,450,25);

		radop1.setBounds(100,150,300,25);

		radop2.setBounds(100,200,300,25);

		radop3.setBounds(100,250,300,25);

		radop4.setBounds(100,300,300,25);

		btnprevious.setBounds(100,350,90,25);

		btnnext.setBounds(250,350,90,25);

		btnclose.setBounds(600,150,90,25);
		


		radop1.addActionListener(this);

		radop2.addActionListener(this);

		radop3.addActionListener(this);

		radop4.addActionListener(this);
		
		btnstart.addActionListener(this);

		btnclose.addActionListener(this);
		
		btnprevious.addActionListener(this);

		btnnext.addActionListener(this);

		btnprevious.setActionCommand(Previous);

		btnnext.setActionCommand(Next);

		btnclose.setActionCommand(Close);


	}


	class CustomPanel extends JPanel
	{   

		public void paintComponent (Graphics painter)   
		{    
			
			Image pic =Toolkit.getDefaultToolkit().getImage("best.jpg");

			if(pic != null)
			
			painter.drawImage(pic, 130,10, this); 

			   

		}

	}

	public void actionPerformed(ActionEvent e) 
	{	String cmd = e.getActionCommand();

		Random rndNumbers = new Random();

		 int qno = 0;

		int marks=0;

		qno = rndNumbers.nextInt(4);  

		if (e.getSource()==btnstart) 
		{
			p1.setVisible(false);
		
			p2.setEnabled(true);

			p2.setVisible(true);
							
            		
				     		
							
				try
				{
					Class.forName("oracle.jdbc.driver.OracleDriver");

					String url="jdbc:oracle:thin:@localhost:1521:xe";

					String username="hr";

					String password="hr";

					Connection connection=DriverManager.getConnection(url,username,password);

					Statement statement=connection.createStatement();
        					
			 		String query1="Select question,op1,op2,op3,op4 from test where qno = "+ qno;

					ResultSet resultset=statement.executeQuery(query1);

					while(resultset.next())
					{
						lblque.setText(resultset.getString(1));
											
						radop1.setText(resultset.getString(2));

						radop2.setText(resultset.getString(3));

						radop3.setText(resultset.getString(4));

						radop4.setText(resultset.getString(5));
					
						
					}

					
					connection.close();			
 				}
				catch(ClassNotFoundException cnfe)
				{
	
					System.out.print("ERROR LOADING DRIVER: " + cnfe);

				}			
				catch(SQLException se)
				{ 
					System.out.print("SQL Exception  " + se);

				}


		}
				
			if (Next.equals(cmd)) 
			{
			
				try
				{
					Class.forName("oracle.jdbc.driver.OracleDriver");

					String url="jdbc:oracle:thin:@localhost:1521:xe";

					String username="hr";

					String password="hr";

					Connection connection=DriverManager.getConnection(url,username,password);

					Statement statement=connection.createStatement();
        					
			 		String query2="Select correct from test where qno = "+ qno;

					ResultSet resultset=statement.executeQuery(query2);

					while(resultset.next())
					{
						int corect = Integer.parseInt(resultset.getString(1));
						
						if(corect==1 && radop1.isSelected())
						{
							marks=marks+1;
						}
						else if(corect==2 && radop2.isSelected())
						{
							marks=marks+1;
						}
						else if(corect==3 && radop3.isSelected())
						{
							marks=marks+1;
						}					
						else if(corect==4 && radop4.isSelected())
						{
							marks=marks+1;
						}	
									
						
					}

					System.out.print(marks);
					connection.close();			
 				}
				catch(ClassNotFoundException cnfe)
				{
	
					System.out.print("ERROR LOADING DRIVER: " + cnfe);

				}			
				catch(SQLException se)
				{ 
					System.out.print("SQL Exception  " + se);

				}

						
			

			}


		


							
 	}



}

I know how to select random number,and i have used it too in my code.

Imagine idea of 20 questions, and you hav to select randomly 5 questions,

This thing I am able to do,

But the problem is ,Sometimes the same question is repeated

Suppose 7,9,11,13,7 random numbers were selected then problem is the same question 7 has been repeated

This is the thing I dont want,

Thank you friends who are helping me.

har58, you should make plan beforehand. For example,
(1) pre-store 20 existing random nmbers in an array.
(2) when executing program store the distinct 5 random numbers in another array one by one.

Should we start with the following code as clues:

public class RandomNumSelected{  
 
 int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    	.....
    	 
      }
}

comments: The random numbers vary in a range. For example, from 0 to 255 [0,255]
You may generate by:
(1) the static method rand() in Math class.
(2) Create a instance of the class Random:
Random ran = new Random();
int n = ran.nextInt(256);

yes I am getting your idea,,

I store the 5 ramndom numbers in an array,,

Then i recheck,,whether any number has been repeated,,,,

If any no. has been repeated,,,generate one more random no. and

again recheck,,,till all are distinct


I think the code will be complicated,,

You have an array of 20 items to chose from and want to chose 5 unique ones at random:
Have a parallel array of 20 boolean that you set true if that question has been chosen yet. And another array of 5 that you'll save the indexes to the array of 20 items.
Generate a random number from 1 to 20, test the boolean array if that number has been chosen yet, if it has, generate another random number. If it has not been chosen, save its index in the array of 5 and set its boolean to indicate its been chosen. Continue until there are 5 saved indexes.
The logic will require a forever loop with an array and index to that array.

commented: thanks +1

Yes ,I got you NormR1

Thank you so much,

Har
To save the repeated checking, you might try one of these methods:

1) Make an array of booleans and mark them "true" as you draw them. Generate a random integer, and check it against the list before you use it.
2) ArrayList can store Objects, which can be removed from the list as they are selected. You can index into the list with a random number in the range given by the list's length() method. That will get you unique random Objects of any sort, including Integers.

I hope the following code could help you.
I also made some comments to help you to understand.

import java.util.*;
public class RandomNumSelected{  
 
 static int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 static int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    Random rn = new Random();
    for (int i=0; i<20; i++)  //  assign 20 random values to the elements of array random 
    random[i]= rn.nextInt(256);
    
    int counter=0;
    selected[0]=random[0]; // the first random number is stored in selected array
    for (int i=1; i<5; i++)
     for(int j=1;i<random.length;j++)
    		if (search(random,i,random[j]) == -1){ // if the current selected array has no such value of random[j]
    		selected[i]=random[j]; // the random number random[j] is stored in the array selected
    		break;  //terminate the nested loop so that the next run for the outerloop starts
    		}    		
   	System.out.println("The 20 random numbers varying betwee 0 and 255 [0,255]: ");
   	for(int a:random)
   	System.out.print(a + " ");
   	System.out.println();  
   	System.out.println("The 5 distinct numbers selected from the above 20 numbers:"); 				
   for (int a:selected)
   System.out.print(a + " ");
   System.out.println();
    }
}

The output:
The 20 random numbers varying betwee 0 and 255 [0,255]:
191 197 185 70 15 205 58 94 130 209 11 79 156 47 169 51 251 156 64 37
The 5 distinct numbers selected from the above 20 numbers:
191 197 185 70 15

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.