flatten a binary tree into a linked list with rotations - linked-list

i want to flatten a binary tree and transforme it into a linked list using rotations. we should have two types of linked lists, the first type is when all the nodes are in the left side ,ie: our tree will only have left children and all the right children will become NULL , we ll do this type of transformation by doing a left rotation to all the nodes that have a right child.
the second type is to have a tree that only have right childs with the left childs set to NULL, we do such transformation by doing a right rotation for all the nodes that have a left child. tha
i didn't know how to write the algorithme of this transformation although i tried a lot, i just need the algorithme of this transformation or the code in C.
here's the data structure:
typedef struct Tib Type_Tib ;
typedef Type_Tib * Typestr_Tib ;
typedef int Type1_Tib ;
typedef bool Type2_Tib ;
struct Tib
{
Type1_Tib Champ1 ;
Type2_Tib Champ2 ;
};
Type1_Tib Struct1_Tib ( Typestr_Tib S)
{
return S->Champ1 ;
}
Type2_Tib Struct2_Tib ( Typestr_Tib S)
{
return S->Champ2 ;
}
void Aff_struct1_Tib ( Typestr_Tib S, Type1_Tib Val )
{
S->Champ1 = Val ;
}
void Aff_struct2_Tib ( Typestr_Tib S, Type2_Tib Val )
{
S->Champ2 = Val ;
}
/** Arbres de recherche binaire **/
typedef Typestr_Tib Typeelem_ATib ;
typedef struct Noeud_ATib * Pointeur_ATib ;
struct Noeud_ATib
{
Typeelem_ATib Val ;
Pointeur_ATib Fg ;
Pointeur_ATib Fd ;
Pointeur_ATib Pere ;
} ;
hope you can help me because i REALLY need this algorithme.

Related

Implicit vector conversion in ImGui (ImVec <--> glm::vec)

