NaN Quantitavity – Quant Trading, Statistical Learning, Coding and Brainstorming

2013-04-21, 4:57 PM, Sunday

Normal Distribution Calculations

Filed under: C++ — weekendsunny @ 4:57 PM
// Cumulative N(0,1) and Inverse Cumulative N(0,1)
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

double f(double);							// N(0,1) density
double N(double);							// N(0,1) cdf
double Ni(double);							// N(0,1) inverse cdf
double Boole(double, double, int);			// Boole's numerical integration
double Bisection(double, double, double);	// Bisection algorithm

int main()
{
	cout << "A few cumulative N(0,1) probabilities" << endl;
	cout << "N(1.96)  = " << N(1.96)  << endl;
	cout << "N(2.33)  = " << N(2.33)  << endl;
	cout << "N(-1.96) = " << N(-1.96)  << endl;
	cout << "N(-2.33) = " << N(-2.33)  << endl;
	cout << endl;
	cout << "A few inverse cumulative N(0,1) probabilities" << endl;
	cout << "Ni(0.99)  = " << Ni(0.99)  << endl;
	cout << "Ni(0.975) = " << Ni(0.975) << endl;
	cout << "Ni(0.05)  = " << Ni(0.05)  << endl;
	return 0;
}

// N(0,1) density
double f(double x) {
	double pi =  4.0*atan(1.0);
	return exp(-x*x*0.5)/sqrt(2*pi);
}

// N(0,1) cdf by Boole's Rule
double N(double x) {
	return Boole(-10.0, x, 240);
}

// Boole's Rule
double Boole(double StartPoint, double EndPoint, int n) {
	vector<double> X(n+1, 0.0);
	vector<double> Y(n+1, 0.0);
	double delta_x = (EndPoint - StartPoint)/double(n);
	for (int i=0; i<=n; i++) {
		X[i] = StartPoint + i*delta_x;
		Y[i] = f(X[i]);
	}
	double sum = 0;
	for (int t=0; t<=(n-1)/4; t++) {
		int ind = 4*t;
		sum += (1/45.0)*(14*Y[ind] + 64*Y[ind+1] + 24*Y[ind+2] + 64*Y[ind+3] + 14*Y[ind+4])*delta_x;
	}
	return sum;
}

// Inverse cumulative N(0,1) by bisection algorithm
double Ni(double prob) {
	return Bisection(prob, -10.0, 10.0);
}

// Bisection Algorithm
double Bisection(double prob, double a, double b)
{
	const int MaxIter = 500;
	double Tol = 0.00001;
	double midP, midCdif;
	double  lowCdif = prob - N(a);
	double highCdif = prob - N(b);
	if (lowCdif*highCdif > 0)
	{
		double Temp = lowCdif;
		lowCdif = highCdif;
		highCdif = Temp;
	}
	else
	for (int i=0; i<=MaxIter; i++)
	{
		midP = (a + b) / 2.0;
		midCdif = prob - N(midP);
		if (abs(midCdif)<Tol) goto LastLine;
		else
		{
			if (midCdif>0) a = midP;
			else b = midP;
		}
	}
	LastLine:
	return midP;
}
// http://www.tohtml.com/cpp

2013-04-20, 6:39 PM, Saturday

Multi-dimensional Matrix – Implementation

Filed under: C++ — weekendsunny @ 6:39 PM
/* Three Dimensional (3 by 5 by 2) Matrix dynamic memeory allocation */
#include <iostream>
#include <vector>
#include <boost/numeric/ublas/matrix.hpp>
#include "boost/multi_array.hpp"
using namespace std;

