GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 12-Aug-2012, 00:59
projectIT13 projectIT13 is offline
New Member
 
Join Date: Aug 2012
Posts: 27
projectIT13 is on a distinguished road
Question

Keep track of the last index used


How do you keep track of the last index use in two vectors/arrays.

For example:
CPP / C++ / C Code:
// contains random numbers
int a[22];

int firstArray[] = { 1, 2, 3, 4, 5, 6 };
int secArray[] = { 0, 0, 1, 3, 4 };

a[8] = firstArray[0];
a[12] =firstArray[1];
a[15] = secArray[0];
a[20] = firstArray[2];
a[3] = firstArray[3];

// and then assign firstArray[4] (last use index is 3) , secArray[1] (last use index is 0) to
// another value of a[].  

Basically I need to keep track of the last index used for the two arrays
Last edited by admin : 12-Aug-2012 at 04:12. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #2  
Old 12-Aug-2012, 08:21
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keep track of the last index used


Quote:
Originally Posted by projectIT13
How do you keep track of the last index use in two vectors/arrays....
I'm not sure what you are expecting here.

I mean, couldn't you just create an int variable with a human-readable significant name for each array (lastReadFirstArray or lastReadSecArray or whatever...) Initialize each to a value of -1.

You can read from an array by incrementing the corresponding bookkeeping variable (before reading) and making sure it won't take you beyond the end of the array.

Or am I missing something? (It wouldn't be the first time.)


Regards,

Dave

Footnote:
Alternatively, your bookeeping variable could indicate the next available index. Initialize it to zero and increment it each time after you read from the array.

You should check each time (before you read) to make sure it won't be reading beyond the end of the array.
__________________
Sometimes I just can't help myself...
Last edited by davekw7x : 12-Aug-2012 at 09:47.
  #3  
Old 13-Aug-2012, 01:48
projectIT13 projectIT13 is offline
New Member
 
Join Date: Aug 2012
Posts: 27
projectIT13 is on a distinguished road

Re: Keep track of the last index used


Here is my code so far:

CPP / C++ / C Code:
int lastReadZero = 0;
int lastReadOne = 0;

/* random[4] contains for random numbers 0-21 and is use as index for array 
   a[22] each random number a[random[i]] is compared to the average 
   
   if a[random[i]] < ave
    replace a[random[i]] = zero[]
   else
    replace a[random[i]] = one[]
*/ 

/* For example:
zero[] = { 0 , 0, 0, 0, 0 };
one[] = { 1, 1, 1, 1, 1, 1 };

*/

// My initial attempt
for( int i = 0; i < 4; ++i )
{
 if( a[random[i]] < average )
 {
   // check if counterZero goes beyond the size of the zero[]
   // if so retain the same number
   if( lastReadZero > zero.size() )
      a[random[i]] = a[random[i]];  
   else
   {
     a[random[i]] = zero[lastReadZero];
     lastReadZero++;  
   }
 }
 else
 {
   // check if counterOne goes beyond the size of the one[] 
   // if so retain the same number
   if( lastReadOne > one.size() )
     a[random[i]] = a[random[i]];  
   else
   {
     a[random[i]] = one[lastReadOne];
     lastReadOne++;  
    }
}
  cout << a[random[i]] << " ";
}
cout << "\n";

for(int i = 0; i < 22; ++i)
    cout << a[i] << " ";
cout << "\n" << "\n";


Output from code above

Code:
// for ex: Average 14.67 // four random numbers from array a[] 8 7 4 12 // there values after being compared to the average 0 0 0 0 // new values of array a[] 20 30 40 27 19 0 10 17 2 9 0 15 0 8 0 16 5 10 15 6 12 3 12 26 36 63 Segmentation fault (core dumped)

Can you point out from my code where I went wrong?
Last edited by admin : 13-Aug-2012 at 01:58. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #4  
Old 13-Aug-2012, 05:16
projectIT13 projectIT13 is offline
New Member
 
Join Date: Aug 2012
Posts: 27
projectIT13 is on a distinguished road

Re: Keep track of the last index used


So I changed to get rid of the segmentation fault but it's still giving me the wrong output

Code:
if( lastReadZero >= zero.size() ) if( lastReadOne >= one.size() )

Output:

Code:
/* For example: zero[] = { 0, 0, 0 }; one[] = { 1, 1 }; */ // this part is correct // Average 13.56 // four random values from array a[] 19 15 12 5 // values after being compared to the average 1 1 0 0 // new values of array a[] 20 30 40 27 1 8 10 17 2 9 7 1 4 8 0 16 0 10 15 6 12 3 //succeeding is wrong // Average 35.44 14 28 44 63 14 28 44 63 12 13 14 15 22 24 26 28 30 33 36 39 36 40 44 48 45 50 55 54 60 63 // should be 14 28 44 63 0 28 44 63 // last three values should stay the same since there are no more available values // from one[] and zero[]
  #5  
Old 13-Aug-2012, 07:22
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keep track of the last index used


Quote:
Originally Posted by projectIT13
So I changed to get rid of the segmentation fault
But you haven't given us anything that we can compile and see whether we can duplicate the results. Maybe we could have given more specific pointers on how to proceed. (A little C-pun there. Get it? Pointers? No? Oh, well...) For example I can't see how you got your value of average. I get nothing like that.

Quote:
Originally Posted by projectIT13
but it's still giving me the wrong output
Well, that's a matter of perspective. Maybe the output it is giving you is absolutely correct, but your expectations are misguided.

Here's a way to get to the bottom of things:

Put meaningful, labeled debugging print statements at each point in the program where things happen. Maybe something like:

CPP / C++ / C Code:
    cout << "Original : ";
    for (int i = 0; i < 22; ++i) {
        cout << a[i] << " ";
    }
    cout << endl << endl;

    cout << "Before loop: average = " << average << endl;

    // My initial attempt
    for (int i = 0; i < 4; ++i) {
        if (a[random[i]] < average) {
            // check if counterZero goes beyond the size of the zero[]
            // if so retain the same number
            if (lastReadZero > (int)zero.size())  // What the heck?  I thought it was an array.  Is it a vector???
            {
                a[random[i]] = a[random[i]]; // This is really silly
            }
            else {
                cout << "i = " << i << ", random[" << i << "] = " << random[i]
                     << ", lastReadZero = " << lastReadZero;

                a[random[i]] = zero[lastReadZero];

                cout << " : a[" << random[i] << "] is now " << a[random[i]]
                    << endl;
                lastReadZero++;
            }
        }
        else {
            // check if counterOne goes beyond the size of the one[] 
            // if so retain the same number
            if (lastReadOne > (int)one.size()) // What the heck?  I thought it was an array.  Is it a vector???
            {
                a[random[i]] = a[random[i]]; // This is really silly
            }
            else {
                cout << "i = " << i << ", random[" << i << "] = " << random[i]
                     << ", lastReadOne = " << lastReadOne;

                a[random[i]] = one[lastReadOne];

                cout << ": a[" << random[i] << "] is now " << a[random[i]]
                    << endl;
                lastReadOne++;
            }
        }
        // A particularly unenlightening unlabeled output.
        // What does this really tell you that helps
        // debugging?
        //cout << a[random[i]] << " "; // 
    }
    cout << "\n";

    cout << "Final    : ";
    for (int i = 0; i < 22; ++i) {
        cout << a[i] << " ";
    }
    cout << endl << endl;

Or some such thing.


Regards,

Dave
__________________
Sometimes I just can't help myself...
  #6  
Old 13-Aug-2012, 08:03
projectIT13 projectIT13 is offline
New Member
 
Join Date: Aug 2012
Posts: 27
projectIT13 is on a distinguished road

Re: Keep track of the last index used


Here's my test program:

Example: read.txt contains
0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 1

CPP / C++ / C Code:
#include <iostream>
#include <cstdlib> 
#include <fstream>
#include <vector>
#include <unordered_set>
#include <cmath>
#include <iomanip>
#include <functional>
#include <algorithm>

using namespace std;

fstream readFile;

void randNumber(int a[], double sum = 0)
{
  int random[4];

  readFile.open( "values.txt", fstream::in );

  // sum of random numbers
  double sumRandom = 0;

  unordered_set< int > unique; 
  unordered_set< int >::iterator it;

  while( unique.size() < 4 )
  {
    random[unique.size()] = rand() % 22;
    unique.insert( a[random[unique.size()]] );
  }

  std::sort( random, random + 4, std::less< int >() );

  cout << "4 Random Numbers " << "\n";
  for( it = unique.begin(); it != unique.end(); ++it )
  {
   sumRandom += *it;
  }

  // display four random numbers from array a[]
  for(int i = 0; i < 4; ++i)
  {
    cout << a[random[i]] << " ";
  }
  cout << "\n";

  double average;
  average = ( sum - sumRandom) / 18;
  
  vector< int > zero;
  vector< int > one;
  int num;

  // read values from file
  while( readFile >> num )
  {
    if( num == 1 )
      one.push_back(num);
    else
      zero.push_back(num);  
  }

 int lastReadZero = 0;
 int lastReadOne = 0;

 // My initial attempt
 for( int i = 0; i < 4; ++i )
 {
   if( a[random[i]] < average )
   {
     // check if counterZero goes beyond the size of the zero[]
     // if so retain the same number
     if( lastReadZero >= zero.size() )
      a[random[i]] = a[random[i]];  
     else
     {
       a[random[i]] = zero[lastReadZero];
       lastReadZero++;  
    }
  }
  else
  {
    // check if counterOne goes beyond the size of the one[] 
    // if so retain the same number
    if( lastReadOne >= one.size() )
     a[random[i]] = a[random[i]];  
    else
    {
      a[random[i]] = one[lastReadOne];
      lastReadOne++;  
    }
}
  cout << a[random[i]] << " ";
}
cout << "\n";

for(int i = 0; i < 22; ++i)
    cout << a[i] << " ";
cout << "\n" << "\n";


MAIN

CPP / C++ / C Code:
srand(time(NULL));

int a[] = { 20, 30, 40, 27, 19, 8, 10, 17, 2, 9, 7, 
              15, 4, 8, 12, 16, 5, 10, 15, 6, 12, 3 };

int b[] = { 12, 13, 14, 15, 22, 24, 26, 28, 30, 33, 
              36, 39, 36, 40, 44, 48, 45, 50, 55, 54, 60, 63 };

int c[] = { 36, 45, 54, 63, 30, 40, 50, 60, 22, 23, 44, 55, 
              12, 24, 36, 48, 13, 26, 39, 14, 28, 15 };

int d[] = { 108, 117, 126, 135, 110, 120, 130, 140, 
              110, 121, 132, 143, 108, 120, 132, 144, 117, 
              130, 143, 126, 140, 135 };

int sumA = 295;
int sumB = 787;
int sumC = 787;
int sumD = 2787;

randNumber(a, sumA);
randNumber(b, sumB);
randNumber(c, sumC);
randNumber(d, sumD);
   
return 0;

  #7  
Old 13-Aug-2012, 10:38
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keep track of the last index used


Quote:
Originally Posted by projectIT13
test program...]


I hate to repeat myself but:

Put print statements at strategic points in the program so that you can see what the program is seeing:

For starters,
CPP / C++ / C Code:
void randNumber(int a[], double sum)
{
    int random[4];
    const char * fileName = "read.txt"; // Or whatever the heck your file name rally is

    //fstream readFile;
    //readFile.open(fileName, fstream::in);
    // Your way is OK, but I would use
    ifstream readFile(fileName);
    if (!readFile)
    {
        cout << "Can't open " << fileName << " for reading." << endl;
        exit(EXIT_FAILURE);
    }
    cout << "  In randNumber:" << endl;
    cout << "    Opened file " << fileName << " for reading." << endl;
.
.
.
    // read values from file
    while (readFile >> num) {
        cout << "  Value from readFile = " << num << endl;
        if (num == 1)
        {
            one.push_back(num);
        }
        else
        {
            zero.push_back(num);
        }
    }
    cout << "    Average = " << average << endl;
    cout << "    Before loop: "
         << "zero.size() = " << zero.size()
         << ", one.size() = " << one.size() << endl;
    int lastReadZero = 0;
    int lastReadOne = 0;

    // My initial attempt
    for (int i = 0; i < 4; ++i)
.
.
        cout << "    End of loop: i = " << i
             << ", lastReadZero = " << lastReadZero
             << ", lastReadOne = " << lastReadOne
             << endl;
    }
    cout << "\n";

    cout << "    At end of randNumber: ";
    for (int i = 0; i < 22; ++i)
        cout << a[i] << " ";
    cout << "\n" << "\n";


I mean, you call the function four times. Each time you open the file and read its values so that the zero and one vectors are reinitialized each time. Right?



Regards,

Dave

Footnotes about style:
You have hard-coded values of the sums of the elements. In addition to making it hard to maintain, you actually have a wrong value for one of them. Let the program calculate the sums for you. Really.

You have also hard-coded the size of the arrays inside the function. What if you want to change the size of one or more of the arrays? Always pass size of arrays as arguments into functions that need to know the size. In general, it might be better to use vectors (or some other data structure that carries the size of the object with it) instead of arrays. But if you do use arrays (and it's usually OK to use arrays in cases like this), be sure to pass the size to functions that need to know. But I said that already.

Your method of calculating average after replacing array values with random values is wrong. Either calculate a new average after replacement or recalculate the average of fewer elements based on the elements that are going to be replaced or whatever the heck it is that that number is supposed to represent.
__________________
Sometimes I just can't help myself...
  #8  
Old 13-Aug-2012, 15:48
projectIT13 projectIT13 is offline
New Member
 
Join Date: Aug 2012
Posts: 27
projectIT13 is on a distinguished road

Re: Keep track of the last index used


Quote:
But you haven't given us anything that we can compile and see whether we can duplicate the results.

that's why I gave my test program

Quote:
You have hard-coded values of the sums of the elements.
this is just a test program that's why I hard coded it but on my other file it's not. I have a loop that calculates the sum.

Quote:
You have also hard-coded the size of the arrays inside the function. What if you want to change the size of one or more of the arrays?
I'm not going to change the size of the arrays.

Quote:
Always pass size of arrays as arguments into functions that need to know the size.

but thanks you for the advice

Quote:
Your method of calculating average after replacing array values with random values is wrong

I'm not calculating the average after. I'm calculating it before (or maybe I misunderstood something? Please feel free to correct me if ever). And I manually calculated to make sure the result of the average is correct.

and thanks for your suggestions I will try them
  #9  
Old 13-Aug-2012, 16:04
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keep track of the last index used


Quote:
Originally Posted by projectIT13
that's why I gave my test program
You gave the test file after my post with that complaint.

Quote:
Originally Posted by projectIT13
I'm not going to change the size of the arrays.
It's still a bad habit. Bad habits are easy to learn and hard to dispose of when/if things ever get beyond the elementary stage of one-programmer, one-program. People who get in a hurry to throw together a test program tend never to get around to making it the "right" way for future reference. The reason that I put the style suggestions in footnotes is because the improper style might not actually be harmful as far as getting immediate results.

Quote:
Originally Posted by projectIT13
I'm not calculating the average after. I'm calculating it before (or maybe I misunderstood something? Please feel free to correct me if ever).
Well, I just didn't understand how you are doing it or what it is supposed to mean. If you are happy with it, I'm probably wrong. So: nevermind my comment(s).

My key points are in the text above the footnotes: Put in print statements that are verbose enough to tell you what the program is seeing at points where it could be coming up with incorrect results.

Regards,

Dave
__________________
Sometimes I just can't help myself...
  #10  
Old 13-Aug-2012, 22:27
projectIT13 projectIT13 is offline
New Member
 
Join Date: Aug 2012
Posts: 27
projectIT13 is on a distinguished road

Re: Keep track of the last index used


already got it
 
 

Recent GIDBlogMatch IP in CIDR by gidnetwork

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

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

vB 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
NetBeans - Inventory Program biglez123 Java Forum 1 23-Jan-2011 19:48
[Tutorial] GUI programming with FLTK dsmith FLTK Forum 10 03-Oct-2005 15:41
Having a problem Chuckles Computer Hardware Forum 19 13-Sep-2004 12:17
hashing help saiz66 C++ Forum 1 06-Jul-2004 06:16
CD burner wont burn!! robertli55 Computer Hardware Forum 1 18-Jun-2004 10:53

Network Sites: GIDNetwork · GIDApp · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 07:51.


vBulletin, Copyright © 2000 - 2013, Jelsoft Enterprises Ltd.