Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,27 @@ set(APP_SOURCES
"src/patterns/creational/AbstractFactory.cpp"
"src/patterns/creational/Builder.cpp"
"src/patterns/creational/Prototype.cpp"
## Streams
"src/core/filehandle/IOStream.cpp"
"src/core/filehandle/StringStream.cpp"
"src/core/filehandle/FileIO.cpp"
## Container
"src/core/datatypes/container/sequence/Array.cpp"
"src/core/datatypes/container/sequence/Vector.cpp"
"src/core/datatypes/container/unordered/UnorderedMap.cpp"
"src/core/expression/Lambda.cpp"
"src/core/expression/FunctionPointer.cpp"
"src/leetcode/arrays/two_sum/TwoSum.cpp"
"src/leetcode/arrays/median_two_arrays/MedianTwoSortedArrays.cpp"
# "src/leetcode/arrays/container_with_most_water/ContainerWithMostWater.cpp"
)

# Test files
set(APP_TESTS
"tests/DeleteMeTest.cpp"
"tests/two_sum_ut.cpp"
"tests/median_two_sorted_arrays_ut.cpp"
# "tests/container_with_most_water_ut.cpp"
)

# ----------------------------------------------------------------------------------------
Expand Down
113 changes: 113 additions & 0 deletions src/core/filehandle/FileIO.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
#include <fstream>
#include <iostream>

namespace {

constexpr inline std::string_view test_file_name = "fileio_test.csv";

void fileInput() {
std::ifstream inFile{std::string{test_file_name}};
if (!inFile.is_open()) {
std::cerr << "Cannot open file: " << test_file_name << " \n";
}

std::string inputStr{};
std::cout << "====skip while space content====" << std::endl;
while (
inFile >>
inputStr) { // Note that ifstream returns a 0 if we’ve reached the end of the file (EOF)
std::cout << inputStr;
}
std::cout << "========" << std::endl;
std::cout << "====full content====" << std::endl;

// not skip whitespace
inFile.close();
inFile.open(std::string{test_file_name}); // explicitly call open()
// The otherway to do this
/**
* inFile.clear(); // clear eof/fail flags
* inFile.seekg(0); // rewind
*/

inputStr.clear();
while (std::getline(inFile, inputStr)) {
std::cout << inputStr << std::endl;
}
std::cout << "========" << std::endl;

inFile.close();
}

void fileOutput() {
std::ofstream outfile{std::string{
test_file_name}}; // only output stream creates new file if not exist
if (!outfile || !outfile.is_open()) {
std::cerr << "Cannot open file: " << test_file_name << " \n";
return;
}

// Put bytes data to the file
// put string
std::string elfBytes{
R"""(
time_s,
gsr_value 0.0, 45.27761157741693 0.005, 41.69912812397066 0.01,
38.13110177547114 0.015, 35.32162785580394 0.02,
31.75617843363382 0.025, 28.352875321528607 0.03,
25.23210282654006 0.035, 21.769688905641132 0.04,
17.99031153059391 0.045, 15.073732055666543 0.05,
15.13550182371759 0.055, 14.69547985289048 0.06,
14.867397107985468 0.065, 14.982082556093832 0.07,
14.893751010484861 0.075, 14.877034044202343 0.08,
14.820590581790071 0.085, 15.1065350504897 0.09,
15.152287796727098 0.095, 14.764395300078201 0.1,
15.118189654760348 0.105, 15.473255351586635 0.11,
14.913896402347113
\n )"""};
outfile << elfBytes;

elfBytes =
"0x0 0x0"
"0x0 0x0"
"0x0 0x0";
outfile << elfBytes;

elfBytes =
"0xF 0xA \
0xE 0xB \
0x0 0x0";
outfile << elfBytes;

outfile.put('E'); // put char
outfile.close();
}

void fileRemove() {
std::remove(std::string{test_file_name}.c_str());
std::ifstream ifile{std::string{test_file_name}};
if (ifile) {
std::cerr << "Cannot delete file: " << test_file_name << " \n";
return;
}

std::cout << "Delete file: " << test_file_name << " \n";
}

void run() {
// Create and produce data to a file
fileOutput();

// Load the created file as input and display its content
fileInput();

// remove the file
fileRemove();
}
} // namespace

struct FileIO {
FileIO() { run(); }
};

static FileIO autoRunner;
35 changes: 35 additions & 0 deletions src/core/filehandle/IOStream.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <iostream>
#include <sstream>
#include <string>

namespace {
void run() {
std::cout << "\n--- IO Streams Example ---\n";
// 1) input stream

// input source using std::stringstream
std::string inputStr{};
std::stringstream input("input aa aa");

// save and redirect std::cin
auto* oldBuf = std::cin.rdbuf(input.rdbuf());

// input from keyboard,
// std::cin >> inputStr; // skip whitespace
std::getline(std::cin, inputStr); // get all

// have to restore std::cin
std::cin.rdbuf(oldBuf);

// 2) output stream
std::cout << "[cout] " << inputStr << '\n';
std::cerr << "[cerr] " << inputStr << '\n'; // unbuffered
std::clog << "[clog] " << inputStr << '\n'; // buffered
}
} // namespace

