Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Nov 16th, 2011, 1:41 PM   #1
javanub
up and coming
 
Join Date: Nov 2011
Posts: 7
Rep Power: 0 javanub is on a distinguished road
Exclamation Median of an array

Okay so this is an assignment for my java lab... and this is also my first time posting, registered cause this is due tomorrow and I still haven't figured it out

I basically have the entire thing done and we're just learning about arrays and this lab was assigned before we even learned two dimensional arrays.

I think I basically have what she wants or what is required, I just seem to be misplacing some code or variables or something... if you guys could take a look at it and tell me what I'm doing wrong.

So also the point is we're supposed to be practicing for loops so I don't need an easier way to work around with more simple or effective methods or something like that, cause that I found in google (and didnt help me learn anything or complete assignment), I just need to figure out how to make this particular loop successful. The rest of the lab we were using for loops to find maximums and find specific names/scores within the arrays.

I have two arrays, only one needs ot be addressed though that is one of student scores. They are arranged randomly and not in numerical order or by the student's names or anything. Basically my attempt is through using a double loop, one that applies the inside loop to the first 7 numbers (half the length of the odd array). I try and use another loop to find the minimum each time of that array, take the minimum and set it to 100 in order to make it so the next minimum found will actually just be the 2nd, 3rd, so forth minimum. I do this 7 times until the next minimum I SHOULD find would be my median that I'm looking for (the 8th smallest number).

I hope this makes sense...
the array for scores are initialized as this though {65, 91, 41, 85, 91, 80, 85, 59, 82, 66, 77, 68, 70, 85, 72}

		int median = scores[0];
		for(int j = 0; j < scores.length/2; j++){
			int index = 0;
			for(int i = 0; i < scores.length; i++){
				if(scores[index] > scores[i]){
					index = i;
				}
			}
			scores[index] = 100;
		}
		for(int i = 0; i < scores.length; i++){
			if(median > scores[i]){
				median = scores[i];
			}
		}
				
		System.out.println("The median score is "+median);

I've reformatted these lines literally like 15 times (just deleted and retried or moved around and experimented with different places for the variables/position of loops), and mostly I'll get either the minimum of the original set as an answer (41) or 65 which is the first number. (65 for this particular code)

I think my problem is with the declaration... but I have continued to try assigning median/index in various positions and still cannot get the median as an answer after running. I feel like whatever I'm doing inside the nested loop is not being applied outside. perhaps I'm on the right track though with how to do this just not applying properly?

Advice, input, an example or anything would be greatly appreciated.

Hopefully I provided enough information for you guys to see what I don't.
javanub is offline   Reply With Quote
Old Nov 16th, 2011, 1:53 PM   #2
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Google / Kitchener
Posts: 4,154
Rep Power: 15 Sane has a spectacular aura aboutSane has a spectacular aura about
Send a message via MSN to Sane
Re: Median of an array

Take out a sheet of paper and run the code manually, tracing through what the values will be on a small example. You will encounter some holes in your logic when you see where it starts doing the wrong thing.

Most notably, your second for loop isn't going to select the median at all, given how you've pre-processed your array. You should be doing something different here. Again, run it by hand on an example to see why. You may be confusing your minimums and maximums.
__________________
PFO's Folding@Home Team | Sane's Monthly Algorithms Challenges
Rules | How to Post a Question | How to Post Code

Becoming a good programmer requires foresight of your code's execution.
Becoming an excellent programmer requires foresight of your code's modification.
Sane is offline   Reply With Quote
Old Nov 17th, 2011, 1:42 AM   #3
javanub
up and coming
 
Join Date: Nov 2011
Posts: 7
Rep Power: 0 javanub is on a distinguished road
Re: Median of an array

I dont see what you mean by confusion

I am basically asking where would I need to put the variable declarations it is not something I can write out, I dont see a flaw in my algorithm, it simply calculates the lowest number, turns that number into a max and then recalculates the newest minimum 6 more times and does the same thing, so that when it calculates the minimum the last time it is the 8th lowest number aka the median but does not turn it into 100 or whatever it just returns its original value.

I do not seem to understand where variables are affected by loops and where they wont be or where they wont transfer to?

If I write this by hand I get the same result I was looking for.

mindex represents the index number of the current minimum, when it is done with the loop for finding minimum, it takes that score and sets it to 100 aka above max in order to find the next lowest number. It then goes back through the entire process again because of the loop it is inside that continues to do this for the first 7 numbers.

I have rewritten this many times and I cannot see what is wrong with my process of finding it according to my teachers requirements by using loops, besides the order in which i declare these things. that is what I need help with.

unless you are saying I am not calculating the numbers I am looking for and it does not lie in the placement. I am sort of confused, because like I said running it by hand I get the numebrs/result I want.

int median = scores[0]; //answer
		for(int j = 0; j < scores.length/2; j++){ //this makes it go through an apply the same process to the lowest 7 numbers first...
			int index = 0; //this index is the location of current min
			for(int i = 0; i < scores.length; i++){ // this compares the currently configured minimum score to the rest of the scores
				if(scores[index] > scores[i]){ //(someone hinted my problem was in variables declaration location) this is saying if the score at this index is greater than the compared score, than the minimum number's index should be swapped to the lower one
					index = i; //if scores[index] = 65, and scores[i] = 41, 41's index will replace 65's for the index of the minimum
				}
			}
			scores[index] = 100; // this is SUPPOSED to change the array's value at that index to 100 in order to eliminate it from being found in the next loop so on so forth
//this entire process stops once its done this 7 times, aka lowest seven numbers are basically elminated as possible minimums, making the next minimum aka median the next selected choice
		}
		for(int i = 0; i < scores.length; i++){//this loops goes through whats left and finds the minimum one more time, which is supposed to be 77 or whatever the median may be, but not change it
			if(median > scores[i]){
				median = scores[i]; //if the compared score is less than the stashed away minimum under median variable, then median will equal the lower score until it has compared itself to all numbers in the array
			}
		}

				
		System.out.println("The median score is "+median); //the end, this should print median but i dont even understand why it prints 65 not even 41 sometimes, it just depends on where I place the last loop/variable assignments if i put them in certain spot it changes result, but never the median is displayed...

//calculations written out...
int median = scores[0];
		for(int j = 0; j < scores.length/2; j++){ //loop goes through 7 times before breaks
			int index = 0; //starts index off as the first number
			for(int i = 0; i < scores.length; i++){ //goes through all numbers in array
				if(scores[index] > scores[i]){ //if min index is greater, change to lower new index
					index = i; //65 > 41, new minimum = 41, 41 is first returned result
				}
			}
			scores[index] = 100; //in the first runthrough the location of 41 should be altered now to 100
		}
//this loop should have repeated itself again, instead of finding 41 this time as a min it should find 59 because 41 is no longer in the array and is greater than the maximum actually. the end of this loop before its 3rd repeat should set 59's place as 100 as well, so that the next loop finds 60 and turns that into 100 so on so forth 7 times
		for(int i = 0; i < scores.length; i++){
			if(median > scores[i]){ //after loop completes 7 times and turns the lowest 7 numbers in the array into huge numbers, this will find the following minimum, aka the median (median is middle number of set of numbers, 7 should be greater and 7 smaller, i elminate the 7 smallest so that median is the smallest number so that i can use the same find minimum loop to simply find the median).
				median = scores[i]; //median should be set to the newest low number aka 77 hopefully
			}
		}
				
		System.out.println("The median score is "+median); //idk why this prints 65 besides the fact index is declared as 0, this is my misunderstanding... i cannot comprehend how to make this variables be affectable through all loops and affect the original array through all loops.

it would be very helpful if you could put into perspective where the different placement of a variable makes a difference... sorry if im rushing before sleep, but is the change in array value only affecting like a local copy of the scores[] array? or is it supposed to affect the original set, but maybe it stops affecting it when loop ends, so i should calculate the median within the larger for loop rather than having its own? but at that point i usually somehow result with 41 as an answer then, sorry if i am totally missing some sort of stupid thing that i shouldve been seeing.

if i am incorrect on my method of actually isolating the median from the other numbers, then im totally off track and i have no clue then what im doing lol either way i hope you can enlighten me thanks for your prompt response

*quick addition edit: i am required to declare the array exactly as stated in the lab assignment, it is part of the challenge i believe to be able to sort with something you cannot simply change the original values of and with only using loops. unless i also misunderstood what you meant by preprocess the array.
javanub is offline   Reply With Quote
Old Nov 17th, 2011, 2:05 AM   #4
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Google / Kitchener
Posts: 4,154
Rep Power: 15 Sane has a spectacular aura aboutSane has a spectacular aura about
Send a message via MSN to Sane
Re: Median of an array

Yes, you are right that you weren't confusing your minimums and maximums. I swept over your code too quickly.

The problem is a bit more subtle. In your example, you initialize median to scores[0] = 65, before preprocessing the array. Do you see any problem with this?

After you've preprocessed scores, then scores[0] is now 100. Every element is also greater than 65, so nothing will be smaller. Therefore 'median' will remain 65, and you will eventually report 65 as the median, even though it wasn't even an element of the preprocessed array. This problem will occur any time that your first element happens to be strictly less than the true median.

You should move the initialization of 'median' down to after you preprocess scores. That way, it would start off as scores[0] = 100, and eventually decrease to the true median.

For future reference, outputting the scores array before/after preprocessing, and the value of median at each step in the loop, would have revealed this problem to you rather quickly. Adding print statements to debug your code can save an enormous amount of time (similar to following the code by hand, when that fails for reasons such as this).
__________________
PFO's Folding@Home Team | Sane's Monthly Algorithms Challenges
Rules | How to Post a Question | How to Post Code

Becoming a good programmer requires foresight of your code's execution.
Becoming an excellent programmer requires foresight of your code's modification.

Last edited by Sane; Nov 17th, 2011 at 2:22 AM.
Sane is offline   Reply With Quote
Old Nov 17th, 2011, 8:35 AM   #5
macteki
Professional Programmer
 
Join Date: Jul 2011
Posts: 437
Rep Power: 4 macteki will become famous soon enough
Re: Median of an array

Keep it simple, if you can preprocess the input, median can be found in 2 lines of code :

java Syntax (Toggle Plain Text)
  1. int[] scores={65, 91, 41, 85, 91, 80, 85, 59, 82, 66, 77, 68, 70, 85, 72};
  2. java.util.Arrays.sort(scores);
  3. System.out.println(scores[scores.length/2]);

The first line is array initialization. It is not counted.

If you cannot change your input, then you need 3 lines of code.
java Syntax (Toggle Plain Text)
  1. int[] scores={65, 91, 41, 85, 91, 80, 85, 59, 82, 66, 77, 68, 70, 85, 72};
  2. int[] buffer=(int[]) scores.clone();
  3. java.util.Arrays.sort(buffer);
  4. System.out.println(buffer[scores.length/2]);
__________________
API belongs to public. Knowledge belongs to yourself

http://java.macteki.com
macteki is offline   Reply With Quote
Old Nov 17th, 2011, 9:28 AM   #6
javanub
up and coming
 
Join Date: Nov 2011
Posts: 7
Rep Power: 0 javanub is on a distinguished road
Re: Median of an array

Okay thank you Sane, that was my problem.

All I had to do was move the median to be initialized after that loop.

I didn't think this was necessary but I may be understanding the concept of memory allocation or addresses in java incorrectly. As I saw it, that value of scores[] that was declared as 65, would automatically be changed for median by the time median was used, since the value 65 is not the assignment of the median variable, but the location of the value that scores[0] points too... which should be now 100.

Or that's how I thought it works, the programs working correctly now, thanks a lot. Though if someone could explain why that value was assigned permanently to median versus it being updated naturally, even though it executes correctly Im not entirely solid of the reason why java makes me do that. Also yes I tried doing print and stuff I guess I just never tried declaring the median completely after the double loop plus printing was messy inside loops. Thank you for your help and advice very much. To macteki you may have misread my problem, I can't use those methods but thanks for your input

edit: maybe you can help me understand this better? to clarify I thought and from what Ive done so far in java as little as it may be, assigning a variable to another variable's value is actually just pointing the program to the address of the original variable. so when median is called upon I THOUGHT that it should point back to scores[0] still, then get that value which at the time of using is 100, not 65.

my teacher basically said
using the following to show what i mean

a = 9
b = a

a = a+5

b should be equal to a's value still, aka 14.

After writing this I first checked in jgrasp and found that this is untrue? whenI print values...

So what was this entire concept even supposed to be applicable to? Has that lesson just gone over my head? lol sorry for the still misunderstanding, i appreciate your help and time

edit again: lol sorry to askagain, but what do you guys mean by preprocessing? or do you just mean the actual application of my loop/code affecting the array

Last edited by javanub; Nov 17th, 2011 at 9:53 AM. Reason: more question
javanub is offline   Reply With Quote
Old Nov 17th, 2011, 1:29 PM   #7
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Google / Kitchener
Posts: 4,154
Rep Power: 15 Sane has a spectacular aura aboutSane has a spectacular aura about
Send a message via MSN to Sane
Re: Median of an array

Quote:
Originally Posted by javanub View Post
Though if someone could explain why that value was assigned permanently to median versus it being updated naturally, even though it executes correctly Im not entirely solid of the reason why java makes me do that.

...

using the following to show what i mean

a = 9
b = a

a = a+5

b should be equal to a's value still, aka 14.

After writing this I first checked in jgrasp and found that this is untrue?
Lol. Glad you tried running that.

Firstly, there's a couple key ideas that you need to get down:
- Programs are read step by step.
- Variables can be assigned values.
- Values in assignment statements are determined by evaluating the right-hand expression, not by pointing to it.
- Variables keep those values until they are assigned a different value.

So in your example, we start with an empty slate. No variable has any value.

Read:

a = 9

Now variable 'a' has value 9.

b = a

Now variable 'b' has the value of 'a', which by evaluation, from the above, is the value 9. We now have a = 9 and b = 9.

a = a+5

Now variable 'a' has the value of 'a' plus 5, which again, by evaluation, is the value 14.

Quote:
Originally Posted by javanub View Post
So what was this entire concept even supposed to be applicable to? Has that lesson just gone over my head? lol sorry for the still misunderstanding, i appreciate your help and time
You might be confusing this with your lesson on "references". For these concepts, your value is an address, not a different datatype like an integer or character. In this case, if b's value is a reference to 'a', then 'b' will change when 'a' does, because it 'points' to the same storage location.

Quote:
Originally Posted by javanub View Post
edit again: lol sorry to askagain, but what do you guys mean by preprocessing? or do you just mean the actual application of my loop/code affecting the array
Yeah. By preprocessing I just meant you were doing a certain amount of processing on the array, thus modifying it, before actually determining what the median was.
__________________
PFO's Folding@Home Team | Sane's Monthly Algorithms Challenges
Rules | How to Post a Question | How to Post Code

Becoming a good programmer requires foresight of your code's execution.
Becoming an excellent programmer requires foresight of your code's modification.

Last edited by Sane; Nov 17th, 2011 at 1:56 PM.
Sane is offline   Reply With Quote
Old Nov 17th, 2011, 1:56 PM   #8
javanub
up and coming
 
Join Date: Nov 2011
Posts: 7
Rep Power: 0 javanub is on a distinguished road
Re: Median of an array

Ah okay I see what you mean, thank you so much for clarifying all this for me

I just have one last question to clear up the thing about pointing to addresses, what is that used for? Like in what practical application of using a reference or pointer would be different from the same idea as just passing on a value and what not. Will my understanding of what reference/pointers mean affect any of my programs? or is it just like a trivial concept that's just there and is taught for the sake of teaching. I think we talked about stuff like this in one of the lectures on passing on values or call by values or something, but unfortunately that was one of the rare days I was too exhausted to be able to absorb anything from that day.

EDIT: Will I ever be in a certain situation when programming to have to worry about when I declare a variable that the value will change because the variable I initially assigned it to is changing.
javanub is offline   Reply With Quote
Old Nov 17th, 2011, 2:58 PM   #9
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Google / Kitchener
Posts: 4,154
Rep Power: 15 Sane has a spectacular aura aboutSane has a spectacular aura about
Send a message via MSN to Sane
Re: Median of an array

Yes, you will need to care about these situations down the road. Also, by your mention of "pass by value" it seems that you did have a lecture on this.

References are used heavily in practice, because you don't always want to copy the value of the data when you're moving data around your program. The reasons for this are mainly because it makes things easier or it makes things faster.

On the side of making things easier: if you pass off a reference to some other routine, you don't have to worry about passing back the data to get its modifications; you can just access the same object and use the modified data.

As for making things faster: some references will point to very large chunks of data that you don't always want to copy every time you change it or pass it to another function. Imagine copying a list of a million elements every time you wanted to pass it elsewhere. It's much better to just copy a reference to that list (this is what happens by default, by the way) and then make modifications to the same underlying storage.

There are several tutorials you can find on the web about reference types in Java, since this is the topic that confuses the most number of people new to programming. For now, if it's too confusing, it's probably okay to just assume that everything is copied by value, and learn about the exceptions (e.g. lists, class instances, etc...) as they come, and see then why they are necessary.
__________________
PFO's Folding@Home Team | Sane's Monthly Algorithms Challenges
Rules | How to Post a Question | How to Post Code

Becoming a good programmer requires foresight of your code's execution.
Becoming an excellent programmer requires foresight of your code's modification.
Sane is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Find integer in list of array jatin89 Assembly 2 Jan 29th, 2011 11:49 AM
Dynamic Array arvigeus Java 11 Sep 2nd, 2010 8:53 PM
I have problem with Array yuriy_777 C++ 10 Feb 11th, 2010 3:28 AM
problem processing file into a char array csrocker101 C++ 1 May 8th, 2007 11:50 PM
changing size of an array Eric the Red Java 3 Apr 3rd, 2006 8:19 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 8:03 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC