What does this recursion function output? - recursion

I'm just starting to learn recursion and I don't understand the output, which is 39493. Could you explain?
struct Node {
int value;
Node* next;
}
head --> 3 --> 9 --> 4 --> NULL
void f4(Node* n) {
if(n == NULL)
return;
if(n->next == NULL)
cout << n->value << “ ”;
else {
cout << n->value << “ ”;
f4(n->next);
cout << n->value << “ ”;
}
}

Your f4 function prints out a linked list of integers, forwards (from the head/root to the tail) and then backwards. It does this because the inner call of f4 within the else clause is surrounded by two cout statements, which will both print the current node's value, adding a stack frame (new execution context with the next node) in between. The last node (the tail) is captured by if(n->next == NULL), and there's only one cout statement in this clause, so the tail only prints once.
I added a main method to illustrate this:
#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
};
void f4(Node* n) {
// This will never be reached
// except if f4 is called with NULL directly
if(n == NULL)
return;
if(n->next == NULL)
cout << n->value << endl;
else {
cout << n->value << endl;
f4(n->next);
cout << n->value << endl;
}
}
int main() {
cout << "Starting!" << endl;
Node n1 = {1, 0};
Node n2 = {2, &n1};
Node n3 = {3, &n2};
// get pointer to n3 -> n2 -> n1
f4(&n3);
return 0;
}
Output:
Starting!
3
2
1
2
3
To understand the stack frame (recursive call) handling mechanism:
https://www.bottomupcs.com/elements_of_a_process.xhtml.
You might understand it better by adding additional markers to differentiate the cout << n->value << endl on different lines.

Related

Get length scale factor of STEP CAD file with OpenCASCADE

I am trying to get the length unit conversion factor in OpenCASCADE, when importing a STEP format CAD file. In my test file the entity #184 sets the length to meters and during import will be converted to milimeters used by OpenCASCADE internally by default
...
#184=(
LENGTH_UNIT()
NAMED_UNIT(*)
SI_UNIT($,.METRE.)
);
...
I belive the function below is how it should be done, but no matter what i try the "Length_Unit" STEP entity is not matched, and therefore I can't get the scaling factor.
void step_unit_scaling(std::string const &file_name) {
STEPControl_Reader reader;
reader.ReadFile( file_name.c_str() );
const Handle(Interface_InterfaceModel) Model = reader.Model();
Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(Model);
Standard_Integer NbEntities = Model->NbEntities();
for (int i=1; i<=NbEntities; i++) {
Handle(Standard_Transient) enti = aSM->Entity(i);
if (enti->IsKind (STANDARD_TYPE(StepBasic_LengthMeasureWithUnit))) {
Handle(StepBasic_LengthMeasureWithUnit) MWU = Handle(StepBasic_LengthMeasureWithUnit)::DownCast(enti);
Standard_Real scal_mm = MWU->ValueComponent();
std::cout << " --- !!! MATCH !!! --- scal_mm = " << scal_mm << std::endl;
}
}
}
Does anyone know if this is the correct approach, or if there perhaps is a better way.
If you search for an entity of a given type, you should check the types to find an error. The following line will show the actual entity type.
std::cout << "Entity type " << enti->DynamicType()->Name() << std::endl;
When I play with STEP files here, I see that your STEP line leads to an entity of type StepBasic_SiUnitAndLengthUnit. With this code I can test for some expected SI units:
if (enti->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit)))
{
Handle(StepBasic_SiUnitAndLengthUnit) unit =
Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(enti);
if (unit->HasPrefix() &&
(StepBasic_SiUnitName::StepBasic_sunMetre == unit->Name()) &&
(StepBasic_SiPrefix::StepBasic_spMilli == unit->Prefix()))
{
std::cout << "SI Unit is millimetre." << std::endl;
}
else if (!unit->HasPrefix() &&
(StepBasic_SiUnitName::StepBasic_sunMetre == unit->Name()))
{
std::cout << "SI Unit is metre." << std::endl;
}
else
{
std::cout << "I did not understand that unit..." << std::endl;
}
}

