print and count the maximun values in 2d array java - java

I have 2d array java, I need to look at it and check on the max value, then print it with the count of how many it is in the array
I was trying to do like this but it doesn't work
int[][] rand = new int[][]{
{1, 80, 3, 4, 5},
{13, 199, 80, 8},
{12, 22, 80, 190}
};
int max = rand[0][0];
int count = 0;
for (int i = 0; i < rand.length; i++){
for (int ii = 0; ii < rand[i].length; ii++) {
if (rand[i][ii] > max) {
max = rand[i][ii];
count++;
}
}
}
System.out.println(max + " " + count);

You are not handling count correctly:
int max = rand[0][0];
int count = 0
for (int i = 0; i < rand.length; i++){
for (int ii = 0; ii < rand[i].length; ii++) {
if (rand[i][ii] > max) {
max = rand[i][ii];
count = 1; // a new maximum's first occurrence
} else if (rand[i][ii] == max) {
count++; // another occurrence of the current maximum
}
}
}
System.out.println(max + " " + count);
When you find a new maximum, you should reset count to 1.
You should check if the current element is equal to the current maximum, and increment count if that's the case.
Output:
199 1
EDIT:
Fixed the case where the first element is the maximum. It turns out count should be initialized to 0 after all, since the loops re-visit the first element, so we don't want to count it twice if it's the maximum.

You can use streams:
int max = Arrays.stream(rand)
.mapToInt(row -> Arrays.stream(row).max().getAsInt())
.max().getAsInt();
int count = Arrays.stream(rand)
.mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
.reduce(Integer::sum).getAsInt();

Related

Finding the subarray with the Maximum sum in the given ArrayList

The problem description:
Given an ArrayList of Integers. Find a subarray with the maximum sum of any potential subarray within the ArrayList.
A subarray a is a combination of consecutive numbers.
The subarray can be of any length n, where the size of n >= 0.
Example
Input:
[-1, 10, -11, -1, 17, 0, 0, 9, 20, 7, -8, -6, -18]
Solution
[17, 0, 0, 9, 20, 0, 7]
Here is the code that I have so far.
public class MaxSubArray {
public ArrayList<Integer> solution(ArrayList<Integer> nums) {
int maxSubArrSum = Integer.MIN_VALUE;
int greatest = Integer.MAX_VALUE;
int smallest = 0;
int start;
int end;
ArrayList<Integer> maxSubArr;
ArrayList<ArrayList<Integer>> lists = new ArrayList();
try {
for (int left = 0; left < nums.size(); left++) {
int runningSum = 0;
for (int right = left; right < nums.size(); right++) {
runningSum += nums.get(right);
if (runningSum >= maxSubArrSum) {
ArrayList<Integer> temp = new ArrayList<>();
maxSubArrSum = runningSum;
start = left;
end = right;
for (int i = start; i <= end; i++) {
temp.add(nums.get(i));
}
lists.add(temp);
}
}
}
for (int i = 0; i < lists.size(); i++) {
if (lists.get(i).size() < greatest) {
greatest = lists.get(i).size();
smallest = i;
}
}
maxSubArr = lists.get(smallest);
return maxSubArr;
} catch (Exception e) {
e.printStackTrace();
return nums;
}
}
}
I am trying to iterate through the nums ArrayList and figuring out the first and last indexes of the subarrays with the maximum sum and putting them in a list of ArrayLists.
After that, I am trying to figure out which of the subarrays has the smallest size and returning it.
What I am doing wrong here?
Here is a more concise solution
private List<Integer> solution(List<Integer> nums) {
int biggestSumSoFar = Integer.MIN_VALUE;
List<Integer> biggestSubListSoFar = new ArrayList<>();
for (int left = 0; left < nums.size(); ++left) {
for (int right = left + 1; right < nums.size(); ++right) {
List<Integer> currentSubList = subListSum(nums, left, right);
int currentSum = sum(currentSubList);
if (currentSum > biggestSumSoFar) {
biggestSumSoFar = currentSum;
biggestSubListSoFar = currentSubList;
}
}
}
return biggestSubListSoFar;
}
private List<Integer> subListSum(final List<Integer> nums, final int left, final int right)
{
final List<Integer> sublist = new ArrayList<>();
for (int i = left; i < right; i++)
{
sublist.add(nums.get(i));
}
return sublist;
}
private int sum(List<Integer> arr) {
int sum = 0;
for(int a : arr){
sum += a;
}
return sum;
}
Adding a third inner for-loop can make the task probably easier. Just think about how you would do it with a pen and paper. Imagine you have an array of 6 elements with indices from 0 to 5, then all possible subarrays would have the following start and end indices (strat inclusive, end exclusive)
0 - 1 1 - 2 2 - 3 3 - 4 4 - 5
0 - 2 1 - 3 2 - 4 3 - 5
0 - 3 1 - 4 2 - 5
0 - 4 1 - 5
0 - 5
Having the above all you need is to calculate the subsum and store the relevant start and end indices
public List<Integer> solution(List<Integer> nums) {
int maxSubArrSum = Integer.MIN_VALUE;
int start = 0;
int end = 0;
for (int left = 0; left < nums.size(); left++){
for (int right = left+1; right < nums.size(); right++){
int subSum = 0;
for (int k = left; k < right; k++){
subSum += nums.get(k);
}
if (subSum > maxSubArrSum){
maxSubArrSum = subSum;
start = left;
end = right;
}
}
}
return nums.subList(start,end);
}
You are quiet close with your approach.
There are two problems with the last part:
int greatest = Integer.MAX_VALUE; should be Integer.MIN_VALUE instead.
You check for the size of a subarray but you have to check for the sum of the subarray.
if you change the last part to:
int greatest = Integer.MIN_VALUE;
for (int i = 0; i < lists.size(); i++) {
if (sum(lists.get(i)) > greatest) {
greatest = lists.get(i).size();
smallest = i;
}
}
by utilizing
public static int sum(List<Integer> arr) {
int sum = 0;
for(int a : arr){
sum += a;
}
return sum;
}
it yields the desired result.
Here is a modified version of Kadane's Algorithm to find the largest sum of contiguous elements in a list. It is adapted from a solution given in Python and works in a single pass.
List<Integer> list = List.of(-1, 10, -11, -1, 17, 0, 0, 9, 20, 7, -8, -6, -18);
List<Integer> subList = maxSubArray(list);
System.out.println(subList);
prints
[17, 0, 0, 9, 20, 7]
public static List<Integer> maxSubArray(List<Integer> list) {
int max = Integer.MIN_VALUE;
int sum = max;
int end = 0;
int cstart = 0, start = 0;
for (int i = 0; i < list.size(); i++) {
int val = list.get(i);
if (sum <= 0) {
sum = val;
cstart = i;
} else {
sum += val;
}
if (sum > max) {
max = sum;
start = cstart;
end = i;
}
}
return list.subList(start,end+1);
}
Basically, you are trying to approach this task with a brute-force algorithm, which in the worse case scenario will have the O(n^2) both time and space complexity.
It could be done with a linear (i.e. O(n)) both time and space complexity, without nested loops.
With this approach, first, we need to find the maximum possible sum of the subarray by using the Kadane's algorithm.
And then perform the iteration with over the source list in a single loop tracking the current sum. When it becomes equal to the maximum sum it would mean the target subarray of consecutive elements was found.
Variables start and end denote the starting and ending indices of the resulting subarray.
Method subList() creates a view over the source list and every modification of the view will be reflected in the source and vice versa. Hence, as a precaution it's being wrapped with with a new instance of ArrayList.
public static List<Integer> solution(List<Integer> nums) {
if (nums.size() == 0) {
return Collections.emptyList();
}
final int maxSum = getMaxSum(nums); // getting max sum by using Kadane's algorithm
int curSum = nums.get(0);
int start = 0; // beginning of the resulting subarray
int end = 0; // end of the resulting subarray exclusive
for (int i = 1; i < nums.size(); i++) {
if (curSum == maxSum) {
end = i;
break; // maximus sub-array was found
}
if (nums.get(i) > curSum + nums.get(i)) {
start = i; // setting start to current index
curSum = nums.get(i); // assigning the current element the sum
} else {
curSum += nums.get(i); // adding the current element to the sum
}
}
return new ArrayList<>(nums.subList(start, end));
}
Kadane's algorithm implementation.
The overall idea is to maintain two variables denoting the global and a local maximum. There are to ways in which the local maximum changes with each iteration, we either
adding the current element to the local maximum;
or assigning the current element's value to the local maximum.
At the end of every iteration, the global maximum is being compared with a local maximum and adjusted if needed.
public static int getMaxSum(List<Integer> nums) {
int maxSum = Integer.MIN_VALUE;
int curSum = nums.get(0);
for (int i = 1; i < nums.size(); i++) {
curSum = Math.max(nums.get(i), curSum + nums.get(i));
maxSum = Math.max(maxSum, curSum);
}
return maxSum;
}
main()
public static void main(String[] args) {
List<Integer> source = List.of(-1, 10, -11, -1, 17, 0, 0, 9, 20, 7, -8, -6, -18);
System.out.println(solution(source));
}
output
[17, 0, 0, 9, 20, 7]

