// 3. Longest Substring Without Repeating Characters
/**
 * Given a string, find the length of the longest substring without repeating characters.
 * For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
 * For "bbbbb" the longest substring is "b", with the length of 1.
 *
 * Tag: Hash Table, Two Pointers, String
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // use two pointers to search a string with non-repeating characters
        int l = 0, r = 0, len = 0;

        // use a hash map to map current char to its last appeared location
        unordered_map<char, int> map;

        // use r to scan the string
        for (r = 0; r < s.size(); r++)
        {
            if (map.find(s[r]) != map.end())   // s[r] appears before
            {
                if (l <= map[s[r]])    // l can only go forward
                {
                    l = map[s[r]] + 1;    // update l to ensure non-repeating
                }
            }

            map[s[r]] = r;    // update last apeared location of s[r]

            if (len < r - l + 1)
            {
                len = r - l + 1;    // update max length
            }
        }

        return len;
    }
};

int main() {
    string s("abcabcbb");
    Solution mySolution;
    int res = mySolution.lengthOfLongestSubstring(s);
    cout << res << endl;
    return 0;
}

Add Solution for Problem 003


#include <cstdio>
#include <vector>

using namespace std;

const int N = 1 << 10;
vector <int> graph[N];
bool visited[N];
int m;

void input()
{
  scanf("%d\n", &m);

  for (int i = 0; i < m; i++)
  {
    int u, v;
    scanf("%d%d", &u, &v);
    graph[u].push_back(v);
  }
}

void dfs(int u)
{
  visited[u] = 1;
  printf("%d ", u);
  for (int i = 0; i < graph[u].size(); i++)
  {
    int v = graph[u][i];
    if (!visited[v])
    {
      dfs(v);
    }
  }
}

int main()
{
  input();
  dfs(1);
  printf("\n");

  return 0;
}

Add a solution for task 8b


// Fixed time step
// C++11, C++14

#include <chrono>
#include <thread>

using namespace std::literals::chrono_literals;

void some_complex_work();

int main()
{
	using clock = std::chrono::steady_clock;
	clock::time_point next_time_point = clock::now() + 5s;

	some_complex_work();

	std::this_thread::sleep_until(next_time_point);
}

// Block the execution of a thread until a fixed point in time.
//
// For the purposes of this sample, we use
// [`std::chrono::steady_clock`](cpp/chrono/steady_clock) ([13]),
// although any other clock will suffice.
//
// On [14], we create a `clock::time_point` representing the point in
// time five seconds from now. To do so, we use `clock::now()` to get
// the current time point and add the duration of `5s` to it. Here we
// have used one of C++14's [duration literal
// suffixes](http://en.cppreference.com/w/cpp/chrono/duration#Literals)
// to representing a duration with the seconds suffix, `s`. The
// `using` directive on [7] is required in order to use these suffixes.
// For C++11, the duration can be constructed manually.
//
// After performing some complex work on [16], we then call
// [`std::this_thread::sleep_until`](cpp/thread/sleep_until) on [18],
// passing it the time point we computed earlier. This blocks the
// current thread until we have reached that time point, ensuring that
// execution continues exactly five seconds after the starting time,
// regardless of how much time the complex work took (unless it took
// more than five seconds).
//
// This technique is most commonly used in a loop to ensure that the
// loop iterates with a fixed time step. Alternatively, if you want to
// sleep for a fixed amount of time, see the [sleep
// sample](/common-tasks/sleep.html).

void some_complex_work() { }

Add fixed time step sample


#include <iostream>
#include <vector>
#include <thread>
#include <algorithm>
#include <cstdlib>

void accumulator_function2(const std::vector<int> &v, unsigned long long &acm, unsigned int beginIndex, unsigned int endIndex) {
    acm = 0;
    for (unsigned int i = beginIndex; i < endIndex; ++i) {
        acm += v[i];
    }
}

int main() {
    unsigned long long acm1 = 0;
    unsigned long long acm2 = 0;

    std::vector<int> v(1024);
    srand(time(nullptr));
    std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } );

    for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } );

    std::thread t1(accumulator_function2, std::ref(v), std::ref(acm1), 0, v.size() / 2);
    std::thread t2(accumulator_function2, std::ref(v), std::ref(acm2), v.size() / 2, v.size());

    t1.join();
    t2.join();

    std::cout << "acm1: " << acm1 << std::endl;
    std::cout << "acm2: " << acm2 << std::endl;
    std::cout << "acm1 + acm2: " << acm1 + acm2 << std::endl;

    return 0;
}

Add c++11 thread creation with function pointer. It generates random vector of 1024 integers and creates two threads to summarize bottom and top half respectfully.


#include "Software/NeuralNet.h"
#include "Software/Backpropagation.h"
#include <iostream>

/*
	This is example code which runs a Backpropagating neural network.
	It is supposed to double any input number.
	This is the example code from the readme of https://github.com/FidoProject/Fido

	To compile, run in terminal:
	fcc linear.cpp
	This will make an executable file a.out which will be this program.

	PS.
	Try tweaking the paramaters of the backprop initialization to make the nerual network more correct
*/

int main() {
	// Creates a neural network with
	// 1 input, 1 output, 2 hidden layers, 4 neurons per hidden layer, and a sigmoid activation function.
	net::NeuralNet neuralNetwork = net::NeuralNet(1, 1, 2, 4, "sigmoid");
	std::vector< std::vector<double> > input = { {1}, {2}, {5}, {6} };
	std::vector< std::vector<double> > correctOutput = { {2}, {4}, {10}, {12} };
	neuralNetwork.setOutputActivationFunction("simpleLinear");

	// Create backpropagation object with
	// a learning rate of 10%, a momentum term of 0.001, an acceptable error level of 5%,
	// and a maximum number of training iterations of 10000
	net::Backpropagation backprop = net::Backpropagation(0.1, 0.001, 0.05, 1000000);
	backprop.trainOnData(&neuralNetwork, input, correctOutput);

	// Cycle through inputs and print the outputs
	for (std::vector<double> current: input) {
		std::vector<double> final = neuralNetwork.getOutput(current);
		std::cout << "Correct answer: " << current[0] << "\tActual answer:" << final[0] << std::endl;
	}
}

Put example code in repo


/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"

#include "SkCanvas.h"
#include "SkTextBlob.h"

namespace skiagm {
class TextBlobBlockReordering : public GM {
public:
    // This gm tests that textblobs translate properly when their draw order is different from their
    // flush order
    TextBlobBlockReordering() { }

protected:
    void onOnceBeforeDraw() override {
        SkTextBlobBuilder builder;

        // make textblob
        // Large text is used to trigger atlas eviction
        SkPaint paint;
        paint.setTextSize(56);
        const char* text = "AB";
        sk_tool_utils::set_portable_typeface(&paint);

        SkRect bounds;
        paint.measureText(text, strlen(text), &bounds);

        SkScalar yOffset = bounds.height();
        sk_tool_utils::add_to_text_blob(&builder, text, paint, 0, yOffset - 30);

        // build
        fBlob.reset(builder.build());
    }

    SkString onShortName() override {
        return SkString("textblobblockreordering");
    }

    SkISize onISize() override {
        return SkISize::Make(kWidth, kHeight);
    }

    // This draws the same text blob 3 times.  The second draw used a different
    // xfer mode so it doens't get batched with the first and third.
    // ultimately thye iwll be flushed in the order first, third, and then second
    void onDraw(SkCanvas* canvas) override {
        canvas->drawColor(sk_tool_utils::color_to_565(SK_ColorGRAY));

        SkPaint paint;
        canvas->translate(10, 40);

        SkRect bounds = fBlob->bounds();
        const int yDelta = SkScalarFloorToInt(bounds.height()) + 20;
        const int xDelta = SkScalarFloorToInt(bounds.width());

        canvas->drawTextBlob(fBlob, 0, 0, paint);

        canvas->translate(SkIntToScalar(xDelta), SkIntToScalar(yDelta));

	// draw a rect where the text should be, and then twiddle the xfermode
        // so we don't batch
        SkPaint redPaint;
        redPaint.setColor(SK_ColorRED);
        canvas->drawRect(bounds, redPaint);
        SkPaint srcInPaint(paint);
        srcInPaint.setXfermodeMode(SkXfermode::kSrcIn_Mode);
        canvas->drawTextBlob(fBlob, 0, 0, srcInPaint);

        canvas->translate(SkIntToScalar(xDelta), SkIntToScalar(yDelta));
        canvas->drawTextBlob(fBlob, 0, 0, paint);
    }

private:
    SkAutoTUnref<const SkTextBlob> fBlob;

    static const int kWidth = 275;
    static const int kHeight = 200;

    typedef GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

DEF_GM(return new TextBlobBlockReordering;)
}

Create new GM to target translations problems in GrAtlasTextContext


/*
 * Copyright (c) 2021-2022-2022, Patrick Pelissier
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * + Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * + Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <set>
#include "m-bptree.h"

BPTREE_DEF(tree_int, 5, int)

// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)

// Container OPLIST
#define CONT_OPL   BPTREE_OPLIST(tree_int, M_OPL_int())

// C++ Base class of the item in the container
#define BASE_CLASS int

// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)

// C++ Container class
#define CONT_CLASS std::set<int>

// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)

// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )

void cmp_cont(const tree_int_t a, const std::set<int> &b)
{
  tree_int_it_t ita;
  tree_int_it(ita, a);
  auto          itb = b.begin();
  while (itb != b.end()) {
    assert(!tree_int_end_p(ita));
    const int *b0 = tree_int_cref(ita);
    const int &b1 = *itb;
    CMP_BASE(*b0, b1);
    itb++;
    tree_int_next(ita);
  }
  assert(tree_int_end_p(ita));
}

#define DEFAULT_NUMBER 1000000

#define push_back insert
#include "check-generic.hpp"

Add check of B+Tree / Set


// 034. Search for a Range
/**
 * Given a sorted array of integers, find the starting and ending position of a given target value.
 *
 * Your algorithm's runtime complexity must be in the order of O(log n).
 *
 * If the target is not found in the array, return [-1, -1].
 *
 * For example,
 * Given [5, 7, 7, 8, 8, 10] and target value 8,
 * return [3, 4].
 *
 * Tags: Array, Binary Search
 *
 * Similar Problems: (E)First Bad Version
 */

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> range;
        range.push_back(-1);
        range.push_back(-1);
        int n = nums.size();
        int left = 0, right = n - 1;
        if ((n == 0) || (nums[left] > target) || (nums[right] < target))
        {
            return range;
        }

        if (nums[left] == nums[right])
        {
            range[0] = 0;
            range[1] = n - 1;
            return range;
        }

        // binary search left: finding the first value >= target
        int mid = 0;
        while (left <= right)
        {
            mid = (left + right) / 2;
            if (target > nums[mid])
            {
                left = mid + 1;
            }
            else
            {
                right = mid - 1;
            }
        }
        range[0] = left;

        // binary search right: finding the last value <= target
        left = 0, right = n - 1;
        while (left <= right)
        {
            mid = (left + right) / 2;
            if (target < nums[mid])
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }
        range[1] = right;

        // if first > last, not found
        if (range[0] > range[1])
        {
            range[0] = -1;
            range[1] = -1;
        }

