Finding max element in Arraylist of integer arrays - java

I'm attempting to create a function that allows you to pass in a ArrayList and return the max element. I have been unable to figure out a correct solution because of the data type being passed in is not primitive. I've also tried converting the ArrayList to ArrayList without success. Here is my (incorrect) code thus far:
public static void maxArrayListValue(ArrayList<int[]> arrayList) {
int maxArrayListValue = arrayList.get(0); // set first arrayList element as highest
for (int index=1; index < arrayList.size(); index++) { // cycle through each arrayList element
if (maxArrayListValue < arrayList.get(index)){ // if new element is > than old element
maxArrayListValue = arrayList.get(index); // replace with new maxValue
maxArrayListIndex = index; // record index of max element
}
}
return maxArrayListValue;
}
Any input would be apprecieated.

Your method isn't returning anything, and I think you want to iterate the values in each array. Something like,
public static int maxArrayListValue(List<int[]> arrayList) {
int maxVal = Integer.MIN_VALUE;
for (int[] arr : arrayList) {
for (int v : arr) {
if (v > maxVal) {
maxVal = v;
}
}
}
return maxVal;
}

You don't need a loop. Just use java.util.Collections.max(arrayList);

Related

How to use selection sort with comparator in java?

help here will be greatly appreciated. I'm pretty stuck. What I have to do is I have to use the selection sort algorithm to sort an arraylist, but there are multiple indexes in each object in the arraylist. This has to be done in java.
For example:
public class a {
private int number;
private String letter;
public a(int n, String l)
{
number = n;
letter = l;
}
}
public class SortingArrays {
private ArrayList<a> myarray;
private Comparator<a> sortByNumber;
private Comparator<a> sortByLetter;
public FootballPlayerData() {
myarray = new ArrayList<a>();
getmyarray().add(new a(2, "A"));
getmyarray().add(new a(7, "J"));
//COMPARATORs//
sortByNumber = new Comparator<a>() {
#Override
public int compare(a o1, a o2)
{
if (o1.number < (o2.number)) {
return -1;
}
if (o1.number == (o2.number)) {
return 0;
}
return 1;
}
};
sortByLetter = new Comparator<a>() {
#Override
public int compare(a o1, a o2)
{
return o1.letter.compareTo(o2.letter);
}
};
public void selectionSortbyNumber
{
???
}
public void selectionSortbyLetter
{
???
}
}
So how do I create a selection sort in java (has to be selection sort) that sorts the arraylist by different elements within the objects? I already have the comparator part down, but I don't know how to incorporate that with selection sort.
A Comparator implementation is usually used to compare two elements with one another, returning -1 (or any negative number) if the first element is less than the second, 0 if they are equal, and 1 (or any positive number) if the first element is greater than the second. This can be used to compare two elements to see if one is greater, less than, or equal to the other.
In the context of selection sort, you can use a supplied comparator to determine which value in the unsorted portion of the list is the minimum. The general algorithm for selection sort is as follows:
for i from 0 to array.length:
current_minimum_index = i
for j from i + 1 to array.length:
if array at j is less than array at current_minimum_index:
current_minimum_index = j
swap array at current_minimum_index with array at i
The if array at j is less than array at current_minimum_index can be implemented using Comparator. For example, given a supplied ArrayList called array, the call to the Comparator object named comparator would be:
if (comparator.compare(array.get(j), array.get(current_minimum_index))) < 0)
I do not want to provide you with the complete answer, as that would not help you learn selection sorting, but the method signature for your sorting would resemble the following:
public <T> void selectionSort(ArrayList<T> array, Comparator<T> comparator) {
// for i from 0 to array.size():
// currentMinIndex = i
// for j from i + 1 to array.size():
if (comparator.compare(array.get(j), array.get(currentMinIndex))) < 0) {
// currentMinIndex = j
}
// swap array at currentMinIndex with array at i
}
Your call to this method would then look like one of the following:
selectionSort(myarray, sortByNumber);
selectionSort(myarray, sortByLetter);
Source from https://en.wikipedia.org/wiki/Selection_sort:
/* a[0] to a[n-1] is the array to sort */
int i,j;
int n;
/* advance the position through the entire array */
/* (could do j < n-1 because single element is also min element) */
int iMin;
for (j = 0; j < n-1; j++) {
/* find the min element in the unsorted a[j .. n-1] */
/* assume the min is the first element */
iMin = j;
/* test against elements after j to find the smallest */
for (i = j+1; i < n; i++) {
/* if this element is less, then it is the new minimum */
if (a[i] < a[iMin]) {
/* found new minimum; remember its index */
iMin = i;
}
}
}
if (iMin != j) {
swap(a[j], a[iMin]);
}
The method swap() just switch the values in the array.
Your job will be to swap the array with list. :P But that's not so hard because you can access the list value by index get(int index) method.