Find max value of each column in 2D array

I was wondering while using java.
There are two-dimensional arrays as shown below.
int[][] test = {{3, 9, 3, 5}, {4, 19, 4, 9}, {2, 10, 5, 6}};
I want to find the max value in each row in a two-dimensional array, and I wonder how to code it.
I want to result is
int[] answer = {4, 19, 5, 9}
Simply add a comment, I want to extract the largest value.
[0][0] = 3;
[1][0] = 4;
[2][0] = 2;
[0][1] = 9;
[1][1] = 19;
[2][1] = 10;
[0][2] = 3;
[1][2] = 4;
[2][2] = 5;
[0][3] = 5;
[1][3] = 9;
[2][3] = 6;
So max value is 4, 19, 5, 9
I tried this method but this method is arr[i][j] compares all elements in a two-dimensional array and finds only max in the comparison.
for (int i = 0; i < test.length; i++) {
int max = test[i][0];
for (int j = 0; j < test[i].length; j++)
if (test[i][j] > max)
max = test[i][j]
}
You can init the result with the first row, then iterate on this matrix, if the current element test[row][column] is greater than result[column], reassign result[column]:
public static void main(String[] args) {
int[][] test = {{3, 9, 3, 5}, {4, 19, 4, 9}, {2, 10, 5, 6}};
int[] result = test[0];
for (int row = 1; row < test.length; row++) {
for (int column = 0; column < test[0].length; column++) {
if (test[row][column] > result[column]) {
result[column] = test[row][column];
}
}
}
for (int number : result) {
System.out.print(number + " "); // 4 19 5 9
}
}
According to your exemple, the "big" loop is going through the columns and the "small" loop through the lines. Sou you'll have something like that :
for(int j=0; j<test[0].length; j++) { //loop through columns
for(int i=0; i<test.length; i++) { //loop through lines
}
}
Then you need a result variable that will be an array : int[] result = new int[test[0].length];
Then you need to have a variable to store the max number of a column. This variable will be re-initialise at every "big" loop since you want to re-determine the max.
int[] result = new int[test[0].length]; //Array to store the result
for(int j=0; j<test[0].length; j++) { //loop through columns
int max = 0; //int to store the max of the i column
for(int i=0; i<test.length; i++) { //loop through lines
}
}
Then for every line check if the number is bigger than max. If it is replace max by the new value.
if(test[i][j] > max) { //if the number at the column i and line j is bigger than max
max = test[i][j]; then max becomes this number
}
Finally when you've run through every line of the column, add the found max to the result
result[i] = max; //Add the found max to the result array
This should give you this :
int[] result = new int[test[0].length]; //Array to store the result
for(int j=0; j<test[0].length; j++) { //loop through columns
int max = 0; //int to store the max of the i column
for(int i=0; i<test.length; i++) { //loop through lines
if(test[i][j] > max) { //if the number at the column i and line j is bigger than max
max = test[i][j]; then max becomes this number
}
}
result[i] = max; //Add the found max to the result array
}
System.out.println(Arrays.toString(result)); //print the result

Getting the most "popular" number from array