template <class Type> class Mymatrix
{
private:
  size_t mWidth, mHeight, mDepth;
  std::vector<Type> mArray;

public:
  Mymatrix(const size_t inWidth, const size_t inHeight, const size_t inDepth) :
   mWidth(inWidth), mHeight(inHeight), mDepth(inDepth)
   {
       mArray.resize(mWidth * mHeight * mDepth);
	   mArray = std::vector<Type>(mWidth * mHeight * mDepth,9.9);
   }

  Type Get(const size_t inX, const size_t inY, const size_t inZ) {
     return mArray[(inX * mHeight * mDepth) + (inY * mDepth) + inZ];
  }

  void Set(const size_t inX, const size_t inY, const size_t inZ, Type val) {
     mArray[(inX * mHeight * mDepth) + (inY * mDepth) + inZ] = val;
  }

};

int main (int argc, char* argv[]) {
	// Method 1: pointer to pointer to pointer
	double*** M1 = new double** [3];
	for (int i=0;i<3;++i){
		M1[i] = new double* [5];
		for (int j=0;j<5;j++){
			M1[i][j] = new double [2];
			for (int k=0;k<2;k++)
				M1[i][j][k]=i*100+j*10+k;
		}
	}
	cout<<M1[2][2][0]<<endl;
	for (int i=0;i<3;++i){
		for (int j=0;j<5;j++){
			delete[] M1[i][j];
		}
		delete[] M1[i];
	}
	delete[] M1;

	// Method 2 - matrix notation in C
	double (*M2)[5][2];
	M2 = new double[3][5][2];
	cout<<M2[2][2][0]<<endl;
	delete[] M2;

	// Method 3 - Boost :: matrix for 2-dim
	typedef boost::numeric::ublas::matrix<double> Bmatrix;
	Bmatrix M3(3,5);
	for (int i=0;i<3;i++)
		for (int j=0;j<5;j++)
				M3(i,j)=i*100+j*10;
	cout<<M3(2,2)<<endl;

	// Method 4 - Boost :: multi_array
	typedef boost::multi_array<double, 3> Trmatrix;
	typedef Trmatrix::index index;
	Trmatrix M4(boost::extents[3][5][2]);
	for (int i=0;i<3;i++)
		for (int j=0;j<5;j++)
				for (int k=0;k<2;k++)
					M4[i][j][k]=i*100+j*10+k;
	cout<<M4[2][3][1]<<endl;

	// Method 5 - Self-defined class
	Mymatrix<double> M5(3,5,2);
	M5.Set(2,4,1, 352.22);
	cout<<M5.Get(2,4,1)<<endl;

	char tmp; cin>>tmp; return 0;
}
// http://www.tohtml.com/cpp/

Matrix Multiplication – trivial

Filed under: C++ — weekendsunny @ 5:25 PM
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;
typedef vector< vector<int> > Intmatrix;

void read(string filename, int& n, Intmatrix &A) {
	string line;
	ifstream infile;
	infile.open (filename.c_str());
	int i=0, j=0, a;

	while (getline(infile, line) && !line.empty() && i<n) {
		istringstream iss(line);
		j = 0;
		while (iss >> a) {
			A[i][j] = a;
			j++;
		}
		i++;
	}
	infile.close();
}

Intmatrix ijkalgorithm(Intmatrix A, Intmatrix B) {
	int n = A.size();

	// initialise C with 0s
	vector<int> tmp(n, 0);
	Intmatrix C(n, tmp);

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			for (int k = 0; k < n; k++) {
				C[i][j] += A[i][k] * B[k][j];
			}
		}
	}
	return C;
}

void printMatrix(Intmatrix matrix) {
	Intmatrix::iterator it;
	vector<int>::iterator inner;
	for (it=matrix.begin(); it != matrix.end(); it++) {
		for (inner = it->begin(); inner != it->end(); inner++) {
			cout << *inner;
			if(inner+1 != it->end()) {
				cout << "\t";
			}
		}
		cout << endl;
	}
}

int main (int argc, char* argv[]) {
	string filename = "C:\\Projects\\2000.in";
	int n = 3;
	Intmatrix A(n,n), B(n,n), C(n,n);
	read (filename, n, A);
	read (filename, n, B);
	C = ijkalgorithm(A, B);
	printMatrix(A);	printMatrix(B);	printMatrix(C);

	char tmp; cin>>tmp; return 0;
}
// https://github.com/MartinThoma/matrix-multiplication
// http://www.tohtml.com/cpp/

