finding maximum number in ArrayList - java

this is my practice before my upcoming test, I'm trying to make the user input a number. And all elements in array1 that is below the user's number, will be put in a new ArrayList.
and then I'm trying to print only the highest number in that ArrayList. If the user input is lower than all number in array1, it will return -1.
here is my code, however, when I put 920, it still returns -1, I think there's something wrong with my code to find highest number in ArrayList. Can you guys please tell me what is wrong?
static Scanner sc = new Scanner(System.in);
static int[] array1 = {900, 885, 989, 1000, 1500, 1243, 999, 915};
public static int blabla(int[] a, int b) {
Integer d = -1;
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < array1.length; i++) { // this is to find all numbers in array1 that is below user's number, and add it to the ArrayList
if (b > array1[i]) {
al.add(array1[i]);
} // if
} // for
outerloop: // and this function below is to find maximum number in ArrayList
for (int g = (al.size()-1); g == 0; g--) {
for (int j = 0; j <=(g-1); j++) {
if (al.get(j) > al.get(g)) {
break;
}
else if(j == (g-1)) {
if (al.get(g) > al.get(j)){
d = al.get(g);
break outerloop;
}
}
} //for^2
} // for
return d;
} // priceisright

static Scanner sc = new Scanner(System.in);
static int[] array1 = {900, 885, 989, 1000, 1500, 1243, 999, 915};
public static int blabla(int[] a, int b) {
Integer d = -1;
ArrayList<Integer> al = new ArrayList<Integer>();
At this point, a1 is an empty array, so a1.length = 0, this loop never gets executed.
for (int i = 0; i < a1.length; i++) {
// this is to find all numbers in array1 that is below user's number,
// and add it to the ArrayList
if (b > a1[i]) {
al.add(a1[i]);
} // if
} // for
a1 is still empty there, the second loop won't do anything either.
// and this function below is to find maximum number in ArrayList
outerloop:
for (int g = (al.size()-1); g == 0; g--) {
for (int j = 0; j <=(g-1); j++) {
if (al.get(j) > al.get(g)) {
break;
}
else if(j == (g-1)) {
if (al.get(g) > al.get(j)){
d = al.get(g);
break outerloop;
}
}
} //for^2
} // for
return d;
} // priceisright
What about this:
// Finds the greater value in values that is below maximum.
// Returns -1 if none is found.
public static int blabla(int[] values, int maximum) {
int best_value = -1;
for (int value : values) {
if (value < maximum && value > best_value) {
best_value = value;
}
}
return best_value;
}
You can replace int[] values by List<Integer> values if your values are in an ArrayList.

You can use this
Collections.max(arrayList);
To know more about read Javadoc for Collection.max

If you want to use an ArrayList you can check fro maximum with linear time by,
public static Integer getMaximum(List<Integer> coll) {
if (coll == null) {
return null;
}
Integer i = coll.get(0);
for (int t = 1; t < coll.size(); t++) {
Integer v = coll.get(i);
if (v != null && v > i) {
i = v;
}
}
return i;
}
Or, you could change that to a SortedSet<Integer> set = new TreeSet<Integer>(); then the maximum element is always set.last();

I would simplify your two for loops by this one:
for (int g = 0; g <=(al.size()-1); g++) { //for each value in your new array
d = (al.get(g)>d)? al.get(g):d; //is current value higher than previous? if not keep old one
}

Simple way to find the max in an array or arrayList (or any collection actually) without using built in methods such as .max
Int currentMax = 0
For (int i = 0; i < al.length; i++)
{
If al[i] > currentMax
{
CurrentMax = al[i]
}
}
Answered this from my phone so I apologize for bad indents, but you get the idea :)

Related

randomly generate 100 unique numbers using Math.random [duplicate]

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

Want to use an array created in a method, for further use in another method

I have a problem and the title actually sums it up perfectly. So i'll just go ahead and show you the code snippet.
So the methode generate, is generating an array, that is filled with numbers between 1 and 1000, including both. The length of the array is user input.
The next method, isPrime, is gonna conclude if its a prime number, so i can use those numbers with the true condition in another method. The generate method works but in isPrime i always get errors. If u can think of a better way, let me know please.
static int[] generate(int n) {
int[] arr = new int[n+1];
for(int x = 0; x <= n; x ++) {
int number = (int) (Math.random()* 999)+1;
arr[x] = number;
}
return arr;
}
static int isPrime(int p, final int q[]) {
boolean itIs = true;
//final int[] arr;
for(int r = 0; r <= p; r++) { // here it somehow states r is deadCode
for(int j = 2; j < q[r]; j++) {
if(q[r]%j == 0) {
itIs = false;
}
}
return q[r];
}
}
First, create a method to check a value is prime:
public boolean isPrime(int value) {
for (int i = 0; i < value / 2; i++) { // value / 2 is enough, doesn't need to check all values
if (value % i == 0) {
return false;
}
}
return true;
}
Then you check each value of array and put prime value to new array:
public int[] filterArray(int[] array) {
List<Integer> intList = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (isPrime(array[i])) {
intList.add(array[i]);
}
}
Integer[] integerArray = intList.toArray(new Integer[intList.size()]);
int[] intArray = ArrayUtils.toPrimitive(integerArray);
return intArray;
}
Then you get the filtered prime array.

How do you find the mode of an Array in java?

I'm new to java and I have a homework assignment where I need to find the Mean, median and Mode of an Array. For some reason my code is not putting out the correct answer.
Here is the code I was provided to create the Arrays:
public static void main(String[] args) {
int[] test01 = new int[]{2,2,2,2,2};
int[] test01Results = new int[]{2,2,2,2};
int[] test02 = new int[]{1,2,1,3,5,6,6,1,2,2,2,99,100};
int[] test02Results = new int[]{2,2,17,100};
int[] test03 = new int[]{100,200,300,400,300};
int[] test03Results = new int[]{300,300,260,400};
int[] test04 = new int[]{100};
int[] test04Results = new int[]{100,100,100,100};
int[] test05 = new int[]{100,1};
int[] test05Results = new int[]{1,100,50,100};
Here is what I came up with to try to calculate the Mode:
public int mode() {
int result = 0;
// Add your code here
int repeatAmount = 0; //the amount of repeats accumulating for the current i
int highestRepeat=0; // the highest number of repeats so far
for (int i=0; i<numberArray.length; i++) {
for (int j=i; j<numberArray.length; j++) {
if (i != j && numberArray[i] == numberArray[j]) {
repeatAmount++;
if (repeatAmount>highestRepeat) {
result=numberArray[i];
}
repeatAmount = highestRepeat;
}
repeatAmount=0; // resets repeat Count for next comparison
}
}
return result;
}
I'm getting the correct results for tests 1, 2 and 3 but getting the wrong result for Tests 4 and 5. Does anyone know what I'm doing wrong?
Thanks!
You never assign anything except 0 to highestRepeat. This should work:
public int mode() {
int result = 0;
int highestRepeat=0;
for (int i=0; i<numberArray.length; i++) {
int repeatAmount = 1;
for (int j = i + 1; j < numberArray.length; j++) {
if (numberArray[i] == numberArray[j]) {
repeatAmount++;
if (repeatAmount > highestRepeat) {
result = numberArray[i];
highestRepeat = repeatAmount;
}
}
}
}
return result;
}
Some other improvements:
By starting the inner loop at i+1 you can skip the check if i != j.
By declaring repeatAmount inside the outer loop you can skip
setting it to zero after the inner loop.
If you need some performance, consider using a HashMap for counting the equal array entries.

Create distinct values in array - not yielding expected results

I am trying to make an array that has different values in its cells, but for some reason it has repeating values. Where am I going wrong?
Here is my code:
package oefarray;
public class OefArray {
int[] getallenArray,differentArray;
public static void main(String[] args) {
OefArray arr = new OefArray();
arr.differentArray(10,10);
}
public void differentArray(int n, int max) {
differentArray= new int[n];
for (int i = 0; i < differentArray.length; i++) {
int value = (int) (Math.random() * max);
differentArray[i]= value;
for (int p: differentArray){
while (value == p){
value = (int) (Math.random() * max);
}
}
differentArray[i]= value;
System.out.println(differentArray[i]);
}
}
}
You're not checking whether the new generated value exists anywhere in the array, only that its value doesn't equal the current value you're examining.
differentArray= new int[n];
for (int i = 0; i < differentArray.length; i++) {
int value = 0;
while(true){
value = (int)(Math.random()*max);
boolean found = false;
for(int p: differentArray){
if(p==value){
found = true;
break;
}
}
if(!found) break;
}
differentArray[i] = value;
}
Here's an alternative to arshajii's solution which doesn't require a direct reference to ArrayList. As he pointed out, this is no more efficient than his solution. Just another way of writing it if you're not comfortable with Lists yet.
int[] nums = new int[max];
for (int i = 0; i < max; i++)
nums[i] = i;
Collections.shuffle(Arrays.asList(nums));
for (int i = 0; i < n; i++)
differentArray[i] = nums.get(i);
For a futuristic approach to this using Java 8, using IntStream.generate can produce some very terse results. This likely performs in the same performance window as the previous answer, so I make no assertion that this is more efficient. It is, however, more expressive.
public int[] differentArray(int length, int maxValue) {
if(length > maxValue) {
throw new IllegalArgumentException("The number of possible unique values is smaller than available number of slots for them.");
}
final Random random = new Random();
return IntStream.generate(() -> random.nextInt(maxValue))
.distinct()
.limit(length)
.toArray();
}

Radix sort in java help

Hi i need some help to improve my code. I am trying to use Radixsort to sort array of 10 numbers (for example) in increasing order.
When i run the program with array of size 10 and put 10 random int numbers in like
70
309
450
279
799
192
586
609
54
657
i get this out:
450
309
192
279
54
192
586
657
54
609
DonĀ“t see where my error is in the code.
class IntQueue
{
static class Hlekkur
{
int tala;
Hlekkur naest;
}
Hlekkur fyrsti;
Hlekkur sidasti;
int n;
public IntQueue()
{
fyrsti = sidasti = null;
}
// First number in queue.
public int first()
{
return fyrsti.tala;
}
public int get()
{
int res = fyrsti.tala;
n--;
if( fyrsti == sidasti )
fyrsti = sidasti = null;
else
fyrsti = fyrsti.naest;
return res;
}
public void put( int i )
{
Hlekkur nyr = new Hlekkur();
n++;
nyr.tala = i;
if( sidasti==null )
f yrsti = sidasti = nyr;
else
{
sidasti.naest = nyr;
sidasti = nyr;
}
}
public int count()
{
return n;
}
public static void radixSort(int [] q, int n, int d){
IntQueue [] queue = new IntQueue[n];
for (int k = 0; k < n; k++){
queue[k] = new IntQueue();
}
for (int i = d-1; i >=0; i--){
for (int j = 0; j < n; j++){
while(queue[j].count() != 0)
{
queue[j].get();
}
}
for (int index = 0; index < n; index++){
// trying to look at one of three digit to sort after.
int v=1;
int digit = (q[index]/v)%10;
v*=10;
queue[digit].put(q[index]);
}
for (int p = 0; p < n; p++){
while(queue[p].count() != 0) {
q[p] = (queue[p].get());
}
}
}
}
}
I am also thinking can I let the function take one queue as an
argument and on return that queue is in increasing order? If so how?
Please help. Sorry if my english is bad not so good in it.
Please let know if you need more details.
import java.util.Random;
public class RadTest extends IntQueue {
public static void main(String[] args)
{
int [] q = new int[10];
Random r = new Random();
int t = 0;
int size = 10;
while(t != size)
{
q[t] = (r.nextInt(1000));
t++;
}
for(int i = 0; i!= size; i++)
{
System.out.println(q[i]);
}
System.out.println("Radad: \n");
radixSort(q,size,3);
for(int i = 0; i!= size; i++)
{
System.out.println(q[i]);
}
}
}
Hope this is what you were talking about...
Thank you for your answer, I will look into it. Not looking for someone to solve the problem for me. Looking for help and Ideas how i can solve it.
in my task it says:
Implement a radix sort function for integers that sorts with queues.
The function should take one queue as an
argument and on return that queue should contain the same values in ascending
order You may assume that the values are between 0 and 999.
Can i put 100 int numbers on my queue and use radixsort function to sort it or do i need to put numbers in array and then array in radixsort function which use queues?
I understand it like i needed to put numbers in Int queue and put that queue into the function but that has not worked.
But Thank for your answers will look at them and try to solve my problem. But if you think you can help please leave comment.
This works for the test cases I tried. It's not entirely well documented, but I think that's okay. I'll leave it to you to read it, compare it to what you're currently doing, and find out why what you have might be different than mine in philosophy. There's also other things that are marked where I did them the "lazy" way, and you should do them a better way.
import java.util.*;
class Radix {
static int[] radixSort(int[] arr) {
// Bucket is only used in this method, so I declare it here
// I'm not 100% sure I recommend doing this in production code
// but it turns out, it's perfectly legal to do!
class Bucket {
private List<Integer> list = new LinkedList<Integer>();
int[] sorted;
public void add(int i) { list.add(i); sorted = null;}
public int[] getSortedArray() {
if(sorted == null) {
sorted = new int[list.size()];
int i = 0;
for(Integer val : list) {
sorted[i++] = val.intValue(); // probably could autobox, oh well
}
Arrays.sort(sorted); // use whatever method you want to sort here...
// Arrays.sort probably isn't allowed
}
return sorted;
}
}
int maxLen = 0;
for(int i : arr) {
if(i < 0) throw new IllegalArgumentException("I don't deal with negative numbers");
int len = numKeys(i);
if(len > maxLen) maxLen = len;
}
Bucket[] buckets = new Bucket[maxLen];
for(int i = 0; i < buckets.length; i++) buckets[i] = new Bucket();
for(int i : arr) buckets[numKeys(i)-1].add(i);
int[] result = new int[arr.length];
int[] posarr = new int[buckets.length]; // all int to 0
for(int i = 0; i < result.length; i++) {
// get the 'best' element, which will be the most appropriate from
// the set of earliest unused elements from each bucket
int best = -1;
int bestpos = -1;
for(int p = 0; p < posarr.length; p++) {
if(posarr[p] == buckets[p].getSortedArray().length) continue;
int oldbest = best;
best = bestOf(best, buckets[p].getSortedArray()[posarr[p]]);
if(best != oldbest) {
bestpos = p;
}
}
posarr[bestpos]++;
result[i] = best;
}
return result;
}
static int bestOf(int a, int b) {
if(a == -1) return b;
// you'll have to write this yourself :)
String as = a+"";
String bs = b+"";
if(as.compareTo(bs) < 0) return a;
return b;
}
static int numKeys(int i) {
if(i < 0) throw new IllegalArgumentException("I don't deal with negative numbers");
if(i == 0) return 1;
//return (i+"").length(); // lame method :}
int len = 0;
while(i > 0) {
len++;
i /= 10;
}
return len;
}
public static void main(String[] args) {
int[] test = {1, 6, 31, 65, 143, 316, 93, 736};
int[] res = radixSort(test);
for(int i : res) System.out.println(i);
}
}
One thing that looks strange:
for (int p = 0; p < n; p++){
while(queue[p].count() != 0) {
q[p] = (queue[p].get());
}
}
Is p supposed to be the index in q, which ranges from 0 to n-1, or in queue, which ranges from 0 to 9? It is unlikely to be both ...
Another:
for (int index = 0; index < n; index++){
// trying to look at one of three digit to sort after.
int v=1;
int digit = (q[index]/v)%10;
v*=10;
queue[digit].put(q[index]);
}
Why are you multiplying v by 10, only to overwrite it by v = 1 in the next iteration? Are you aware than v will always be one, and you will thus look at the same digit in every iteration?
Well I don't think I can help without almost posting the solution (just giving hints is more exhausting and I'm a bit tired, sorry), so I'll just contribute a nice little fuzz test so you can test your solution. How does that sound? :-)
Coming up with a good fuzztester is always a good idea if you're implementing some algorithm. While there's no 100% certainty if that runs with your implementation chances are it'll work (radix sort doesn't have any strange edge cases I'm aware of that only happen extremely rarely)
private static void fuzztest() throws Exception{
Random rnd = new Random();
int testcnt = 0;
final int NR_TESTS = 10000;
// Maximum size of array.
final int MAX_DATA_LENGTH = 1000;
// Maximum value allowed for each integer.
final int MAX_SIZE = Integer.MAX_VALUE;
while(testcnt < NR_TESTS){
int len = rnd.nextInt(MAX_DATA_LENGTH) + 1;
Integer[] array = new Integer[len];
Integer[] radix = new Integer[len];
for(int i = 0; i < len; i++){
array[i] = rnd.nextInt(MAX_SIZE);
radix[i] = new Integer(array[i]);
}
Arrays.sort(array);
sort(radix); // use your own sort function here.
for(int i = 0; i < len; i++){
if(array[i].compareTo(radix[i]) != 0){
throw new Exception("Not sorted!");
}
}
System.out.println(testcnt);
testcnt++;
}

Categories