I need for homework to get the most "popular" number in an array (the number in the highest frequency), and if there are several numbers with the same number of shows, get some number randomly.
After more then three hours of trying, and either searching the web, this is what I got:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return popular;
}
This code work, but don't take into account an important case- if there is more than one number with the same count of shows. Then it just get the first one.
for example: int[]a = {1, 2, 3, 4, 4, ,5 ,4 ,5 ,5}; The code will grab 4 since it shown first, and it's not random as it should be.
Another thing- since it's homework I can't use ArrayList/maps and stuff that we still didn't learn.
Any help would be appreciated.
Since they didn't give you any time complexity boundary, you can "brute force" the problem by scanning the the array N^2 times. (disclaimer, this is the most intuitive way of doing it, not the fastest or the most efficient in terms of memory and cpu).
Here is some psuedo-code:
Create another array with the same size as the original array, this will be the "occurrence array"
Zero its elements
For each index i in the original array, iterate the original array, and increment the element in the occurrence array at i each time the scan finds duplicates of the value stored in i in the original array.
Find the maximum in the occurrence array
Return the value stored in that index in the original array
This way you mimic the use of maps with just another array.
If you are not allowed to use collection then you can try below code :
public int getPopularNumber(){
int inputArr[] = {1, 2, 3, 4, 4, 5 ,4 ,5 ,5}; // given input array
int[] tempArr = new int[inputArr.length];
int[] maxValArr = new int[inputArr.length];
// tempArr will have number as index and count as no of occurrence
for( int i = 0 ; i < inputArr.length ; i++){
tempArr[inputArr[i]]++;
}
int maValue = 0;
// find out max count of occurrence (in this case 3 for value 4 and 5)
for( int j = 0 ; j < tempArr.length ; j++){
maValue = Math.max(maValue, tempArr[j]);
}
int l =0;
// maxValArr contains all value having maximum occurrence (in this case 4 and 5)
for( int k = 0 ; k < tempArr.length ; k++){
if(tempArr[k] == maValue){
maxValArr[l] = k;
l++;
}
}
return maxValArr[(int)(Math.random() * getArraySize(maxValArr))];
}
private int getArraySize(int[] arr) {
int size = 0;
for( int i =0; i < arr.length ; i++){
if(arr[i] == 0){
break;
}
size++;
}
return size;
}
that's hard as hell :D
After some trying, I guess I have it (If there will be 2 numbers with same frequency, it will return first found):
int mostPopNumber =0;
int tmpLastCount =0;
for (int i = 0; i < array.length-1; i++) {
int tmpActual = array[i];
int tmpCount=0;
for (int j = 0; j < array.length; j++) {
if(tmpActual == array[j]){
tmpCount++;
}
}
// >= for the last one
if(tmpCount > tmpLastCount){
tmpLastCount = tmpCount;
mostPopNumber = tmpActual;
}
}
return mostPopNumber;
--
Hah your code give me idea- you cant just remember last most popular number, btw I've found it solved there Find the most popular element in int[] array
:)
EDIT- after many, and many years :D, that works well :)
I've used 2D int and Integer array - you can also use just int array, but you will have to make more length array and copy actual values, Integer has default value null, so that's faster
Enjoy
public static void main(String[] args) {
//income array
int[] array= {1,1,1,1,50,10,20,20,2,2,2,2,20,20};
//associated unique numbers with frequency
int[][] uniQFreqArr = getUniqValues(array);
//print uniq numbers with it's frequency
for (int i = 0; i < uniQFreqArr.length; i++) {
System.out.println("Number: " + uniQFreqArr[i][0] + " found : " + uniQFreqArr[i][1]);
}
//get just most frequency founded numbers
int[][] maxFreqArray = getMaxFreqArray(uniQFreqArr);
//print just most frequency founded numbers
System.out.println("Most freq. values");
for (int i = 0; i < maxFreqArray.length; i++) {
System.out.println("Number: " + maxFreqArray[i][0] + " found : " + maxFreqArray[i][1]);
}
//get some of found values and print
int[] result = getRandomResult(maxFreqArray);
System.out.println("Found most frequency number: " + result[0] + " with count: " + result[1]);
}
//get associated array with unique numbers and it's frequency
static int[][] getUniqValues(int[] inArray){
//first time sort array
Arrays.sort(inArray);
//default value is null, not zero as in int (used bellow)
Integer[][] uniqArr = new Integer[inArray.length][2];
//counter and temp variable
int currUniqNumbers=1;
int actualNum = inArray[currUniqNumbers-1];
uniqArr[currUniqNumbers-1][0]=currUniqNumbers;
uniqArr[currUniqNumbers-1][1]=1;
for (int i = 1; i < inArray.length; i++) {
if(actualNum != inArray[i]){
uniqArr[currUniqNumbers][0]=inArray[i];
uniqArr[currUniqNumbers][1]=1;
actualNum = inArray[i];
currUniqNumbers++;
}else{
uniqArr[currUniqNumbers-1][1]++;
}
}
//get correctly lengthed array
int[][] ret = new int[currUniqNumbers][2];
for (int i = 0; i < uniqArr.length; i++) {
if(uniqArr[i][0] != null){
ret[i][0] = uniqArr[i][0];
ret[i][1] = uniqArr[i][1];
}else{
break;
}
}
return ret;
}
//found and return most frequency numbers
static int[][] getMaxFreqArray(int[][] inArray){
int maxFreq =0;
int foundedMaxValues = 0;
//filter- used sorted array, so you can decision about actual and next value from array
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] > maxFreq){
maxFreq = inArray[i][1];
foundedMaxValues=1;
}else if(inArray[i][1] == maxFreq){
foundedMaxValues++;
}
}
//and again copy to correctly lengthed array
int[][] mostFreqArr = new int[foundedMaxValues][2];
int inArr= 0;
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] == maxFreq){
mostFreqArr[inArr][0] = inArray[i][0];
mostFreqArr[inArr][1] = inArray[i][1];
inArr++;
}
}
return mostFreqArr;
}
//generate number from interval and get result value and it's frequency
static int[] getRandomResult(int[][] inArray){
int[]ret=new int[2];
int random = new Random().nextInt(inArray.length);
ret[0] = inArray[random][0];
ret[1] = inArray[random][1];
return ret;
}

Find smallest integer value in array list in Java without Arrays.sort

How can I find the smallest value in a int array without changing the array order?
code snippet:
int[] tenIntArray = new int [10];
int i, userIn;
Scanner KyBdIn = new Scanner(System.in);
System.out.println("Please enter 10 integer numbers ");
for(i = 0; i < tenIntArray.length; i++){
System.out.println("Please enter integer " + i);
userIn = KyBdIn.nextInt();
tenIntArray[i] = userIn;
}
I am not sure how I can find the smallest array value in the tenIntArray and display the position
For example the array holds - [50, 8, 2, 3, 1, 9, 8, 7 ,54, 10]
The output should say "The smallest value is 1 at position 5 in array"
This figure should be helpful :
Then to answer your question, what would you do on paper ?
Create and initialize the min value at tenIntArray[0]
Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at tenIntArray[0])
Loop through the elements of your array
If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
You're done
Writing the algorithm should be straightforward now.
Try this:
//Let arr be your array of integers
if (arr.length == 0)
return;
int small = arr[0];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < small) {
small = arr[i];
index = i;
}
}
Using Java 8 Streams you can create a Binary operator which compares two integers and returns smallest among them.
Let arr is your array
int[] arr = new int[]{54,234,1,45,14,54};
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
The method I am proposing will find both min and max.
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min and max values. Output is:
min: 10
max: 69
int[] input = {12,9,33,14,5,4};
int max = 0;
int index = 0;
int indexOne = 0;
int min = input[0];
for(int i = 0;i<input.length;i++)
{
if(max<input[i])
{
max = input[i];
indexOne = i;
}
if(min>input[i])
{
min = input[i];
index = i;
}
}
System.out.println(max);
System.out.println(indexOne);
System.out.println(min);
System.out.println(index);
Here is the function
public int getIndexOfMin(ArrayList<Integer> arr){
int minVal = arr.get(0); // take first as minVal
int indexOfMin = -1; //returns -1 if all elements are equal
for (int i = 0; i < arr.size(); i++) {
//if current is less then minVal
if(arr.get(i) < minVal ){
minVal = arr.get(i); // put it in minVal
indexOfMin = i; // put index of current min
}
}
return indexOfMin;
}
the first index of a array is zero. not one.
for(i = 0; i < tenIntArray.length; i++)
so correct this.
the code that you asked is :
int small = Integer.MAX_VALUE;
int i = 0;
int index = 0;
for(int j : tenIntArray){
if(j < small){
small = j;
i++;
index = i;
}
}
System.out.print("The smallest value is"+small+"at position"+ index +"in array");

Algorithm to find the largest integer in array

