Hey guys I'm really struggling with trying to print my array index and element value, I posted a question a few days ago and got really helpful advice but cannot seem to get this part right at all, I am able to print the 1st index of the array (distance) but not able to print the entire thing without losing the original index value:
double minVal = Double.MAX_VALUE;
int minIndex = -1;
for (int i=0, max=distances.length; i<max;i++) {
if (distances[i] < minVal) {
minVal = distances[i];
minIndex = i;
//Gets the minimum point and minimum distance
}
}
System.out.println("The Nearest to point K is point: "+minIndex+" with distance "+minVal);
Really sorry to keep bringing this matter up but really have tried and cannot get it to work for the life of me any help or advice would be appreciated.
First, you sort
for (int i=0; i<distances.length; i++) {
for(int j = i+1; j<distances.length; j++)
{
if (distances[i] > distances[j])
{
double temp = distances[j];
distances[j] = distances[i];
distances[i] = temp;
}
}
}
Then, you merely print
for (int i=0; i<distances.length; i++) {
System.out.println(i + " -> " + distances[i]);
}
If you want to keep the original indexes, you can do that too.
the most obvious way would be to have a second paralell array, and sort that along with your original array
example:
if (distances[i] < minVal)
{
double temp = distances[j];
int tempindex = indices[j];
...
the better way would be to make a class with an index(or more appropriately named, an ID), and a value(which is your double), and sort an array of type Distance.
.
Class Distance
{
public int ID;
public double value;
}
Try change the for loop to for(int i=0; max = distances.length && i < max; i++){...}
Related
Hello all please check the problemHackerRank Problem Statement
This is my solution for the above problem(link)
static int migratoryBirds(List<Integer> arr) {
int ar[]=new int[arr.size()];
for(int i=0;i<arr.size();i++){
ar[i] = Collections.frequency(arr,arr.get(i));
// ar[i] = obj.occuranceOfElement(arr,arr.get(i));
}
int maxAt = 0;
for (int i = 0; i < ar.length; i++) {
maxAt = ar[i] > ar[maxAt] ? i : maxAt;
}
return arr.get(maxAt);
}
my code is unable to handle when the array size is bigger,example 17623 elements in array.
Terminated due to timeout
The problem is in the second for loop which iterates over the array and gives me the index of the largest number in the array.Is there any other way that I could increase the performance.
Your problem is in this part:
for(int i = 0; i < arr.size(); i++)
ar[i] = Collections.frequency(arr, arr.get(i));
This is O(N²): Collections.frequency() iterates over whole list to calculate frequency for only one element. Manually, you can iterate over the list to calculate frequencey for all elements.
Moreover, ther're only 5 birds, so you need only 5 length array.
static int migratoryBirds(int[] arr) {
int max = 1;
int[] freq = new int[6];
for (int val : arr)
freq[val]++;
for (int i = 2; i < freq.length; i++)
max = freq[i] > freq[max] ? i : max;
return max;
}
Your problem is the call to Colletions.frequency, which is an O(N) operation. When you call it from inside a loop it becomes O(N²) and that consumes all your time.
Also, are you sure which implmentation of List you receive? You call list.get(i) which might also be O(N) if the implementation is a LinkedList.
The target of this exercise is to calculate the frequency of each value in one pass over the input. You need a place where you store and increase the number of occurrences for each value and you need to store the largest value of the input.
You have also skipped over a crucial part of the specification. The input has limits which makes solving the problem easier than you now think.
Here's another one:
static int migratoryBirds(List<Integer> arr) {
int freq[]=new int[6];
for(int i=0;i<arr.size();i++){
++freq[arr.get(i)];
}
int maxAt = 1;
for (int i = 2; i < freq.length; i++) {
if (freq[i] > freq[maxAt]) {
maxAt = i;
}
}
return maxAt;
}
We can determine the type number of the most common bird in one loop. This has the time complexity O(n).
static int migratoryBirds(int[] arr) {
int highestFrequency = 0;
int highestFrequencyBirdType = 0;
int[] frequencies = new int[5]; // there are 5 bird types
for (int birdType : arr) {
int frequency = ++frequencies[birdType - 1];
if (frequency > highestFrequency) {
highestFrequency = frequency;
highestFrequencyBirdType = birdType;
} else if (frequency == highestFrequency && birdType < highestFrequencyBirdType) {
highestFrequencyBirdType = birdType;
}
}
return highestFrequencyBirdType;
}
For each element in the array arr we update the overall highestFrequency and are storing the corresponding value representing the highestFrequencyBirdType . If two different bird types have the highest frequency the lower type (with the smallest ID number) is set.
I have an array of grades(g) which is an int[] and I'm trying to find the largest grade in that array. I have tried this:
public static String highestGradeName(int[] g, String[] n) {
String highStudent;
int highest = g[0];
for (int i=1; i < g.length; i++) {
if (highest < g[i]) {
highStudent = n[i+1];
return (highStudent);
}
}
return null;
}
I have another array which is a String array and contains the names of the students, I have the return null there because it said it needed a return statement however I didn't plan on it ever being null. What's causing it to return null instead of highstudent?
I've used the exact code to find the lowest grade and it works fine the only thing I did to this one was change the if statement from highest > g[i] to highest < g[i].
Returning from inside the loop is wrong, as you can always have an even larger number later on in the array. You should keep the index of the highest grade and just return the corresponding name at the end:
public static String highestGradeName(int[] g, String[] n) {
int highest = 0;
for (int i = 1; i < g.length; i++) {
if (g[highest] < g[i]) {
highest = i;
}
}
return n[highest];
}
According to your logic let's break things.
Raw Test Case:
Take {0,1,2} as an integer arrays.
Take {"arya", "jon", "tyrion"} as an string arrays.
highest = 0; // according to your code.
For int i = 1, i < 3; i++
0 < 1
highstudent = 2 // tyrion
// returns tyrion
The reason why you are getting null is your integer at 0 index should be greater or equal to the index at 1.
Now, when you are using a type String in your method. You should return a string and that's what your editor said to have something return. You should use return out of the loop because you need to find the highest student which is only possible after looping all the list.
You can try this:
public static String highestGradeName(int[] g, String[] n) {
int max = 0;
int index = 0;
for (int i = 0; i < g.length; i++) {
if (max < g[i]) {
max = g[i];
index = i;
}
}
return n[index];
}
PS: Imporve code according to mureinik answer, I have one more variable to help you understand easily.
Preface: This isn't for homework, but it is for a "coding challenge", it's not worth any points in my course but i would like a fuller understanding of arrays and loops so i want this to work before i move on in the course.
So here's my problem. I'm trying to design a method that reverse sorts an array and places the numbers from highest to lowest. The code i have now is :
public static void selectionReverseSort (int[] array)
{
int startScan, index, maxIndex, maxValue;
for (startScan = 0; startScan < (array.length - 1); startScan++)
{
maxIndex = startScan;
maxValue = array[startScan];
for(index = startScan + 1; index < array.length; index++)
//index is 1
{
if (array[index] > maxValue)
{
maxValue = array[index];
//maxValue now becomes the second array number
maxIndex = index;
//maxIndex becomes the current index number.
}
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
}
}
}
The problem with this code, is that it seems to only reverse sort the arrays if they were in ascending order to start with, otherwise it just repeats the highest number for the first few array slots. Anyone wanna help me understand what's going on here and what i could do to fix this?
Your algorithm is correct. But you are swapping unnecessarily even if the you have a small number. I updated you logic.
import java.io.*;
public class Hey{
public static void main(String args[])throws IOException{
int []ar = {1,2,5,4,6,8,7,9,10};
selectionReverseSort(ar);
}
public static void selectionReverseSort (int[] array){
int startScan, index, maxIndex, maxValue;
for (startScan = 0; startScan < (array.length - 1); startScan++){
maxIndex = startScan;
maxValue = array[startScan];
for(index = startScan + 1; index < array.length; index++){
//index is 1
if (array[index] > maxValue){
maxValue = array[index];
//maxValue now becomes the second array number
maxIndex = index;
//maxIndex becomes the current index number.
//swap only if the condition is true
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
}
}
}
}
for(int i = 0; i < array.length; i++ )
System.out.println(array[i]+"");
}
}
And I suggest you to use any other better sorting algorithm than Insertion sort.
It appears that the algorithm you've chosen is to find the largest value in the array, then use a swap to move the largest value to the first position in the array. Then you do the same for the subarray starting with the second element, then with the subarray starting with the third, and so on.
This will work, but your code does the swap too early. You need to wait until your inner loop is done finding the largest element before you do the swap. I haven't tested it, but I think all you need to do is move these two statements:
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
outside of the inner loop.
This is just a one-line solution by using java API:
public static void selectionReverseSort (int[] array){
Collections.sort(Arrays.asList(array),Collections.reverseOrder());
}
Keep it for future purpose :).
I'm trying to search an ArrayList and find the highest student mark. The values are randomly inputted. I have written code that works if the values are in order. But when I try to enter values in a random order, the loop always returns the last value entered! (Which is starting to frustrate me a little as I thought it worked!) It's probably something simple but I have missed the point again.
One other note .getName retrieves the student name with the highest mark.
Here is the code:
public String top()
{
int highest = 0;
int k;
for (k = 0; k < people.size();k++)
{
if (people.get(k).getMark() > highest)
{
highest = k;
}
}
return people.get(highest).getName();
}
You're setting highest to the index of the student with the highest mark, not to the highest mark itself. You probably want to keep both:
public String top()
{
int highestIndex = 0;
int highestMark = people.get(0).getMark();
for (int k = 1; k < people.size(); k++)
{
int mark = people.get(k).getMark();
if (mark > highestMark)
{
highestMark = mark;
highestIndex = k;
}
}
return people.get(highestIndex).getName();
}
Note two other changes I've made:
There's no point in declaring k before the loop; in general, it's tidiest to give local variables the smallest scope you can
I've used initial values from the first person in the collection; this will now work with negative marks as well
Separately, you should think about what you want to happen if people is empty. (Currently the code will throw an exception.)
the problem is that highest is the index, so your if condition should be:
if (people.get(k).getMark() > people.get(highest).getMark())
You can also store both the highest value and the index in two variables:
int highestVal = -1;
int highestIdx = -1;
for (int k = 0; k < people.size(); k++)
{
if (people.get(k).getMark() > highestVal)
{
highestVal = people.get(k).getMark();
highestIdx = k;
}
}
return people.get(highestIdx).getName();
You are comparing indices and values.
Try:
if (people.get(k).getMark() > people.get(highest).getMark())
You're confusing what your variables represent. You're comparing the indivduals marks to 'highst', but then you're setting highest to equal the index of that person (k).
So you're comparing indexes with marks...
highest is the index, you are comparing the mark to the index of the mark
if (people.get(k).getMark() > highest)
Instead of comparing to highest in the loop you should compare to people.get(highest).getMark()
Use an extra variable to hold the person's index.
public String top()
{
int highest = 0;
int k;
int topPerson;
for (k = 0; k < people.size();k++)
{
if (people.get(k).getMark() > highest)
{
highest = people.get(k).getMark() ;
topPerson = k;
}
}
return people.get(topPerson).getName();
}
try this one :)
public String top()
{
int highest = 0;
int k;
for (k = 1; k < people.size();k++)
{
if (people.get(k).getMark() > people.get(highest).getMark())
{
highest = k;
}
}
return people.get(highest).getName();
}
Basically, I have an assignment that requires me to find the mode of a given set of numbers.
This is my Method:
public void findMode (){
/* The vector data is analyzed and transferred into a smaller vector
smallList (0..100). For each occurrence of n in vector data,
smallList[n] is incremented +1. function Largest is then called
to find the largest quantity in vector smallList. The mode(s)
is/are printed out. */
int loop, largest;
int[] smallList = new int[101];
for (int i = 0; i < myHowMany; i++)
{
smallList[myData[i]]++;
}
int max = 0;
for (int i = 0; i < smallList.length; i++)
{
if (max < smallList[i])
{
max = smallList[i];
}
}
//Max is 26
int size = 0;
for (int i = 0; i < smallList.length; i++)
{
if (i == max) size++;
}
int[] modes = new int[size];
int modeIndex = 0;
for (int i = 0; i < smallList.length; i++)
{
if (smallList[i] == max)
{
modes[modeIndex] = smallList[i];
System.out.println(modes[modeIndex]);
modeIndex++;
}
} Everything compiles fine, but when I run this method, I get an out of bounds array method. I have no idea WHY this happens so I
need to know if the community can help me
.
Solved!
Please tell me if I need more information!
edit: I forgot to mention that I get the error here:
modes[modeIndex] = smallList[i];
New Problem:
I fixed the problem from before, but now, I find that my max goes unto the array so that modes = 26(max)
Your error is in this line
if (i == max) size++;
It should be
if (smallList[i] == max) size++;
This is causing the size of modes to be wrong
That should be clear enough: either modeIndex or i exceeds the array size. Since you're looping over smallList with smallList.length, I guess the error is in the modeIndex then. In this case, size (which is used to construct modes) isn't big enough.
if (i == max) size++;
and then
if (smallList[i] == max)
Please check your value for size.