How to add item to array without using built-in methods

I am creating a class that has an array, and I want to implement methods add, remove, and replace.
But I don't want to use any built-in internals.
public class MySet {
public int set[];
private int size = 0;
public MySet(int size) {
this.set = new int[size];
}
public boolean add(int item) {
for (int i = 0; i < this.size(); i++) {
if (this.set[i] != 0) {
// add to array
}
}
this.size++;
return true;
}
public int size()
{
return this.size;
}
}
When you initialize an array with a fixed size in Java, each item is equal to 0. The part with if this.set[i] != 0 is where I am stuck to add an item.
Should I use a while loop with pointers? Such as:
public boolean add(int item) {
int index = 0;
while (index <= this.size()) {
if (this.set[index] != 0 || index <= ) {
// increase pointer
index++;
}
this.set[index] = item;
}
But if I have an array such as [7, 2, 0 , 1] in the list, it won't get the last item in the loop, which I need.
So, how is this usually done?
You should keep the current index for the size of populated elements which looks like you do. When you add the set[size]= item and increment size. Once size hits the preallocated size of your array you need to create a new array with increased size (can pick double the size for example) and copy old array to the new one.

What is the best way to check if ALL values in a range exist in an array? (java)

I have the task of determining whether each value from 1, 2, 3... n is in an unordered int array. I'm not sure if this is the most efficient way to go about this, but I created an int[] called range that just has all the numbers from 1-n in order at range[i] (range[0]=1, range[1]=2, ect). Then I tried to use the containsAll method to check if my array of given numbers contains all of the numbers in the range array. However, when I test this it returns false. What's wrong with my code, and what would be a more efficient way to solve this problem?
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(I'm pretty sure I'm supposed to do this manually rather than using the containsAll method, so if anyone knows how to solve it that way it would be especially helpful!)
Here's where this method is implicated for anyone who is curious:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
valuesThere is false when printed.
First style:
if (condition == false) // Works, but at the end you have if (true == false) or such
if (!condition) // Better: not condition
// Do proper usage, if you have a parameter, do not read it in the method.
File numberFile = new File("valid3x3") ;
intMatrix = readMatrix(numberFile);
checkMatrix(intMatrix);
public static void checkMatrix(int[][] intMatrix) {
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
Then the problem. It is laudable to see that a List or even better a Set approach is the exact abstraction level: going into detail not sensible. Here however just that is wanted.
To know whether every element in a range [1, ..., n] is present.
You could walk through the given numbers,
and for every number look whether it new in the range, mark it as no longer new,
and if n new numbers are reached: return true.
int newRangeNumbers = 0;
boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
Think of better names.
You say you have a one dimensional array right?
Good. Then I think you are thinking to complicated.
I try to explain you another way to check if all numbers in an array are in number order.
For instance you have the array with following values:
int[] array = {9,4,6,7,8,1,2,3,5,8};
First of all you can order the Array simpel with
Arrays.sort(array);
After you've done this you can loop through the array and compare with the index like (in a method):
for(int i = array[0];i < array.length; i++){
if(array[i] != i) return false;
One way to solve this is to first sort the unsorted int array like you said then run a binary search to look for all values from 1...n. Sorry I'm not familiar with Java so I wrote in pseudocode. Instead of a linear search which takes O(N), binary search runs in O(logN) so is much quicker. But precondition is the array you are searching through must be sorted.
//pseudocode
int range[N] = {1...n};
cnt = 0;
while(i<-inputStream)
int unsortedArray[cnt]=i
cnt++;
sort(unsortedArray);
for(i from 0 to N-1)
{
bool res = binarySearch(unsortedArray, range[i]);
if(!res)
return false;
}
return true;
What I comprehended from your description is that the array is not necessarily sorted (in order). So, we can try using linear search method.
public static void main(String[] args){
boolean result = true;
int[] range <- Contains all the numbers
int[] givenNums <- Contains the numbers to check
for(int i=0; i<givenNums.length; i++){
if(!has(range, givenNums[i])){
result = false;
break;
}
}
System.out.println(result==false?"All elements do not exist":"All elements exist");
}
private static boolean has(int[] range, int n){
//we do linear search here
for(int i:range){
if(i == n)
return true;
}
return false;
}
This code displays whether all the elements in array givenNums exist in the array range.
Arrays.asList(givenNums).
This does not do what you think. It returns a List<int[]> with a single element, it does not box the values in givenNums to Integer and return a List<Integer>. This explains why your approach does not work.
Using Java 8 streams, assuming you don't want to permanently sort givens. Eliminate the copyOf() if you don't care:
int[] sorted = Arrays.copyOf(givens,givens.length);
Arrays.sort(sorted);
boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
public static boolean hasRange(int [] givenNums, int[] range) {
Set result = new HashSet();
for (int givenNum : givenNums) {
result.add(givenNum);
}
for (int num : range) {
result.add(num);
}
return result.size() == givenNums.length;
}
The problem with your code is that the function hasRange takes two primitive int array and when you pass primitive int array to Arrays.asList it will return a List containing a single element of type int[]. In this containsAll will not check actual elements rather it will compare primitive array object references.
Solution is either you create an Integer[] and then use Arrays.asList or if that's not possible then convert the int[] to Integer[].
public static boolean hasRange(Integer[] givenNums, Integer[] range) {
return Arrays.asList(givenNums).containsAll(Arrays.asList(range));
}
Check here for sample code and output.
If you are using ApacheCommonsLang library you can directly convert int[] to Integer[].
Integer[] newRangeArray = ArrayUtils.toObject(range);
A mathematical approach: if you know the max value (or search the max value) check the sum. Because the sum for the numbers 1,2,3,...,n is always equal to n*(n+1)/2. So if the sum is equal to that expression all values are in your array and if not some values are missing. Example
public class NewClass12 {
static int [] arr = {1,5,2,3,4,7,9,8};
public static void main(String [] args){
System.out.println(containsAllValues(arr, highestValue(arr)));
}
public static boolean containsAllValues(int[] arr, int n){
int sum = 0;
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == n*(n+1)/2);
}
public static int highestValue(int[]arr){
int highest = arr[0];
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
return highest;
}
}
according to this your method could look like this
public static boolen hasRange (int [] arr){
int highest = arr[0];
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == highest *(highest +1)/2);
}

Index of ordered array in Java

How Can I have index of a sorted array in Java?
For instance:
int[] myIntArray = new int[]{20,100,69,4};
and Arrays.sort(myIntArray) result is:
{4,20,69,100}
What if , index of original array is desired?
which means :
{3,0,2,1}
If I understood your problem correctly.
Considering there is no duplicates in you array. After you sort the array.
OPTION 1:
Writing a small helper method.
Passing each value to the below method and getting it's index.
public int findIndex(int[] iarray, int value) {
for(int i=0; i<iarray.length; i++)
if(iarray[i] == value)
return i;
}
OPTION 2:
Use org.apache.commons.lang Class ArrayUtils
public static int indexOf(int[] array,
int valueToFind)
Then,
If you are wanting to store these index in an array, take an array with initial array length and fill that array with returned index.
Declare a class that contains the index and the value, and sets up a comparator that compares just the values.
class IndexAndValue implements Comparable<IndexAndValue> {
public int index;
public int value;
public IndexAndValue(int index, int value) {
this.index = index;
this.value = value;
}
#Override
public int compareTo(IndexAndValue other) {
return Integer.compareTo(value, other.value);
}
}
Build an array of IndexAndValue of objects that contain the index and value.
IndexAndValue[] myIVArray = new IndexAndValue[myIntArray.length];
for (int i = 0; i < myIntArray.length, i++)
myIVArray[i] = new IndexAndValue(i, myIntArray[i]);
Now when you call sort on myIVArray, it will use the comparator to sort, which means it will compare the values. But the resulting array contains the IndexAndValue objects, which will keep the indexes together with the values.
(P.S. not tested, so it's possible I botched some syntax...)
(PPS. Public data members are usually evil, but I think it's OK for a small class like this whose purpose is just to hold a few values together. But if you don't like it, make them private and use accessor methods.)
I think a way to do this would be to create a class "intWithIndex" implementing Comparable. In that ways you could jeep track of the index.
public class IntWithIndex implements Comparable<IntWithIndex>{
public int value;
public int index;
#Override
Public int compareTo(intWithIndex x) {
return value - x.value;
}
}
public Test {
IntWithIndex[] myArray = ...
myArray[].sort;
}
IntWithIndex[].sort should then work, and you can check the initial indices with the index field.
Do you see what I mean ?
Additional to #SURESH ATTA, you can use Map to define your data structure, the key would be save as index and value would be your integers.
To get indexArray of sorted value without using any lib. Also take care of duplicate/multiple array element.
import java.util.Arrays;
public class IndexCal {
public static void main(String args[]) {
int[] myIntArray = new int[] { 20, 100, 69, 4, 20, 4, 100 };
int[] copyArray = new int[myIntArray.length];
System.arraycopy(myIntArray, 0, copyArray, 0, myIntArray.length);
Arrays.sort(myIntArray);
int[] indexArray = new int[myIntArray.length];
Arrays.fill(indexArray, -1);
for (int i = 0; i < copyArray.length; i++) {
int skiplength = 0;
int index = find(copyArray, myIntArray[i], 0);
while(find(indexArray, index, 0) != -1){
index = find(copyArray, myIntArray[i], skiplength++);
}
indexArray[i] = index;
}
for (int i = 0; i < copyArray.length; i++) {
System.out.println(indexArray[i]);
}
}
public static int find(int[] array, int value, int skiplength) {
for (int i = 0; i < array.length; i++)
if (array[i] == value)
if(skiplength == 0)
return i;
else
skiplength--;
return -1;
}
}

How do you remove the first instance of an element value in an array?

Add a method void removeFirst(int newVal) to the IntegerList class that removes the first occurrence of a value from the list. If the value does not appear in the list, it should do nothing (but it's not an error). Removing an item should not change the size of the array, but note that the array values do need to remain contiguous, so when you remove a value you will have to shift everything after it down to fill up its space. Also remember to decrement the variable that keeps track of the number of elements.
Please help, I have tried all of the other solutions listed on this site regarding "removing an element from an array" and none have worked.
This method supports the same functionality as Collection.remove() which is how an ArrayList removes the first matching element.
public boolean remove(int n) {
for (int i = 0; i < size; i++) {
if (array[i] != n) continue;
size--;
System.arraycopy(array, i + 1, array, i, size - i);
return true;
}
return false;
}
Rather than write this code yourself, I suggest you look at Trove4J's TIntArrayList which is a wrapper for int[] You can also read the code for ArrayList to see how it is written.
You could do this:
int count; //No of elements in the array
for(i=0;i<count;i++)
{
if(Array[i]==element )
{
swap(Array,i,count);
if(count)
--count;
break;
}
}
int swap(int Array[],int i,int count)
{
int j;
for(j=i;j<=count-i;j++)
a[i]=a[i+1];
}
This is not the Full Implementation.You have to create a class and do this.
Using the method below
public static <TypeOfObject> TypeOfObject[] removeFirst(TypeOfObject[] array, TypeOfObject valueToRemove) {
TypeOfObject[] result = Arrays.copyOf(array, array.length - 1);
List<TypeOfObject> tempList = new ArrayList<>();
tempList.addAll(Arrays.asList(array));
tempList.remove(valueToRemove);
return tempList.toArray(result);
}
You can remove the first element of any array by calling the method as demonstrated in the below JUnit test.
#Test
public void removeFirstTest() {
// Given
Integer valToRemove = 5;
Integer[] input = {1,2,3,valToRemove,4,valToRemove,6,7,8,9};
Integer[] expected = {1,2,3,4,valToRemove,6,7,8,9};
// When
Integer[] actual = removeFirst(input, valToRemove);
// Then
Assert.assertArrayEquals(expected, actual);
}

Categories

Resources