Skip to main content
gamedev.net
🔒 Locked

Array Function problems

Started by dodger_404 10 replies 2.1k views
Original Post
dodger_404
dodger_404
i am trying to write a function or set of functions to seperate a file of numbers that has been put in an array into three catagories, odd, even, and negative. i have writen the function fine to read in the file of numbers into the array but im having a hard time deciding the logic in the sorting, i have thought to have a function sort into neg and pos, then sort even and odd and then have the reamining be the last of them. any input on this would be greatly appreciated. i have this function header so far not sure where to go from here. i just was thinking and it shouldnt be an int maybe a void being that im not returning any values just writing to a new arrray??? const int MAXSIZE = 150; istream & ReadArr(istream & in, double a[], const int MAX, int & howMany); void displayArray(ostream & os, const double ar[], int used); int sepnegs(const double a[], ???????????)
midasmax
midasmax
I am not sure if I fully understand your question, assuming you have an array consisting of,

[ 10, -2, 55, -32, 15, 9, 7 ]

You would want to get 3 different arrays?
E.g.

OddNums = [ 55, 15, 9 ,7 ]
EvenNums = [ 10 ]
NegNums = [ -2, -32 ]

If that's the case, you could simple create 3 boolean tests for each of these predicates, such as,

bool isEven( int n);
bool isOdd( int n );
bool isNegative(int n );

Then you can simply iterate through the array, test each number and then place them into their corresponding arrays.

dodger_404
dodger_404
yes i have a array like you had made but larger and i am trying to do exactly what you described but the array i am reading from is from file not counsel input.
midasmax
midasmax
Yup, it should still work nonetheless.

Once you have initialised your array ( whether it be from standard input or from a file ), you just iterate through it with a for loop, and test each number and place them into appropriate groups. A vector would be useful in this situation... for example

// your array int myArray[200];// initalise your Array from your file// e.g. readFromFileToArray( myArray );//assume unallocated indexes are assigned 0 value// your 3 groupsvector<int> oddNumbers; vector<int> evenNumbers;vector<int> negNumbers;// loop over the numbers// break when a zero (0) is encountered.for ( int i=0; i < 200; i++ ){   if ( isOdd(myArray) )        oddNumbers.push_back(myArray);   else if ( isEven(myArray) )        evenNumbers.push_back(myArray);   else if ( isNegative(myArray )        negNumbers.push_back(myArray;   else         break;}
dodger_404
dodger_404
i have just started reading on vectors so im not to familiar with them.
dodger_404
dodger_404
Ok NEW question I was able to seperatet the arrays into the three different arrays needed. i want to display the arrays in 3 colums odd, even, and negative, i can display them correct till i run out of entries in an array and then i get random 7-12 digit numbers, i dont know how i would display a blank slot on there. am i possibly doing this the hard way?
#include <iostream>#include <fstream>#include <iomanip>using namespace std;void output(int b[], int c[], int d[]);int main(){	const int ARRAY_SIZE = 150;  	int numbers[ARRAY_SIZE];    int b[100],c[100], d[100],n(0),m(0),p(0),q(0);	int count;	ifstream inputFile;		inputFile.open("numbers.in");		for (count = 0; count < ARRAY_SIZE; count++)		inputFile >> numbers[count];		inputFile.close();	n=0;	while(numbers[n] !=0)	{        if(numbers[n] < 0)        {            b[m] = numbers[n];            m++;        }        else if(numbers[n] %2 == 1)        {            c = numbers[n];            p++;        }        else         {             d[q] = numbers[n];             q++;        }        n++;    }    cout << "The arrays are: " << endl;    cout << setw(4) << "odd" <<            setw(9) << "even" <<            setw(12) << "negative\n" << endl;    int drac=0;    while(drac < 50)    {        cout << setw(4) << c[drac]             << setw(9) << d[drac]             << setw(12) << b[drac] << endl;        drac++;    }    system("pause");	return 0;}
yaustar
yaustar
Quote:
Original post by dodger_404
    int drac=0;    while(drac < 50)    {

You are assuming that there are 50 valid entries in each array. Is this right? Or should you be using a different value? After all, you already know how many valid entries there are in each already.
Steven Yau
[Blog] [Portfolio]
dodger_404
dodger_404
yeah is there a way i could find out how many entries ended up in the array?
a counter maybe like

int counterB = 0
while(b[] == !0)
{
counterB++
}

then later set the cout for each to be set to the counter found???
Winegums
Winegums
You use the value ARRAY_SIZE earlier in the program, perhaps this should be used here instead of a hard-coded number 50? Also reconsider your variable names. b..c...d...are not very good names.

XTAL256
XTAL256
Quote:
Original post by Winegums
You use the value ARRAY_SIZE earlier in the program, perhaps this should be used here instead of a hard-coded number 50?

Or, if you use vectors, you can use the size() function. Vectors aren't too hard to learn and are a lot easier to use than arrays so i suggest learning how to use them as soon as possible.
[Window Detective] - Windows UI spy utility for programmers
Zahlman
Zahlman
Quote:
Original post by dodger_404
i am trying to write a function or set of functions to seperate a file of numbers that has been put in an array into three catagories, odd, even, and negative.


By normal definitions, negative numbers can be even or odd, too, so those categories overlap. From the rest of your post, I understand that you want to separate into negative numbers, positive odd and positive even numbers.

Quote:
i have writen the function fine to read in the file of numbers into the array but im having a hard time deciding the logic in the sorting, i have thought to have a function sort into neg and pos, then sort even and odd and then have the reamining be the last of them.


This isn't really sorting; it's partitioning.

The standard library provides an algorithm called std::partition. It allows you to specify some condition and a sequence, and it rearranges the container so that elements that meet the condition come first, and elements that don't meet the condition come after. By keeping everything in the original container, we don't need to worry about how many elements fall into each category, or about assigning space for the new "groups" of elements.

You can define the conditions with functions, and just use the function's name as an argument. (Behind the scenes, the compiler interprets the function's name as a "function pointer" - a term you may want to toss into Google).