Matrix multiplication – Boost

Filed under: C++ — weekendsunny @ 5:11 PM
#include <sstream>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/operation.hpp>
using namespace std;
using namespace boost::numeric::ublas;
typedef matrix<int> Bmatrix;

void read(string filename, int& n, Bmatrix &A) {
	string line;
	ifstream infile;
	infile.open (filename.c_str());
	int i=0, j=0, a;

	while (getline(infile, line) && !line.empty() && i<n) {
		istringstream iss(line);
		j = 0;
		while (iss >> a) {
			A(i,j) = a;
			j++;
		}
		i++;
	}
	infile.close();
}

void printMatrix(Bmatrix matrix) {
	for (int i=0; i < matrix.size1(); i++) {
		for (int j=0; j < matrix.size2(); j++) {
			cout << matrix(i, j);
			if(j+1 != matrix.size2()) {
				cout << "\t";
			}
		}
		cout << endl;
	}
	cout<<endl;
}

int main (int argc, char* argv[]) {
	string filename = "C:\\Projects\\2000.in";
	int n = 3;
	Bmatrix A(n,n), B(n,n), C(n,n);
	read (filename, n, A);
	read (filename, n, B);
	boost::numeric::ublas::axpy_prod(A, B, C);
	printMatrix(A);	printMatrix(B);	printMatrix(C);

	char tmp; cin>>tmp; return 0;
}
// http://martin-thoma.com/matrix-multiplication-python-java-cpp/
// http://www.tohtml.com/cpp/

2013-03-13, 10:31 PM, Wednesday

Random Permutation 2 – Random sample m out of n

Filed under: C++, Java — weekendsunny @ 10:31 PM
int[] pickMRandomly(int[] array, int m) {
    int[] subset = new int[m];
    for (int j = 0; j < m; j++) {
        int index = random(j, n); // random number between j and n
        int temp = array[index];
        array[index] = array[j];
        array[j] = temp;
        subset[j] = temp;
    }
    return subset;
}

Random Permutation 1 – shuffle

Filed under: C++, Java — weekendsunny @ 10:29 PM
public static void shuffleArray(int[] array) {
    Random generator = new Random();
    for (int j = 0; j < array.length; j++) {
    int index = generator.nextInt(array.length-j)+j; // random number between j and n
    int temp = array[index];
    array[index] = array[j];
    array[j] = temp;
    }
}

2013-01-20, 1:01 AM, Sunday

Fibonacci Number: Recursive vs. Iterative

Filed under: C++ — weekendsunny @ 1:01 AM
#include <iostream>
using namespace std;

// Recursive:
int fibo2(int n){
    if (n<=0) return -1;
    else if (n<=2) return 1;
    else return fibo2(n-1)+fibo2(n-2);
}

// Iterative:
int fibo1(int n){
    if (n<=0) return -1;
    int a=1, b=1, c=2;
    for (int i=3; i<=n; i++){
        c = a+b;
        a = b;
        b = c;
    }
    return b;
}

int main() 
{
    cout<<"Fiboracci Number:\n";
    for (int n=1; n<40; n++){
        cout<<fibo1(n)<<endl;
    }
    return 0;
}

//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++

2012-12-11, 6:50 PM, Tuesday

Implementation of Binary Search Tree

Filed under: C++ — weekendsunny @ 6:50 PM
#include <iostream>
#include <vector>
using namespace std;

struct Tree
{
    char data;
    Tree *left, *right, *parent;

    Tree(char a){
        data = a;
        left = NULL; right = NULL; parent = NULL;
    }
};

Tree* insertTreeNode(Tree* node, char data){
    if(node == NULL){
        Tree* newNode = new Tree(data);
        return newNode;        
    }
    else if(data <= node->data){
        node->left = insertTreeNode(node->left, data);
        node->left->parent = node;
    }
    else{
        node->right = insertTreeNode(node->right, data);
        node->right->parent = node;
    }
    return node;
}

bool isBST(Tree* root){
    if (root == NULL)
        return 1;
    else if (!isBST(root->left) || !isBST(root->right))
        return 0;
    else if(root->left){
        if(root->left->data > root->data)
            return 0;
    }
    else if(root->right){
        if(root->data >= root->right->data)
            return 0;    
    }
        return 1;
}

int main ()
{
    char ch, ch1, ch2;
    Tree *found=NULL, *succ=NULL, *pred=NULL, *ancestor=NULL;
    char charArr[9] = {'A','B','C','D','E','F','G','H','I'};

    Tree* root=NULL;
//    for (int i=0;i<sizeof(charArr)/sizeof(char);++i)
//        insertTreeNode(root,charArr[i]);
    root = insertTreeNode(root,'B');
    root->left = insertTreeNode(root->left,'A');

    /* is the tree BST? */
    cout<< "Binary Search Tree?: "<< ( isBST(root) ? 'Y':'N') <<endl;

    return 0;
}

//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++
//http://www.bogotobogo.com/cplusplus/cpptut.php

2012-12-10, 5:44 PM, Monday

Implementation of Hashing Table

Filed under: C++ — weekendsunny @ 5:44 PM
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int TABLE_SIZE = 128;

struct TableList {
    string key;
    int value;
    struct TableList *next;
};

unsigned hash_function(string s)
{
    unsigned hash = 0;

    for (int i = 0; i < s.length(); i++)
        hash = s[i] + 31*hash;
    return hash % TABLE_SIZE;
}

unsigned rehash(unsigned);

class HashMap 
{
private:
    TableList **table;
public:
    HashMap() 
    {
        table = new TableList*[TABLE_SIZE];
        for(int i = 0; i < TABLE_SIZE; i++) table[i] = NULL;
    }

    void showMap() 
    {
        struct TableList *tp;
        for (int i = 0; i < TABLE_SIZE; i++) {
            tp = table[i];
            if(tp){ 
                cout << "table[" << i << "] " << tp->key << "(" << tp->value << ")";
                tp = tp->next;
            }
            else 
                continue;
            while(tp) {
                cout << "->" << tp->key << "(" << tp->value << ")";
                tp = tp->next;
            }
            cout << endl;
        }
    }

    struct TableList* lookup(string s) 
    {
        struct TableList *tp;
        for(tp = table[hash_function(s)]; tp != NULL; tp = tp->next) 
                if((tp->key).compare(s) == 0) return tp;  // found
        return NULL;  // not found
    }

    void put(string key, int value) {
        struct TableList *tp;
        unsigned hash;

        // not found
        if(!(tp = lookup(key))) {
            tp = new TableList;
            tp->key = key;
            tp->value = value;
            hash = hash_function(key);
            tp->next = table[hash];
            table[hash] = tp;
        // it's already there
        } else {
            tp->key = key;
            tp->value = value;
            hash = hash_function(key);
            table[hash] = tp;
        }
    }     

    ~HashMap() 
    {
        for (int i = 0; i < TABLE_SIZE; i++)
            if (table[i] != NULL) delete table[i];
        delete[] table;
    }

};

int main()
{
    HashMap m;
    string line;
    ifstream dict_reader("C:/Temp/linux.words");
    //ifstream dict_reader("C:/Temp/shortlist");
    if( !dict_reader ) {
        cout << "Error opening input file - dict  " << endl ;
        exit(1) ;
    }

    int count = 0;
    while(getline(dict_reader,line)) {    
        if((line[0] >= 'x' && line[0] < 'y') || (line[0] >= 'X' && line[0] < 'Y') ) {
            m.put(line,count++);
        }
    }

    m.showMap();
    return 0;
}
//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++
//http://www.bogotobogo.com/cplusplus/cpptut.php

2012-12-07, 6:01 PM, Friday

Implementation of Linked List

Filed under: C++ — weekendsunny @ 6:01 PM
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

// only for the 1st Node
void initNode(Node *head, int n){
    head->data = n;
    head->next =NULL;
}

// apending
void addNode(struct Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = NULL;

    Node *cur = head;
    while(cur) {
        if(cur->next == NULL) {
            cur->next = newNode;
            return;
        }
        cur = cur->next;
    }
}

// insert at the head
void insertFront(struct Node **head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = *head;
    *head = newNode;
}

// Traversing the list
/*display*/
void display(struct Node* head) {
    Node *list = head;
    while(list) {
        cout << list->data << "";
        list = list->next;
    }
    cout << endl;
    cout << endl;
}

/*search a node*/
struct Node *searchNode(struct Node* head, int n) {
    while(head) {
        if(head->data == n) return head;
        head = head->next;
    }
    cout << "No Node " << n << " in list.\n";
}

struct Node *searchNode2(struct Node* head, int n) {
    while(head!=NULL & head->data != n) {
        head = head->next;
    }
    return head;
}

/*delete a node*/
bool deleteNode(struct Node **head, Node *ptrDel) {
    Node* cur = *head;
    if(ptrDel == *head) {
        *head = (**head).next;
        delete ptrDel;
        return true;
    }
    while(cur){
        if(cur->next == ptrDel) {
            cur->next = ptrDel->next;
            delete ptrDel;
            return true;
        }
        cur = cur->next;
    }
    return false;
}

// delete 
void deleteLinkedList(struct Node **node)
{
    struct Node* tmpNode;
    while(*node) {
        tmpNode = *node;
        *node = tmpNode->next;
        delete tmpNode;
    }
}

// reverse the list
struct Node* reverse(struct Node** List) 
{
    Node* parent = *List;
    Node* me = parent->next;
    Node* child = me->next;

    /* make parent as tail */
    parent->next = NULL;
    while(child) {
        me->next = parent;
        parent = me;
        me = child;
        child = child->next;
    }
    me->next = parent;
    *List = me;
    return *List;
}

// copy
void copyLinkedList(struct Node *node, struct Node **pNew)
{
    if(node != NULL) {
        *pNew = new Node;
        (*pNew)->data = node->data;
        (*pNew)->next = NULL;
        copyLinkedList(node->next, &((*pNew)->next));
    }
}

// Compare two linked list: return value: same(1), different(0)
int compareLinkedList(struct Node *node1, struct Node *node2)
{
    static int flag;

    /* both lists are NULL */
    if(node1 == NULL && node2 == NULL) {
        flag = 1;
    }
    else {
        if(node1 == NULL || node2 == NULL) 
            flag = 0;
        else if(node1->data != node2->data) 
            flag = 0;
        else
            compareLinkedList(node1->next, node2->next);
    }

    return flag;
}

int main() 
{
    Node* newHead=0;    
    Node* head = new Node;
    initNode(head,10);
    display(head);
    addNode(head,20);
    addNode(head,30);
    display(head);

    insertFront(&head,5);
    display(head);

    int numDel = 5;
    Node* ptrDelete = searchNode(head,numDel);
    if(deleteNode(&head,ptrDelete)) 
        cout << "Node "<< numDel << " deleted!\n";
    display(head);

    cout << "The list is reversed\n";
    reverse(&head);
    display(head);

    cout << "The list is copied\n";
    copyLinkedList(head,&newHead);
    display(newHead);

    cout << "Comparing the two lists...\n";
    cout << "Are the two lists same?\n";
    if(compareLinkedList(head,newHead)) 
        cout << "Yes, they are same!\n";
    else
        cout << "No, they are different!\n";
    cout << endl;

    numDel = 20;
    ptrDelete = searchNode(newHead,numDel);
    if(deleteNode(&newHead,ptrDelete)) {
        cout << "Node "<< numDel << " deleted!\n";
        cout << "The new list after the delete is\n";
        display(newHead);
    }
    cout << "Comparing the two lists again...\n";
    cout << "Are the two lists same?\n";
    if(compareLinkedList(head,newHead)) 
        cout << "Yes, they are same!\n";
    else
        cout << "No, they are different!\n";

    cout << endl;
    cout << "Deleting the copied list\n";
    deleteLinkedList(&newHead);
    cout << "Displaying afer deleting:\n";
    display(newHead);
    cout << "END\n";
    return 0;
}

//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++
//http://www.bogotobogo.com/cplusplus/cpptut.php

2012-12-06, 11:24 PM, Thursday

Replace a char by a string

Filed under: C++ — weekendsunny @ 11:24 PM
// Replace all spaces in a string with '%20'
#include <iostream>
#include <string>
using namespace std;

//Method 1: use STL::string
string repUsestring(string str){
    string newStr;
    for (int i=0; i<str.length(); i++){
        if (str[i]==' ')
            newStr += "%20";
        else
            newStr += str[i];
    }
    return newStr;
}

//Method 2: use C-stype array

char* repUsearray(char* str){
    int length = strlen(str), newLength=length;
    for (int i=0;i<length;i++){
        if (str[i]== ' ')
            newLength+=2;
    }
    char* newStr = new char[newLength];

    int j = 0;
    for (int i=0; i<length; i++){
        if (str[i]!=' '){
            newStr[j] = str[i];
            j++;
        }
        else{
            newStr[j] = '%';
            j++;
            newStr[j] = '2';
            j++;
            newStr[j] = '0';
            j++;
        }
    }
    newStr[newLength]=0; //ALWAYS REMEMBER TO ADD THE END OF ARRAY
    return newStr;
}

int main(){
    string str1("test a test b test c  ");
    char* str2 = "ai ni ai wo ai ta ";
    cout<<str1<<endl;
    cout<<repUsestring(str1)<<endl;
    cout<<str2<<endl;
    cout<<repUsearray(str2)<<endl;

    return 0;
}

//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++
//http://www.bogotobogo.com/cplusplus/cpptut.php

Hash Tables in C++

Filed under: C++ — weekendsunny @ 9:37 PM

To be…

Remove duplicate characters

Filed under: C++ — weekendsunny @ 6:11 PM
// Remove duplicated characters
#include <iostream>
using namespace std;

// Method1: no (large) memory; O(n^2)
void rmDuplicated1(char str[]) {
    int nOld = strlen(str);
    if (nOld>1) {
        int nNew = 0;
        int j;
        for (int i=0; i < nOld; ++i){  //iterate for each orignal element
            // check if this element is a nonduplicated one
            for (j=0; j<nNew; ++j){
                if (str[j]==str[i])
                    break;
            }
            // if nonduplicated, add it. 
            if (j==nNew){
                nNew++;
                str[nNew-1] = str[i];
            }
        }

        str[nNew] = 0;
    }
}

// Method2: addtional memory; O(n)
char* rmDuplicated2(char str[]) {
    int nOld = strlen(str);
    if (nOld<2)
        return str;
    else{
        char* newStr = new char[nOld];
        bool check[256] = {0};

        int nNew = 0;
        for (int i=0; i < nOld; ++i){
            if (!check[(int)str[i]]){
                newStr[nNew] = str[i];
                nNew++;
                check[str[i]] = true;
            }
        }

        newStr[nNew] = 0;
        return newStr;
    }
}

int main(){
    char* str = new char[10];
    strcpy(str, "aaaBBB");
    // char* str = "Hello" doesn't work. Cz here str is const type.
    cout<<str<<endl;
    rmDuplicated1(str);
    cout<<str<<endl;
    cout<<rmDuplicated2(str)<<endl;
    delete[] str;

    return 0;
}

//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++

2012-11-02, 4:49 PM, Friday