"usage:\n\tll '(a+a)'" meaning in ll1 parser program

I am unable to understand what is the role of "usage:\n\tll '(a+a)'" in the code. What is its function?? I am using g++ compiler to compile the code. If more than 2 arguments are passed in command prompt then problem occurs.
#include <iostream>
#include <map>
#include <stack>
enum Symbols {
TS_L_PARENS,
TS_R_PARENS,
TS_A,
TS_PLUS,
TS_EOS,
TS_INVALID,
NTS_S,
NTS_F
};
enum Symbols lexer(char c)
{
switch(c)
{
case '(': return TS_L_PARENS;
case ')': return TS_R_PARENS;
case 'a': return TS_A;
case '+': return TS_PLUS;
case '\0': return TS_EOS;
default: return TS_INVALID;
}
}
int main(int argc, char **argv)
{
using namespace std;
if (argc < 2)
{
cout << **"usage:\n\tll '(a+a)'"** << endl;
return 0;
}
map< enum Symbols, map<enum Symbols, int> > table;
stack<enum Symbols> ss; // symbol stack
char *p; // input buffer
ss.push(TS_EOS); // terminal, $
ss.push(NTS_S); // non-terminal, S
p = &argv[1][0];
table[NTS_S][TS_L_PARENS] = 2;
table[NTS_S][TS_A] = 1;
table[NTS_F][TS_A] = 3;
while(ss.size() > 0)
{
if(lexer(*p) == ss.top())
{
cout << "Matched symbols: " << lexer(*p) << endl;
p++;
ss.pop();
}
else
{
cout << "Rule " << table[ss.top()][lexer(*p)] << endl;
switch(table[ss.top()][lexer(*p)])
{
case 1: // 1. S → F
ss.pop();
ss.push(NTS_F); // F
break;
case 2: // 2. S → ( S + F )
ss.pop();
ss.push(TS_R_PARENS); // )
ss.push(NTS_F); // F
ss.push(TS_PLUS); // +
ss.push(NTS_S); // S
ss.push(TS_L_PARENS); // (
break;
case 3: // 3. F → a
ss.pop();
ss.push(TS_A); // a
break;
default:
cout << "parsing table defaulted" << endl;
return 0;
break;
}
}
}
cout << "finished parsing" << endl;
return 0;
}
cout is the function, "usage:\n\tll '(a+a)'" is a string literal passed to the function. This bit in your question prints:
usage:
ll '(a+a)'

C++ 11 correct way to pass a functional object by reference or pointer?

I am trying to pass a random number generator around my program (I want to use a single one), however I cannot seem to find a way to pass it by reference.
Here is what I have tried thus far:
#include <iostream>
#include <random>
#include <functional>
using namespace std;
void test(const function<int()> arng0, const function<int()> & arng1, const function<int()> & arng2,
const function<int()> frng0, const function<int()> & frng1, const function<int()> & frng2)
{
cerr << "Auto - std::_bind size: " << sizeof(arng0) << endl;
cerr << "Auto - std::_bind & size: " << sizeof(arng1) << endl;
cerr << "Auto - std::_bind ref size: " << sizeof(arng2) << endl;
cerr << "Functional size: " << sizeof(frng0) << endl;
cerr << "Functional & size: " << sizeof(frng1) << endl;
cerr << "Functional ref size: " << sizeof(frng2) << endl;
}
void main()
{
default_random_engine e;
uniform_int_distribution<int> dist(0, 100);
auto autoRng = bind(ref(dist), ref(e));
function<int()> funcRng = bind(ref(dist), ref(e));
test(autoRng, autoRng, ref(autoRng),
funcRng, funcRng, ref(funcRng));
system("Pause");
}
The output is 24 bytes for all of them. I know functional is a heavy wrapper, however passing by reference still should be 4 bytes?
Answer:
void testValue(const function<int()> arng0)
{
arng0();
}
void testRef(const function<int()> & arng0)
{
arng0();
}
{// Pass by value
auto start = high_resolution_clock::now();
for (unsigned int i = 0; i < 100000; i++)
{
testValue(funcRng);
}
auto end = high_resolution_clock::now();
auto total = duration_cast<milliseconds>(end - start).count();
cerr << "TestVal time: " << total << endl;
}
{// Pass by ref
auto start = high_resolution_clock::now();
for (unsigned int i = 0; i < 100000; i++)
{
testRef(funcRng);
}
auto end = high_resolution_clock::now();
auto total = duration_cast<milliseconds>(end - start).count();
cerr << "TestRef time: " << total << endl;
}
Results:
Test Value Time: 179 ms
Test Ref Time: 74 ms
I think you've got it right, passing by reference should be 4 bytes if you're on a 32 bit machine. sizeof is giving you the size of the thing being referenced, not the size of the reference. I don't think you need to use 'ref' at the callsite.
See sizeof documentation here:
http://en.cppreference.com/w/cpp/language/sizeof

What is the defined behavior of SQLite when interleaving statements that affect each other?

In SQLite if I prepare a SELECT statement and begin stepping through it, then before the last row of the results is reached I execute another statement that has an effect on the SELECT statement that I am stepping through, what is the expected result?
I can't find anything in the SQLite documentation about what is supposed to happen but it seems like an extremely common case when programming in a multi-threaded environment.
Below is a c++ file that can be compiled and run on Windows to demonstrate the situation.
#include "stdafx.h"
#include "sqlite3.h"
#include <Windows.h>
#include <iostream>
#include <Knownfolders.h>
#include <Shlobj.h>
#include <wchar.h>
#include <comdef.h>
using namespace std;
int exec_sql(sqlite3 *db, const char* sql)
{
char *errmsg;
int result = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
if (result != SQLITE_OK) {
cout << errmsg << endl;
return -1;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Running jsqltst with SQLite version: ";
cout << sqlite3_libversion();
cout << endl;
PWSTR userhome;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Profile, NULL, NULL, &userhome))) {
cout << "Failed getting user home dir\n";
return -1;
}
wcout << "User home: " << userhome << endl;
wchar_t *ws1 = userhome, *ws2 = L"\\test.sqlite";
wstring dbpath_str(ws1);
dbpath_str += wstring(ws2);
_bstr_t dbpath(dbpath_str.c_str());
cout << "DB path: " << dbpath << endl;
sqlite3 *db;
int result = sqlite3_open_v2(dbpath, &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
if (result != SQLITE_OK) {
cout << sqlite3_errmsg(db) << endl;
return -1;
}
const char * create_stmt = "CREATE TABLE IF NOT EXISTS atable (id INTEGER PRIMARY KEY, name TEXT, number INTEGER);";
if (exec_sql(db, create_stmt) != 0) {
return -1;
}
const char * delete_stmt = "DELETE FROM atable;";
if (exec_sql(db, delete_stmt) != 0) {
return -1;
}
const char * insert_stmt = "INSERT INTO atable (name,number) VALUES ('Beta',77),('Alpha',99);";
if (exec_sql(db, insert_stmt) != 0) {
return -1;
}
sqlite3_stmt* select_ss;
const char * select_stmt = "SELECT * FROM atable;";
result = sqlite3_prepare_v2(db, select_stmt, -1, &select_ss, NULL);
if (result != SQLITE_OK) {
cout << sqlite3_errmsg(db) << endl;
return -1;
}
int i = 0;
boolean gotrow;
do {
result = sqlite3_step(select_ss);
gotrow = result == SQLITE_ROW;
if (gotrow) {
i++;
cout << "I got a row!" << endl;
if (i == 1) {
if (exec_sql(db, insert_stmt) != 0) {
return -1;
}
}
}
} while (gotrow);
cout << "Last result: " << result << ", errstr: " << sqlite3_errstr(result) << endl;
result = sqlite3_finalize(select_ss);
if (result != SQLITE_OK) {
cout << sqlite3_errmsg(db) << endl;
return -1;
}
return 0;
}
SQLite's behaviour for concurrent statements in the same transaction is neither documented nor defined.
As you have seen, newly inserted records might be seen when a SELECT's cursor has not yet reached that part of the table.
However, if SQLite needed to create a temporary result table for sorting or grouping, later changes in the table will not appear in that result.
Whether you have a temporary table or not might depend on decisions made by the query optimizer, so this is often not predictable.
If multiple threads access the same connection, SQLite will lock the DB around each sqlite3_step call.
This prevent data corruption, but you will still have the problem that automatic transaction end when their last active statement ends, and that explicit transaction will fail the COMMIT if there is some other active statement.
Multi-threaded programs are better off using (at least) one connection per thread.

Stack-recursion program problems

I am a novice C++ coder and obviously not very good at it. I am having an immense amount of trouble with this program.
I am getting syntax errors on my opening and closing parenthesis on my functions, syntax errors on my "<" in my header cpp file, and errors that I'm missing parenthesis.
My first stack is not recognized (main driver file) and in my StackType.cpp file - original is an "undeclared identifier".
Lastly, the left of Push must have class/struct/union - in my for loop when filling the first stack with the rings.
I apologize for all of these issues in advance. Any help you could give me would be greatly appreciated!
Thank you.
======================Stack Header================================
// File: StackType.h
// Stack template class definition.
// Dynamic array implementation
#ifndef StackType
#define StackType
template <class ItemType>
class StackType
{
private:
int ItemType;
ItemType *myStack; // pointer to dynamic array
int _top, _maxSize; // using underscores to remind that it's private
public:
StackType(int numRings = 50); // Constructor
StackType (const StackType<ItemType>&); // Copy Constructor
// Member Functions
void Push(ItemType); // Push
void Pop(ItemType &); // Pop
void stackTop(ItemType &) const; // retrieve top
bool stackIsEmpty() const; // Test for Empty stack
bool stackIsFull() const; // Test for Full stack
~StackType(); // Destructor
};
#endif
=====================Stack cpp file==================================
#include "StackType.h"
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
// Constructor with argument, size is numRings, limit is 50 (set in .h header)
template <class ItemType>
StackType<ItemType>::StackType()
{
_maxSize = numRings;
_top = -1;
}
// Copy Constructor
template <class ItemType>
StackType<ItemType>::StackType(const StackType<ItemType>& original :
_maxSize(original._maxSize), top(original._top)
{
myStack = new ItemType[_maxSize];
for (int i = 0; i <= top; i++) myStack[i] = original.myStack[i];
}
// Destructor
template <class ItemType>
StackType<ItemType>::~StackType()
{
delete [] myStack;
}
// Push
template <class ItemType>
void StackType<ItemType>::Push(StackType<ItemType> ringVal)
{
if(stackIsFull()) cout << "\t There is not enough available memory = the stack is
full!" << endl;
else myStack[++_top] = ringVal;
}
// Pop
template <class ItemType>
void StackType<ItemType>::Pop(StackType<ItemType> &ringVal)
{
if(stackIsEmpty()) cout << "\t The stack is empty!" << endl;
else ringVal = myStack[_top--];
}
// Retrieve stack top without removing it
template <class ItemType>
void StackType<ItemType>::stackTop(StackType<ItemType> &ringVal) const
{
if(stackIsEmpty()) cout << "The stack is empty!";
else ringVal = myStack[_top];
}
// Test for Empty stack
template <class ItemType>
bool StackType<ItemType>::stackIsEmpty() const
{
return (_top < 0);
}
// Test for Full stack
template <class ItemType>
bool StackType<class ItemType>::stackIsFull() const
{
return (_top >= (_maxSize - 1));
}
// end StackType.cpp
=========================Main Driver file=======================================
#include "StackType.h"
#ifdef _DEBUG
#include "StackType.cpp"
#endif // _DEBUG
#include <stack>
#include "StdAfx.h"
#include <iostream>
using namespace std;
// Global Variable - Counter to display the number of moves.
int count = 0;
class StackType;
// Functions Prototypes
void MoveRings(StackType<ItemType>&, StackType<ItemType>&);
// Function to move the rings
void Pegs(int D,StackType<ItemType>& b,StackType<ItemType>& e, StackType<ItemType>& h);
// This is a recursive function.
void Display (int, StackType <ItemType>& , StackType<ItemType>&, StackType<ItemType>&);
// Function to display the pegs
// Main - Driver File
int main()
{
// create 3 empty stacks
StackType<ItemType> FirstPeg; // Receiving an error that this is not identified
StackType<ItemType> EndPeg;
StackType<ItemType> HelperPeg;
// Number of rings.
int numRings;
cout << "\n\t *********** Rings to Pegs (Towers of Hanoi) ***********\n" << endl;
cout << "\t Please Enter the number of rings you want to play with: ";
// Input number of rings
cin >> numRings;
cout << endl;
while(numRings < 0 || isalpha(numRings)) // To make sure that the user did not
// enter an invalid number
{
cout << " Your entry is invalid. Please use only integers. Please re-
enter: ";
cin >> numRings;
cout << endl;
}
for(int i = 1; i <= numRings; i++)
// Fill the first peg with the number of rings.
{
FirstPeg.Push(i);
}
Pegs(int, StackType<ItemType>&, StackType<ItemType>&, StackType<ItemType>&);
// To call the recursive function that will move the rings
Display (int, StackType<ItemType>&, StackType<ItemType>&, StackType<ItemType>&);
// To call the display function
cin.clear();
cin.ignore('\n');
cin.get();
return 0;
}
// This function will move an ring from first peg to the second peg
void MoveRings(StackType<ItemType>& beg, StackType<ItemType>& theEnd) //End
{
int r; // disk will be removed from one stack and added to the other
beg.Pop(r);//pop from source
theEnd.Push(r);//and move to target
}
// This function displays the moves
void Display(int R, StackType<ItemType>& toBegin , StackType<ItemType>& toEnd,
StackType<ItemType>& toHelp)
{
StackType<int> B;// create temporarily first stack
StackType<int> E;// create temporarily End(End) stack
StackType<int> H;// create temporarily helper stack
for(int i = 1; i <= R; i++)
{
toBegin.Pop(i);//moves the ring from source
B.Push(i);//to the temporarily stack to display it
cout << "Beginning Peg:" << &B << endl;
toEnd.Pop(i);//moves the ring from source
E.Push(i);//to the temporarily stack to display it
cout << " End(Final) Peg: " << &E << endl;
toHelp.Pop(i);//moves the ring from source
H.Push(i);//to the temporarily stack to display it
cout << " Helper Peg:" << &H << endl;
}
}
//-------------------------------------------------------------------
void Pegs(int D,StackType<ItemType>& b,StackType<ItemType>& e,StackType<ItemType>& h)
// This is a recursive function.
{
if (D == 0) // The base
{
return 1;
}
else if(D == 1) // If there is only one ring, move this ring from the
// first peg to the end(final) peg
{
MoveRings(b, e); // moves the ring from the first to the end(final) peg
cout<<" Really? You have entered one ring..." << endl;
cout<<" It moves directly from the first peg to the End peg." << endl;
count++; // increment the number of moves
cout << "There has been " << count << " move. "<< endl;// display the
// number of moves
Display (D, b, e, h);
}
else if (D > 1) // a recursive function in order to move the rings
{
Pegs(D - 1, b, e, h); // to move N-1 rings from the first peg to the
// end(final) peg by using the helper peg
MoveRings(b, e);// to move the last ring to the end(final) peg
count++; // increment the number of steps before displaying
cout << "There has been " << count << " moves. "<< endl;
Pegs(D - 1, b, e, h);
// to move N-1 rings from the helper peg to the end(final) peg with the help of
// first peg
//Display ( D(rings), First Peg, End(Final) Peg, Helper Peg );
}
}
One problem that I can see immediately is that your header file defines StackType to prevent double inclusion, which is also used as a class name. After #define StackType, it ends up being a macro that expands to nothing, so your code looks like class { ... }.
You should use a symbol to prevent double inclusion that isn't used for anything else. The typical thing to use is STACKTYPE_H for a file called StackType.h.
Once you've fixed this, some other problems you're experiencing might go away. Please come back with an update if you're having more problems, and post the exact compiler errors if you do.

Resources