I am trying to create a method which returns an int - the value of the largest integer in the sent array.
The way I want this method to work, is to check the first and the last element of the array in a for-loop, and work their way to the middle. So i = first integer, k = last integer. When i = 0, k = n-1 (indexes), when i = 1, k = n-2 if you catch my drift. In every loop it needs to check if a[i]>a[k]. Then they switch places. Then I know that the largest number is in the leading half of the array, and then I want it to check that half, so ultimately the largest int is at index 0.
I tried like this:
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length/2; i++)
{
k--;
if(a[i]<a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length /=2;
}
return a[0];
}
..but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
EDIT
Also: The array {6,15,2,5,8,14,10,16,11,17,13,7,1,18,3,4,9,12}; will spit out 17 as the largest number. I realize I have to fix the odd-length bug, but I would like to solve this even-length array first..
A bug is when encountering length is odd.
In these cases, you "miss" the middle element.
Example: for input int[] arr = { 8, 1, 5, 4, 9, 4, 3, 7, 2 }; - the element 9 will be compared and checked against itself, but then you reduce the size of length, you exclude 9 from the array you are going to iterate next.
I believe it can be solved by reducing the problem to ceil(length/2) instead of length/2 (and handling special case of length==1)
The other issue as was mentioned in comments is: you need to iterate up to length/2 rather then up to length, otherwise you are overriding yourself.
Lastly - the sign is wrong.
if(a[i]>a[k])
should be
if(a[i]<a[k])
Remember - you are trying to swap the elements if the first is smaller the the second in order to push the larger elements to the head of your array.
but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
In that case you should use a debugger to step through the code to get a picture of what each line of code does.
What I would do is:
public static int maxOfArray(int[] a) {
int max = a[0];
for (int i : a)
if (max < i)
max = i;
return max;
}
public static int findMaxTheHardWay(int[] array) {
for (int length = array.length; length > 1; length = (length + 1) / 2) {
for (int i = 0; i < length / 2; i++) {
if (array[i] < array[length - i - 1])
array[i] = array[length - i - 1]; // don't need to swap.
}
}
return array[0];
}
public static void main(String... args) {
Random rand = new Random(1);
for (int i = 1; i <= 1000; i++) {
int[] a = new int[i];
for (int j = 0; j < i; j++) a[j] = rand.nextInt();
int max = maxOfArray(a);
int max2 = findMaxTheHardWay(a);
if (max != max2)
throw new AssertionError(i + ": " + max + " != " + max2);
}
}
This is rather a crazy way to solve the problem, but I'll play along.
The problem is in the inner loop.
You start out with i = 0 and k = length - 1.
If a[i] > a[k] you swap them.
...
You end up with k = 0 and i = length - 1
If a[i] > a[k] you swap them.
If you look at that carefully you will notice that if we swapped the elements in the first swap, we will also swap them in the last swap; i.e. we will UNDO the effects of the first swap. And the same applies pair-wise through the entire array slice.
See?
What you need to do is to stop the inner loop half way ... and then take account of the case where length is odd.
By the way, the reason I called this "rather crazy", because the obvious and simple way is much faster: O(N) versus O(NlogN)
int a[] = {1,7,3};
List<Integer> list = Arrays.asList(a);
Integer largest = Collections.max(list);
This will give you Largest number in Array.
Here is a solution that fits the specifications that you want (unlike many other here, humm, humm):
final Integer[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
int half = (input.length / 2);
int mod = input.length % 2;
while (half >= 0) {
for (int i = 0, j = (half * 2) + mod - 1; i <= half && j >= half; i++, j--) {
if (input[i] < input[j]) {
final int tmp = input[i];
input[i] = input[j];
input[j] = tmp;
}
}
if (half == 0) break;
half = half / 2;
mod = half % 2;
}
//Here, input[0] = the biggest number in the original input.
Edit: Added mod, so it works if the last element is the largest..
I think your code is working, you just have to ceil the length / 2 in case of odd array but my tests return proper result:
package org.devince.largestinteger;
import java.util.NoSuchElementException;
public class LargestInteger {
final static int[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
// final static int[] input = { 8, 1, 5, 4, 9, 4, 3, 7, 2 };
// final static int[] input = {1,3,7};
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(String.valueOf(maxOfArray(input)));
}
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
k--;
if(a[i]>a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length = (int) Math.ceil(length / 2f);
}
return a[0];
}
}
Why not just store the first value of the array to a variable max.
After that just loop through the array starting from second position till the last ,
in the loop just check if the current value is greater than max or not.If it is greater just assign max that value.
Return max and you have the largest number.
public int FindLargest()
{
int[] num = { 1, 2, 5, 12, 13, 56, 16, 4 };
int max = num[0];
for (int i = 1; i <num.length; i++)
{
if (num[i] > max)
{
max = num[i];
}
}
return max;
}
As the same u can approach like also,
int length = a.length;
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
for(int y = k-1; y >= i; y--)
{
if(a[i]<a[y])
{
int j = a[i];
a[i] = a[y];
a[y] = j;
}
}
}
length /=2;
}
final int validSampleRates[] = new int[]{
5644800, 2822400, 352800, 192000, 176400, 96000,
88200, 50400, 50000, 4800,47250, 44100, 44056, 37800, 32000, 22050, 16000, 11025, 4800, 8000};
ArrayList <Integer> YourArray = new ArrayList <Integer> ():
for (int smaple : validSampleRates){
YourArray.add(smaple);
}
Integer largest = Collections.max(YourArray);
System.out.println("Largest " + String.valueOf(largest));
The best way is to use Array that extends List Collection as ArrayList

Categories