I am trying to get the implicit conversion between ImGui's (ImVec) and glm's (glm::vec) vector types working.
In here I read, that I have to change the following lines in the imconfig.h file:
#define IM_VEC2_CLASS_EXTRA \
constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
operator MyVec4() const { return MyVec4(x,y,z,w); }
The first line makes sense to me, but I don't see the point of the second making a new constructor for MyVec.
Since I really have no idea what is going on here, I just tried to replace MyVecN with either glm::vecN or vecN, but neither works.
Also I don't get why there are these backslashes, I guess they're to comment out? Either way, I removed them, and it still didn't work.
The compiler ends up throwing tons of errors so I don't know where the problem is.
You have to defined/include your struct before including imgui:
// define glm::vecN or include it from another file
namespace glm
{
struct vec2
{
float x, y;
vec2(float x, float y) : x(x), y(y) {};
};
struct vec4
{
float x, y, z, w;
vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {};
};
}
// define extra conversion here before including imgui, don't do it in the imconfig.h
#define IM_VEC2_CLASS_EXTRA \
constexpr ImVec2(glm::vec2& f) : x(f.x), y(f.y) {} \
operator glm::vec2() const { return glm::vec2(x, y); }
#define IM_VEC4_CLASS_EXTRA \
constexpr ImVec4(const glm::vec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
operator glm::vec4() const { return glm::vec4(x,y,z,w); }
#include "imgui/imgui.h"
And the backslashes \ are just line breaks in the #define, to specify a continuous definition

Dijkstra Algorithm infinite loop

I'm learning about shortest path algorithms, and I'm trying to implement A Dijkstra Algorithm that takes the input from a file like this:
7
A
B
C
D
E
F
G
A B 21
A C 14
B E 5
B D 7
D F 3
E C 44
E G 53
E D 123
G F 51
The problem is when i add an extra edge to some vertex like D B 12,:
DIJKSTRA ALGORITHM:
public Set<Vertex> dijkstraAlgo(Graph G, int s) {
initializeSingleSource(G, s);
Set<Vertex> set = new HashSet<Vertex>(); // intitially empty set of
// vertexes
Queue<Vertex> Q = new PriorityQueue<Vertex>(10, new VertexComparator()); // min
// priority
// queue
for (Vertex v : G.vertices) { // add source to priority queue
Q.add(G.vertices[s]);
}
while (Q.size() != 0) {
Vertex u = Q.poll(); // extract vertex which have min distance in
// priority queue
set.add(u); // add that vertex to set
for (String vertexId : u.neighbours.keySet()) { // see neighbours of
// vertex extracted
int vertexNum = indexForName(G, vertexId);
Vertex v = G.vertices[vertexNum];
int w = weightFunc(G, u, v);
relax(u, v, w);
Q.add(v);
}
}
return set;
}
READING THE FILE:
public class Graph {
Vertex[] vertices;
public Graph(String file) throws FileNotFoundException{
Scanner sc = new Scanner(new File(file));
vertices=new Vertex[sc.nextInt()];
for (int v = 0; v < vertices.length; v++){
vertices[v] = new Vertex(sc.next());
}
while (sc.hasNext()) {
int v1= indexForName(sc.next()); //read source vertex
String destination=sc.next(); //read destination vertex
int w=sc.nextInt(); //read weight of the edge
vertices[v1].neighbours.put(destination, w); //put the edge adjacent to source vertex
}
sc.close();
}
MAIN:
public static void main(String[] args) throws FileNotFoundException {
String fileName = "Dijikstra.txt";
Dijkstra dijkstra = new Dijkstra(fileName);
Set<Vertex> vertexInfo = dijkstra.dijkstraAlgo(dijkstra.graph, 0);
System.out
.println("Printing min distance of all vertexes from source vertex A ");
for (Vertex v : vertexInfo) {
System.out.println("Id: " + v.id + " distance: " + v.d + " Comming From " + v.p);
}
}
VERTEX:
class Vertex{
String id;
int d; //to store min distance from source
Vertex p; //to store last vertex from which min distance is reached
Map<String,Integer> neighbours; //to store edges of adjacent to the vertex
public Vertex(String id){
this.id=id;
neighbours=new HashMap<String,Integer>();
}
}
for (Vertex v : G.vertices) { // add source to priority queue
Q.add(G.vertices[s]);
}
Why are you adding every Vertex to the Priority Queue instead of just the initial one? What does your Vertex class look like?

How to reduce parser stack or 'unshift' the current token depending on what follows?

Given the following language described as:
formally: (identifier operator identifier+)*
in plain English: zero or more operations written as an identifier (the lvalue), then an operator, then one or more identifiers (the rvalue)
An example of a sequence of operations in that language would be, given the arbitrary operator #:
A # B C X # Y
Whitespace is not significant and it may also be written more clearly as:
A # B C
X # Y
How would you parse this with a yacc-like LALR parser ?
What I tried so far
I know how to parse explicitly delimited operations, say A # B C ; X # Y but I would like to know if parsing the above input is feasible and how. Hereafter is a (non-functional) minimal example using Flex/Bison.
lex.l:
%{
#include "y.tab.h"
%}
%option noyywrap
%option yylineno
%%
[a-zA-Z][a-zA-Z0-9_]* { return ID; }
# { return OP; }
[ \t\r\n]+ ; /* ignore whitespace */
. { return ERROR; } /* any other character causes parse error */
%%
yacc.y:
%{
#include <stdio.h>
extern int yylineno;
void yyerror(const char *str);
int yylex();
%}
%define parse.lac full
%define parse.error verbose
%token ID OP ERROR
%left OP
%start opdefs
%%
opright:
| opright ID
;
opdef: ID OP ID opright
;
opdefs:
| opdefs opdef
;
%%
void yyerror(const char *str) {
fprintf(stderr, "error#%d: %s\n", yylineno, str);
}
int main(int argc, char *argv[]) {
yyparse();
}
Build with: $ flex lex.l && yacc -d yacc.y --report=all --verbose && gcc lex.yy.c y.tab.c
The issue: I cannot get the parser to not include the next lvalue identifier to the rvalue of the first operation.
$ ./a.out
A # B C X # Y
error#1: syntax error, unexpected OP, expecting $end or ID
The above is always parsed as: reduce(A # B reduce(C X)) # Y
I get the feeling I have to somehow put a condition on the lookahead token that says that if it is the operator, the last identifier should not be shifted and the current stack should be reduced:
A # B C X # Y
^ * // ^: current, *: lookahead
-> reduce 'A # B C' !
-> shift 'X' !
I tried all kind of operator precedence arrangements but cannot get it to work.
I would be willing to accept a solution that does not apply to Bison as well.
A naïve grammar for that language is LALR(2), and bison does not generate LALR(2) parsers.
Any LALR(2) grammar can be mechanically modified to produce an LALR(1) grammar with a compatible parse tree, but I don't know of any automatic tool which does that.
It's possible but annoying to do the transformation by hand, but be aware that you will need to adjust the actions in order to recover the correct parse tree:
%{
typedef struct IdList { char* id; struct IdList* next; };
typedef struct Def { char* lhs; IdList* rhs; };
typedef struct DefList { Def* def; struct DefList* next; };
%}
union {
Def* def;
DefList* defs;
char* id;
}
%type <def> ophead
%type <defs> opdefs
%token <id> ID
%%
prog : opdefs { $1->def->rhs = IdList_reverse($1->def->rhs);
DefList_show(DefList_reverse($1)); }
ophead: ID '#' ID { $$ = Def_new($1);
$$->rhs = IdList_push($$->rhs, $3); }
opdefs: ophead { $$ = DefList_push(NULL, $1); }
| opdefs ID { $1->def->rhs = IdList_push($1->def->rhs, $2); }
| opdefs ophead { $1->def->rhs = IdList_reverse($1->def->rhs);
$$ = DefList_push($1, $2); }
This precise problem is, ironically, part of bison itself, because productions do not require a ; terminator. Bison uses itself to generate a parser, and it solves this problem in the lexer rather than jumping through the loops as outlined above. In the lexer, once an ID is found, the scan continues up to the next non-whitespace character. If that is a :, then the lexer returns an identifier-definition token; otherwise, the non-whitespace character is returned to the input stream, and an ordinary identifier token is returned.
Here's one way of implementing that in the lexer:
%x SEEK_AT
%%
/* See below for explanation, if needed */
static int deferred_eof = 0;
if (deferred_eof) { deferred_eof = 0; return 0; }
[[:alpha:]][[:alnum:]_]* yylval = strdup(yytext); BEGIN(SEEK_AT);
[[:space:]]+ ; /* ignore whitespace */
/* Could be other rules here */
. return *yytext; /* Let the parser handle errors */
<SEEK_AT>{
[[:space:]]+ ; /* ignore whitespace */
"#" BEGIN(INITIAL); return ID_AT;
. BEGIN(INITIAL); yyless(0); return ID;
<EOF> BEGIN(INITIAL); deferred_eof = 1; return ID;
}
In the SEEK_AT start condition, we're only interested in #. If we find one, then the ID was the start of a def, and we return the correct token type. If we find anything else (other than whitespace), we return the character to the input stream using yyless, and return the ID token type. Note that yylval was already set from the initial scan of the ID, so there is no need to worry about it here.
The only complicated bit of the above code is the EOF handling. Once an EOF has been detected, it is not possible to reinsert it into the input stream, neither with yyless nor with unputc. Nor is it legal to let the scanner read the EOF again. So it needs to be fully dealt with. Unfortunately, in the SEEK_AT start condition, fully dealing with EOF requires sending two tokens: first the already detected ID token, and then the 0 which yyparse will recognize as end of input. Without a push-parser, we cannot send two tokens from a single scanner action, so we need to register the fact of having received an EOF, and check for that on the next call to the scanner.
Indented code before the first rule is inserted at the top of the yylex function, so it can declare local variables and do whatever needs to be done before the scan starts. As written, this lexer is not re-entrant, but it is restartable because the persistent state is reset in the if (deferred_eof) action. To make it re-entrant, you'd only need to put deferred_eof in the yystate structure instead of making it a static local.
Following rici's useful comment and answer, here is what I came up with:
lex.l:
%{
#include "y.tab.h"
%}
%option noyywrap
%option yylineno
%%
[a-zA-Z][a-zA-Z0-9_]* { yylval.a = strdup(yytext); return ID; }
# { return OP; }
[ \t\r\n]+ ; /* ignore whitespace */
. { return ERROR; } /* any other character causes parse error */
%%
yacc.y:
%{
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
extern int yylineno;
void yyerror(const char *str);
int yylex();
#define STR_OP " # "
#define STR_SPACE " "
char *concat3(const char *, const char *, const char *);
struct oplist {
char **ops;
size_t capacity, count;
} my_oplist = { NULL, 0, 0 };
int oplist_append(struct oplist *, char *);
void oplist_clear(struct oplist *);
void oplist_dump(struct oplist *);
%}
%union {
char *a;
}
%define parse.lac full
%define parse.error verbose
%token ID OP END ERROR
%start input
%%
opbase: ID OP ID {
char *s = concat3($<a>1, STR_OP, $<a>3);
free($<a>1);
free($<a>3);
assert(s && "opbase: allocation failed");
$<a>$ = s;
}
;
ops: opbase {
$<a>$ = $<a>1;
}
| ops opbase {
int r = oplist_append(&my_oplist, $<a>1);
assert(r == 0 && "ops: allocation failed");
$<a>$ = $<a>2;
}
| ops ID {
char *s = concat3($<a>1, STR_SPACE, $<a>2);
free($<a>1);
free($<a>2);
assert(s && "ops: allocation failed");
$<a>$ = s;
}
;
input: ops {
int r = oplist_append(&my_oplist, $<a>1);
assert(r == 0 && "input: allocation failed");
}
;
%%
char *concat3(const char *s1, const char *s2, const char *s3) {
size_t len = strlen(s1) + strlen(s2) + strlen(s3);
char *s = malloc(len + 1);
if (!s)
goto concat3__end;
sprintf(s, "%s%s%s", s1, s2, s3);
concat3__end:
return s;
}
int oplist_append(struct oplist *oplist, char *op) {
if (oplist->count == oplist->capacity) {
char **ops = realloc(oplist->ops, (oplist->capacity + 32) * sizeof(char *));
if (!ops)
return 1;
oplist->ops = ops;
oplist->capacity += 32;
}
oplist->ops[oplist->count++] = op;
return 0;
}
void oplist_clear(struct oplist *oplist) {
if (oplist->count > 0) {
for (size_t i = 0; i < oplist->count; ++i)
free(oplist->ops[i]);
oplist->count = 0;
}
if (oplist->capacity > 0) {
free(oplist->ops);
oplist->capacity = 0;
}
}
void oplist_dump(struct oplist *oplist) {
for (size_t i = 0; i < oplist->count; ++i)
printf("%2zu: '%s'\n", i, oplist->ops[i]);
}
void yyerror(const char *str) {
fprintf(stderr, "error#%d: %s\n", yylineno, str);
}
int main(int argc, char *argv[]) {
yyparse();
oplist_dump(&my_oplist);
oplist_clear(&my_oplist);
}
Output with A # B C X # Y:
0: 'A # B C'
1: 'X # Y'

Storing functions in an array and applying them to an array of numbers

I've prototyped an algorithm for my iOS game in Python, and I need to rewrite in in ObjC. Basically, I have a board of 16 numbers, and I want to loop through every number three times and the four functions I'm using (add, subtract, multiply, exponentiate). 1+2+3, 2*3-4, 3^4-5, 9-4^3, etc., but without order of operations (first operation is always done first).
What I would like is an overview of how this might be implemented in Objective-C. Specifically, what is the equivalent of an array of functions in Objective-C? Is there an easy way to implement it with selectors? What's the best structure to use for loops with numbers? Array of NSIntegers, array of ints, NSArray/NSMutableArray of NSNumbers?
import random as rand
min = 0
max = 9
max_target = 20
maximum_to_calculate = 100
def multiply(x, y):
return x * y
def exponate(x, y):
return x ** y
def add(x, y):
return x + y
def subtract(x, y):
return x - y
function_array = [multiply, exponate, add, subtract]
board = [rand.randint(min, max) for i in xrange(0, 16)]
dict_of_frequencies = {}
for a in board:
for b in board:
for first_fun in function_array:
first_result = first_fun(a, b)
for c in board:
for second_fun in function_array:
final_result = second_fun(first_result, c)
if final_result not in dict_of_frequencies:
dict_of_frequencies[final_result] = 0
dict_of_frequencies[final_result] += 1
The most convenient way in Objective-C to construct an array of functions would be to use Blocks:
typedef NSInteger (^ArithmeticBlock)(NSInteger, NSInteger);
ArithmeticBlock add = ^NSInteger (NSInteger x, NSInteger y){
return x + y;
};
ArithmeticBlock sub = ^NSInteger (NSInteger x, NSInteger y){
return x - y;
};
NSArray * operations = #[add, sub];
Since there's no great way to perform arithmetic on NSNumbers, it would probably be best to create and store the board's values as primitives, such as NSIntegers, in a plain C array. You can box them up later easily enough, if necessary -- #(boardValue) gives you an NSNumber.
If you want to do it with straight C function pointers, something like this will do it:
#include <stdio.h>
#include <math.h>
long add(int a, int b) {
return a + b;
}
long subtract(int a, int b) {
return a - b;
}
long multiply(int a, int b) {
return a * b;
}
long exponate(int a, int b) {
return pow(a, b);
}
int main(void) {
long (*mfunc[4])(int, int) = {add, subtract, multiply, exponate};
char ops[4] = {'+', '-', '*', '^'};
for ( int i = 0; i < 4; ++i ) {
printf("5 %c 9 = %ld\n", ops[i], mfunc[i](5, 9));
}
return 0;
}
and gives the output:
paul#MacBook:~/Documents/src$ ./rndfnc
5 + 9 = 14
5 - 9 = -4
5 * 9 = 45
5 ^ 9 = 1953125
paul#MacBook:~/Documents/src$
Function pointer syntax can be slightly convoluted. long (*mfunc[4])(int, int) basically translates to defining a four-element array, called mfunc, of pointers to functions returning long and taking two arguments of type int.
Maddy is right. Anyway, I'll give it a try just for the fun of it.
This has never seen a compiler. So please forgive me all the typos and minor syntax errors in advance.
#include <stdlib.h>
...
const int MIN = 0;
const int MAX = 9;
const int MAX_TARGET = 20;
const int MAX_TO_CALCULATE = 100;
...
- (int) multiply:(int)x with:(int)y { return x * y; }
- (int) exponate:(int)x with:(int)y { return x ^ y; }
- (int) add:(int)x to:(int)y { return x + y; }
- (int) substract:(int)x by:(int)y { return x - y; }
// some method should start here, probably with
-(void) someMethod {
NSArray *functionArray = [NSArray arrayWithObjects: #selector(multiply::), #selector(exponate::), #selector(add::), #substract(multiply::), nil]; // there are other ways of generating an array of objects
NSMutableArray *board = [NSMutableArray arrayWithCapacity:16]; //Again, there are other ways available.
for (int i = 0; i < 16; i++) {
[board addObject:#(arc4random() % (MAX-MIN) + MIN)];
}
NSMutableDictionary dictOfFrequencies = [[NSMutableDictionary alloc] init];
for (NSNumber a in board)
for (NSNumber b in board)
for (SEL firstFun in functionArray) {
NSNumber firstResult = #([self performSelector:firstFun withObject:a withObject:b]);
NSNumber countedResults = [dictOfFrequencies objectForKey:firstResult];
if (countedResults) {
[dictOfFrequencies removeObjectForKey:firstResult];
countedResults = #(1 + [countedResults intValue]);
} else {
countedResults = #1; // BTW, using the # followed by a numeric expression creates an NSNumber object with the value 1.
}
[dictOfFrequencies setObject:countedResults forKey:firstResult];
}
}
Well, let me add some comments before others do. :-)
There is no need for objective c. You python code is iterative therefore you can implement it in plain C. Plain C is available where ever Objective C is.
If you really want to go for Objective-C here then you should forget your python code and implement the same logic (aiming for the same result) in Objective-C in an OOP style. My code really tries to translate your code as close as possible. Therefore my code is far far away from neither beeing good style nor maintainable nor proper OOP. Just keep that in mind before you think, ObjC was complicated compared to python :-)

Polygon to contour in OpenCV? e.g. an opposite of cvApproxPoly()?

Is there an easy and fast OpenCV solution that will convert a set of CvPoint vertices defining a polygon, to a contour with many more vertices?
I have simple polygons in one space, and I want to transform the polygons into another space, where straight lines will become curvy. Thus its important that I add more vertices to my straight lines. This would be the opposite of cvApproxPoly().
Internally cvPolyLine() is doing exactly what I want. Is there any way to access that?
I am using OpenCV 1.1.
So I wrote my own function GetLineFromEndPts() that should solve this problem in a kludgy way. Given two points a and b, this function outputs a list of points on a line connecting a and b. Therefore, to find a contour with many points from a polygon defined by a few vertices, I can run this function on consecutive pairs of vertices.
/*
* Given two points a and b , and a sequence of CvPoints
* this function will find the points that walk the line
* between a and b and append those
* the end of the sequence
*
* Note that the output includes point a, but not point b.
*/
int GetLineFromEndPts(CvPoint a, CvPoint b, CvSeq* contour){
if (contour==NULL) {
printf("ERROR! contour in GetLineFromEndPts() is NULL!\n");
return -1;
}
float d=dist(a,b);
/** Normalized vector with components i and j pointing along the line**/
float ihat= ( (float) (b.x -a.x) ) /d;
float jhat= ( (float) (b.y -a.y) ) /d;
CvPoint currPt; /* Current Point On integer grid*/
CvPoint prevPt=a; /* Prev Point on integer grid */
currPt=a;
/** Prepare Writer for Appending Points to Seq **/
CvSeqWriter writer;
cvStartAppendToSeq( contour, &writer );
int t;
float tempPtx;
float tempPty;
int signx=1;
int signy=1;
for (t = 0; t < (int) (d+0.5) ; ++t) {
/** Our target point is now defined by a parametric equation **/
tempPtx=(float) t * ihat + (float) a.x;
tempPty=(float) t * jhat + (float) a.y;
/** We will want to round and we need to know the number's sign to round correctly **/
if (tempPtx<0) {
signx=-1;
} else {
signx=1;
}
if (tempPty<0) {
signy=-1;
} else{
signy=1;
}
/** Round to an integer value. Note that we need the sign before we add/subtract .5 **/
currPt=cvPoint((int) ( tempPtx + (float) signx * 0.5 ) ,
(int) ( tempPty + (float) signy * 0.5 ));
/** If first point, OR the current approx point is not the same as prev **/
if ( t==0 || !( currPt.x == prevPt.x && currPt.y == prevPt.y ) ){
/** Write out the point **/
CV_WRITE_SEQ_ELEM( currPt, writer );
printf(" t=%d\n",t);
printf(" currPt.x=%d\n",currPt.x);
printf(" currPt.y=%d\n",currPt.y);
}
prevPt=currPt;
}
cvEndWriteSeq( &writer );
return 1;
}
And associated functions:
/*
* Returns the squared distance between two points
*/
int sqDist(CvPoint pta, CvPoint ptb){
return ( ((pta.x - ptb.x)*(pta.x - ptb.x) ) + ((pta.y - ptb.y)*(pta.y - ptb.y) ) );
}
And finally:
/*
* Finds the distance between two points
* and returns the value as a float
*/
float dist(CvPoint a, CvPoint b){
return ( sqrt( (float) sqDist(a,b)) );
}
So, for example, if called with:
GetLineFromEndPts(cvPoint(0,0),cvPoint(10,15),test);
the function outputs:
t=0
currPt.x=0
currPt.y=0
t=1
currPt.x=1
currPt.y=1
t=2
currPt.x=1
currPt.y=2
t=3
currPt.x=2
currPt.y=2
t=4
currPt.x=2
currPt.y=3
t=5
currPt.x=3
currPt.y=4
t=6
currPt.x=3
currPt.y=5
t=7
currPt.x=4
currPt.y=6
t=8
currPt.x=4
currPt.y=7
t=9
currPt.x=5
currPt.y=7
t=10
currPt.x=6
currPt.y=8
t=11
currPt.x=6
currPt.y=9
t=12
currPt.x=7
currPt.y=10
t=13
currPt.x=7
currPt.y=11
t=14
currPt.x=8
currPt.y=12
t=16
currPt.x=9
currPt.y=13
t=17
currPt.x=9
currPt.y=14

Resources