In: Computer Science
Write a java program creating an array of the numbers 1 through 10. Shuffle those numbers.
Randomly pick a number between one and ten and then sequentially search the array for that number.
Once the number is found, place that number at the top of the list.
Print the list. Perform #3 thru #5 ten times.
SOURCE CODE:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new
Scanner(System.in);
int arr[] =
{1,2,3,4,5,6,7,8,9,10}; //array that stores 1-10 numbers
int
t,i,j,r,search_element,iterations;
System.out.println("Intial Array: ");
for(i = 0; i
< 10; i++)
{
System.out.print(arr[i]+" "); //printing array
values
}
Random rn = new
Random();
for
(i=(arr.length-1); i> 0; i--)
{
r=rn.nextInt(i + 1); //selecting random integer
t= arr[r]; //rando
arr[r] = arr[i];
arr[i] = t;
}
System.out.print("\nShuffled array: ");
System.out.println();
for(i = 0; i < 10; i++)
{
System.out.print(arr[i]+" "); //printing array
values
}
System.out.print("\nEnter number of iterations(3 or 5):");
iterations=sc.nextInt();
ArrayList<Integer> Arrlist = new
ArrayList<Integer>(iterations); // if 5 iterationsn then set
list size 5
i=iterations; //
5 or 3 iteration
while(i>0)
{
search_element=arr[rn.nextInt(10)];
//selecting random search_element in the array
System.out.println("Iteration
:-"+(iterations-i));
System.out.println("Search element is:"+
search_element);
for(j=0;j<arr.length;j++)
{
if(arr[j]==search_element)
{
System.out.println("Found element :"+search_element+" At index:
"+j);
Arrlist.add(search_element);
break;
}
}
System.out.println("Array list is:
"+Arrlist);
i--;
System.out.println();
}
}
}
CODE SCREENSHOT:
OUTPUT-1:
OUTPUT-2:
OUTPUT-3: