Why my code compare only first and last number of array - Java - java

I want to get the minimum number of my array, but my "if" compare only checks the first and last positions of array.
Here is my code:
int[] randNumbers = new int[20]; //deklaracja nowej tablicy 20-elementowej
Random r = new Random(); // Dodana metoda random do losowania
for(int i=0; i<randNumbers.length; i++) {
randNumbers[i] = r.nextInt(101);
int min = randNumbers[0];
System.out.println("Number "+i+": " + randNumbers[i]);
if (randNumbers[i] < min) {
min = randNumbers[i];
}
if (i == randNumbers.length-1) {
System.out.println("Min number is: " + min);
}
}

You don't even need the array here. Just iterate from 0 to N and check each random number if it less than min:
Random r = new Random();
int min = 101; // assign max value 101 before loop
for(int i = 0; i < 20; i++) {
int number = r.nextInt(101);
System.out.println("Number " + i + ": " + number);
if (number < min) {
min = number;
}
}
System.out.println(min);
If you want use array, you could initialize it before. For example using Random.ints():
int[] randNumbers = new Random().ints(20, 0, 101).toArray();
And then use the same for-loop idea with randNumbers[i] instead of nextInt(101)

try this out, your int min = randNumbers[0]; resets the min value every time so move it out of the loop
int min = 100;
for(int i=0; i<randNumbers.length; i++) {
randNumbers[i] = r.nextInt(101);
System.out.println("Number "+i+": " + randNumbers[i]);
if (randNumbers[i] < min) {
min = randNumbers[i];
}
}
System.out.println("Min number is: " + min);

The issue is that you are not remembering the minimum number as the loop runs. If you make a variable outside of the loop, it won't get updated every single iteration. Your code might look something like this:
int[] randNumbers = new int[20]; //deklaracja nowej tablicy 20-elementowej
Random r = new Random(); // Dodana metoda random do losowania
int min = 0;
for(int i=0; i<randNumbers.length; i++) {
int number = r.nextInt(101);
if(i == 0) min = number;
randNumbers[i] = number;
System.out.println("Number "+i+": " + number);
min = Math.min(min, number);
}
System.out.println("Min number is: " + min);
A few things to notice:
The variable min was moved outside of the loop. This is to make sure it is persistent across the loop, and won't be updated every iteration of the loop.
A new variable number is introduced. This is to prevent you from constantly calling randNumbers[i], which looks nicer, and to my knowledge slightly speeds it up. It also make it easier to change the variable once, and have it effective everywhere it is needed.
The last S.O.P was moved outside of the loop. There is no point in checking if the loop is at the last element if you can just put the statement the line after the loop ends. It will work the same functionally, but this looks nicer.
Instead of using an if statement to set min, it uses the output of Math.min. This is just a cosmetic change, and behaves the exact same with an if statement.

Move min int outside loop with value 0 isn't working, because my result will be everytime because Not initialized array have only '0'
Move it with 100+ is good idea. It's working when we know maximum number.
#geneSummons "int min = Integer.MAX_INT"
This works very well with different range/scope of numbers:) Thanks
Btw. I still don't understand why it's compare only first and last number ;)

Related

How to randomly generate integers between 0 to 3 without making them consecutive in Java?

