The problem is to find the minimum number in the random array 50 numbers. It should be between 0-100 and its index. I don't know what's the wrong with my code. It prints more than one minimum value and I haven't found a way to make limit to the array:
You are not generating random number properly.
To find a random number in range 0..99,use
Random r = new Random();
int randomInt = r.nextInt(100);
Try this
public class RandomTest {
public static void main(String[] args) {
int arr[] = new int[50];
Random r = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(100);
System.out.println(arr[i]);
}
int minimum = arr[0];
for (int j = 1; j < arr.length; j++) {
if (minimum > arr[j])
minimum = arr[j];
}
System.out.println("Minimum value-->" + minimum);
}
}
Output
Output will vary as per the generated number.In my case,I got
Minimum value-->4
You shouldn't print inside the "for" loop.
The loop determines which value is the minimum.
Once it has ended, print the result.
for{
...
...
}
System.out.println(Minimum);
You can use the following code:
int[] a = ...; // after random for
int min = a[0];
int minIndex = 0;
for(int i = 1; i < a.length(); i++) {
if(a[i] < min) {
min = a[i];
minIndex = i;
}
}
System.out.println(minIndex);
Related
I'm very new to coding.
I'm writing this code and I'm struggling because I need to make a code that makes an array with 8 random integers and then it swaps the largest integer with the first number in the array.
When doing this though I'm getting an error and I cannot seem to fix it.
import java.util.Scanner;
import java.util.Random;
public class finalExam {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
Random spinner = new Random();
int [] userInputs = new int [8];
for (int i = 0; i < userInputs.length; i++) {
userInputs[i] = spinner.nextInt(100)+1;
System.out.println(userInputs[i]);
}
int largest = userInputs[0];
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest)
largest = userInputs[j];
}
System.out.println("Your largest number is: " + largest);
int holder;
int [] arr = new int[101];
for (int m = 0; m <= arr.length; m++) {
holder = largest;
userInputs[0] = userInputs[largest];
holder = userInputs[0];
}
}
}
The error comes from the last bit of your code. userInputs[largest] is out of bound because the array is only 8 integers long (while largest can have a value of 100).
Since you need the position of the largest number, you'll have to save it in largestPosition when you identify which number is the largest, like so:
int largest = userInputs[0];
int largestPosition = 0;
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest){
largest = userInputs[j];
largestPosition = j;
}
}
That said, the loop which you used at the end also isn't needed here. You could just swap the first value of the array with the largest one using this method:
int first = userInputs[0];
userInputs[0] = largest;
userInputs[largestPosition] = first;
I am trying to get the indices of large numbers within an array and I am having trouble doing so..
My code works if there is only one large number in the array. However, if there is one or more of the same large number, it does not works.
For example,
if I have an array {2,1,1,2,1}, it should return me the index 0 and 3 (this does not)
if I have an array {2,1,3,2,1}, it will then return me index 2. (this works)
Currently, I am trying to store the index by making use of an array, however in my code, as given in my example above, it only returns me the index of the first large number it found.
My code:
class Main {
public static void getIndexOfMax(int array[]) {
int max = array[0];
int pos = 0;
int max_index[] = new int[array.length];
int counter = 0;
for(int i=1; i<array.length; i++) {
if (max < array[i])
{
pos = i;
max = array[i];
max_index[counter] = pos;
counter += 1;
}
}
public static void main(String[] args) {
int[] num = {2,1,1,2,1};
getIndexOfMax(num);
}
}
Thanks in advance for any replies!
You need to check another case when you find the maximum value again and store the index. And when the new maximum value starts the counter from 0 again.
public static void printIndexOfMax(int array[]) {
int max = 0;
int max_index[] = new int[array.length];
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (max <= array[i]) { // Allowing same maximum number
if (max < array[i]) // Start counter from 0 when new maximum value found
counter = 0;
max = array[i];
max_index[counter] = i;
counter++;
}
}
for (int i = 0; i < counter; i++) {
System.out.println(max_index[i]);
}
}
You can have another conditional stating, if max is equal to an array element, then store that element index also. Then you would have to declare another array for the max index positions.
`if (max < array[i]) {
pos = i;
indexStorage.add(pos)
max = array[I];
max_index[counter] = pos;
counter += 1;
}`
I know this may stand for a silly question but I have got a lot of problems with this.
I will first explain how it should work :
1)Generate random Array with size in range <4,7>
2)Fill it with random elements in range <100, 999>
3)Print the index of three numbers with biggest digit sum
So the question is-how? I know I should implement this:
SumOfDigits += ElementFromArray % 10;
ElementFromArray /= 10;
But i have got no idea where. I tried to add this as a if (i>0) loop inside for loop-but its not working.
Also how at the end im going to print the proper elements? Should I use Arrays.sort(tab) and then System.out.println(tab[tab.length - 1]) (and so on with -2, -3 for 3 last elements)?
import java.util.Arrays;
import java.util.Random;
public class Ex1 {
public static void main(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int tab[] = new int[size];
for (int i = 0; i < tab.length; i++) {
int elements = rand.nextInt(900) + 100;
tab[i] = elements;
}
System.out.println(Arrays.toString(tab));
}
}
If we aim for a solution using only arrays I would use a 2d array to hold the sum of digits and the index of the corresponding number in the tab array
So first create the array based on the size of the original array
int[][] sums = new int[size][2];
then in the for loop, calculate the sum of the random number and store it and the index
sums[i][0] = elements / 100 + (elements / 10) % 10 + elements % 10;
sums[i][1] = i;
Then sort the sums array using a custom comparator
Arrays.sort(sums, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
And finally print the index and number of the numbers of the top 3
for (int i = 0; i < 3; i++) {
System.out.printf("%d: %d\n", sums[i][1], tab[sums[i][1]]);
}
Just use while loop: here is a quick and dirty solution:
private static void main10(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int[] tab = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = rand.nextInt(900) + 100;
tab[i] = element;
}
System.out.println(Arrays.toString(tab));
// calculate digits:
int[] digitsums = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = tab[i];
int sumOfDigits = 0;
while (element > 0) {
sumOfDigits += element % 10;
element /= 10;
}
digitsums[i] = sumOfDigits;
}
System.out.println(Arrays.toString(digitsums));
int[] copyOfdigitsums = Arrays.copyOf(digitsums, digitsums.length);
for (int i = 1; i <= 3; i++) {
int j = getIndexOfLargest(copyOfdigitsums);
System.out.println("index of " + i + "largest is " + j + ", with a digitsum of " + copyOfdigitsums[j]);
copyOfdigitsums[j] = 0;
}
}
static int getIndexOfLargest(int[] digitsums) {
int largest = 0;
int index = 0;
for (int i = 0; i < digitsums.length; i++) {
int d = digitsums[i];
if (largest < d) {
largest = d;
index = i;
}
}
return index;
}
I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50
(inclusive) and finds the maximum and minimum number.
I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.
import java.util.Scanner;
import java.util.Random;
class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in .nextInt();
System.out.println();
int x;
int randNum;
int y;
//create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
} //for
} //for
} //main method
} //class
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
Look closely at this code. Inside the loop, you are setting
largest = array[s];
and then immediately checking
if (array[s] > largest)
Of course it's not, you just made them equal!
Put the assignments inside the conditions:
// Remove largest = array[s]
if (array[s] > largest) {
largest = array[s];
}
Similarly for smallest.
Note: I would recommend against commenting on closing braces. Note only is it unnecessary effort, it is confusion-prone: in this snippet of code above, the //for and //if are reversed. Additionally, it doesn't tell you which "if" or "for" it is closing.
Simply looking at the indentation is an easier way.
Your program does not fill the array with random numbers. It creates several arrays and fills each of them with a single number. You should change this part of the program:
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
/* min-max code */
}
}
to this:
Random r = new Random();
int[] array = new int[userNum];
for (int i = 0; i <= userNum; i++) {
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]);
}
/* min-max code */
This will create a single array, fill it with random numbers, and print each element of the array, which seems to be what you intended.
The code that finds the minimum and maximum is also incorrect.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
} else if (array[s] < smallest) {
System.out.println(smallest);
}
}
You should only set largest or smallest when array[s] is actually the largest or smallest value in the array so far. To check whether or not this is the case, you can use Math.min() and Math.max(), which return the smallest or largest, respectively, of two values.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = Math.max(array[s], largest);
smallest = Math.min(array[s], smallest);
}
System.out.println(largest);
System.out.println(smallest);
This is what you looking for::
import java.util.Scanner;
import java.util.Random;
public class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in.nextInt();
System.out.println();
int x;
int randNum;
int y;
int[] array = new int[userNum];
// create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println("number " + i + ":: " + randNum);
array[i - 1] = randNum;
}
// print array
for (int s = 0; s < array.length; s++) {
System.out.println("array[" + s + "] number :: " + array[s]);
}
// find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
if (array[s] > largest) {
largest = array[s];
// find min
} else if (array[s] < smallest) {
smallest = array[s];
}
}
System.out.println("\nLargets Number:: " + largest);
System.out.println("Smallest Number:: " + smallest);
} // main method
} // class
Don't confuse too much when you are using loops.Some mistakes you done while writing code.
1> You have declared array int[] array = new int[userNum];
in for loop. which mean it will create as much arrays as loop iterate. and not accessible outside loop.
2> Same with variables largest and smallest int largest = array[0];
int smallest = array[0];
3> for (x = 1; x < 1; x++) control never ever enter the loop since your condition x<1 is never satisfy because you have initiated x=1 and and it will never ever be less than 1 as in condition (x<1).
Suggestion :: To find largest you have to traverse through array and check every element for largest and smallest and store it in separate variable rather than printing it at every check.
In my code i have used three for loops::
1>> to generate and print random number. In same loop i'm filling array with generated number.
2>> Here just printing array separately for better presentation in output.
3>> Finding largest and smallest by assigning values in if block if they satisfy condition.
I hope this will help you to understand code.
Im trying to generate an array with 1000 integers of non-repeating numbers in ascending order from 0 to 10,000
So far what I have is:
public static void InitArray(int[] arr) { // InitArray method
int i, a_num; // int declared
Random my_rand_obj = new Random(); // random numbers
for (i = 0; i <= arr.length-1; i++) // for loop
{
a_num = my_rand_obj.nextInt(10000); // acquiring random numbers from 0 - 10000
arr[i] = a_num; // numbers being put into array (previoulsy declared of size 1000)
}
}
public static void ShowArray(int[] arr) { // ShowArray method
int i; // int declared
for (i = 0; i <= arr.length-1; i++) { // for loop
System.out.print(arr[i] + " "); // show current array content
}
System.out.println(); // empty line
}
public static void Sort(int[] arr) { // SortArray method
int i, min, j; // int decalred
for (i = 0; i < arr.length-1; i++) { // for loop
min = i; // min is i
for (j = i + 1; j < arr.length; j++) { // nested for loop
if (arr[j] < arr[min]) { // if statement
min = j; // j is the new minimum
}
}
int swap = arr[min]; // swap "method"
arr[min] = arr[i];
arr[i] = swap;
}
}
Is there any way to check the numbers are not repeating? Is there a function besides the random generator that will let me generate numbers without repeating? Thanks for any help
You can declare array of size 10,000
and init the array in away that each cell in the array will holds the value of it's index:
int [] arr= new int[10000];
for (int i=0 i < arr.length; i++){
arr[i] = i
}
Now you can shuffle the array using java Collections.
and take the first 1000 items from the array and sort then using java sort.
This will do I believe..
HashSet hs = new HashSet();
for(int i=0;i< arr.length;i++)
hs.add(arr[i]);
List<Integer> integers=new ArrayList<>(hs);
Collections.sort(integers);
A very simple solution is to generate the numbers cleverly. I have a solution. Though it may not have an even distribution, it's as simple as it can get. So, here goes:
public static int[] randomSortedArray (int minLimit, int maxLimit, int size) {
int range = (maxLimit - minLimit) / size;
int[] array = new int[size];
Random rand = new Random();
for (int i = 0; i < array.length; i++ ) {
array[i] = minLimit + rand.nextInt(range) + range * i;
}
return array;
}
So, in your case, call the method as:
int randomSortedArray = randomSortedArray(0, 10_000, 1_000);
It's very simple and doesn't require any sorting algorithm. It simply runs a single loop which makes it run in linear time (i.e. it is of time complexity = O(1)).
As a result, you get a randomly generated, "pre-sorted" int[] (int array) in unbelievable time!
Post a comment if you need an explanation of the algorithm (though it's fairly simple).