1
0
Fork 0

Compare commits

...

27 Commits

Author SHA1 Message Date
Eric Teunis de Boone 3c197c647d Commit all PDFs belonging to this course 2021-11-03 15:09:33 +01:00
Eric Teunis de Boone 69ea1f7005 Ex4.3: Optional Substring 2020-07-09 23:47:59 +02:00
Eric Teunis de Boone c6e48cf47c Ex10: Successfull pyBind11 2020-07-09 22:52:04 +02:00
Eric Teunis de Boone c5f7489717 Ex10: CPP code working 2020-07-09 21:22:39 +02:00
Eric Teunis de Boone 5fbca6ec01 Ex10: almost able to compile 2020-07-09 18:09:10 +02:00
Eric Teunis de Boone 70f6134222 Ex9 feedback: missed the fourth assignment 2020-07-09 17:46:23 +02:00
Eric Teunis de Boone 6d63474276 Ex8.* feedback: syntactic sugar 2020-07-09 17:07:15 +02:00
Eric Teunis de Boone 815e771d7d Ex8.1 feedback: emphasize uniqueness within set in comment 2020-07-09 17:00:57 +02:00
Eric Teunis de Boone 83318d7e73 Ex7.4 feedback: change _s pointer to member attribute 2020-07-09 16:58:05 +02:00
Eric Teunis de Boone f0ec419a8a Ex7.3 feedback: missed conclusion 2020-07-09 16:45:01 +02:00
Eric Teunis de Boone 599b73b216 Ex10: initial header files 2020-07-08 16:56:24 +02:00
Eric Teunis de Boone 817e492ef0 Ex6.3 feedback: Remove Dynamic Allocation in Stack 2020-07-01 19:18:47 +02:00
Eric Teunis de Boone 5ac86eccb3 Ex6.2 feedback: forgot to copy _default in Array copy ctor. 2020-07-01 17:47:24 +02:00
Eric Teunis de Boone 969ee37aa8 Ex5.3 feedback: use a string when reading from linebuffer
We do not know how long the words will be (except not longer than a line) so a std::string more suitable for this.
Plus, we can now use  instead of checking for a  character ourselves.
2020-07-01 17:45:17 +02:00
Eric Teunis de Boone b4edcd7ed1 Ex5.3 feedback: wrong wordcount due to empty lines 2020-07-01 17:40:47 +02:00
Eric Teunis de Boone 2c33d4246c Ex4.2 feedback: fix const_cast implementation for CaloGrid::cell() 2020-07-01 16:56:00 +02:00
Eric Teunis de Boone c79e9e4af7 Ex4.2 feedback: setup Calorimeter class 2020-07-01 16:29:22 +02:00
Eric Teunis de Boone 9ea32ed1c0 Ex4.3 feedback: declare global String operator+() in header file 2020-07-01 15:11:48 +02:00
Eric Teunis de Boone ff96644889 Ex4.1 feedback: copy member objects in the correct way in copy constructor 2020-07-01 14:34:41 +02:00
Eric Teunis de Boone bf04d5a4b2 Ex2.2 feedback: explicit definition for `int,double` and `double,int` signatures for `min` function 2020-07-01 14:11:07 +02:00
Eric Teunis de Boone 52d1f4e4e9 Ex4.2 feedback: CaloGrid::cell() return pointer instead of object 2020-06-30 14:00:21 +02:00
Eric Teunis de Boone 83bf4e34dc Ex4.2 feedback: CaloCell return type 2020-06-30 13:58:41 +02:00
Eric Teunis de Boone f5524b020c Ex4.1 feedback: Copy constructors of dependency objects were not called when copying Telephone 2020-06-30 12:57:01 +02:00
Eric Teunis de Boone 95ddbf5bde Ex2.5 feedback: Show how a multidimensional array is stored in-memory 2020-06-30 11:29:50 +02:00
Eric Teunis de Boone 415032e0ef Ex3.3 feedback: The Stack's bufsize was not updated on Stack::grow() so the stack would not actually grow 2020-06-30 11:18:10 +02:00
Eric Teunis de Boone c49a9f3e5b Ex2.1: feedback: mixed up pointers and references 2020-06-30 10:29:44 +02:00
Eric Teunis de Boone 982866a7e6 Feedback on ex0.* and ex1.* 2020-05-06 11:43:09 +02:00
72 changed files with 704 additions and 146 deletions

View File

@ -0,0 +1,12 @@
#!/usr/bin/env python3
import numpy as np
import sys
N = 1e6
if len(sys.argv) > 1:
N = float(sys.argv[1])
for _ in range(int(N)):
print( np.random.rand(1) )

View File

@ -1,4 +1,10 @@
Running `time ./gen_rand.py "1e9"` gives
Running `time ./gen_rand.py "1e6"` gives
real 0m13.803s
user 0m8.874s
real 0m0.237s
user 0m0.160s
Contrast this to the following:
Running `time ./gen_rand_explicit.py "1e6"` gives
real 2m11.564s
user 2m1.950s

