Archive for the ‘Code’ Category

OpenCL memset

Sunday, November 21st, 2010

In September I was porting to OpenCL a version of the radioastronomy beam forming algorithm I realized in CUDA for my master project. The algorithm needs to clean the memory after some iterations, and with CUDA I was using the memset function to do it. Unluckily, OpenCL does not provide a function like memset, so I had to write a kernel to accomplish the task.

Now, it is clear that writing a kernel like this is one of the easiest tasks ever :), and is a one-liner BTW, but as always I’d like to share the code with the Internet, cause it’s always useful to find some example code on-line, especially when you are in a hurry.

__kernel void memSet(float value, __global float *mem) {
    mem[get_global_id(0)] = value;
}

As can be seen, the memory to clean was an array of float values, but changing it to work with other data types is trivial.

My Random Utilities version 1.0.0

Sunday, November 7th, 2010

Hi everyone.

In the past few days I spent some time, while working on my last exams and my master project, putting together the C++ utilities that I wrote and published on this website in the past. The goal is just to have a library with these utilities that I can use when I need it, without having to take pieces from here and there every time I need.

So I put together the ArgumentList, the string replacement and another couple of small functions in a single package, adding a pair of self defined exceptions. Of course this is not the best code in the world, is just a “not really organized” library of random stuffs, that I put online just because I like to share and think, still, that source code is something nice and that should be read :)

The library can be downloaded here, it is so small and simple that I don’t think explanations are necessary, anyway comment here if you want to talk about it.

Replace a substring with another string

Sunday, September 26th, 2010

Few days ago, working on an automatic code generator for my master project, I had to read a string representing the structure of the code and containing some placeholders. I had then to replace these placeholders with some other generated code.

Given the fact that the C++ std library doesn’t seem to contain something to do what I needed, I wrote these few lines of code to solve my problem:



std::string *replace(std::string src, std::string placeholder, std::string value) {
	std::string *toRet = new std::string();
	size_t pos = 0;
	size_t oldPos = 0;

	while ( (pos = src.find(placeholder, pos)) < std::string::npos ) {
		toRet->append(src.substr(oldPos, pos - oldPos));
		toRet->append(value);
		pos += placeholder.length();
		oldPos = pos;
	}
	toRet->append(src.substr(oldPos));

	return toRet;
}

The code is really simple and it uses only standard C++, the only dependence being the string library. The complexity of the code is linear in the length of the source string.

Evaluate a sequence

Tuesday, June 1st, 2010

Hello everyone.

While working on some other things, like my MSc thesis, I saw a simple problem on a form to apply for a job, and I wanted to solve it. The problem is quite simple, but I enjoyed it and wanted to share my solution with the whole Internet; moreover the main reason I thought about modifying my ArgumentList class derives from this problem :)

The problem

Given a sequence of digits in some order, print all the expressions obtainable inserting a + (plus), – (minus), * (multiplication) or nothing, that evaluate to a given number. The solution should be written in C++ using the std library.

My solution

The solution is straightforward and is composed by two steps: generating all the possible expressions and then evaluate them.
To generate all the possible expressions what I did is the following. I used a pair to represent an expression: the pair is formed by an integer, representing the element after which the operators can be inserted, and a string, representing the expression to operate on. The first pair is just (0, sequence), where sequence is the one provided as input.
Now it is possible to use a queue to iteratively get a pair, evaluate the expression in it, and then generate the new expressions  and put them into the queue to get successively evaluated.
The code is the following:

while ( !queue.empty() ) {
		pair< unsigned int, string > *toEvaluate = queue.back();

		if ( evaluate(target, toEvaluate->second) ) {
			found.insert(toEvaluate->second);
		}

		if ( toEvaluate->first < (toEvaluate->second).length() - 1 ) {
			queue.push_front(new pair< unsigned int, string >(toEvaluate->first + 1, toEvaluate->second));
			for ( unsigned int i(0); i < NR_OPERATORS; i++ ) {
				queue.push_front(new pair< unsigned int, string>(toEvaluate->first + 2, (toEvaluate->second).substr(0, toEvaluate->first + 1) + operators[i] + (toEvaluate->second).substr(toEvaluate->first + 1)));
			}
		}

		queue.pop_back();
	}

The evaluation is quite simple too. When an expression has to be evaluated is first parsed and divided into two components: the operands and the operators. After that each operator is applied to its operands (starting with the multiplication in our case) and a total is computed. If it matches with the goal number the boolean value true is returned.

The code is the following:

bool evaluate(int target, string &item) {

	vector< int > operands;
	vector< char > operators;
	unsigned int i(0);

	while ( i < item.length() ) {
		unsigned int counter(i);
		while ( counter < item.length() && isdigit(item.at(counter)) ) {
			counter++;
		}
		operands.push_back(atoi((item.substr(i, counter - i)).c_str()));
		if ( counter < item.length() ) {
			operators.push_back(item.at(counter));
		}
		i = counter + 1;
	}

	// Performs the multiplies first
	for ( unsigned int op(0); op < operators.size(); op++ ) {
		if ( operators[op] == '*' ) {
			operands[op] *= operands[op + 1];
			operands[op + 1] = 1;
		}
	}

	int total(operands[0]);
	unsigned int opCounter(0);
	for ( unsigned int i(1); i < operands.size(); i++ ) {
		switch( operators[opCounter++] ) {
			case '+':
				total += operands[i];
				break;
			case '-':
				total -= operands[i];
				break;
			case '*':
				total *= operands[i];
				break;
		}
	}

	if ( total == target ) {
		return true;
	}

	return false;
}

Notes

The original problem was less general and asked just to print all the expressions evaluating the number 3141 given the sequence 987654321, I generalized it for the sake of fun.
The complete code, with a Makefile, is available here. It needs to have my ArgumentList installed to work.

Post scriptum

The answer of the original question are the expressions “9*8*7*6+54+3*21” and “987-6+5*432*1” :)

ArgumentList 0.2.1

Friday, May 28th, 2010

Hello everyone, this is just a minor update of the ArgumentList class.

Two are the differences between this one and the previous version:

  1. CMake will now produce also the “install” directive for Make
  2. The getSwitchArgument() method, instead of returning a zero in case of failure, will throw a std::exception

So it will be safe, from now on, to call the getSwitchArgument method inside a try/catch block, like in the following example:

int i(0);
float f(0.0);
try {
    i = args.getSwitchArgument< int >("-i");
    f = args.getSwitchArgument< float >("-f");
}
catch (std::exception) {
    std::cerr << "Ops :)" << std::endl;
}

The new version or ArgumentList can be downloaded from this link.