Reverse a C-style String

Filed under: C++ — weekendsunny @ 4:49 PM
// Reverse a C-Style String
#include <iostream>
using namespace std;

void reverse(char *str) {
    char * end = str;
    char tmp;
    if (str) {
        while (*end) {
            ++end;
        }
        --end;
        while (str < end) {
            tmp = *str;
            *str++ = *end;
            *end-- = tmp;
        }
    }
} 

int main(){
    char* str = new char[6];
    strcpy(str, "Hello");
    // char* str = "Hello" doesn't work. Cz here str is const type.
    cout<<str<<endl;
    reverse(str);
    cout<<str<<endl;
    delete[] str;

    return 0;
}
//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++

STL Stack and Queue

Filed under: C++ — weekendsunny @ 11:37 AM
// Read words and print them in reverse order;
// Using STL Stack or Queue;
// http://www.cplusplus.com/reference/stl/stack/
//Highlighted at http://tohtml.com/cpp/

#include <iostream>
#include <stack>
#include <queue>
#include <string>
using namespace std;

int main() {

    // stack<string> allWords;
    queue<string> allWords;
    string word;

    while (cin >> word) {
        allWords.push(word);
    }

    cout << "Number of words = " << allWords.size() << endl;

    while (!allWords.empty()) {
       // cout << allWords.top() << endl;
       cout << allWords.front() << endl;
       allWords.pop();
    }
    return 0;
}

2012-11-01, 9:58 PM, Thursday

Stack/Queue Implementation in Cpp

Filed under: C++ — weekendsunny @ 9:58 PM
#include <iostream>
#include <string>
using namespace std;
typedef int Object;

class Node{
    public:
        Object data;
        Node*  next;

        Node (Object item){
            data = item;
            next = NULL;
        }
        ~Node(){ delete next;}
};

class Stack{
public:
    Node* head;

    Object pop(){
        if (head != NULL){
            Object item = head->data;
            head = head->next;
            return item;
        }
        return NULL;
    }

    void push (Object item){
        Node* t = new Node (item);
        t->next = head;
        head     = t;
    }

};

class Queue{
public:
    Node* head;
    Node* tail;

    void push (Object item){
        Node* t = new Node (item);
        if(tail!=NULL){
            tail->next = t;
            tail    = t;
        }
        else{
            head=tail=t;
        }
    }

    Object pop(){
        if (head != NULL){
            Object item = head->data;
            head = head->next;
            return item;
        }
        return NULL;
    }
};

int main()
{
    Stack* st=new Stack();
    Queue* qu=new Queue();
    Object temp;
    while (cin >> temp){
        st->push(temp);
        qu->push(temp);
    }

    cout<<"Stake (FILO): ";
    while(st->head !=NULL){
        cout<< st->pop();
    }
    cout<<endl;

    cout<<"Queue (FIFO): ";
    while(qu->head !=NULL){
        cout<< qu->pop();
    }
    cout<<endl;

    return 0;
}
//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++

2012-06-14, 2:06 PM, Thursday

Static members and functions

Filed under: C++ — weekendsunny @ 2:06 PM
// A static member is shared by all objects of the class.
// All static data is initialized to zero when the first object is created, if no other initialization is present.
// We can't put it in the class definition but it can be initialized outside the class
// http://tohtml.com/cpp/

#include <iostream>
using namespace std;

class MyClass
{
public:
      MyClass(){std::cout << "default constructor" << ++count <<endl;}
      static int count;
};

int MyClass::count = 0;

int main(int argc, char** argv)
{
     MyClass* myObjArray = new MyClass[5];
     cout<<MyClass::count<<endl;
}

// A static member function can be called even if no objects of the class exist,
// and the static functions are accessed using only the class name and the scope resolution operator ::.

2012-06-06, 6:33 PM, Wednesday

ASCII Cstring/CharArray to float

Filed under: C++ — weekendsunny @ 6:33 PM
#include <iostream>
using namespace std;

