My question is if I input two maxvalue numbers in array, ex. 100, 10, 100. How can i get the output to print both index numbers?
The output expected would be 100 on index 1 and index 3
the index has 1 added as I want the index to start at one not zero
Add this to initialization.
HashSet<Integer> maxIndices = new HashSet<Integer>();
Make a second pass through the mileage array and add any max values to the HashSet.
The other option is to use a HashMap where the first integer is the mileage and the second value is the positive integer of how many have been found.
Because it makes only one pass, it may be faster even though you are counting every mileage, not just the one that ends up being the largest. Whether it is will be, of course, dependent upon the data, the compiler, and environmental conditions at the time of execution.
For your return value, you'll either need a custom POJO Java Bean or you can use Pair<> or Tuple<>. (See Using Pairs or 2-tuples in Java.)
Just simple Java using a series of for loops. The below method will return a 2D int array with each row consisting of two columns, the highest array value and its' respective array index number.
public int[][] getAllMaxValues(int[] allValues) {
int maxVal = 0;
int counter = 0;
// Get the Max value in array...
for (int i = 0; i < allValues.length; i++) {
if (allValues[i] > maxVal) {
maxVal = allValues[i];
}
}
// How many of the same max values are there?
for (int i = 0; i < allValues.length; i++) {
if (allValues[i] == maxVal) {
counter++;
}
}
// Place all the max values and their respective
// indexes into a 2D int array...
int[][] result = new int[counter][2];
counter = 0;
for (int i = 0; i < allValues.length; i++) {
if (allValues[i] == maxVal) {
result[counter][0] = maxVal;
result[counter][1] = i;
counter++;
}
}
// Return the 2D Array.
return result;
}
How you might use this method:
int[] allMiles = {100, 10, 100, 60, 20, 100, 34, 66, 74};
int[][] a = getAllMaxValues(allMiles);
for (int i = 0; i < a.length; i++) {
System.out.println("Array max value of " + a[i][0] +
" is located at index: " + a[i][1]);
}
Console window would display:
Array max value of 100 is located at index: 0
Array max value of 100 is located at index: 2
Array max value of 100 is located at index: 5
Related
need help taking an an array, counting frequency, putting in another array with array index acting at the number and individual value acting as the frequency in Java
You can sort a large array of m integers that are in the range 1 to n by using an array count of n
entries to count the number of occurrences of each integer in the array. For example, consider
the following array A of 14 integers that are in the range from 1 to 9 (note that in this case m =
14 and n = 9):
9 2 4 8 9 4 3 2 8 1 2 7 2 5
Form an array count of 9 elements such that count[i-1] contains the number of times that i
occurs in the array to be sorted. Thus, count is
1 4 1 2 1 0 1 2 2
In particular,
count[0] = 1 since 1 occurs once in A.
count[1] = 4 since 2 occurs 4 times in A.
count[2]=1 since 3 occurs once in A.
count[3] =2 since 4 occurs 2 times in A.
Use the count array to sort the original array A. Implement this sorting algorithm in the function
public static void countingSort(int[] a, int n )
and analyze its worst case running time in terms of m (the length of array a) and n.
After calling countingSort(), a must be a sorted array (do not store sorting result in a
temporary array).
edit:
this is what i've tried
public static void countingSort1(int[] a, int n) {
int [] temp = new int[n];
int [] temp2 = new int[n];
int visited = -1;
for (int index = 0; index < n; index++) {
int count = 1;
for (int j = index +1; j < n; j++) {
if(a[index] == a[j]) {
count++;
temp[j] = visited;
}
}
if (temp[index]!= visited) {
temp[index] = count;
}
}
for(int i = 1; i < temp.length; i++) {
if (temp[i] != visited) {
System.out.println(" " +a[i] + " | " +temp[i]);
}
}
Just to count the frequency but i think im doing it wrong
Something like below should do the work:
Since you already know what the highest value is, in yor example 9,
create a frequency array with space for nine elements.
iterate over your input array and for each value you find increase
the value at the index of the value in your frequency arra by one
create a counter for the index and initialize it with 0
iterate over your frequency array in a nested loop and replace the
values in your input array with the indexes of your frequency array.
I leave the analysis of the complexity to you
public static void countingSort(int[] a, int n ){
//counting
int[] freq = new int[n];
for(int i = 0; i<a.length; i++){
freq[a[i]-1]++;
}
//sorting
int index = 0;
for(int i = 0; i< freq.length; i++){
for(int j = 0;j < freq[i];j++){
a[index++]= i+1;
}
}
System.out.println(Arrays.toString(a));
}
A interviewer wrecked my life with this sort question today.
You have an array of a million integers and you need to sort them by remainder.
1. You don't know what integer they are going to divide by.
2. You can't use classes such as a Comparator to help.
3. Loop as little as possible.
4. Keep in mind to conserve memory.
For instance
int[] ints = {5434, 3454, 2, 0, 356, 896, 7324, 888, 99, 78365, 111};
int divider = 27;
Would be
int[] int2 = {0, 2, 111, 356, 896, 5434, 7324, 78365, 99, 888, 3454};
The method I came up with loops = divider / 2.
It works but if the divider is 250 then it loops 125 times.
public void sortByMod(int[] millionInts, int divideBy) {
long time = System.nanoTime();
int[] b = new int[millionInts.length];
int remainder, remainderMin = 0, remainderMax = divideBy, positionMin = 0, positionMax = millionInts.length - 1;
for (int i = 0; i < millionInts.length;) {
for (int j = 0; j < millionInts.length; j++) {
remainder = millionInts[j] % divideBy;
if (remainder == remainderMin) {
b[positionMin] = millionInts[j];
positionMin++;
i++;
} else if (remainder == remainderMax) {
b[positionMax] = millionInts[j];
positionMax--;
i++;
}
}
remainderMax--;
remainderMin++;
}
System.out.println("time = " + (System.nanoTime() - time));
System.out.println("loopcount = " + remainderMin);
}
I wrote another method that can do it in 2 loops but its confusing to read.
It violates the memory constraint but is extremely fast.
public void sortByModPro(int[] millionInts, int divideBy) {
int[] range = new int[divideBy];
int[] remainders = new int[millionInts.length];
int[] newArray = new int[millionInts.length];
long times = System.nanoTime();
for (int i = 0; i < millionInts.length; i++) {
remainders[i] = millionInts[i] % divideBy;
range[millionInts[i] % divideBy]++;
}
for (int i = range.length - 1, past = millionInts.length; i >= 0; i--) {
range[i] = past - range[i];
past = range[i];
}
for (int i = 0; i < millionInts.length; i++) {
newArray[range[remainders[i]]] = millionInts[i];
range[remainders[i]]++;
}
System.out.println("time = " + (System.nanoTime() - times));
}
How would you do this with 1 loop?
Speed > Memory
You can loop only once by using a bunch of buckets, one for each remainder. Simply dump the numbers in the buckets based on their remainder and then merge the buckets. Of course this violates the memory constraint.
Use your array to hold the buckets
The problem with the buckets is that you need to at least add a reference to each item in the array. What you could do to avoid that is partition the array into buckets and maintain a reference to the start and end index of each bucket. Of course this uses some memory, but the divideBy parameter should be rather small, right?
So, here's some pseudocode:
// init each bucket with 0 elements
for (remainder=0; remainder<divideBy; remainder++) {
buckets = {
start : 0, // startIndex in the array
end: 0, // the index after the last item actually placed in the bucket
count: 0 // how many items should be in the bucket
}
}
// count how many elements fit in each bucket
for (i=0; i<N; i++) {
buckets[array[i]%divideBy].count++;
}
// init the start and end points of each bucket
elementsCounted=0;
for (remainder=0; remainder<divideBy; remainder++) {
buckets[remainder].start = elementsCounted;
buckets[remainder].end = elementsCounted;
elementsCounted += buckets[remainder].count;
}
// at this point each bucket starts where it should in the array, but has no elements
// loop through the array and place items in the right bucket by swapping them
for (i=0; i<N; i++) {
remainder = array[i]%divideBy;
if (i < buckets[remainder].start || i >= buckets[remainder].end) {
// array[i] is in the wrong bucket, swap it at the end of the right bucket
swap(array[i], array[buckets[remainder].end]);
buckets[remainder].end++;
i--;
}
}
// everything is in the right place
You will note that there is an i-- in the final for, so it technically could go on forever. That is not the case, i will stay in place only if the array[i] is not in the right place. Each iteration will either place an element in the correct position or advance to the next position if the element is not in the correct position. All in all, it will iterate at most 2N times.
Total time complexity: O(3N+divideBy) = O(N + divideBy)
Total extra space used: divideBy*sizeof(bucket) = divideBy*12
I have an array which I would like to find the highest value for, but this value might be repeated.
For example, consider this array of integers:
{10, 2, 6, 25, 40, 58, 60, 60}.
//Here the value 60 is repeated
Here, I would like the output to show that there are two highest values in this array. Like in upper example it have to be show that 60 is highest value among all values in array and that value is 2 time available in array. And i do not want like to count how many numbers but like addition of that two highest numbers. I have search programs but i could not find any relevant solution for this.
class Cal
{
void CalculateThis()
{
int[] myArray = new int[] {20,10,5,40,20,41,41,2,6,7,3,4,5,6,23,34,7,8,9,2};
int max = Integer.MIN_VALUE;
int sum=0;
for(int i = 0; i < myArray.length; i++)
{
if(myArray[i] > max)
{
max = myArray[i]*3;
sum = sum + max;
}
}
System.out.println(sum);
}
}
class program1
{
public static void main(String args[])
{
Cal obj = new Cal();
obj.CalculateThis();
}
}
int max = ar[0];
int maxSum = 0;
for (int i=1; i< ar.length; i++)
{
if(ar[i] > max)
max = ar[i];
else
if(ar[i] == max)
maxSum+=max;
}
int[] myArray = { 10, 2, 6, 25, 40, 58, 60, 60 };
int max = Integer.MIN_VALUE;
int maxCount = 0;
for (int x : myArray) {
if (x > max) {
max = x;
maxCount = 1;
} else if (x == max) {
maxCount++;
}
}
int maxSum = max * maxCount;
System.out.println("Max value : " + max);
System.out.println("Max Count : " + maxCount);
System.out.println("Max Sum : " + maxSum);
output :
Max value : 60
Max Count : 2
Max Sum : 120
There are various approaches you could take here:
Sort the array using Arrays.sort, then work from the end until you saw a different value... letting you work out the value and the count, which you could then multiply together. This is relatively inefficient, as you don't really need to sort.
Write two methods, one of which returned the maximum value and one of which returned the count of a specific value. Find the maximum first, then the count of that, then multiply together. This requires two passes, but is clean in terms of building the final result from separate and reusable operations.
Write a method to keep track of the max and the sum at the same time, resetting both if you see a higher value. This will probably be the most efficient, but wouldn't be reusable for other requirements. (You could equivalently keep track of a count as you went, and multiply the max by count at the end instead.)
Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.
Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.
My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.
Thank you for your time!
public class arrayProject {
public static void main(String[] args) {
int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
projecttwo(arraytwo);
}
public static void projecttwo(int[]array){
/*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
arrays and a method that takes array of numbers as parameter and returns max value in array*/
int modetracker[] = new int[10];
int max = 0; int number = 0;
for (int i = 0; i < array.length; i++){
modetracker[array[i]] += 1; //Add one to each index of modetracker where the element of array[i] appears.
}
int index = 0;
for (int i = 1; i < modetracker.length; i++){
int newnumber = modetracker[i];
if ((newnumber > modetracker[i-1]) == true){
index = i;
}
} System.out.println(+index);
}
}
Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])
You should change your last rows to:
int maxIndex = 0;
for (int i = 1; i < modetracker.length; i++) {
int newnumber = modetracker[i];
if ((newnumber > modetracker[maxIndex])) {
maxIndex = i;
}
}
System.out.println(maxIndex);
You could change last part to:
int maxIndex = 0;
for (int i = 0; i < modetracker.length; i++) {
if (modetracker[i] > max) {
max = modetracker[i];
maxIndex = i;
}
}
System.out.println(maxIndex);