        return range;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(5);
    nums.push_back(7);
    nums.push_back(7);
    nums.push_back(8);
    nums.push_back(8);
    nums.push_back(10);
    int target = 10;

    Solution mySolution;
    vector<int> res = mySolution.searchRange(nums, target);
    cout << "[" << res[0] << "," << res[1] << "]" << endl;
    system("pause");

    return 0;
}

Add Solution for Problem 034


// 124. Binary Tree Maximum Path Sum
/**
 * Given a binary tree, find the maximum path sum.
 *
 * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
 *
 * For example:
 * Given the below binary tree,
 *
 *       1
 *      / \
 *     2   3
 * Return 6.
 *
 * Tags: Tree, Depth-first Search
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <windows.h>

using namespace std;

/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
    int curMax;

public:
    int maxPathSum(TreeNode* root) {
        curMax = INT_MIN;
        dfs(root);
        return curMax;
    }

// if we look at each individual nodes, there are only 3 possiblities:
//   a) Left branch:   root->val + left
//   b) Right branch:  root->val + right
//   c) Both branches: root->val + left + right
//
// a) or b): it can be accumulated between different nodes, so we use them as the return value in the recursion
// c):       it can be only a local maximum, so we compare it to the global maximum and keep whichever is larger

    int dfs(TreeNode* root) {
        if (!root) return 0;

        int left  = max(dfs(root->left), 0);    // if left child val < 0, keep only the parent node value
        int right = max(dfs(root->right), 0);   // if right child val < 0, keep only the parent node value
        curMax = max(curMax, root->val + left + right);  // compare the global max to possible local max

        return root->val + max(left, right);    // choose whichever is larger
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}

Add Solution for Problem 124


//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Baozeng Ding <sploving1@gmail.com>
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/RuntimeExceptions.h"

#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"

namespace cling {
  namespace runtime {
    cling_null_deref_exception::cling_null_deref_exception(
      void* Loc, clang::Sema* S) : m_Location(*(unsigned *)Loc), m_Sema(S){}

    cling_null_deref_exception::~cling_null_deref_exception() {}

    void cling_null_deref_exception::what() throw() {
        clang::DiagnosticsEngine& Diag = m_Sema->getDiagnostics();
        Diag.Report(clang::SourceLocation::getFromRawEncoding(m_Location),
                                              clang::diag::warn_null_arg);
    }
  } // end namespace runtime
} // end namespace cling

Add forgotten to commit file.


/**
 * Longest Common Subsequence:
 * Given two strings, find longest common subsequence between them.
 * https://www.youtube.com/watch?v=NnD96abizww&index=2&list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr
 */
 #include <iostream>
 using namespace std;

void print(unsigned int **T, int M, int N) {
	for (int i = 0; i <= M; i++) {
		for (int j = 0; j <= N; j++) {
			cout<<T[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}

int max(int a, int b) {
	return a > b ? a : b;
}

int findCommonSubsequence(char str1[], char str2[], int M, int N) {
	unsigned int solution = 0;
	unsigned int **T = new unsigned int*[M+1];
	for (int i = 0; i <= M; i++)
		T[i] = new unsigned int[N+1];
	//print(T, M, N);
	for (int i = 1; i <= M; i++) {
		for (int j = 1; j <= N; j++) {
			if (str1[j-1] == str2[i-1]) {
				T[i][j] = T[i-1][j-1] + 1;
			}
			else
				T[i][j] = max(T[i-1][j], T[i][j-1]);
		}
	}
	print(T, M, N);
	solution = T[M][N];
	for (int i = 0; i <= M; i++)
		delete [] T[i];
	delete [] T;
	return solution;
}

 int main() {
 	char str1[] = {'a', 'b', 'e', 'l', 'k', 'q', 'd'};
 	int N = sizeof (str1)/sizeof(str1[0]);
 	char str2[] = {'b','l','a','q','m', 'd', 'b'};
 	int M = sizeof (str2)/sizeof(str2[0]);

 	cout<<findCommonSubsequence(str1, str2, M, N)<<endl;
 	return 0;
 }

Implement longest common subsequence length


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/crypto_module_password_dialog.h"

#include "base/logging.h"

namespace chrome {

void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules,
                            CryptoModulePasswordReason reason,
                            const std::string& host,
                            const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

void UnlockCertSlotIfNecessary(net::X509Certificate* cert,
                               CryptoModulePasswordReason reason,
                               const std::string& host,
                               const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

}  // namespace chrome

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/crypto_module_password_dialog.h"

#include "base/logging.h"

namespace chrome {

void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules,
                            CryptoModulePasswordReason reason,
                            const std::string& host,
                            gfx::NativeWindow parent,
                            const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

void UnlockCertSlotIfNecessary(net::X509Certificate* cert,
                               CryptoModulePasswordReason reason,
                               const std::string& host,
                               gfx::NativeWindow parent,
                               const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

}  // namespace chrome

Fix the linux redux build.


/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <boost/test/unit_test.hpp>

#include <thread>

#include "kaa/utils/KaaTimer.hpp"

namespace kaa {

std::int32_t counter = 0;

void increment(void) { counter++; }

void resetCounter() { counter = 0; }

BOOST_AUTO_TEST_SUITE(KaaTimerTestSuite)

BOOST_AUTO_TEST_CASE(SuccessTimerTriggerTest)
{
    std::size_t timeToWait = 4;
    KaaTimer<void (void)> timer;
    timer.start(timeToWait, [] { increment(); });

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2));

    BOOST_CHECK_EQUAL(counter, 0);

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2 + 1));

    BOOST_CHECK_EQUAL(counter, 1);
    resetCounter();
}

BOOST_AUTO_TEST_CASE(StopTimerTest)
{
    std::size_t timeToWait = 4;
    KaaTimer<void (void)> timer;
    timer.start(timeToWait, [] { increment(); });

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2));

    BOOST_CHECK_EQUAL(counter, 0);
    timer.stop();

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2 + 1));

    BOOST_CHECK_EQUAL(counter, 0);
    resetCounter();
}

BOOST_AUTO_TEST_SUITE_END()

}

Add unit test for timer implementation.


#include <Rcpp.h>
#include "s2/s2latlng.h"
#include "s2/s2cellid.h"

//' @title
//' cell_center
//' @description
//' Get center of S2 cell containing a specified point
//'
//' @param lat latitude of interest (between -90 and +90)
//'
//' @param lng longitude of interest (between -180 and +180)
//'
//' @details
//' \code{cell_center} takes a single (lat,lng) point on the sphere, finds the
//' S2 leaf cell that contains this point and returns the center of this cell.
//' In S2 leaf cells have a very fine resolution, so the output is expected to
//' be very close to the input, and differences are typically on something like
//' the 5th decimal place.
//'
//' @examples
//' cell_center(57.0139595, 9.988967)
//'
//' @export
//[[Rcpp::export]]
Rcpp::NumericVector cell_center(double lat, double lng) {
  S2LatLng p = S2LatLng::FromDegrees(lat, lng);
  S2CellId id = S2CellId::FromLatLng(p);
  S2LatLng center = id.ToLatLng();
  Rcpp::NumericVector rslt(2);
  rslt[0] = center.lat().degrees();
  rslt[1] = center.lng().degrees();
  return rslt;
}

Add missing C++ source file.


#include <stdio.h>
#include "Halide.h"

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y, c;

    Func f, g;

    f(x, y) = x;
    g(x, y) = f(x-1, y+1) + f(x, y-1);
    f.store_root().compute_at(g, y).fold_storage(y, 2);

    Image<int> im = g.realize(100, 1000);

    printf("Should have gotten a bad fold!\n");
    return -1;
}

Add test for a bad fold.


// Chapter 25, Try This 3: get bits example to work, try a few values

#include<iostream>
#include<iomanip>
#include<bitset>

using namespace std;

int main()
{
    int i;
    while (cin>>i)
        cout << dec << i << " == "
        << hex << "0x" << setw(8) << setfill('0') << i << " == "
        << bitset<8*sizeof(int)>(i) << '\n';
}

Add Chapter 25, Try This 3


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Debugger is flaky on browser_tests on Windows: crbug.com/234166.
#if defined(OS_WIN)
#define MAYBE(x) DISABLED_##x
#else
#define MAYBE(x) x
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) {
  ASSERT_TRUE(RunExtensionTest("debugger")) << message_;
}

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Debugger is flaky on browser_tests on Windows, Linux, and Chrome OS:
// crbug.com/234166.
#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS)
#define MAYBE(x) DISABLED_##x
#else
#define MAYBE(x) x
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) {
  ASSERT_TRUE(RunExtensionTest("debugger")) << message_;
}

Disable flaky ExtensionApiTest.Debugger on Linux and Chrome OS.


#include <stdio.h>
#include <string>

class Shape {
 public:
  virtual void draw() = 0;
};

class Rectangle : public Shape {
 public:
  void draw() override { printf("Drawing Rectangle \n"); }
};

class Square : public Shape {
 public:
  void draw() override { printf("Drawing Square \n"); }
};

class Circle : public Shape {
 public:
  void draw() override { printf("Drawing Circle \n"); }
};

class ShapeFactory {
 public:
  Shape* GetShape(std::string str) {
    if (str.find("Rectangle") != std::string::npos) {
      return new Rectangle();
    } else if (str.find("Square") != std::string::npos) {
      return new Square();
    } else if (str.find("Circle") != std::string::npos) {
      return new Circle();
    } else {
      return nullptr;
    }
  }
};

int main(int argc, char const* argv[]) {
  ShapeFactory shapeFactory;
  Shape* shape1 = shapeFactory.GetShape("Rectangle");
  shape1->draw();
  Shape* shape2 = shapeFactory.GetShape("Square");
  shape2->draw();
  Shape* shape3 = shapeFactory.GetShape("Circle");
  shape3->draw();

  return 0;
}

Add Factory method design pattern.


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int nlen = 1, n = nums.size();;
        if(n <= 1) return n;
        for(int i=1; i < nums.size();i++){
            if(nums[i] != nums[i-1]){
                nums[nlen++] = nums[i];
            }
        }
        return nlen;
    }
};

Remove Duplicates from Sorted Array


//
//  main.cpp
//  backToProblemSolving
//
//  Created by Khaled Abdelfattah on 6/27/17.
//  Copyright © 2017 Khaled Abdelfattah. All rights reserved.
//

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
#define MAX 1000000000
#define BASE1 23
#define BASE2 31
#define MOD1 1000000007
#define MOD2 217645177
#define EPS 1e-6
#define SIZE 20005

int n, m;
vector<pair<pair<int, int>, int>> edges;
int bestDist[SIZE];

void Bellman_Ford (int s) {
    memset(bestDist, INT_MAX, n + 1);
    bestDist[s] = 0;
    for (int i = 0; i < n - 1; i ++) {
        bool relaxed = false;
        for (int j = 0; j < edges.size(); j ++) {
            int from = edges[j].first.first, to = edges[j].first.second;
            int dist = edges[j].second;
            if (bestDist[from] + dist < bestDist[to]) {
                bestDist[to] = bestDist[from] + dist;
                relaxed = true;
            }
        }
        if (!relaxed)
            break;
    }
}

