Clojure -> Some recursive functions

(defn fibonacci
  ([n]
    (fibonacci [0 1] n))
  ([x,n]
    (if (< (count x) n)
      (fibonacci (conj x (+ (last x) (nth x (- (count x) 2)))) n)
    x))
)

(defn factorial [n]
  (cond 
    (= n 0)  1
    (> n 0) (* n (factorial (- n 1)))
    )
)

(defn collatz [n,s]
  (if (not= n 1)
    (cond 
      (even? n) (collatz (/ n 2) (+ 1 s) )
      (odd? n) (collatz (+ (* 3 n) 1) (+ 1 s))
    )
    s )
)

(defn collatz-sequence [n s]
  (do (println n) 
    (if (not= n 1)
      (cond 
        (even? n) (collatz-sequence (/ n 2) (+ 1 s) )
        (odd? n) (collatz-sequence (+ (* 3 n) 1) (+ 1 s))
      )
    )

  )
)

(println (collatz 141151 0))
(collatz-sequence 1441151 0)
Continue reading →

Some recursive algorithms using C++ template metaprogramming

#include <iostream>
#include <cstdint>

Fibonacci

Continue reading →

Latexdiff – sometimes is just a pain

Just posting a command for latexdiff that saved me from trying to solve a lot of errors:

latexdiff --append-safecmd=subfile --config="PICTUREENV=(?:picture|DIFnomarkup|align|tabular)[\w\d*@]*" draft.tex revision.tex --flatten > diff_new.tex
Continue reading →

Thread-safe Singleton Design Pattern in C++

class Singleton {
public:
  static std::shared_ptr<Singleton> &GetInstance() {
    static std::shared_ptr<Singleton> instance = nullptr;
    if (!instance) {
      std::lock_guard<std::mutex> lock(Singleton::_mutex);

      if (!instance) {
        instance.reset(new Singleton());
      }

    }
    return instance;
  }
 
  ~Singleton() {}
private:
    Singleton() {
    }
  Singleton(const Singleton &) = delete;
  Singleton(Singleton &&) = delete;
  Singleton &operator=(const Singleton &) = delete;
  Singleton &operator=(Singleton &&) = delete;
  static std::mutex _mutex;
};

std::mutex Singleton::_mutex;
Continue reading →

C++ map of member functions

Using look-up tables of member functions is a common use case for implementing and registering callbacks for certain events. The syntax for doing this is not quite straightforward.

#include <iostream>
#include <string>
#include <memory>
#include <functional>
#include <map>
class SomeObj
{
    public:
       void Run(){
           fct_t funct;
           for (auto entry:functionsMap) {
               funct = entry.second;
               funct("some string");
           }
       }
    private:
        void myFunction(const std::string &str)
        {
            std::cout<<str;
        }
        using fct_t = std::function<void(const std::string &)>;
        const std::map<int,fct_t> functionsMap = 
        {
                {1,std::bind(&SomeObj::myFunction, this,
                  std::placeholders::_1)},
        };
};

int main() {
    SomeObj obj;
    obj.Run();

  return 0;
}
Continue reading →