struct IOStreamRunner {
IOStreamRunner() { run(); }
};

static IOStreamRunner autoRunner;
41 changes: 41 additions & 0 deletions src/core/filehandle/StringStream.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <iostream>
#include <sstream>
#include <string>
namespace {
void run() {
std::cout << "\n--- String Stream Example ---\n";

std::stringstream os{};

// input
os << "0xF";
std::cout << os.str();

// Note: After changing .str(), always call .clear() before reading.
os.str("0x1 0x2");
os.clear();
std::cout << os.str();

// output
std::string bytesStr = os.str();
std::cout << bytesStr;

os.str("0x0 0xF 0xE 0x2");
os.clear();
os >> bytesStr;
std::cout << bytesStr;

// conversions
int byte_low = 0xFFF;
int byte_high = 0x001;
os.clear();
os << byte_low << ' ' << byte_high;
std::cout << os.str();
}
} // namespace

struct StringStreamRunner {
StringStreamRunner() { run(); }
};

static StringStreamRunner autoRunner;
37 changes: 37 additions & 0 deletions src/leetcode/arrays/median_two_arrays/MedianTwoSortedArrays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include "MedianTwoSortedArrays.h"
#include <algorithm>

/**
* Time Complexity: O((m+n) + (m+n)log(m+n)) ~ O((m+n)log(m+n))
* Space Complexity: O(n+m)
*/
double MedianTwoSortedArrays::findMedianSortedArrays(
const std::vector<int>& nums1, const std::vector<int>& nums2) {
std::vector<int> nums{};
nums.reserve(
nums1.size() +
nums2.size()); // should use reserve to pre-allocate the required mem

nums.insert(nums.end(), nums1.begin(),
nums1.end()); // insert: copy n + m => O(m+n)
nums.insert(nums.end(), nums2.begin(), nums2.end());

std::sort(nums.begin(), nums.end()); // sort: NLogN => (m+n)Log(m+n)

size_t size = nums.size();
if (size == 0) {
return -1;
}

if (size % 2 != 0) {
int index =
size /
2; // integer division truncates toward zero, so size / 2 gives the lower middle index
return nums.at(index);
} else {
int index1 = size / 2;
int index2 = size / 2 - 1;
int sum = nums.at(index1) + nums.at(index2);
return sum / 2.0;
}
}
32 changes: 32 additions & 0 deletions src/leetcode/arrays/median_two_arrays/MedianTwoSortedArrays.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

//cppcheck-suppress-file [functionStatic]
#pragma once
// Hard

// Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
// The overall run time complexity should be O(log (m+n)).

// Example 1:
// Input: nums1 = [1,3], nums2 = [2]
// Output: 2.00000
// Explanation: merged array = [1,2,3] and median is 2.

// Example 2:
// Input: nums1 = [1,2], nums2 = [3,4]
// Output: 2.50000
// Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

// Constraints:
// nums1.length == m
// nums2.length == n
// 0 <= m <= 1000
// 0 <= n <= 1000
// 1 <= m + n <= 2000
// -106 <= nums1[i], nums2[i] <= 106

#include <vector>
class MedianTwoSortedArrays {
public:
double findMedianSortedArrays(const std::vector<int>& nums1,
const std::vector<int>& nums2);
};
48 changes: 48 additions & 0 deletions src/leetcode/arrays/two_sum/TwoSum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include "TwoSum.h"

/**
* S1: Using for-loop-index
* Time complexity: O(n2)
* Space complexity: O(1)
*/
std::vector<int> Solution::twoSum(const std::vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
int diff = target - nums.at(i);
for (int j = i + 1; j < nums.size(); ++j) {
if (diff == nums.at(j)) {
return std::vector<int>{i, j};
}
}
}

// no solution
return std::vector<int>{-1, -1};
}

// #include <unordered_map>
// /**
// * 3 1 4
// * =====
// * 3 1 4
// * -----
// * 0 1 2
// * =====
// * Time complexity: O(n)
// * Space complexity: O(n)
// */
// std::vector<int> Solution::twoSum(const std::vector<int>& nums, int target) {
// std::unordered_map<int, int> numMap{};
// for (int i = 0; i < nums.size(); ++i) {
// int xkey = nums[i];
// int ykey = target - nums[i];
// if (numMap.find(ykey) != nullptr) {
// return std::vector<int>{numMap.at(ykey), i};
// }

// // save vector to map<key=num,value=index>
// numMap.insert(std::pair(xkey, i));
// }

// // no solution
// return std::vector<int>{-1, -1};
// }
34 changes: 34 additions & 0 deletions src/leetcode/arrays/two_sum/TwoSum.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//cppcheck-suppress-file [functionStatic]

// Given an array of integers nums and an integer target, return indices[ˈɪn.də.siːz] of the two numbers such that they add up to target.

// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.

// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]

// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]

// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.

// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity ?

#pragma once
#include <vector>
class Solution {
public:
std::vector<int> twoSum(const std::vector<int>& nums, int target);
};
Loading