bool hasNegCycle () {
    for (int j = 0; j < edges.size(); j ++) {
        int from = edges[j].first.first, to = edges[j].first.second;
        int dist = edges[j].second;
        if (bestDist[from] + dist < bestDist[to]) {
            return true;
        }
    }
    return false;
}
int main() {
    n = 6;
    m = 5;
    edges.push_back(make_pair(make_pair(1, 2), -2));
    edges.push_back(make_pair(make_pair(1, 3), 5));
    edges.push_back(make_pair(make_pair(2, 3), -2));
    edges.push_back(make_pair(make_pair(3, 4), 7));
    edges.push_back(make_pair(make_pair(4, 5), -12));
    Bellman_Ford(1);
    for (int i = 1; i <= n; i ++)
        cout << bestDist[i] << " ";
    cout << endl;
    cout << hasNegCycle();
    return 0;
}

Add Bellman Ford Algorithm to graph search in c++


#include <iostream>
using namespace std;

/*
This represents the structure of the node of the Binary Search Tree.
*/

struct node
{
    node * left;
    node * right;
    int data;
};

/*
This function adds new data into binary search tree (BST).
It takes root of the tree as parameter along with the new data to be inserted.
*/

node * add(node * root,int val)
{
    if(root == NULL)
    {
        node * newNode = new node;
        newNode->data = val;
        newNode->left=NULL;
        newNode->right=NULL;
        return newNode;
    }
    if(val > root->data)
        root->right=add(root->right,val);
    else
        root->left=add(root->left,val);
    return root;
}

/*
This function traverses the second tree and adds its nodes to tree 1.
It takes roots of tree 1 and tree 2 as parameters.
*/

node * merge(node * root1,node * root2)
{
    if(root2==NULL)
        return root1;
    merge(root1,root2->left);
    add(root1,root2->data);
    merge(root1,root2->right);
}

/*
This function prints the inorder traversal of the BST thus printing
a list of entered values in ascending order.It takes the root node as a parameter.
*/

void print_inorder(node *root)
{
    if(root==NULL)
    return;
    print_inorder(root->left);
    cout<<root->data<<" ";
    print_inorder(root->right);

}

int main()
{
    node * root1 =NULL;
    node * root2 =NULL;

    //  Insertion into tree1
    root1=add(root1,12);
    root1=add(root1,30);
    root1=add(root1,2);
    root1=add(root1,15);
    root1=add(root1,6);
    root1=add(root1,54);
    root1=add(root1,27);

    //Printing result
    print_inorder(root1);
    cout<<"\n";

    //  Insertion into tree2
    root2=add(root2,30);
    root2=add(root2,23);
    root2=add(root2,12);
    root2=add(root2,43);
    root2=add(root2,33);
    root2=add(root2,62);
    root2=add(root2,31);

    //Printing result
    print_inorder(root2);
    cout<<"\n";

    //  Merging the two trees

    merge(root1,root2);

    //  Printing merged tree

    print_inorder(root1);

    return 0;
}

Add merging of two Binary Search Trees


#include "ec_gen.h"

Handle<ScopedEVP_PKEY> EC_generate(int &nidEc) {
	LOG_FUNC();

	Handle<ScopedEVP_PKEY> pkey;

	ScopedEC_KEY eckey(EC_KEY_new_by_curve_name(nidEc));

	if (eckey.isEmpty()) {
		THROW_OPENSSL("EC_KEY_new_by_curve_name");
	}
	if (!EC_KEY_generate_key(eckey.Get())) {
		THROW_OPENSSL("EC_KEY_generate_key");
	}

	pkey = Handle<ScopedEVP_PKEY>(new ScopedEVP_PKEY(EVP_PKEY_new()));

	if (EVP_PKEY_assign_EC_KEY(pkey->Get(), eckey.Get()) != 1) {
		THROW_OPENSSL("EVP_PKEY_assign_EC_KEY");
	}

	eckey.unref();

	return pkey;
}

#include "ec_gen.h"

Handle<ScopedEVP_PKEY> EC_generate(int &nidEc) {
	LOG_FUNC();

	Handle<ScopedEVP_PKEY> pkey;

	ScopedEC_KEY eckey(EC_KEY_new_by_curve_name(nidEc));

	if (eckey.isEmpty()) {
		THROW_OPENSSL("EC_KEY_new_by_curve_name");
	}
	if (!EC_KEY_generate_key(eckey.Get())) {
		THROW_OPENSSL("EC_KEY_generate_key");
	}

	/**
	 * Current flag is needed to get a CHROME like pkcs8, spki output
	 */
	EC_GROUP *group = (EC_GROUP *)EC_KEY_get0_group(eckey.Get());
	EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);

	pkey = Handle<ScopedEVP_PKEY>(new ScopedEVP_PKEY(EVP_PKEY_new()));

	if (EVP_PKEY_assign_EC_KEY(pkey->Get(), eckey.Get()) != 1) {
		THROW_OPENSSL("EVP_PKEY_assign_EC_KEY");
	}

	eckey.unref();

	return pkey;
}

Support CHROME like format for pkcs8, spki EC keys


class Solution {
public:
    bool checkString(string s) {
        bool b_found = false;
        for (const auto& c : s) {
            if (c == 'a' && b_found)
                return false;
            if (c == 'b')
                b_found = true;
        }
        return true;
    }
};

Check if All A's Appears Before All B's


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"
#include "chrome/browser/first_run/upgrade_util.h"

// The entry point for all invocations of Chromium, browser and renderer. On
// windows, this does nothing but load chrome.dll and invoke its entry point in
// order to make it easy to update the app from GoogleUpdate. We don't need
// that extra layer with on linux.

extern "C" {
int ChromeMain(int argc, const char** argv);
}

int main(int argc, const char** argv) {
  int return_code = ChromeMain(argc, argv);

#if defined(OS_LINUX)
  // Launch a new instance if we're shutting down because we detected an
  // upgrade in the persistent mode.
  upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
#endif

  return return_code;
}

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"
#include "chrome/browser/first_run/upgrade_util.h"

// The entry point for all invocations of Chromium, browser and renderer. On
// windows, this does nothing but load chrome.dll and invoke its entry point in
// order to make it easy to update the app from GoogleUpdate. We don't need
// that extra layer with on linux.

#if defined(ADDRESS_SANITIZER) && defined(GOOGLE_CHROME_BUILD)
const char *kAsanDefaultOptions = "quarantine_size=1048576";

// Override the default ASan options for the Google Chrome executable.
// __asan_default_options should not be instrumented, because it is called
// before ASan is initialized.
extern "C"
__attribute__((no_address_safety_analysis))
const char *__asan_default_options() {
  return kAsanDefaultOptions;
}
#endif

extern "C" {
int ChromeMain(int argc, const char** argv);
}

int main(int argc, const char** argv) {
  int return_code = ChromeMain(argc, argv);

#if defined(OS_LINUX)
  // Launch a new instance if we're shutting down because we detected an
  // upgrade in the persistent mode.
  upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
#endif

  return return_code;
}

Set the default ASan options for the Official Chrome build.


#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "outputtrack.h"

int main(int argc, char** argv)
{
	FILE* fpInput = fopen("../output.bin", "rb");
	if (fpInput == NULL)
	{
		printf("Error opening input file\n");
		exit(1);
	}

	//Loop over all events in the input file.
	//Number of events is not stored int the file, but we just read until we reach the end of file.
	//All values stored in the file are either int or float, so 32 bit.
	//Thus, we do not need to care about alignment. The same data structures must be used again for reading the file.
	int nEvents = 0;
	std::vector<unsigned int> ClusterIDs;
	while (!feof(fpInput))
	{
		int numTracks; //Must be int!
		OutputTrack track;
		fread(&numTracks, sizeof(numTracks), 1, fpInput);
		printf("Event: %d, Number of tracks: %d\n", nEvents, numTracks);
		for (int iTrack = 0;iTrack < numTracks;iTrack++)
		{
			fread(&track, sizeof(track), 1, fpInput);
			printf("Track %d Parameters: Alpha %f, X %f, Y %f, Z %f, SinPhi %f, DzDs %f, Q/Pt %f, Number of clusters %d, Fit OK %d\n", iTrack, track.Alpha, track.X, track.Y, track.Z, track.SinPhi, track.DzDs, track.QPt, track.NClusters, track.FitOK);
			if (track.NClusters > ClusterIDs.size()) ClusterIDs.resize(track.NClusters);
			fread(&ClusterIDs[0], sizeof(ClusterIDs[0]), track.NClusters, fpInput);
			printf("Cluster IDs:");
			for (int iCluster = 0;iCluster < track.NClusters;iCluster++)
			{
				printf(" %d", ClusterIDs[iCluster]);
			}
			printf("\n");
		}

		nEvents++;
	}
	fclose(fpInput);
}

Add example to read tracks from binary output file


// Test that the -c flag works.
// RUN: llvmc -c %s -o %t.o
// RUN: llvmc --linker=c++ %t.o -o %t
// RUN: %abs_tmp | grep hello
// XFAIL: vg
#include <iostream>

int main() {
    std::cout << "hello" << '\n';
}

Add a test for the -c flag.


// 19. Remove Nth Node From End of List
/**
 * Given a linked list, remove the nth node from the end of list and return its head.
 *
 * For example,
 *
 * Given linked list: 1->2->3->4->5, and n = 2.
 *
 * After removing the second node from the end, the linked list becomes 1->2->3->5.
 *
 * Note:
 * Given n will always be valid.
 * Try to do this in one pass.
 *
 * Tags: Linked List, Two Pointers
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    ListNode(int x, ListNode *p) : val(x), next(p) {}
};

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // use a dummy node to mark the head of the list
        ListNode dummy(0);
        dummy.next = head;

        // set two pointer difference by n
        ListNode *slow = &dummy, *fast = slow;
        for (int i = 0; i < n; i++) {
            fast = fast->next;
        }

        // move fast to the last element
        // find the node to be removed: slow->next
        while (fast->next != NULL) {
            slow = slow->next;
            fast = fast->next;
        }

        // remove the node
        fast = slow->next;
        slow->next = fast->next;
        delete fast;

        return dummy.next;
    }
};

int main() {
    ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2);
    Solution sol;
    ListNode *newhead = sol.removeNthFromEnd(&node1, 5);
    for (ListNode *p = newhead; p != NULL; p = p->next) {
        cout << p->val << " ";
    }
    cout << endl;
    cin.get();

    return 0;
}

Add Solution for 019 Remove Nth Node From End of List


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/touch/touch_device.h"
#include "base/win/windows_version.h"
#include <windows.h>

namespace ui {

bool IsTouchDevicePresent() {
  int value = GetSystemMetrics(SM_DIGITIZER);
  return (value & (NID_READY | NID_INTEGRATED_TOUCH)) ==
             (NID_READY | NID_INTEGRATED_TOUCH);
}

}  // namespace ui

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/touch/touch_device.h"
#include "base/win/windows_version.h"
#include <windows.h>

namespace ui {

bool IsTouchDevicePresent() {
  int value = GetSystemMetrics(SM_DIGITIZER);
  return (value & NID_READY) &&
      ((value & NID_INTEGRATED_TOUCH) || (value & NID_EXTERNAL_TOUCH));
}

}  // namespace ui

Enable touch on external touch devices.


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (!root)
            return root;
        if (root->val < key) {
            root->right = deleteNode(root->right, key);
        } else if (root->val > key) {
            root->left = deleteNode(root->left, key);
        } else {
            if (!root->left && !root->right) {
                delete(root);
                return nullptr;
            } else if (!root->left && root->right) {
                auto ret = root->right;
                delete(root);
                return ret;
            } else if (root->left && !root->right) {
                auto ret = root->left;
                delete(root);
                return ret;
            } else {
                auto removal = root->right;
                while (removal->left) {
                    removal = removal->left;
                }
                root->val = removal->val;
                root->right = deleteNode(root->right, root->val);
            }
        }
        return root;
    }
};

Delete Node in a BST


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (!root) {
            TreeNode* newroot = new TreeNode{val};
            return newroot;
        }
        if (val < root->val) {
            root->left = insertIntoBST(root->left, val);
        } else {
            root->right = insertIntoBST(root->right, val);
        }
        return root;
    }
};

Insert into a Binary Search Tree


#include <cstdio>

using namespace std;

const int N = 1 << 10;
int a[N][N], m;
int INF = 1 << 20;
int n = 0;

void input()
{
  for (int i = 0; i < m; i++)
  {
    int u, v, d;
    scanf("%d%d%d", &u, &v, &d);
    a[u][v] = d;
    if (u > n) n = u;
    if (v > n) n = v;
  }
}

void floyd()
{
  for (int i = 1; i <= n; i++)
  {
    for (int j = 1; j <= n; j++)
    {
      if (a[i][j] == 0) a[i][j] = INF;
    }
  }

  for (int k = 1; k <= n; k++)
  {
    for (int i = 1; i <= n; i++)
    {
      for (int j = 1; j <= n; j++)
      {
        if (a[i][j] > (a[i][k] + a[k][j]))
        {
          a[i][j] = a[i][k] + a[k][j];
        }
      }
    }
  }

  for (int i = 1; i <= n; i++)
  {
    a[i][i] = 0;
  }
}

void print_graph()
{
  for (int i = 1; i <= n; i++)
  {
    for (int j = 1; j <= n; j++)
    {
      if (a[i][j] == INF) printf("-1 ");
      else printf("%d ", a[i][j]);
    }
    printf("\n");
  }
}

void clear_graph()
{
  for (int i = 1; i <= n; i++)
  {
    for (int j = 1; j <= n; j++)
    {
      a[i][j] = 0;
    }
  }
  n = 0;
}

int main()
{
  while (scanf("%d", &m) != EOF)
  {
    input();
    floyd();
    print_graph();
    clear_graph();
  }
  return 0;
}

Add a solution for task 9a


//kinda-sorta functional code from Real Life (tm):

// The operator<() will sort this vector by version in descending order,
// placing pure AutoCAD first in respective sequence of matching versions.
std::sort (values.begin (), values.end ());

// The operator==() will eliminate adjacent elements with matching version
// numbers (ignoring product code names).
std::unique (values.begin (), values.end ());

// By now, we have only the values that we want to write to versionized CurVers.
std::for_each (values.begin (), values.end (),
               boost::bind (&setCurVer, hModule, _1));

AutoCadInfoVector pureAcadsOnly;
pureAcadsOnly.reserve (values.size ());

// Remove AutoCAD verticals if any remains.
std::remove_copy_if (values.begin (), values.end (),
                     std::back_inserter (pureAcadsOnly),
                     std::not1 (std::mem_fun_ref (&AutoCadInfo::isPureAutoCad)));

// Non-versionized CurVer will hold the latest pure AutoCAD, if available,
// or some latest vertical otherwise.
if (pureAcadsOnly.empty ())
    setNonVersionizedCurVer (hModule, values[0]);
else
    setNonVersionizedCurVer (hModule, pureAcadsOnly[0]);

Add an example C++ code from real life


#include "HSHumanoidNodeParser.hpp"

namespace dynamicsJRLJapan
{
  namespace HumanoidSpecificitiesData {

    namespace fusion = boost::fusion;
    namespace phoenix = boost::phoenix;
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;

    int ReadXMLData3(std::string &aFileName,
		     HumanoidNode &ast)
    {
      std::ifstream in((char *)aFileName.c_str(), std::ios_base::in);

      if (!in)
	{
	  std::cerr << "Error: Could not open input file: "
		    << aFileName << std::endl;
	  return 1;
	}

      std::string storage; // We will read the contents here.
      in.unsetf(std::ios::skipws); // No white space skipping!
      std::copy(
		std::istream_iterator<char>(in),
		std::istream_iterator<char>(),
		std::back_inserter(storage));

      struct HumanoidNode_parser<std::string::const_iterator>
	hsxml; // Our grammar

      using boost::spirit::ascii::space;
      std::string::const_iterator iter = storage.begin();
      std::string::const_iterator end = storage.end();

      // this will print something like: boost::fusion::vector2<int, double>
      display_attribute_of_parser(hsxml);

      bool r = phrase_parse(iter, end, hsxml, space, ast);

      if (r && iter == end)
	{
	  std::cout << "-------------------------\n";
	  std::cout << "Parsing succeeded\n";
	  std::cout << "-------------------------\n";
	  return 0;
	}
      else
	{
	  std::string::const_iterator some = iter+30;
	  std::string context(iter, (some>end)?end:some);
	  std::cout << "-------------------------\n";
	  std::cout << "Parsing failed\n";
	  std::cout << "stopped at: \": " << context << "...\"\n";
	  std::cout << "-------------------------\n";
	  return 1;
	}
    }
  };
};

int main()
{
  namespace dhs=dynamicsJRLJapan::HumanoidSpecificitiesData;
  std::string aFileName("/home/stasse/devel/openrobots/share/hrp2_14/HRP2Specificities.xml");
  dhs::HumanoidNode ahn;
  dhs::ReadXMLData3(aFileName,ahn);
  std::cout <<ahn <<std::endl;
}

Add test during development for parser.


#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int unfairness(vector<int> &a, int k)
{
	sort(a.begin(), a.end());
	int unfairness = a[k - 1] - a[0];
	for (int i = 1; i <= a.size() - k; i++) {
		if (a[i + k - 1] - a[i] < unfairness) {
			unfairness = a[i + k - 1] - a[i];
		}
	}
	return unfairness;
}

int main()
{
	int n, k;
	cin >> n >> k;
	vector<int> a;
	for (int i = 0; i < n; i++) {
		int x;
		cin >> x;
		a.push_back(x);
	}
	cout << unfairness(a, k) << endl;
	return 0;
}

Add the solution to "Angry Children".


//===--------------- RPCUtils.cpp - RPCUtils implementation ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// RPCUtils implementation.
//
//===----------------------------------------------------------------------===//

#include "llvm/ExecutionEngine/Orc/RPCUtils.h"

char llvm::orc::rpc::RPCFatalError::ID = 0;
char llvm::orc::rpc::ConnectionClosed::ID = 0;
char llvm::orc::rpc::ResponseAbandoned::ID = 0;
char llvm::orc::rpc::CouldNotNegotiate::ID = 0;

namespace llvm {
namespace orc {
namespace rpc {

std::error_code ConnectionClosed::convertToErrorCode() const {
  return orcError(OrcErrorCode::RPCConnectionClosed);
}

void ConnectionClosed::log(raw_ostream &OS) const {
  OS << "RPC connection already closed";
}

std::error_code ResponseAbandoned::convertToErrorCode() const {
  return orcError(OrcErrorCode::RPCResponseAbandoned);
}

void ResponseAbandoned::log(raw_ostream &OS) const {
  OS << "RPC response abandoned";
}

CouldNotNegotiate::CouldNotNegotiate(std::string Signature)
    : Signature(std::move(Signature)) {}

std::error_code CouldNotNegotiate::convertToErrorCode() const {
  return orcError(OrcErrorCode::RPCCouldNotNegotiateFunction);
}

void CouldNotNegotiate::log(raw_ostream &OS) const {
  OS << "Could not negotiate RPC function " << Signature;
}

} // end namespace rpc
} // end namespace orc
} // end namespace llvm

Add missing file from r300155.


#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct Node
{
	int data;
	Node* next;
};
int HasCycle(Node* head)
{
    Node* slow = head;
    Node* fast = head;
    while (fast != NULL && fast->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) {
            break;
        }
    }
    return (fast == NULL || fast->next == NULL) ? 0 : 1;
}
int main()
{
	Node *A, *B, *C, *D,*E,*F;
	A = new Node();	B= new Node();  C= new Node(); D = new Node(); E = new Node(); F= new Node();
	// case 1:  NULL list
	if(HasCycle(NULL)) cout<<"1";
	else cout<<"0";
	//case 2:
	A->next = B;
	B->next = C;
	C->next = A;
	if(HasCycle(A)) cout<<"1";
	else cout<<"0";
	//case 3:
	A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = E;
	if(HasCycle(A)) cout<<"1";
	else cout<<"0";
	//case 4:
	A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = NULL;
	if(HasCycle(A)) cout<<"1";
	else cout<<"0";
	// case 5:
	A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = A;
	if(HasCycle(A)) cout<<"1";
	else cout<<"0";
}

Add the solution to determine whether there's a cycle in a linked list.


//
//  main.c
//  SequentialSA
//
//  Created by Vincent Ramdhanie on 11/27/14.
//  Copyright (c) 2014 Vincent Ramdhanie. All rights reserved.
//

#include <time.h>
#include <iostream>
#include <fstream>
#include <iostream>
#include "generator.h"
#include "generator.cpp"

int cost(); //cost function calculates the cost of a certain configuration
void nextConfiguration(); //find another configuration
void loadData(); //load all data from the input file

//define some data structures
int plots[PLOT_N][PLOT_M];

int main(int argc, const char * argv[]) {
    int S;
    double T;
    int N;

    srand(time(NULL));

    generate(plots);
    print(plots);

    nextConfiguration();//initialize the array randomly
    S = cost();
    T = TEMPERATURE;
    N = NUMBER_ITERATIONS;

    int SP;
    int deltaE;
    do{
        printf("Intermediate value: %d\n", S);
        for(int i = 1; i <= N; i++){
            nextConfiguration();
            SP = cost();
            deltaE = SP - S;
            if(deltaE < 0 || deltaE < T){
                S = SP;
            }
        }
        T *= 0.99;
    }while(T > 0.1);

    printf("Final Value: %d\n", S);

    return 0;
}

void nextConfiguration(){
    for(int i = 0; i < PLOT_N; i++){
        for(int j = 0; j < PLOT_M; j++){
            plots[i][j] = (rand() % 1000);
        }
    }
}

int cost(){
    int sum = 0;
        for(int i = 0; i < PLOT_N; i++){
            for(int j = 0; j < PLOT_M; j++){
                sum += plots[i][j];
            }
        }
    return sum;
}

void loadData(){

}

Write the main structure of the algorithm


#include <iostream>
#include <cmath>

using std::cout;
using std::cin;

class Shape {
public:

  virtual double perimeter() const = 0;
  virtual double area() const = 0;
  virtual void print() const = 0;
};

class Rectangle: public Shape {
protected:
  double a;
  double b;

public:

  Rectangle(double _a, double _b): a(_a), b(_b) {}

  double perimeter() const {
    return 2 * (a + b);
  }

  double area() const {
    return a * b;
  }

  void print() const {
    cout << "Rectangle(" << a << ", " << b
         << ")\nPerimeter: " << perimeter() << "\nArea: " << area() << '\n';
  }
};

class Square: public Rectangle {
public:

  Square(double _a): Rectangle(_a, _a) {}

  void print() const {
    cout << "Square(" << a << ")\nPerimeter: "
         << perimeter() << "\nArea: " << area() << '\n';
  }
};

class Circle: public Shape {
  double radius;

public:

  Circle(double _radius): radius(_radius) {}

  double perimeter() const {
    return 2 * M_PI * radius;
  }

  double area() const {
    return M_PI * radius * radius;
  }

  void print() const {
    cout << "Circle(" << radius << ")\nPerimeter: "
         << perimeter() << "\nArea: " << area() << '\n';
  }
};

int main() {
  cout << "Choose an option (r - input a rectangle, s - input a square, c - input a circle): ";
  char option;
  cin >> option;

  Shape* shape = nullptr;

  if (option == 'r') {
    double a, b;
    cin >> a >> b;
    shape = new Rectangle(a, b);
  } else if (option == 's') {
    double a;
    cin >> a;
    shape = new Square(a);
  } else if (option == 'c') {
    double radius;
    cin >> radius;
    shape = new Circle(radius);
  } else {
    cout << "Option '" << option << "' doesn't exist.";
    return 0;
  }

  shape->print();

  return 0;
}

Add solution to week 11 Shapes problem


#include <iostream>
#include <algorithm>
using namespace std;

bool zero(int *a, int n)
{
	int *b = new int[n];
	b[0] = a[0];
	if (a[0] == 0) {
		return true;
	}
	for (int i = 1; i < n; i++) {
		b[i] = b[i - 1] + a[i];
	}
	sort(b, b + n);

	for (int i = 1; i < n; i++) {
		if (b[0] == 0) {
			return true;
		}
		if (b[i] == b[i - 1]) {
			return true;
		}
	}
	return false;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int k;
		cin >> k;
		int *a = new int[k];
		for (int i = 0; i < k; i++) {
			cin >> a[i];
		}
		if (zero(a, k)) {
			cout << "zero" << endl;
		}
		else {
			cout << "nonzero" << endl;
		}
	}
	return 0;
}

Add the solution to "Subtle Summation".


#include <csetjmp>
#include <unistd.h>

#if defined(__APPLE__)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

#include "Halide.h"
#include "HalideRuntimeOpenGL.h"

std::string error_message;

/*
** Don't rely on func.set_error_handler() mechanism, it doesn't seem to catch
** the user OpenGL state errors. That might be a separate bug.
*/
jmp_buf env;
void on_sigabrt (int signum)
{
  longjmp (env, 1);
}
void catching_stderr_abort(std::function<void ()> func)
{
    auto ferr = tmpfile();
    auto prev_stderr = dup(2);
    dup2(fileno(ferr), 2);
    if (setjmp (env) == 0) {
        auto prev_handler = signal(SIGABRT, &on_sigabrt);
        (func)();
        signal(SIGABRT, prev_handler);
    }
    fseek(ferr, 0, SEEK_END);
    error_message.resize(ftell(ferr));
    rewind(ferr);
    fread(&error_message[0], 1, error_message.size(), ferr);
    dup2(prev_stderr, 2);
    close(prev_stderr);
}

