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-4 of 4 total  RSS 

Generate all subsets of a set

This code generates all the subsets of {1, 2, ..., n} and prints them.

This also contains a very fast binary counter implementation.

See this for further explanations.

#include <stdio.h>

/* Applies the mask to a set like {1, 2, ..., n} and prints it */
void printv(int mask[], int n) {
	int i;
	printf("{ ");
	for (i = 0; i < n; ++i)
		if (mask[i])
			printf("%d ", i + 1); /*i+1 is part of the subset*/
	printf("\b }\n");
}

/* Generates the next mask*/
int next(int mask[], int n) {
	int i;
	for (i = 0; (i < n) && mask[i]; ++i)
		mask[i] = 0;

	if (i < n) {
		mask[i] = 1;
		return 1;
	}
	return 0;
}

int main(int argc, char *argv[]) {
	int n = 3;

	int mask[16]; /* Guess what this is */
	int i;
	for (i = 0; i < n; ++i)
		mask[i] = 0;

	/* Print the first set */
	printv(mask, n);

	/* Print all the others */
	while (next(mask, n))
		printv(mask, n);

	return 0;
}

Treating first/last loop iterations differently

Sometimes, you need to iterate over a list of items and treat the first and last element differently from the rest. This tends to produce really messy code, which can be avoided using the following snippet.

Imagine you have a list of Kittens, and you want to print out a summary of them, saying "My kittens are called Bob, James, John, and Ally." You need to treat the first and last element of the list differently from the rest, lest you end up with superfluous commas in the text. You also need to deal with the cases of there being only one kitten, or no kittens at all.

To do this, you can avail yourself of a Counter class that keeps track of where you are in the iteration:
String kittenDesc = "I have no kittens.";
Counter kc = new Counter(kittens);
for (Kitten k : kittens) switch(kc.next()) {
	case one:   kittenDesc =  "My kitten is called " + k.getName() + "."; break;
	case first: kittenDesc =  "My kittens are called " + k.getName();     break;
	case item:  kittenDesc += ", " + k.getName();                         break;
	case last:  kittenDesc += " and " + k.getName() + ".";                break;
}

package com.zarkonnen.util;

import java.util.Collection;

/**
 * Used for keeping track of where you are in a collection/array being iterated over. Use by
 * initialising with the collection/array before the loop and embedding a switch on the next() Mode
 * value into the loop.
 *
 * LICENCE: This code is licenced under a BSD licence. Feel free to alter and redistribute.
 *
 * @author David Stark, http://www.zarkonnen.com
 * @version 1.0 (2007-07-11)
 */
public class Counter {
	/**
	 * An enumeration of modes identifying where in the collection/array we are.
	 */
	public enum Where {
		/** The only element of an array/collection of size 1. */ one,
		/** The first element. */                                 first,
		/** The last element of the array/collection. */          last,
		/** Any other element somewhere in the middle. */         item
	}
	
	private int size;
	private int nextIndex = 0;
	
	/**
	 * @param c A collection to keep track of. If its size changes between now and the
	 * iteration, strange things will happen.
	 */
	public Counter(Collection c) {
		size = c.size();
	}
	
	/**
	 * @param a An array to keep track of. If its size changes between now and the iteration,
	 * strange things will happen.
	 */
	public Counter(Object[] a) {
		size = a.length;
	}
	
	/**
	 * @return A Where enum value for where in the array/collection we now are:
	 * <ul>
	 * <li><strong>one</strong> at the only element of an array/collection of size 1</li>
	 * <li><strong>first</strong> at the first element</li>
	 * <li><strong>last</strong> at the last element</li>
	 * <li><strong>item</strong> at any other element</li>
	 * </ul>
	 */
	public Where next() {
		return size == 1         ? Where.one   :
		       nextIndex++ == 0  ? Where.first :
		       nextIndex == size ? Where.last  :
		                           Where.item  ;
	}
	
	/**
	 * @return Which index of the array/collection we're currently at.
	 */
	public int index() {
		return nextIndex == 0 ? 0 : nextIndex - 1;
	}
}

Count Characters in Input Fields

Stick these methods in helpers/application_helper.rb:
  def countdown_field(field_id,update_id,max,options = {})
    function = "$('#{update_id}').innerHTML = (#{max} - $F('#{field_id}').length);"
    count_field_tag(field_id,function,options)
  end
  
  def count_field(field_id,update_id,options = {})
    function = "$('#{update_id}').innerHTML = $F('#{field_id}').length;"
    count_field_tag(field_id,function,options)
  end
  
  def count_field_tag(field_id,function,options = {})  
    out = javascript_tag function
    out += observe_field(field_id, options.merge(:function => function))
    return out
  end


And then in your view, you can use them like:
<input id="message">
<p>You have used <span id="counter">...</span> letters.</p>

<%= count_field('message','counter') %>

Stopwatch

It can start, stop, start again, and reset.
Use 'select' key and menu.
from appuifw import *
from key_codes import *
import e32, time

class StopWatch:
    running = 0
    time_start = None
    elap = 0.0

    def __init__(self):
        self.canvas = Canvas(self.update)
        app.body = self.canvas
        self.canvas.bind(EKeySelect, self.toggle)
        self.update()

    def update(self, rect=None):
        if self.running:
            self.elap = time.clock() - self.time_start
            e32.ao_sleep(0.05, self.update)
        t = self.elap
        min = int(t / 60)
        sec =  int(t - min*60)
        hsec = int((t - min*60 - sec)*100)
        self.canvas.clear()
        self.canvas.text((20,40), u"%02d:%02d:%02d" % (min,sec,hsec), font='title')

    def toggle(self):
        if self.running:
            self.running = 0
            self.elap = time.clock() - self.time_start
        else:
            self.running = 1
            self.time_start = time.clock() - self.elap
            self.update()

    def reset(self):
        self.running = 0
        self.elap = 0.0
        self.update()


sw = StopWatch()
lock = e32.Ao_lock()
app.menu = [(u'Reset', sw.reset), (u'Close', lock.signal)]
app.exit_key_handler = lock.signal
lock.wait()

Screenshot

I am new to using class var and instance var.
But the code seems easier than the non-OO version I tried at first.
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS