Error in Turtle recursion - recursion

I'm attempting to use Turtle Graphics to make a fractal via recursion, but for some reason my code seems to not return the Turtle back to the origin.
My code is as follows
public static void sun(Turtle t, double radius) {
for ( int i = 0; i < 360; i++ ) {
t.forward( radius * .0174 );
t.left( 1 );
}
t.penup();
t.left(90);
t.forward(radius);
//t.fill();
t.pendown();
for (int i = 0; i < 8; i++) {
t.forward(2*radius);
t.backward(2*radius);
t.left(45);
}
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
}
public static void fractalSun(Turtle t, double r, int level) {
int color;
if (level == 0) {
t.color(255, 0, 0);
sun(t, r);
}
else {
sun(t, r);
t.left(90);
t.forward(r);
t.right(90);
t.forward(r * 2);
t.right(90);
fractalSun(t, r/4, level -1);
t.left(90);
t.backward(r * 2);
}
}
The code compiles successfully, but produces this image:
Screenshot
My goal would be for the turtle to return to the center of each 'sun' but something isn't working.

Although the sun() method returns the turtle to where it started, the fractalSun() method leaves the turtle to the center of the figure. So whether fractalSun() calls itself or sun() it has to make adjustments. Here's an update fix with fewer changes (mostly deletions):
Change this final block of code in sun():
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
to be simply one statement:
// t.penup();
// t.backward(radius);
t.right(90);
// t.pendown();
Drop three lines of code from fractalSun() and change the arguments to the final function call:
public static void fractalSun(Turtle t, double r, int level) {
if (level == 0) {
t.color(255, 0, 0);
sun(t, r);
} else {
sun(t, r);
// t.left(90);
// t.forward(r);
// t.right(90);
t.forward(r * 2);
t.right(90);
fractalSun(t, r / 4, level - 1);
t.left(90);
t.backward(r * 2 + r / 4); // added a term to the equation
}
}
OUTPUT
Note: I simulated this using Python turtle so you may need to tweak my Java code if it's amiss.

Your 8-spoke loop leaves the pen at the center of the figure after each spoke. At the end of the loop, starting at the center, you execute this sequence:
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
In particular, you back up one radius; I think that's where you're getting off your intended point. Drop that line, double-check your desired direction, and I think you'll be okay.

Related

can coroutine be used to solve stack overflow due to too deep recursive function call?

Has anyone tried to use coroutine to solve stack overflow caused by too deep recursive function call? according to the document on coroutines, the coroutine state will be saved on heap instead of on stack, which could have the potential to avoid the limitation imposed by the limited stack size and thus provide a way to solve the stack overflow issue in a generic way. i have tried with some code but it looks like the stack over flow issue persists. anyone has any tips/advice to share? or point me to some tutorial? thanks in advance.
// file main
#include "RecursiveCall.h"
// coroutine
static ReturnObject DoIntegration(Context& ctx, ReturnObject::promise_type* parent, double x_n)
{
double* dummyA = new double[(int)((x_n + 1) * 2)]; // an effort to prevent heap allocation from "optimized out"
co_await AwaitableBase(ctx, parent, x_n);
ctx._dummyVec.push_back(dummyA); // part of the effort to prevent heap allocation from "optimized out"
}
// caller
static double Invoke(Context& ctx, ReturnObject::promise_type* parent, double x_n)
{
auto ret = DoIntegration(ctx, parent, x_n);
std::coroutine_handle<ReturnObject::promise_type> h = ret._coroH;
auto p = h.promise();
while (!h.done())
{
if (p.AreChildrenReady())
{
h();
break;
}
}
return p._area;
}
bool AwaitableBase::await_suspend(std::coroutine_handle<PromiseType> h)
{
_promise = &h.promise();
if (_parent)
{
_parent->RegisterChild(h);
}
if (_x_n <= _ctx._b)
{
_promise->_x_n = 0.0;
_promise->_area = 0.0;
return false;
}
_promise->_area = GetArea(_x_n, _ctx._incr);
double newX = _x_n - _ctx._incr;
_promise->_x_n = newX;
double area = Invoke(_ctx, &h.promise(), newX);
//post calculation
_promise->_area += area;
return true;
}
double CallRecursive(double x0, double x_n, double incr)
{
Context ctx{ x0, incr };
return Invoke(ctx, nullptr, x_n);
}
int main()
{
double x0 = 0.0;
double x_n = 4.5;
double incr = 0.5; // no stackoveflow
//double incr = 0.0015; // stack oveflow
auto area = CallRecursive(x0, x_n, incr);
std::cout << "integrated result: " << area << "\n";
}
// file RecrusiveCall.h
#include <coroutine>
#include <exception>
#include <map>
#include <iostream>
#include <vector>
/* integration certainly can and should be done in a sequencial way in real world. but here is just use it as a simple example of recursive call, so the integration is implemented as a recursive function call and is done from high limit of x to the lower limit */
static double GetY(double x)
{
using CurvePoint = std::pair<double, double>;
constexpr CurvePoint curve[10] = { {0.0, 1.0}, {0.5, 1.2}, {1.0, 1.0}, {1.5, 1.2}, {2.0, 1.0},
{2.5, 1.2}, {3.0, 1.0}, {3.5, 1.2}, {4.0, 1.0}, {4.5, 1.2} };
if (x < curve[0].first || x > curve[9].first)
return 0.0;
CurvePoint newPoint;
const auto p1 = std::lower_bound(&curve[0], &curve[10], x, [](const auto& a, const auto& b) constexpr { return a.first < b; });
// check for special cases: first
const auto p0 = p1 - 1;
return (p1->second - p0->second) * (x - p0->first) / (p1->first - p0->first) + p0->second;
}
static double GetArea(double end, double incr)
{
return (GetY(end) + GetY(end - incr)) * 0.5 * incr;
}
struct Context
{
double _b; // lower limit of the integration range
double _incr; // increment steplength
std::vector<double*> _dummyVec; // effort to prevent heap allocation from being optimzed out
~Context()
{
for (auto p : _dummyVec)
delete p;
}
};
struct ReturnObject
{
struct promise_type
{
using Handle = std::coroutine_handle<promise_type>;
ReturnObject get_return_object() {
return { std::coroutine_handle<promise_type>::from_promise(*this) };
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void unhandled_exception() {}
void return_void() {}
void RegisterChild(Handle& childH)
{
_children.push_back(childH);
}
bool AreChildrenReady()
{
for (auto c : _children)
{
if (!c.done())
return false;
}
return true;
}
double GetValue() const { return _area; }
std::vector<Handle> _children;
double _area{ 0 };
double _x_n{ 0 };
};
ReturnObject(promise_type::Handle coro) : _coroH(coro)
{
}
operator std::coroutine_handle<promise_type>() const { return _coroH; }
// A coroutine_handle<promise_type> converts to coroutine_handle<>
operator std::coroutine_handle<>() const { return _coroH; }
std::coroutine_handle<promise_type> _coroH;
};
struct AwaitableBase
{
typedef Context Ctx;
using PromiseType = ReturnObject::promise_type; // todo: remove
bool await_ready()
{
return false;
}
bool await_suspend(std::coroutine_handle<PromiseType> h);
PromiseType* await_resume()
{
return _promise;
}
AwaitableBase(Ctx& ctx, PromiseType* parent, double x_n) : _ctx(ctx), _x_n(x_n), _parent(parent)
{
}
~AwaitableBase()
{
}
Ctx& _ctx;
PromiseType* _parent{ nullptr };
PromiseType* _promise{ nullptr };
double _x_n{ 0.0 };
};
no.
the coroutine's stack frame remains allocated. what's pushed to heap (as custom handle struct) is minimal register state plus struct data, to later resume the stack frame.
that is how you can access all local variables after resuming where you left off.

Stacking of data, extracting of value, pushing stack down

I might have missed a post for this question or searched the wrong question online so if there is something that answers this question exactly, sorry please link :)
Question: I'm trying to create a array to store a few integers in order,
data(1)
data(2)
data(3)
data(4)
data(5)
with the array complete, the program finds a average of the integers and then moves the stack up or deletes the oldest (data1) entry and moves the entire thing up by one, so it starts:
data(2)
""
data(6)
and this continues over in a loop until the software is terminated.
A stack is a LIFO data structure. It looks like you want to use a queue, which is a FIFO data structure. This can be accomplished using a circular buffer. This allows us to use a simple array. An example of the behavior you described in the question can be found in the following code example.
uint8_t qhead;
uint8_t qtail;
uint8_t qsize;
const uint8_t qcapacity = 5;
uint8_t qdata[qcapacity];
void queue_enqueue(const uint8_t data)
{
// Check to make sure that we do not overflow
if (qsize + 1 > qcapacity)
{
return;
}
qdata[qhead] = data;
// Calculate the new head
qhead = (qhead + 1) % qcapacity;
qsize++;
}
uint16_t queue_dequeue(void)
{
// Make sure there is something to dequeue
if (qsize == 0)
{
return 0xFFFFFFFF;
}
uint8_t result = qdata[qtail];
// Calculate the new tail
qtail = (qtail + 1) % qcapacity;
qsize--;
return result;
}
void setup()
{
qhead = 0;
qtail = 0;
qsize = 0;
}
void loop()
{
uint8_t data = /* Input source here */;
/* Need to fill the queue with qcapacity items first */
if (qsize < qcapacity)
{
queue_enqueue(data);
}
else
{
/* Calculate the average */
uint16_t average = 0;
for (uint8_t i = 0; i < qsize; i += 1)
{
average += qdata[i];
}
average = average / qsize;
/* Remove the old element */
queue_dequeue();
/* Add the new element */
queue_enqueue(data);
}
}

Game of Life Processing

import processing.core.PApplet;
public class gl extends PApplet {
static int neighborCount;
static int screenRows;
int tNC; // Temporary Neighbor Count
int newState;
int columns = 960;
int rows = 477;
int[][] cells = new int[columns][rows];
int[][] newGen = new int[columns][rows];
public static void main(String[] args) {
PApplet.main("gl");
}
public void settings() {
size(1920, 955);
}
public void setup() {
// Set background white and all of cells[][] to 0 or 1
screenRows = 0;
background(255);
for (int j = 0; j < (rows / 2); j++) {
for (int i = 0; i < (columns / 2); i++) {
cells[i][j] = (int) random(0, 2);
}
}
}
public void draw() {
// If program has finished generating this frame, reset everything and set cells[][] equal to newGen[][]
if (screenRows > (height / 2)) {
screenRows = 0;
System.out.println("End of generation reached");
background(255);
cells = newGen.clone();
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
newGen[i][j] = 0;
}
}
}
// Go through every element in cells[][], determine it's value, and display it
for (int x = 1; x < (width / 2) - 1; x++) {
for (int y = 1; y < (height / 2) - 1; y++) {
printCell(x, y);
}
}
screenRows++;
}
public void printCell(int x, int y) {
setCellState(x, y);
if (newGen[x][y] == 0) {
stroke(255);
fill(255);
} else if (newGen[x][y] == 1) {
stroke(0);
fill(0);
}
System.out.println(x + ", " + y);
rect(x, y, 2, 2);
}
public void setCellState(int x, int y) {
tNC = getNeighborCount(x, y);
neighborCount = 0;
System.out.println(tNC);
if (tNC < 2) { // If less than 2 neighbors, cell dead
newGen[x][y] = 0;
} else if (tNC > 3) { // If more than 3 neighbors, cell dead
newGen[x][y] = 0;
} else if ((tNC == 2 || tNC == 3) && cells[x][y] == 1) { // If 2 or 3 neighbors and cell is alive, do nothing (unnecessary statement but makes visualizing easier)
} else if (tNC == 3 && cells[x][y] == 0) { // If 3 neighbors and cell is dead, cell is alive
newGen[x][y] = 1;
} else if (tNC == 2 && cells[x][y] == 0) { // If 2 neighbors and cel is dead, do nothing (also unnecessary)
} else {
System.out.println("Error in setCellState(int, int);"); // In event of none of the conditions being met
}
tNC = 0; // Reset variable (probably unnecessary but might as well)
}
public int getNeighborCount(int x, int y) {
// Go through each cell adjacent or diagonal to the cell and add it's value (0 or 1) to neighborCount
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
neighborCount += cells[i + x][j + y];
}
}
// Subtract the value of the cell being evaluated from neighborCount as that is not a factor in the sum of the neighbors
neighborCount -= cells[x][y];
return neighborCount;
}
}
Pastebin
I am just going for functionality over speed, for now.
I am attempting to code Conway's Game of Life using Processing in Eclipse. The above code is dysfunctional in multiple ways:
The generation displayed appears much smaller in the window than I want to be. It only takes up a fraction of the window despite my efforts to counterbalance this by making each cell 2x2 pixels and half as many rows and columns as the window is tall and wide.
Also, the generation does not appear to update in the window after the first generation is displayed after a few seconds.
I noticed that the variable tNC is often equal to 0 when it should be equal to any number from 0 to 7.
You've got three main problems.
Problem 1: You seem to be generating the next generation as you render cells, which might be okay... but then what are you doing with the screenRows logic (the if statement in your draw() function)?
If I were you, I would split your logic up into two sections: write one function that draws your board, and another function that returns a new board based on the current one. Stop trying to calculate the next generation as you're drawing the current generation, as that's just going to give you a ton of headaches.
I also don't think your logic for switching between the arrays is correct. Which array holds the current generation, and which holds the next generation? Are you sure?
Problem 2: You seem to be switching between pixel sizes and array coordinates. For example, you're drawing each cell at its array index coordinate, but you're drawing them as 2x2 rectangles. This doesn't make a ton of sense, since you're just going to draw over top of it with the next cell anyway. Again, separate your logic: create a function that draws a cell based on the window width and height, an array position, and an array length.
Problem 3: Your print statements are killing your framerate. Print statements are notoriously slow. Your framerate is already pretty slow because of all of the calculations you're doing, but it gets even slower when you print out (960*477*2) things every single frame. This isn't really a logic error, but it makes it harder to see exactly what your program is doing.
The Solution: To fix your problems, I'd recommend refactoring your code quite a bit. If I were you, I would start over with a new program. Then:
Step 1: Separate your drawing logic from your logic for calculating the next generation. Create two functions: one for drawing, and another one that returns a new array based on the current one.
Step 2: In your drawing code, make sure you separate your array indexes and your pixel positions. Maybe write another function that takes a cell position and draws a rectangle based on the window size and the array size.
PS: Are you in the same class as this person? Are you using Daniel Shiffman's code too?

Why does the x value change in this program?

I have created this code, and when I run it, don't get any errors until the arrow leaves the screen (ie: (*I)->x>maxx), after which the O will randomly teleport (Well, I'm guessing its not random, but I'm trying to find a pattern to it).
EDIT: the random teleportation don't seem to occur if I move up, and if I move down, the O is teleported directly to the bottom. Also, a glitch has occured where the O becomes a '>'. (I am trying to figure out how that happens)
EDIT: the transform-into-'>' glitch occurs if the O is at the bottom right of the screen (player.x=9;player.y=9) and the sequence "wqs" is entered.
EDIT: I've removed the class declarations because I am fairly sure that the error is within the _move()s and check().
EDIT: The transform glitch appears to occur when 'wq' is typed, then any other character is entered (ie "skiping" the next move)
EDIT: The tranform glitch occurs when player.x=9; player.y=8; and then 'q' is pressed, the next move the player tranforms into a '>'
This is the code:
#include<vector>
#include<iostream>
#include<string>
using namespace std;
const int maxx = 10, maxy = 10; //two constants that show the size of the sector
char sector[maxx][maxy]; //array of characters used to display the sector
prgm player(0, 0, 'O'); //player definition at x0,y0,and displayed with 'O'
const int vsize = 1; //size of the enemy array (ie: how many enemies there will be
X1 a(9, 5, 'X', 10); //enemy "a", has a move function that moves it back and forth
virus * viral_data[vsize] = {&a}; //array of enemies used to set the sector
vector<antivirus*> antiviral_data; //vector of pointers to "antivirus" the weapon used
vector<antivirus*>::iterator I; //iterator for previous vector
void display() //function to display the sector
{
for(int i = 0; i < maxy; i++)
{
for(int j = 0; j < maxx; j++)
{
cout<<sector[j][i];
}
cout<<endl;
}
return;
}
void p_move() //function to get players input, then move the player or create "antivirus"
{
char dir;
cin>>dir;
switch(dir)
{
case 'w':
player.y--;
break;
case 'a':
player.x--;
break;
case 's':
player.y++;
break;
case 'd':
player.x++;
break;
case 'q':
antiviral_data.push_back(new aX1(player.x, player.y, '>')); //creates a new aX1 at the players position
break;
}
return;
}
void v_move() //uses the enemies move
{
for(int i = 0; i < vsize; i++)
{
viral_data[i]->move();
}
return;
}
void a_move() //uses the weapon (ie: moves the weapon forward)
{
for(I = antiviral_data.begin(); I < antiviral_data.end(); I++)
{
(*I)->move();
}
return;
}
void set() //sets the sector array (char)
{
for(int i = 0; i < maxy; i++)
{
for(int j = 0; j < maxx; j++)
{
sector[j][i] = ' '; makes the entire sector blank
}
}
sector[player.x][player.y]=player.sym; //sets the sector at the player's position to 'O'
for(int i = 0; i < vsize; i++)
{
sector[viral_data[i]->x][viral_data[i]->y] = viral_data[i]->sym; //sets the sector at each enemy's position to be 'X'
}
for(I = antiviral_data.begin(); I < antiviral_data.end(); I++)
{
sector[(*I)->x][(*I)->y] = (*I)->sym; //sets the sector at each weapon's position to be '>'
}
return;
}
void check() //prevents the player from moving off the screen, erases bullet if it moves of the screen (to prevent access to non-allocated memory)
{
if(player.x < 0)
{
player.x = 0;
}
if(player.y < 0)
{
player.y = 0;
}
if(player.x > (maxx-1))
{
player.x = (maxx-1);
}
if(player.y > (maxy-1))
{
player.y = (maxy-1);
}
//PROBLEM APPEARS TO OCCUR HERE
for(I = antiviral_data.begin(); I! = antiviral_data.end();)
{
if((*I)->x > maxx)
{
I = antiviral_data.erase(I);
}
else
{
I++;
}
}
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
return;
}
int main()
{
while(true)
{
set(); //set sector
display(); //display sector
p_move(); //player's move
v_move(); //enemy's move
a_move(); //bullet's move
check();//check moves
}
return 0;
}
In check(), the test
((*I)->x > maxx)
should be
((*I)->x >= maxx)
. This is an off-by-one error that lets the > get one square off the screen. When the display routine tries to display it, it clobbers the display symbol for the X.

Jogl making balls disappear

At the moment am using JOGL for a ball detection program I have been told to make the balls disappear once they get to close to one another.
//this is the method from the main class
public void display(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glColor3f(1.0f, 1.0f, 1.0f);
glut.glutWireCube(2.0f * limit);
for (int i = 0; i < ball.length; ++i)
{
ball[i].display(gl);
}
for (int i = 0; i < ball.length; ++i)
{
ball[i].moveRandomly();
}
//this is the method from the auxiliary class
for (int i = 0; i < ball.length; ++i)
{
for (int j = 0; j < ball.length; ++j)
{
if (ball[i].distanceFrom(ball[j]) <= 10)
{
}
}
}
}
void display(GL gl) {
gl.glLoadIdentity();
gl.glTranslatef(position[0], position[1], position[2]);
gl.glColor3fv(colour, 0);
glut.glutSolidSphere(radius, 10, 10);
//glut.glutSolidTeapot(radius);
}
I tried doing this to no avail the balls disappear all at once, I also tried decreasing the radius with the same results, any sort of point in the right direction would be much appreciated.
The reason they're all disappearing is that each ball is being compared to itself.
Add this in the inner loop before the if statement (this is a quick fix):
if (i == j) continue;
I have more questions than help at the moment.
First, how many balls do you have?
This line bothers me:
if(ballGone == false)
{
glut.glutSolidSphere(radius, 10, 10);
}
If ballGone is false then the ball isn't displayed, but that would imply there is only one ball, so when it is set to false no balls will be displayed.
According to here: http://www.cs.umd.edu/~meesh/kmconroy/JOGLTutorial/ my concern should be justified:
Display is very similar to
java.awt.Component.paint() in that it
is called each time the canvas needs
to be redraw/repainted/redisplayed
So, you may want to look at how you will redraw and make certain that each object that doesn't have a state set to false will be drawn.

Resources