?
Solved

sorting values generated in a loop

Posted on 2003-02-26
7
Medium Priority
?
244 Views
Last Modified: 2010-04-17
i am trying to get values (n number of values, determined by the user) that will be controlled in a FOR loop
"for (counter = 1; counter <= n; counter++)
    {
    printf(" Enter a score: ");
    scanf("%d", &score);
    sum += score;
    average = (float)sum/n;"
I will have -1 values to mean n/a score. if there are two or more -1's then do not calculate the average (and dont print it)
for instance, if n=4, the program should take the best three to calculate the average i.e. drop the least(smallest) value.
i am dont have the faintest idea on how to sort these values and be able to drop the least value.
programming skills is quiet basic, nothing really fancy (probably simple if statements) although i will be more than happy to encounter new stuff.
Any help is appreciated. Thanks
0
Comment
Question by:mafrenz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 

Expert Comment

by:mnf
ID: 8029527
Hi,

Many possible solutions here.
Assuming you are using C++ and need to save the values (and not calculate the average as you go)

#include <algorith.h>  // Standard library algorithms

int results[10];       // Store for results

// Get / generate results results[0]..results[n-1]
std::sort(results, results+n);    // Sorts your results

Alternatives include storing the results in order.  Have a look at the use of some of the container classes (array / list etc) - perhaps a little tricky to start with but a real goldmine of useful techniques.  Truly time well spent.

Martin
PS If using C have a look at qsort.
0
 

Author Comment

by:mafrenz
ID: 8029887
Thanks Martin, actually I am using C.
qsort works on pre-existing values (now unless i need to know how to convert pre-existing values to variables entered as the program executes)
This is exactly what I need "... when entering the scores, n/a will be entered as -1. if there are two or more n/a's then do not compute the average and grade it as incomplete. if there is none or one -1, compute the average by dropping the lowest score and averaging the others.(ofcourse if an entry has one -1, it will be dropped.
The variable n is entered by the user to determine the number of scores that will be entered. the scores are also entered by the user in no specific order.
0
 
LVL 2

Expert Comment

by:Jacamar
ID: 8030332
ok, I am not farmiliar with C, but I will give you a nice step by step method to sort.

Using a For loop

if the first value of the array1(n) is less than then next value array1(n+1) then swap the two values.  

To do this use a variable that will be the temp variable.

Temp = array(n)
array1(n) = array1(n+1)
array1(n+1) = Temp

Then check for the next n.

If you are only worried about the least value, you only have to go through this for loop (1 to n) once.  Because after doing this loop once, your smallest value will be the last value in the array.

If you are worried about multiple appearances of the smallest value.  ie. three 2's.  Then go through the for loop however many times you want to check for multiple values (call it degrees of safety).  Then you can do a for loop for 1 to n-1, or (n - however many smallest values ther are)

I hope this was helpful.

Jacamar
0
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 
LVL 7

Accepted Solution

by:
billious earned 225 total points
ID: 8030333
Your requirements are quite unclear.
If you have 2 n/a entries, then don't calculate ... fine
But what's this business about dropping the minimum real entry? Does this always happen, or only if you have 4 (or more?) scores, or are you only interested in the average of the best 3?

minentry = somelargeconstant
count_na = 0

for...
(
  ...
  if score == -1
    count_na ++
  else
    if score < minentry
      minentry = score
...}

if count_na < 2  // not more than 2 n/as
{
  sum = sum + count_na    //add back -1 summed if one n/a
  if n > 3
    {sum = sum - minentry
     average = sum / (n-1)}
  else
    average = sum / n}
  print ...
}


up to you to correct syntax - method should be clear - only wish the question was clearer! :)

...Bill
0
 

Expert Comment

by:mnf
ID: 8031959
A quick solution using C:


#include   <stdio.h>


int compare(void *a, void *b)
{
        // Nasty typecast to get at ints ppointed to by void *ptrs
        return (*(int *)a) - (*(int *)b);
}

#pragma argsused
int main(int argc, char* argv[])
{
        int scores, input;
        int results[100];
        int i, n;
        scores = 0; na_scores = 0;
        printf("Enter number of results ");
        scanf("%d", &n);     // Check < MAX_SCORES
        for(i = 0; i < n; ++i)
        {
                printf("Result %i = ", i);
                scanf("%d", &input); // Check valid / add to total
                if(input != -1) results[i] = input;
        }
        qsort(results, n,  sizeof(int),  compare);
        for(i = 0; i < n; ++i)
        {
                // Work with results
                printf("Result no %i = %i\n", i, results[i]);
        }
        getchar();
        getchar();
        return 0;
}

Hope this helps

Martin
0
 

Expert Comment

by:mnf
ID: 8033672
A quick solution using C:


#include   <stdio.h>


int compare(void *a, void *b)
{
        // Nasty typecast to get at ints ppointed to by void *ptrs
        return (*(int *)a) - (*(int *)b);
}

#pragma argsused
int main(int argc, char* argv[])
{
        int scores, input;
        int results[100];
        int i, n;
        scores = 0; na_scores = 0;
        printf("Enter number of results ");
        scanf("%d", &n);     // Check < MAX_SCORES
        for(i = 0; i < n; ++i)
        {
                printf("Result %i = ", i);
                scanf("%d", &input); // Check valid / add to total
                if(input != -1) results[i] = input;
        }
        qsort(results, n,  sizeof(int),  compare);
        for(i = 0; i < n; ++i)
        {
                // Work with results
                printf("Result no %i = %i\n", i, results[i]);
        }
        getchar();
        getchar();
        return 0;
}

Hope this helps

Martin
0
 

Author Comment

by:mafrenz
ID: 8067405
Athough you said i was unclear, but your syntax seemed to fit exactly with what i wanted (nothing fancy and most with nested ifs). i got the program rolling now. thanks.
also appreciate your efforts Martin (i need to get deeper into your stuff/i am still young in C!) and Jacamar.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
Introduction to Processes

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question