double atofA(char s[]) 
{
    int sign = 1, i = 0, left = 0, power = 10;
    double right = 0.0;

    // Determine the sign:
    if (s[0]=='-')
    {
        sign = -1;
        i++;
    }

    // Calculate the integer part - left:
    while(s[i] && s[i]!='.')
    {
        left = left*10 + (s[i]-'0');
        i++;
    }

    // Calculate the float part - right:
    if (s[i]=='.')
    {
        i++;
        while(s[i])
        {
            right = right + (double)(s[i]-'0')/(power);
            power*=10;
            i++;
        }
    }

    return sign*(left+right);
}

int main()
{
    double d = atofA("-314.1592");
    // double d = atofA("-.1592");
    cout.precision(7);
    cout  << d << endl;
    return 0;
}

// Syntax highlighted at: http://tohtml.com/cpp/

2012-05-31, 9:06 PM, Thursday

Remove Specified Characters

Filed under: C++ — weekendsunny @ 9:06 PM
#include <iostream>
using namespace std;

int main()
{
    char s[] = "Battle of the Vowels: Hawaii vs. Grozny";
    char r[] = "aeiou";

    int *flags = new int[128]; // assumes ASCII!
    int src, dst;

    // Set flags for characters to be removed
    for( src = 0; src < strlen(r); ++src )
    {
        flags[(int)r[src]] = 1;
    }

    src = 0; dst = 0;

    while(src<strlen(s))
    {
        if(flags[(int)s[src]]!=1)
        {
            s[dst++] = s[src];
        }
        src++;
    }

    delete[] flags;

    char* res = new char[dst+1];
    strncpy(res, s, dst);
    res[dst] = '';
    cout<<res<<endl;

    delete[] res;
    return 0;
}
/*
int main(){
    char s[] = "Battle of the Vowels: Hawaii vs. Grozny";
    char r[] = "aeiou";
    char* sNew = new char[strlen(s)];

    int* flag = new int[128];
    for (int i=0; i < strlen(r); i++){
        flag[(int)r[i]]=1;
    }

    int iNew = 0;
    for (int i=0; i < strlen(s); i++){
        if (flag[(int)s[i]]!=1){
            sNew[iNew++] = s[i];
        }
    }
    sNew[iNew]='';

    cout<<sNew<<endl;
    delete[] flag;
    delete[] sNew;

    return 0;
}
*/
//Highlighted at http://tohtml.com/cpp/

First Non-Repeated Character

Filed under: C++ — weekendsunny @ 2:48 PM
#include <iostream>
#include <string>
using namespace std;

// The first 128 code points (0–127) of Unicode correspond to
// the letters and symbols on a standard U.S. keyboard.

// C stype string is an array of char, and ended by '' automatically;
// char x[]="abc"; then strlen(x)=3;
// char x[]="abcdef"; then strlen(x)=3;
// char x[]="abc"; then the real memory is 

bool isUniqueChars(string str) {
    bool char_set[256] = {0};
    for (int i = 0; i < str.size(); i++) {
        int val = str[i];
        if (char_set[val]) return false;
        char_set[val] = true;
    }
    return true;
}

int main()
{
    char str[20] = "abcd", xRepeat = ' ';
    bool iRepeat = false;
    int i = 0, len = strlen(str);

    for (i = 0; i < len;i++)
    {
        iRepeat = false;
        for (int j = 0; j < len; j++)
        {
            if (j!=i && str[j]==str[i])
            {
                iRepeat = true;
                break;
            }
        }
        if(!iRepeat)
        {
            xRepeat = str[i];
            break;
        }    
    }
    cout<<"In the string of "<<str<<endl;
    cout<<"the first nonrepeat char is the "<< i+1 << " th char: "<<xRepeat<<endl<<endl;
    cout<<isUniqueChars(str)<<endl;
    return 0;
}
//Highlighted at http://tohtml.com/cpp/
//Bred 3 + C++

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started