View File

@ -19,15 +19,15 @@ int main() {
unsigned int chars_capital = 0, chars_lower = 0, chars_digits = 0, chars_other = 0;
while ( *ptr != 0 )
{
if ( *ptr >= int('A') && *ptr <= int('Z') )
if ( *ptr >= 'A' && *ptr <= 'Z' )
{
++chars_capital;
}
else if ( *ptr >= int('a') && *ptr <= int('z') )
else if ( *ptr >= 'a' && *ptr <= 'z' )
{
++chars_lower;
}
else if ( *ptr >= int('0') && *ptr <= int('9') )
else if ( *ptr >= '0' && *ptr <= '9' )
{
++chars_digits;
}

View File

@ -39,7 +39,9 @@ char* join(const char* str1 , const char* str2)
char* joinb(const char* str1 , const char* str2)
{
int size = strlen(str1) + strlen(str2) + 1;
// size should be 2 more than required for the strlens to
// incorporate the space and the null byte
int size = strlen(str1) + strlen(str2) + 2;
char* new_str = new char[size];
*new_str = 0;

View File

@ -15,12 +15,25 @@
#define MEMORY_SIZE_IN_CHARS G
void make_throwaway_ptrs(int leak_size ) {
for ( int i = 0; i < leak_size ; i++)
{
char* throwaway_ptr = new char;
}
// oops, we are not returning the pointers
// this means it goes out of scope when the function ends
}
int main() {
char* throwaway_ptr = new char[MEMORY_SIZE_IN_CHARS];
make_throwaway_ptrs(MEMORY_SIZE_IN_CHARS);
std::cout << "We leaked " << MEMORY_SIZE_IN_CHARS * sizeof " " << " bits" << std::endl;
std::cout << "Ready to kill the process? (press Enter)" << std::endl;
std::cin.ignore();
return 0;
}

View File

@ -23,10 +23,10 @@
#include <iostream>
#include <cmath>
#define VERBOSE false
#define VERBOSE true
char b32_lookup_table[] = "ABCDEFGHIJKLMNOPQRSTUV";
int base = 8;
char b32_lookup_table[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
int base = 32;
int main() {
//a
@ -75,7 +75,7 @@ int main() {
digits[digit_num] = number & lsb_bitmask;
// Shift off the bits we have put in to the array
number = ( number >> bits_in_char );
number >>= bits_in_char;
++digit_num;
}
@ -91,14 +91,7 @@ int main() {
// Loop the other way so the first digit we get out is MSB
while ( digit_num >= 0 )
{
if ( digits[digit_num] < 10 )
{
std::cout << digits[digit_num];
}
else
{
std::cout << b32_lookup_table[digits[digit_num] - 10];
}
std::cout << b32_lookup_table[digits[digit_num]];
digit_num--;
}

77
ex10/ThreadPool.cc Normal file
View File

@ -0,0 +1,77 @@
// ThreadPool.cc
#include "threadpool.hh"
#include "shared_queue.hh"
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
void producer( const int id, SharedQueue<int>& q, int max_t, int max_n )
{
std::random_device d;
std::mt19937 mt(d());
std::uniform_int_distribution<> distr(0., max_t);
std::cout << " -- Starting Producer " << id << " (max_t: " << max_t << " max_n: " << max_n << ")" << std::endl;
for ( int n = 0; n < max_n ; ++n )
{
std::cout << " -- Producer " << id << "; n = " << n << std::endl;
int l = distr(mt);
std::this_thread::sleep_for(std::chrono::milliseconds(l));
// Lock q so we can push a new element
std::unique_lock<std::mutex> lock(*q.mutex());
q.queue()->push(l);
std::cout << " -- Producer " << id << " pushed = " << l << std::endl;
// Notify one of the consumers
q.cv()->notify_one();
}
std::cout << "Exiting Producer " << id << std::endl;
}
void consumer( const int id, SharedQueue<int>& q, int max_t, int max_n )
{
const int time_out = 5 ;// seconds
int b = 0;
std::cout << " -- Starting Consumer " << id << " (max_t: " << max_t << " max_n: " << max_n << ")" << std::endl;
for ( int n = 0; n < max_n ; n++ )
{
std::cout << " -- Consumer " << id << "; n = " << n << std::endl;
{ // Scope the lock of the queue
std::unique_lock<std::mutex> q_lock(*q.mutex());
while ( q.queue()->empty() ) {
// Wait until we get a signal from the condition variable
// or we reach a timeout
if ( q.cv()->wait_for(q_lock, std::chrono::seconds(time_out)) == std::cv_status::timeout )
{
// We reached the timeout
std::cout << " -- Consumer " << id << " timed out (" << time_out << "s)" << std::endl;
// this consumer does nothing after stopping the loop
// so we can return to break the loops
return;
}
}
// Get a value and pop it off
b = q.queue()->front();
q.queue()->pop();
}
std::cout << " -- Consumer " << id << " read: " << b << std::endl;
// Slow down this thread to have a race between the consumers and the producers
// This only works after we have successfully read an int
std::this_thread::sleep_for(std::chrono::milliseconds(max_t));
}
std::cout << "Exiting Consumer " << id << std::endl;
}

24
ex10/main.cpp Normal file
View File

@ -0,0 +1,24 @@
#include "shared_queue.hh"
#include "threadpool.hh"
#include <string>
#include <iostream>
int main() {
std::cout << "Set up ThreadPool" << std::endl;
ThreadPool tp;
std::cout << "Add Producer" << std::endl;
tp.addProducer();
std::cout << "Add Consumers" << std::endl;
tp.addConsumer();
tp.addConsumer();
std::cout << "Run" << std::endl;
tp.run();
std::cout << "Finishing up" << std::endl;
return 0;
}

20
ex10/main.py Normal file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env python3
import ThreadPool
if __name__ == "__main__":
print(dir(ThreadPool))
tp = ThreadPool.ThreadPool()
print("Creating Consumers")
tp.addConsumer( 2000, 20 )
tp.addConsumer( 2000, 10 )
print("Create Producers")
tp.addProducer( 4000, 5 )
print("Run all Threads")
tp.run()
print("End of Program")

8
ex10/makefile Normal file
View File

@ -0,0 +1,8 @@
main:
g++ -pthread ThreadPool.cc main.cpp
threadpool:
g++ -pthread -D ENABLE_PYBIND=1 -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` ThreadPool.cc -o ThreadPool`python3-config --extension-suffix`
clean:
rm -rf *.so __pycache__

39
ex10/shared_queue.hh Normal file
View File

@ -0,0 +1,39 @@
// Shared_Queue.hh
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#ifndef SHARED_QUEUE_HH
#define SHARED_QUEUE_HH
template <class T>
class SharedQueue
{
public:
SharedQueue() :
_q(),
_q_mutex(),
_q_cv()
{};
SharedQueue( const SharedQueue& other )
{
std::cout << "Copy Constructor SharedQueue" << std::endl;
// (Read)Lock the other queue for copying
std::unique_lock<std::mutex> other_lock(other._q_mutex);
_q = other._q;
}
std::queue<T> * queue() { return& _q; }
std::mutex * mutex() { return& _q_mutex; }
std::condition_variable * cv() { return& _q_cv; }
private:
// Queue
std::queue<T> _q;
// Synchronisation
std::mutex _q_mutex;
std::condition_variable _q_cv;
};
#endif

79
ex10/threadpool.hh Normal file
View File

@ -0,0 +1,79 @@
// ThreadPool.hh
#include "shared_queue.hh"
#include <thread>
#include <vector>
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
// Implementations for producers and consumers
void producer( const int id, SharedQueue<int>& _q, int max_t, int max_n );
void consumer( const int id, SharedQueue<int>& _q, int max_t, int max_n );
class ThreadPool
{
public:
ThreadPool() :
_q(),
_consumers(),
_producers()
{};
void addProducer( int max_t = 3000, int max_n = 10)
{
std::thread * tp = new std::thread( producer, _producers.size(), std::ref(_q), max_t, max_n );
_producers.push_back(tp);
}
void addConsumer( int max_t = 2000, int max_n = 10)
{
std::thread * tp = new std::thread( consumer, _consumers.size(), std::ref(_q), max_t, max_n );
_consumers.push_back(tp);
}
void run()
{
// join all producers
for ( int i = 0; i < _producers.size() ; i++ )
{
(*_producers[i]).join();
}
// join all consumers
for ( int i = 0; i < _consumers.size() ; i++ )
{
(*_consumers[i]).join();
}
}
private:
// Consumer and Producers threads
std::vector<std::thread * > _consumers;
std::vector<std::thread * > _producers;
// queue
SharedQueue<int> _q;
};
#if ENABLE_PYBIND
/*
* Define Python access
*/
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(ThreadPool, tp)
{
py::class_<ThreadPool>( tp, "ThreadPool")
.def(py::init())
.def("addProducer", &ThreadPool::addProducer, "Add a new Producer to the Pool")
.def("addConsumer", &ThreadPool::addConsumer, "Add a new Consumer to the Pool")
.def("run", &ThreadPool::run, "Run all registered Producers and Consumers");
}
#endif
#endif

View File

@ -83,8 +83,8 @@ void orderptr( int* a, int* b ) {
return;
}
int* tmp = a;
a = b;
b = tmp;
int tmp = *a;
*a = *b;
*b = tmp;
}
#endif

View File

@ -15,9 +15,9 @@
void sort( const char** A, const int size );
#if !USE_PTR
void order( const char* a, const char* b );
void order( const char* &a, const char* &b );
#else
void orderptr( const char* &a, const char* &b );
void orderptr( const char* *a, const char* *b );
#endif
@ -78,34 +78,14 @@ void sort( const char** A, const int size ) {
#if !USE_PTR
order( A[ i ], A[ j ] );
#else
orderptr( A[ i ], A[ j ] );
orderptr( &A[ i ], &A[ j ] );
#endif
}
}
}
#if !USE_PTR
void order( const char* a, const char* b ) {
#if VERBOSE
std::cout << "Order: " << a << std::endl;
#endif
// b is greater or equal to a, do nothing
if ( strcmp(a, b) > 0) {
#if VERBOSE
std::cout << "Ordering OK" << std::endl;
#endif
return;
}
#if VERBOSE
std::cout << "Ordering ToDo" << std::endl;
#endif
const char* tmp = a;
a = b;
b = tmp;
}
#else
void orderptr( const char* &a, const char* &b ) {
void order( const char* &a, const char* &b ) {
#if VERBOSE
std::cout << "Order: " << a << ", " << b << std::endl;
#endif
@ -123,4 +103,24 @@ void orderptr( const char* &a, const char* &b ) {
a = b;
b = tmp;
}
#else
void orderptr( const char* *a, const char* *b ) {
#if VERBOSE
std::cout << "Order: " << a << std::endl;
#endif
// b is greater or equal to a, do nothing
if ( strcmp(*a, *b) > 0) {
#if VERBOSE
std::cout << "Ordering OK" << std::endl;
#endif
return;
}
#if VERBOSE
std::cout << "Ordering ToDo" << std::endl;
#endif
const char* tmp = *a;
*a = *b;
*b = tmp;
}
#endif

View File

@ -3,12 +3,14 @@
*
* generalisation of type is possible
* => not writing an int implementation means always use the double
* => => even when to ints are supplied, they are generalised to doubles
* => => even when two ints are supplied, they are generalised to doubles
*/
#include <iostream>
//int min( int a, int b );
int min( int a, int b );
double min( double a, int b );
double min( int a, double b );
double min( double a, double b );
int min( int a[], int size);
@ -27,15 +29,30 @@ int main() {
std::cout << "min( 3.12345, 4 ) = " << min(3.12345, 4) << std::endl;
std::cout << "min( 4, 3.12345 ) = " << min(4, 3.12345) << std::endl;
return 0;
}
//int min( int a, int b ) {
// if ( a < b ) {
// return a;
// }
// return b;
//}
int min( int a, int b ) {
if ( a < b ) {
return a;
}
return b;
}
double min( double a, int b ) {
if ( a < b ) {
return a;
}
return b;
}
double min( int a, double b ) {
if ( a < b ) {
return a;
}
return b;
}
double min( double a, double b ) {
if ( a < b ) {
@ -53,3 +70,5 @@ int min( int a[], int size ) {
return m;
}
// Fix interchangeabiliy of doubles and ints

View File

@ -37,7 +37,6 @@ int main() {
double * nvec = multiply( ivec, Nx, mtx );
@ -49,6 +48,17 @@ int main() {
}
std::cout << "]" << std::endl;
delete nvec;
// print the matrix as it is stored in memory
std::cout << "In-Memory Matrix = ";
std::cout << "[" << std::endl;
for ( int i = 0; i < Nx*Y_SIZE; i++ ){
std::cout << mtx[0][i] << ", ";
}
std::cout << std::endl;
std::cout << "]" << std::endl;
}

View File

@ -4,8 +4,6 @@
void Stack::push(double c) {
if (full()) {
std::cout << "Stack::push() Error: stack is full" << std::endl ;
grow( DELTA );
}
s[count++] = c ;
@ -34,7 +32,10 @@ void Stack::init( int in_size ) {
}
void Stack::grow( int delta ) {
std::cout << "Growing by " << delta << std::endl;
double* newbuf = new double[ bufsize + delta ];
int newbufsize = bufsize + delta;
double* newbuf = new double[ newbufsize ];
// Copy elements
for ( int i=0; i < count ; i++ )
@ -47,4 +48,8 @@ void Stack::grow( int delta ) {
// Assign pointer
s = newbuf;
// Update bufsize
bufsize = newbufsize;
}

View File

@ -7,7 +7,7 @@
using namespace std ;
int main() {
Stack s(10) ;// initialize Stack
Stack s(5) ;// initialize Stack
// Write doubles into Stack
int i ;
@ -17,7 +17,7 @@ int main() {
}
// Count doubles in fifo
cout << s.nitems() << " value in stack" << endl ;
cout << s.nitems() << " values in Stack" << endl ;
cout << "Inspect the FIFO" << endl;
s.inspect();
@ -26,7 +26,7 @@ int main() {
// Read doubles back from fifo
while (!s.empty()) {
double val = s.pop() ;
cout << "popping value " << val << " from stack" << endl ;
cout << "popping value " << val << " from Stack" << endl ;
}
cout << "Inspect the FIFO" << endl;

View File

@ -4,6 +4,8 @@
#include "Button.hh"
#define DEFAULT_NUMBER_BUTTONS 12
class Dialer {
public:
@ -14,7 +16,11 @@ public:
Dialer(const Dialer& other) {
std::cout << "Dialer Copy Constructor " << this << std::endl ;
init();
init(other.buttons_size);
// Copy the buttons
for ( int i = 0; i < other.buttons_size; i++ ) {
buttons[i] = other.buttons[i];
}
}
~Dialer() {
std::cout << "Dialer Destructor " << this << std::endl ;
@ -25,10 +31,16 @@ private:
void init()
{
buttons = new Button[12];
this->init( DEFAULT_NUMBER_BUTTONS );
}
void init( int num_buttons )
{
buttons_size = num_buttons;
buttons = new Button[buttons_size];
}
Button* buttons ;
int buttons_size;
} ;

View File

@ -10,7 +10,13 @@ class Handset {
public:
Handset() { std::cout << "Handset Constructor " << this << std::endl ; }
Handset(const Handset&) { std::cout << "Handset Copy Constructor " << this << std::endl ; }
Handset(const Handset& h) :
mouthpiece( h.mouthpiece ),
earpiece( h.earpiece ),
cable( h.cable )
{
std::cout << "Handset Copy Constructor " << this << std::endl ;
}
~Handset() { std::cout << "Handset Destructor " << this << std::endl ; }
private:

View File

@ -9,7 +9,12 @@ class Housing {
public:
Housing() { std::cout << "Housing Constructor " << this << std::endl ; }
Housing(const Housing&) { std::cout << "Housing Copy Constructor " << this << std::endl ; }
Housing(const Housing& h) :
chassis( h.chassis ),
shell( h.shell )
{
std::cout << "Housing Copy Constructor " << this << std::endl ;
}
~Housing() { std::cout << "Housing Destructor " << this << std::endl ; }
private:

View File

@ -9,9 +9,19 @@
class Telephone {
public:
Telephone() { std::cout << "Telephone Constructor " << this << std::endl ; }
Telephone(const Telephone& t ) { std::cout << "Telephone Copy Constructor " << this << std::endl ; }
~Telephone() { std::cout << "Telephone Destructor " << this << std::endl ; }
Telephone() {
std::cout << "Telephone Constructor " << this << std::endl;
}
Telephone(const Telephone& t ) :
cable( t.cable ),
housing( t.housing ),
dialer( t.dialer ),
handset( t.handset ) {
std::cout << "Telephone Copy Constructor " << this << std::endl;
}
~Telephone() {
std::cout << "Telephone Destructor " << this << std::endl;
}
private:

View File

@ -3,5 +3,14 @@
int main(){
Telephone t;
std::cout << std::endl;
std::cout << "Cloning the Telephone object" << std::endl;
std::cout << std::endl;
Telephone t2 = t;
std::cout << std::endl;
std::cout << "Destructing all objects" << std::endl;
std::cout << std::endl;
}

View File

@ -1,18 +0,0 @@
//CaloGrid.cc
#include <iostream>
#include "CaloGrid.hh"
CaloCell* CaloGrid::cell(int x, int y ) {
if ( x > nx or x < 0 ) {
std::cout << "CaloGrid::cell() Error: out of grid (x)" << std::endl ;
return nullptr;
}
if ( y > ny or y < 0 ) {
std::cout << "CaloGrid::cell() Error: out of grid (y)" << std::endl ;
return nullptr;
}
return cells[ x*nx + y ] ;
}

View File

@ -13,10 +13,10 @@ class CaloCell
// No need for Constructor or Destructor
double getEnergy() const { return energy; }
bool setEnergy( double new_energy ) { return (energy = new_energy) ; }
void setEnergy( double new_energy ) { energy = new_energy ; }
int getId() const { return ID ; }
bool setId( int new_id ) { return ( ID = new_id ) ; }
void setId( int new_id ) { ID = new_id ; }
private:

View File

@ -2,17 +2,17 @@
#include <iostream>
#include "CaloGrid.hh"
CaloCell* CaloGrid::cell(int x, int y ) {
if ( x > nx or x < 0 ) {
CaloCell* CaloGrid::cell( int x, int y ) {
if ( x >= nx or x < 0 ) {
std::cout << "CaloGrid::cell() Error: out of grid (x)" << std::endl ;
return nullptr;
}
if ( y > ny or y < 0 ) {
if ( y >= ny or y < 0 ) {
std::cout << "CaloGrid::cell() Error: out of grid (y)" << std::endl ;
return nullptr;
}
return cells[ x * nx + y ] ;
return &cells[ x*nx + y ] ;
}

View File

@ -25,6 +25,9 @@ class CaloGrid
}
CaloCell* cell(int x, int y);
const CaloCell* cell(int x, int y) const {
return const_cast<CaloGrid*>(this)->cell(x, y);
}
private:
@ -37,6 +40,13 @@ class CaloGrid
// contigious cells
cells = new CaloCell[ nx*ny ];
// set Cell Ids
for ( int i = 0; i < nx ; i++ ) {
for ( int j = 0; j < ny ; j++ ) {
cells[ i*ny+j ].setId( i*ny+j );
}
}
}
} ;
#endif

View File

@ -5,5 +5,34 @@
class Calorimeter
{
}
public:
Calorimeter( int nx, int ny, double x = 0, double y = 0, double z = 0) :
calogrid(nx, ny),
point(x, y, z)
{}
Calorimeter( const Calorimeter& other ) :
calogrid( other.calogrid ),
point( other.point )
{}
CaloGrid& grid() {
return calogrid;
}
const CaloGrid& grid() const {
return calogrid;
}
Point& position() {
return point;
}
const Point& position() const {
return point;
}
private:
Point point;
CaloGrid calogrid;
};
#endif

View File

@ -6,28 +6,29 @@
class Point
{
public:
Point() { init(0, 0, 0) ; }
Point( double x, double y, double z ) { init( x, y, z ); }
Point( double x = 0, double y = 0, double z = 0) { init( x, y, z ) ; }
// No need for Constructor or Destructor
int getX() const { return x ; }
bool setX( int new_x ) { return ( x = new_x ) ; }
void setX( double new_x ) { x = new_x ; }
int getY() const { return y ; }
bool setY( int new_y ) { return ( y = new_y ) ; }
void setY( double new_y ) { y = new_y ; }
int getZ() const { return z ; }
bool setZ( int new_z ) { return ( z = new_z ) ; }
void setZ( double new_z ) { z = new_z ; }
void setPoint( double in_x, double in_y, double in_z ) {
x = in_x ;
y = in_y ;
z = in_z ;
void setPoint( double x, double y, double z ) {
setX(x) ;
setY(y) ;
setZ(z) ;
}
private:
void init( double x, double y, double z ) {
setPoint( x, y, z );
setPoint( x, y, z ) ;
}
double x, y, z = 0 ;

View File

@ -1,6 +1,12 @@
#include "iostream"
#include "CaloCell.hh"
#include "CaloGrid.hh"
#include "Point.hh"
#include "Calorimeter.hh"
void printCellId( const CaloCell* cell ) {
std::cout << cell->getId() << std::endl;
}
int main() {
CaloCell cell(0, 1) ;
@ -10,4 +16,19 @@ int main() {
grid.cell(1, 1);
int nx = 3;
int ny = 4;
Calorimeter calo(nx, ny) ;
std::cout << "CellId at Start: " << calo.grid().cell(0,0)->getId() << std::endl;
std::cout << "CellId at End: " << calo.grid().cell(nx-1,ny-1)->getId() << std::endl;
std::cout << "CellId at Center: " ;
printCellId(calo.grid().cell(nx/2,ny/2));
const CaloGrid grid2(5,5);
grid2.cell(3,3);
}

View File

@ -1,6 +1,7 @@
//String.cc
#include "String.hh"
#include <iostream>
String operator+( const String& lhs, const String& rhs ) {
String result(lhs); // Copy lhs into res with constructor
result += rhs ; // Use operator+= function which is a member of the class
@ -28,3 +29,65 @@ String& String::operator+=( const String& a ) {
return *this ;
}
String& String::subString( int start, int stop ) {
/*
* Return a substring
*
* if stop is negative, interpret as len - stop
* if start is negative, set start = 0
*
* if start > stop, return reversed string
*/
bool reverse = 0;
int len = 0;
char * tmp;
// Higher than Range
if ( start > _len ) {
start = _len ;
}
if ( stop > _len ) {
stop = _len ;
}
// Lower than Range
if ( start < 0 ) {
start = _len + start%_len ;
}
if ( stop < 0 ) {
stop = _len + stop%_len ;
}
// Set length
len = stop - start;
if ( start > stop ) {
// Make sure len is positive
len = -1 * len ;
reverse = 1;
}
// allocate
tmp = new char[ len - 1];
tmp[len] = '\0';
for ( int i = 0 ; i < len ; i++ )
{
if ( reverse )
{
tmp[i] = _s[ start - i ];
}
else
{
tmp[i] = _s[ start + i ];
}
}
// make it a String again
String * result = new String(tmp);
delete tmp;
return *result;
}

View File

@ -12,6 +12,8 @@ public:
String& operator=( const String& a );
String& operator+=( const String& a );
String& subString( int start, int stop );
operator const char* const() { return data(); }
int length() const { return _len ; }
@ -32,4 +34,6 @@ private:
} ;
String operator+( const String& lhs, const String& rhs );
#endif

View File

@ -1,6 +1,7 @@
#include "String.hh"
#include <iostream>
#include <cstring>
#include "String.hh"
int main() {
String str("Blubaloo");
@ -32,4 +33,10 @@ int main() {
String c("Almost Empty");
std::cout << "String '" << c.data() << "' is " << strlen(c) << " chars long." << std::endl;
// Substring
std::cout << "First five characters: " << c.subString(0, 5) << std::endl;
std::cout << "First five characters reversed: " << c.subString(5, 0) << std::endl;
std::cout << "Last five characters: " << c.subString(-5, -1) << std::endl;
}

View File

@ -24,9 +24,6 @@ int main( int argc, char* argv[] ) {
const int bufsize = 100;
char buf[bufsize];
const int linebufsize = 10;
char linebuf[linebufsize];
// if EOF, fh returns false
while( fh ) {
fh.getline(buf, bufsize);
@ -36,8 +33,14 @@ int main( int argc, char* argv[] ) {
std::istringstream line(buf);
while( line ) {
std::string linebuf;
line >> linebuf;
wordcount++ ;
if ( ! linebuf.empty() ) {
wordcount++ ;
}
if ( line.eof() )
{
@ -48,5 +51,5 @@ int main( int argc, char* argv[] ) {
}
std::cout << " " << linecount-1 << " " << wordcount-1 << " " << charcount-1 << " " << argv[1] << std::endl;
std::cout << " " << linecount-1 << " " << wordcount << " " << charcount-1 << " " << argv[1] << std::endl;
}

View File

@ -11,6 +11,7 @@ public:
Array(const Array& other) : _size(other._size) {
_arr = new T[other._size] ;
_default = other._default;
// Copy elements
for (int i=0 ; i<_size ; i++) {

View File

@ -11,6 +11,7 @@ public:
Array(const Array& other) : _size(other._size) {
_arr = new T[other._size] ;
_default = other._default ;
// Copy elements
for (int i=0 ; i<_size ; i++) {

View File

@ -8,23 +8,23 @@ template<class T>
class Stack {
// Interface
public:
Stack( int in_size ) {
count = 0;
_s = new Array<T>(in_size, 0);
}
Stack( int size ):
_s(size, 0)
{}
int nitems() { return count ; }
bool full() { return (count == _s->size()) ; }
bool full() { return (count == _s.size()) ; }
bool empty() { return (count == 0) ; }
void push(T c) {
if (full()) {
std::cout << "Stack::push() Error: stack is full" << std::endl ;
_s->resize( _s->size() + 10 );
_s.resize( _s.size() + 10 );
}
_s[0][count++] = c ;
_s[count++] = c ;
}
T pop() {
@ -33,20 +33,20 @@ class Stack {
return 0 ;
}
return _s[0][--count] ;
return _s[--count] ;
}
void inspect() {
for ( int i = nitems() - 1; i >= 0; i-- )
{
std::cout << i << ": " << _s[0][i] << std::endl;
std::cout << i << ": " << _s[i] << std::endl;
}
}
// Implementation
private:
Array<T>* _s ;
int count ;
Array<T> _s ;
int count = 0;
};
#endif

3
ex7.3/conclusion.txt Normal file
View File

@ -0,0 +1,3 @@
The timing is much longer for vectors than for a list.
However, I also get a segfault for the vector program.

4
ex7.3/list.time Normal file
View File

@ -0,0 +1,4 @@
real 0m0.028s
user 0m0.021s
sys 0m0.004s

View File

@ -4,7 +4,7 @@ int main() {
std::list<int> l;
// Fill List
for (int i = 0; i < 10000000 ; i++) {
for (int i = 0; i < 10000 ; i++) {
l.push_back(i);
}

View File

@ -13,5 +13,4 @@ int main() {
iter = l.erase( iter );
}
}
}

5
ex7.3/vector.time Normal file
View File

@ -0,0 +1,5 @@
Segmentation fault (core dumped)
real 0m0.927s
user 0m0.349s
sys 0m0.007s

View File

@ -8,18 +8,11 @@ template<class T>
class Stack {
// Interface
public:
Stack() {
_s = new std::deque<T>();
}
~Stack() {
delete _s;
}
int nitems() { return _s->size() ; }
bool empty() { return (_s->size() == 0) ; }
int nitems() { return _s.size() ; }
bool empty() { return (_s.size() == 0) ; }
void push(T c) {
_s->push_back(c);
_s.push_back(c);
}
T pop() {
@ -28,15 +21,15 @@ class Stack {
return 0 ;
}
T tmp = _s->back();
_s->pop_back();
T tmp = _s.back();
_s.pop_back();
return tmp;
}
void inspect() {
for ( auto iter = _s->begin(); iter != _s->end() ; iter++ )
for ( auto iter = _s.begin(); iter != _s.end() ; iter++ )
{
std::cout << *iter << std::endl;
}
@ -44,7 +37,7 @@ class Stack {
// Implementation
private:
std::deque<T>* _s ;
std::deque<T> _s ;
};
#endif

View File

@ -36,7 +36,7 @@ public:
private:
string _name ;
double _salary ;
set<Employee*> _subordinates ;// subordinates is an unordered collection so set is usefull enough
set<Employee*> _subordinates ;// subordinates is an unordered collection of unique people so set is usefull enough
} ;

View File

@ -36,7 +36,7 @@ public:
private:
string _name ;
double _salary ;
set<Employee*> _subordinates ;// subordinates is an unordered collection so set is usefull enough
set<Employee*> _subordinates ;// subordinates is an unordered collection of unique people so set is usefull enough
} ;

View File

@ -10,15 +10,15 @@ void populate_directory( set<Employee*>& directory ) {
Manager* jo = new Manager("Jo", 5);
Manager* frank = new Manager("Frank", 6);
(*stan).addSubordinate( *wouter );
(*stan).addSubordinate( *ivo );
stan->addSubordinate( *wouter );
stan->addSubordinate( *ivo );
directory.insert( stan );
directory.insert( wouter );
// This does not give a problem because stan is also of type Employee
(*frank).addSubordinate( *stan );
(*frank).addSubordinate( *jo );
frank->addSubordinate( *stan );
frank->addSubordinate( *jo );
directory.insert( wouter );
directory.insert( ivo );

View File

@ -9,7 +9,7 @@ class Circle: public Shape {
public:
// Constructor, destructor
Circle(int radius) : _radius(radius) {} ;
Circle( double radius ) : _radius(radius) {} ;
virtual ~Circle() {} ;
// Implementation of abstract interface
@ -18,6 +18,6 @@ public:
virtual const char* shapeName() const { return "Circle"; }
private:
int _radius ;
double _radius ;
} ;
#endif

82
ex9.1/d.cpp Normal file
View File

@ -0,0 +1,82 @@
#include <thread>
#include <string>
#include <iostream>
#include <chrono>
#include <vector>
#include <functional>
/*
* Compile with 'g++ -pthread a.cpp'
*
* Modifying an object
*/
using namespace std;
/*
* This method will push the addition of the last two elements on the vector.
*/
void manipulate(vector<double>& v) {
int sleep = 2;
for ( int i = 0; i < 5; i++ )
{
double a = 0;
// Only use the last two elements
int j = 0;
for ( auto rit = v.rbegin() ; rit != v.rend(); ++rit )
{
if ( j > 1 )
{
break;
}
a += *rit;
++j;
}
v.push_back( a);
std::cout << "Updated Vector" << std::endl;
this_thread::sleep_for(std::chrono::seconds(sleep));
}
}
void display(vector<double>& v) {
int sleep = 1;
for ( int i = 0; i < 10; i++ )
{
std::cout << "Vector is now:" << std::endl;
std::cout << "{";
for ( int i = 0; i < v.size() ; i++ ) {
std::cout << v[i] << ", ";
}
std::cout << "}" << std::endl;
this_thread::sleep_for(std::chrono::seconds(sleep));
}
}
struct my_f {
vector<double>& v;
my_f(vector<double>& vv): v(vv) {};
void my_function() { manipulate(v); };
};
int main() {
vector<double> v { 1.1, 1.1 };
thread t {display, ref(v)};
my_f f{v};
thread t2( &my_f::my_function, std::ref(f) );
// Run the threads
t.join();
t2.join();
return 0;
}

Binary file not shown.

BIN
pdfs/Chapter1-reduced.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter2.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter3.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter4.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter5.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter6.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter7.pdf Normal file

Binary file not shown.

BIN
pdfs/Chapter8.pdf Normal file

Binary file not shown.

Binary file not shown.

BIN
pdfs/Introduction.pdf Normal file

Binary file not shown.

View File

@ -0,0 +1 @@
<html><head><meta http-equiv="&#39;Content-Type&#39;" content="&#39;text/html;charset=utf-8&#39;" /><title>1920 CDS: Advanced Programming (KW2 V)</title></head><body><table cellpadding=0 cellspacing=0 border=0 width=100%><tr><td colspan=3>&nbsp;</td></tr><tr><td valign="top" width="100%"><font class="title"><strong>1920 CDS: Advanced Programming (KW2 V)</strong></font><br><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Advanced-Programming.pdf" />1. Advanced-Programming</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises0.pdf" />2. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Introduction.pdf" />3. Introduction</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter1-reduced.pdf" />4. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises1-reduced.pdf" />5. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter2.pdf" />6. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises2.pdf" />7. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter3.pdf" />8. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises3.pdf" />9. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter4.pdf" />10. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises4.pdf" />11. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter5.pdf" />12. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises5.pdf" />13. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter6.pdf" />14. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises6.pdf" />15. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter7.pdf" />16. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises7.pdf" />17. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter8.pdf" />18. Course material</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises8.pdf" />19. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="Chapter9-concurrency.pdf" />20. Chapter9-concurrency</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercises91.pdf" />21. exercises</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="chapter10-bindings.pdf" />22. chapter10-bindings</a></p><p class='d2l' style=' margin-left: 40px'><a target="_blank" href="exercise10.pdf" />23. exercise</a></p></td></tr></table></body></html>

BIN
pdfs/chapter10-bindings.pdf Normal file

Binary file not shown.

BIN
pdfs/exercise10.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises0.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises1-reduced.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises2.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises3.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises4.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises5.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises6.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises7.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises8.pdf Normal file

Binary file not shown.

BIN
pdfs/exercises91.pdf Normal file

Binary file not shown.