Thread: Spiral Problem
View Single Post
Old Aug 27th, 2004, 5:53 PM   #2
Infinite Recursion
Programming Guru
 
Infinite Recursion's Avatar
 
Join Date: Jul 2004
Location: United States
Posts: 3,475
Rep Power: 8 Infinite Recursion is on a distinguished road
Send a message via MSN to Infinite Recursion Send a message via Yahoo to Infinite Recursion
This is called a Ulam Spiral... if you want more graphical representation or a few docs to read, check it out via google.

Here are two Java classes to handle this... Enjoy.


import java.awt.*;

public final class SpiralGenerator extends Object {
	static final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3;
	int count, remain, distance, direction;

	SpiralGenerator() {
 count = 1;
 remain = 2;
 distance = 1;
 direction = RIGHT;
 }

	public void generate(int number, Point point) {
 int dx = 0, dy = 0;

 for (; count <= number; count++) {
 	if (--remain == 0) {
  switch (direction) {
  	case UP: distance++; direction = LEFT; break;
  	case DOWN: distance++;
  	default: direction--; break;
  	}
  remain = distance;
  }
 	switch (direction) {
  case LEFT: --dx; break;
  case RIGHT: ++dx; break;
  case UP: --dy; break;
  case DOWN: ++dy; break;
  }
 	}

 point.translate(dx, dy);
 }
	}

public final class PrimeGenerator extends Object {
	int number, index, primes[], squares[];

	PrimeGenerator() {
 index = 0;
 number = 1;
 primes = new int[1];
 squares = new int[1];
 }

	public int generate() {
 if (number > 2) {
loop:
 	while(true) {
  number += 2;
  for (int i = 1; i < index && number >= squares[i]; i++) {
  	if ((number % primes[i]) == 0) continue loop;
  	}
  break loop;
  }
 	}
 else number++;

 squares[index] = (primes[index] = number) * number;

 if (++index == primes.length) reallocate();

 return number;
 }

	void reallocate() {
 int array[];

 System.arraycopy(primes, 0, (array = new int[primes.length * 2]), 0, primes.length);
 primes = array;

 System.arraycopy(squares, 0, (array = new int[squares.length * 2]), 0, squares.length);
 squares = array;
 }
	}
__________________
http://jasonpowers.net

"There are a thousand hacking at the branches of evil to one who is striking at the root."
Infinite Recursion is offline   Reply With Quote