Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

The Qeens Problem

Prints all valid ways to arrange n qeens on a n x n chessboard so that the qeens don't attack each other.

#include <iostream>
#include <vector>

typedef std::vector< int > Vect;
typedef std::vector< Vect > List;

const int n = 12;

bool checkRow(const Vect &v, int k) {
	for (int i = k - 1; i >= 0; --i)
		if (v[k] == v[i])
			return false;

	return true;
}

bool checkDiag(const Vect &v, int k) {
	for (int i = k - 1; i >= 0; --i)
		if (k - i == abs(v[k] - v[i]))
			return false;
	
	return true;
}

List filter(List l, int k) {
	List r;
	for (List::const_iterator it = l.begin(); it != l.end(); ++it) {
		if (checkRow(*it, k) && checkDiag(*it, k))
			r.push_back(*it);
	}
	
	return r;
}

List qeens(int k) {
	if (0 == k) {
		List l;
		l.push_back(Vect());
		return l;
	}
	
	List l = qeens(k - 1);
	List r;
	for (List::iterator it = l.begin(); it != l.end(); ++it) {
		for (int newRow = 1; newRow <= n; ++newRow) {
			Vect v(*it);
			v.push_back(newRow);
			r.push_back(v);
		}
	}
	
	r = filter(r, k - 1);
	
	return r;
}

void printS(List l) {
	for (List::const_iterator it = l.begin(); it != l.end(); ++it) {
		for (Vect::const_iterator jt = it->begin(); jt != it->end(); ++jt)
			std::cout << *jt << " ";
		std::cout << std::endl;
	}
}

int main(int argc, char *argv[]) {
	List l = qeens(n);
	
	printS(l);
	
	return 0;
}

Simple integer expression interpreter

This is a simple integer expression interpreter.

#include <iostream>
#include <string>
#include <map>
#include <cctype>

char look;
std::map<std::string, int> table;

void getChar() {
    look = std::cin.get();
}

void error(const std::string &s) {
    std::cout << std::endl;
    std::cout << "Error: " << s << "." << std::endl;
}

void abort(const std::string &s) {
    error(s);
    exit(1);
}

void expected(const std::string &s) {
    abort(s + " Expected");
}

bool isAlpha(char c) {
    return isalpha(c);
}

bool isDigit(char c) {
    return isdigit(c);
}

bool isAlNum(char c) {
    return isalnum(c);
}

bool isAddop(char c) {
    return ((c == '+') || (c == '-'));
}

bool isMulop(char c) {
    return (('*' == c) || ('/' == c));
}

bool isWhite(char c) {
    return ((' ' == c) || ('\t' == c));
}

void skipWhite() {
    while (isWhite(look))
        getChar();
}

void match(char x) {
    if (look != x)
        expected(std::string("\"") + x + "\"");
    else {
        getChar();
        skipWhite();
    }
}

void emit(const std::string &s) {
    std::cout << "\t"  << s;
}

void emitLn(const std::string &s) {
    emit(s);
    std::cout << std::endl;
}

void newLine() {
    if (look == '\n')
        getChar();
}

std::string getName() {
    if (!isAlpha(look))
        expected("Name");

    std::string name;
    while (isAlNum(look)) {
        name += look;
        getChar();
    }
    skipWhite();

    return name;
}

int getNum() {
    int value(0);

    if (!isDigit(look))
        expected("Integer");

    while (isDigit(look)) {
        value = value * 10 + look - '0';
        getChar();
    }
    skipWhite();

    return value;
}

int expression();

int factor() {
    int ret;

    if (look == '(') {
        match('(');
        ret = expression();
        match(')');
    } else if (isAlpha(look)) {
        std::string name = getName();
        if (table.count(name) == 0)
            table.insert(std::pair<std::string, int>(name, 0));
        ret = table[name];
    } else
        ret = getNum();

    return ret;
}

int term() {
    int value = factor();

    while (isMulop(look)) {
        if (look == '*') {
            match('*');
            value *= factor();
        } else if (look == '/') {
            match('/');
            value /= factor();
        }
    }

    return value;
}

int expression() {
    int value(0);

    if (!isAddop(look))
        value = term();

    while (isAddop(look)) {
        if (look == '+') {
            match('+');
            value += term();
        } else if (look == '-') {
            match('-');
            value -= term();
        }
    }

    return value;
}

void assignment() {
    std::string name = getName();
    match('=');
    if (table.count(name) == 1)
        table[name] = expression();
    else
        table.insert(std::pair<std::string, int>(name, expression()));

    std::cout << name << " = " << table[name] << std::endl;
}

void init() {
    getChar();
    skipWhite();
}

int main(int argc, char *argv[]) {
    init();

    do {
        assignment();
        newLine();
    } while ((look != '.') && (look != '\n'));

    return 0;
}

C++ way to randomly select M numbers

This will randomly select M numbers from the interval [1, NMAX].

Note the extensive use of STL.

const short NMAX = 49;
const short M = 6;

std::vector<short> v;
for (short i(0); i < NMAX; ++i)
	v.push_back(i + 1);

random_shuffle(v.begin(), v.end());
copy(v.begin(), v.begin() + M, std::ostream_iterator<short>(std::cout, " "));

Vector And Sort

// æ??述了STL里é?¢çš„Vector的用法以å?пޒåº?

#include "stdafx.h"
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;

int main()
{
	vector<double> homework;

	double x;
	while(cin >> x)
	{
		homework.push_back(x);
	}

	vector<int>::size_type size = homework.size();
	if(size == 0)
	{
		cout << "The size must not be Zero" << endl;
		return 1;
	}

	sort(homework.begin(), homework.end());
	vector<int>::size_type mid = size / 2;

	double median = (size % 2 == 0) ? (homework[mid] + homework[mid+1]) / 2 : homework[mid];

	cout << "The median is " << median << endl;
}

write STL container to output stream

//write all elements without any delimiter
copy (coll.begin(), coll.end(), ostream_iterator(cout));

reff : josutis, pg. 278

//with boost
for_each(coll.begin(), coll.end(), cout << _1);


« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS