Compare commits
23 Commits
cdfa46e84c
...
3f447a25ab
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f447a25ab | |||
| f4d6e67706 | |||
| 222e402599 | |||
|
|
29dca37612 | ||
|
|
539e4b0077 | ||
|
|
e9877a356e | ||
|
|
721e183dc9 | ||
| c640548c05 | |||
| 1a17b9fe6c | |||
| c79fe4e087 | |||
| 22296de96d | |||
| 6f8d1f34d5 | |||
| 6744c38f0d | |||
| f7a3211b5c | |||
| 971803daa2 | |||
| d84fcbace8 | |||
|
|
0e4cbb799c | ||
| ef2a51644c | |||
|
|
28d25dff1c | ||
|
|
1c1a09ac3a | ||
|
|
1fd2219777 | ||
| 0d22446c1a | |||
| 6398bb5e4b |
49
.vscode/c_cpp_properties.json
vendored
Normal file
49
.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceRoot}",
|
||||
"/usr/include",
|
||||
"/usr/local/include"
|
||||
],
|
||||
"defines": [],
|
||||
"browse": {
|
||||
"path": [
|
||||
"/usr/include",
|
||||
"/usr/local/include"
|
||||
],
|
||||
"limitSymbolsToIncludedHeaders": true,
|
||||
"databaseFilename": ""
|
||||
},
|
||||
"intelliSenseMode": "clang-x64",
|
||||
"compilerPath": "/bin/clang",
|
||||
"cStandard": "c11",
|
||||
"cppStandard": "c++20"
|
||||
},
|
||||
{
|
||||
"name": "Win32",
|
||||
"includePath": [
|
||||
"${workspaceRoot}",
|
||||
"C:\\bin\\msvc2017\\community\\VC\\Tools\\MSVC\\14.12.25827\\include"
|
||||
],
|
||||
"defines": [
|
||||
"_DEBUG",
|
||||
"UNICODE"
|
||||
],
|
||||
"browse": {
|
||||
"path": [
|
||||
"${workspaceRoot}",
|
||||
"C:\\bin\\msvc2017\\community\\VC\\Tools\\MSVC\\14.12.25827\\include"
|
||||
],
|
||||
"limitSymbolsToIncludedHeaders": true,
|
||||
"databaseFilename": ""
|
||||
},
|
||||
"intelliSenseMode": "msvc-x64",
|
||||
"compilerPath": "/bin/clang",
|
||||
"cStandard": "c11",
|
||||
"cppStandard": "c++14"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
49
.vscode/launch.json
vendored
Normal file
49
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Python",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"stopOnEntry": true,
|
||||
"pythonPath": "${config:python.pythonPath}",
|
||||
"program": "${file}",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {},
|
||||
"envFile": "${workspaceFolder}/.env",
|
||||
"debugOptions": [
|
||||
"RedirectOutput"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Debug (CLang-Linux)",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${fileDirname}/${fileBasenameNoExtension}",
|
||||
"args": [],
|
||||
"cwd": "${fileDirname}",
|
||||
"MIMode": "lldb",
|
||||
"externalConsole": false,
|
||||
"stopAtEntry": true,
|
||||
"miDebuggerPath": "/usr/local/bin/lldb-mi",
|
||||
"preLaunchTask": "C/C++: clang++ build active file"
|
||||
},
|
||||
{
|
||||
"name": "C++ Launch (Windows)",
|
||||
"type": "cppvsdbg",
|
||||
"request": "launch",
|
||||
"program": "enter program name, for example ${workspaceRoot}/${file}.exe",
|
||||
"args": [],
|
||||
"stopAtEntry": false,
|
||||
"cwd": "${workspaceRoot}",
|
||||
"environment": [],
|
||||
"externalConsole": false
|
||||
},
|
||||
{
|
||||
"name": "C++ Attach (Windows)",
|
||||
"type": "cppvsdbg",
|
||||
"request": "attach",
|
||||
"processId": "${command:pickProcess}"
|
||||
}
|
||||
]
|
||||
}
|
||||
8
.vscode/settings.json
vendored
Normal file
8
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"vector": "cpp",
|
||||
"iostream": "cpp",
|
||||
"xutility": "cpp"
|
||||
},
|
||||
"python.pythonPath": "C:\\bin\\python-3.6\\python.exe"
|
||||
}
|
||||
27
.vscode/tasks.json
vendored
Normal file
27
.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "shell",
|
||||
"label": "C/C++: clang++ build active file",
|
||||
"command": "/bin/clang++",
|
||||
"args": [
|
||||
"-std=c++20",
|
||||
"-g",
|
||||
"${file}",
|
||||
"-o",
|
||||
"${fileDirname}/${fileBasenameNoExtension}"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": [
|
||||
"$gcc"
|
||||
],
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
59
cpp/adl.cpp
Normal file
59
cpp/adl.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
|
||||
namespace ttt {
|
||||
struct s {
|
||||
};
|
||||
void print( const s& t ){
|
||||
std::cout << "ttt::print" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
namespace C
|
||||
{
|
||||
template <typename T>
|
||||
void print( T t ){
|
||||
std::cout << "C::print" << std::endl;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void call_print( const T& t ){
|
||||
print( t );
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
C::call_print(ttt::s{});
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
87
cpp/boost/multi_index.cpp
Normal file
87
cpp/boost/multi_index.cpp
Normal file
@@ -0,0 +1,87 @@
|
||||
/* Check cf5-opt.vim defs.
|
||||
VIM: let g:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let g:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let g:cppflags=g:Iboost.g:Itbb
|
||||
VIM: let g:ldflags=g:Lboost.g:Ltbb.g:tbbmalloc.g:tbbmproxy
|
||||
VIM: let g:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM: let g:argv=""
|
||||
VIM-: let g:cf5output=0
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
|
||||
#include <boost/multi_index_container.hpp>
|
||||
//#include <boost/multi_index/sequenced_index.hpp>
|
||||
#include <boost/multi_index/hashed_index.hpp>
|
||||
#include <boost/multi_index/ordered_index.hpp>
|
||||
#include <boost/multi_index/member.hpp>
|
||||
#include <boost/multi_index/identity.hpp>
|
||||
|
||||
struct entry
|
||||
{
|
||||
std::string d_sessionId;
|
||||
std::string d_curveId;
|
||||
std::string key3;
|
||||
};
|
||||
|
||||
typedef boost::multi_index::ordered_unique<
|
||||
boost::multi_index::identity<entry>
|
||||
> index_by_entry;
|
||||
|
||||
struct ByCurveId {};
|
||||
typedef boost::multi_index::hashed_unique<
|
||||
boost::multi_index::tag<ByCurveId>,
|
||||
boost::multi_index::member<
|
||||
entry,
|
||||
std::string,
|
||||
&entry::d_curveId
|
||||
>
|
||||
> index_ByCurveId;
|
||||
|
||||
struct BySessionId {};
|
||||
typedef boost::multi_index::hashed_unique<
|
||||
boost::multi_index::tag<BySessionId>,
|
||||
boost::multi_index::member<
|
||||
entry,
|
||||
std::string,
|
||||
&entry::d_sessionId
|
||||
>
|
||||
> index_BySessionId;
|
||||
|
||||
typedef boost::multi_index_container<
|
||||
entry,
|
||||
boost::multi_index::indexed_by<
|
||||
//boost::multi_index::sequenced<>,
|
||||
//index_by_entry,
|
||||
index_BySessionId,
|
||||
index_ByCurveId
|
||||
>
|
||||
> my_multi_index_container_type;
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
my_multi_index_container_type c;
|
||||
|
||||
if ( c.get<BySessionId>().find( "tutuc" )
|
||||
== c.get<BySessionId>().end() )
|
||||
{
|
||||
std::cout << "no tutuc\n";
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
102
cpp/cpp11/forwarding_reference.cpp
Normal file
102
cpp/cpp11/forwarding_reference.cpp
Normal file
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM-: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
|
||||
class A
|
||||
{
|
||||
public:
|
||||
int i;
|
||||
|
||||
A() {
|
||||
std::cout << "default ctr" << std::endl;
|
||||
}
|
||||
|
||||
A(const A&) {
|
||||
std::cout << "copy ctr" << std::endl;
|
||||
}
|
||||
|
||||
A(A&&) {
|
||||
std::cout << "move ctr" << std::endl;
|
||||
}
|
||||
|
||||
void operator = (const A&) {
|
||||
std::cout << "copy" << std::endl;
|
||||
}
|
||||
|
||||
void operator = (A&&) {
|
||||
std::cout << "move" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
void test3( A a ){
|
||||
std::cout << "by value" << std::endl;
|
||||
}
|
||||
void test3( A&& a ){
|
||||
std::cout << "rvalue" << std::endl;
|
||||
}
|
||||
void test3( const A& a ){
|
||||
std::cout << "const lvalue&" << std::endl;
|
||||
}
|
||||
void test3( A& a ){
|
||||
std::cout << "lvalue &" << std::endl;
|
||||
}
|
||||
|
||||
|
||||
template <typename T>
|
||||
void test2( T&& t ){
|
||||
test3(std::forward<T>(t));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void test( T t ){
|
||||
//test2(std::forward<T>(t));
|
||||
test3(t);
|
||||
}
|
||||
|
||||
A rvalue()
|
||||
{
|
||||
return A();
|
||||
}
|
||||
|
||||
A& lvalue()
|
||||
{
|
||||
static A a;
|
||||
return a;
|
||||
}
|
||||
|
||||
const A& clvalue()
|
||||
{
|
||||
static A a;
|
||||
return a;
|
||||
}
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
test(rvalue());
|
||||
test(lvalue());
|
||||
test(clvalue());
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
72
cpp/cpp11/initializer_list.cpp
Normal file
72
cpp/cpp11/initializer_list.cpp
Normal file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread"
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <vector>
|
||||
//#include <initializer_list>
|
||||
|
||||
template <typename CONT>
|
||||
void print( CONT&& cont )
|
||||
{
|
||||
std::cout << "template ";
|
||||
for( auto n : cont ){
|
||||
std::cout << n << ' ';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
#if 1
|
||||
void print( const std::initializer_list<auto>& cont )
|
||||
{
|
||||
std::cout << "initializer_list<auto> ";
|
||||
for( auto n : cont ){
|
||||
std::cout << n << ' ';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
#if 1
|
||||
void print( const std::initializer_list<int>& cont )
|
||||
{
|
||||
std::cout << "initializer_list<int> ";
|
||||
for( auto n : cont ){
|
||||
std::cout << n << ' ';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
std::vector<int> v = {1,2,3};
|
||||
|
||||
print(v);
|
||||
|
||||
|
||||
print({3,4,5});
|
||||
|
||||
print({3LL,4LL,5LL});
|
||||
|
||||
print({3LL,4,5});
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
42
cpp/cpp11/overload.cpp
Normal file
42
cpp/cpp11/overload.cpp
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
void a( std::string&& s )
|
||||
{
|
||||
std::cout << " by value " << std::endl;
|
||||
}
|
||||
|
||||
void a( const std::string& s )
|
||||
{
|
||||
std::cout << " const ref " << std::endl;
|
||||
}
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
std::string s = "bbbbbb";
|
||||
|
||||
a(s);
|
||||
a(std::string("aaaa"));
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
93
cpp/cpp11/test1.cpp
Normal file
93
cpp/cpp11/test1.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <trnx_vector.h>
|
||||
|
||||
namespace trnx {
|
||||
|
||||
struct A{
|
||||
int a1;
|
||||
};
|
||||
|
||||
void test()
|
||||
{
|
||||
trnx::vector<A> v;
|
||||
v.push_back(A{0});
|
||||
v.push_back(A{1});
|
||||
v.push_back(A{2});
|
||||
|
||||
for(const auto& x : v)
|
||||
{
|
||||
std::cout << x.a1 << ' ';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
#if 1
|
||||
struct MoveOnly
|
||||
{
|
||||
int d_datum;
|
||||
|
||||
// Allow moves
|
||||
MoveOnly(MoveOnly&&) = default;
|
||||
MoveOnly& operator=(MoveOnly&&) = default;
|
||||
|
||||
// Prevent copies
|
||||
MoveOnly(const MoveOnly&) = delete;
|
||||
MoveOnly& operator=(const MoveOnly&) = delete;
|
||||
};
|
||||
|
||||
void lab1()
|
||||
{
|
||||
trnx::vector<MoveOnly> v;
|
||||
v.push_back(MoveOnly{0});
|
||||
v.push_back(MoveOnly{1});
|
||||
v.push_back(MoveOnly{2});
|
||||
|
||||
for(const auto& x : v)
|
||||
{
|
||||
std::cout << x.d_datum << ' ';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
void main()
|
||||
{
|
||||
test();
|
||||
lab1();
|
||||
}
|
||||
|
||||
|
||||
|
||||
} // close namespace trnx
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
trnx::main();
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
75
cpp/cpp11/trnx_order.h
Normal file
75
cpp/cpp11/trnx_order.h
Normal file
@@ -0,0 +1,75 @@
|
||||
#ifndef INCLUDED_TRNX_ORDER
|
||||
#define INCLUDED_TRNX_ORDER
|
||||
|
||||
#include <bsl_iostream.h>
|
||||
#include <bsl_string.h>
|
||||
|
||||
#include <bael_log.h>
|
||||
|
||||
namespace BloombergLP {
|
||||
namespace trnx {
|
||||
|
||||
class Order
|
||||
{
|
||||
public:
|
||||
Order()
|
||||
{
|
||||
BAEL_LOG_SET_CATEGORY("ORDER");
|
||||
BAEL_LOG_INFO << "Order::Order()" << BAEL_LOG_END;
|
||||
};
|
||||
|
||||
Order(const bsl::string& symbol, double price, int amount,
|
||||
char side)
|
||||
: d_symbol(symbol), d_price(price), d_amount(amount),
|
||||
d_side(side)
|
||||
{
|
||||
BAEL_LOG_SET_CATEGORY("ORDER");
|
||||
BAEL_LOG_INFO << "Order::Order(string, double, int, char)"
|
||||
<< BAEL_LOG_END;
|
||||
}
|
||||
|
||||
Order(const Order& other)
|
||||
: d_symbol(other.d_symbol), d_price(other.d_price),
|
||||
d_amount(other.d_amount), d_side(other.d_side)
|
||||
{
|
||||
BAEL_LOG_SET_CATEGORY("ORDER");
|
||||
BAEL_LOG_INFO << "Order::Order(const Order&)" << BAEL_LOG_END;
|
||||
}
|
||||
|
||||
~Order()
|
||||
{
|
||||
BAEL_LOG_SET_CATEGORY("ORDER");
|
||||
BAEL_LOG_INFO << "Order::~Order()" << BAEL_LOG_END;
|
||||
}
|
||||
|
||||
bool operator==(const Order& other) const
|
||||
{
|
||||
return (d_symbol == other.d_symbol &&
|
||||
d_price == other.d_price &&
|
||||
d_amount == other.d_amount && d_side == other.d_side);
|
||||
}
|
||||
|
||||
const bsl::string& symbol() const { return d_symbol; }
|
||||
double price() const { return d_price; }
|
||||
int amount() const { return d_amount; }
|
||||
char side() const { return d_side; }
|
||||
|
||||
private:
|
||||
bsl::string d_symbol;
|
||||
double d_price;
|
||||
int d_amount;
|
||||
char d_side;
|
||||
friend bsl::ostream& operator<<(bsl::ostream& os, const Order& o);
|
||||
};
|
||||
|
||||
inline bsl::ostream& operator<<(bsl::ostream& os, const Order& o)
|
||||
{
|
||||
os << "[" << o.d_symbol << ',' << o.d_price << ',' << o.d_amount
|
||||
<< ',' << o.d_side << "]";
|
||||
return os;
|
||||
}
|
||||
|
||||
} // close namespace trnx
|
||||
} // close namespace BloombergLP
|
||||
|
||||
#endif
|
||||
224
cpp/cpp11/trnx_vector.h
Normal file
224
cpp/cpp11/trnx_vector.h
Normal file
@@ -0,0 +1,224 @@
|
||||
#ifndef INCLUDED_TRNX_VECTOR
|
||||
#define INCLUDED_TRNX_VECTOR
|
||||
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <iterator>
|
||||
#include <type_traits>
|
||||
#include <memory>
|
||||
#include <trnx_vector_impl.h>
|
||||
|
||||
namespace trnx {
|
||||
|
||||
template <typename T>
|
||||
class vector
|
||||
{
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef std::size_t size_type;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef T& reference;
|
||||
typedef const T& const_reference;
|
||||
typedef T* pointer;
|
||||
typedef const T* const_pointer;
|
||||
|
||||
private:
|
||||
size_type d_size;
|
||||
size_type d_capacity;
|
||||
typedef detail::uninitialized<T> buff_type[];
|
||||
std::unique_ptr<buff_type> d_buff;
|
||||
// `uninitialized<T>` represents enough uninitialized storage for an
|
||||
// instance of `T`. The lifetime of the `T` instance is controlled
|
||||
// manually via the `.construct` and `.destroy` member functions.
|
||||
// An initialized instance can be accessed through `.get`.
|
||||
|
||||
public:
|
||||
typedef detail::iter_impl<detail::uninitialized<T> > iterator; //CHG
|
||||
typedef detail::iter_impl<const detail::uninitialized<T> > const_iterator; //CHG
|
||||
// `iter_impl` is an iterator type that automatically transforms
|
||||
// `uninitialized<T>*` into `T*` when dereferencing.
|
||||
|
||||
vector() : d_size(0), d_capacity(0), d_buff(nullptr)
|
||||
{
|
||||
// A default-constructed vector is empty and has no allocated buffer.
|
||||
}
|
||||
|
||||
vector(const vector& rhs)
|
||||
: d_size(rhs.d_size),
|
||||
d_capacity(rhs.d_capacity),
|
||||
|
||||
// Allocate enough space for `rhs.d_size` items.
|
||||
d_buff(std::make_unique<buff_type>(rhs.d_size))
|
||||
{
|
||||
// Copy-construct all of `rhs`'s elements into the current buffer.
|
||||
for(size_type i = 0; i < d_size; ++i)
|
||||
{
|
||||
d_buff[i].construct(rhs.d_buff[i].get());
|
||||
}
|
||||
}
|
||||
|
||||
~vector()
|
||||
{
|
||||
// Destroy all elements in the vector. In the Standard, the order of
|
||||
// destruction is unspecified.
|
||||
for(size_type i = 0; i < d_size; ++i)
|
||||
{
|
||||
d_buff[i].destroy();
|
||||
}
|
||||
}
|
||||
|
||||
vector<T>& operator=(const vector<T>& rhs);
|
||||
// The copy-constructor allocates enough memory to store `rhs`'s
|
||||
// elements in a new buffer, copies over the current elements to the
|
||||
// new buffer, and finally sets `d_buff` to point to the new buffer.
|
||||
|
||||
size_type size() const { return d_size; }
|
||||
size_type capacity() const { return d_capacity; }
|
||||
bool empty() const { return d_size == 0; }
|
||||
|
||||
iterator begin() { return iterator(d_buff.get()); }
|
||||
iterator begin() const { return iterator(d_buff.get()); }
|
||||
|
||||
iterator end() { return iterator(d_buff.get() + d_size); }
|
||||
iterator end() const { return iterator(d_buff.get() + d_size); }
|
||||
|
||||
const_iterator cbegin() const { return const_iterator(d_buff.get()); }
|
||||
const_iterator cend() const { return const_iterator(d_buff.get() + d_size); }
|
||||
|
||||
reference front() { return d_buff[0].get(); }
|
||||
const_reference front() const { return d_buff[0].get(); }
|
||||
|
||||
reference back() { return d_buff[d_size - 1].get(); }
|
||||
const_reference back() const { return d_buff[d_size - 1].get(); }
|
||||
|
||||
reference operator[](size_type i) { return d_buff[i].get(); }
|
||||
const_reference operator[](size_type i) const { return d_buff[i].get(); }
|
||||
|
||||
reference at(size_type i)
|
||||
{
|
||||
if(i >= d_size)
|
||||
{
|
||||
throw std::out_of_range("Index out of range");
|
||||
}
|
||||
else
|
||||
{
|
||||
return d_buff[i].get();
|
||||
}
|
||||
}
|
||||
|
||||
const_reference at(size_type i) const
|
||||
{
|
||||
// The following use of `const_cast` is legal and simply prevents code
|
||||
// repetition with the non-`const` version of `at`.
|
||||
return const_cast<vector<T>&>(*this).at(i);
|
||||
}
|
||||
|
||||
void push_back(const T& item);
|
||||
void push_back(T&& item);
|
||||
void pop_back();
|
||||
void clear();
|
||||
void reserve(size_type new_capacity);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
void vector<T>::push_back(const T& item)
|
||||
{
|
||||
if(d_size >= d_capacity)
|
||||
{
|
||||
const size_type new_capacity = (d_capacity == 0) ? 1
|
||||
: d_capacity * 2;
|
||||
|
||||
reserve(new_capacity);
|
||||
}
|
||||
|
||||
d_buff[d_size++].construct(item);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void vector<T>::push_back(T&& item)
|
||||
{
|
||||
if(d_size >= d_capacity)
|
||||
{
|
||||
const size_type new_capacity = (d_capacity == 0) ? 1
|
||||
: d_capacity * 2;
|
||||
|
||||
reserve(new_capacity);
|
||||
}
|
||||
|
||||
d_buff[d_size++].construct(std::move(item));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void vector<T>::pop_back()
|
||||
{
|
||||
BSLS_ASSERT(!empty());
|
||||
|
||||
d_buff[d_size - 1].destroy();
|
||||
--d_size;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void vector<T>::clear()
|
||||
{
|
||||
// Destroy all existing elements
|
||||
for(size_type i = 0; i < d_size; ++i)
|
||||
{
|
||||
d_buff[i].destroy();
|
||||
}
|
||||
|
||||
// Set size to zero, but leave capacity unchanged
|
||||
d_size = 0;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
vector<T>& vector<T>::operator=(const vector& rhs)
|
||||
{
|
||||
// Prevent self-assignment
|
||||
if(&rhs != this)
|
||||
{
|
||||
// Destroy all existing elements and set size to zero
|
||||
clear();
|
||||
|
||||
// Reserve if necessary
|
||||
reserve(rhs.d_size);
|
||||
|
||||
// Copy elements from `rhs`
|
||||
for(size_type i = 0; i < rhs.d_size; ++i)
|
||||
{
|
||||
d_buff[i].construct(rhs.d_buff[i].get());
|
||||
}
|
||||
|
||||
// Update size
|
||||
d_size = rhs.d_size;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void vector<T>::reserve(size_type new_capacity)
|
||||
{
|
||||
// Exit early if there's no need to reserve more memory
|
||||
if(new_capacity <= d_capacity) { return; }
|
||||
|
||||
// Allocate a new buffer
|
||||
auto buff = std::make_unique<buff_type>(new_capacity);
|
||||
|
||||
// Copy-construct existing elements into the new buffer and destroy them
|
||||
// in the old one
|
||||
for(size_type i = 0; i < d_size; ++i)
|
||||
{
|
||||
buff[i].construct(std::move(d_buff[i].get()));
|
||||
d_buff[i].destroy();
|
||||
}
|
||||
|
||||
// Deallocate old buffer, set the owned buffer to `buff`
|
||||
d_buff = std::move(buff);
|
||||
|
||||
// Update capacity
|
||||
d_capacity = new_capacity;
|
||||
}
|
||||
|
||||
} // close namespace trnx
|
||||
|
||||
#endif
|
||||
106
cpp/cpp11/trnx_vector_impl.h
Normal file
106
cpp/cpp11/trnx_vector_impl.h
Normal file
@@ -0,0 +1,106 @@
|
||||
#ifndef INCLUDED_TRNX_VECTOR_IMPL
|
||||
#define INCLUDED_TRNX_VECTOR_IMPL
|
||||
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <iterator>
|
||||
#include <type_traits>
|
||||
|
||||
namespace trnx {
|
||||
namespace detail {
|
||||
|
||||
// This union is not meant to be shown/completely understood from the students.
|
||||
//
|
||||
// They should know that `uninitialized<T>` means "enough storage for a `T`
|
||||
// instance, and that they can manually control the lifetime of that instance
|
||||
// through the `.construct` and `.destroy` member functions.
|
||||
//
|
||||
// It is undefined behavior to:
|
||||
// * Call `construct` on an already-initialized instance.
|
||||
// * Call `destroy` on a non-initialized instance.
|
||||
// * Access the reference returned by `get` on a non-initialized instance.
|
||||
//
|
||||
template <typename T>
|
||||
union uninitialized
|
||||
{
|
||||
private:
|
||||
T d_datum;
|
||||
|
||||
public:
|
||||
using inner_type = T;
|
||||
|
||||
uninitialized() { }
|
||||
~uninitialized() { }
|
||||
|
||||
template <typename... Ts>
|
||||
void construct(Ts&&... xs)
|
||||
{
|
||||
new (&d_datum) T(std::forward<Ts>(xs)...);
|
||||
}
|
||||
|
||||
void destroy()
|
||||
{
|
||||
d_datum.~T();
|
||||
}
|
||||
|
||||
T& get() { return d_datum; }
|
||||
const T& get() const { return d_datum; }
|
||||
};
|
||||
|
||||
// This class is not meant to be shown/completely understood from the students.
|
||||
//
|
||||
// It basically unwraps `uninitialized<T>` upon dereference, behaving as any
|
||||
// other normal random access iterator, transparently to the user.
|
||||
//
|
||||
template <typename T>
|
||||
class iter_impl
|
||||
{
|
||||
private:
|
||||
T* d_ptr;
|
||||
using inner_type = typename T::inner_type;
|
||||
|
||||
public:
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using value_type = inner_type;
|
||||
using pointer = inner_type*;
|
||||
using reference = inner_type&;
|
||||
using iterator_category = std::random_access_iterator_tag;
|
||||
|
||||
iter_impl() : d_ptr(nullptr) { }
|
||||
iter_impl(T* rhs) : d_ptr(rhs) { }
|
||||
|
||||
iter_impl(const iter_impl& rhs) : d_ptr(rhs.d_ptr) { }
|
||||
iter_impl& operator=(const iter_impl &rhs) { d_ptr = rhs.d_ptr; return *this; }
|
||||
|
||||
iter_impl& operator+=(difference_type rhs) { d_ptr += rhs; return *this; }
|
||||
iter_impl& operator-=(difference_type rhs) { d_ptr -= rhs; return *this; }
|
||||
|
||||
inner_type& operator*() const { return d_ptr->get(); }
|
||||
inner_type* operator->() const { return &d_ptr->get(); }
|
||||
inner_type& operator[](difference_type rhs) const { return d_ptr[rhs]; }
|
||||
|
||||
iter_impl& operator++() { ++d_ptr; return *this; }
|
||||
iter_impl& operator--() { --d_ptr; return *this; }
|
||||
|
||||
iter_impl operator++(int) { iter_impl tmp(*this); ++d_ptr; return tmp; }
|
||||
iter_impl operator--(int) { iter_impl tmp(*this); --d_ptr; return tmp; }
|
||||
|
||||
difference_type operator-(const iter_impl& rhs) const { return iter_impl(d_ptr - rhs.ptr); }
|
||||
|
||||
iter_impl operator+(difference_type rhs) const { return iter_impl(d_ptr + rhs); }
|
||||
iter_impl operator-(difference_type rhs) const { return iter_impl(d_ptr - rhs); }
|
||||
friend iter_impl operator+(difference_type lhs, const iter_impl& rhs) { return iter_impl(lhs + rhs.d_ptr); }
|
||||
friend iter_impl operator-(difference_type lhs, const iter_impl& rhs) { return iter_impl(lhs - rhs.d_ptr); }
|
||||
|
||||
bool operator==(const iter_impl& rhs) const { return d_ptr == rhs.d_ptr; }
|
||||
bool operator!=(const iter_impl& rhs) const { return d_ptr != rhs.d_ptr; }
|
||||
bool operator>(const iter_impl& rhs) const { return d_ptr > rhs.d_ptr; }
|
||||
bool operator<(const iter_impl& rhs) const { return d_ptr < rhs.d_ptr; }
|
||||
bool operator>=(const iter_impl& rhs) const { return d_ptr >= rhs.d_ptr; }
|
||||
bool operator<=(const iter_impl& rhs) const { return d_ptr <= rhs.d_ptr; }
|
||||
};
|
||||
|
||||
} // close namespace detail
|
||||
} // close namespace trnx
|
||||
|
||||
#endif
|
||||
31
cpp/different_linkage.cpp
Normal file
31
cpp/different_linkage.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
|
||||
class Test {
|
||||
public:
|
||||
virtual int increment(int num) = 0;
|
||||
|
||||
static int increment(Test& t, int num) {return t.increment(num);}
|
||||
};
|
||||
|
||||
class TestImpl : public Test
|
||||
{
|
||||
public:
|
||||
virtual int increment(int num) {
|
||||
std::cout << "Test " << num;
|
||||
return num;
|
||||
}
|
||||
};
|
||||
|
||||
int main ( void )
|
||||
{
|
||||
TestImpl t;
|
||||
Test::increment(t, 2);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
64
cpp/hidden_method_call.cpp
Normal file
64
cpp/hidden_method_call.cpp
Normal file
@@ -0,0 +1,64 @@
|
||||
/* Check cf5-opt.vim defs.
|
||||
VIM: let g:lcppflags="-D__USE_XOPEN2K8 -O2 -pthread"
|
||||
VIM-: let g:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let g:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM-: let g:cf5output=0
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
|
||||
struct A
|
||||
{
|
||||
A()
|
||||
{}
|
||||
~A()
|
||||
{}
|
||||
|
||||
virtual void fun()
|
||||
{
|
||||
std::cout << "I am a hidden function." << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
struct B : public A
|
||||
{
|
||||
B()
|
||||
{}
|
||||
~B()
|
||||
{}
|
||||
|
||||
void fun()
|
||||
{
|
||||
std::cout << "I am the visible function." << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
B o;
|
||||
|
||||
o.fun();
|
||||
|
||||
o.A::fun();
|
||||
|
||||
typedef A a_type;
|
||||
o.a_type::fun();
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
55
cpp/p.cpp
Normal file
55
cpp/p.cpp
Normal file
@@ -0,0 +1,55 @@
|
||||
/* Check cf5-opt.vim defs.
|
||||
VIM: let g:lcppflags="-O2 -pthread -D__USE_XOPEN2K8"
|
||||
VIM: let g:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let g:cppflags=""
|
||||
VIM: let g:ldflags=""
|
||||
VIM: let g:ldlibpath=""
|
||||
VIM: let g:argv=""
|
||||
VIM-: let g:cf5output=0
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
int some_c_function_( int param1 );
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
some_c_function_( 99 );
|
||||
if (int i = 1)
|
||||
std::cout << "lkkk" << i << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
34
cpp/shared_ptr.cpp
Normal file
34
cpp/shared_ptr.cpp
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM-: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
23
cpp/shared_ptr_cast.cpp
Normal file
23
cpp/shared_ptr_cast.cpp
Normal file
@@ -0,0 +1,23 @@
|
||||
/* Check cf5-opt.vim defs.
|
||||
VIM: let b:lcppflags="-std=c++11 -O2 -pthread"
|
||||
*/
|
||||
|
||||
#include <memory>
|
||||
|
||||
class A
|
||||
{
|
||||
int i;
|
||||
};
|
||||
|
||||
class B : public A
|
||||
{
|
||||
int j;
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
std::shared_ptr<A> a = std::make_shared<B>();
|
||||
|
||||
std::shared_ptr<B> b = std::static_pointer_cast<B>(a);
|
||||
}
|
||||
|
||||
77
cpp/stl/istringstream_fail_eof.cpp
Normal file
77
cpp/stl/istringstream_fail_eof.cpp
Normal file
@@ -0,0 +1,77 @@
|
||||
/* Check cf5-opt.vim defs.
|
||||
-VIM-: let g:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let g:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let g:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <exception>
|
||||
|
||||
void test( const std::string& str_to_parse )
|
||||
{
|
||||
std::stringstream ss(str_to_parse);
|
||||
std::string str;
|
||||
int v;
|
||||
ss >> str >> v;
|
||||
|
||||
std::cout << "str=\"" << str_to_parse << '"' <<std::endl
|
||||
<< "good()=" << ss.good()
|
||||
<< " fail()=" << ss.fail()
|
||||
<< " bad()=" << ss.bad()
|
||||
<< " eof()=" << ss.eof()
|
||||
<< std::endl << std::endl;
|
||||
}
|
||||
|
||||
void test2( const std::string& str_to_parse )
|
||||
{
|
||||
std::stringstream ss(str_to_parse);
|
||||
std::string str;
|
||||
std::string str2;
|
||||
int v;
|
||||
ss >> str >> v;
|
||||
|
||||
if ( ss.fail() && !ss.eof() )
|
||||
{
|
||||
ss.clear();
|
||||
ss >> str2;
|
||||
}
|
||||
|
||||
std::cout << "str=\"" << str_to_parse << '"' <<std::endl
|
||||
<< "str2=\"" << str2 << '"' <<std::endl
|
||||
<< "good()=" << ss.good()
|
||||
<< " fail()=" << ss.fail()
|
||||
<< " bad()=" << ss.bad()
|
||||
<< " eof()=" << ss.eof()
|
||||
<< std::endl << std::endl;
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
test("string 1234");
|
||||
test("string 1234 ");
|
||||
test("string 1234 12");
|
||||
test("string ");
|
||||
test("string");
|
||||
test("string aaaa");
|
||||
test("string aaaa ");
|
||||
|
||||
test2("sss tttt");
|
||||
test2("sss tttt ");
|
||||
test2("sss 3456tttt");
|
||||
test2("sss");
|
||||
test2("sss ");
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
91
cpp/struct_alignment.cpp
Normal file
91
cpp/struct_alignment.cpp
Normal file
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
|
||||
struct A {
|
||||
long l;
|
||||
char c;
|
||||
};
|
||||
|
||||
struct L {
|
||||
long l;
|
||||
};
|
||||
|
||||
struct C {
|
||||
char c;
|
||||
};
|
||||
|
||||
struct B {
|
||||
bool b;
|
||||
};
|
||||
|
||||
struct alignas(16) Ba {
|
||||
bool b;
|
||||
};
|
||||
|
||||
struct alignas(16) BBa {
|
||||
bool b;
|
||||
bool b2;
|
||||
};
|
||||
|
||||
struct alignas(16) BBaa {
|
||||
alignas(16) bool b;
|
||||
alignas(16) bool b2;
|
||||
};
|
||||
|
||||
struct I128 {
|
||||
__int128 i128;
|
||||
};
|
||||
|
||||
struct I128i {
|
||||
__int128 i128;
|
||||
int i;
|
||||
};
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
A a;
|
||||
L l;
|
||||
C c;
|
||||
B b;
|
||||
Ba ba;
|
||||
BBa bba;
|
||||
BBaa bbaa;
|
||||
I128 i128;
|
||||
I128i i128i;
|
||||
|
||||
std::cout << "sizeof(A)=" << sizeof(A) << " &a=" << &a <<std::endl;
|
||||
std::cout << "sizeof(L)=" << sizeof(L) << " &l=" << &l <<std::endl;
|
||||
std::cout << "sizeof(C)=" << sizeof(C) << " &c=" << &c <<std::endl;
|
||||
std::cout << "sizeof(B)=" << sizeof(B) << " &b=" << &b <<std::endl;
|
||||
std::cout << "sizeof(Ba)=" << sizeof(Ba) << " &ba=" << &ba <<std::endl;
|
||||
std::cout << "sizeof(BBa)=" << sizeof(BBa) << " &bba=" << &bba <<std::endl;
|
||||
std::cout << "sizeof(BBaa)=" << sizeof(BBaa) << " &bbaa=" << &bbaa <<std::endl;
|
||||
std::cout << "sizeof(I128)=" << sizeof(I128) << " &i128=" << &i128 <<std::endl;
|
||||
std::cout << "sizeof(I128i)=" << sizeof(I128i) << " &i128i=" << &i128i <<std::endl;
|
||||
//......
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
73
cpp/tbb/message_flow_graph_example.cpp
Normal file
73
cpp/tbb/message_flow_graph_example.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <cstdio>
|
||||
|
||||
#include <tbb/flow_graph.h>
|
||||
|
||||
using namespace tbb::flow;
|
||||
|
||||
struct square {
|
||||
int operator()(int v) { return v*v; }
|
||||
};
|
||||
|
||||
struct cube {
|
||||
int operator()(int v) { return v*v*v; }
|
||||
};
|
||||
|
||||
class sum {
|
||||
int &my_sum;
|
||||
public:
|
||||
sum( int &s ) : my_sum(s) {}
|
||||
int operator()( tuple< int, int > v ) {
|
||||
my_sum += get<0>(v) + get<1>(v);
|
||||
return my_sum;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{try{
|
||||
int result = 0;
|
||||
|
||||
graph g;
|
||||
broadcast_node<int> input(g);
|
||||
function_node<int,int> squarer( g, unlimited, square() );
|
||||
function_node<int,int> cuber( g, unlimited, cube() );
|
||||
join_node< tuple<int,int>, queueing > join( g );
|
||||
function_node<tuple<int,int>,int>
|
||||
summer( g, serial, sum(result) );
|
||||
|
||||
make_edge( input, squarer );
|
||||
make_edge( input, cuber );
|
||||
make_edge( squarer, get<0>( join.input_ports() ) );
|
||||
make_edge( cuber, get<1>( join.input_ports() ) );
|
||||
make_edge( join, summer );
|
||||
|
||||
for (int i = 1; i <= 10; ++i)
|
||||
input.try_put(i);
|
||||
g.wait_for_all();
|
||||
|
||||
printf("Final result is %d\n", result);
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
70
cpp/tbb/simple_flow_graph.cpp
Normal file
70
cpp/tbb/simple_flow_graph.cpp
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM: let b:argv=""
|
||||
*/
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
|
||||
#include "tbb/flow_graph.h"
|
||||
|
||||
using namespace tbb::flow;
|
||||
|
||||
typedef std::shared_ptr<std::string> msg_type;
|
||||
|
||||
struct body {
|
||||
std::string my_name;
|
||||
body( const char *name ) : my_name(name) {}
|
||||
void operator()( msg_type msg ) const {
|
||||
std::stringstream ss;
|
||||
ss << my_name << " got " << *msg << std::endl;
|
||||
std::cout << ss.str();
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{try{
|
||||
graph g;
|
||||
|
||||
broadcast_node<msg_type> start( g );
|
||||
continue_node<msg_type> a( g, body("A"));
|
||||
continue_node<msg_type> b( g, body("B"));
|
||||
continue_node<msg_type> c( g, body("C"));
|
||||
continue_node<msg_type> d( g, body("D"));
|
||||
continue_node<msg_type> e( g, body("E"));
|
||||
|
||||
make_edge( start, a );
|
||||
make_edge( start, b );
|
||||
make_edge( a, c );
|
||||
make_edge( b, c );
|
||||
make_edge( c, d );
|
||||
make_edge( a, e );
|
||||
|
||||
for (int i = 0; i < 3; ++i ) {
|
||||
std::stringstream ss;
|
||||
ss << i << std::endl;
|
||||
|
||||
start.try_put( std::make_shared( ss.str() ) );
|
||||
g.wait_for_all();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
97
cpp/tbb/tbb_unspawned_child.cpp
Normal file
97
cpp/tbb/tbb_unspawned_child.cpp
Normal file
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++11 -O2 -pthread"
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM: let b:ldflags=g:Lboost.g:LtbbD
|
||||
VIM: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM: let b:argv=""
|
||||
*/
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
|
||||
#include <tbb/task.h>
|
||||
|
||||
/*
|
||||
* Conclusion:
|
||||
* The first task_sheduler_init is configuring number of threads in
|
||||
* the thread pool. If the task scheduler initialised implicitly then
|
||||
* the number of threads is the number of cores. To ensure uncomment
|
||||
* the commented line below.
|
||||
*/
|
||||
|
||||
class ChildTask : public tbb::task
|
||||
{
|
||||
tbb::task * execute()
|
||||
{
|
||||
std::printf( "ChildTask is running.\n" );
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
class ContTask : public tbb::task
|
||||
{
|
||||
tbb::task * execute()
|
||||
{
|
||||
std::printf( "ContTask is running.\n" );
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
tbb::task * t;
|
||||
|
||||
struct RootTask : public tbb::task
|
||||
{
|
||||
tbb::task * execute()
|
||||
{
|
||||
std::printf( "RootTask is running.\n" );
|
||||
|
||||
auto& c = *new( allocate_continuation()) ContTask();
|
||||
t = &c;
|
||||
|
||||
tbb::task& ctask1 = *new( c.allocate_child() ) ChildTask();
|
||||
tbb::task& ctask2 = *new( c.allocate_child() ) ChildTask();
|
||||
c.set_ref_count( 3 );
|
||||
spawn( ctask1 );
|
||||
spawn( ctask2 );
|
||||
|
||||
|
||||
std::printf( "RootTask is done.\n" );
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
auto& rtask = *new( tbb::task::allocate_root()) RootTask();
|
||||
|
||||
tbb::task::enqueue( rtask );
|
||||
|
||||
std::this_thread::sleep_for( std::chrono::seconds(1) );
|
||||
std::printf( "After sleep.\n" );
|
||||
|
||||
tbb::task::spawn( *new (t->allocate_child()) tbb::empty_task() );
|
||||
|
||||
std::this_thread::sleep_for( std::chrono::seconds(1) );
|
||||
std::printf( "After second sleep.\n" );
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
38
cpp/test_const_cast_string.cpp
Normal file
38
cpp/test_const_cast_string.cpp
Normal file
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM-: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
static const std::string str = "initial";
|
||||
const_cast<std::string&>(str) = "test";
|
||||
std::cout << str << std::endl;
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
265
puzzles/interviews/BehaviralInterview.md
Normal file
265
puzzles/interviews/BehaviralInterview.md
Normal file
@@ -0,0 +1,265 @@
|
||||
## Areas
|
||||
- Decision making and problem-solving
|
||||
- Leadership
|
||||
- Motivation and Values
|
||||
- Conflict/Disagreement/Communication
|
||||
- Mistakes/Failures
|
||||
- Work Ethic Questions
|
||||
- Teamwork/Collaboration
|
||||
- Interpersonal skills
|
||||
- Ability to Adapt
|
||||
- Planning and organization
|
||||
- Time Management Skills
|
||||
- Professional feedback
|
||||
|
||||
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
- mifid II
|
||||
- #Leadership, #ManagingUp, #ProblemSolving, #SelfStarter,
|
||||
#DecisionMaking
|
||||
|
||||
- oxe tasks
|
||||
- #Mentoring, #DecisionMakeing, #SelfStarter, #Motivation
|
||||
|
||||
- proposal to migrate tcs to linux
|
||||
- #Collaboration, #Teamwork
|
||||
|
||||
- failed synopsys project
|
||||
- #Failure
|
||||
- we cannot achieve success separately
|
||||
|
||||
- Metrics (how to measure erichment time)
|
||||
- refroot
|
||||
- refactoring blo - dpkg blo
|
||||
- #Conflict, #Disagreement
|
||||
- try to be constructive
|
||||
|
||||
|
||||
- Vika's feedback
|
||||
- #ProfessionalFeedback
|
||||
- I do not articulate architectual changes early on.
|
||||
- Visibility
|
||||
|
||||
- I was against cashing in liquidity offloading service
|
||||
|
||||
|
||||
|
||||
Where do you see yourself in 2-3 years? (career growth)
|
||||
|
||||
|
||||
- **Why Facebook**
|
||||
|
||||
- Philosophy ("break things move fast") matches.
|
||||
- *Not sure about move fast*
|
||||
- *I like open box thinking, break boundaries if they don't work.*
|
||||
- Successful.
|
||||
- *I can contribute to company, and the company can contribute to me.*
|
||||
|
||||
|
||||
## Decision making and problem-solving
|
||||
- Describe a situation in which you used good judgment and logic to solve a problem.
|
||||
- Give me an example of a time when you had to be quick in coming to a decision.
|
||||
- Can you tell me about the last time you had to act and there was no formal procedure on how to do so?
|
||||
- How do you approach a task that you’ve never done before?
|
||||
- Can you tell me about a time when you had to deal with a customer that made unreasonable or stretched demands and how you created a win-win situation?
|
||||
- We’ve all been asked on occasion to perform tasks to accomplish a goal where the instructions are really ambiguous. Can you tell me about a time that this happened to you and what you did to achieve the goal?
|
||||
- Talk about a time where you had to make an important decision quickly. What did you decide? What were the results?
|
||||
|
||||
- Tell me about a time you made a difficult decision.
|
||||
- Tell me about a problem you solved in a creative way.
|
||||
- Tell me about a time when you handled a challenging situation.
|
||||
- Tell me about a time when you made a mistake. What did you do to correct it?
|
||||
- Tell me about a goal you set and reached and how you achieved it.
|
||||
- Talk about a difficult problem you’ve had to solve. How did you solve it?
|
||||
- Talk about a time when you had to adapt to big changes at work.
|
||||
- Tell me about a time when you had to be creative to solve a problem.
|
||||
|
||||
- **Difficult problem to solve**
|
||||
- AKA: Tell me about a difficult work challenge you’ve had.
|
||||
- *MIFID II project*
|
||||
|
||||
|
||||
## Leadership
|
||||
|
||||
- Tell me about a time when you stepped up into a leadership position.
|
||||
- Talk about a time when you’ve had to manage up.
|
||||
- *How I became Synopsys manager.*
|
||||
|
||||
- Tell me about a time when you felt like a good leader.
|
||||
- Can you tell us about a time you took initiative on a project?
|
||||
- *Mifid II project.*
|
||||
|
||||
- Tell me about a time you had to stand up for your beliefs.
|
||||
- Tell me about a time you disagreed with a supervisor.
|
||||
- Tell me about a time when you had to say “no.”
|
||||
- *Refroot.*
|
||||
|
||||
- Give me an example of a time when you persuaded someone. How’d you do it and why?
|
||||
- Describe the most challenging group from which you’ve had to gain cooperation.
|
||||
- Have you ever had trouble getting others to agree with your ideas? - Tell me about a time when you collaborated with others who were different than you.
|
||||
- Have you ever had to convince your team to do a job they were reluctant to do?
|
||||
|
||||
- How do you manage the outcomes of your team members?
|
||||
- Share an example of how you were able to motivate a coworker, your peers or your team.
|
||||
- gggg
|
||||
|
||||
|
||||
- Tell me about a time when you disagreed with your manager’s leadership style or team culture.
|
||||
- Harries micromanagement. Did nothing other than accepting it.
|
||||
- Ben's micromanagement. Digging into reasons why he wants to do this or that. Understand the problem, and propose solution for the problem.
|
||||
|
||||
- Who have you mentored or coached to achieve success?
|
||||
- Hamlet - Manager in Amazon
|
||||
- Adrian - Working on oxe
|
||||
|
||||
- Describe a time when you led by example.
|
||||
|
||||
- Can you give me an example of how you’ve contributed to the culture of previous teams, companies or groups?
|
||||
- What have you done when colleagues have been stressed out by a project?
|
||||
|
||||
|
||||
|
||||
## Motivation and Values
|
||||
|
||||
- Can you give me an example of a time when you felt dissatisfied with your work?
|
||||
- Tell me about a time when you went above and beyond the call of duty.
|
||||
|
||||
- Give me an example of a situation in which you positively influenced the actions of others.
|
||||
- Give an example of a goal you reached, and tell me how you achieved it.
|
||||
|
||||
- Give me an example of how you set goals.
|
||||
- Tell me about a time you felt you went above and beyond.
|
||||
- Tell me about a time when you had to fight for an idea at work.
|
||||
- Tell me about your proudest moment in your professional career why it was meaningful to you.
|
||||
|
||||
- What Do You Do To Stay Motivated?
|
||||
```
|
||||
As long as there are problems to solve I am motivated usually.
|
||||
Trying to find better ways to improve things.
|
||||
Looking for new projects.
|
||||
```
|
||||
|
||||
|
||||
## Conflict/Disagreement/Communication
|
||||
|
||||
- Describe a situation in which you were able to communicate with another individual who did not personally like you (or vice versa).
|
||||
- Describe a time you had to use written communication to convey an important argument or idea.
|
||||
- Have you ever unintentionally offended or upset somebody? Can you describe the details?
|
||||
|
||||
- Talk about a time when you’ve had to sell an idea to your colleagues.
|
||||
- Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.
|
||||
|
||||
|
||||
|
||||
- Give me an example of a time when you had to respond to an angry customer.
|
||||
|
||||
|
||||
- Tell me about a time when you had a difference of opinion with a teammate.
|
||||
- Tell me about a time when you disagreed with your supervisor. How did you handle it?
|
||||
- ff
|
||||
|
||||
|
||||
## Mistakes/Failures
|
||||
|
||||
- Tell me about a goal you failed to achieve.
|
||||
- Tell me about a major setback you’ve had. How did you deal with it?
|
||||
- Tell me about a decision you regret making.
|
||||
- What is your biggest professional mistake? How did you handle it?
|
||||
- Tell me about a time you wish you’d handled something differently.
|
||||
- Tell me about a time you failed.
|
||||
|
||||
- For me, failure is about not living up to others’ expectations, but also not meeting my own expectations for myself. In my marketing class last year, we were assigned a group project, and each person had his or her individual assignment. I had a ton of papers due, and I got behind—and I didn’t want to burden my team by giving them more work. I met the deadline, but it wasn’t my best work. If I had communicated that I was behind, my team could have worked with me to ensure everything was done well. We did fine on the project, but I knew I could have done better on my end. Now, I always communicate from day one on any project, scheduling regular check-ins and providing frequent updates.
|
||||
|
||||
```
|
||||
Grigor who was under the cap.
|
||||
Management experience.
|
||||
```
|
||||
|
||||
## Work Ethic Questions
|
||||
|
||||
|
||||
- What are you most proud of? Why?
|
||||
- I previously worked as a project assistant at a leadership development firm, and the project manager had to drop out of a big engagement one week beforehand due to a family emergency. Because I’d been supporting the team closely, they asked me to take over that role and manage the engagement as the key organizer and client liaison. I flew to Texas for the delivery, and I managed the engagement from start to finish. The lead consultant was so happy that she asked me to come back for the remaining sessions. This was outside of the original scope of my job, and I was able to support the client with a successful engagement. Afterwards, my supervisor put me on track for a promotion to project manager.
|
||||
|
||||
- Tell me about a time when you went above and beyond to get the job done.
|
||||
- Share a time when you had to juggle multiple important projects at the same time. How did you deal with that?
|
||||
- Have you ever been in a business situation that was ethically questionable? What did you do?
|
||||
|
||||
|
||||
## Teamwork/Collaboration
|
||||
|
||||
- Talk about a time when you had to work closely with someone whose personality was very different from yours.
|
||||
- Give me an example of a time you faced a conflict while working on a team. How did you handle that?
|
||||
- Describe a time when you struggled to build a relationship with someone important. How did you eventually overcome that?
|
||||
- We all make mistakes we wish we could take back. Tell me about a time you wish you’d handled a situation differently with a colleague.
|
||||
- Tell me about a time you needed to get information from someone who wasn’t very responsive. What did you do?
|
||||
|
||||
|
||||
- What’s the most successful team project you’ve worked on?
|
||||
- Tell me about a time when you had to work on a team and felt disappointed in the outcome.
|
||||
- I took an anthropology class last year, which I absolutely loved. For the final project, we broke into teams of three, with each team given a different area to research and present on. My team decided to divvy up each aspect of the project. I was responsible for writing the text for the poster, another teammate was responsible for making the images and graphs, and another for writing our speech.
|
||||
- I didn’t want to micromanage and was focused on my own work, so I just forged ahead. I checked in with my teammates two days before the presentation, and one had done absolutely nothing. I was furious. However, I took a deep breath, and the three of us met up. We worked all night long to make those graphs and get the poster designed. In the end, it wasn’t great, but it was something. It taught me that on a team, everyone needs to work together to ensure a great outcome. Now, I always schedule regular check-ins with team members, making sure that we’re on the same page and moving forward in a timely manner.
|
||||
- Share a time when you had to work with a teammate who wasn’t pulling their weight on a project. What happened?
|
||||
|
||||
- **Collaboration Experience**
|
||||
|
||||
|
||||
## Interpersonal skills
|
||||
|
||||
- Give me examples of what you’ve done in the past to nurture teamwork.
|
||||
- Give an example of an unpopular decision you’ve made, what the result was, and how you managed it.
|
||||
- What was your relationship with the best boss you ever had?
|
||||
- Can you tell me about a time that you let someone down? How did you handle it?
|
||||
|
||||
- Tell me about a time when you were in conflict with a peer and how the situation was resolved.
|
||||
- Talk about a time when a co-worker was not doing their share on a project. How did you handle it?
|
||||
- How have you dealt with an angry or upset customer?
|
||||
- Tell me about a time your co-workers had a conflict. How did you handle it?
|
||||
- How Do You Build Relationships?
|
||||
|
||||
## Ability to Adapt
|
||||
|
||||
- Tell me about a time you were under a lot of pressure. What was going on, and how did you get through it?
|
||||
- Describe a time when your team or company was undergoing some change. How did that impact you, and how did you adapt?
|
||||
- Tell me about the first job you’ve ever had. What did you do to learn the ropes?
|
||||
- Give me an example of a time when you had to think on your feet in order to delicately extricate yourself from a difficult or awkward situation.
|
||||
- Tell me about a time you failed. How did you deal with the situation?
|
||||
|
||||
- Tell me about how you work under pressure.
|
||||
- Tell me about a time you had to learn quickly.
|
||||
- Have you ever had a project that had to change drastically while it was in progress? Why? How did you do it?
|
||||
- Can you share about a time you had to be flexible or adaptable?
|
||||
|
||||
|
||||
## Planning and organization
|
||||
|
||||
- When scheduling your time, what method do you use to decide which items are priorities?
|
||||
- Describe how you’ve handled a sudden interruption to your schedule.
|
||||
- Give me an example of a time you had to prioritize certain tasks or projects over others.
|
||||
- How have you prioritized being assigned multiple projects?
|
||||
- Tell me about the last time your workday ended before you were able to get everything done.
|
||||
- Have you ever had a deadline you were not able to meet? What happened? What did you do?
|
||||
|
||||
|
||||
## Time Management Skills
|
||||
|
||||
- Tell me about a time you had to be very strategic in order to meet all your top priorities.
|
||||
- Describe a long-term project that you managed. How did you keep everything moving along in a timely manner?
|
||||
- Sometimes it’s just not possible to get everything on your to-do list done. Tell me about a time your responsibilities got a little overwhelming. What did you do?
|
||||
- Tell me about a time you set a goal for yourself. How did you go about ensuring that you would meet your objective?
|
||||
- Give me an example of a time you managed numerous responsibilities. How did you handle that?
|
||||
|
||||
|
||||
## Professional feedback
|
||||
|
||||
- What’s been the toughest criticism you received so far in your career? What did you do with it?
|
||||
- Can you describe the details of a time you were unfairly criticized?
|
||||
- When was the last time you got constructive feedback? What was it? What did you do with it?
|
||||
|
||||
- Tell me about a stressful situation at work and how you handled it.
|
||||
|
||||
- Can you give an example of a valuable piece of feedback that you have received?
|
||||
- When did you receive constructive/negative/difficult feedback? How did you act upon this?
|
||||
34
puzzles/interviews/Facebook Interview Questions.md
Normal file
34
puzzles/interviews/Facebook Interview Questions.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Facebook Interview Questions
|
||||
|
||||
## Coding Interview 1
|
||||
|
||||
### Problem 1
|
||||
Given alphabet [c b a]
|
||||
sort the array in alphabetical order
|
||||
[[a b b][a b c][c][b]] -> [[c][b][a b c][a b b]]
|
||||
|
||||
|
||||
### Problem 2
|
||||
Given a tree, calculate sum of all path sums
|
||||
|
||||
```
|
||||
4
|
||||
/ \
|
||||
9 0
|
||||
/ \
|
||||
5 1
|
||||
```
|
||||
495+491+40
|
||||
|
||||
This one I remember vaguely.
|
||||
|
||||
## Coding Interview 2
|
||||
|
||||
### Problem 1
|
||||
How many unbalance parentheses are the in a given string.
|
||||
|
||||
e.g. )(())(() -> 2
|
||||
|
||||
### Problem 2
|
||||
|
||||
Given m sorted arrays, return k-th element from joined sorted array.
|
||||
125
puzzles/interviews/Google Interview Questions.md
Normal file
125
puzzles/interviews/Google Interview Questions.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# Google Interview
|
||||
|
||||
## Coding Interview 1
|
||||
|
||||
[['a1', 'a2', 'a1b'], ['b1', 'b2'], ['c1', 'c2']]
|
||||
|
||||
### problem 1
|
||||
|
||||
print all combinations, like
|
||||
```
|
||||
a1b1c1
|
||||
a1b1c2
|
||||
a1b2c1
|
||||
a1b2c2
|
||||
a2b1c1
|
||||
a2b1c2
|
||||
a2b2c1
|
||||
a2b2c2
|
||||
a1bb1c1
|
||||
a1bb1c2
|
||||
a1bb2c1
|
||||
a1bb2c2
|
||||
```
|
||||
### problem 2
|
||||
|
||||
given a string 'a2b2c1', is it one of combinations from above.
|
||||
|
||||
solved by dynamic programming.
|
||||
|
||||
|
||||
|
||||
## Coding Interview 2
|
||||
|
||||
### Problem 1
|
||||
given a tree (not a binary one)
|
||||
|
||||
```
|
||||
o
|
||||
/|\
|
||||
/ | \
|
||||
o o o
|
||||
/ \ / \
|
||||
o o o o
|
||||
| |
|
||||
o o
|
||||
```
|
||||
Find nodes with similar structure. Like all life nodes are similar.
|
||||
|
||||
My solution was to come up with a signature for each node, like
|
||||
sig node = <num child>,(<sig child 1>),(<sig child 2>),(<sig child 3>) ...;
|
||||
then create a map <sig> -> set of similar nodes.
|
||||
|
||||
if we know that nodes are divers, then we could actually create a hash.
|
||||
|
||||
### Problem 2
|
||||
Represent a number in (-2) base, like a*(-2)^4+b*(-2)^3+c*(-2)^2+d*(-2)^1+e*(-2)^0
|
||||
|
||||
e.g. 1 -2 4 -8 16 -32
|
||||
|
||||
0 = 0000
|
||||
1 = 0001
|
||||
-1 = 0011
|
||||
2 = 0110
|
||||
-2 = 0010
|
||||
3 = 0111
|
||||
-3 = 1111
|
||||
....
|
||||
|
||||
|
||||
## System Design 1
|
||||
|
||||
800 Billions query log entries, 8 machines
|
||||
top million query by frequency
|
||||
|
||||
unique queries? take samples to estimate the unique query, shrinks by 1 factor of ten
|
||||
|
||||
distribute queries evenly by machine
|
||||
|
||||
go over the logs in each machine
|
||||
and create 10B key value pairs (assume 10x reduction)
|
||||
|
||||
For all machines = 4T
|
||||
average query length = 50B
|
||||
|
||||
Data per machine = 500GB of data (This produced from 5T)
|
||||
(use hash map, split data in chunks ~1T or 0.5T
|
||||
Produce about 50GB for each chunks, do this 5-10 time for all data)
|
||||
|
||||
reading from disk is going to be 20h at 200MB/s -> but we have 6 disks -> 3.5h to read everything
|
||||
|
||||
Another way to do this is to sort each chunk (by query), merge those. Produce all 500GB of data.
|
||||
|
||||
idea: merge the data between machines in pairs (1.5h to send to wire)
|
||||
|
||||
Somehow sort 500GB data on each machine and produce 1 M query per machine.
|
||||
(50Meg Data)
|
||||
About 10x50GB chunks. Create another hash count->set of queries.)
|
||||
|
||||
Do chunks have overlapping queries? yes they wiil
|
||||
|
||||
|
||||
Send all data to one machine (400Meg Data)
|
||||
Apply some sort of heap sort and merge presorted arrays.
|
||||
|
||||
|
||||
Correctness of data
|
||||
|
||||
how big are the machines?
|
||||
32 cores of 3 GHz
|
||||
120 G of RAM
|
||||
6x2T each (spinning disk)
|
||||
10Gbps network connection
|
||||
|
||||
you can store 5T in each machine
|
||||
|
||||
how to do the key value pair?
|
||||
have an hash map
|
||||
|
||||
Run Time
|
||||
|
||||
2M querie 100MB data per machine, (1GB data transfered for all) May be another 1GB for the second phase.
|
||||
|
||||
~4-5h to process this data.
|
||||
|
||||
|
||||
45
puzzles/interviews/SystemDesign.md
Normal file
45
puzzles/interviews/SystemDesign.md
Normal file
@@ -0,0 +1,45 @@
|
||||
|
||||
Request Per Second
|
||||
|
||||
Data Store Characteristics
|
||||
- size / growth rate
|
||||
- latency / bandwidth
|
||||
- availability / consistency
|
||||
|
||||
Cache
|
||||
- size
|
||||
- expiration
|
||||
|
||||
High Level Design
|
||||
- failover
|
||||
|
||||
|
||||
|
||||
Top Facebook System Design Interview Questions
|
||||
1. Design Facebook News Feed
|
||||
2. Design Facebook Status Search
|
||||
3. Design Live Commenting
|
||||
4. Design Facebook Messenger or WhatsApp
|
||||
5. Design Instagram
|
||||
|
||||
|
||||
1. Design Proximity Server
|
||||
2. Design Typeahead Suggestions
|
||||
3. Design Top N Songs
|
||||
4. Design Privacy Settings at Facebook
|
||||
5. Design Web Crawler
|
||||
|
||||
Learn more about the design goals, scale estimations, high-level design overview, and detailed architecture diagram of these problems in this video - youtube.com/watch?v=Hq8pZ8G2Lm8
|
||||
|
||||
Part 1: youtube.com/watch?v=hykjbT5Z0oE
|
||||
|
||||
|
||||
|
||||
|
||||
## coding
|
||||
|
||||
- find target in chess board with given start position of knight
|
||||
|
||||
- Given an integer array and an integer K, find the number of sub arrays in which all elements are less than K.
|
||||
- Follow up
|
||||
- Given an integer array and an integer K, find the number of non overlapping unordered pairs of sub arrays in which all elements are less than K.
|
||||
72
puzzles/interviews/man_AHL/rand_num_next.py
Normal file
72
puzzles/interviews/man_AHL/rand_num_next.py
Normal file
@@ -0,0 +1,72 @@
|
||||
import random
|
||||
import bisect
|
||||
|
||||
class RandomGen(object):
|
||||
|
||||
def __init__(self, random_nums, probabilities):
|
||||
assert len(random_nums), 'Random number list is empty.'
|
||||
assert len(random_nums) == len(probabilities), 'Random numbers and probabilities do not match.'
|
||||
assert abs(1. - sum(probabilities)) < 0.0000001, 'Probabilities do not sum to 1.'
|
||||
|
||||
# Values that may be returned by next_num()
|
||||
self._random_nums = random_nums
|
||||
# Probability of the occurence of random_nums.
|
||||
# Actually we create range table here, such that all random numbers
|
||||
# ranging from (tbl[i-1],tbl[i]] map to random_number[i]
|
||||
self._range_table = probabilities
|
||||
for i in range(1,len(self._range_table)):
|
||||
self._range_table[i] += self._range_table[i-1]
|
||||
# All random numbers which are not in any range will map
|
||||
# to last _random_num. Therefore there is no point to have
|
||||
# last _random_num probability range in the table.
|
||||
self._range_table.pop()
|
||||
|
||||
|
||||
def next_num(self):
|
||||
"""
|
||||
Returns one of the randomNums. When this method is called
|
||||
multiple times over a long period, it should return the
|
||||
numbers roughly with the initialized probabilities.
|
||||
"""
|
||||
r = random.random()
|
||||
return self._random_nums[bisect.bisect_left(self._range_table, r)]
|
||||
|
||||
|
||||
def test_init(random_nums, probabilities):
|
||||
try:
|
||||
rg = RandomGen(random_nums, probabilities)
|
||||
except AssertionError as e:
|
||||
return
|
||||
assert False, "Had to be assert, but no assert could be detected."
|
||||
|
||||
|
||||
def test(input, rep_count = 1000):
|
||||
generate_stat = { _1 : 0 for _1,_ in input.items() }
|
||||
rg = RandomGen([key for key in input.keys()], [val for val in input.values()])
|
||||
for i in range(rep_count):
|
||||
generate_stat[rg.next_num()] += 1
|
||||
|
||||
for rnum, rnum_stat in generate_stat.items():
|
||||
stat_prob = rnum_stat/rep_count
|
||||
orig_prob = input[rnum]
|
||||
print('{}: orig: {} actual: {}'.format(rnum, orig_prob, stat_prob))
|
||||
print('')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_init([], []) # Empty list of numbers not allowed
|
||||
test_init([1, 2], [1. ]) # Probabilities don't match
|
||||
test_init([1, 2], [ 0.1, 0.1]) # Probabilities don't sum to 1.
|
||||
test({0 : 0.5,
|
||||
1 : 0.25,
|
||||
2 : 0.25 })
|
||||
test({-1 : 0.01,
|
||||
0 : 0.3,
|
||||
1 : 0.58,
|
||||
2 : 0.1,
|
||||
3 : 0.01 }, 100)
|
||||
test({-1 : 0.01,
|
||||
0 : 0.3,
|
||||
1 : 0.58,
|
||||
2 : 0.1,
|
||||
3 : 0.01 }, 100000)
|
||||
23
puzzles/interviews/man_AHL/sql_query.txt
Normal file
23
puzzles/interviews/man_AHL/sql_query.txt
Normal file
@@ -0,0 +1,23 @@
|
||||
I can imagine that the query should be something like this. But my SQL is not very good.
|
||||
|
||||
SELECT
|
||||
p.product_id as product_id,
|
||||
p.name as name,
|
||||
o.quantity as quantity
|
||||
FROM
|
||||
product p
|
||||
JOIN (
|
||||
SELECT
|
||||
product_id,
|
||||
SUM(quantity) as quantity
|
||||
FROM
|
||||
order
|
||||
WHERE
|
||||
dispatch_date > DATEADD(year, -1, GETDATE())
|
||||
GROUP BY
|
||||
product_id
|
||||
) o ON o.product_id = p.product_id
|
||||
WHERE
|
||||
p.available_from < DATEADD(month, -1, GETDATE())
|
||||
AND o.quantity < 10
|
||||
|
||||
22
puzzles/interviews/training/two_segments_intersect.cpp
Normal file
22
puzzles/interviews/training/two_segments_intersect.cpp
Normal file
@@ -0,0 +1,22 @@
|
||||
CareerCup
|
||||
Questions
|
||||
|
||||
Forum
|
||||
|
||||
Salaries
|
||||
|
||||
Resume Tips
|
||||
|
||||
RSS
|
||||
|
||||
Sign In
|
||||
|
||||
Microsoft Interview Question for SDE1s
|
||||
microsoft-interview-questions0
|
||||
of 0 votes
|
||||
0
|
||||
Answers
|
||||
Given n line segments, find if any two segments intersect
|
||||
http://www.geeksforgeeks.org/given-a-set-of-line-segments-find-if-any-two-segments-intersect/
|
||||
|
||||
- anonymous December 10, 2017 i
|
||||
71
puzzles/training/2048.cpp
Normal file
71
puzzles/training/2048.cpp
Normal file
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
|
||||
void print(const std::vector<int>& row)
|
||||
{
|
||||
for (auto i : row){
|
||||
std::cout << i << ',';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
void push(std::vector<int> row)
|
||||
{
|
||||
print(row);
|
||||
auto q = row.begin();
|
||||
auto pe = row.end();
|
||||
for (auto p = row.begin()+1; p != pe; ++p){
|
||||
if (*p==0){
|
||||
continue;
|
||||
}
|
||||
else if (*q == 0){
|
||||
*q+=*p;
|
||||
*p = 0;
|
||||
}
|
||||
else if (*q == *p){
|
||||
*q+=*p;
|
||||
*p = 0;
|
||||
++q;
|
||||
}
|
||||
else {
|
||||
*++q = *p;
|
||||
if (*q != *p){
|
||||
*p = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
print(row);
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
push({4, 0, 4, 8});
|
||||
|
||||
//......
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
136
puzzles/training/add_space_to_make_sentence.cpp
Normal file
136
puzzles/training/add_space_to_make_sentence.cpp
Normal file
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang++ -std=c++20 -O2 -pthread -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
/*
|
||||
## Problem Description
|
||||
|
||||
Given an input of a dictionary of words and an input string that does not
|
||||
contain spaces, write a method that returns a string with spaces inserted
|
||||
accordingly.
|
||||
|
||||
## Expected Completion Time
|
||||
|
||||
For unoptimized recursive solution: 25 minutes
|
||||
|
||||
## Problem Complexity Level
|
||||
|
||||
Coding Fluency: Medium
|
||||
|
||||
Problem Solving: Medium
|
||||
|
||||
## Questions the candidate might ask
|
||||
|
||||
1) Do you need to find all combinations of sentences? Always return
|
||||
the sentence with the shorter valid matches.
|
||||
2) What if there are spaces already in the string? Assume there aren't
|
||||
already spaces.
|
||||
3) What are the valid set of characters (eg. uppercase, symbols)? Assume
|
||||
dictionary is always all lowercase and are letters.
|
||||
4) What happens if nothing matches in the dictionary? Return null/none.
|
||||
5) What if there are left over characters in the string? Return null/none.
|
||||
|
||||
## Sample inputs - Expected outputs
|
||||
|
||||
Input: "bloombergisfun", ["bloom","bloomberg","is","fun"]
|
||||
Output: "bloomberg is fun"
|
||||
|
||||
## Input corner cases
|
||||
|
||||
Input: "bloombergisfun", ["bloom", "bloomberg","is"]
|
||||
Output: None/Null
|
||||
|
||||
Input: "bloombergisfun", ["bloom", "berg", "bloomberg","is","fun"]
|
||||
Output: "bloom berg is fun"
|
||||
|
||||
## Runtime complexity
|
||||
|
||||
Recursive Solution: O(2^N)
|
||||
This solution O(N*K) where `K` is max length of word in vocab)
|
||||
|
||||
Note:
|
||||
hashing of a string is not an O(1) function, but O(N) therefore complexity
|
||||
is O(N*K^2). But it can be made O(N*K).
|
||||
|
||||
*/
|
||||
|
||||
using dict_t = std::unordered_set<std::string>;
|
||||
|
||||
std::string solution(const std::string& str, const dict_t& dict)
|
||||
{
|
||||
size_t minw = str.size() +1;
|
||||
size_t maxw = 0;
|
||||
for (const auto& w : dict){
|
||||
minw = std::min(minw, w.size());
|
||||
maxw = std::max(maxw, w.size());
|
||||
}
|
||||
|
||||
std::vector<std::string> memo(str.size()+1, std::string());
|
||||
|
||||
for (size_t i = 0; i < str.size(); ++i){
|
||||
if (i != 0 && memo[i].empty()){
|
||||
continue;
|
||||
}
|
||||
for (size_t j = minw; j <= maxw && i+j <= str.size(); ++j){
|
||||
std::string candidate(str.data()+i, j);
|
||||
auto it = dict.find(candidate);
|
||||
if (it != dict.end()){
|
||||
memo[i+j]=memo[i] + " " + *it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return memo[str.size()];
|
||||
}
|
||||
|
||||
void test(const std::string& str, const dict_t& dict)
|
||||
{
|
||||
std::cout << "dict=[";
|
||||
bool first = true;
|
||||
for (const auto& word : dict){
|
||||
if (first){
|
||||
first = false;
|
||||
} else {
|
||||
std::cout <<", ";
|
||||
}
|
||||
std::cout << word;
|
||||
}
|
||||
std::cout << "]\n";
|
||||
std::cout << "str='" << str << "' -> ";
|
||||
std::cout.flush();
|
||||
std::cout << "'" << solution(str, dict) << "'\n\n";
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
test("bloombergisfun", {"bloom","bloomberg","is","fun"});
|
||||
test("bloombergisfun", {"bloom","bloomberg","is"});
|
||||
test("bloombergisfun", {"bloom", "berg", "bloomberg","is","fun"});
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
175
puzzles/training/airport_routes.cpp
Normal file
175
puzzles/training/airport_routes.cpp
Normal file
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <functional>
|
||||
|
||||
/*
|
||||
Implement a class called AirMap that has two methods:
|
||||
|
||||
1- add_route(start, destination)
|
||||
- adds a ONE WAY connecting flight from start to destination
|
||||
|
||||
2- print_all_routes(start, destination)
|
||||
- prints all possible routes from start to destination irrespective of hops
|
||||
|
||||
Sample inputs - Expected outputs
|
||||
Given the following flight routes, print all possible routes between the airports C and D
|
||||
|
||||
A ----> B
|
||||
B ----> A
|
||||
A ----> C
|
||||
C ----> A
|
||||
A ----> D
|
||||
D ----> A
|
||||
B ----> C
|
||||
C ----> B
|
||||
B ----> D
|
||||
D ----> B
|
||||
Expected output:
|
||||
|
||||
C,A,B,D,
|
||||
C,A,D,
|
||||
C,B,A,D,
|
||||
C,B,D,
|
||||
|
||||
Input corner cases
|
||||
Find all routes from A to C
|
||||
|
||||
No route example:
|
||||
|
||||
A ----> B
|
||||
C ----> B
|
||||
C ----> A
|
||||
|
||||
Expected output:
|
||||
|
||||
"No route was found" message or an empty output
|
||||
Source equals destination example: Find all routes from A to A
|
||||
|
||||
A ----> B
|
||||
B ----> C
|
||||
C ----> A
|
||||
Expected output:
|
||||
|
||||
A
|
||||
*/
|
||||
|
||||
class AirMap
|
||||
{
|
||||
std::unordered_map<std::string, std::unordered_set<std::string>> graph_;
|
||||
|
||||
public:
|
||||
void add_route(const std::string& start, const std::string& destination)
|
||||
{
|
||||
graph_[start].insert(destination);
|
||||
}
|
||||
|
||||
void print_all_routes(
|
||||
const std::string& start,
|
||||
const std::string& destination) const
|
||||
{
|
||||
std::unordered_set<std::string> visited;
|
||||
std::vector<std::string> path;
|
||||
|
||||
print_all_routes_helper(start, destination, visited, path,
|
||||
[](const std::vector<std::string>& path){
|
||||
for (const auto& node : path){
|
||||
std::cout << node << ',';
|
||||
}
|
||||
std::cout << std::endl;
|
||||
});
|
||||
}
|
||||
|
||||
void print_all_routes_helper(
|
||||
const std::string& start,
|
||||
const std::string& destination,
|
||||
std::unordered_set<std::string>& visited,
|
||||
std::vector<std::string>& path,
|
||||
std::function<void (const std::vector<std::string>& path)> fn) const
|
||||
{
|
||||
visited.insert(start);
|
||||
path.push_back(start);
|
||||
|
||||
if (start == destination){
|
||||
fn(path);
|
||||
} else {
|
||||
const auto it = graph_.find(start);
|
||||
if ( it != graph_.end()){
|
||||
for (const auto& node : it->second){
|
||||
if ( !visited.contains(node) ){
|
||||
print_all_routes_helper(node, destination, visited, path, fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visited.erase(start);
|
||||
path.pop_back();
|
||||
}
|
||||
};
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
AirMap map;
|
||||
map.add_route("A","B");
|
||||
map.add_route("B","A");
|
||||
map.add_route("B","D");
|
||||
map.add_route("A","D");
|
||||
map.add_route("A","C");
|
||||
map.add_route("C","A");
|
||||
map.add_route("C","B");
|
||||
map.add_route("B","C");
|
||||
map.add_route("D","A");
|
||||
map.add_route("D","B");
|
||||
|
||||
map.print_all_routes("C", "D");
|
||||
//......
|
||||
|
||||
{
|
||||
std::cout << "---------------------------------------" << std::endl;
|
||||
AirMap map;
|
||||
map.add_route("A","B");
|
||||
map.add_route("C","A");
|
||||
map.add_route("C","B");
|
||||
map.print_all_routes("A", "C");
|
||||
}
|
||||
|
||||
{
|
||||
std::cout << "---------------------------------------" << std::endl;
|
||||
AirMap map;
|
||||
map.add_route("A","B");
|
||||
map.add_route("B","C");
|
||||
map.add_route("C","A");
|
||||
map.print_all_routes("A", "A");
|
||||
}
|
||||
|
||||
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
74
puzzles/training/all_possible_subsets.cpp
Normal file
74
puzzles/training/all_possible_subsets.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
|
||||
/*
|
||||
Problem Description
|
||||
For given set of N elements print all possible subsets.
|
||||
|
||||
Sample inputs - Expected outputs
|
||||
{"a"} ->
|
||||
<- empty set
|
||||
a
|
||||
{"a", "b"} ->
|
||||
<- empty set
|
||||
a
|
||||
b
|
||||
a b
|
||||
Input corner cases
|
||||
Empty input set yields to one empty subset.
|
||||
*/
|
||||
|
||||
void printAllSubsets(const std::vector<std::string> &inputSet, std::ostream &os)
|
||||
{
|
||||
std::vector<bool> subset(inputSet.size(), false);
|
||||
|
||||
while (){
|
||||
|
||||
std::cout << '[';
|
||||
for (size_t i = 0; i < inputSet.size(); ++i){
|
||||
if (subset[i]){
|
||||
std::cout << inputSet[i] << ' ';
|
||||
}
|
||||
}
|
||||
std::cout << ']' << std::endl;
|
||||
|
||||
|
||||
std::
|
||||
|
||||
}
|
||||
std::vector<std::string>
|
||||
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
const std::vector<std::string> inputSet = {"a", "b", "c", "d"};
|
||||
printAllSubsets(inputSet, std::cout);
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
89
puzzles/training/array_inversion_count.cpp
Normal file
89
puzzles/training/array_inversion_count.cpp
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <functional>
|
||||
|
||||
/*
|
||||
https://app.codility.com/programmers/lessons/99-future_training/array_inversion_count/
|
||||
|
||||
An array A consisting of N integers is given. An inversion is a pair of indexes (P, Q) such that P < Q and A[Q] < A[P].
|
||||
|
||||
Write a function:
|
||||
|
||||
int solution(vector<int> &A);
|
||||
|
||||
that computes the number of inversions in A, or returns −1 if it exceeds 1,000,000,000.
|
||||
|
||||
For example, in the following array:
|
||||
A[0] = -1 A[1] = 6 A[2] = 3
|
||||
A[3] = 4 A[4] = 7 A[5] = 4
|
||||
|
||||
there are four inversions:
|
||||
(1,2) (1,3) (1,5) (4,5)
|
||||
|
||||
so the function should return 4.
|
||||
|
||||
Write an efficient algorithm for the following assumptions:
|
||||
|
||||
N is an integer within the range [0..100,000];
|
||||
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
|
||||
|
||||
*/
|
||||
|
||||
int solution(const std::vector<int>& v)
|
||||
{
|
||||
std::vector<size_t> iv(v.size(),0);
|
||||
for (size_t i=0; i<v.size(); ++i){
|
||||
iv[i] = i;
|
||||
}
|
||||
std::stable_sort(iv.begin(), iv.end(), [&v](size_t op1, size_t op2){
|
||||
return v[op1] < v[op2];
|
||||
});
|
||||
|
||||
size_t count = 0;
|
||||
for (size_t i=0; i < iv.size(); ++i){
|
||||
if ( i < iv[i]){
|
||||
count += iv[i] - i;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
std::cout << solution({-1, 6, 3, 4, 7, 4}) << std::endl;
|
||||
|
||||
std::cout << solution({0, 0, 0, 1, 1, 1}) << std::endl;
|
||||
std::cout << solution({0, 1, 0, 1, 1, 1}) << std::endl;
|
||||
std::cout << solution({0}) << std::endl;
|
||||
std::cout << solution({}) << std::endl;
|
||||
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
5
puzzles/training/build_and_run_last_changed.sh
Normal file
5
puzzles/training/build_and_run_last_changed.sh
Normal file
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
SRC=$(ls -t *.cpp | head -1)
|
||||
|
||||
set -x
|
||||
clang -std=c++20 -O2 -pthread -lstdc++ -I. $SRC && ./a.out
|
||||
86
puzzles/training/consolidate_contacts.cpp
Normal file
86
puzzles/training/consolidate_contacts.cpp
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
/*
|
||||
|
||||
std::unordered_map<std::string, std::unordered_set<std::string>>
|
||||
*/
|
||||
|
||||
using contacts_type = std::unordered_map<std::string, std::unordered_set<std::string>>;
|
||||
using emails_type = std::unordered_map<std::string, std::unordered_set<std::string>>;
|
||||
|
||||
|
||||
void
|
||||
all_contacts(
|
||||
const std::string& contact,
|
||||
std::unordered_set<std::string>& visited_contacts,
|
||||
const contacts_type& contacts,
|
||||
const emails_type& emails,
|
||||
std::unordered_set<std::string>& merged_emails)
|
||||
{
|
||||
visited_contacts.insert(contact);
|
||||
for (const auto& email: contacts[contact]){
|
||||
if (merged_emails.count(email)==0){
|
||||
merged_emails.insert(email);
|
||||
for (const auto& merging_contacts : emails[email]){
|
||||
all_contacts(merging_contacts, visited_contacts, contacts, emails, merged_emails );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
contacts_type merge( const contacts_type& contacts){
|
||||
|
||||
std::unordered_map<std::string, std::unordered_set<std::string>> emails;
|
||||
|
||||
for (const auto& contact : contacts){
|
||||
for (const auto& email : contact.second){
|
||||
emails[email].insert(contact.first);
|
||||
}
|
||||
}
|
||||
|
||||
contacts_type merged_contacts;
|
||||
std::unordered_set<std::string> visited_contacts;
|
||||
for (const auto& contact : contacts){
|
||||
if (visited_contacts.count(contact.first) == 0){
|
||||
auto& merged_emails = merged_contacts[contact.first];
|
||||
all_contacts(contact.first, visited_contacts, contacts, emails, merged_emails);
|
||||
}
|
||||
}
|
||||
|
||||
return merged_contacts;
|
||||
}
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
61
puzzles/training/constexpr_sqrt.cpp
Normal file
61
puzzles/training/constexpr_sqrt.cpp
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
|
||||
/* This is from "The C++ Programming Language, Fourth Edition
|
||||
* by Bjarne Stroustrup"*/
|
||||
constexpr int sqrt2(int x, int i = 3, int i_sq = 1){
|
||||
return i_sq <= x ? sqrt2(x, i+2, i_sq + i) : i/2-1;
|
||||
}
|
||||
|
||||
/* My simplified version:
|
||||
* Basically sum(1+2*i) where i==0..n-1 == n^2
|
||||
*/
|
||||
constexpr int sqrt(int x, int i = 1, int i_sq = 1){
|
||||
return i_sq <= x ? sqrt(x, i+1, i_sq + (1+2*i)) : i-1;
|
||||
}
|
||||
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
std::cout << "sqrt(-1)=" << sqrt(-1) << " vs " << sqrt2(-1) << std::endl;
|
||||
std::cout << "sqrt(0)=" << sqrt(0) << " vs " << sqrt2(0) << std::endl;
|
||||
std::cout << "sqrt(1)=" << sqrt(1) << " vs " << sqrt2(1) << std::endl;
|
||||
std::cout << "sqrt(2)=" << sqrt(2) << " vs " << sqrt2(2) << std::endl;
|
||||
std::cout << "sqrt(3)=" << sqrt(3) << " vs " << sqrt2(3) << std::endl;
|
||||
std::cout << "sqrt(4)=" << sqrt(4) << " vs " << sqrt2(4) << std::endl;
|
||||
std::cout << "sqrt(5)=" << sqrt(5) << " vs " << sqrt2(5) << std::endl;
|
||||
std::cout << "sqrt(6)=" << sqrt(6) << " vs " << sqrt2(6) << std::endl;
|
||||
std::cout << "sqrt(9)=" << sqrt(9) << " vs " << sqrt2(9) << std::endl;
|
||||
std::cout << "sqrt(16)=" << sqrt(16) << " vs " << sqrt2(16) << std::endl;
|
||||
std::cout << "sqrt(24)=" << sqrt(24) << " vs " << sqrt2(24) << std::endl;
|
||||
std::cout << "sqrt(25)=" << sqrt(25) << " vs " << sqrt2(25) << std::endl;
|
||||
std::cout << "sqrt(26)=" << sqrt(26) << " vs " << sqrt2(26) << std::endl;
|
||||
std::cout << "sqrt(36)=" << sqrt(36) << " vs " << sqrt2(36) << std::endl;
|
||||
|
||||
//......
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM-: let b:argv=""
|
||||
VIM: let b:cf5build="clang -std=c++14 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
118
puzzles/training/disjoint_intervals.cpp
Normal file
118
puzzles/training/disjoint_intervals.cpp
Normal file
@@ -0,0 +1,118 @@
|
||||
[2, 9]
|
||||
[3, 13]
|
||||
[3, 10]
|
||||
[3, 8]
|
||||
[3, 6]
|
||||
[3, 7]
|
||||
[4, 8]
|
||||
[4, 4] *
|
||||
[4, 10]
|
||||
[5, 11]
|
||||
[7, 7] *
|
||||
[7, 8]
|
||||
[7, 12]
|
||||
[7, 15]
|
||||
[9, 12]
|
||||
[9, 10] *
|
||||
|
||||
/*
|
||||
|
||||
Disjoint Intervals (https://www.interviewbit.com/problems/disjoint-intervals/)
|
||||
|
||||
Asked in:
|
||||
Google
|
||||
|
||||
Problem Description
|
||||
|
||||
Given a set of N intervals denoted by 2D array A of size N x 2, the task is to find the length of maximal set of mutually disjoint intervals.
|
||||
|
||||
Two intervals [x, y] & [p, q] are said to be disjoint if they do not have any point in common.
|
||||
|
||||
Return a integer denoting the length of maximal set of mutually disjoint intervals.
|
||||
|
||||
|
||||
|
||||
Problem Constraints
|
||||
|
||||
1 <= N <= 105
|
||||
|
||||
1 <= A[i][0] <= A[i][1] <= 109
|
||||
|
||||
|
||||
|
||||
Input Format
|
||||
|
||||
First and only argument is a 2D array A of size N x 2 denoting the N intervals.
|
||||
|
||||
|
||||
Output Format
|
||||
|
||||
Return a integer denoting the length of maximal set of mutually disjoint intervals.
|
||||
|
||||
|
||||
Example Input
|
||||
|
||||
Input 1:
|
||||
|
||||
A = [
|
||||
[1, 4]
|
||||
[2, 3]
|
||||
[4, 6]
|
||||
[8, 9]
|
||||
]
|
||||
|
||||
Input 2:
|
||||
|
||||
A = [
|
||||
[1, 9]
|
||||
[2, 3]
|
||||
[5, 7]
|
||||
]
|
||||
|
||||
|
||||
|
||||
Example Output
|
||||
|
||||
Output 1:
|
||||
|
||||
3
|
||||
|
||||
Output 2:
|
||||
|
||||
2
|
||||
|
||||
|
||||
|
||||
Example Explanation
|
||||
|
||||
Explanation 1:
|
||||
|
||||
Intervals: [ [1, 4], [2, 3], [4, 6], [8, 9] ]
|
||||
Intervals [2, 3] and [1, 4] overlap.
|
||||
We must include [2, 3] because if [1, 4] is included thenwe cannot include [4, 6].
|
||||
We can include at max three disjoint intervals: [[2, 3], [4, 6], [8, 9]]
|
||||
|
||||
Explanation 2:
|
||||
|
||||
Intervals: [ [1, 9], [2, 3], [5, 7] ]
|
||||
We can include at max two disjoint intervals: [[2, 3], [5, 7]]
|
||||
*/
|
||||
int Solution::solve(vector<vector<int> > &A) {
|
||||
|
||||
std::sort(A.begin(),A.end(),
|
||||
[](const vector<int>& op1, const vector<int>& op2){
|
||||
return (op1[0] < op2[0] );
|
||||
});
|
||||
|
||||
int c = 1;
|
||||
auto it = A.begin();
|
||||
for (auto jt = A.begin()+1; jt != A.end(); ++jt){
|
||||
if (it->at(1) < jt->at(0)){
|
||||
c++;
|
||||
it = jt;
|
||||
} if (jt->at(1) < it->at(1)){
|
||||
it = jt;
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
77
puzzles/training/distinct_integer_range.cpp
Normal file
77
puzzles/training/distinct_integer_range.cpp
Normal file
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include "stdafx.h"
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
/*
|
||||
You are given a sorted list of distinct integers from 0 to 99, for
|
||||
instance [0, 1, 2, 50, 52, 75]. Your task is to produce a string
|
||||
that describes numbers missing from the list; in this case
|
||||
"3-49,51,53-74,76-99".
|
||||
|
||||
Examples:
|
||||
|
||||
[] <20>0-99<39>
|
||||
[0] <20>1-99<39>
|
||||
[3, 5] <20>0-2,4,6-99<39>
|
||||
*/
|
||||
|
||||
inline
|
||||
void print_range_if_not_empty(int rb, int re)
|
||||
{
|
||||
if (re - rb > 2) {
|
||||
std::cout << ',' << rb + 1 << '-' << re - 1;
|
||||
}
|
||||
else if (re - rb > 1) {
|
||||
std::cout << ',' << rb + 1;
|
||||
}
|
||||
}
|
||||
|
||||
void print_gaps(std::vector<int> v)
|
||||
{
|
||||
int v_prev = -1;
|
||||
for (int i = 0; i < v.size(); v_prev = v[i++]) {
|
||||
print_range_if_not_empty(v_prev, v[i]);
|
||||
}
|
||||
print_range_if_not_empty(v_prev, 100);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try {
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
print_gaps({ 0, 1, 2, 50, 52, 75 });
|
||||
print_gaps({ 2, 4, 5, 7, 90 });
|
||||
print_gaps({ 0, 4, 5, 7, 99 });
|
||||
|
||||
|
||||
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
79
puzzles/training/find_gaps.cpp
Normal file
79
puzzles/training/find_gaps.cpp
Normal file
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include "stdafx.h"
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
/*
|
||||
google-interview-questions
|
||||
|
||||
You are given a sorted list of distinct integers from 0 to 99, for
|
||||
instance [0, 1, 2, 50, 52, 75]. Your task is to produce a string
|
||||
that describes numbers missing from the list; in this case
|
||||
"3-49,51,53-74,76-99".
|
||||
|
||||
Examples:
|
||||
|
||||
[] <20>0-99<39>
|
||||
[0] <20>1-99<39>
|
||||
[3, 5] <20>0-2,4,6-99<39>
|
||||
*/
|
||||
|
||||
inline
|
||||
void print_range_if_not_empty(int rb, int re)
|
||||
{
|
||||
if (re-rb > 2) {
|
||||
std::cout << ',' << rb + 1 << '-' << re - 1;
|
||||
}
|
||||
else if (re-rb > 1) {
|
||||
std::cout << ',' << rb + 1;
|
||||
}
|
||||
}
|
||||
|
||||
void print_gaps(std::vector<int> v)
|
||||
{
|
||||
int v_prev = -1;
|
||||
for (int i = 0; i < v.size(); v_prev = v[i++]) {
|
||||
print_range_if_not_empty(v_prev, v[i]);
|
||||
}
|
||||
print_range_if_not_empty(v_prev, 100);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try {
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
print_gaps({ 0, 1, 2, 50, 52, 75 });
|
||||
print_gaps({ 2, 4, 5, 7, 90 });
|
||||
print_gaps({ 0, 4, 5, 7, 99 });
|
||||
|
||||
|
||||
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
61
puzzles/training/gas_station.cpp
Normal file
61
puzzles/training/gas_station.cpp
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
|
||||
Gas Station
|
||||
|
||||
Asked in:
|
||||
Bloomberg
|
||||
Google
|
||||
DE Shaw
|
||||
Amazon
|
||||
Flipkart
|
||||
|
||||
Given two integer arrays A and B of size N.
|
||||
There are N gas stations along a circular route, where the amount of gas at station i is A[i].
|
||||
|
||||
You have a car with an unlimited gas tank and it costs B[i] of gas to travel from station i
|
||||
to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
|
||||
|
||||
Return the minimum starting gas station’s index if you can travel around the circuit once, otherwise return -1.
|
||||
|
||||
You can only travel in one direction. i to i+1, i+2, … n-1, 0, 1, 2.. Completing the circuit means starting at i and
|
||||
ending up at i again.
|
||||
|
||||
|
||||
|
||||
Input Format
|
||||
|
||||
The first argument given is the integer array A.
|
||||
The second argument given is the integer array B.
|
||||
|
||||
Output Format
|
||||
|
||||
Return the minimum starting gas station's index if you can travel around the circuit once, otherwise return -1.
|
||||
|
||||
For Example
|
||||
|
||||
Input 1:
|
||||
A = [1, 2]
|
||||
B = [2, 1]
|
||||
Output 1:
|
||||
1
|
||||
Explanation 1:
|
||||
If you start from index 0, you can fill in A[0] = 1 amount of gas. Now your tank has 1 unit of gas. But you need B[0] = 2 gas to travel to station 1.
|
||||
If you start from index 1, you can fill in A[1] = 2 amount of gas. Now your tank has
|
||||
*/
|
||||
int Solution::canCompleteCircuit(const vector<int> &A, const vector<int> &B) {
|
||||
int f = 0;
|
||||
int mf = 0;
|
||||
size_t mi = -1;
|
||||
for (size_t i =0; i < A.size(); ++i){
|
||||
f += A[i]-B[i];
|
||||
if (f < mf){
|
||||
mf = f;
|
||||
mi = i;
|
||||
}
|
||||
if ((i+1) == A.size() && f < 0){
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return (mi+1) % A.size();
|
||||
}
|
||||
89
puzzles/training/longest_chain_equal_K.cpp
Normal file
89
puzzles/training/longest_chain_equal_K.cpp
Normal file
@@ -0,0 +1,89 @@
|
||||
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
/*
|
||||
snap-inc-interview-questions
|
||||
|
||||
You are given an array of integers and a number K. You have to find the any
|
||||
continue sub-array whose elements sum is K. Please note that, the array may
|
||||
have positive, negative, and zeros as its element.
|
||||
|
||||
The desired complexity is O(N).
|
||||
|
||||
Example:
|
||||
Input: [7 0 9 -10 0 789], K = 0
|
||||
Output: Array from index 1 to Index 1.
|
||||
|
||||
Input: [1 2 3 5 -10] K = 0
|
||||
Output: Array from Index 1 to Index 4.
|
||||
|
||||
If K = -2, Output would have been SubArray from Index 2 to Index 4.
|
||||
*/
|
||||
|
||||
void solution( std::vector<int> v, int K )
|
||||
{
|
||||
int f = -1;
|
||||
int l = -2;
|
||||
|
||||
std::unordered_map<int, int> m;
|
||||
int s = 0;
|
||||
for ( int i = 0; i < v.size(); ++i ) {
|
||||
s+= v[i];
|
||||
auto p = m.emplace( s, i);
|
||||
if ( !p.second ){
|
||||
p.first->second = i;
|
||||
}
|
||||
}
|
||||
|
||||
s = 0;
|
||||
for ( int i = 0; i < v.size(); ++i ) {
|
||||
auto r = m.find(s+K);
|
||||
if ( r != m.end() && l-f < r->second - i){
|
||||
l = r->second;
|
||||
f = i;
|
||||
}
|
||||
s+= v[i];
|
||||
}
|
||||
|
||||
std::cout << " {";
|
||||
for ( auto i : v ){
|
||||
std::cout << i << ", ";
|
||||
}
|
||||
std::cout << "}, " << K << " -> (" << f << ", " << l << ")" << std::endl;
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
|
||||
solution({7, 0, 9, -10, 0, 789}, 0);
|
||||
solution({1, 2, 3, 5, -10}, 0);
|
||||
solution({1, 2, 3, 5, -10}, -2);
|
||||
solution({1, 2, 3, 5, -10}, -10);
|
||||
solution({1, 2, 3, 5, -10}, 1);
|
||||
solution({7, 2, 9, -10, 0, 789}, 7);
|
||||
solution({7, 2, 9, -10, 0, 789}, 10000);
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
34
puzzles/training/majority_element.cpp
Normal file
34
puzzles/training/majority_element.cpp
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
Majority Element (https://www.interviewbit.com/problems/majority-element/)
|
||||
|
||||
Asked in:
|
||||
Microsoft
|
||||
Yahoo
|
||||
Google
|
||||
Amazon
|
||||
|
||||
Given an array of size n, find the majority element. The majority element is the element that appears more than floor(n/2) times.
|
||||
|
||||
You may assume that the array is non-empty and the majority element always exist in the array.
|
||||
|
||||
Example :
|
||||
|
||||
Input : [2, 1, 2]
|
||||
Return : 2 which occurs 2 times which is greater than 3/2.
|
||||
|
||||
*/
|
||||
int Solution::majorityElement(const vector<int> &A) {
|
||||
int c =0;
|
||||
int e =0;
|
||||
for (int a : A){
|
||||
if (c == 0){
|
||||
e = a;
|
||||
c++;
|
||||
} else if ( e != a ){
|
||||
c--;
|
||||
} else {
|
||||
c++;
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
116
puzzles/training/max_points_on_a_line.cpp
Normal file
116
puzzles/training/max_points_on_a_line.cpp
Normal file
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include "stdafx.h"
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
/*
|
||||
https://leetcode.com/problems/max-points-on-a-line/
|
||||
|
||||
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
|
||||
*/
|
||||
|
||||
struct Point {
|
||||
int x;
|
||||
int y;
|
||||
Point() : x(0), y(0) {}
|
||||
Point(int a, int b) : x(a), y(b) {}
|
||||
};
|
||||
|
||||
struct pairhash {
|
||||
std::size_t operator() (const Point& p) const {
|
||||
return std::hash<int>()(p.x) ^ std::hash<int>()(p.y);
|
||||
}
|
||||
};
|
||||
|
||||
bool operator == (const Point& p1, const Point& p2) {
|
||||
return p1.x == p2.x && p1.y == p2.y;
|
||||
}
|
||||
|
||||
Point ratio(int x, int y) {
|
||||
if (x == 0) {
|
||||
return Point(0, 1);
|
||||
}
|
||||
else if (y == 0) {
|
||||
return Point(1, 0);
|
||||
}
|
||||
else if ( x < 0 ) {
|
||||
x = -x;
|
||||
y = -y;
|
||||
}
|
||||
|
||||
int a = std::max(abs(x), abs(y));
|
||||
int b = std::min(abs(x), abs(y));
|
||||
for (int c; (c = a % b); a = b, b = c);
|
||||
return Point(x / b, y / b);
|
||||
}
|
||||
|
||||
int solve(const std::vector<Point>& v) {
|
||||
|
||||
std::unordered_map<Point, int, pairhash> vv;
|
||||
for (const auto& p : v) {
|
||||
vv[p]++;
|
||||
}
|
||||
|
||||
if (vv.empty()) {
|
||||
return 0;
|
||||
}
|
||||
else if (vv.size()==1) {
|
||||
return vv.begin()->second;
|
||||
}
|
||||
|
||||
int max_points = 1;
|
||||
for (auto i = vv.begin(); i != vv.end(); i++) {
|
||||
std::unordered_map<Point, int, pairhash> s;
|
||||
for (auto j = std::next(i); j != vv.end(); j++) {
|
||||
const auto line = ratio(i->first.x - j->first.x, i->first.y - j->first.y);
|
||||
s[line] += j->second;
|
||||
max_points = std::max(max_points, s[line] + i->second);
|
||||
}
|
||||
}
|
||||
|
||||
return max_points;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try {
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
std::cout << solve({ { 1,1 },{ 2,2 },{ 3,3 } }) << std::endl;
|
||||
std::cout << solve({ { 1,1 },{ 3,2 },{ 5,3 },{ 4,1 },{ 2,3 },{ 1,4 } }) << std::endl;
|
||||
std::cout << solve({ { 2, 3 },{ 3, 3 },{ -5, 3 } }) << std::endl;
|
||||
std::cout << solve({ { 2, 2 },{ 3, 3 },{ 2, 2 },{ 3, 3 } }) << std::endl;
|
||||
std::cout << solve({ { 2, 2 },{ 2, 3 },{ 3, 2 },{ 3, 3 } }) << std::endl;
|
||||
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
159
puzzles/training/median_stream.cpp
Normal file
159
puzzles/training/median_stream.cpp
Normal file
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
/*
|
||||
Median Stream
|
||||
You're given a list of n integers arr[0..(n-1)]. You must compute a list
|
||||
output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive),
|
||||
output[i] is equal to the median of the elements arr[0..i] (rounded down to
|
||||
the nearest integer).
|
||||
|
||||
The median of a list of integers is defined as follows. If the integers were
|
||||
to be sorted, then:
|
||||
|
||||
If there are an odd number of integers, then the median is equal to the
|
||||
middle integer in the sorted order.
|
||||
Otherwise, if there are an even number of integers, then the median is equal
|
||||
to the average of the two middle-most integers in the sorted order.
|
||||
|
||||
Input
|
||||
n is in the range [1, 1,000,000].
|
||||
Each value arr[i] is in the range [1, 1,000,000].
|
||||
Output
|
||||
Return a list of n integers output[0..(n-1)], as described above.
|
||||
|
||||
Example 1
|
||||
n = 4
|
||||
arr = [5, 15, 1, 3]
|
||||
output = [5, 10, 5, 4]
|
||||
The median of [5] is 5, the median of [5, 15] is (5 + 15) / 2 = 10,
|
||||
the median of [5, 15, 1] is 5, and the median of [5, 15, 1, 3] is (3 + 5) / 2 = 4.
|
||||
|
||||
Example 2
|
||||
n = 2
|
||||
arr = [1, 2]
|
||||
output = [1, 1]
|
||||
The median of [1] is 1,
|
||||
the median of [1, 2] is (1 + 2) / 2 = 1.5 (which should be rounded down to 1).
|
||||
*/
|
||||
|
||||
std::vector<int> findMedian(std::vector <int> arr) {
|
||||
// Write your code here
|
||||
std::vector<int> r;
|
||||
std::vector<int> l;
|
||||
|
||||
for (size_t i = 0; i < arr.size(); ++i){
|
||||
l.push_back(arr[i]);
|
||||
std::push_heap(l.begin(), l.end());
|
||||
|
||||
if (l.size() > ((i+1)/2+1)){
|
||||
std::pop_heap(l.begin(), l.end());
|
||||
l.resize(l.size()-1);
|
||||
}
|
||||
|
||||
if ((i+1)%2){
|
||||
r.push_back(l[0]);
|
||||
} else if (l.size() == 2){
|
||||
r.push_back( (l[0]+l[1])/2 );
|
||||
} else {
|
||||
r.push_back( (l[0]+std::max(l[1],l[2]))/2 );
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
// These are the tests we use to determine if the solution is correct.
|
||||
// You can add your own at the bottom, but they are otherwise not editable!
|
||||
void printIntegerVector(std::vector <int> array) {
|
||||
int size = array.size();
|
||||
std::cout << "[";
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (i != 0) {
|
||||
std::cout << ", ";
|
||||
}
|
||||
std::cout << array[i];
|
||||
}
|
||||
std::cout << "]";
|
||||
}
|
||||
|
||||
int test_case_number = 1;
|
||||
|
||||
void check(std::vector <int>& expected, std::vector <int>& output) {
|
||||
int expected_size = expected.size();
|
||||
int output_size = output.size();
|
||||
bool result = true;
|
||||
if (expected_size != output_size) {
|
||||
result = false;
|
||||
}
|
||||
for (int i = 0; i < std::min(expected_size, output_size); i++) {
|
||||
result &= (output[i] == expected[i]);
|
||||
}
|
||||
const char* rightTick = "PASS - ";
|
||||
const char* wrongTick = "FAIL - ";
|
||||
if (result) {
|
||||
std::cout << rightTick << "Test #" << test_case_number << "\n";
|
||||
}
|
||||
else {
|
||||
std::cout << wrongTick << "Test #" << test_case_number << ": Expected ";
|
||||
printIntegerVector(expected);
|
||||
std::cout << " Your output: ";
|
||||
printIntegerVector(output);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
test_case_number++;
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
{
|
||||
std::vector <int> arr_1{5, 15, 1, 3};
|
||||
std::vector <int> expected_1{5, 10, 5, 4};
|
||||
std::vector <int> output_1 = findMedian(arr_1);
|
||||
check(expected_1, output_1);
|
||||
}{
|
||||
std::vector <int> arr_2{2, 4, 7, 1, 5, 3};
|
||||
std::vector <int> expected_2{2, 3, 4, 3, 4, 3};
|
||||
std::vector <int> output_2 = findMedian(arr_2);
|
||||
check(expected_2, output_2);
|
||||
}{
|
||||
std::vector <int> arr_2{2, 4, 7, 1, 5};
|
||||
std::vector <int> expected_2{2, 3, 4, 3, 4};
|
||||
std::vector <int> output_2 = findMedian(arr_2);
|
||||
check(expected_2, output_2);
|
||||
}{
|
||||
std::vector <int> arr_2{2, 4, 7, 1, 5, 3, 4};
|
||||
std::vector <int> expected_2{2, 3, 4, 3, 4, 3, 4 };
|
||||
std::vector <int> output_2 = findMedian(arr_2);
|
||||
check(expected_2, output_2);
|
||||
}
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
148
puzzles/training/multithreaded_queue.cpp
Normal file
148
puzzles/training/multithreaded_queue.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include "stdafx.h"
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
|
||||
/*
|
||||
Queue.
|
||||
*/
|
||||
|
||||
thread_local size_t this_tid;
|
||||
|
||||
template <typename M>
|
||||
class MtQueue {
|
||||
|
||||
std::queue<M> m_queue;
|
||||
std::mutex m_mutex;
|
||||
std::condition_variable m_push_cond;
|
||||
std::condition_variable m_pop_cond;
|
||||
std::atomic<bool> m_stopped;
|
||||
|
||||
static const size_t max_queue = 100;
|
||||
|
||||
|
||||
public:
|
||||
|
||||
/* Stop Queue */
|
||||
void stop() {
|
||||
std::unique_lock<std::mutex> lock(m_mutex);
|
||||
m_stopped.store(true);
|
||||
m_pop_cond.notify_all();
|
||||
m_push_cond.notify_all();
|
||||
}
|
||||
|
||||
/* Blocks when */
|
||||
bool push(M m) {
|
||||
std::unique_lock<std::mutex> lock(m_mutex);
|
||||
while (m_queue.size() >= max_queue && !m_stopped.load()) {
|
||||
printf(" %lld: is full.\n", this_tid);
|
||||
m_push_cond.wait(lock);
|
||||
}
|
||||
if (m_stopped.load()) {
|
||||
return false;
|
||||
}
|
||||
m_queue.push(m);
|
||||
printf("%lld: size %lld.\n", this_tid, m_queue.size());
|
||||
m_pop_cond.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Blocks when empty.*/
|
||||
bool pop(M& m) {
|
||||
std::unique_lock<std::mutex> lock(m_mutex);
|
||||
while (m_queue.empty() && !m_stopped.load()) {
|
||||
printf(" %lld: is empty.\n", this_tid);
|
||||
m_pop_cond.wait(lock);
|
||||
}
|
||||
if (m_stopped.load()) {
|
||||
return false;
|
||||
}
|
||||
m = m_queue.front();
|
||||
m_queue.pop();
|
||||
printf("%lld: size %lld.\n", this_tid, m_queue.size());
|
||||
m_push_cond.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
void test() {
|
||||
MtQueue<int> q;
|
||||
|
||||
auto push_proc = [&q](size_t tid) {
|
||||
this_tid = tid;
|
||||
int i = 0;
|
||||
while (q.push(2)) {
|
||||
if (++i % 101 == 0) {
|
||||
auto m = std::chrono::milliseconds(100);
|
||||
//printf("%lld: pusher waiting for %lldms.\n", this_tid, m.count());
|
||||
//std::this_thread::sleep_for(m);
|
||||
}
|
||||
}
|
||||
};
|
||||
auto pop_proc = [&q](size_t tid) {
|
||||
this_tid = tid;
|
||||
int m;
|
||||
while (q.pop(m)) {
|
||||
|
||||
//printf("%lld: popper waiting for %dms.\n", this_tid, m);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(m));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
std::vector<std::thread> v;
|
||||
v.reserve(16);
|
||||
v.emplace_back(push_proc, v.size());
|
||||
v.emplace_back(pop_proc, v.size());
|
||||
v.emplace_back(pop_proc, v.size());
|
||||
v.emplace_back(pop_proc, v.size());
|
||||
v.emplace_back(pop_proc, v.size());
|
||||
v.emplace_back(pop_proc, v.size());
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
q.stop();
|
||||
printf(" STOPPING.\n");
|
||||
for (auto& t : v) {
|
||||
t.join();
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try {
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
while (true) {
|
||||
test();
|
||||
}
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
185
puzzles/training/old_mile.cpp
Normal file
185
puzzles/training/old_mile.cpp
Normal file
@@ -0,0 +1,185 @@
|
||||
O,1,11.3,4781,S, 1,5
|
||||
O,6,53.8,1589,S, 3,7
|
||||
O,4,40.7,9544,B, 5,9
|
||||
O,7,14.6,858,B, 6,10
|
||||
O,3,32.5,6971,S, 7,11
|
||||
O,5,19.5,8747,S, 7,11
|
||||
O,0,95.6,1206,S, 10,14
|
||||
O,2,57.5,2178,B, 11,15
|
||||
|
||||
|
||||
Q,1
|
||||
Q,6
|
||||
Q,10
|
||||
Q,12
|
||||
Q,14
|
||||
Q,14
|
||||
Q,15
|
||||
Q,15
|
||||
|
||||
|
||||
R,3384
|
||||
R,3384
|
||||
R,3384
|
||||
R,3384
|
||||
R,3384
|
||||
R,11133
|
||||
R,0
|
||||
R,16576
|
||||
|
||||
#include <cstdint>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
using namespace std;
|
||||
|
||||
// Please disable before submitting.
|
||||
constexpr bool kDebug = false;
|
||||
|
||||
struct order {
|
||||
uint64_t order_token;
|
||||
uint64_t shares;
|
||||
double price;
|
||||
bool side; // false = sell, true = buy
|
||||
uint64_t created_at;
|
||||
uint64_t cancelled_or_executed_at;
|
||||
};
|
||||
|
||||
struct query {
|
||||
uint64_t query_time;
|
||||
};
|
||||
|
||||
std::vector<uint64_t> your_solution(const vector<order> &orders,
|
||||
const vector<query> &queries) {
|
||||
|
||||
std::vector<uint64_t> resp(queries.size(), 0);
|
||||
|
||||
std::vector<std::pair<query, size_t>> sorted_queries;
|
||||
sorted_queries.reserve(queries.size());
|
||||
for (size_t i = 0; i < queries.size(); ++i ){
|
||||
sorted_queries.emplace_back(queries[i],i);
|
||||
}
|
||||
std::sort(sorted_queries.begin(), sorted_queries.end(),
|
||||
[](const auto& op1, const auto& op2){
|
||||
return op1.first.query_time < op2.first.query_time;
|
||||
});
|
||||
|
||||
std::vector<order> sorted_orders(orders.begin(), orders.end());
|
||||
std::sort(sorted_orders.begin(), sorted_orders.end(),
|
||||
[](const auto& op1, const auto& op2){
|
||||
return op1.created_at < op2.created_at;
|
||||
});
|
||||
|
||||
std::vector<std::vector<order>::iterator> current_orders;
|
||||
auto current_orders_cmp = [](const auto& op1, const auto& op2){
|
||||
return op1->cancelled_or_executed_at < op2->cancelled_or_executed_at;
|
||||
};
|
||||
|
||||
|
||||
auto ot = sorted_orders.begin();
|
||||
for (const auto& q : sorted_queries){
|
||||
while ( !current_orders.empty()
|
||||
&& current_orders.front()->cancelled_or_executed_at < q.first.query_time){
|
||||
// remove from heap
|
||||
std::pop_heap(current_orders.begin(), current_orders.end(),
|
||||
current_orders_cmp);
|
||||
current_orders.resize(current_orders.size()-1);
|
||||
}
|
||||
|
||||
// std::cout << "2222222" << std::endl;
|
||||
|
||||
while (ot != sorted_orders.end() && ot->created_at <= q.first.query_time){
|
||||
if ( ot->cancelled_or_executed_at >= q.first.query_time){
|
||||
current_orders.push_back(ot);
|
||||
std::push_heap(current_orders.begin(), current_orders.end(),
|
||||
current_orders_cmp);
|
||||
}
|
||||
++ot;
|
||||
}
|
||||
|
||||
// std::cout << "33333" << std::endl;
|
||||
|
||||
uint64_t shares_live = 0;
|
||||
for (const auto cot : current_orders){
|
||||
shares_live += cot->shares;
|
||||
}
|
||||
resp[q.second] = shares_live;
|
||||
}
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Please do not change any code below. //
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
std::pair<vector<order>, vector<query>> gen_input(int seed) {
|
||||
mt19937 gen(seed);
|
||||
|
||||
const uint64_t order_len = 1 << (gen() % 20);
|
||||
const uint64_t time_len = 1 << (gen() % 20);
|
||||
|
||||
vector<order> orders;
|
||||
for (uint64_t i = 0; i < order_len; ++i) {
|
||||
const double duration = std::max(1.0, time_len / std::log2(time_len));
|
||||
const uint64_t start = gen() % time_len;
|
||||
const uint64_t end = std::min<int>(start + duration, time_len);
|
||||
order o{
|
||||
.order_token = i,
|
||||
.shares = static_cast<uint64_t>(gen() % 10000),
|
||||
.price = static_cast<double>(gen() % 1000) / 10,
|
||||
.side = gen() % 2 ? false : true,
|
||||
.created_at = start,
|
||||
.cancelled_or_executed_at = end,
|
||||
};
|
||||
orders.emplace_back(o);
|
||||
}
|
||||
|
||||
vector<query> queries;
|
||||
for (uint64_t i = 0; i < order_len; ++i) {
|
||||
query q{
|
||||
.query_time = static_cast<uint64_t>(gen() % time_len),
|
||||
};
|
||||
queries.emplace_back(q);
|
||||
}
|
||||
|
||||
return {std::move(orders), std::move(queries)};
|
||||
}
|
||||
|
||||
int hash_result(const std::vector<uint64_t> &answers) {
|
||||
std::hash<uint64_t> hasher;
|
||||
uint64_t result = 0;
|
||||
for (auto &a : answers) {
|
||||
result = hasher(a) ^ (result << 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// This test harness generates an input to and hashes the output from your
|
||||
// solution. Please do not change any code below this line.
|
||||
int solution(int seed) {
|
||||
auto input = gen_input(seed);
|
||||
bool debug = kDebug && input.first.size() < 100 && input.second.size() < 100;
|
||||
if (debug) {
|
||||
for (auto &o : input.first) {
|
||||
std::cerr << "O," << o.order_token << "," << o.price << "," << o.shares
|
||||
<< "," << (o.side ? 'B' : 'S') << "," << o.created_at << ","
|
||||
<< o.cancelled_or_executed_at << "\n";
|
||||
}
|
||||
for (auto &q : input.second) {
|
||||
std::cerr << 'Q' << "," << q.query_time << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
const auto answers = your_solution(input.first, input.second);
|
||||
|
||||
if (debug) {
|
||||
for (auto &a : answers) {
|
||||
std::cerr << "R," << a << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return hash_result(answers);
|
||||
}
|
||||
|
||||
70
puzzles/training/permutation.cpp
Normal file
70
puzzles/training/permutation.cpp
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
VIM: let b:cf5build="clang++ -std=c++20 -O2 -pthread -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
|
||||
void permutate(auto b, auto e)
|
||||
{
|
||||
auto bt = std::reverse_iterator(e);
|
||||
auto et = std::reverse_iterator(b);
|
||||
|
||||
auto it = bt+1;
|
||||
for ( ; it != et && *it >= *(it-1); ++it);
|
||||
|
||||
for (auto qt = bt, rt = it-1; rt > qt; qt++, rt--){
|
||||
std::swap(*qt, *rt);
|
||||
}
|
||||
|
||||
if (it != et){
|
||||
auto pt = it-1;
|
||||
for( ; pt != bt && *it >= *pt; --pt);
|
||||
std::swap(*it, *pt);
|
||||
}
|
||||
}
|
||||
|
||||
void test(std::string char_set)
|
||||
{
|
||||
std::sort(char_set.begin(), char_set.end());
|
||||
std::string perm = char_set;
|
||||
int i = 0;
|
||||
do {
|
||||
++i;
|
||||
std::cout << perm << '\n';
|
||||
permutate(perm.begin(), perm.end());
|
||||
} while (perm != char_set);
|
||||
|
||||
std::cout << i << '\n' << "-------------------------------------\n";
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
test( "abcd" );
|
||||
test( "aab" );
|
||||
test( "aabb" );
|
||||
test( "aaabbb" );
|
||||
|
||||
//......
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
84
puzzles/training/string_addition.cpp
Normal file
84
puzzles/training/string_addition.cpp
Normal file
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include "stdafx.h"
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
|
||||
/*
|
||||
given an array representing a non-negative integer (ex: 123 represented
|
||||
as [1,2,3]), return the next integer (output: [1,2,4]).
|
||||
run through all edge cases (ex: [9,9,9,9,9,9,9,9] etc)
|
||||
*/
|
||||
|
||||
int dig(char ch) {
|
||||
return ch - '0';
|
||||
}
|
||||
|
||||
char chr(int dig) {
|
||||
return dig + '0';
|
||||
}
|
||||
|
||||
std::string incr(std::string n) {
|
||||
int carry = 1;
|
||||
for (size_t i = n.size(); i-- > 0; ) {
|
||||
int ds = dig(n[i]) + carry;
|
||||
if (ds >= 10) {
|
||||
carry = ds / 10;
|
||||
ds %= 10;
|
||||
}
|
||||
else {
|
||||
carry = 0;
|
||||
}
|
||||
n[i] = chr(ds);
|
||||
}
|
||||
|
||||
if (carry) {
|
||||
return chr(carry) + n;
|
||||
}
|
||||
else {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try {
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
std::cout << incr("0") << std::endl;
|
||||
std::cout << incr("1") << std::endl;
|
||||
std::cout << incr("9") << std::endl;
|
||||
std::cout << incr("10") << std::endl;
|
||||
std::cout << incr("15") << std::endl;
|
||||
std::cout << incr("19") << std::endl;
|
||||
std::cout << incr("99") << std::endl;
|
||||
std::cout << incr("9999999") << std::endl;
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
74
puzzles/training/subset_min_max_count.cpp
Normal file
74
puzzles/training/subset_min_max_count.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
*/
|
||||
#include "stdafx.h"
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
/*
|
||||
google-interview-questions
|
||||
For a given vector of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) <= K
|
||||
For example, for K = 8 and vector [2, 4, 5, 7], the solution is 5 ([2], [4], [2, 4], [2, 4, 5], [2, 5])
|
||||
The time complexity should be O(n2). Approach and code was asked
|
||||
*/
|
||||
|
||||
int countSubsets(std::vector<int> numbers, int k)
|
||||
{
|
||||
int total_sum = 0;
|
||||
for (int i = 0; i < numbers.size(); ++i) {
|
||||
|
||||
if (2 * numbers[i] > k) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int sum = 1;
|
||||
int max = numbers[i];
|
||||
int min = numbers[i];
|
||||
for (int j = i+1; j < numbers.size(); ++j) {
|
||||
int tmp_max = std::max(max, numbers[j]);
|
||||
int tmp_min = std::min(min, numbers[j]);
|
||||
|
||||
if (tmp_max + tmp_min <= k) {
|
||||
sum *= 2;
|
||||
min = tmp_min;
|
||||
max = tmp_max;
|
||||
}
|
||||
}
|
||||
total_sum += sum;
|
||||
}
|
||||
|
||||
return total_sum;
|
||||
}
|
||||
|
||||
int main()
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
std::cout << countSubsets({ 2, 4, 5, 7 }, 8) << std::endl;
|
||||
|
||||
|
||||
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
6
py/python_path.py
Normal file
6
py/python_path.py
Normal file
@@ -0,0 +1,6 @@
|
||||
#VIM: let b:lcppflags="-std=c++11 -O2 -pthread"
|
||||
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
print( "sys.path= {}".format(sys.path))
|
||||
@@ -1,10 +1,9 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}"
|
||||
VIM: let b:cf5run="{OUT}"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM-: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
|
||||
Reference in New Issue
Block a user