Sunday, August 2, 2009

Programming c subvectors?

i am using C and i need help with subvectors, i have to make a program that does the following





A file contains a list of integers. The integers can, and are likely to, contain a mix of positive and negative values. The name of the file comes into your program via argv[1].


The first n numbers of the file are read by your program. The number n comes into your program via argv[2]. The number n will be no greater than 200,000.





For example, the file could contain the values:





-3 100 -4 -2 9 –63 -200 55





Your program will output a number that is the largest sum found in a subvector of this list. In the example above, the output would be 103 since that is the largest sum that can be formed by adding the elements of any subvector.





A subvector can be the entire list, a single member of the list, or it can be any collection of adjacent numbers. If the entire list of numbers contains negative numbers then your program should output 0.





Here is another example: 1 4 3 -4 8


The answer in this case would be 12 since the entire list of numbers forms the maximum sum.

Programming c subvectors?
#include %26lt;stdio.h%26gt; /* Include lots of standard definitions */


#include %26lt;stdlib.h%26gt; /* Get more useful definitions, like atof() */





main(argc,argv) /* Operating System supplies argc %26amp; argv */


int argc; /* The number of words in command line */


char *argv[]; /* The sequence of words in command line */


{ /* argv[0] is the program name */


int i; /* a loop counter - always an integer */


int highest; /* Highest number*/


int high2nd; /* 2nd highest*/


int temp;


double x, sum; /* working variables, double precision here */


sum = 0; /* Initialize sum to 0 */








for( i = 1 ; i %26lt; argc ; ++i ) { /* loop over args[1,...] */


x = atof(argv[i]); /* convert a string to a number */


if(x%26gt;high1st) {


temp=highest;


highest = x;


x = temp;


}


if(x%26gt;high2nd) {


high2nd=x;


}





}


sum = highest+high2nd;


printf("SUM:%i\n",sum); /* print sum after the loop completes */


}
Reply:You know, the problem here is that us real programmers, although we love writing code, couldn't be bothered to write programs to solve such trivial problems.





Which aspect of the question are you having a problem with? Arrays ("subvectors") can be a bit weird in C sometimes.

blue flowers

No comments:

Post a Comment