Problem:
Write a program called FindValue. The program creates an
array of 20 integers, and initializes this array to some values. The program
will then ask the user to enter three integer values and searches the array for
the first of any of these values. Once one of the values is found, the
program will display which value of the three is found first and the
location where it was found. No further searches are performed. If however none
of the three values was found, then the program must indicate that to the user.
Once done, calculate the complexity (Big O) of your program.
For example if the array is as follows (Notice that this is
just an example; your solution must NOT refer to this example in anyways):
12
|
18
|
33
|
80
|
22
|
25
|
19
|
25
|
90
|
76
|
25
|
45
|
83
|
10
|
21
|
10
|
74
|
80
|
14
|
7
|
and the user enters 10, 25 and 80 then the output should
look like the following:
One of the three values, 80, was found first. It was
found at index #4.
On the other hand, if the user enters 88, 16 and 36 then the
output will be as follows:
None of the three values was found in the array.
The initial part of the solution is given below to assist
you.
Import java.util.Scanner;
Public class FindValue{
Public static void main(String[]
args) {
int v1, v2, v3,
i; //Read the three values and put them in v1, v2 and v3
…….
}//end of main
} //end of
class FindValue
Solution:
import java.util.Scanner; public class FindValue { public static void main (String[] args) { int v1, v2, v3, i; //Read the three values and put them in v1, v2 and v3 Scanner scan = new Scanner(System.in); int index=0, value=0; int[] nums = new int[20]; v1 =scan.nextInt(); v2 =scan.nextInt(); v3 =scan.nextInt(); for (i= 0; i < nums.length;i++) nums[i] = (int)(Math.random()*20 + 1); for (i = 0; i < nums.length;i++) { if (v1 == nums[i]) { index = i; value = nums[i]; break; } else if (v2 == nums[i]) { index = i; value = nums[i]; break; } else if (v2 == nums[i]) { index = i; value = nums[i]; break; } } if (value == 0) System.out.println("None of the three " + "values was found in the array."); else System.out.println("One of the three values, " + value + " was found first." + " It was found at index #" + index + "."); /** *The complexity is O(n). */ }//end of main } //end of class FindValue
after liposuction Korea's #1 Liposculpture Clinic. Lydian plastic surgery is the home of VIP patients. Celebrities, Influencers and Diplomats all know and trust Doctor An and Lydian plastic surgery clinic to provide detailed results.
ReplyDelete