View Single Post
Old July 31, 2019, 10:23   #299
Kusunose
Rookie
 
Join Date: Jan 2019
Posts: 6
Kusunose is on a distinguished road
It's nice but I think something like this is nicer because you can keep using for loop, though bit wordy.
Code:
struct loc_iterator {
	struct loc cur;
	struct loc begin;
	struct loc end;
};

struct loc_iterator loc_iterator(struct loc begin, struct loc end)
{
	struct loc_iterator iter;
	iter.cur = iter.begin = begin;
	iter.end = end;
	return iter;
}

bool loc_iterator_test(const struct loc_iterator* iter)
{
	return iter->cur.y != iter->end.y;
}

void loc_iterator_next(struct loc_iterator* iter)
{
	iter->cur.x++;
	if (iter->cur.x == iter->end.x) {
		iter->cur.x = iter->begin.x;
		iter->cur.y++;
	}
}
This code
Code:
	for (y = y1; y < y2; y++) {
		for (x = x1; x < x2; x++) {
can be translated as
Code:
	for (struct loc_iterator iter = loc_iterator(loc(x1, y1), loc(x2, y2));
		loc_iterator_test(&iter); loc_iterator_next(&iter)) {
			/* use iter.cur */
			int x = iter.cur.x;
			int y = iter.cur.y;
and this
Code:
	for (y = y1 - 1; y < y2 + 1; y++) {
		for (x = x1 - 1; x < x2 + 1; x++) {
can be translated as
Code:
	for (struct loc_iterator iter = loc_iterator(loc(x1 - 1, y1 - 1), loc(x2 + 1, y2 + 1));
		loc_iterator_test(&iter); loc_iterator_next(&iter)) {
Values for initializers and conditions can be directly translated, provided conditions are exclusive (if inclusive, add +1 for x and y for loc end).

Last edited by Kusunose; July 31, 2019 at 10:34.
Kusunose is offline   Reply With Quote