using namespace Halide;

int main()
{
    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Image<uint8_t> output(255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = Halide::cast<uint8_t>(255);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);

    // Let Halide initialize OpenGL
    g.realize(output);

    // Bad OpenGL call leaves OpenGL in a bad state
    glEnableVertexAttribArray(-1);

    // Halide should report that the OpenGL context is in a bad state due to user code`
    catching_stderr_abort( [&] () { g.realize(output); } );

    if (error_message.empty()) {
        fprintf(stderr, "Failed to report error in user OpenGL state\n");
        return 1;
    }
    else if (error_message.find("user OpenGL state") == std::string::npos) {
        error_message.erase(error_message.size() - 1); // remove trailing newline
        fprintf(stderr, "Reported error '%s' rather than identifying error at 'user OpenGL state'\n", error_message.c_str());
        return 1;
    }

    printf("Success!\n");
    return 0;
}

Add (failing) test that halide reports user error when called with OpenGL in bad state


/**
 * Copyright (c) 2014-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <CSSLayout/CSSLayout.h>
#include <gtest/gtest.h>

TEST(CSSLayoutTest, dirty_propagation) {
  const CSSNodeRef root = CSSNodeNew();
  CSSNodeStyleSetAlignItems(root, CSSAlignFlexStart);
  CSSNodeStyleSetWidth(root, 100);
  CSSNodeStyleSetHeight(root, 100);

  const CSSNodeRef root_child0 = CSSNodeNew();
  CSSNodeStyleSetWidth(root_child0, 50);
  CSSNodeStyleSetHeight(root_child0, 20);
  CSSNodeInsertChild(root, root_child0, 0);

  const CSSNodeRef root_child1 = CSSNodeNew();
  CSSNodeStyleSetWidth(root_child1, 50);
  CSSNodeStyleSetHeight(root_child1, 20);
  CSSNodeInsertChild(root, root_child1, 1);

  CSSNodeCalculateLayout(root, CSSUndefined, CSSUndefined, CSSDirectionLTR);

  CSSNodeStyleSetWidth(root_child0, 20);

  EXPECT_TRUE(CSSNodeIsDirty(root_child0));
  EXPECT_FALSE(CSSNodeIsDirty(root_child1));
  EXPECT_TRUE(CSSNodeIsDirty(root));

  CSSNodeCalculateLayout(root, CSSUndefined, CSSUndefined, CSSDirectionLTR);

  EXPECT_FALSE(CSSNodeIsDirty(root_child0));
  EXPECT_FALSE(CSSNodeIsDirty(root_child1));
  EXPECT_FALSE(CSSNodeIsDirty(root));
}

TEST(CSSLayoutTest, dirty_propagation_only_if_prop_changed) {
  const CSSNodeRef root = CSSNodeNew();
  CSSNodeStyleSetAlignItems(root, CSSAlignFlexStart);
  CSSNodeStyleSetWidth(root, 100);
  CSSNodeStyleSetHeight(root, 100);

  const CSSNodeRef root_child0 = CSSNodeNew();
  CSSNodeStyleSetWidth(root_child0, 50);
  CSSNodeStyleSetHeight(root_child0, 20);
  CSSNodeInsertChild(root, root_child0, 0);

  const CSSNodeRef root_child1 = CSSNodeNew();
  CSSNodeStyleSetWidth(root_child1, 50);
  CSSNodeStyleSetHeight(root_child1, 20);
  CSSNodeInsertChild(root, root_child1, 1);

  CSSNodeCalculateLayout(root, CSSUndefined, CSSUndefined, CSSDirectionLTR);

  CSSNodeStyleSetWidth(root_child0, 50);

  EXPECT_FALSE(CSSNodeIsDirty(root_child0));
  EXPECT_FALSE(CSSNodeIsDirty(root_child1));
  EXPECT_FALSE(CSSNodeIsDirty(root));
}

Add tests for dirty propagation


// Chapter 25, exercise 11: like exercise 10, but keep the bits in a bitset<32>

#include<iostream>
#include<bitset>

using namespace std;

int main()
{
    bitset<32> bs;
    bs = 15121<<10; // PFN
    bs |= 6<<4;     // CCA
    bs[3] = 1;      // nonreachable
    bs[0] = 1;      // global
    cout << "Using a bitset<32>:\n"
        << "PFN: " << ((bs>>10)&bitset<32>(0x3fffff)).to_ulong() << '\n'
        << "CCA: " << ((bs>>4)&bitset<32>(0x7)).to_ulong() << '\n'
        << "nonreachable: " << bs[3] << '\n'
        << "dirty: " << bs[2] << '\n'
        << "valid: " << bs[1] << '\n'
        << "global: " << bs[0] << '\n';
}

Add Chapter 25, exercise 11


#include "gfakluge.hpp"

int main() {
    gfak::GFAKluge og;

    og.set_version(1);

    gfak::sequence_elem s;
    s.sequence = "ACCTT";
    s.name = "11";

    gfak::sequence_elem t;
    t.sequence = "TCAAGG";
    t.name = "12";

    gfak::sequence_elem u;
    u.sequence = "CTTGATT";
    u.name = "13";

    gfak::link_elem l;
    l.source_name = s.name;
    l.sink_name = t.name;
    l.source_orientation_forward = true;
    l.sink_orientation_forward = false;
    l.cigar = "4M";

    gfak::link_elem m;
    m.source_name = t.name;
    m.sink_name = u.name;
    m.source_orientation_forward = false;
    m.sink_orientation_forward = true;
    m.cigar = "5M";

    gfak::link_elem n;
    n.source_name = s.name;
    n.sink_name = u.name;
    n.source_orientation_forward = true;
    n.sink_orientation_forward = true;
    n.cigar = "3M";

    gfak::path_elem p;
    p.name = "14";
    p.segment_names = {s.name, t.name, u.name};
    p.orientations = {true, false, true};
    p.overlaps = {"4M", "5M"};

    og.add_sequence(s);
    og.add_sequence(t);
    og.add_sequence(u);
    og.add_link(s, l);
    og.add_link(t, m);
    og.add_link(s, n);
    og.add_path(p.name, p);

    og.gfa_2_ize();
    og.gfa_1_ize();
    og.set_version(2.0);
    cout << og << endl;

}

Add a small test case


#include <iomanip>
#include <iostream>
#include "TimeUtil.h"

int main() {
    std::cout << std::setprecision(10) << TimeUtil::GetJulianDayNumber() << '\n';
    return 0;
}

Test harness for the new TimeUtil::GetJulianDayNumber() function.


// Naive solution would first sort the numbers, then find the maximum gap.
// But there is a better solution: use the pigeonhole principle.
// Suppose the sorted sequence of arguments are a1, a2, ..., an.
// There are n-1 gaps and the accumulated gap is an-a1. The average gap is
// (an-a1)/(n-1). By the pigeonhole principle, the maximum gap is greater or
// equal to the average. We could assign the numbers into n buckets [a1, a1+avg),
// [a1+avg, a1+avg*2), ..., [a1+avg*(n-2), a1+avg*(n-1)), [an, an + avg).
// The maximum gap can't be between two numbers in the same bucket. It must be the
// maximum difference between the maximum of a lower bucket and the next minimum
// of a higher bucket. Note the two buckets may not be consecutive because there
// may be empty bucket.

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        size_t n = nums.size();
        if (n < 2) return 0;
        int maxi = *max_element(nums.begin(), nums.end());
        int mini = *min_element(nums.begin(), nums.end());
		int total_gap = maxi - mini;
        if (total_gap == 0) { //we need to divide total_gap later
            return 0;
        }

        vector<int> range_max(n, -1);
        vector<int> range_min(n, INT_MAX);
        for (size_t i = 0; i < n; ++i) {
			// The following statement is actually average=total_gap/(n-1), then (nums[i]-mini)/average
			// I write it as it is to avoid possible precision problems.
            int index = static_cast<long long>(nums[i]-mini)*(n-1)/total_gap;
            range_max[index] = std::max(range_max[index], nums[i]);
            range_min[index] = std::min(range_min[index], nums[i]);
        }

        int max_gap = 0, last = 0;
        for (size_t i = 1; i < n; ++i) {
            if (range_max[i] == -1) {
                continue;
            }
            max_gap = std::max(range_min[i]-range_max[last], max_gap);
            last = i;
        }

        return max_gap;
    }
};

Add a solution for problem 164: Maximum Gap.


/** \file
 *
 *  Copyright (c) 2015 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"

#include <jsonv/algorithm.hpp>
#include <jsonv/functional.hpp>
#include <jsonv/value.hpp>
#include <jsonv/serialization_builder.hpp>

#include <algorithm>
#include <vector>

namespace jsonv_test
{

using namespace jsonv;

using string_list = std::vector<std::string>;

template <typename FJsonCmp, typename FStrCmp>
static void check_sort(const formats& fmts, string_list source, FJsonCmp json_cmp, FStrCmp str_cmp)
{
    value orig = to_json(source, fmts);
    if (source != extract<string_list>(orig, fmts))
        throw std::logic_error("Extraction or encoding is broken");

    std::sort(source.begin(),     source.end(),     str_cmp);
    std::sort(orig.begin_array(), orig.end_array(), json_cmp);

    if (source != extract<string_list>(orig, fmts))
        throw std::logic_error("Sorting did not produce identical results");
}

TEST(functional_sort_strings)
{
    formats fmts =
        formats::compose
        ({
            formats_builder()
                .register_container<std::vector<std::string>>(),
            formats::defaults()
        });
    std::vector<std::string> source = { "fire", "wind", "water", "earth", "heart" };

    check_sort(fmts, source, value_less(),          std::less<std::string>());
    check_sort(fmts, source, value_less_equal(),    std::less_equal<std::string>());
    check_sort(fmts, source, value_greater(),       std::greater<std::string>());
    check_sort(fmts, source, value_greater_equal(), std::greater_equal<std::string>());
}

}

Add some basic unit tests for the value functors.


#include <iostream>
#include <bitset>
#include <vector>

using namespace std;

template <unsigned N>
class TestResult {
    template <unsigned M>
    friend ostream& operator<<(ostream&, TestResult<M>&);
public:

    TestResult() = default;
    TestResult(unsigned long long u) : ans(u) { }
    TestResult(const string &s) : ans(s) { }
    TestResult(const char* cp) : ans(cp) { }

    //required by test 17.12
    void set_answer(size_t index, bool answer = true) {
        ans.set(index, answer);
    }

    bool get_answer(size_t index) {
        return ans[index];
    }

    size_t size() const {
        return ans.size();
    }

private:
    bitset<N> ans;
};
template <unsigned N>
ostream& operator<<(ostream &os, TestResult<N> &tr) {
    os << tr.ans;
    return os;
}

int main() {
    //test 17.11
    TestResult<32> tr1(8);
    TestResult<10> tr2("1001010001");
    cout << tr1 << endl;
    cout << tr2 << endl;

    //test 17.13
    vector<bool> bvec = {1, 1, 1, 1, 1, 0, 0, 0, 0, 0};
    TestResult<10> tr3;
    for(size_t i = 0; i != bvec.size(); ++ i) {
        tr3.set_answer(i, bvec[i]);
    }
    cout << tr3 << endl;

    //test get_answer
    //notice: low bit in the head
    for(size_t i = 0; i != tr3.size(); ++ i) {
        cout << tr3.get_answer(i) << ends;
    }
    cout << endl;

    return 0;
}

Add solution for chapter 17 test 11, 12, 13


#include "IncomingConnectionValidator.hpp"

#include <boost/algorithm/string.hpp>

using namespace std;

sip::IncomingConnectionValidator::IncomingConnectionValidator(std::string validUriExpression)
        : validUriExpression(validUriExpression),
          logger(log4cpp::Category::getInstance("IncomingConnectionValidator")) {

    vector<string> separateUris;
    boost::split(separateUris, validUriExpression, boost::is_any_of("\t "));
    for (auto &uri : separateUris) {
        boost::replace_all(uri, ".", "\\.");
        boost::replace_all(uri, "*", "[\\+\\w]*");
        uriRegexVec.push_back(boost::regex(uri));
    }
}

bool sip::IncomingConnectionValidator::validateUri(std::string uri) {
    boost::regex addressRegex("[\"\\+\\w ]*<sip:([\\+\\w\\.]+@[\\w\\.]+)>");

    boost::smatch s;

    if (not boost::regex_match(uri, s, addressRegex)) {
        logger.warn("URI has invalid format: %s", uri.c_str());
        return false;
    }

    string rawAddress = s[1].str();

    for (auto &reg : uriRegexVec) {
        if (boost::regex_match(rawAddress, s, reg)) {
            logger.info("URI %s is valid.", rawAddress.c_str());
            return true;
        }
    }

    logger.info("URI %s not valid.", rawAddress.c_str());

    return false;
}

#include "IncomingConnectionValidator.hpp"

#include <boost/algorithm/string.hpp>

using namespace std;

sip::IncomingConnectionValidator::IncomingConnectionValidator(std::string validUriExpression)
        : validUriExpression(validUriExpression),
          logger(log4cpp::Category::getInstance("IncomingConnectionValidator")) {

    vector<string> separateUris;
    boost::split(separateUris, validUriExpression, boost::is_any_of("\t "));
    for (auto &uri : separateUris) {
        boost::replace_all(uri, ".", "\\.");
        boost::replace_all(uri, "*", "[\\+\\w]*");
        uriRegexVec.push_back(boost::regex(uri));
    }
}

bool sip::IncomingConnectionValidator::validateUri(std::string uri) {
    boost::regex addressRegex("[\"\\+\\w\\. ]*<?sip:([\\+\\w\\.]+@[\\w\\.]+)>?");

    boost::smatch s;

    if (not boost::regex_match(uri, s, addressRegex)) {
        logger.warn("URI has invalid format: %s", uri.c_str());
        return false;
    }

    string rawAddress = s[1].str();

    for (auto &reg : uriRegexVec) {
        if (boost::regex_match(rawAddress, s, reg)) {
            logger.info("URI %s is valid.", rawAddress.c_str());
            return true;
        }
    }

    logger.info("URI %s not valid.", rawAddress.c_str());

    return false;
}

Update URI validation regex to be more generic.


#include <bits/stdc++.h>
using namespace std;
bool isPerfectSquare(int x){
  int s = sqrt(x);
  return (s*s == x);
}
bool isFibonacci(int n){
    // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    // is a perferct square, this is deduced of the discriminant
    //of binnets formule
    return isPerfectSquare(5*n*n + 4) || isPerfectSquare(5*n*n - 4);
}

// A utility function to test above functions
int main() {
  for (int i = 1; i <= 10; i++)
     isFibonacci(i)? cout << i << " is a Fibonacci Number \n":
                     cout << i << " is a not Fibonacci Number \n" ;
  return 0;
}

Add algorithm to check if a number belong to fibo series.


// RUN: %llvmgxx -c -emit-llvm %s -o - | llvm-dis | grep noalias

class foo {
  int member[4];

  void bar(int * a);

};

void foo::bar(int * a) __restrict {
  member[3] = *a;
}

Clean up C++ restrict test cases and add a test for restrict qualified methods.


// 66. Plus One
/**
 * Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
 *
 * You may assume the integer do not contain any leading zero, except the number 0 itself.
 *
 * The digits are stored such that the most significant digit is at the head of the list.
 *
 * Subscribe to see which companies asked this question
 *
 * Tags: Array, Math
 *
 * Similar Problems: (M) Multiply Strings, (E) Add Binary, (M) Plus One Linked List
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int n = digits.size(), sum = 0, carry = 1;
        for (int i = n - 1; i >= 0; i--) {
            sum = digits[i] + carry;
            carry = sum / 10;
            digits[i] = sum % 10;
            if (!carry)
                break;  // no change in the remaining digits
        }

        // if carry still exists after the most significant digit, the original array must be all '9'
        if (carry) {
            digits[0] = 1;
            digits.push_back(0);
        }

        return digits;
    }
};

int main() {
    vector<int> digits = {9, 9, 9, 9};
    Solution sol;
    vector<int> res = sol.plusOne(digits);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i];
    }
    cout << endl;
    cin.get();

    return 0;
}

Add Solution for 066 Plus One


#include <iostream>

using namespace std;

class A {
public:
    A() {
        cout << "A()" << endl;
    }
};

class B : public A {
public:
    B() {
        cout << "B()" << endl;
    }
};

class C : public B {
public:
    C() {
        cout << "C()" << endl;
    }
};

class X {
public:
    X() {
        cout << "X()" << endl;
    }
};

class Y {
public:
    Y() {
        cout << "Y()" << endl;
    }
};

class Z : public X, public Y {
public:
    Z() {
        cout << "Z()" << endl;
    }
};

class MI : public C, public Z {
public:
    MI() {
        cout << "MI()" << endl;
    }
};

int main() {
    MI mi;
}

Add solution for chapter 18, test 22


// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin -std=c++11 %s -o - | FileCheck %s

union E {
  int a;
  float b;
  int bb() { return a;}
  float aa() { return b;}
  E() { a = 0; }
};

E e;

// CHECK: metadata !{i32 {{.*}}, null, metadata !"E", metadata !6, i32 3, i64 32, i64 32, i64 0, i32 0, null, metadata !11, i32 0, null} ; [ DW_TAG_union_type ]
// CHECK: metadata !{i32 {{.*}}, i32 0, metadata !10, metadata !"bb", metadata !"bb", metadata !"_ZN1E2bbEv", metadata !6, i32 6, metadata !17, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !19, i32 6} ; [ DW_TAG_subprogram ]
// CHECK: metadata !{i32 {{.*}}, i32 0, metadata !10, metadata !"aa", metadata !"aa", metadata !"_ZN1E2aaEv", metadata !6, i32 7, metadata !22, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !24, i32 7} ; [ DW_TAG_subprogram ]
// CHECK: metadata !{i32 {{.*}}, i32 0, metadata !10, metadata !"E", metadata !"E", metadata !"", metadata !6, i32 8, metadata !7, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !27, i32 8} ; [ DW_TAG_subprogram ]

Add a testcase for C++11 union support.


#include <vector>
#include <queue>
#include <unordered_set>
#include <iostream>
using namespace std;

void bfs(int S, const vector<vector<int>>& adjLists, vector<int>& results) {
  queue<int> toTraverse;
  toTraverse.push(S);

  unordered_set<int> traversed;
  traversed.emplace(S);

  while (!toTraverse.empty()) {
    int currentNode = toTraverse.front();
    toTraverse.pop();

    for (int successor : adjLists[currentNode - 1]) {
      if (traversed.find(successor) == traversed.end()) {
        toTraverse.push(successor);
        traversed.emplace(successor);
        results[successor - 1] = results[currentNode - 1] + 6;
      }
    }
  }
}

int main() {
  int T;
  cin >> T;

  for (int i = 0; i < T; ++i) {
    int N, M;
    cin >> N >> M;

    vector<vector<int>> adjLists(N);
    for (int j = 0; j < M; ++j) {
      int x, y;
      cin >> x >> y;
      adjLists[x - 1].push_back(y);
      adjLists[y - 1].push_back(x);
    }

    int S;
    cin >> S;

    vector<int> results(N, 0);

    bfs(S, adjLists, results);

    for (int j = 0; j < N; ++j) {
      if (j + 1 == S) {
        continue;
      }

      cout << (results[j] ? results[j] : -1) << ' ';
    }
    cout << '\n';
  }

  return 0;
}

Add solution to second homework


//
//  TestOptocoupler.cpp
//  FxDSP
//
//  Created by Hamilton Kibbe on 5/3/15.
//  Copyright (c) 2015 Hamilton Kibbe. All rights reserved.
//

#include "Optocoupler.h"
#include <math.h>
#include <gtest/gtest.h>

TEST(OptocouplerSingle, Smoketest)
{
    const Opto_t types[2] = {OPTO_LDR, OPTO_PHOTOTRANSISTOR};
    float sinewave[10000];
    float out[10000];
    for (unsigned i = 0; i < 10000; ++i)
    {
        sinewave[i] = sinf((6000 * M_PI * i)/10000); // 3000Hz sinewave at 44100
    }
    for (unsigned i = 0; i < sizeof(types); ++i)
    {
        Opto* opto = OptoInit(types[i], 0.5, 44100);
        ASSERT_NE((void*)opto, (void*)NULL);

        OptoProcess(opto, out, sinewave, 10000);
        OptoFree(opto);
    }
}

TEST(OptocouplerDouble, Smoketest)
{
    const Opto_t types[2] = {OPTO_LDR, OPTO_PHOTOTRANSISTOR};
    double sinewave[10000];
    double out[10000];
    for (unsigned i = 0; i < 10000; ++i)
    {
        sinewave[i] = sin((6000 * M_PI * i)/10000); // 3000Hz sinewave at 44100
    }
    for (unsigned i = 0; i < sizeof(types); ++i)
    {
        OptoD* opto = OptoInitD(types[i], 0.5, 44100);
        ASSERT_NE((void*)opto, (void*)NULL);

        OptoProcessD(opto, out, sinewave, 10000);
        OptoFreeD(opto);
    }
}

Add initial opto model tests


#include "usbutil.h"

USBDevice USB_DEVICE(usbCallback);
USB_HANDLE USB_INPUT_HANDLE = 0;

void send_message(uint8_t* message, int message_size) {
    int currentByte = 0;
    Serial.print("sending message: ");
    Serial.println((char*)message);

    while(currentByte <= message_size) {
        while(USB_DEVICE.HandleBusy(USB_INPUT_HANDLE));
        int bytesToTransfer = min(USB_PACKET_SIZE, message_size - currentByte);
        USB_INPUT_HANDLE = USB_DEVICE.GenWrite(DATA_ENDPOINT, message,
                bytesToTransfer);
        currentByte += bytesToTransfer;
    }
}

void initializeUsb() {
    Serial.print("Initializing USB...  ");
    USB_DEVICE.InitializeSystem(true);
    while(USB_DEVICE.GetDeviceState() < CONFIGURED_STATE);
    Serial.println("Done.");
}

static boolean usbCallback(USB_EVENT event, void *pdata, word size) {
    // initial connection up to configure will be handled by the default
    // callback routine.
    USB_DEVICE.DefaultCBEventHandler(event, pdata, size);

    switch(event) {
    case EVENT_CONFIGURED:
        Serial.println("Event: Configured");
        // Enable DATA_ENDPOINT for input
        USB_DEVICE.EnableEndpoint(DATA_ENDPOINT,
                USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
        break;
    default:
        break;
    }
}

#include "usbutil.h"

USBDevice USB_DEVICE(usbCallback);
USB_HANDLE USB_INPUT_HANDLE = 0;

void send_message(uint8_t* message, int message_size) {
    int nextByteIndex = 0;
    Serial.print("sending message: ");
    Serial.println((char*)message);

    while(nextByteIndex < message_size) {
        while(USB_DEVICE.HandleBusy(USB_INPUT_HANDLE));
        int bytesToTransfer = min(USB_PACKET_SIZE,
                message_size - nextByteIndex);
        USB_INPUT_HANDLE = USB_DEVICE.GenWrite(DATA_ENDPOINT,
                (uint8_t*)(message + nextByteIndex), bytesToTransfer);
        nextByteIndex += bytesToTransfer;
    }
}

void initializeUsb() {
    Serial.print("Initializing USB...  ");
    USB_DEVICE.InitializeSystem(true);
    while(USB_DEVICE.GetDeviceState() < CONFIGURED_STATE);
    Serial.println("Done.");
}

static boolean usbCallback(USB_EVENT event, void *pdata, word size) {
    // initial connection up to configure will be handled by the default
    // callback routine.
    USB_DEVICE.DefaultCBEventHandler(event, pdata, size);

    switch(event) {
    case EVENT_CONFIGURED:
        Serial.println("Event: Configured");
        // Enable DATA_ENDPOINT for input
        USB_DEVICE.EnableEndpoint(DATA_ENDPOINT,
                USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
        break;
    default:
        break;
    }
}

Fix an off by one error when sending messages over USB.


#ifdef _WINDOWS

/*
 * NOTE: Some macros must be defined in project options of Visual Studio.
 *       - NOMINMAX
 *         To use std::min(), std::max().
 * NOTE: Suppress some warnings of Visual Studio.
 *       - C4251
 */