In C++, we do not generally use arrays for things where we don't know ahead of time how many elements we need. We certainly don't make assumptions like "150 ought to be enough". (You can already see why from some of the difficulty you've had so far.)

Instead, use the standard library container std::vector. The vector provides .begin() and .end() iterators, which can be used to specify the sequence for partitioning.

When we put all of that together, we (ok, I) get:

#include <vector> // this is where std::vector comes from#include <iostream>#include <algorithm> // this is where std::partition and std::copy come from#include <iterator> // I use this to do the output in a neat way.bool isNegative(int n) {  return n < 0;}bool isOdd(int n) {  return (n % 2) == 1;}int main() {  std::vector<int> numbers;  typedef std::vector<int>::iterator iterator;  // Here is a clever way to read the input stream. I'm using std::cin here.  // To "end" the standard input, use control-D on Windows; control-Z on Linux.  {    std::istream_iterator<int> number_reader(std::cin), end;    std::copy(number_reader, end, std::back_inserter(numbers));  }  iterator begin = numbers.begin(), end = numbers.end();  // Put the negative numbers in front of the positive numbers, and remember  // where the first positive number is, using std::partition:  iterator firstPositive = std::partition(begin, end, isNegative);  // Similarly, partition the positive numbers:  iterator firstEven = std::partition(firstPositive, end, isOdd);  // Now we can display each range of numbers. I'll do this using the std::copy  // algorithm, for illustrative purposes.  std::ostream_iterator<int> number_writer(std::cout, " ");  std::cout << "Negative numbers: ";  std::copy(begin, firstPositive, number_writer);  std::cout << "\nPositive even numbers: ";  std::copy(firstPositive, firstEven, number_writer);  std::cout << "\nPositive odd numbers: ";  std::copy(firstEven, end, number_writer);}
DevFred
DevFred
Quote:
Original post by Zahlman
bool isOdd(int n) {  return (n % 2) == 1;}


The % operator doesn't play well with negative arguments. It doesn't matter in this case, because we only pass positive numbers, but in general I'd prefer one of these solutions:
bool isOdd(int n) {  return (n % 2) != 0;}bool isOdd(int n) {  return (n % 2);}bool isOdd(int n) {  return (n & 1);}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.