So far I have managed to generate random numbers using Random.
for(int i=0; i<10; i++){
prevnum = num;
num = random.nextInt(4);
num = num==prevnum?ran.nextInt(4):num;
System.out.println("random number: " + num);
}
I do not want consecutive repeats, what should I do?
EDIT/SOLUTION:
I solved the issue using this workaround.
By checking if it was running for the first time to avoid nullpointerexception.
And the just used an ArrayList to remove any chances of repitition by removing the previous randomly generated number from the small pool/range.
public void printRandom(){
for(int i=0; i<10; i++){
if(firstrun){
firstrun=false;
num = random.nextInt(4);
System.out.println(num);
} else{
num = getRandom(num);
System.out.println(num);
}
}
}
int getRandom(int prevNum){
ArrayList choices = new ArrayList(Arrays.asList(0, 1, 2, 3));
choices.remove(prevNum);
return (int) choices.get(random.nextInt(3));
}
You better to get a random number until it would be different with the last number, not just once, in other words repeat this condition:
num = num==prevnum?ran.nextInt(4):num;
like:
do {
num = num==prevnum?ran.nextInt(4):num;
while (num != prevnum);
because your numbers are few, they might be the same, so check it more than once if it is needed.
Try this
Random ran = new Random();
int cur, pre = ran.nextInt(4);
for (int i = 0; i < 10; i++) {
cur = ran.nextInt(4);
while (cur == pre) {
cur = ran.nextInt(4);
}
pre = cur;
System.out.println(cur);
}
If you do not want a consecutive repeat, then you always want the gap between two consecutive numbers to be non-zero. That you suggests you pick your first number normally, and from that point on you pick a random, but non-zero, gap. Add the gap to the previous number to get the next number, which will always be different.
Some pseudocode:
// First random number.
currentNum <- random(4);
print(currentNum);
// The rest of the random numbers.
repeat
gap <- 1 + random(3);
currentNum <- (currentNum + gap) MOD 4;
print(currentNum);
until enough numbers;

Finding a missing number in an array that uses a random generator

I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5

Attempting to create chance calculator

I am relatively new to Java and wanted to try and make a code that would randomly generate 2 numbers a set amount of times, and it would track how many times the 2 numbers are the same. Then after X amount of attempts it would calculate the chance of it happening.
# of randoms divided by times they were the same
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
int[] anArray;
anArray = new int[100000];
Random randomGenerator = new Random();
for (int loop = 1; loop < 1000; loop++) {
int random1 = randomGenerator.nextInt(100);
int random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
int number = number + 1;
countArray[number] = loop;
}
if (loop == 1000) {
System.out.println("Took " + loop + " randoms.");
break;
}
else {}
}
}
}
Main issue seems to be getting array to fill and to get ints in/out of the loop.
Here is my version of your code:
import java.util.Random;
import java.util.ArrayList;
public class RandomTest {
public static void main(String[] args) {
ArrayList<Integer> duplicates = new ArrayList<Integer>();
int random1 = 0, random2 = 0;
Random randomGenerator = new Random();
for (int loop = 1; loop <= 1000; loop++) {
random1 = randomGenerator.nextInt(100);
random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
duplicates.add(new Integer(random1));
}
}
for (Integer i : duplicates) {
System.out.println("Duplicate: "+i.toString());
}
}
}
There are a number of problems that your solution contains:
int number = number + 1;
The above will create a new int called number and give it the value null + 1, this is because the above can be split into 2 lines:
int num;
num = num + 1;
The first line will reserve memory space for a variable called num. The second line will try and put the value of (num + 1) into num. As we are calling num and it has not been initialised - this will give us a java.lang.Error (at least that is what I got).
So as you can see, putting number outside the for loop and initialising it like this:
int number = 0;
for (int loop = 1; loop <= 1000; loop++) {
number = number + 1;
}
Will increment the value of number by 1, 999 times.
Which brings me to the next point. The for loop will never make loop = 1000 because the condition will stop the loop before the condition is true, so when the for loop finishes, loop will equal 999. If you wanted the loop to finish on loop = 1000 you should use loop <= 1000. Also, the if condition is not necessary as when the loop finishes it will just carry on with the rest of the code beneath it.
I haven't used number at all in my solution, this is because I used an ArrayList, which is essentially a much more advanced version of an array that can grow dynamically and do loads of other cool stuff. Unfortunately ArrayLists need to contain objects, so I wrap each int inside an Integer object and this is fine. At the end I use a for loop to iterate through the duplicates list, for each result I print it out.
Hope this helps and if you have any questions feel free to comment beneath.
You probably want to do something about this line:
int number = number + 1;
To step through the array, set number to zero
int number = 0;
before entering the loop then increment number with
number = number + 1;

How to compare six integer variables and show which one it's the bigger one

In my application, I have six integer variables (int) and I want to compare them and choose the bigger one but I don't know how to do that. Could you help me please?
int numbers[] = new int[] {4,6,....};
int max = numbers[0];
for(int indx=1; indx<numbers.length; indx++){
if(max< numbers[indx]){
max = numbers[indx];
}
}
System.out.println("max=="+max);
int max = array[0];
for (int counter = 1; counter < array.length; counter++)
{
if (array[counter] > max)
{
max = array[counter];
}
}
System.out.println("The maximum number is: " + max);
You must have to try this,
max=array[0];
for (int counter = 1; counter < array.length; counter++)
{
if (array[counter] > max)
{
max = array[counter];
}
}
System.out.println("The maximum number is: " + max);
It works 100%.
Write a simple bubble sort method and then choose the last element which will give you the biggest integer value.
You can find pseudo code here: http://en.wikipedia.org/wiki/Bubble_sort
PS: Only use bubble sort because you have only six elements. Otherwise it is discouraging to use bubble sort.
I think there are 2 scheme for your task:
firstly you should put these data into an array ,and that will make your work easier.
1.iterate all the data and select the biggest one
int biggest=-10000000;//this is just a compare tag
for(i=0;i<6;i++)
{
if(array[i]>biggest)
biggest=array[i];
}
printf("%d\n",biggest);
2.sort this array,for instance ,rank these data ascendingly.
so just choose the max index of this array as max value;

Java duplicates distinct unique array value

I am trying to solve this, but i don't know how...
Values[10] = {1,1,4,4,2,3,3,2,1,3}
to print:
{1,2,3,4} or {1,4,2,3} (not sorted, any order, but distinct)
I also need to count the number of times each number has occurred, both without sort, new arrays or boolean methods or other data structures, please advise as i am stuck.
Is there a simple method i can use to just print the unique values/ distinct values ?
It can be accomplished if your are willing to destroy your current array. and you assume that the array is either of type Integer (so nullable) or if not there is some bound such as all int are poistive so you can use -1.
for(int i = 0; i < values.length; i++){ //for entire array
Integer currVal = values[i]; // select current value
int count = 1; // and set count to 1
if(currVal != null){ // if value not seen
for( int j = i + 1; j < values.length; j++){ // for rest of array
if(values[j] == currVal){ // if same as current Value
values[j] = null; // mark as seen
count++; // and count it
}
}
System.out.print("Number : " + currVal + " Count : " + count + "\n");
//print information
}
// if seen skip.
}
In plain english, Go through the array in 2 loops, roughly O(n^2) time.
Go to index i. If index has not yet been seen (is not null) then go through the rest of array, mark any indexs with same value as seen (make it null) and increment count varable. At end of loop print value and count. If Index has be seen (is null) skip and go to next index. At end of both loops all values will be left null.
Input : Values[] = {1,1,4,4,2,3,3,2,1,3}
Output : Values[] = {1,null,4,null,2,3,null,null,null,null}
Number : 1 Count : 3
Number : 4 Count : 2
Number : 2 Count : 2
Number : 3 Count : 3
Edit: corrected my mistake in output, pointed out by commenters.
Another solution, without creating additional objects:
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
if (i == 0 || value[i] != value[i-1]) {
System.out.println(values[i]);
}
}
And the shortest solution I can think of:
Integer[] values = {1,1,4,4,2,3,3,2,1,3};
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(values));
System.out.println(set);
Assuming the values are guaranteed to be integers, you could also do it by incrementing a check value, scan over the array, sum the number of that check value in the array, add it to an accumulator and loop while the accumulator < array.length.
Something like this (untested):
public void checkArray(int[] toCheck) {
int currentNum = 0;
int currentCount = 0;
int totalSeen = 0;
StringBuilder sb = new StringBuilder();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0; i<toCheck.length; i++) {
min = Math.min(toCheck[i], min);
max = Math.max(toCheck[i], max);
}
System.out.print("{ ");
for(currentNum = min; currentNum < max; currentNum++) {
for(int i=0; i<toCheck.length; i++) {
if(toCheck[i] == currentNum) currentCount++;
}
if(currentCount != 0) {
if(currentNum == min) System.out.print(currentCount + "(" +currentCount+ ")");
else System.out.print(", " + currentCount + " (" +currentCount+ ")");
}
totalSeen += currentCount;
currentCount = 0;
}
System.out.println(" }");
}
It should be noted that while this technically fulfills all your requirements, it will be far less efficient than gbtimmon's approach.
If your ints were {1,2,3,150000}, for example, it will needlessly spin over all the values between 4 and 149999.
Edit: added better limits from tbitof's suggestion.
Your question isn't quite clear to me, since it sounds like you want to do these things without creating any additional objects at all. But if it's just about not creating another array, you could use a Map<Integer, Integer>, where the key is the number from your original array, and the value is the count of times you've seen it. Then at the end you can look up the count for all numbers, and print out all the keys by using Map.keyset()
Edit: For example:
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for( int i : values ) {
if( counts.containsKey(i) ) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
// get the set of unique keys
Set uniqueInts = counts.keyset();

Categories