#include <windows.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

#endif

Enable to build empty components for Windows.


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/aura/window_observer.h"

#include "base/logging.h"
#include "ui/aura/window.h"

namespace aura {

WindowObserver::WindowObserver() : observing_(0) {
}

WindowObserver::~WindowObserver() {
  // TODO(flackr): Remove this check and observing_ counter when the cause of
  // http://crbug.com/365364 is discovered.
  CHECK_EQ(0, observing_);
}

void WindowObserver::OnObservingWindow(aura::Window* window) {
  if (!window->HasObserver(this))
    observing_++;
}

void WindowObserver::OnUnobservingWindow(aura::Window* window) {
  if (window->HasObserver(this))
    observing_--;
}

}  // namespace aura

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/aura/window_observer.h"

#include "base/logging.h"
#include "ui/aura/window.h"

namespace aura {

WindowObserver::WindowObserver() : observing_(0) {
}

WindowObserver::~WindowObserver() {
  CHECK_EQ(0, observing_);
}

void WindowObserver::OnObservingWindow(aura::Window* window) {
  if (!window->HasObserver(this))
    observing_++;
}

void WindowObserver::OnUnobservingWindow(aura::Window* window) {
  if (window->HasObserver(this))
    observing_--;
}

}  // namespace aura

Remove TODO to remove 0 observed window checks on WindowObserver.


// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "unit_tests.hpp"
#include "mfem.hpp"

namespace mfem
{

#ifdef MFEM_USE_MPI

TEST_CASE("HypreParVector I/O", "[Parallel], [HypreParVector]")
{
   // Create a test vector (two entries per rank) with entries increasing
   // sequentially. Write the vector to a file, read it into another vector, and
   // make sure we get the same answer.

   int world_size, rank;
   MPI_Comm_size(MPI_COMM_WORLD, &world_size);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
   int size_per_rank = 2;

   HYPRE_BigInt glob_size = world_size*size_per_rank;
   std::vector<HYPRE_BigInt> col;
   if (HYPRE_AssumedPartitionCheck())
   {
      int offset = rank*size_per_rank;
      col = {offset, offset + size_per_rank};
   }
   else
   {
      col.resize(world_size+1);
      for (int i=0; i<world_size; ++i)
      {
         col[i] = i*size_per_rank;
      }
   }

   // Initialize vector and write to files
   HypreParVector v1(MPI_COMM_WORLD, glob_size, col.data());
   for (int i=0; i<size_per_rank; ++i)
   {
      v1(i) = rank*size_per_rank + i;
   }
   v1.Print("vec");

   // Check that we read the same vector from disk
   HypreParVector v2;
   v2.Read(MPI_COMM_WORLD, "vec");
   v2 -= v1;
   REQUIRE(InnerProduct(v2, v2) == MFEM_Approx(0.0));

   // Clean up
   std::string prefix = "vec.";
   std::string suffix = std::to_string(rank);
   remove((prefix + suffix).c_str());
   remove((prefix + "INFO." + suffix).c_str());
}

#endif // MFEM_USE_MPI

} // namespace mfem

Add unit test for HypreParVector::Read


// 143_Reorder_List.cpp : Defines the entry point for the console application.
/**
 * Given a singly linked list L: L0->L1->->Ln-1->Ln,
 * reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->
 *
 * You must do this in-place without altering the nodes' values.
 *
 * For example,
 * Given {1,2,3,4}, reorder it to {1,4,2,3}.
 *
 * Tags: Linked List
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    ListNode(int x, ListNode *p) : val(x), next(p) {}
};

class Solution {
public:
    void reorderList(ListNode* head) {
        if ((head == NULL) || (head->next == NULL))
        {
            return;
        }

        // cut the list into two halves
        ListNode *slow = head, *fast = head->next;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }

        // reverse the second list
        ListNode *curr = slow->next, *prev = NULL;
        while (curr)
        {
            ListNode *next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }

        // terminate the list at the end of first half
        slow->next = NULL;

        // merge two lists
        while (prev)
        {
            ListNode *next1 = head->next, *next2 = prev->next;
            head->next = prev;
            prev->next = next1;
            head = next1;
            prev = next2;
        }
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2);
    ListNode *head = &node1, *curr = head;
    cout << "Before Reorder:" << endl;
    while (curr)
    {
        cout << curr->val << " ";
        curr = curr->next;
    }
    cout << endl;

    Solution mySolution;
    mySolution.reorderList(head);
    curr = head;
    cout << "After Reorder:" << endl;
    while (curr)
    {
        cout << curr->val << " ";
        curr = curr->next;
    }
    cout << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 143


/*
 * Largest prime factor
 *
 * The prime factors of 13'195 are 5, 7, 13 and 29.
 *
 * What is the largest prime factor of the number 600'851'475'143?
 */

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <vector>

#include "sieve.hpp"

constexpr Long number = 600'851'475'143;

int main(int, char **) {
    std::vector<Long> primes;
    // Compute all prime numbers less than or equal to `sqrt(number)`
    do {
        sieve(primes, primes.size() + 100);
    } while(primes.back() < static_cast<Long>(std::sqrt(number)));

    auto it = std::find_if(primes.rbegin(), primes.rend(),
            [](Long x) { return x <= static_cast<Long>(std::sqrt(number)); });
    it = std::find_if(
            it, primes.rend(), [](Long x) { return number % x == 0; });
    auto maxFactor = (it != primes.rend() ? *it : number);

    std::cout << "Project Euler - Problem 3: Largest prime factor\n\n";
    std::cout << "The largets prime factor of " << number << " is\n"
              << maxFactor << '\n';
}

Add solution to problem 3.


