Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

/prog/ challenge (S(SKK)(SKK))(S(SKK)(SKK))

Name: Anonymous 2011-04-10 9:36

The challenge: Implement generators in the favourite language of yours.
Are banned: Language native generators (i.e. FIOC's yield), delimited continuations (sorry, Schemers, that would be too easy).

The test program will be an infinite generator that computes facts, and a loop that takes the first five of them.

The deadline is 17/04/2011 00:00 /prog/time.
The most complete, small and easy to use implementation wins.

Name: HotCupOfJava !!7YfDQjROXukLpYb 2011-04-12 5:06

Ok, I lied, I didn't go to sleep quite yet. I retooled my program to address the valid concerns of >>58 while keeping encapsulation.

public class Generator {

    int counter;
    int bound;
    int[] list;
   
    public Generator(){
        counter = 0;
        bound = 100;
        list = new int[bound];
    }
   
    public int generateNext(){
        if(counter + 1 == bound)
            reallocate();
        return facts(counter++);
    }
   
    private void reallocate() {
        int i;
        int[] temp = list;
        bound = bound * 2;
        list = new int[bound];
        for(i = 0; i < bound/2; i++)
            list[i] = temp[i];
    }

    public int facts(int n){
        if(n == 0)
            return list[counter] = 1;
        else
            return list[counter] = n * list[counter-1];
    }
}

public class GeneratorTester {
    public static void main(String args[]){
        int i;
        Generator gen = new Generator();
       
        for(i = 0; i < 200; i++){
            System.out.println(gen.generateNext());
        }
    }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List