Search Results

Search found 85 results on 4 pages for 'srand'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • Why is my simple recusive method's final return value always off by 1?

    - by FrankTheTank
    I'm attempting to create a text-based version of this game: http://www.cse.nd.edu/java/SameGame.html Here is the code I have so far: #include <iostream> #include <vector> #include <ctime> class Clickomania { public: Clickomania(); std::vector<std::vector<int> > board; int move(int, int); bool isSolved(); void print(); void pushDown(); bool isValid(); }; Clickomania::Clickomania() : board(12, std::vector<int>(8,0)) { srand((unsigned)time(0)); for(int i = 0; i < 12; i++) { for(int j = 0; j < 8; j++) { int color = (rand() % 3) + 1; board[i][j] = color; } } } void Clickomania::pushDown() { for(int i = 0; i < 8; i++) { for(int j = 0; j < 12; j++) { if (board[j][i] == 0) { for(int k = j; k > 0; k--) { board[k][i] = board[k-1][i]; } board[0][i] = 0; } } } } int Clickomania::move(int row, int col) { bool match = false; int totalMatches = 0; if (row > 12 || row < 0 || col > 8 || col < 0) { return 0; } int currentColor = board[row][col]; board[row][col] = 0; if ((row + 1) < 12) { if (board[row+1][col] == currentColor) { match = true; totalMatches++; totalMatches += move(row+1, col); } } if ((row - 1) >= 0) { if (board[row-1][col] == currentColor) { match = true; totalMatches++; totalMatches += move(row-1, col); } } if ((col + 1) < 8) { if (board[row][col+1] == currentColor) { match = true; totalMatches++; totalMatches += move(row, col+1); } } if ((col - 1) >= 0) { if (board[row][col-1] == currentColor) { match = true; totalMatches++; totalMatches += move(row, col-1); } } return totalMatches; } void Clickomania::print() { for(int i = 0; i < 12; i++) { for(int j = 0; j < 8; j++) { std::cout << board[i][j]; } std::cout << "\n"; } } int main() { Clickomania game; game.print(); int row; int col; std::cout << "Enter row: "; std::cin >> row; std::cout << "Enter col: "; std::cin >> col; int numDestroyed = game.move(row,col); game.print(); std::cout << "Destroyed: " << numDestroyed << "\n"; } The method that is giving me trouble is my "move" method. This method, given a pair of coordinates, should delete all the squares at that coordinate with the same number and likewise with all the squares with the same number connected to it. If you play the link I gave above you'll see how the deletion works on a click. int Clickomania::move(int row, int col) { bool match = false; int totalMatches = 0; if (row > 12 || row < 0 || col > 8 || col < 0) { return 0; } int currentColor = board[row][col]; board[row][col] = 0; if ((row + 1) < 12) { if (board[row+1][col] == currentColor) { match = true; totalMatches++; totalMatches += move(row+1, col); } } if ((row - 1) >= 0) { if (board[row-1][col] == currentColor) { match = true; totalMatches++; totalMatches += move(row-1, col); } } if ((col + 1) < 8) { if (board[row][col+1] == currentColor) { match = true; totalMatches++; totalMatches += move(row, col+1); } } if ((col - 1) >= 0) { if (board[row][col-1] == currentColor) { match = true; totalMatches++; totalMatches += move(row, col-1); } } return totalMatches; } My move() method above works fine, as in, it will delete the appropriate "blocks" and replace them with zeros. However, the number of destroyed (value returned) is always one off (too small). I believe this is because the first call of move() isn't being counted but I don't know how to differentiate between the first call or subsequent calls in that recursive method. How can I modify my move() method so it returns the correct number of destroyed blocks?

    Read the article

  • g++ SSE intrinsics dilemma - value from intrinsic "saturates"

    - by Sriram
    Hi, I wrote a simple program to implement SSE intrinsics for computing the inner product of two large (100000 or more elements) vectors. The program compares the execution time for both, inner product computed the conventional way and using intrinsics. Everything works out fine, until I insert (just for the fun of it) an inner loop before the statement that computes the inner product. Before I go further, here is the code: //this is a sample Intrinsics program to compute inner product of two vectors and compare Intrinsics with traditional method of doing things. #include <iostream> #include <iomanip> #include <xmmintrin.h> #include <stdio.h> #include <time.h> #include <stdlib.h> using namespace std; typedef float v4sf __attribute__ ((vector_size(16))); double innerProduct(float* arr1, int len1, float* arr2, int len2) { //assume len1 = len2. float result = 0.0; for(int i = 0; i < len1; i++) { for(int j = 0; j < len1; j++) { result += (arr1[i] * arr2[i]); } } //float y = 1.23e+09; //cout << "y = " << y << endl; return result; } double sse_v4sf_innerProduct(float* arr1, int len1, float* arr2, int len2) { //assume that len1 = len2. if(len1 != len2) { cout << "Lengths not equal." << endl; exit(1); } /*steps: * 1. load a long-type (4 float) into a v4sf type data from both arrays. * 2. multiply the two. * 3. multiply the same and store result. * 4. add this to previous results. */ v4sf arr1Data, arr2Data, prevSums, multVal, xyz; //__builtin_ia32_xorps(prevSums, prevSums); //making it equal zero. //can explicitly load 0 into prevSums using loadps or storeps (Check). float temp[4] = {0.0, 0.0, 0.0, 0.0}; prevSums = __builtin_ia32_loadups(temp); float result = 0.0; for(int i = 0; i < (len1 - 3); i += 4) { for(int j = 0; j < len1; j++) { arr1Data = __builtin_ia32_loadups(&arr1[i]); arr2Data = __builtin_ia32_loadups(&arr2[i]); //store the contents of two arrays. multVal = __builtin_ia32_mulps(arr1Data, arr2Data); //multiply. xyz = __builtin_ia32_addps(multVal, prevSums); prevSums = xyz; } } //prevSums will hold the sums of 4 32-bit floating point values taken at a time. Individual entries in prevSums also need to be added. __builtin_ia32_storeups(temp, prevSums); //store prevSums into temp. cout << "Values of temp:" << endl; for(int i = 0; i < 4; i++) cout << temp[i] << endl; result += temp[0] + temp[1] + temp[2] + temp[3]; return result; } int main() { clock_t begin, end; int length = 100000; float *arr1, *arr2; double result_Conventional, result_Intrinsic; // printStats("Allocating memory."); arr1 = new float[length]; arr2 = new float[length]; // printStats("End allocation."); srand(time(NULL)); //init random seed. // printStats("Initializing array1 and array2"); begin = clock(); for(int i = 0; i < length; i++) { // for(int j = 0; j < length; j++) { // arr1[i] = rand() % 10 + 1; arr1[i] = 2.5; // arr2[i] = rand() % 10 - 1; arr2[i] = 2.5; // } } end = clock(); cout << "Time to initialize array1 and array2 = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl; // printStats("Finished initialization."); // printStats("Begin inner product conventionally."); begin = clock(); result_Conventional = innerProduct(arr1, length, arr2, length); end = clock(); cout << "Time to compute inner product conventionally = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl; // printStats("End inner product conventionally."); // printStats("Begin inner product using Intrinsics."); begin = clock(); result_Intrinsic = sse_v4sf_innerProduct(arr1, length, arr2, length); end = clock(); cout << "Time to compute inner product with intrinsics = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl; //printStats("End inner product using Intrinsics."); cout << "Results: " << endl; cout << " result_Conventional = " << result_Conventional << endl; cout << " result_Intrinsics = " << result_Intrinsic << endl; return 0; } I use the following g++ invocation to build this: g++ -W -Wall -O2 -pedantic -march=i386 -msse intrinsics_SSE_innerProduct.C -o innerProduct Each of the loops above, in both the functions, runs a total of N^2 times. However, given that arr1 and arr2 (the two floating point vectors) are loaded with a value 2.5, the length of the array is 100,000, the result in both cases should be 6.25e+10. The results I get are: Results: result_Conventional = 6.25e+10 result_Intrinsics = 5.36871e+08 This is not all. It seems that the value returned from the function that uses intrinsics "saturates" at the value above. I tried putting other values for the elements of the array and different sizes too. But it seems that any value above 1.0 for the array contents and any size above 1000 meets with the same value we see above. Initially, I thought it might be because all operations within SSE are in floating point, but floating point should be able to store a number that is of the order of e+08. I am trying to see where I could be going wrong but cannot seem to figure it out. I am using g++ version: g++ (GCC) 4.4.1 20090725 (Red Hat 4.4.1-2). Any help on this is most welcome. Thanks, Sriram.

    Read the article

  • Cumulative +1/-1 Cointoss crashes on 1000 iterations. Please advise; c++ boost random libraries

    - by user1731972
    following some former advice Multithreaded application, am I doing it right? I think I have a threadsafe number generator using boost, but my program crashes when I input 1000 iterations. The output .csv file when graphed looks right, but I'm not sure why it's crashing. It's using _beginthread, and everyone is telling me I should use the more (convoluted) _beingthreadex, which I'm not familiar with. If someone could recommend an example, I would greatly appreciate it. Also... someone pointed out I should be applying a second parameter to my _beginthread for the array counting start positions, but I have no idea how to pass more than one parameter, other than attempting to use a structure, and I've read structure's and _beginthread don't get along (although, I could just use the boost threads...) #include <process.h> #include <windows.h> #include <iostream> #include <fstream> #include <time.h> #include <random> #include <boost/random.hpp> //for srand48_r(time(NULL), &randBuffer); which doesn't work #include <stdio.h> #include <stdlib.h> //#include <thread> using namespace std; using namespace boost; using namespace boost::random; void myThread0 (void *dummy ); void myThread1 (void *dummy ); void myThread2 (void *dummy ); void myThread3 (void *dummy ); //for random seeds void initialize(); //from http://stackoverflow.com/questions/7114043/random-number-generation-in-c11-how-to-generate-how-do-they-work uniform_int_distribution<> two(1,2); typedef std::mt19937 MyRNG; // the Mersenne Twister with a popular choice of parameters uint32_t seed_val; // populate somehow MyRNG rng1; // e.g. keep one global instance (per thread) MyRNG rng2; // e.g. keep one global instance (per thread) MyRNG rng3; // e.g. keep one global instance (per thread) MyRNG rng4; // e.g. keep one global instance (per thread) //only needed for shared variables //CRITICAL_SECTION cs1,cs2,cs3,cs4; // global int main() { ofstream myfile; myfile.open ("coinToss.csv"); int rNum; long numRuns; long count = 0; int divisor = 1; float fHolder = 0; long counter = 0; float percent = 0.0; //? //unsigned threadID; //HANDLE hThread; initialize(); HANDLE hThread[4]; const int size = 100000; int array[size]; printf ("Runs (uses multiple of 100,000) "); cin >> numRuns; for (int a = 0; a < numRuns; a++) { hThread[0] = (HANDLE)_beginthread( myThread0, 0, (void*)(array) ); hThread[1] = (HANDLE)_beginthread( myThread1, 0, (void*)(array) ); hThread[2] = (HANDLE)_beginthread( myThread2, 0, (void*)(array) ); hThread[3] = (HANDLE)_beginthread( myThread3, 0, (void*)(array) ); //waits for threads to finish before continuing WaitForMultipleObjects(4, hThread, TRUE, INFINITE); //closes handles I guess? CloseHandle( hThread[0] ); CloseHandle( hThread[1] ); CloseHandle( hThread[2] ); CloseHandle( hThread[3] ); //dump array into calculations //average array into fHolder //this could be split into threads as well for (int p = 0; p < size; p++) { counter += array[p] == 2 ? 1 : -1; //cout << array[p] << endl; //cout << counter << endl; } //this fHolder calculation didn't work //fHolder = counter / size; //so I had to use this cout << counter << endl; fHolder = counter; fHolder = fHolder / size; myfile << fHolder << endl; } } void initialize() { //seed value needs to be supplied //rng1.seed(seed_val*1); rng1.seed((unsigned int)time(NULL)); rng2.seed(((unsigned int)time(NULL))*2); rng3.seed(((unsigned int)time(NULL))*3); rng4.seed(((unsigned int)time(NULL))*4); }; void myThread0 (void *param) { //EnterCriticalSection(&cs1); //aquire the critical section object int *i = (int *)param; for (int x = 0; x < 25000; x++) { //doesn't work, part of merssene twister //i[x] = next(); i[x] = two(rng1); //original srand //i[x] = rand() % 2 + 1; //doesn't work for some reason. //uint_dist2(rng); //i[x] = qrand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs1); // release the critical section object } void myThread1 (void *param) { //EnterCriticalSection(&cs2); //aquire the critical section object int *i = (int *)param; for (int x = 25000; x < 50000; x++) { //param[x] = rand() % 2 + 1; i[x] = two(rng2); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs2); // release the critical section object } void myThread2 (void *param) { //EnterCriticalSection(&cs3); //aquire the critical section object int *i = (int *)param; for (int x = 50000; x < 75000; x++) { i[x] = two(rng3); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs3); // release the critical section object } void myThread3 (void *param) { //EnterCriticalSection(&cs4); //aquire the critical section object int *i = (int *)param; for (int x = 75000; x < 100000; x++) { i[x] = two(rng4); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs4); // release the critical section object }

    Read the article

  • C++ function not found during compilation

    - by forthewinwin
    For a homework assignment: I'm supposed to create randomized alphabetial keys, print them to a file, and then hash each of them into a hash table using the function "goodHash", found in my below code. When I try to run the below code, it says my "goodHash" "identifier isn't found". What's wrong with my code? #include <iostream> #include <vector> #include <cstdlib> #include "math.h" #include <fstream> #include <time.h> using namespace std; // "makeKey" function to create an alphabetical key // based on 8 randomized numbers 0 - 25. string makeKey() { int k; string key = ""; for (k = 0; k < 8; k++) { int keyNumber = (rand() % 25); if (keyNumber == 0) key.append("A"); if (keyNumber == 1) key.append("B"); if (keyNumber == 2) key.append("C"); if (keyNumber == 3) key.append("D"); if (keyNumber == 4) key.append("E"); if (keyNumber == 5) key.append("F"); if (keyNumber == 6) key.append("G"); if (keyNumber == 7) key.append("H"); if (keyNumber == 8) key.append("I"); if (keyNumber == 9) key.append("J"); if (keyNumber == 10) key.append("K"); if (keyNumber == 11) key.append("L"); if (keyNumber == 12) key.append("M"); if (keyNumber == 13) key.append("N"); if (keyNumber == 14) key.append("O"); if (keyNumber == 15) key.append("P"); if (keyNumber == 16) key.append("Q"); if (keyNumber == 17) key.append("R"); if (keyNumber == 18) key.append("S"); if (keyNumber == 19) key.append("T"); if (keyNumber == 20) key.append("U"); if (keyNumber == 21) key.append("V"); if (keyNumber == 22) key.append("W"); if (keyNumber == 23) key.append("X"); if (keyNumber == 24) key.append("Y"); if (keyNumber == 25) key.append("Z"); } return key; } // "makeFile" function to produce the desired text file. // Note this only works as intended if you include the ".txt" extension, // and that a file of the same name doesn't already exist. void makeFile(string fileName, int n) { ofstream ourFile; ourFile.open(fileName); int k; // For use in below loop to compare with n. int l; // For use in the loop inside the below loop. string keyToPassTogoodHash = ""; for (k = 1; k <= n; k++) { for (l = 0; l < 8; l++) { // For-loop to write to the file ONE key ourFile << makeKey()[l]; keyToPassTogoodHash += (makeKey()[l]); } ourFile << " " << k << "\n";// Writes two spaces and the data value goodHash(keyToPassTogoodHash); // I think this has to do with the problem makeKey(); // Call again to make a new key. } } // Primary function to create our desired file! void mainFunction(string fileName, int n) { makeKey(); makeFile(fileName, n); } // Hash Table for Part 2 struct Node { int key; string value; Node* next; }; const int hashTableSize = 10; Node* hashTable[hashTableSize]; // "goodHash" function for Part 2 void goodHash(string key) { int x = 0; int y; int keyConvertedToNumber = 0; // For-loop to produce a numeric value based on the alphabetic key, // which is then hashed into hashTable using the hash function // declared below the loop (hashFunction). for (y = 0; y < 8; y++) { if (key[y] == 'A' || 'B' || 'C') x = 0; if (key[y] == 'D' || 'E' || 'F') x = 1; if (key[y] == 'G' || 'H' || 'I') x = 2; if (key[y] == 'J' || 'K' || 'L') x = 3; if (key[y] == 'M' || 'N' || 'O') x = 4; if (key[y] == 'P' || 'Q' || 'R') x = 5; if (key[y] == 'S' || 'T') x = 6; if (key[y] == 'U' || 'V') x = 7; if (key[y] == 'W' || 'X') x = 8; if (key[y] == 'Y' || 'Z') x = 9; keyConvertedToNumber = x + keyConvertedToNumber; } int hashFunction = keyConvertedToNumber % hashTableSize; Node *temp; temp = new Node; temp->value = key; temp->next = hashTable[hashFunction]; hashTable[hashFunction] = temp; } // First two lines are for Part 1, to call the functions key to Part 1. int main() { srand ( time(NULL) ); // To make sure our randomization works. mainFunction("sandwich.txt", 5); // To test program cin.get(); return 0; } I realize my code is cumbersome in some sections, but I'm a noob at C++ and don't know much to do it better. I'm guessing another way I could do it is to AFTER writing the alphabetical keys to the file, read them from the file and hash each key as I do that, but I wouldn't know how to go about coding that.

    Read the article

  • mysterical error

    - by Görkem Buzcu
    i get "customer_service_simulator.exe stopped" error, but i dont know why? this is my c programming project and i have limited time left before deadline. the code is: #include <stdio.h> #include <stdlib.h> #include<time.h> #define FALSE 0 #define TRUE 1 /*A Node declaration to store a value, pointer to the next node and a priority value*/ struct Node { int priority; //arrival time int val; //type int wait_time; int departure_time; struct Node *next; }; Queue Record that will store the following: size: total number of elements stored in the list front: it shows the front node of the queue (front of the queue) rear: it shows the rare node of the queue (rear of the queue) availability: availabity of the teller struct QueueRecord { struct Node *front; struct Node *rear; int size; int availability; }; typedef struct Node *niyazi; typedef struct QueueRecord *Queue; Queue CreateQueue(int); void MakeEmptyQueue(Queue); void enqueue(Queue, int, int); int QueueSize(Queue); int FrontOfQueue(Queue); int RearOfQueue(Queue); niyazi dequeue(Queue); int IsFullQueue(Queue); int IsEmptyQueue(Queue); void DisplayQueue(Queue); void sorteddequeue(Queue); void sortedenqueue(Queue, int, int); void tellerzfunctionz(Queue *, Queue, int, int); int main() { int system_clock=0; Queue waitqueue; int exit, val, priority, customers, tellers, avg_serv_time, sim_time,counter; char command; waitqueue = CreateQueue(0); srand(time(NULL)); fflush(stdin); printf("Enter number of customers, number of tellers, average service time, simulation time\n:"); scanf("%d%c %d%c %d%c %d",&customers, &command,&tellers,&command,&avg_serv_time,&command,&sim_time); fflush(stdin); Queue tellerarray[tellers]; for(counter=0;counter<tellers;counter++){ tellerarray[counter]=CreateQueue(0); //burada teller sayisi kadar queue yaratiyorum } for(counter=0;counter<customers;counter++){ priority=1+(int)rand()%sim_time; //this will generate the arrival time sortedenqueue(waitqueue,1,priority); //here i put the customers in the waiting queue } tellerzfunctionz(tellerarray,waitqueue,tellers,customers); DisplayQueue(waitqueue); DisplayQueue(tellerarray[0]); DisplayQueue(tellerarray[1]); // waitqueue-> printf("\n\n"); system("PAUSE"); return 0; } /*This function initialises the queue*/ Queue CreateQueue(int maxElements) { Queue q; q = (struct QueueRecord *) malloc(sizeof(struct QueueRecord)); if (q == NULL) printf("Out of memory space\n"); else MakeEmptyQueue(q); return q; } /*This function sets the queue size to 0, and creates a dummy element and sets the front and rear point to this dummy element*/ void MakeEmptyQueue(Queue q) { q->size = 0; q->availability=0; q->front = (struct Node *) malloc(sizeof(struct Node)); if (q->front == NULL) printf("Out of memory space\n"); else{ q->front->next = NULL; q->rear = q->front; } } /*Shows if the queue is empty*/ int IsEmptyQueue(Queue q) { return (q->size == 0); } /*Returns the queue size*/ int QueueSize(Queue q) { return (q->size); } /*Shows the queue is full or not*/ int IsFullQueue(Queue q) { return FALSE; } /*Returns the value stored in the front of the queue*/ int FrontOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->front->next->val; else { printf("The queue is empty\n"); return -1; } } /*Returns the value stored in the rear of the queue*/ int RearOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->rear->val; else { printf("The queue is empty\n"); return -1; } } /*Displays the content of the queue*/ void DisplayQueue(Queue q) { struct Node *pos; pos=q->front->next; printf("Queue content:\n"); printf("-->Priority Value\n"); while (pos != NULL) { printf("--> %d\t %d\n", pos->priority, pos->val); pos = pos->next; } } void enqueue(Queue q, int element, int priority){ if(IsFullQueue(q)){ printf("Error queue is full"); } else{ q->rear->next=(struct Node *)malloc(sizeof(struct Node)); q->rear=q->rear->next; q->rear->next=NULL; q->rear->val=element; q->rear->priority=priority; q->size++; } } void sortedenqueue(Queue q, int val, int priority) { struct Node *insert,*temp; insert=(struct Node *)malloc(sizeof(struct Node)); insert->val=val; insert->priority=priority; temp=q->front; if(q->size==0){ enqueue(q, val, priority); } else{ while(temp->next!=NULL && temp->next->priority<insert->priority){ temp=temp->next; } //printf("%d",temp->priority); insert->next=temp->next; temp->next=insert; q->size++; if(insert->next==NULL){ q->rear=insert; } } } niyazi dequeue(Queue q) { niyazi del; niyazi deli; del=(niyazi)malloc(sizeof(struct Node)); deli=(niyazi)malloc(sizeof(struct Node)); if(IsEmptyQueue(q)){ printf("Queue is empty!"); return NULL; } else { del=q->front->next; q->front->next=del->next; deli->val=del->val; deli->priority=del->priority; free(del); q->size--; return deli; } } void sorteddequeue(Queue q) { struct Node *temp; struct Node *min; temp=q->front->next; min=q->front; int i; for(i=1;i<q->size;i++) { if(temp->next->priority<min->next->priority) { min=temp; } temp=temp->next; } temp=min->next; min->next=min->next->next; free(temp); if(min->next==NULL){ q->rear=min; } q->size--; } void tellerzfunctionz(Queue *a, Queue b, int c, int d){ int i; int value=0; int priority; niyazi temp; temp=(niyazi)malloc(sizeof(struct Node)); if(c==1){ for(i=0;i<d;i++){ temp=dequeue(b); sortedenqueue((*(a)),temp->val,temp->priority); } } else{ for(i=0;i<d;i++){ while(b->front->next->val==1){ if((*(a+value))->availability==1){ temp=dequeue(b); sortedenqueue((*(a+value)),temp->val,temp->priority); (*(a+value))->rear->val=2; } else{ value++; } } } } } //end of the program

    Read the article

  • Error codes for C++

    - by billy
    #include <iostream> #include <iomanip> using namespace std; //Global constant variable declaration const int MaxRows = 8, MaxCols = 10, SEED = 10325; //Functions Declaration void PrintNameHeader(ostream& out); void Fill2DArray(double ary[][MaxCols]); void Print2DArray(const double ary[][MaxCols]); double GetTotal(const double ary[][MaxCols]); double GetAverage(const double ary[][MaxCols]); double GetRowTotal(const double ary[][MaxCols], int theRow); double GetColumnTotal(const double ary[][MaxCols], int theRow); double GetHighestInRow(const double ary[][MaxCols], int theRow); double GetLowestInRow(const double ary[][MaxCols], int theRow); double GetHighestInCol(const double ary[][MaxCols], int theCol); double GetLowestInCol(const double ary[][MaxCols], int theCol); double GetHighest(const double ary[][MaxCols], int& theRow, int& theCol); double GetLowest(const double ary[][MaxCols], int& theRow, int& theCol); int main() { int theRow; int theCol; PrintNameHeader(cout); cout << fixed << showpoint << setprecision(1); srand(static_cast<unsigned int>(SEED)); double ary[MaxRows][MaxCols]; cout << "The seed value for random number generator is: " << SEED << endl; cout << endl; Fill2DArray(ary); Print2DArray(ary); cout << " The Total for all the elements in this array is: " << setw(7) << GetTotal(ary) << endl; cout << "The Average of all the elements in this array is: " << setw(7) << GetAverage(ary) << endl; cout << endl; cout << "The sum of each row is:" << endl; for(int index = 0; index < MaxRows; index++) { cout << "Row " << (index + 1) << ": " << GetRowTotal(ary, theRow) << endl; } cout << "The highest and lowest of each row is: " << endl; for(int index = 0; index < MaxCols; index++) { cout << "Row " << (index + 1) << ": " << GetHighestInRow(ary, theRow) << " " << GetLowestInRow(ary, theRow) << endl; } cout << "The highest and lowest of each column is: " << endl; for(int index = 0; index < MaxCols; index++) { cout << "Col " << (index + 1) << ": " << GetHighestInCol(ary, theRow) << " " << GetLowestInCol(ary, theRow) << endl; } cout << "The highest value in all the elements in this array is: " << endl; cout << GetHighest(ary, theRow, theCol) << "[" << theRow << "]" << "[" << theCol << "]" << endl; cout << "The lowest value in all the elements in this array is: " << endl; cout << GetLowest(ary, theRow, theCol) << "[" << theRow << "]" << "[" << theCol << "]" << endl; return 0; } //Define Functions void PrintNameHeader(ostream& out) { out << "*******************************" << endl; out << "* *" << endl; out << "* C.S M10A Spring 2010 *" << endl; out << "* Programming Assignment 10 *" << endl; out << "* Due Date: Thurs. Mar. 25 *" << endl; out << "*******************************" << endl; out << endl; } void Fill2DArray(double ary[][MaxCols]) { for(int index1 = 0; index1 < MaxRows; index1++) { for(int index2= 0; index2 < MaxCols; index2++) { ary[index1][index2] = (rand()%1000)/10; } } } void Print2DArray(const double ary[][MaxCols]) { cout << " Column "; for(int index = 0; index < MaxCols; index++) { int column = index + 1; cout << " " << column << " "; } cout << endl; cout << " "; for(int index = 0; index < MaxCols; index++) { int column = index +1; cout << "----- "; } cout << endl; for(int index1 = 0; index1 < MaxRows; index1++) { cout << "Row " << (index1 + 1) << ":"; for(int index2= 0; index2 < MaxCols; index2++) { cout << setw(6) << ary[index1][index2]; } } } double GetTotal(const double ary[][MaxCols]) { double total = 0; for(int theRow = 0; theRow < MaxRows; theRow++) { total = total + GetRowTotal(ary, theRow); } return total; } double GetAverage(const double ary[][MaxCols]) { double total = 0, average = 0; total = GetTotal(ary); average = total / (MaxRows * MaxCols); return average; } double GetRowTotal(const double ary[][MaxCols], int theRow) { double sum = 0; for(int index = 0; index < MaxCols; index++) { sum = sum + ary[theRow][index]; } return sum; } double GetColumTotal(const double ary[][MaxCols], int theCol) { double sum = 0; for(int index = 0; index < theCol; index++) { sum = sum + ary[index][theCol]; } return sum; } double GetHighestInRow(const double ary[][MaxCols], int theRow) { double highest = 0; for(int index = 0; index < MaxCols; index++) { if(ary[theRow][index] > highest) highest = ary[theRow][index]; } return highest; } double GetLowestInRow(const double ary[][MaxCols], int theRow) { double lowest = 0; for(int index = 0; index < MaxCols; index++) { if(ary[theRow][index] < lowest) lowest = ary[theRow][index]; } return lowest; } double GetHighestInCol(const double ary[][MaxCols], int theCol) { double highest = 0; for(int index = 0; index < MaxRows; index++) { if(ary[index][theCol] > highest) highest = ary[index][theCol]; } return highest; } double GetLowestInCol(const double ary[][MaxCols], int theCol) { double lowest = 0; for(int index = 0; index < MaxRows; index++) { if(ary[index][theCol] < lowest) lowest = ary[index][theCol]; } return lowest; } double GetHighest(const double ary[][MaxCols], int& theRow, int& theCol) { theRow = 0; theCol = 0; double highest = ary[theRow][theCol]; for(int index = 0; index < MaxRows; index++) { for(int index1 = 0; index1 < MaxCols; index1++) { double highest = 0; if(ary[index1][theCol] > highest) { highest = ary[index][index1]; theRow = index; theCol = index1; } } } return highest; } double Getlowest(const double ary[][MaxCols], int& theRow, int& theCol) { theRow = 0; theCol = 0; double lowest = ary[theRow][theCol]; for(int index = 0; index < MaxRows; index++) { for(int index1 = 0; index1 < MaxCols; index1++) { double lowest = 0; if(ary[index1][theCol] < lowest) { lowest = ary[index][index1]; theRow = index; theCol = index1; } } } return lowest; } . 1>------ Build started: Project: teddy lab 10, Configuration: Debug Win32 ------ 1>Compiling... 1>lab 10.cpp 1>c:\users\owner\documents\visual studio 2008\projects\teddy lab 10\teddy lab 10\ lab 10.cpp(46) : warning C4700: uninitialized local variable 'theRow' used 1>c:\users\owner\documents\visual studio 2008\projects\teddy lab 10\teddy lab 10\ lab 10.cpp(62) : warning C4700: uninitialized local variable 'theCol' used 1>Linking... 1> lab 10.obj : error LNK2028: unresolved token (0A0002E0) "double __cdecl GetLowest(double const (* const)[10],int &,int &)" (?GetLowest@@$$FYANQAY09$$CBNAAH1@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) 1> lab 10.obj : error LNK2019: unresolved external symbol "double __cdecl GetLowest(double const (* const)[10],int &,int &)" (?GetLowest@@$$FYANQAY09$$CBNAAH1@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) 1>C:\Users\owner\Documents\Visual Studio 2008\Projects\ lab 10\Debug\ lab 10.exe : fatal error LNK1120: 2 unresolved externals 1>Build log was saved at "file://c:\Users\owner\Documents\Visual Studio 2008\Projects\ lab 10\teddy lab 10\Debug\BuildLog.htm" 1>teddy lab 10 - 3 error(s), 2 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Read the article

  • Very different I/O performance in C++ on Windows

    - by Mr.Gate
    Hi all, I'm a new user and my english is not so good so I hope to be clear. We're facing a performance problem using large files (1GB or more) expecially (as it seems) when you try to grow them in size. Anyway... to verify our sensations we tryed the following (on Win 7 64Bit, 4core, 8GB Ram, 32 bit code compiled with VC2008) a) Open an unexisting file. Write it from the beginning up to 1Gb in 1Mb slots. Now you have a 1Gb file. Now randomize 10000 positions within that file, seek to that position and write 50 bytes in each position, no matter what you write. Close the file and look at the results. Time to create the file is quite fast (about 0.3"), time to write 10000 times is fast all the same (about 0.03"). Very good, this is the beginnig. Now try something else... b) Open an unexisting file, seek to 1Gb-1byte and write just 1 byte. Now you have another 1Gb file. Follow the next steps exactly same way of case 'a', close the file and look at the results. Time to create the file is the faster you can imagine (about 0.00009") but write time is something you can't believe.... about 90"!!!!! b.1) Open an unexisting file, don't write any byte. Act as before, ramdomizing, seeking and writing, close the file and look at the result. Time to write is long all the same: about 90"!!!!! Ok... this is quite amazing. But there's more! c) Open again the file you crated in case 'a', don't truncate it... randomize again 10000 positions and act as before. You're fast as before, about 0,03" to write 10000 times. This sounds Ok... try another step. d) Now open the file you created in case 'b', don't truncate it... randomize again 10000 positions and act as before. You're slow again and again, but the time is reduced to... 45"!! Maybe, trying again, the time will reduce. I actually wonder why... Any Idea? The following is part of the code I used to test what I told in previuos cases (you'll have to change someting in order to have a clean compilation, I just cut & paste from some source code, sorry). The sample can read and write, in random, ordered or reverse ordered mode, but write only in random order is the clearest test. We tryed using std::fstream but also using directly CreateFile(), WriteFile() and so on the results are the same (even if std::fstream is actually a little slower). Parameters for case 'a' = -f_tempdir_\casea.dat -n10000 -t -p -w Parameters for case 'b' = -f_tempdir_\caseb.dat -n10000 -t -v -w Parameters for case 'b.1' = -f_tempdir_\caseb.dat -n10000 -t -w Parameters for case 'c' = -f_tempdir_\casea.dat -n10000 -w Parameters for case 'd' = -f_tempdir_\caseb.dat -n10000 -w Run the test (and even others) and see... // iotest.cpp : Defines the entry point for the console application. // #include <windows.h> #include <iostream> #include <set> #include <vector> #include "stdafx.h" double RealTime_Microsecs() { LARGE_INTEGER fr = {0, 0}; LARGE_INTEGER ti = {0, 0}; double time = 0.0; QueryPerformanceCounter(&ti); QueryPerformanceFrequency(&fr); time = (double) ti.QuadPart / (double) fr.QuadPart; return time; } int main(int argc, char* argv[]) { std::string sFileName ; size_t stSize, stTimes, stBytes ; int retval = 0 ; char *p = NULL ; char *pPattern = NULL ; char *pReadBuf = NULL ; try { // Default stSize = 1<<30 ; // 1Gb stTimes = 1000 ; stBytes = 50 ; bool bTruncate = false ; bool bPre = false ; bool bPreFast = false ; bool bOrdered = false ; bool bReverse = false ; bool bWriteOnly = false ; // Comsumo i parametri for(int index=1; index < argc; ++index) { if ( '-' != argv[index][0] ) throw ; switch(argv[index][1]) { case 'f': sFileName = argv[index]+2 ; break ; case 's': stSize = xw::str::strtol(argv[index]+2) ; break ; case 'n': stTimes = xw::str::strtol(argv[index]+2) ; break ; case 'b':stBytes = xw::str::strtol(argv[index]+2) ; break ; case 't': bTruncate = true ; break ; case 'p' : bPre = true, bPreFast = false ; break ; case 'v' : bPreFast = true, bPre = false ; break ; case 'o' : bOrdered = true, bReverse = false ; break ; case 'r' : bReverse = true, bOrdered = false ; break ; case 'w' : bWriteOnly = true ; break ; default: throw ; break ; } } if ( sFileName.empty() ) { std::cout << "Usage: -f<File Name> -s<File Size> -n<Number of Reads and Writes> -b<Bytes per Read and Write> -t -p -v -o -r -w" << std::endl ; std::cout << "-t truncates the file, -p pre load the file, -v pre load 'veloce', -o writes in order mode, -r write in reverse order mode, -w Write Only" << std::endl ; std::cout << "Default: 1Gb, 1000 times, 50 bytes" << std::endl ; throw ; } if ( !stSize || !stTimes || !stBytes ) { std::cout << "Invalid Parameters" << std::endl ; return -1 ; } size_t stBestSize = 0x00100000 ; std::fstream fFile ; fFile.open(sFileName.c_str(), std::ios_base::binary|std::ios_base::out|std::ios_base::in|(bTruncate?std::ios_base::trunc:0)) ; p = new char[stBestSize] ; pPattern = new char[stBytes] ; pReadBuf = new char[stBytes] ; memset(p, 0, stBestSize) ; memset(pPattern, (int)(stBytes&0x000000ff), stBytes) ; double dTime = RealTime_Microsecs() ; size_t stCopySize, stSizeToCopy = stSize ; if ( bPre ) { do { stCopySize = std::min(stSizeToCopy, stBestSize) ; fFile.write(p, stCopySize) ; stSizeToCopy -= stCopySize ; } while (stSizeToCopy) ; std::cout << "Creating time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } else if ( bPreFast ) { fFile.seekp(stSize-1) ; fFile.write(p, 1) ; std::cout << "Creating Fast time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } size_t stPos ; ::srand((unsigned int)dTime) ; double dReadTime, dWriteTime ; stCopySize = stTimes ; std::vector<size_t> inVect ; std::vector<size_t> outVect ; std::set<size_t> outSet ; std::set<size_t> inSet ; // Prepare vector and set do { stPos = (size_t)(::rand()<<16) % stSize ; outVect.push_back(stPos) ; outSet.insert(stPos) ; stPos = (size_t)(::rand()<<16) % stSize ; inVect.push_back(stPos) ; inSet.insert(stPos) ; } while (--stCopySize) ; // Write & read using vectors if ( !bReverse && !bOrdered ) { std::vector<size_t>::iterator outI, inI ; outI = outVect.begin() ; inI = inVect.begin() ; stCopySize = stTimes ; dReadTime = 0.0 ; dWriteTime = 0.0 ; do { dTime = RealTime_Microsecs() ; fFile.seekp(*outI) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++outI ; if ( !bWriteOnly ) { dTime = RealTime_Microsecs() ; fFile.seekg(*inI) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++inI ; } } while (--stCopySize) ; std::cout << "Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " (Ave: " << xw::str::itoa(dWriteTime/stTimes, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { std::cout << "Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " (Ave: " << xw::str::itoa(dReadTime/stTimes, 10, 'f') << ")" << std::endl ; } } // End // Write in order if ( bOrdered ) { std::set<size_t>::iterator i = outSet.begin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.begin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End // Write in reverse order if ( bReverse ) { std::set<size_t>::reverse_iterator i = outSet.rbegin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.rbegin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End dTime = RealTime_Microsecs() ; fFile.close() ; std::cout << "Flush/Close Time is " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; std::cout << "Program Terminated" << std::endl ; } catch(...) { std::cout << "Something wrong or wrong parameters" << std::endl ; retval = -1 ; } if ( p ) delete []p ; if ( pPattern ) delete []pPattern ; if ( pReadBuf ) delete []pReadBuf ; return retval ; }

    Read the article

  • Very different IO performance in C/C++

    - by Roberto Tirabassi
    Hi all, I'm a new user and my english is not so good so I hope to be clear. We're facing a performance problem using large files (1GB or more) expecially (as it seems) when you try to grow them in size. Anyway... to verify our sensations we tryed the following (on Win 7 64Bit, 4core, 8GB Ram, 32 bit code compiled with VC2008) a) Open an unexisting file. Write it from the beginning up to 1Gb in 1Mb slots. Now you have a 1Gb file. Now randomize 10000 positions within that file, seek to that position and write 50 bytes in each position, no matter what you write. Close the file and look at the results. Time to create the file is quite fast (about 0.3"), time to write 10000 times is fast all the same (about 0.03"). Very good, this is the beginnig. Now try something else... b) Open an unexisting file, seek to 1Gb-1byte and write just 1 byte. Now you have another 1Gb file. Follow the next steps exactly same way of case 'a', close the file and look at the results. Time to create the file is the faster you can imagine (about 0.00009") but write time is something you can't believe.... about 90"!!!!! b.1) Open an unexisting file, don't write any byte. Act as before, ramdomizing, seeking and writing, close the file and look at the result. Time to write is long all the same: about 90"!!!!! Ok... this is quite amazing. But there's more! c) Open again the file you crated in case 'a', don't truncate it... randomize again 10000 positions and act as before. You're fast as before, about 0,03" to write 10000 times. This sounds Ok... try another step. d) Now open the file you created in case 'b', don't truncate it... randomize again 10000 positions and act as before. You're slow again and again, but the time is reduced to... 45"!! Maybe, trying again, the time will reduce. I actually wonder why... Any Idea? The following is part of the code I used to test what I told in previuos cases (you'll have to change someting in order to have a clean compilation, I just cut & paste from some source code, sorry). The sample can read and write, in random, ordered or reverse ordered mode, but write only in random order is the clearest test. We tryed using std::fstream but also using directly CreateFile(), WriteFile() and so on the results are the same (even if std::fstream is actually a little slower). Parameters for case 'a' = -f_tempdir_\casea.dat -n10000 -t -p -w Parameters for case 'b' = -f_tempdir_\caseb.dat -n10000 -t -v -w Parameters for case 'b.1' = -f_tempdir_\caseb.dat -n10000 -t -w Parameters for case 'c' = -f_tempdir_\casea.dat -n10000 -w Parameters for case 'd' = -f_tempdir_\caseb.dat -n10000 -w Run the test (and even others) and see... // iotest.cpp : Defines the entry point for the console application. // #include <windows.h> #include <iostream> #include <set> #include <vector> #include "stdafx.h" double RealTime_Microsecs() { LARGE_INTEGER fr = {0, 0}; LARGE_INTEGER ti = {0, 0}; double time = 0.0; QueryPerformanceCounter(&ti); QueryPerformanceFrequency(&fr); time = (double) ti.QuadPart / (double) fr.QuadPart; return time; } int main(int argc, char* argv[]) { std::string sFileName ; size_t stSize, stTimes, stBytes ; int retval = 0 ; char *p = NULL ; char *pPattern = NULL ; char *pReadBuf = NULL ; try { // Default stSize = 1<<30 ; // 1Gb stTimes = 1000 ; stBytes = 50 ; bool bTruncate = false ; bool bPre = false ; bool bPreFast = false ; bool bOrdered = false ; bool bReverse = false ; bool bWriteOnly = false ; // Comsumo i parametri for(int index=1; index < argc; ++index) { if ( '-' != argv[index][0] ) throw ; switch(argv[index][1]) { case 'f': sFileName = argv[index]+2 ; break ; case 's': stSize = xw::str::strtol(argv[index]+2) ; break ; case 'n': stTimes = xw::str::strtol(argv[index]+2) ; break ; case 'b':stBytes = xw::str::strtol(argv[index]+2) ; break ; case 't': bTruncate = true ; break ; case 'p' : bPre = true, bPreFast = false ; break ; case 'v' : bPreFast = true, bPre = false ; break ; case 'o' : bOrdered = true, bReverse = false ; break ; case 'r' : bReverse = true, bOrdered = false ; break ; case 'w' : bWriteOnly = true ; break ; default: throw ; break ; } } if ( sFileName.empty() ) { std::cout << "Usage: -f<File Name> -s<File Size> -n<Number of Reads and Writes> -b<Bytes per Read and Write> -t -p -v -o -r -w" << std::endl ; std::cout << "-t truncates the file, -p pre load the file, -v pre load 'veloce', -o writes in order mode, -r write in reverse order mode, -w Write Only" << std::endl ; std::cout << "Default: 1Gb, 1000 times, 50 bytes" << std::endl ; throw ; } if ( !stSize || !stTimes || !stBytes ) { std::cout << "Invalid Parameters" << std::endl ; return -1 ; } size_t stBestSize = 0x00100000 ; std::fstream fFile ; fFile.open(sFileName.c_str(), std::ios_base::binary|std::ios_base::out|std::ios_base::in|(bTruncate?std::ios_base::trunc:0)) ; p = new char[stBestSize] ; pPattern = new char[stBytes] ; pReadBuf = new char[stBytes] ; memset(p, 0, stBestSize) ; memset(pPattern, (int)(stBytes&0x000000ff), stBytes) ; double dTime = RealTime_Microsecs() ; size_t stCopySize, stSizeToCopy = stSize ; if ( bPre ) { do { stCopySize = std::min(stSizeToCopy, stBestSize) ; fFile.write(p, stCopySize) ; stSizeToCopy -= stCopySize ; } while (stSizeToCopy) ; std::cout << "Creating time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } else if ( bPreFast ) { fFile.seekp(stSize-1) ; fFile.write(p, 1) ; std::cout << "Creating Fast time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } size_t stPos ; ::srand((unsigned int)dTime) ; double dReadTime, dWriteTime ; stCopySize = stTimes ; std::vector<size_t> inVect ; std::vector<size_t> outVect ; std::set<size_t> outSet ; std::set<size_t> inSet ; // Prepare vector and set do { stPos = (size_t)(::rand()<<16) % stSize ; outVect.push_back(stPos) ; outSet.insert(stPos) ; stPos = (size_t)(::rand()<<16) % stSize ; inVect.push_back(stPos) ; inSet.insert(stPos) ; } while (--stCopySize) ; // Write & read using vectors if ( !bReverse && !bOrdered ) { std::vector<size_t>::iterator outI, inI ; outI = outVect.begin() ; inI = inVect.begin() ; stCopySize = stTimes ; dReadTime = 0.0 ; dWriteTime = 0.0 ; do { dTime = RealTime_Microsecs() ; fFile.seekp(*outI) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++outI ; if ( !bWriteOnly ) { dTime = RealTime_Microsecs() ; fFile.seekg(*inI) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++inI ; } } while (--stCopySize) ; std::cout << "Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " (Ave: " << xw::str::itoa(dWriteTime/stTimes, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { std::cout << "Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " (Ave: " << xw::str::itoa(dReadTime/stTimes, 10, 'f') << ")" << std::endl ; } } // End // Write in order if ( bOrdered ) { std::set<size_t>::iterator i = outSet.begin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.begin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End // Write in reverse order if ( bReverse ) { std::set<size_t>::reverse_iterator i = outSet.rbegin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.rbegin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End dTime = RealTime_Microsecs() ; fFile.close() ; std::cout << "Flush/Close Time is " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; std::cout << "Program Terminated" << std::endl ; } catch(...) { std::cout << "Something wrong or wrong parameters" << std::endl ; retval = -1 ; } if ( p ) delete []p ; if ( pPattern ) delete []pPattern ; if ( pReadBuf ) delete []pReadBuf ; return retval ; }

    Read the article

  • Conceal packet loss in PCM stream

    - by ZeroDefect
    I am looking to use 'Packet Loss Concealment' to conceal lost PCM frames in an audio stream. Unfortunately, I cannot find a library that is accessible without all the licensing restrictions and code bloat (...up for some suggestions though). I have located some GPL code written by Steve Underwood for the Asterisk project which implements PLC. There are several limitations; although, as Steve suggests in his code, his algorithm can be applied to different streams with a bit of work. Currently, the code works with 8kHz 16-bit signed mono streams. Variations of the code can be found through a simple search of Google Code Search. My hope is that I can adapt the code to work with other streams. Initially, the goal is to adjust the algorithm for 8+ kHz, 16-bit signed, multichannel audio (all in a C++ environment). Eventually, I'm looking to make the code available under the GPL license in hopes that it could be of benefit to others... Attached is the code below with my efforts. The code includes a main function that will "drop" a number of frames with a given probability. Unfortunately, the code does not quite work as expected. I'm receiving EXC_BAD_ACCESS when running in gdb, but I don't get a trace from gdb when using 'bt' command. Clearly, I'm trampimg on memory some where but not sure exactly where. When I comment out the *amdf_pitch* function, the code runs without crashing... int main (int argc, char *argv[]) { std::ifstream fin("C:\\cc32kHz.pcm"); if(!fin.is_open()) { std::cout << "Failed to open input file" << std::endl; return 1; } std::ofstream fout_repaired("C:\\cc32kHz_repaired.pcm"); if(!fout_repaired.is_open()) { std::cout << "Failed to open output repaired file" << std::endl; return 1; } std::ofstream fout_lossy("C:\\cc32kHz_lossy.pcm"); if(!fout_lossy.is_open()) { std::cout << "Failed to open output repaired file" << std::endl; return 1; } audio::PcmConcealer Concealer; Concealer.Init(1, 16, 32000); //Generate random numbers; srand( time(NULL) ); int value = 0; int probability = 5; while(!fin.eof()) { char arr[2]; fin.read(arr, 2); //Generate's random number; value = rand() % 100 + 1; if(value <= probability) { char blank[2] = {0x00, 0x00}; fout_lossy.write(blank, 2); //Fill in data; Concealer.Fill((int16_t *)blank, 1); fout_repaired.write(blank, 2); } else { //Write data to file; fout_repaired.write(arr, 2); fout_lossy.write(arr, 2); Concealer.Receive((int16_t *)arr, 1); } } fin.close(); fout_repaired.close(); fout_lossy.close(); return 0; } PcmConcealer.hpp /* * Code adapted from Steve Underwood of the Asterisk Project. This code inherits * the same licensing restrictions as the Asterisk Project. */ #ifndef __PCMCONCEALER_HPP__ #define __PCMCONCEALER_HPP__ /** 1. What does it do? The packet loss concealment module provides a suitable synthetic fill-in signal, to minimise the audible effect of lost packets in VoIP applications. It is not tied to any particular codec, and could be used with almost any codec which does not specify its own procedure for packet loss concealment. Where a codec specific concealment procedure exists, the algorithm is usually built around knowledge of the characteristics of the particular codec. It will, therefore, generally give better results for that particular codec than this generic concealer will. 2. How does it work? While good packets are being received, the plc_rx() routine keeps a record of the trailing section of the known speech signal. If a packet is missed, plc_fillin() is called to produce a synthetic replacement for the real speech signal. The average mean difference function (AMDF) is applied to the last known good signal, to determine its effective pitch. Based on this, the last pitch period of signal is saved. Essentially, this cycle of speech will be repeated over and over until the real speech resumes. However, several refinements are needed to obtain smooth pleasant sounding results. - The two ends of the stored cycle of speech will not always fit together smoothly. This can cause roughness, or even clicks, at the joins between cycles. To soften this, the 1/4 pitch period of real speech preceeding the cycle to be repeated is blended with the last 1/4 pitch period of the cycle to be repeated, using an overlap-add (OLA) technique (i.e. in total, the last 5/4 pitch periods of real speech are used). - The start of the synthetic speech will not always fit together smoothly with the tail of real speech passed on before the erasure was identified. Ideally, we would like to modify the last 1/4 pitch period of the real speech, to blend it into the synthetic speech. However, it is too late for that. We could have delayed the real speech a little, but that would require more buffer manipulation, and hurt the efficiency of the no-lost-packets case (which we hope is the dominant case). Instead we use a degenerate form of OLA to modify the start of the synthetic data. The last 1/4 pitch period of real speech is time reversed, and OLA is used to blend it with the first 1/4 pitch period of synthetic speech. The result seems quite acceptable. - As we progress into the erasure, the chances of the synthetic signal being anything like correct steadily fall. Therefore, the volume of the synthesized signal is made to decay linearly, such that after 50ms of missing audio it is reduced to silence. - When real speech resumes, an extra 1/4 pitch period of sythetic speech is blended with the start of the real speech. If the erasure is small, this smoothes the transition. If the erasure is long, and the synthetic signal has faded to zero, the blending softens the start up of the real signal, avoiding a kind of "click" or "pop" effect that might occur with a sudden onset. 3. How do I use it? Before audio is processed, call plc_init() to create an instance of the packet loss concealer. For each received audio packet that is acceptable (i.e. not including those being dropped for being too late) call plc_rx() to record the content of the packet. Note this may modify the packet a little after a period of packet loss, to blend real synthetic data smoothly. When a real packet is not available in time, call plc_fillin() to create a sythetic substitute. That's it! */ /*! Minimum allowed pitch (66 Hz) */ #define PLC_PITCH_MIN(SAMPLE_RATE) ((double)(SAMPLE_RATE) / 66.6) /*! Maximum allowed pitch (200 Hz) */ #define PLC_PITCH_MAX(SAMPLE_RATE) ((SAMPLE_RATE) / 200) /*! Maximum pitch OLA window */ //#define PLC_PITCH_OVERLAP_MAX(SAMPLE_RATE) ((PLC_PITCH_MIN(SAMPLE_RATE)) >> 2) /*! The length over which the AMDF function looks for similarity (20 ms) */ #define CORRELATION_SPAN(SAMPLE_RATE) ((20 * (SAMPLE_RATE)) / 1000) /*! History buffer length. The buffer must also be at leat 1.25 times PLC_PITCH_MIN, but that is much smaller than the buffer needs to be for the pitch assessment. */ //#define PLC_HISTORY_LEN(SAMPLE_RATE) ((CORRELATION_SPAN(SAMPLE_RATE)) + (PLC_PITCH_MIN(SAMPLE_RATE))) namespace audio { typedef struct { /*! Consecutive erased samples */ int missing_samples; /*! Current offset into pitch period */ int pitch_offset; /*! Pitch estimate */ int pitch; /*! Buffer for a cycle of speech */ float *pitchbuf;//[PLC_PITCH_MIN]; /*! History buffer */ short *history;//[PLC_HISTORY_LEN]; /*! Current pointer into the history buffer */ int buf_ptr; } plc_state_t; class PcmConcealer { public: PcmConcealer(); ~PcmConcealer(); void Init(int channels, int bit_depth, int sample_rate); //Process a block of received audio samples. int Receive(short amp[], int frames); //Fill-in a block of missing audio samples. int Fill(short amp[], int frames); void Destroy(); private: int amdf_pitch(int min_pitch, int max_pitch, short amp[], int channel_index, int frames); void save_history(plc_state_t *s, short *buf, int channel_index, int frames); void normalise_history(plc_state_t *s); /** Holds the states of each of the channels **/ std::vector< plc_state_t * > ChannelStates; int plc_pitch_min; int plc_pitch_max; int plc_pitch_overlap_max; int correlation_span; int plc_history_len; int channel_count; int sample_rate; bool Initialized; }; } #endif PcmConcealer.cpp /* * Code adapted from Steve Underwood of the Asterisk Project. This code inherits * the same licensing restrictions as the Asterisk Project. */ #include "audio/PcmConcealer.hpp" /* We do a straight line fade to zero volume in 50ms when we are filling in for missing data. */ #define ATTENUATION_INCREMENT 0.0025 /* Attenuation per sample */ #if !defined(INT16_MAX) #define INT16_MAX (32767) #define INT16_MIN (-32767-1) #endif #ifdef WIN32 inline double rint(double x) { return floor(x + 0.5); } #endif inline short fsaturate(double damp) { if (damp > 32767.0) return INT16_MAX; if (damp < -32768.0) return INT16_MIN; return (short)rint(damp); } namespace audio { PcmConcealer::PcmConcealer() : Initialized(false) { } PcmConcealer::~PcmConcealer() { Destroy(); } void PcmConcealer::Init(int channels, int bit_depth, int sample_rate) { if(Initialized) return; if(channels <= 0 || bit_depth != 16) return; Initialized = true; channel_count = channels; this->sample_rate = sample_rate; ////////////// double min = PLC_PITCH_MIN(sample_rate); int imin = (int)min; double max = PLC_PITCH_MAX(sample_rate); int imax = (int)max; plc_pitch_min = imin; plc_pitch_max = imax; plc_pitch_overlap_max = (plc_pitch_min >> 2); correlation_span = CORRELATION_SPAN(sample_rate); plc_history_len = correlation_span + plc_pitch_min; ////////////// for(int i = 0; i < channel_count; i ++) { plc_state_t *t = new plc_state_t; memset(t, 0, sizeof(plc_state_t)); t->pitchbuf = new float[plc_pitch_min]; t->history = new short[plc_history_len]; ChannelStates.push_back(t); } } void PcmConcealer::Destroy() { if(!Initialized) return; while(ChannelStates.size()) { plc_state_t *s = ChannelStates.at(0); if(s) { if(s->history) delete s->history; if(s->pitchbuf) delete s->pitchbuf; memset(s, 0, sizeof(plc_state_t)); delete s; } ChannelStates.erase(ChannelStates.begin()); } ChannelStates.clear(); Initialized = false; } //Process a block of received audio samples. int PcmConcealer::Receive(short amp[], int frames) { if(!Initialized) return 0; int j = 0; for(int k = 0; k < ChannelStates.size(); k++) { int i; int overlap_len; int pitch_overlap; float old_step; float new_step; float old_weight; float new_weight; float gain; plc_state_t *s = ChannelStates.at(k); if (s->missing_samples) { /* Although we have a real signal, we need to smooth it to fit well with the synthetic signal we used for the previous block */ /* The start of the real data is overlapped with the next 1/4 cycle of the synthetic data. */ pitch_overlap = s->pitch >> 2; if (pitch_overlap > frames) pitch_overlap = frames; gain = 1.0 - s->missing_samples * ATTENUATION_INCREMENT; if (gain < 0.0) gain = 0.0; new_step = 1.0/pitch_overlap; old_step = new_step*gain; new_weight = new_step; old_weight = (1.0 - new_step)*gain; for (i = 0; i < pitch_overlap; i++) { int index = (i * channel_count) + j; amp[index] = fsaturate(old_weight * s->pitchbuf[s->pitch_offset] + new_weight * amp[index]); if (++s->pitch_offset >= s->pitch) s->pitch_offset = 0; new_weight += new_step; old_weight -= old_step; if (old_weight < 0.0) old_weight = 0.0; } s->missing_samples = 0; } save_history(s, amp, j, frames); j++; } return frames; } //Fill-in a block of missing audio samples. int PcmConcealer::Fill(short amp[], int frames) { if(!Initialized) return 0; int j =0; for(int k = 0; k < ChannelStates.size(); k++) { short *tmp = new short[plc_pitch_overlap_max]; int i; int pitch_overlap; float old_step; float new_step; float old_weight; float new_weight; float gain; short *orig_amp; int orig_len; orig_amp = amp; orig_len = frames; plc_state_t *s = ChannelStates.at(k); if (s->missing_samples == 0) { // As the gap in real speech starts we need to assess the last known pitch, //and prepare the synthetic data we will use for fill-in normalise_history(s); s->pitch = amdf_pitch(plc_pitch_min, plc_pitch_max, s->history + plc_history_len - correlation_span - plc_pitch_min, j, correlation_span); // We overlap a 1/4 wavelength pitch_overlap = s->pitch >> 2; // Cook up a single cycle of pitch, using a single of the real signal with 1/4 //cycle OLA'ed to make the ends join up nicely // The first 3/4 of the cycle is a simple copy for (i = 0; i < s->pitch - pitch_overlap; i++) s->pitchbuf[i] = s->history[plc_history_len - s->pitch + i]; // The last 1/4 of the cycle is overlapped with the end of the previous cycle new_step = 1.0/pitch_overlap; new_weight = new_step; for ( ; i < s->pitch; i++) { s->pitchbuf[i] = s->history[plc_history_len - s->pitch + i]*(1.0 - new_weight) + s->history[plc_history_len - 2*s->pitch + i]*new_weight; new_weight += new_step; } // We should now be ready to fill in the gap with repeated, decaying cycles // of what is in pitchbuf // We need to OLA the first 1/4 wavelength of the synthetic data, to smooth // it into the previous real data. To avoid the need to introduce a delay // in the stream, reverse the last 1/4 wavelength, and OLA with that. gain = 1.0; new_step = 1.0/pitch_overlap; old_step = new_step; new_weight = new_step; old_weight = 1.0 - new_step; for (i = 0; i < pitch_overlap; i++) { int index = (i * channel_count) + j; amp[index] = fsaturate(old_weight * s->history[plc_history_len - 1 - i] + new_weight * s->pitchbuf[i]); new_weight += new_step; old_weight -= old_step; if (old_weight < 0.0) old_weight = 0.0; } s->pitch_offset = i; } else { gain = 1.0 - s->missing_samples*ATTENUATION_INCREMENT; i = 0; } for ( ; gain > 0.0 && i < frames; i++) { int index = (i * channel_count) + j; amp[index] = s->pitchbuf[s->pitch_offset]*gain; gain -= ATTENUATION_INCREMENT; if (++s->pitch_offset >= s->pitch) s->pitch_offset = 0; } for ( ; i < frames; i++) { int index = (i * channel_count) + j; amp[i] = 0; } s->missing_samples += orig_len; save_history(s, amp, j, frames); delete [] tmp; j++; } return frames; } void PcmConcealer::save_history(plc_state_t *s, short *buf, int channel_index, int frames) { if (frames >= plc_history_len) { /* Just keep the last part of the new data, starting at the beginning of the buffer */ //memcpy(s->history, buf + len - plc_history_len, sizeof(short)*plc_history_len); int frames_to_copy = plc_history_len; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * (i + frames - plc_history_len)) + channel_index; s->history[i] = buf[index]; } s->buf_ptr = 0; return; } if (s->buf_ptr + frames > plc_history_len) { /* Wraps around - must break into two sections */ //memcpy(s->history + s->buf_ptr, buf, sizeof(short)*(plc_history_len - s->buf_ptr)); short *hist_ptr = s->history + s->buf_ptr; int frames_to_copy = plc_history_len - s->buf_ptr; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * i) + channel_index; hist_ptr[i] = buf[index]; } frames -= (plc_history_len - s->buf_ptr); //memcpy(s->history, buf + (plc_history_len - s->buf_ptr), sizeof(short)*len); frames_to_copy = frames; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * (i + (plc_history_len - s->buf_ptr))) + channel_index; s->history[i] = buf[index]; } s->buf_ptr = frames; return; } /* Can use just one section */ //memcpy(s->history + s->buf_ptr, buf, sizeof(short)*len); short *hist_ptr = s->history + s->buf_ptr; int frames_to_copy = frames; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * i) + channel_index; hist_ptr[i] = buf[index]; } s->buf_ptr += frames; } void PcmConcealer::normalise_history(plc_state_t *s) { short *tmp = new short[plc_history_len]; if (s->buf_ptr == 0) return; memcpy(tmp, s->history, sizeof(short)*s->buf_ptr); memcpy(s->history, s->history + s->buf_ptr, sizeof(short)*(plc_history_len - s->buf_ptr)); memcpy(s->history + plc_history_len - s->buf_ptr, tmp, sizeof(short)*s->buf_ptr); s->buf_ptr = 0; delete [] tmp; } int PcmConcealer::amdf_pitch(int min_pitch, int max_pitch, short amp[], int channel_index, int frames) { int i; int j; int acc; int min_acc; int pitch; pitch = min_pitch; min_acc = INT_MAX; for (i = max_pitch; i <= min_pitch; i++) { acc = 0; for (j = 0; j < frames; j++) { int index1 = (channel_count * (i+j)) + channel_index; int index2 = (channel_count * j) + channel_index; //std::cout << "Index 1: " << index1 << ", Index 2: " << index2 << std::endl; acc += abs(amp[index1] - amp[index2]); } if (acc < min_acc) { min_acc = acc; pitch = i; } } std::cout << "Pitch: " << pitch << std::endl; return pitch; } } P.S. - I must confess that digital audio is not my forte...

    Read the article

  • Having an issue with overwriting an element of a file correctly (numeric)

    - by IngeniousHax
    This is an ATM style program, but currently it doesn't do exactly what I need it to do... I need to get the current balance, and when money is transferred from either checking or savings, it should add it to checking and subtract it from savings. which is does, but not correctly... Input example -=[ Funds Transfer ]=- -=[ Savings to Checking ]=- Account Name: nomadic Amount to transfer: $400 New Balance in Checking: $900 // original was 500 New Balance in Savings: $7.7068e+012 // this should now be 1100... Here is my code, it's a lot of code, but there are no errors, so throwing it into an IDE and compiling should be fairly quick for whoever would like to help. mainBankClass.h mainBankClass.h #ifndef MAINBANKCLASS_H #define MAINBANKCLASS_H #include <iostream> #include <fstream> #include <string> using namespace std; class Banking { protected: string checkAcctName, saveAcctName; // Name on the account int acctNumber[13]; // Account number float acctBalance, initSaveDeposit, initCheckDeposit, depAmt; // amount in account, and amount to deposit public: char getBalanceChoice(); // Get name on account for displaying relevant information char newAccountMenu(); // Create a new account and assign it a random account number void invalid(char *); // If an invalid option is chosen char menu(); // Print the main menu for the user. virtual float deposit(){ return 0; } // virtual function for deposits // virtual float withdrawal() = 0; // Virtual function for withdrawals void fatal(char *); // Handles fatal errors. Banking(); }; class Checking : public Banking { public: friend ostream operator<<(ostream &, Checking &); friend istream operator>>(istream &, Checking &); Checking operator <= (const Checking &) const; void newCheckingAccount(); void viewCheckingBalance(); void transferFromSaving(); float deposit() { return (acctBalance += depAmt); } }; class Saving : public Banking { public: friend ostream &operator<<(ostream &, Saving &); friend istream &operator>>(istream &, Saving &); Saving operator <= (const Saving &) const; void newSavingAccount(); void viewSavingBalance(); void transferFromChecking(); float deposit() { return (acctBalance += depAmt); } }; class checkAndSave : public Banking { public: void newCheckAndSave(); void viewBothBalances(); }; #endif bankAccount.cpp #include <iostream> #include <sstream> #include <string> #include <iomanip> #include <fstream> #include <time.h> #include "MainBankClass.h" /*****************************\ | BANKING CONSTRUCTOR | \*****************************/ Banking::Banking() { string acctName; // Name on the account acctNumber[13] = 0; // Account number acctBalance = 0; initCheckDeposit = 0; initSaveDeposit = 0; depAmt = 0; }; /********************************\ | The following code is to print the menu | | and recieve the users choice on what | | they want to do with the ATM | \********************************/ char Banking::menu() { char choice; system("cls"); cout << "\t\t -=[ Main Menu ]=- \n\n" << "\tA) Create New Account\n" << "\tB) View Account Balance\n" << "\tC) Transfer Funds From Checking To Savings\n" << "\tD) Transfer Funds From Savings To Checking\n" << "\tE) Exit\n" << "\n\n\tSelection: "; cin >> choice; cin.ignore(); choice = toupper(choice); while(!isalpha(choice)) { invalid("[!!] Invalid selection.\n[!!] Choose a valid option: "); cin >> choice; cin.ignore(); } return choice; } /*********************\ | Will read in account choic | | and display it for the user | \*********************/ char Banking::getBalanceChoice() { char choice; fstream saveFile("saving.dat", ios::in | ios::beg); system("cls"); cout << "\t\t -=[ View Account Balance ]=-\n\n"; cout << "A) View Checking Account\n" << "B) View Saving Account\n" << "C) View Checking \\ Saving Account\n" << endl; cout << "Choice: "; cin >> choice; choice = toupper(choice); if(!isalpha(choice)) fatal(" [!!] Invalid Choice"); return choice; } /***************************\ | Incase an invalid decision to made | | this throws the error message sent | | to it by the calling area | \***************************/ void Banking::invalid(char *msg) { cout << msg; } /*************************\ | Used if files can not be opened | | and exits with code 251: | | miscommunication with server | \*************************/ void Banking::fatal(char *msg) { cout << msg; exit(1); } /***************************\ | Create an account, either checking | | or savings, or both. | | Must should create a randomly | | generated account number that will | | correspond with each account. | \***************************/ /************************\ NOTE:: WILL BE UPDATED TO CONTAIN A PIN FOR ACCOUNT VERIFICATION *************************/ char Banking::newAccountMenu() { srand(time(NULL)); // Seed random generator with time initialized to NULL char acctChoice; // choice for the account type ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts system("cls"); cout << "\t\t-=[ New Account Creation ]=-\n\n" << endl; cout << "A) Checking Account\n" << "B) Savings Account\n" << "C) Checking and Saving Account\n" << endl; cout << "New account type: "; cin >> acctChoice; acctChoice = toupper(acctChoice); cin.clear(); cin.sync(); return acctChoice; } /********************************************************************* ********************************************************************** CHECKING ACCOUNT CODE ********************************************************************** **********************************************************************/ // New Checking Account Creation void Checking::newCheckingAccount() { system("cls"); ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts cout << "\t\t -=[ New Checking Account ]=- \n" << endl; cout << "Name of the main holder to be on the account: "; getline(cin, checkAcctName); cout << "Initial deposit amount: $"; cin >> initCheckDeposit; if(initCheckDeposit <= 0) { while(initCheckDeposit <= 0) { invalid("[!!] 0 or negative amount entered\nMaybe a typo?\n"); cout << "Deposit Amount: $"; cin >> initCheckDeposit; } } if(!checkFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); checkFile << checkAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); // Build a random checking account number checkFile << acctNumber[j]; } checkFile << endl; checkFile << initCheckDeposit << endl; checkFile.close(); } void Checking::viewCheckingBalance() { fstream checkFile("checking.dat", ios::in | ios::beg); string name; int i = 0; double balance = 0; system("cls"); cout << "\t\t -=[ View Checking Account ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } if(name == checkAcctName) { system("cls"); cout << "\t\t -=[ Checking Account Balance ]=-\n\n" << endl; cout << "Account Name: " << checkAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; checkFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } else fatal("[!!] Invalid Account\n"); checkFile.close(); getchar(); } void Checking::transferFromSaving() // Move funds FROM SAVINGS to CHECKING { system("cls"); string name; long checkPos = 0; long savePos = 0; float savingBalance = 0; string saveAcctName; int i = 0; cin.clear(); fstream saveFile("saving.dat", ios::in | ios::out | ios::beg); fstream checkFile("checking.dat", ios::in | ios::out | ios::beg); cout << "\t\t-=[ Funds Transfer ]=-" << endl; cout << "\t\t-=[ Savings to Checking ]=-" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i = 0; i++; getline(saveFile, saveAcctName); } if(name == checkAcctName) { cout << "Amount to transfer: $"; float depAmt = 0; cin >> depAmt; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; } checkPos = checkFile.tellg(); // if the file is found, get the position of acctBalance and store it in ptrPos checkFile.seekg(checkPos); checkFile >> acctBalance; savePos = saveFile.tellg(); saveFile.seekg(savePos); // sending the cursor in the file to ptrPos + 1 to ignore white space saveFile >> savingBalance; if(savingBalance < depAmt) // if checking account does not have enough funds, exit with NSF code fatal("[!!] Insufficient Funds\n"); acctBalance += depAmt; // can be changed to an overloaded operator savingBalance -= depAmt; // can be changed to an overloaded operator checkFile.seekp(checkPos); // go to position previously set above checkFile << acctBalance; // write new balance to checkFile saveFile.seekp(savePos); // same thing as above comment saveFile << savingBalance; // write new balance to saveFile cout << "New Balance in Checking: $" << acctBalance << endl; // will be removed later cout << "New Balance in Savings: $" << savingBalance << endl; // will be removed later aswell } else fatal("[!!] Linked accounts do not exist.\n"); // if account is not found saveFile.close(); checkFile.close(); } /******************************************************** ******************************************************** SAVING ACCOUNT CODE ********************************************************* *********************************************************/ void Saving::newSavingAccount() { system("cls"); ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts cout << "\t\t -=[ New Savings Account ]=- \n" << endl; cout << "Name of the main holder to be on account: "; getline(cin, saveAcctName); cout << "Deposit Amount: $"; cin >> initSaveDeposit; if(initSaveDeposit <= 0) { while(initSaveDeposit <= 0) { invalid("[!!]0 or negative value entered.\nPerhaps a typo?\n"); cout << "Deposit amount: $"; cin >> initSaveDeposit; } } if(!saveFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); saveFile << saveAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); saveFile << acctNumber[j]; } saveFile << endl; saveFile << initSaveDeposit << endl; saveFile.close(); } void Saving::viewSavingBalance() { string name; int i = 0; fstream saveFile("saving.dat", ios::in | ios::beg); cin.clear(); system("cls"); cout << "\t\t -=[ View Saving Account ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i++; getline(saveFile, saveAcctName); } if(name == saveAcctName) { system("cls"); cout << "\t\t -=[ Saving Account Balance ]=-\n\n" << endl; cout << "Account Name: " << saveAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; saveFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } else fatal("[!!] Invalid Account\n"); saveFile.close(); getchar(); } // NEED TO WORK ON THIS PORTION TOMORROW AND MONDAY, ADD OVERLOADED OPS FOR ASSIGNMENT!!!!!!! void Saving::transferFromChecking() // This is to take money FROM checking and ADD IT TO SAVING { system("cls"); string name; long savePos = 0; long checkPos = 0; float checkingBalance = 0; string checkAcctName; int i = 0; cin.clear(); fstream saveFile("saving.dat", ios::in | ios::out | ios::beg); fstream checkFile("checking.dat", ios::in | ios::out | ios::beg); cout << "\t\t-=[ Funds Transfer ]=-" << endl; cout << "\t\t-=[ Checking to Savings ]=-" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(saveFile, saveAcctName); getline(checkFile, checkAcctName); while(name != saveAcctName && name != checkAcctName && !saveFile.fail() && !checkFile.fail()) { i++; getline(saveFile, saveAcctName); getline(checkFile, checkAcctName); } if(name == saveAcctName) { cout << "Amount to transfer: $"; float depAmt = 0; cin >> depAmt; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; } savePos = saveFile.tellg(); // if the file is found, get the position of acctBalance and store it in ptrPos saveFile.seekg(savePos); saveFile >> acctBalance; checkPos = checkFile.tellg(); checkFile.seekg(checkPos); // if file is found, store current position of the cursor to ptrPos checkFile >> checkingBalance; if(checkingBalance < depAmt) // if checking account does not have enough funds, exit with NSF code fatal("[!!] Insufficient Funds\n"); // Can also place overloaded op here acctBalance += depAmt; // can be changed to an overloaded operator checkingBalance -= depAmt; // can be changed to an overloaded operator saveFile.seekg(savePos); // go to position previously set above saveFile << acctBalance; // write new balance to saveFile checkFile.seekg(checkPos); // same thing as above comment checkFile << checkingBalance; // write new balance to checkFile cout << "New Balance in Savings: $" << acctBalance << endl; // will be removed later cout << "New Balance in Checking: $" << checkingBalance << endl; // will be removed later aswell } else fatal("[!!] Linked accounts do not exist.\n"); // if account is not found saveFile.close(); checkFile.close(); } /******************************************** ******************************************** CHECK AND SAVE CODE ********************************************** **********************************************/ void checkAndSave::newCheckAndSave() { system("cls"); ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts cout << "\t -=[ New Checking & Saving Account ]=- \n" << endl; cout << "Name of the main holder to be on account: "; getline(cin, checkAcctName); saveAcctName = checkAcctName; cout << "Checking Deposit Amount: $"; cin >> initCheckDeposit; if(initCheckDeposit <= 0) { while(initCheckDeposit <= 0) { invalid("[!!] 0 or negative amount entered\nMaybe a typo?\n"); cout << "Deposit Amount: $"; cin >> initCheckDeposit; } } cout << "Saving Deposit Amount: $"; cin >> initSaveDeposit; if(initSaveDeposit <= 0) { while(initSaveDeposit <= 0) { invalid("[!!]0 or negative value entered.\nPerhaps a typo?\n"); cout << "Deposit amount: $"; cin >> initSaveDeposit; } } if(!saveFile || !checkFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); checkFile << checkAcctName << endl; saveFile << saveAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); checkFile << acctNumber[j]; saveFile << acctNumber[j]; } saveFile << endl; saveFile << initSaveDeposit << endl; checkFile << endl; checkFile << initCheckDeposit << endl; checkFile.close(); saveFile.close(); } void checkAndSave::viewBothBalances() { string name; int i = 0; fstream checkFile("checking.dat", ios::in | ios::beg); fstream saveFile("saving.dat", ios::in | ios::beg); system("cls"); cin.clear(); cout << "\t-=[ Saving & Checking Account Balance ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); saveAcctName = name; /**********************\ | Checking Account portion | | of the checking & savings | | overview | \**********************/ while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } system("cls"); if(name != checkAcctName && checkFile.fail()) invalid("\n\n[!!] No Checking Account Found\n"); cout << "\t\t -=[ Checking Account ]=- \n" << endl; cout << "Account Name: " << checkAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; checkFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; /*********************\ | Saving Account portion | | of the checking & saving | | overview | \*********************/ getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i++; getline(saveFile, saveAcctName); } if(name != saveAcctName && saveFile.fail()) invalid("\n\n[!!] No Saving Account Found\n"); if(name == saveAcctName) { cout << "\t\t -=[ Saving Account ]=-\n\n" << endl; cout << "Account Name: " << saveAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; saveFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } if(name != saveAcctName && name != checkAcctName && saveFile.fail() && checkFile.fail()) fatal("[!!] No Accounts Have Been Found\n"); checkFile.close(); saveFile.close(); getchar(); } Main.cpp #include <iostream> #include "MainBankClass.h" using namespace std; int main() { Banking bank; Checking check; Saving save; checkAndSave CanS; char choice; choice = bank.menu(); // Call the banking menu switch(choice) { case 'A': choice = bank.newAccountMenu(); switch(choice) { case 'A': check.newCheckingAccount(); break; case 'B': save.newSavingAccount(); break; case 'C': CanS.newCheckAndSave(); break; default: system("cls"); bank.fatal("[!!] Invalid option\n"); break; } break; /***********************************************/ case 'B': choice = bank.getBalanceChoice(); switch(choice) { case 'A': check.viewCheckingBalance(); break; case 'B': save.viewSavingBalance(); break; case 'C': CanS.viewBothBalances(); break; default: bank.fatal("Invalid decision\n"); break; } /*************************************************/ break; case 'C': check.transferFromSaving(); break; case 'D': save.transferFromChecking(); break; case 'E': system("cls"); cout << "\t\t-=[ Disconnecting From System ]=-\n"; cout << "\t\t\t Thank you" << endl; cout << "\t\t Have a nice day!" << endl; exit(1); break; default: system("cls"); bank.invalid("\n\n\n\n\t\t [+] Invalid Selection \n\t\t[+] Disconnecting From System \n\t\t\tGood-bye \n\n\n\n\n\n\n"); exit(1); break; } return 0; }

    Read the article

< Previous Page | 1 2 3 4