/*
  Copyright (c) 2014, Randolph Voorhies, Shane Grant
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of cereal nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "common.hpp"
#include <boost/test/unit_test.hpp>

template <typename T>
struct template_test_struct
{
    T x;
};

template <typename Archive, typename T>
std::string save_minimal(Archive const &,
        template_test_struct<T> const & m)
{
    return std::to_string(m.x);
}

template <typename Archive, typename T>
void load_minimal(Archive const &,
        template_test_struct<T>& m, std::string const & str)
{
    m.x = std::stoi(str);
}

template <class IArchive, class OArchive>
void test_template_structs_minimal()
{
    template_test_struct <uint32_t> mb_i;

    std::ostringstream os;
    {
      OArchive oar(os);
      oar(mb_i);
    }

    decltype(mb_i) mb_o;

    std::istringstream is(os.str());
    {
      IArchive iar(is);
      iar(mb_o);
    }

    BOOST_CHECK(mb_i.x == mb_o.x);

}

BOOST_AUTO_TEST_CASE( template_test_struct_minimal_all )
{
    test_template_structs_minimal<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>();
    test_template_structs_minimal<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>();
    test_template_structs_minimal<cereal::XMLInputArchive, cereal::XMLOutputArchive>();
    test_template_structs_minimal<cereal::JSONInputArchive, cereal::JSONOutputArchive>();
}

Add serialization of minimal template unit-test that is broken


/** \brief Test harness for the SimpleXmlParser class.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015 Universitätsbiblothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "SimpleXmlParser.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << progname << " xml_input\n";
    std::exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    progname = argv[0];

    if (argc != 2)
        Usage();

    const std::string input_filename(argv[1]);
    File input(input_filename, "rm");
    if (not input)
	Error("can't open \"" + input_filename + "\" for reading!");

    SimpleXmlParser::Type type;
    std::string data;
    std::map<std::string, std::string> attrib_map;
    SimpleXmlParser xml_parser(&input);
    while (xml_parser.getNext(&type, &attrib_map, &data)) {
	switch (type) {
	case SimpleXmlParser::UNINITIALISED:
	    Error("we should never get here as UNINITIALISED should never be returned!");
	case SimpleXmlParser::START_OF_DOCUMENT:
	    std::cout << "START_OF_DOCUMENT()\n";
	    break;
	case SimpleXmlParser::END_OF_DOCUMENT:
	    break;
	case SimpleXmlParser::ERROR:
	    Error("we should never get here because SimpleXmlParser::getNext() should have returned false!");
	case SimpleXmlParser::OPENING_TAG:
	    std::cout << "OPENING_TAG(" << data;
	    for (const auto &name_and_value : attrib_map)
		std::cout << ' ' << name_and_value.first << '=' << name_and_value.second;
	    std::cout << ")\n";
	    break;
	case SimpleXmlParser::CLOSING_TAG:
	    std::cout << "CLOSING_TAG(" << data << ")\n";
	    break;
	case SimpleXmlParser::CHARACTERS:
	    std::cout << "CHARACTERS(" << data << ")\n";
	    break;
	}
    }

    Error("XML parsing error: " + xml_parser.getLastErrorMessage());
}

Test harness for the new SimpleXMLParser class.


/*****************************************************************************
 * File: keyShiftCypher.cpp
 *
 * Description: Take an encrypted text string, shift it by the input key, and
 *              print the decrypted string.
 *
 * Author: Tim Troxler
 *
 * Created: 1/5/2015
 *
 ****************************************************************************/

// STL includes
#include <string>
#include <iostream>

// Boost includes
#include <boost/algorithm/string.hpp>

static const int ALPHABET_LENGTH = 26;

// Return if the character is in the alphabet or not
// True if a-z
// False all others
inline bool isAlpha(const char c)
{
    return (c >= 'a' && c <= 'z');
}

// Shift each alphabetic character of the encrypted string by the
// corresponding character in the key, and return the decrypted string.
std::string solver(const std::string encrypted, const std::string key)
{
    // Convert to lowercase for simplicity
    auto decrypted = encrypted;
    std::transform(decrypted.begin(), decrypted.end(), decrypted.begin(), ::tolower);

    const int keylength = key.length();

    // Keep track of any whitespace or punctuation
    int ignoreChars = 0;

    // For each encrypted character...
    for(unsigned int cryptIdx = 0; cryptIdx < decrypted.length(); cryptIdx++) {
        auto c = decrypted.at(cryptIdx);

        // If in the lowercase alphabet...
        if(isAlpha(c)) {

            // Find the corresponding index in the key string
            const int keyIdx = (cryptIdx - ignoreChars) % keylength;

            // Shift the encrypted character by the key; wrap within the size
            // of the alphabet
            auto temp = ((c - key.at(keyIdx)) % ALPHABET_LENGTH);
            if(temp < 0) {
                temp += ALPHABET_LENGTH;
            }

            // Convert back to lowercase text
            decrypted[cryptIdx] = temp + 'a';
        } else {
            ignoreChars++;
        }
    }

    return decrypted;
}

int main(int argc, char* argv[])
{
    // Very simple validation - require the 2 input strings
    // To do - any error handling
    if (argc != 3) {
        std::cout << "This program requires two strings as input:" << std::endl;
        std::cout << "keyShiftCypher.exe \"encrypted string\" \"keystring\"" << std::endl;
    }

    // Decrypt and display
    auto encrypted = std::string(argv[1]);
    auto key = std::string(argv[2]);
    std::cout << "Solving cyphertext '" << encrypted << "' with key '" << key << "'." << std::endl;
    auto decrypted = solver(encrypted, key);
    std::cout << decrypted << std::endl;

    return 0;
}

Add a program to take an encrypted text string, shift it by the input key, and print the decrypted string.


#include "UnitTest++/UnitTest++.h"

#include <fstream>
#include <cereal/archives/binary.hpp>

SUITE( CerealTest )
{
    TEST( basicSaveAndLoad )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( actualData );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }
}

Test cereal for a basic save and load operation


// 203. Remove Linked List Elements
/**
 * Remove all elements from a linked list of integers that have value val.
 *
 * Example
 * Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
 * Return: 1 --> 2 --> 3 --> 4 --> 5
 *
 * Tags: Linked List
 *
 * Similar Problems: (E) Remove Element (E) Delete Node in a Linked List
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    ListNode(int x, ListNode *p) : val(x), next(p) {}
};

// iterative solution
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode dummy(0);
        dummy.next = head;

        ListNode *prev = &dummy, *curr = head;
        while (curr != NULL) {
            if (curr->val == val) {
                prev->next = curr->next;
            }
            else {
                // move prev forward
                prev = curr;
            }

            curr = curr->next;
        }

        return dummy.next;
    }
};

// recursive solution
class Solution_recursive {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (head == NULL) {
            return NULL;
        }

        head->next = removeElements(head->next, val);

        // return head->next if head is deleted
        return (head->val == val) ? head->next : head;
    }
};

int main() {
    ListNode node7(6), node6(5, &node7), node5(4, &node6), node4(3, &node5), node3(6, &node4), node2(2, &node3), node1(1, &node2);
    Solution sol;
    ListNode *newhead = sol.removeElements(&node1, 6);
    for (ListNode *p = newhead; p != NULL; p = p->next) {
        cout << p->val << " ";
    }
    cout << endl;
    cin.get();

    return 0;
}

Add Solution for 203 Remove Linked List Elements


#include <iostream>

using namespace std;

int powLastFourDigits(int number, long long unsigned power) {
    number %= 10000;
    if (power == 0)
        return 1;

    return (powLastFourDigits(number, power - 1) * number) % 10000;
}

int powIterLastFourDigits(int number, long long unsigned power) {
    int result = 1;
    number %= 10000;

    for (long long unsigned i = 0; i < power; i++)
        result = (result * number) % 10000;

    return result;
}

int fastPowLastFourDigits(int number, long long unsigned power) {
    number %= 10000;

    if (power == 0)
        return 1;

    if (power == 1)
        return number;

    int t = fastPowLastFourDigits(number, power / 2);
    if (power % 2)
        return (t * t * number) % 10000;
    else
        return (t * t) % 10000;
}

void testPow() {
    for (int i = 10000; i < 10009; i++) {
        cout << "2 ^ " << i << ": pow: " << powLastFourDigits(2, i) << endl;
        cout << "2 ^ " << i << ": pow iter: " << powIterLastFourDigits(2, i) << endl;
        cout << "2 ^ " << i << ": fast pow: " << fastPowLastFourDigits(2, i) << endl;
    }

    cout << "13 ^ 100000000000000000 = " <<  fastPowLastFourDigits(13, 100000000000000000) << endl;
}

void printMenu() {
    cout << "1 - slow pow | 2 - iterative pow | 3 - fast pow | 4 - run tests | e - exit" << endl;
}

int main() {
    char choice;
    int n;
    long long unsigned pow;

    printMenu();
    while (cin >> choice) {
        switch (choice) {
            case '1':
                cout << "Enter n: ";
                cin >> n;
                cout << "Enter power: ";
                cin >> pow;
                cout << powLastFourDigits(n, pow) << endl;
                break;
            case '2':
                cout << "Enter n: ";
                cin >> n;
                cout << "Enter power: ";
                cin >> pow;
                cout << powIterLastFourDigits(n, pow) << endl;
                break;
            case '3':
                cout << "Enter n: ";
                cin >> n;
                cout << "Enter power: ";
                cin >> pow;
                cout << fastPowLastFourDigits(n, pow) << endl;
                break;
            case '4':
                testPow();
                break;
            case 'e':
                return 0;
            default:
                cout << "No such option. Try again." << endl;
        }
        printMenu();
    }
    testPow();

    return 0;
}

Add solution to the power problem


//				To find an element in increasing seq. of values
#include <bits/stdc++.h>
using namespace std;

int arr[100];
int binary(int l,int r,int key) // Code template for Binary Search
{
	while(l<=r)
	{
		int mid = (l+r)/2;
		if(arr[mid] == key) // key is the element to find
		{
			return mid;
		}
		else if( arr[mid] > key)
		{
			r = mid-1;
		}
		else
		{
			l = mid+1;
		}
	}
		return -1; // Not Found
}
int main()
{
	int n,m,i;
	cin >> n; // Enter the size of the array
	for(i=0;i<n;i++)
	{
		cin >> arr[i];
	}
	sort(arr,arr+n); // Hence the array is sorted
	cout<<"Enter the element to be searched\n";
	cin >> m;
	int x = binary(0,n,m);
	cout << x<<"\n";
	return 0;
}

Advance Program for Binary Search


class Solution {
public:
    int minSetSize(vector<int>& arr) {
        std::unordered_map<int, int> m;
        for (const auto& num : arr) {
            auto iter = m.find(num);
            if (iter == m.end()) {
                m[num] = 1;
            } else {
                ++m[num];
            }
        }
        int half = arr.size() / 2;
        std::vector<std::vector<int>> nums;
        for (auto iter = m.begin(); iter != m.end(); ++iter) {
            std::vector<int> cur(2, 0);
            cur[0] = iter->second;
            cur[1] = iter->first;
            nums.emplace_back(std::move(cur));
        }
        std::sort(nums.begin(), nums.end(), [](std::vector<int>& a, std::vector<int>& b){
            return a[0] > b[0];
        });
        int ret = 0;
        for (const auto& v : nums) {
            if (half <= 0) {
                break;
            } else {
                half -= v[0];
                ++ret;
            }
        }
        return ret;
    }
};

Reduce Array Size to The Half