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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9242f211e6ccc6774c15a7570a7adacec00e867c | C++ | yazyyyyy/Leetcode_Problems | /Array problems/threeSum.cpp | UTF-8 | 1,218 | 3.234375 | 3 | [] | no_license | //Problem link: https://leetcode.com/problems/3sum/
class Solution {
public:
vector<vector<int> > threeSum(vector<int>& nums) {
vector<vector<int> >ans;
sort(nums.begin(), nums.end());
for(int i=0; i<(int)nums.size()-2; i++){
if(i==0 || (i>0 && nums[i]!=nums[i-1])){
int target = 0 - nums[i];
int l = i + 1;
int r = (int)nums.size() - 1;
int lp,rp;
while(l<r){
lp = nums[l];
rp = nums[r];
if(lp + rp == target){
vector<int> tri;
tri.push_back(nums[i]);
tri.push_back(lp);
tri.push_back(rp);
ans.push_back(tri);
while(l<r && nums[l]==nums[l+1]) l++;
while(l<r && nums[r]==nums[r-1]) r--;
l++;
r--;
}else if(lp + rp < target){
l++;
}else{
r--;
}
}
}
}
return ans;
}
}; | true |
ee8c1f1384c5ee5183cf6218439ad9131cd78e00 | C++ | openbmc/openpower-occ-control | /test/occ_dbus_test.cpp | UTF-8 | 2,151 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include <occ_dbus.hpp>
#include <gtest/gtest.h>
using namespace open_power::occ::dbus;
TEST(OccDBusSensors, MaxValue)
{
std::string tmpPath = "/abc/def";
double maxValue = 100.00;
double retMaxValue = 0;
OccDBusSensors::getOccDBus().setMaxValue(tmpPath, maxValue);
retMaxValue = OccDBusSensors::getOccDBus().getMaxValue(tmpPath);
EXPECT_EQ(maxValue, retMaxValue);
ASSERT_THROW(OccDBusSensors::getOccDBus().getMaxValue("/abcd/"),
std::invalid_argument);
}
TEST(OccDBusSensors, MinValue)
{
std::string tmpPath = "/abc/def";
double minValue = 10.00;
double retMinValue = 0;
OccDBusSensors::getOccDBus().setMinValue(tmpPath, minValue);
retMinValue = OccDBusSensors::getOccDBus().getMinValue(tmpPath);
EXPECT_EQ(minValue, retMinValue);
ASSERT_THROW(OccDBusSensors::getOccDBus().getMinValue("/abcd/"),
std::invalid_argument);
}
TEST(OccDBusSensors, Value)
{
std::string tmpPath = "/abc/def";
double value = 30.00;
double retValue = 0;
OccDBusSensors::getOccDBus().setValue(tmpPath, value);
retValue = OccDBusSensors::getOccDBus().getValue(tmpPath);
EXPECT_EQ(value, retValue);
ASSERT_THROW(OccDBusSensors::getOccDBus().getValue("/abcd/"),
std::invalid_argument);
}
TEST(OccDBusSensors, Unit)
{
std::string tmpPath = "/abc/def";
const std::string unit = "xyz.openbmc_project.Sensor.Value.Unit.DegreesC";
std::string retUnit = "";
OccDBusSensors::getOccDBus().setUnit(tmpPath, unit);
retUnit = OccDBusSensors::getOccDBus().getUnit(tmpPath);
EXPECT_EQ(unit, retUnit);
ASSERT_THROW(OccDBusSensors::getOccDBus().getUnit("/abcd/"),
std::invalid_argument);
}
TEST(OccDBusSensors, OperationalStatus)
{
std::string tmpPath = "/abc/def";
bool retStatus = false;
OccDBusSensors::getOccDBus().setOperationalStatus(tmpPath, true);
retStatus = OccDBusSensors::getOccDBus().getOperationalStatus(tmpPath);
EXPECT_EQ(true, retStatus);
ASSERT_THROW(OccDBusSensors::getOccDBus().getOperationalStatus("/abcd/"),
std::invalid_argument);
}
| true |
16e6b843ee2cc52e9775fa716b862155e93a8c8f | C++ | LogicFan/Project-OpenCLe | /src/memory/global_ptr_base.cpp | UTF-8 | 1,206 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "global_ptr_base.hpp"
#include "global_ptr_impl.hpp"
namespace opencle
{
global_ptr_base::global_ptr_base(std::unique_ptr<global_ptr_impl> &&impl)
: impl_{std::move(impl)}
{
}
global_ptr_base::global_ptr_base(size_t size, bool read_only = false)
: impl_{std::make_unique<global_ptr_impl>(size, read_only)}
{
}
global_ptr_base::global_ptr_base(void *ptr, size_t size, Deleter deleter, bool read_only = false)
: impl_{std::make_unique<global_ptr_impl>(ptr, size, deleter, read_only)}
{
}
global_ptr_base::global_ptr_base(global_ptr_base &&rhs)
: impl_{std::move(rhs.impl_)}
{
}
global_ptr_base &global_ptr_base::operator=(global_ptr_base &&rhs)
{
impl_ = std::move(rhs.impl_);
}
void *global_ptr_base::impl_get()
{
return impl_->get();
}
void *global_ptr_base::impl_release()
{
return impl_->release();
}
global_ptr_base global_ptr_base::clone() const
{
return global_ptr_base{impl_->clone()};
}
bool global_ptr_base::impl_bool() const
{
return impl_->operator bool();
}
size_t global_ptr_base::impl_size() const
{
return impl_->size();
}
bool global_ptr_base::impl_is_allocated() const
{
return impl_->is_allocated();
}
} // namespace opencle | true |
6d3e58178d4eb88cb192f4ce4e599d8b493bac9e | C++ | AhmdNassar/problem-solving | /codeforces/Effective Approach.cpp | UTF-8 | 572 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
#define lo(n) for(int k = 0; k<n; k++)
#define ll long long int
#define ull unsigned long long int
int main()
{
int n, m, q, temp;
ll leftCnt = 0, rightCnt = 0;
cin>>n;
int numbers[n]{-1};
fill_n(numbers,n,-1);
lo(n)
{
cin>>temp;
numbers[temp] = k + 1;
}
cin>>m;
lo(m)
{
cin>>q;
leftCnt += numbers[q];
rightCnt += (n - numbers[q] + 1);
}
cout<<leftCnt<<" "<<rightCnt<<endl;
} | true |
630ba2e4bb3f2db4368f0ed5418036713ea7e33c | C++ | jumbagenii/CP-DSA-Cpp-C | /April_Leetcode_challenge/Problem1_SingleNumber.cpp | UTF-8 | 327 | 2.5625 | 3 | [] | no_license | class Solution {
public:
int singleNumber(vector<int>& nums) {
long int i,j,flag;
sort(nums.begin(),nums.end());
for(i=0;i<nums.size()-1;)
{
if(nums[i]==nums[i+1])
i+=2;
else
break;
}
return nums[i];
}
}; | true |
cd6c76521ec59018e4da881aa907c458ddc03d51 | C++ | mengdiwang/ROBDD | /nqueentest.cpp | UTF-8 | 638 | 2.578125 | 3 | [] | no_license | //
// main.cpp
// nqueentest
//
// Created by Mengdi Wang on 13-5-16.
// Copyright (c) 2013年 Mengdi Wang. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include "nqueen.h"
int main(int argc, const char * argv[])
{
int n = 8; /* board of size n*n */
Nqueen *nq = new Nqueen(n);
int r = nq->SolveQueen(); /* r = bdd representing n-queens constraints */
nq->PrintResults();
/*
printf("Final bdd size: %d nodes\n", nq->GetBdd()->Getsize());
nq->GetBdd()->AllSat(r); // print all solutions in compact form
printf("%d solutions\n", nq->GetBdd()->SatCount(r));
*/
return 0;
}
| true |
03de6d6c06e1c0b67990991914b51838520fbc6b | C++ | Evil-crow/platinum | /src/.1.0/src/http_response.cc | UTF-8 | 913 | 2.921875 | 3 | [
"MIT"
] | permissive | /*
* Created by Crow on 8/24/18.
* Description: the class http_response inherit from httpxx::ResponseBuilder
*/
#include <string>
#include <iostream>
#include "http_response.h"
bool PlatinumServer::http_response::set_header(std::string &&key, std::string &&val)
{
this->headers().insert(std::make_pair(std::move(key), std::move(val)));
return true;
}
bool PlatinumServer::http_response::build()
{
auto http_status_line = this->status_line();
auto http_headers = this->headers();
// build the http-response
this->server_response = http_status_line + "\r\n"; // The httpxx library has add "\r\n" (modify the code);
for (auto &i : http_headers)
this->server_response += i.first + ": " + i.second + "\r\n";
this->server_response += "\r\n";
return true;
}
const std::string &PlatinumServer::http_response::get_response()
{
return this->server_response;
} | true |
5120fe410c554ccd643423c3f482915ced497e1f | C++ | zachlambert/platform | /sceneManager.cpp | UTF-8 | 419 | 2.703125 | 3 | [] | no_license |
#include "scene.h"
#include <memory>
#include <string>
class SceneData{
public:
SceneData(){}
private:
std::string name;
std::unique_ptr<Scene> scene;
};
class SceneManager: public sf::Drawable{
public:
SceneManager(){}
virtual void handleEvent(sf::Event){}
virtual void update(float);
virtual void draw(sf::RenderTarget& target,sf::RenderStates states)const;
private:
std::vector<SceneData> scenes;
}; | true |
87d862b55e81872701ac629f34692e2b899b6698 | C++ | jankroken/aoc2018 | /day4/cpp/accumulators.cpp | UTF-8 | 1,322 | 2.953125 | 3 | [] | no_license | #include "accumulators.h"
#include <set>
#include <list>
#include "sleeprecords.h"
using namespace std;
map<int,int> minutesAsleepByGuard(list<SleepRecord> records) {
map<int, int> result{};
for (auto rec: records) {
auto it = result.find(rec.guardId);
if (it != result.end()) {
int newValue = it->second + rec.minutes();
result.erase(it);
result[rec.guardId] = newValue;
} else {
result[rec.guardId] = rec.minutes();
}
}
return result;
}
pair<int,int> largestValue(map<int,int> valueMap) {
pair<int,int> result = pair(-1,-1);
for (auto entry: valueMap) {
if (entry.second > result.second) {
result = entry;
}
}
return result;
}
map<int,int> timesPerMinute(list<SleepRecord> records) {
map<int,int> result;
for(auto record: records) {
for (int min = record.start; min < record.end; min++) {
auto it = result.find(min);
if (it != result.end()) {
it->second += 1;
} else {
result[min] = 1;
}
}
}
return result;
}
list<int> keys(map<int,int> m) {
list<int> result{};
for (auto entry: m) {
result.push_back(entry.first);
}
return result;
}
| true |
1dab350f4ee1cabbfb28bf809c3ff7b09b1cf07b | C++ | jmhong-simulation/LithopiaOpen | /Engine/Geometry/StaticTriangle.h | UTF-8 | 3,004 | 2.84375 | 3 | [
"MIT"
] | permissive | // The Lithopia project initiated by Jeong-Mo Hong for 3D Printing Community.
// Copyright (c) 2015 Jeong-Mo Hong - All Rights Reserved.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
#pragma once
#include "GENERIC_DEFINITIONS.h"
#include "DataStructure/LinkedArray.h"
#include "DataStructure/DynamicArray.h"
#include "DataStructure/Vector3D.h"
class StaticTriangle
{
public:
TV v0_, v1_, v2_;
public:
StaticTriangle()
{}
StaticTriangle(const TV& _v0, const TV& _v1, const TV& _v2)
: v0_(_v0), v1_(_v1), v2_(_v2)
{}
TV getClosestPointFromLine(const TV& location, const TV& x1, const TV& x2) const;
TV getBarycentricCoordinates(const TV& location, const TV& x1, const TV& x2, const TV& x3) const;
TV getClosestPosition(const TV& location) const;
T getDistance(const TV& location) const;
T getArea() const;
T getAspectRatio() const;
TV getNormal() const {
return crossProduct(v1_ - v0_, v2_ - v0_).normalized();
}
bool checkOnTriangle(const TV& p, const float rad) {
TV3 cen = (v0_ + v1_ + v2_) / 3.0f;
TV3 n = crossProduct(v1_ - v0_, v2_ - v0_).normalized();
float h = dotProduct(n, p - v0_);
TV3 n0 = crossProduct(n, (v1_ - v0_).normalized()).normalized();
if (dotProduct(v0_ - cen, n0) < 0.0f) {
n0 *= -1.0f;
}
TV3 n1 = crossProduct(n, (v2_ - v1_).normalized()).normalized();
if (dotProduct(v1_ - cen, n1) < 0.0f) {
n1 *= -1.0f;
}
TV3 n2 = crossProduct(n, (v0_ - v2_).normalized()).normalized();
if (dotProduct(v2_ - cen, n2) < 0.0f) {
n2 *= -1.0f;
}
float d0 = dotProduct(n0, p - v0_);
float d1 = dotProduct(n1, p - v1_);
float d2 = dotProduct(n2, p - v2_);
if (d0 <= 1e-04 && d1 <= 1e-04 && d2 <= 1e-04) {
if (h >= -rad && h <= rad) {
return true;
}
}
return false;
}
void getXMinMax(T& x_min, T& x_max) const;
void getYMinMax(T& y_min, T& y_max) const;
void getZMinMax(T& z_min, T& z_max) const;
template<class EE> const EE Interpolate(const TV& q, const TV& p0, const TV& p1, const EE& v0, const EE& v1) const {
float dot = dotProduct(q - p0, p1 - p0) / dotProduct(p1 - p0, p1 - p0);
dot = CLAMP(dot, 0.0f, 1.0f);
return v0*(1.0f-dot) + v1*dot;
}
template<class EE> const EE Interpolate(const TV& p, const EE arr[3]) const {
float dot = dotProduct(p - v0_, v1_ - v0_) / (dotProduct(v1_ - v0_, v1_ - v0_));
dot = CLAMP(dot, 0.0f, 1.0f);
TV v00 = v0_ + (v1_ - v0_) * dot;
EE e00 = arr[0] * (1.0f - dot) + arr[1] * dot;
dot = dotProduct(p - v0_, v2_ - v0_) / (dotProduct(v2_ - v0_, v2_ - v0_));
dot = CLAMP(dot, 0.0f, 1.0f);
TV v11 = v0_ + (v2_ - v0_) * dot;
EE e11 = arr[0] * (1.0f - dot) + arr[2] * dot;
dot = dotProduct(p - v00, v11 - v00) / dotProduct(v11 - v00, v11 - v00);
dot = CLAMP(dot, 0.0f, 1.0f);
EE result = e00*(1.0f - dot) + e11*dot;
return result;
}
}; | true |
f4bc8ad26ee33bf4a563403f1ee530c16da2b710 | C++ | sebsprojects/CPHemeral | /rendering/src/opengl/ShaderProgram.h | UTF-8 | 830 | 2.59375 | 3 | [] | no_license | #ifndef SHADER_PROGRAM_H_
#define SHADER_PROGRAM_H_
#include <string>
#include <set>
#include "AttributeFormat.h"
namespace cph {
class ShaderProgram {
private:
GLuint vertHandle, fragHandle, programHandle;
bool initialized, linked;
std::set<AttributeFormat> attribFormat;
std::string shaderId, vertSource, fragSource;
void processVertexShader();
void compileShaderGL();
void attachShaderGL();
void linkShaderGL();
void checkCompilationGL(int handle);
void checkLinkageGL();
public:
ShaderProgram(std::string shaderPath);
ShaderProgram(const ShaderProgram& other);
~ShaderProgram();
std::string getShaderId() const;
GLuint getProgramHandle() const;
const std::set<AttributeFormat>& getAttritbuteFormat() const;
bool isLinked() const;
void bindGL();
void unbindGL();
void destroyGL();
};
}
#endif | true |
972d49ab180f7f97c30f19f0bd9fab4bbf27b580 | C++ | taetinn/Algo_BOJ | /ssibal/ssibal/boj16430.cpp | UTF-8 | 195 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
int a, b, tmp=0;
cin >> a >> b;
tmp = b - a;
cout << tmp << ' ' << b << '\n';
return 0;
} | true |
3ff2be727a3486cefc6a2863c8355bab3e09803c | C++ | 2719896135/- | /NOIP-master/2008/drawing/drawing.cpp | UTF-8 | 2,410 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <memory.h>
#include <string.h>
const char* block[] = {"+---+",
"/ /|",
"+---+ |",
"| | +",
"| |/",
"+---+"};
#define MAX_WIDTH 50
#define MAX_DEPTH 50
#define MAX_HEIGHT 100
char canvas[3*MAX_HEIGHT + 2*MAX_DEPTH +1][4*MAX_WIDTH + 1 + 2 * MAX_DEPTH];
void DrawBlock (int x, int y);
void Print (int x, int y, int width, int height);
void DrawLayer (int layer, int depth, int width, int x, int y);
int map [MAX_DEPTH][MAX_WIDTH];
void ReadInMap (int depth, int width);
int max_x = 0;
int min_y = 3*MAX_HEIGHT + 2*MAX_DEPTH;
int layers = 0;
#define MAX(a,b) ((a)>=(b) ? (a) : (b))
#define MIN(a,b) ((a)<=(b) ? (a) : (b))
int main ()
{
int depth, width;
scanf ("%d", &depth);
scanf ("%d", &width);
ReadInMap (depth, width);
memset (canvas, '.', sizeof (canvas));
int orgx = 0;
int orgy = 3*MAX_HEIGHT + 2*MAX_DEPTH;
for (int i = 0; i < layers; i++) {
DrawLayer (i, depth, width, orgx, orgy - 3 * i);
}
Print (orgx, orgy, max_x+1, (3*MAX_HEIGHT + 2*MAX_DEPTH +1 - min_y));
return 0;
}
void DrawBlock (int x, int y)
{
memcpy (&canvas[y-5][x+2], block[0], strlen(block[0]));
memcpy (&canvas[y-4][x+1], block[1], strlen(block[1]));
memcpy (&canvas[y-3][x], block[2], strlen(block[2]));
memcpy (&canvas[y-2][x], block[3], strlen(block[3]));
memcpy (&canvas[y-1][x], block[4], strlen(block[4]));
memcpy (&canvas[y][x], block[5], strlen(block[5]));
}
void Print (int x, int y, int width, int height)
{
for (int i = y-height + 1; i <= y; i++) {
for (int j = x; j < x+width; j++) {
printf ("%c", canvas[i][j]);
}
printf ("\n");
}
}
void ReadInMap (int depth, int width)
{
for (int i = 0; i < depth; i ++) {
for (int j = 0; j < width; j++) {
scanf ("%d", &map[i][j]);
layers = MAX (layers, map[i][j]);
}
}
}
void DrawLayer (int layer, int depth, int width, int x, int y)
{
int x0 = x + 2 * depth;
int y0 = y - 2 * depth;
for (int i = 0; i < depth; i ++) {
y0 += 2;
x0 -= 2;
int x1 = x0;
for (int j = 0; j < width; j++) {
if (map[i][j] > layer) {
DrawBlock (x1, y0);
max_x = MAX(max_x, x1+6);
min_y = MIN(min_y, y0-5);
}
x1 +=4;
}
}
} | true |
5b1aae430d5f2bd7c93b14d82eca0cdeddb82617 | C++ | ORNL-Fusion/xolotl | /xolotl/util/include/xolotl/util/Log.h | UTF-8 | 2,005 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include <iomanip>
#include <sstream>
#include <boost/log/attributes/named_scope.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_logger.hpp>
namespace xolotl
{
namespace util
{
/**
* @brief Serves as namespace for log-related functions as well as lazy
* singleton for initializing logging
*/
class Log
{
public:
/**
* Severity levels for log messages
*/
enum Level
{
debug = 0,
extra,
info,
warning,
error
};
/**
* Alias for severity logger type
*/
using LoggerType = boost::log::sources::severity_logger<Level>;
Log();
/**
* @brief Set logging output threshold level
*/
static void
setLevelThreshold(Level level);
/**
* @brief Set logging output threshold level
*/
static void
setLevelThreshold(const std::string& levelString);
/**
* @brief Get a severity logger
*/
static LoggerType&
getLogger();
/**
* @brief Flush the logging core
*/
static void
flush();
private:
static Level _threshold;
friend void
setupLogs();
};
/**
* @relates Log
* @brief Insert a Log::Level into a stream
*/
std::ostream&
operator<<(std::ostream& os, Log::Level level);
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(Logger, Log::LoggerType);
/**
* @brief Customize a std::stringstream with a precision for floats
*/
class StringStream : public std::stringstream
{
public:
explicit StringStream(std::streamsize prec = 16)
{
this->precision(prec);
}
};
} // namespace util
} // namespace xolotl
#define XOLOTL_LOG_SEV(level) \
BOOST_LOG_SEV(::xolotl::util::Log::getLogger(), level) \
<< std::setprecision(16)
#define XOLOTL_LOG XOLOTL_LOG_SEV(::xolotl::util::Log::info)
#define XOLOTL_LOG_DBG XOLOTL_LOG_SEV(::xolotl::util::Log::debug)
#define XOLOTL_LOG_XTRA XOLOTL_LOG_SEV(::xolotl::util::Log::extra)
#define XOLOTL_LOG_WARN XOLOTL_LOG_SEV(::xolotl::util::Log::warning)
#define XOLOTL_LOG_ERR XOLOTL_LOG_SEV(::xolotl::util::Log::error)
| true |
8ff46b6dd3efff81179366d1b93ee9ff356d28cc | C++ | misiekc/rsa3d | /rsa3d/shape/shapes/polydisk/Fibrinogen.cpp | UTF-8 | 2,356 | 3.09375 | 3 | [] | no_license | //
// Created by pkua on 04.09.2019.
//
#include <sstream>
#include "Fibrinogen.h"
/**
* @brief Initializes Polydisk class so it represents linear fibrinogen particle, consisting in medium disk connected
* with 2 large disks at the ends by chains of small disks.
* @param attr parameters in format: (radius of large disks) (radius of a medium disk) (radius of small disks)
* (number of small disks in one chain)
*/
void Fibrinogen::initClass(const std::string &attr) {
std::istringstream attrStream;
if (attr.empty())
attrStream = std::istringstream("6.7 5.3 1.5 10");
else
attrStream = std::istringstream(attr);
double largeDiskRadius{}, mediumDiskRadius{}, smallDiskRadius{};
std::size_t numberOfSmallDisks{};
attrStream >> largeDiskRadius >> mediumDiskRadius >> smallDiskRadius >> numberOfSmallDisks;
ValidateMsg(attrStream, "Wrong format, expecting: (radius of large disks) (radius of a medium disk) "
"(radius of small disks) (radius of small disks in one chain)");
Validate(largeDiskRadius > 0);
Validate(mediumDiskRadius > 0);
Validate(smallDiskRadius > 0);
Validate(numberOfSmallDisks > 0);
/* Polydisk attr format: number_of_disks [xy|rt] c01 c02 r0 c11 c12 r1 c21 c22 r2 ... area */
std::ostringstream polydiskAttrStream;
std::size_t numberOfDisks = 3 + 2*numberOfSmallDisks;
polydiskAttrStream << numberOfDisks << " xy 0 0 " << mediumDiskRadius;
double lastCircleDisplacement = mediumDiskRadius;
for (std::size_t i = 0; i < numberOfSmallDisks; i++) {
lastCircleDisplacement += smallDiskRadius;
polydiskAttrStream << " " << lastCircleDisplacement << " 0 " << smallDiskRadius;
polydiskAttrStream << " -" << lastCircleDisplacement << " 0 " << smallDiskRadius;
lastCircleDisplacement += smallDiskRadius;
}
lastCircleDisplacement += largeDiskRadius;
polydiskAttrStream << " " << lastCircleDisplacement << " 0 " << largeDiskRadius;
polydiskAttrStream << " -" << lastCircleDisplacement << " 0 " << largeDiskRadius;
double area = M_PI * (2*std::pow(largeDiskRadius, 2) + std::pow(mediumDiskRadius, 2)
+ 2*numberOfSmallDisks * std::pow(smallDiskRadius, 2));
polydiskAttrStream << " " << area;
Polydisk::initClass(polydiskAttrStream.str());
}
| true |
381c29b5b4970e251abbcdb62cb8daf618f7b66a | C++ | djabraham/cordova-ionic-bean | /docs/sketches/BeanSDK/3.LowPower/EnableWakeOnConnection/EnableWakeOnConnection.ino | UTF-8 | 773 | 3.4375 | 3 | [
"MIT"
] | permissive | /*
This sketch shows how to use the enableWakeOnConnect() function.
In this example the LED is turned on when the Bean is awake.
To save power the Bean will be put to sleep when it's not connected to another device,
and woken up when it's connected to by using enableWakeOnConnect().
This example code is in the public domain.
*/
bool connected;
void setup()
{
// Turn off the LED
Bean.setLed(0, 0, 0);
Bean.enableWakeOnConnect(true);
}
void loop()
{
connected = Bean.getConnectionState();
if(connected)
{
// Turn the LED green
Bean.setLed(0, 255, 0);
Bean.sleep(1000);
}else{
// Turn off the LED
Bean.setLed(0, 0, 0);
// Sleep forever or until the Bean wakes up by being connected to
Bean.sleep(0xFFFFFFFF);
}
}
| true |
e9376452811862222212ec2250bfbe99b0a4d570 | C++ | twxjyg/CarND-Extended-Kalman-Filter-Project | /src/tools.h | UTF-8 | 1,917 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef TOOLS_H_
#define TOOLS_H_
#include <vector>
#include "Eigen/Dense"
class Tools {
public:
/**
* A helper method to calculate RMSE.
*/
static Eigen::VectorXd CalculateRMSE(const std::vector<Eigen::VectorXd>& estimations,
const std::vector<Eigen::VectorXd>& ground_truth);
/**
* A helper method to calculate Jacobians.
*/
static Eigen::MatrixXd CalculateJacobian(const Eigen::VectorXd& x_state);
/**
* A helper method to calcute linear measurement matrix
*/
static Eigen::MatrixXd CalculateLinearMeasurementMatrix();
/**
* A helper methond to calculate linear State Transform Matrix
*/
static Eigen::MatrixXd CalculateLinearStateTransform(const double& det_t);
/**
* A helper method to calculate process noise Matrix
*/
static Eigen::MatrixXd CalculateProcessNoise(const double& det_t, const double& noise_ax, const double& noise_ay);
/**
* A helper method to calculate motion noise Vector
*/
static Eigen::VectorXd CalculateMotionNoise(const double& det_t, const double& noise_ax, const double& noise_ay);
/**
* A helper method to transform radar measurment to EKF state vector
*/
static Eigen::VectorXd TransformRadarMeasurementToState(const Eigen::VectorXd& radar_measurement);
/**
* A helper method to transform laser measurement to EKF state vector
*/
static Eigen::VectorXd TransformLaserMeasurementToState(const Eigen::VectorXd& laser_measurement);
/**
* A helper method to transform state vector to radar measurement space
*/
static Eigen::VectorXd TransformStateToRadarMeasurement(const Eigen::VectorXd& state);
/**
* A helper method to transform state vector to laser measurement space
*/
static Eigen::VectorXd TransformStateToLaserMeasurement(const Eigen::VectorXd& state);
static double NormalizeAngle(const double& phi);
};
#endif // TOOLS_H_
| true |
c2f23bf11f11810862ad04d780801028f5bf11df | C++ | anjinhyuk/Algorithms | /Priority.cpp | UTF-8 | 3,166 | 2.984375 | 3 | [] | no_license | #include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <array>
#include<cmath>
#include <math.h>
#include<conio.h>
#include<limits>
using namespace std;
vector<int> A;
int numLines;
int heapSize;
//left heap
int Left(int i){
return 2*(i);
};
//right heap
int Right(int i){
return (2*i)+ 1;
};
//parent
int Parent(int i){
return i/2;
};
//HEAP-MAXIMUM(A)
int HEAPMAXIMUM(){
return A[1];
}
//MAXHEAPIFY
void MAXHEAPIFY(int i){
int l = Left(i);
int r = Right(i);
int largest;
if (l <= heapSize && A[l] > A[i]){
largest = l;
}
else {
largest = i;
}
if (r <= numLines && A[r] > A[largest]){
largest = r;
}
if (largest != i){
swap(A[i], A[largest]);
MAXHEAPIFY(largest);
}
}
//HEAP-EXTRACT-MAX(A)
int HEAPEXTRACTMAX(){
if (heapSize < 1){
cerr << "heap underflow" << endl;
}
int max;
max = A[1];
A[1] = A[heapSize];
heapSize = heapSize - 1;
MAXHEAPIFY(1);
return max;
}
//HEAP-INCREASE-KEY(A,i, key)
void HEAPINCREASEKEY(int i, int key){
if (key < A[i]){
cerr << " new key is smaller than current key" << endl;
}
A[i] = key;
while ( i > 1 && A[Parent(i)] < A[i]){
swap (A[i], A[Parent(i)]);
i = Parent(i);
}
}
//MAX-HEAP-INSERT(A, key)
void MAXHEAPINSERT(int key){
heapSize = heapSize + 1;
A.resize(heapSize+1);
A[heapSize] = -std::numeric_limits<int>::infinity();
HEAPINCREASEKEY(heapSize, key);
}
int _tmain(int argc, _TCHAR* argv[])
{
ifstream ifs;
//roster file exception handling
if (argc < 2) {
cout << "missing command line parameter!" << endl;
exit(1);
}
ifs.open(argv[1], ios::in);
if (!ifs) {
cout << "file not found. How sad." << endl;
exit(1);
}
//instantiate the string tmp
string tmp;
//read in lines from the input file
getline(ifs, tmp);
//typecast the string tmp to integer
int numLines = stoi(tmp);
//printing out what is stored in n
cout << "I need to read " << numLines << " lines." << endl;
//////////////////////////////////////OK
//reading in input file as a string stream
for (int i=0; i< numLines; i++) {
//instantiate the string cmd for command variable
string cmd;
//reading in the file and store it to tmp
getline(ifs, tmp);
//store tmp to ss stringstream
stringstream ss(tmp);
ss >> cmd;
//cout << tmp << endl;
////////// ENQUEUE
if (cmd == "ENQUEUE"){
int key;
ss >> key;
MAXHEAPINSERT(key);
//cout << "enqueue" << key << endl;
}
///////// DEQUEUE
else if (cmd == "DEQUEUE"){
if(heapSize < 1){
cout << "empty"<<endl;
}else{
int k = HEAPEXTRACTMAX();
cout << k << endl;
}
}
////////// PEEK
else if( cmd == "PEEK"){
cout << HEAPMAXIMUM() << endl;
}
////////// CLEAR
else if(cmd == "CLEAR")
heapSize = 0;
}
return 0;
} | true |
083359623d175ea24edcd7af4bedeac2d26168cb | C++ | MotionPlanning-YC/ramp | /trajectory_generator/include/trajectory_generator_fixtureTest.h | UTF-8 | 2,289 | 2.609375 | 3 | [] | no_license | /*
* File: trajectory_generator_fixtureTest.h
* Author: Annaliese Andrews, PhD
* Author: Mahmoud Abdelgawad, PhD Candidate
* University of Denver
* Computer Science
* Created on December 9, 2015, 1:24 PM
*/
#ifndef TRAJECTORY_GENERATOR_FIXTURETEST_H
#define TRAJECTORY_GENERATOR_FIXTURETEST_H
// include google test library
#include <gtest/gtest.h>
// include main file of the server process (trajectory generator) as header file.
#include "main_testing.h"
// include messages that needed for client process (planner).
/*#include "ramp_msgs/Path.h"
#include "ramp_msgs/KnotPoint.h"
#include "ramp_msgs/MotionState.h"
#include "ramp_msgs/BezierCurve.h"*/
#include "utility.h"
class trajectoryGeneratorFixtureTest:public ::testing::Test{
public:
// Constructor & Destructor.
trajectoryGeneratorFixtureTest();
virtual ~trajectoryGeneratorFixtureTest();
// Setup & TearDowm.
virtual void SetUp();
virtual void TearDown();
//Callback method that calls the callback function of the server process (trajectory generator).
bool Callback(ramp_msgs::TrajectorySrv::Request& req, ramp_msgs::TrajectorySrv::Response& res);
// Data Members.
ros::NodeHandle client_handle, server_handle;
ros::ServiceClient _client;
ros::ServiceServer _service;
// Argument for Trajectory Request.
ramp_msgs::TrajectorySrv _trajectorySrv;
};
// Constructor: Initialize start and final points
trajectoryGeneratorFixtureTest::trajectoryGeneratorFixtureTest(){}
trajectoryGeneratorFixtureTest::~trajectoryGeneratorFixtureTest(){}
void trajectoryGeneratorFixtureTest::SetUp(){
// Initialize client and server processes.
_client = client_handle.serviceClient<ramp_msgs::TrajectorySrv>("/trajectory_generator");
_service = server_handle.advertiseService("/trajectory_generator", &trajectoryGeneratorFixtureTest::Callback,this);
}
void trajectoryGeneratorFixtureTest::TearDown(){}
bool trajectoryGeneratorFixtureTest::Callback(ramp_msgs::TrajectorySrv::Request& req, ramp_msgs::TrajectorySrv::Response& res){
if(requestCallback(req,res)){
return true;
}else{
return false;
}
}
#endif /* TRAJECTORY_GENERATOR_FIXTURETEST_H */
| true |
777e0ff55fc05a3d3d3e9aa84dc43190893e53a7 | C++ | AntonioHernandez28/InterviewUltimateGuide | /Intervals/Intervals.cpp | UTF-8 | 992 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
vector<vector<int>> MergeLists(vector<vector<int>> A, vector<vector<int>> B){
int s = INT_MIN, e = INT_MIN, i = 0, j = 0;
vector<vector<int>> res;
while(i < A.size() || j < B.size()){
vector<int> curr(2,-1);
if(i >= A.size()) curr = B[j++];
else if(j >= B.size()) curr = A[i++];
else curr = A[i][0] < B[j][0] ? A[i++] : B[j++];
if(curr[0] > e){
if(e > INT_MIN) res.push_back({s,e});
s = curr[0];
e = curr[1];
}
else e = max(curr[1], e);
}
if(e > INT_MIN) res.push_back({s,e});
return res;
}
int main(){
vector<vector<int>> A {{1,3}, {4,5}, {7,10}, {16,17}};
vector<vector<int>> B {{2,3}, {4,8}, {11,15}};
//Output {[1,3], [4, 10], [11, 15], [16, 17]}
vector<vector<int>> v = MergeLists(A,B);
for(auto x:v){
for(auto y:x) cout << y << " ";
cout << endl;
}
} | true |
d554d00f7f22a46a1eac6db3957b831db51ad99a | C++ | alinabi/NRE | /nre/apps/vancouver/bus/bus.h | UTF-8 | 3,908 | 2.75 | 3 | [] | no_license | /** @file
* Bus infrastucture and generic Device class.
*
* Copyright (C) 2007-2009, Bernhard Kauer <bk@vmmon.org>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of Vancouver.
*
* Vancouver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Vancouver is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
#pragma once
#include <stream/Serial.h>
#include <cstring>
/**
* The generic Device used in generic bus transactions.
*/
class Device {
const char *_debug_name;
public:
void debug_dump() {
nre::Serial::get().writef("\t%s\n", _debug_name);
}
Device(const char *debug_name) : _debug_name(debug_name) {
}
};
/**
* This template converts from static receive to member functions.
*/
template<typename Y>
class StaticReceiver : public Device {
public:
template<class M>
static bool receive_static(Device *o, M& msg) {
return static_cast<Y*>(o)->receive(msg);
}
StaticReceiver() : Device(__PRETTY_FUNCTION__) {
}
};
/**
* A bus is a way to connect devices.
*/
template<class M>
class DBus {
typedef bool (*ReceiveFunction)(Device *, M&);
struct Entry {
Device *_dev;
ReceiveFunction _func;
};
unsigned long _debug_counter;
size_t _list_count;
size_t _list_size;
struct Entry *_list;
/**
* To avoid bugs we disallow the copy constuctor.
*/
DBus(const DBus<M> &bus);
DBus& operator=(const DBus<M> &bus);
void set_size(size_t new_size) {
Entry *n = new Entry[new_size];
if(_list) {
memcpy(n, _list, _list_count * sizeof(*_list));
delete[] _list;
}
_list = n;
_list_size = new_size;
}
public:
void add(Device *dev, ReceiveFunction func) {
if(_list_count >= _list_size)
set_size(_list_size > 0 ? _list_size * 2 : 1);
_list[_list_count]._dev = dev;
_list[_list_count]._func = func;
_list_count++;
}
/**
* Send message LIFO.
*/
bool send(M &msg, bool earlyout = false) {
_debug_counter++;
bool res = false;
for(size_t i = _list_count; i-- && !(earlyout && res); )
res |= _list[i]._func(_list[i]._dev, msg);
return res;
}
/**
* Send message in FIFO order
*/
bool send_fifo(M &msg) {
_debug_counter++;
bool res = false;
for(size_t i = 0; i < _list_count; i++)
res |= _list[i]._func(_list[i]._dev, msg);
return 0;
}
/**
* Send message first hit round robin and return the number of the
* next one that accepted the message.
*/
bool send_rr(M &msg, unsigned &start) {
_debug_counter++;
for(size_t i = 0; i < _list_count; i++) {
if(_list[i]._func(_list[(i + start) % _list_count]._dev, msg)) {
start = (i + start + 1) % _list_count;
return true;
}
}
return false;
}
/**
* Return the number of entries in the list.
*/
size_t count() {
return _list_count;
}
/**
* Debugging output.
*/
void debug_dump() {
nre::Serial::get().writef("%s: Bus used %ld times.", __PRETTY_FUNCTION__, _debug_counter);
for(size_t i = 0; i < _list_count; i++) {
nre::Serial::get().writef("\n%2d:\t", i);
_list[i]._dev->debug_dump();
}
nre::Serial::get().writef("\n");
}
/** Default constructor. */
DBus() : _debug_counter(), _list_count(), _list_size(), _list() {
}
};
| true |
8e24092172eb4321aed89910e2e6d360cc3d91a7 | C++ | ORNL-CEES/DataTransferKit | /packages/Utils/src/DTK_DBC.hpp | UTF-8 | 7,297 | 2.515625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | /****************************************************************************
* Copyright (c) 2012-2020 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
/*!
* \file DTK_DBC.hpp
* \author Stuart Slattery
* \brief Assertions and Design-by-Contract for error handling.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_DBC_HPP
#define DTK_DBC_HPP
#include <stdexcept>
#include <string>
#include <DTK_ConfigDefs.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
* \brief Base class for DTK assertions. This structure is heavily based on
* that in Nemesis developed by Tom Evans. We derive from std::logic_error
* here as the DBC checks that utilize this class are meant to find errors
* that can be prevented before runtime.
*/
//---------------------------------------------------------------------------//
class DataTransferKitException : public std::logic_error
{
public:
/*!
* \brief Default constructor.
*
* \param msg Error message.
*/
DataTransferKitException( const std::string &msg )
: std::logic_error( msg )
{ /* ... */
}
/*!
* \brief DBC constructor.
*
* \param cond A string containing the assertion condition that failed.
*
* \param file A string containing the file name in which the assertion
* failed.
*
* \param line The line number at which the assertion failed.
*/
DataTransferKitException( const std::string &cond, const std::string &file,
const int line )
: std::logic_error( generate_output( cond, file, line ) )
{ /* ... */
}
//! Destructor.
virtual ~DataTransferKitException() throw()
{ /* ... */
}
private:
// Build an assertion output from advanced constructor arguments.
std::string generate_output( const std::string &cond,
const std::string &file,
const int line ) const;
};
//---------------------------------------------------------------------------//
/*!
* \brief Not implemented exception.
*/
//---------------------------------------------------------------------------//
class DataTransferKitNotImplementedException : public DataTransferKitException
{
public:
DataTransferKitNotImplementedException()
: DataTransferKitException( "Not implemented" )
{
}
};
//---------------------------------------------------------------------------//
// Throw functions.
//---------------------------------------------------------------------------//
// Throw a DataTransferKit::DataTransferKitException.
void throwDataTransferKitException( const std::string &cond,
const std::string &file, const int line );
// Throw an assertion based on an error code failure.
void errorCodeFailure( const std::string &cond, const std::string &file,
const int line, const int error_code );
// Throw an assertion based on a missing user function.
void missingUserFunction( const std::string &cond );
//---------------------------------------------------------------------------//
} // namespace DataTransferKit
//---------------------------------------------------------------------------//
// Design-by-Contract macros.
//---------------------------------------------------------------------------//
/*!
\page DataTransferKit Design-by-Contract.
Design-by-Contract (DBC) functionality is provided to verify function
preconditions, postconditions, and invariants. These checks are separated
from the debug build and can be activated for both release and debug
builds. They can be activated by setting the following in a CMake
configure:
-D DataTransferKit_ENABLE_DBC:BOOL=ON
By default, DBC is deactivated. Although they will require additional
computational overhead, these checks provide a mechanism for verifying
library input arguments. Note that the bounds-checking functionality used
within the DataTransferKit is only provided by a debug build.
In addition, DTK_REMEMBER is provided to store values used only for DBC
checks and no other place in executed code.
Separate from the DBC build, DTK_INSIST can be used at any time verify a
conditional. This should be used instead of the standard cassert.
DTK_CHECK_ERROR_CODE provides DBC support for libraries that return error
codes with 0 as the value for no errors.
*/
#if HAVE_DTK_DBC
#define DTK_REQUIRE( c ) \
if ( !( c ) ) \
DataTransferKit::throwDataTransferKitException( #c, __FILE__, __LINE__ )
#define DTK_ENSURE( c ) \
if ( !( c ) ) \
DataTransferKit::throwDataTransferKitException( #c, __FILE__, __LINE__ )
#define DTK_CHECK( c ) \
if ( !( c ) ) \
DataTransferKit::throwDataTransferKitException( #c, __FILE__, __LINE__ )
#define DTK_REMEMBER( c ) c
#define DTK_CHECK_ERROR_CODE( c ) \
do \
{ \
int ec = c; \
if ( 0 != ec ) \
DataTransferKit::errorCodeFailure( #c, __FILE__, __LINE__, ec ); \
} while ( 0 )
#else
#define DTK_REQUIRE( c )
#define DTK_ENSURE( c )
#define DTK_CHECK( c )
#define DTK_REMEMBER( c )
#define DTK_CHECK_ERROR_CODE( c ) c
#endif
#define DTK_INSIST( c ) \
if ( !( c ) ) \
DataTransferKit::throwDataTransferKitException( #c, __FILE__, __LINE__ )
#define DTK_CHECK_USER_FUNCTION( c ) \
if ( !( c ) ) \
DataTransferKit::missingUserFunction( #c )
//---------------------------------------------------------------------------//
#endif // end DTK_DBC_HPP
//---------------------------------------------------------------------------//
// end DTK_DBC.hpp
//---------------------------------------------------------------------------//
| true |
19b08f861ef3117442e4e75029473d875c8cf2ff | C++ | jk983294/Explore | /lsp/process/schedule/setscheduler.cpp | UTF-8 | 993 | 2.984375 | 3 | [] | no_license | #include <sched.h>
#include <stdio.h>
void get_current_scheduler() {
int policy = sched_getscheduler(0);
switch (policy) {
case SCHED_OTHER:
printf("policy is normal\n");
break;
case SCHED_RR:
printf("policy is round-robin\n");
break;
case SCHED_FIFO:
printf("policy is first-in, first-out\n");
break;
case -1:
perror("sched_getscheduler");
break;
default:
fprintf(stderr, "Unknown policy!\n");
}
}
int main(void) {
get_current_scheduler();
// set scheduler to RR
struct sched_param sp = {.sched_priority = 1};
struct timespec tp;
sched_setscheduler(0, SCHED_RR, &sp);
sched_getparam(0, &sp);
printf("Our priority is %d\n", sp.sched_priority);
sched_rr_get_interval(0, &tp);
printf("Our time quantum is %.2lf milliseconds\n", (tp.tv_sec * 1000.0f) + (tp.tv_nsec / 1000000.0f));
return 0;
}
| true |
897bb37df119f5257abb6d96619893d848d613bd | C++ | kim-online/KIMKOEHLERCODE2 | /HW3/Ball.hpp | UTF-8 | 485 | 2.546875 | 3 | [] | no_license | //
// Ball.hpp
// myOOPS
//
// Created by Kim Köhler on 26/02/16.
//
//
#ifndef Ball_hpp
#define Ball_hpp
#include <stdio.h>
#include "ofMain.h"
class Ball{
public:
//constructor
Ball();
//variabels
float x, y, z;
float xSpeed, ySpeed, zSpeed;
float change;
int dim;
ofColor color;
//methods
void setup(float _x, float _y, float _z, int _dim);
void update();
void draw();
};
#endif /* Ball_hpp */ | true |
b9dfd73f6cf785f37dfa7b16fa4c62f86de5d60e | C++ | liangzai90/Coding-Interviews | /02 替换空格.cpp | GB18030 | 751 | 3.890625 | 4 | [] | no_license | /*2ʵһһַеĿո滻ɡ%20
磬ַΪWe Are Happy.滻ַ֮ΪWe%20Are%20Happy*/
class Solution {
public:
void replaceSpace(char *str, int length) {
int OldLength = 0;
int NewLength = 0;
int BlankLength = 0;
while (str[OldLength] != '\0'){
if (str[OldLength] == ' '){
BlankLength++;
}
OldLength++;
}
NewLength = OldLength + BlankLength * 2;
if (NewLength>length)
return;
while (NewLength>OldLength){
if (str[OldLength] == ' '){
str[NewLength--] = '0';
str[NewLength--] = '2';
str[NewLength--] = '%';
}
else
str[NewLength--] = str[OldLength];
OldLength--;
}
}
}; | true |
ecdec4c1e688cd92e3a18cab8448e38e88f744ac | C++ | pablorecio/KGLT | /kglt/ui/label.h | UTF-8 | 845 | 2.734375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef LABEL_H
#define LABEL_H
#include <tr1/memory>
#include "../generic/identifiable.h"
#include "element.h"
#include "types.h"
namespace kglt {
class Text;
class UI;
namespace ui {
class Label :
public Element,
public generic::Identifiable<LabelID> {
public:
typedef std::tr1::shared_ptr<Label> ptr;
Label(UI* ui, LabelID id):
Element(ui),
generic::Identifiable<LabelID>(id),
text_id_(0) {}
void set_text(const std::string& text);
std::string text() const;
void set_font(kglt::FontID fid);
virtual double width();
virtual double height();
virtual void _initialize(Scene &scene);
virtual void set_foreground_colour(const kglt::Colour& colour);
private:
TextID text_id_;
Text& text_object();
const Text& text_object() const;
};
}
}
#endif // LABEL_H
| true |
3fd3767d06331d81aa0821a03128d6757a0be1d3 | C++ | hermann-p/segemehl-visual | /utils.cpp | UTF-8 | 1,403 | 2.96875 | 3 | [] | no_license | #include "utils.h"
#include "genome.h"
#include <iostream>
#include <vector>
#include <string>
#include <memory>
void log ( const std::string msg ) {
std::cout << msg << std::endl;
}
bool assume ( const bool isGood, const std::string msg, bool fatal ) {
if (!isGood) {
if (fatal) {
std::cerr << "Error: " << msg << ", halting.\n";
std::exit(-1);
return false; // pro forma for compiler
}
else {
std::cerr << "Warning: " << msg << std::endl;
return false;
}
}
return true;
}
std::vector< std::string > strsplit ( const std::string input, const std::string& delim, bool keepEmpty ) {
std::string token, theStr(input);
int L = delim.length();
std::unique_ptr<std::vector< std::string >> result(new std::vector<std::string>());
int end(0);
int start(0);
while (end >= 0) {
end = theStr.find_first_of(delim, start);
// theStr = theStr.substr(end + L);
if (keepEmpty || end != start) {
token = theStr.substr(start, end-start);
result->push_back(token);
}
start = end + L;
}
return *result;
}
/*
* For numerical values. May be inexact for floating point numbers.
* If one of {b,c} < a and the other one > a, then
* b-a <= 0 ^ c-a >= 0
* or b-a >= 0 ^ c-a <= 0
* => (b-a) * (c-a) <= 0
*/
template <typename T>
bool isBetweenBC ( T a, T b, T c ) {
return (b-a) * (c-a) <= 0;
}
| true |
80b79ed7a367a787736527a626ebeef7da0879d0 | C++ | westlicht/performer | /src/platform/sim/sim/frontend/Common.h | UTF-8 | 1,908 | 2.96875 | 3 | [
"freertos-exception-2.0",
"MIT",
"GPL-2.0-or-later"
] | permissive | #pragma once
#include "Vector.h"
#include <SDL.h>
#include <string>
#include <vector>
#include <array>
#include <memory>
#include <iostream>
#include <functional>
#include <cstdint>
#include <cmath>
namespace sim {
static const float PI = 3.141592653589793f;
static const float TWO_PI = 6.283185307179586f;
class Color : public Vector4f {
public:
Color() : Vector4f(0.f, 0.f, 0.f, 0.f) {}
explicit Color(const Vector4f &color) : Vector4f(color) {}
explicit Color(const Vector3f &color, float alpha) : Color(color[0], color[1], color[2], alpha) {}
explicit Color(const Vector3i &color, int alpha) : Color(Vector3f(color) / 255.f, alpha / 255.f) {}
explicit Color(const Vector3f &color) : Color(color, 1.0f) {}
explicit Color(const Vector3i &color) : Color((Vector3f(color) / 255.f)) {}
explicit Color(const Vector4i &color) : Color((Vector4f(color) / 255.f)) {}
explicit Color(float intensity, float alpha) : Color(Vector3f(intensity), alpha) {}
explicit Color(int intensity, int alpha) : Color(Vector3i(intensity), alpha) {}
explicit Color(float r, float g, float b, float a) : Color(Vector4f(r, g, b, a)) {}
explicit Color(int r, int g, int b, int a) : Color(Vector4i(r, g, b, a)) {}
const float &r() const { return x(); }
float &r() { return x(); }
const float &g() const { return y(); }
float &g() { return y(); }
const float &b() const { return z(); }
float &b() { return z(); }
const float &a() const { return w(); }
float &a() { return w(); }
uint32_t rgba() const {
return (
std::min(255, int(std::floor(x() * 255))) |
std::min(255, int(std::floor(y() * 255))) << 8 |
std::min(255, int(std::floor(z() * 255))) << 16 |
std::min(255, int(std::floor(w() * 255))) << 24
);
}
};
} // namespace sim
| true |
20234fa8bf74fa45e739c4072d39255b2b01a71a | C++ | episkipoe/Agents | /organism_libraries/common/shmem.cpp | UTF-8 | 1,411 | 2.78125 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#include <string>
void push_to_shared_memory(int key, char * data, int size) {
printf("push %i := %i%i\n", size, data[0], data[1]);
int shmid = shmget(key, size, IPC_CREAT | 0666);
if(shmid<0) return ;
char * shm;
if((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) return ;
memcpy(shm, data, size);
}
int read_from_shared_memory(int key, char * data, int size) {
int shmid = shmget(key, size, 0666);
if(shmid<0) return 0;
char * shm;
if((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) return 0;
memcpy(data, shm, size);
printf("read %i := %i%i\n", size, data[0], data[1]);
return 1;
}
int pop_from_shared_memory(int key, char * data, int size) {
int shmid = shmget(key, size, 0666);
if(shmid<0) return 0;
char * shm;
if((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) return 0;
memcpy(data, shm, size);
shmdt(shm);
shmctl(shmid, IPC_RMID, 0);
return 1;
}
#if 0
int main() {
char push_data[] = "test_shared";
push_to_shared_memory(123, push_data, sizeof(push_data));
char pop_data[64];
pop_from_shared_memory(123, pop_data, sizeof(push_data));
printf("revcd %s\n", pop_data);
int val = 7;
push_to_shared_memory(123, (char*)&val, sizeof(int));
val = 49;
pop_from_shared_memory(123, (char*)&val, sizeof(int));
printf("val is %i\n", val);
return 0;
}
#endif
| true |
a93857501514e12525a199a498524e979f78415c | C++ | ChrisJorisBol/CSD2 | /inheritance/winds.cpp | UTF-8 | 272 | 2.5625 | 3 | [] | no_license | //winds.cpp
#include "winds.h"
#include <iostream>
#include <string>
using namespace std;
Winds::Winds(string sound) : Instrument(sound)
{
// this->sound = timbre;
cout << "\nConstructor - Winds\n";
// cout << "\nThis sounds like = " << timbre << "\n";
};
| true |
8fef998ac1ed53ceebbfae735b8e7d031556b91d | C++ | alexandraback/datacollection | /solutions_2449486_1/C++/NilayVaish/B.cpp | UTF-8 | 1,140 | 2.546875 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
int G[105][105];
int H[105][105];
int main()
{
int T;
scanf("%d\n",&T);
for (int ii = 1; ii <= T; ++ii)
{
int N, M;
scanf("%d %d\n", &N, &M);
for (int i = 0; i < N; ++i) for (int j = 0 ;j < M; ++j)
{
scanf("%d", G[i]+j);
H[i][j] = 100;
}
for(int i = 0; i < N; ++i)
{
int A = 0;
for(int j = 0;j < M; ++j) A = std::max(A,G[i][j]);
for(int j = 0;j < M; ++j) H[i][j] = A;
}
for(int j = 0;j < M; ++j)
{
int B = 0;
for(int i = 0; i < N; ++i) B = std::max(B,G[i][j]);
for(int i = 0; i < N; ++i) H[i][j] = std::min(B,H[i][j]);
}
bool found = false;
for (int i = 0; i < N; ++i) for (int j = 0 ;j < M; ++j)
{
if(H[i][j] != G[i][j])
{
// printf("%d %d %d %d\n", i,j,G[i][j], H[i][j]);
found = true;
goto L;
}
}
L:
printf("Case #%d: %s\n", ii, found ? "NO":"YES");
}
return 0;
}
| true |
15e01bd4cde45f931245e11886871dc9a706ff5c | C++ | sympe/practice | /aizu/ITP/1_1/C.cpp | UTF-8 | 201 | 2.78125 | 3 | [] | no_license | #include <cstdio>
#include <math.h>
int main ()
{
int x;
int y;
int S;
int L;
scanf("%d", &x);
scanf("%d", &y);
S = x * y;
L = x * 2 + y * 2;
printf("%d %d\n", S, L);
return 0;
} | true |
058cabbca2c7ca96340da5414ab4e3ae9f38481a | C++ | HORSESUNICE/PATB | /1038.cpp | GB18030 | 1,502 | 3.125 | 3 | [] | no_license | //1038. ͳͬɼѧ(20)
//
//ʱ
//250 ms
//ڴ
//65536 kB
//볤
//8000 B
//
//Standard
//
//CHEN, Yue
//ҪNѧijɼijһѧ
//
//ʽ
//
//ڵ1и105Nѧ
//1иNѧİٷɼмԿոָ1иҪѯķKN
//KмԿոָ
//
//ʽ
//
//һаѯ˳÷ֵָѧмԿոָĩжո
//
//
//10
//60 75 90 55 75 99 82 90 75 50
//3 75 90 88
//
//3 2 0
//idea:
//1032
//ʼvectorcount-6ʱ
//ijͨ
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#pragma warning(disable:4996)
using namespace std;
int main()
{
vector<int> grade;
int n;
int num;
cin >> n;
int st[101] = { 0 };
for (int i = 0; i != n; ++i)
{
scanf("%d", &num);
++st[num];
}
cin >> n;
for (int i = 0; i != n; ++i)
{
scanf("%d", &num);
grade.push_back(num);
}
cout << st[grade[0]];
if (grade.size() > 1)
{
for (int i = 1; i != grade.size(); ++i)
cout << " " << st[grade[i]];
}
} | true |
c836e569e692c1add0c4edcf568c232a908652e3 | C++ | Samiatrix/Leetcode-Problems | /reorder-data-in-log-files/reorder-data-in-log-files.cpp | UTF-8 | 1,266 | 2.921875 | 3 | [] | no_license | class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<pair<string, string>> letter;
vector<pair<string, string>> digits;
for(auto s:logs){
string identifier = "";
string log="";
bool spaceFound = false;
for(int i=0;i<s.size();i++){
if(!spaceFound && s[i] != ' '){
identifier+=s[i];
}
else if(!spaceFound && s[i] == ' '){
spaceFound = true;
}
else if(spaceFound){
log+=s[i];
}
}
if(isdigit(log[0])){
digits.push_back({identifier, log});
}
else{
letter.push_back({identifier, log});
}
}
sort(letter.begin(), letter.end(), [](pair<string, string> a, pair<string, string> b){
return a.second == b.second ? a.first<b.first : a.second<b.second;
});
vector<string> ans;
for(auto p:letter){
ans.push_back(p.first+" "+p.second);
}
for(auto p:digits){
ans.push_back(p.first+" "+p.second);
}
return ans;
}
}; | true |
0ec08a651d79b733131093ceb4d03986088881e5 | C++ | fightingsleep/Pleasantville485 | /common/controls.cpp | UTF-8 | 6,516 | 2.640625 | 3 | [] | no_license | #include <GL/glew.h>
#include <glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stdio.h>
#include "init.hpp"
#include "controls.hpp"
#include "window.hpp"
bool renderDepthTexture = false;
// Camera vectors
glm::vec3 position = glm::vec3(0, GROUND_Y_VALUE, -1);
glm::vec3 direction = glm::vec3(0, 0, 0.01);
glm::vec3 right = glm::vec3(-1, 0, 0);
glm::vec3 up = glm::cross(right, direction);
// Transform matrices
glm::mat4 ViewMatrix = glm::lookAt(
// Camera is here
position,
// Camera looks here
position + direction,
// Vector pointing up from camera
up
);
glm::mat4 ProjectionMatrix = glm::perspective(45.0f,
16.0f / 9.0f,
0.1f,
1000.0f);
glm::mat4 getViewMatrix()
{
return ViewMatrix;
}
glm::mat4 getProjectionMatrix()
{
return ProjectionMatrix;
}
// Mouse info
double xpos, ypos;
double mouseSpeed = 0.0015f;
// Camera movement speed (units / second)
float speed = 25.0f;
// Camera angles
double horizontalAngle = 0.0f;
double verticalAngle = 0.0f;
const float pi = 3.14;
bool godMode = false;
bool jumping = false;
bool falling = false;
bool hanging = false;
bool keys[1024];
void updateView() {
ViewMatrix = glm::lookAt(
// Camera is here
position,
// Camera looks here
position + direction,
// Vector pointing up from camera
up
);
}
void processUserInput()
{
static double lastTime = glfwGetTime();
// Compute time difference between current and last frame
double currentTime = glfwGetTime();
double deltaTime = double(currentTime - lastTime);
static int counter = 0;
// Move forward
if (keys[GLFW_KEY_W]){
position += direction * float(deltaTime) * speed;
}
// Move backward
if (keys[GLFW_KEY_S]){
position -= direction * float(deltaTime) * speed;
}
// Strafe right
if (keys[GLFW_KEY_D]){
position += right * float(deltaTime) * speed;
}
// Strafe left
if (keys[GLFW_KEY_A]){
position -= right * float(deltaTime) * speed;
}
if (!godMode && !jumping && !falling && !hanging) {
// Keep the camera on the x-z plane
position = glm::vec3(position.x, GROUND_Y_VALUE, position.z);
}
if (jumping) {
if (position.y >= 7.0) {
jumping = false;
hanging = true;
counter = 0;
} else if (position.y >= 5.0) {
position = glm::vec3(position.x, position.y + 0.08, position.z);
} else {
position = glm::vec3(position.x, position.y + 0.1, position.z);
}
}
if (hanging) {
if (counter > 5) {
hanging = false;
falling = true;
counter = 0;
} else {
counter++;
}
}
if (falling) {
position = glm::vec3(position.x, position.y - 0.1, position.z);
if(position.y <= GROUND_Y_VALUE) {
position = glm::vec3(position.x, GROUND_Y_VALUE, position.z);
falling = false;
}
}
// Update the View matrix
updateView();
// DEBUG PRINTING
// printf("xpos: %f, ypos: %f\n", xpos, ypos);
// printf("horizontalAngle: %f, verticalAngle: %f\n",
// horizontalAngle, verticalAngle);
//
//
// printf("double(xpos - lastXPos) = %f\n", double(xpos - lastXPos));
// printf("double(lastYPos - ypos) = %f\n", double(lastYPos - ypos));
//
// printf("mouseSpeed * double(xpos - lastXPos) = %f\n", mouseSpeed * double(xpos - lastXPos));
// printf("mouseSpeed * double(lastYPos - ypos) = %f\n", mouseSpeed * double(lastYPos - ypos));
//
// printf("\n\ndirection:(%f,%f,%f)\n,right:(%f,%f,%f)\n\n",
// direction.x, direction.y, direction.z,
// right.x, right.y, right.z);
lastTime = currentTime;
}
void keyPressCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key >= 0 && key < 1024)
{
if (action == GLFW_PRESS)
keys[key] = true;
else if (action == GLFW_RELEASE)
keys[key] = false;
}
// Toggle godMode
if (action == GLFW_PRESS && key == GLFW_KEY_G){
godMode = !godMode;
}
// Toggle depth texture debug rendering
if (action == GLFW_PRESS && key == GLFW_KEY_APOSTROPHE){
renderDepthTexture = !renderDepthTexture;
}
if (action == GLFW_PRESS && key == GLFW_KEY_SPACE){
if (!falling && !hanging && !godMode) {
jumping = true;
}
}
}
void mouseMovementCallback(GLFWwindow* window, double xpos, double ypos)
{
static double lastXPos, lastYPos;
static bool firstTime = true;
// Get mouse position
glfwGetCursorPos(window, &xpos, &ypos);
if (firstTime) {
lastXPos = xpos;
lastYPos = ypos;
firstTime = false;
}
// Compute new orientation
horizontalAngle += mouseSpeed * double(lastXPos - xpos);
verticalAngle += mouseSpeed * double(lastYPos - ypos);
if (!godMode) {
// Limit how far the camera can look up and down
if (verticalAngle > pi/2) {
verticalAngle = pi/2;
} else if (verticalAngle < -pi/5) {
verticalAngle = -pi/5;
}
}
// Direction : Spherical coordinates to Cartesian coordinates conversion
direction = glm::vec3(
cos(verticalAngle) * sin(horizontalAngle),
sin(verticalAngle),
cos(verticalAngle) * cos(horizontalAngle)
);
// Right vector
right = glm::vec3(
sin(horizontalAngle - pi/2.0f),
0,
cos(horizontalAngle - pi/2.0f)
);
// Up vector
up = glm::cross(right, direction);
lastXPos = xpos;
lastYPos = ypos;
updateView();
}
void initCallbacks()
{
glfwSetKeyCallback(window, keyPressCallback);
glfwSetCursorPosCallback(window, mouseMovementCallback);
}
| true |
5eae319a27eec1b51ae1628c21e08dcbba22873f | C++ | tastelife/WX3000 | /WXMemDataVector.h | GB18030 | 1,914 | 2.796875 | 3 | [] | no_license | //WXMemDataVector.h
#pragma once
#include <vector>
template<class _Ty>
class CWXMemDataVector : public std::vector<_Ty>
{
public:
CWXMemDataVector()
{
}
~CWXMemDataVector()
{
}
inline void Add(const _Ty& tNewData)
{
push_back(tNewData);
}
//ɾ
inline int Delete(const _Ty& tCurrent)
{
int nRtn = 0;
for(int i=size()-1; i>=0; --i)
{
if(tCurrent==(at(i)))
{
erase(begin()+i);
++nRtn;
}
}
return nRtn;
}
//ɾ pred
template<class _Pr>
inline int Delete(_Pr pred)
{
int nRtn = 0;
for(int i=size()-1; i>=0; --i)
{
if(pred(at(i)))
{
erase(begin()+i);
++nRtn;
}
}
return nRtn;
}
//༭
inline int Edit(const _Ty& tCurrent, const _Ty& tEdit)
{
int nRtn = 0;
for(iterator iter = begin(); iter!=end(); ++iter)
{
if(tCurrent==(*iter))
{
*iter = tEdit;
++nRtn;
}
}
return nRtn;
}
//༭ pred
template<class _Pr>
inline int Edit(const _Ty& tEdit, _Pr pred)
{
int nRtn = 0;
for(iterator iter = begin(); iter!=end(); ++iter)
{
if(pred(*iter))
{
*iter = tEdit;
++nRtn;
}
}
return nRtn;
}
//
inline int Find(const _Ty& tCurrent, CWXMemDataVector<_Ty>& memDataVec)
{
int nRtn = 0;
for(iterator iter=begin(); iter!=end(); ++iter)
{
if(tCurrent==(*iter))
{
memDataVec.push_back(*iter);
++nRtn;
}
}
return nRtn;
}
// pred
template<class _Pr>
inline int Find(_Pr pred, CWXMemDataVector<_Ty>& memDataVec)
{
int nRtn = 0;
for(iterator iter=begin(); iter!=end(); ++iter)
{
if(pred(*iter))
{
memDataVec.push_back(*iter);
++nRtn;
}
}
return nRtn;
}
//,ҵĵһ pred
template<class _Pr>
bool Find(_Pr pred, _Ty& data)
{
for(iterator iter=begin(); iter!=end(); ++iter)
{
if(pred(*iter))
{
data = *iter;
return true;
}
}
return false;
}
};
| true |
7dcd9ef5c1f7c07cdd3ea351bb296c7f266c6ad0 | C++ | cpprhtn/ML-DL-with-cpp | /Make_ML_Models/NaiveBayes_Model/naive_bayes.cpp | UTF-8 | 5,252 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <sstream>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <utility>
#include "naive_bayes.h"
using namespace std;
NaiveBayesClassifier::NaiveBayesClassifier() {
;
}
NaiveBayesClassifier::NaiveBayesClassifier(
int Max_n, int Min_p, const string& train_data,
const string& voca_data, const string& sw_data = "") {
//setting
reviews_p = 0;
reviews_n = 0;
this -> Max_n = Max_n;
this -> Min_p = Min_p;
sw_drop = false;
if (sw_data != "") {
stop_words = readWords(sw_data);
sw_drop = true;
}
voca_word = readWords(voca_data);
ll voca_size = voca_word.size();
vector<pair<pair<ll, ll>, pair<ll, ll>>> words_freq;
//setup
words_freq.resize(voca_size);
prob_word.resize(voca_size);
for (auto& word_info: words_freq) {
word_info.first.first = 0;
word_info.first.second = 0;
word_info.second.first = 0;
word_info.second.second = 0;
}
//populate
ifstream in(train_data);
if (!in.is_open()) {
cerr << "File opening failed\n";
exit(0);
}
string line;
ll pos_wobin_freq = 0, neg_wobin_freq = 0, pos_wbin_freq = 0, neg_wbin_freq = 0;
//iteration 하나당 review도 한번검토
while (getline(in, line)) {
//review값 확인
stringstream ss;
ss.str(line);
ll rating;
bool is_pos;
ss >> rating;
if (rating <= Max_n) {
is_pos = false;
++reviews_n;
} else if (rating >= Min_p) {
is_pos = true;
++reviews_p;
} else {
cerr << "Unexpected Neutral: " << rating << "\n";
exit(0);
}
//encoded된 단어 처리
ll a, b;
char discard;
while (!ss.eof()) {
ss >> a;
ss.get(discard);
ss >> b;
ss.get(discard);
if (sw_drop && binary_search(stop_words.begin(), stop_words.end(), voca_word[a])) {
continue;
}
if (is_pos) {
words_freq[a].first.first += b;
pos_wobin_freq += b;
words_freq[a].second.first += 1;
++pos_wbin_freq;
} else {
words_freq[a].first.second += b;
neg_wobin_freq += b;
words_freq[a].second.second += 1;
++neg_wbin_freq;
}
}
}
in.close();
//populate
for (ll i = 0; i < voca_size; i++) {
prob_word[i].first.first = (1.0 + words_freq[i].first.first) / (pos_wobin_freq + voca_size);
prob_word[i].first.second = (1.0 + words_freq[i].first.second) / (neg_wobin_freq + voca_size);
prob_word[i].second.first = (1.0 + words_freq[i].second.first) / (pos_wbin_freq + voca_size);
prob_word[i].second.second = (1.0 + words_freq[i].second.second) / (neg_wbin_freq + voca_size);
}
}
void NaiveBayesClassifier::test(const string& test_bow_file, bool use_bin) {
ifstream in(test_bow_file);
if (!in.is_open()) {
cerr << "File opening failed\n";
exit(0);
}
ll tp = 0, fp = 0, fn = 0, tn = 0;
string line;
//iteration 하나당 review도 한번검토
while (getline(in, line)) {
//review 값 확인
ll rating;
stringstream ss;
ss.str(line);
ss >> rating;
bool is_pos;
if (rating <= Max_n) {
is_pos = false;
} else if (rating >= Min_p) {
is_pos = true;
} else {
cerr << "Unexpected Neutral: " << rating << "\n";
exit(0);
}
//인스턴스 분류
if (classify(ss, use_bin)) {
if (is_pos) {
++tp;
} else {
++fp;
}
} else {
if (is_pos) {
++fn;
} else {
++tn;
}
}
}
in.close();
//실제 출력 구간
cout << fixed << setprecision(6)
<< "Accuracy: " << (static_cast<double>(tp + tn) / (tp + tn + fp + fn)) * 100 << "%\n"
<< "Precision: " << (static_cast<double>(tp)) / (tp + fp) << "\n"
<< "Recall: " << (static_cast<double>(tp)) / (tp + fn) << "\n"
<< "F1 Measure: " << (2 * static_cast<double>(tp)) / (2 * tp + fp + fn) << "\n";
}
vector<string> NaiveBayesClassifier::most_important(ll num, bool use_bin) {
//find P(w/+ve sentiment) / P(w/-ve sentiment) for each word
vector<pair<ld,ll>> temp;
for(int i =0 ;i<prob_word.size(); i++) {
if(!use_bin)
temp.push_back(make_pair(prob_word[i].first.first/prob_word[i].first.second,i));
else temp.push_back(make_pair(prob_word[i].second.first/prob_word[i].second.second,i));
}
sort(temp.begin(),temp.end());
reverse(temp.begin(),temp.end());
//num 변수의 특성 반환
vector<string> return_vec;
for(int i=0; i<num; i++) return_vec.push_back(voca_word[temp[i].second]);
return return_vec;
}
vector<string> NaiveBayesClassifier::readWords(const string& sw_data) {
ifstream fin(sw_data,ios::in);
vector<string> data;
while(!fin.eof()){
string s;
fin>>s;
stringstream str(s);
data.push_back(s);
}
return data;
}
bool NaiveBayesClassifier::classify(stringstream& bow_review_instance, bool use_bin) {
stringstream& ss = bow_review_instance;
ld pos_prob = log(static_cast<ld>(reviews_p) / (reviews_p + reviews_n));
ld neg_prob = log(static_cast<ld>(reviews_n) / (reviews_p + reviews_n));
ll a, b;
char discard;
while (!ss.eof()) {
ss >> a;
ss.get(discard);
ss >> b;
ss.get(discard);
//stopword이면 skip
if (sw_drop && binary_search(stop_words.begin(), stop_words.end(), voca_word[a])) {
continue;
}
if (use_bin) {
pos_prob += log(prob_word[a].second.first);
neg_prob += log(prob_word[a].second.second);
} else {
pos_prob += (b * log(prob_word[a].first.first));
neg_prob += (b * log(prob_word[a].first.second));
}
}
return (pos_prob >= neg_prob ? true : false);
}
| true |
2dc9f9656913d769edd2b9426bcc40761d08af53 | C++ | lacrymose/3bem | /unit_tests/test_numbers.cpp | UTF-8 | 414 | 3.109375 | 3 | [] | no_license | #include "catch.hpp"
#include "numbers.h"
using namespace tbem;
TEST_CASE("Range", "[numbers]") {
auto nats5 = range(-1, 8);
double correct[] = {-1, 0, 1, 2, 3, 4, 5, 6, 7};
REQUIRE_ARRAY_EQUAL(nats5, correct, 9);
}
TEST_CASE("Linspace", "[numbers]") {
auto vals = linspace(0.0, 1.0, 10);
REQUIRE(vals.size() == 10);
REQUIRE(vals[0] == 0.0);
REQUIRE(vals[vals.size() - 1] == 1.0);
}
| true |
b643cf42a1dd04da69364f6ce3c380046af636fe | C++ | RabbiAmin/Sudoku | /Suduku01.cpp | UTF-8 | 2,834 | 3.390625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define UNASSIGNED 0 // for unassigned value
#define N 9 //sudoku size N*N
bool UnassignedAddress (int cell[N][N],int &row, int &colum);
bool legal(int cell[N][N], int row, int colum, int number);// Checks its legal or not
bool solution(int cell[N][N])
{
int row, colum;
if (!UnassignedAddress(cell, row, colum))
return true;
for (int number = 1; number <= 9; number++)
{
if (legal(cell, row, colum, number))
{
cell[row][colum] = number;
if (solution(cell))
return true;
2 cell[row][colum] = UNASSIGNED;
}
}
return false;
}
bool UnassignedAddress(int cell[N][N],int &row, int &colum)
{
for (row = 0; row < N; row++)
for (colum = 0; colum < N; colum++)
if (cell[row][colum] == UNASSIGNED)
return true;
return false;
}
bool Row(int cell[N][N], int row, int number )
{
for (int colum = 0; colum < N; colum++)
if (cell[row][colum] == number)
return true;
return false;
}
bool Colum(int cell[N][N], int colum, int number)
{
for (int row = 0; row < N; row++)
if (cell[row][colum] == number)
return true;
return false;
}
bool Box(int cell[N][N], int boxStartRow, int boxStartColum, int number)
{
for (int row = 0; row < 3; row++)
for (int colum = 0; colum < 3; colum++)
if (cell[row + boxStartRow]
[colum + boxStartColum] == number)
return true;
return false;
}
bool legal(int cell[N][N], int row,int colum, int number)
{
return !Row (cell, row, number) &&
!Colum(cell, colum, number) &&
!Box (cell, row - row % 3 , colum - colum % 3, number) &&
cell[row][colum] == UNASSIGNED;
}
void print(int cell[N][N])
{
for (int row = 0; row < N; row++)
{
for (int colum = 0; colum < N; colum++)
cout << cell[row][colum] << " ";
cout << endl;
}
}
int main()
{
int cell[N][N] = {{0, 0, 0, 2, 6, 0, 7, 0, 1},
{6, 8, 0, 0, 7, 0, 0, 9, 0},
{0, 9, 0, 0, 0, 4, 5, 0, 0},
{8, 2, 0, 1, 0, 0, 0, 4, 0},
{0, 0, 4, 6, 0, 2, 9, 0, 0},
{0, 5, 0, 0, 0, 3, 0, 2, 8},
{0, 0, 9, 3, 0, 0, 0, 7, 4},
{0, 4, 0, 0, 5, 0, 0, 3, 6},
{7, 0, 3, 0, 1, 8, 0, 0, 0}};
if ( solution(cell) == true)
print(cell);
//cout << "Successfully solved :) " ;
else
cout << "No solution exists";
return 0;
}
| true |
cddbcf80d63863da94582f2c169d469725a139be | C++ | zchen0211/topcoder | /cc/leetcode/035_search_insert.cc | UTF-8 | 380 | 3.03125 | 3 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int i = 0, j = n;
while (i < j) {
int mid = (i + j) / 2;
if (nums[mid] > target)
j = mid;
else if (nums[mid] == target)
return mid;
else
i = mid + 1;
}
return max(i, j);
}
};
| true |
2b1df24386b669523b281a77f670dd7e9a9a86e6 | C++ | Dopiz/DesignPattern-Shape | /include/Circle.h | UTF-8 | 364 | 2.859375 | 3 | [] | no_license | #ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
#include "Point.h"
class Circle : public Shape
{
private:
Point _center;
double _radius;
public:
Circle(double cx, double cy, double radius);
string description();
double perimeter() const;
double area() const;
~Circle();
};
#endif // CIRCLE_H
| true |
068099924d164bb986e6afb2edc3d52755f76710 | C++ | Petros89/Algorithms-CPP | /twosum/twosum.cpp | UTF-8 | 1,282 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class TwoSum
{
public:
static pair<int, int> findTwoSum(const vector<int>&vector_input, int target)
{
unordered_map<int,int> set;
for (size_t i = 0; i < vector_input.size(); ++i)
{
auto search = set.find(target - vector_input[i]);
if (search != set.end())
return make_pair(i,search->second);
set[vector_input[i]] = i;
}
return make_pair(-1, -1);
}
};
#ifndef RunTests
int main(int argc, const char* argv[])
{
vector<int> myvec;
myvec.push_back(1);
myvec.push_back(5);
myvec.push_back(1);
myvec.push_back(8);
myvec.push_back(4);
sort(myvec.begin(),myvec.end());
//play with vector
reverse(myvec.begin(),myvec.end());
auto last = unique(myvec.begin(),myvec.end());
myvec.erase(last,myvec.end());
for (vector<int>::iterator it=myvec.begin(); it!=myvec.end(); ++it)
cout << ' ' << *it;
cout << '\n';
int target = 8;
pair<int, int> position;
position = TwoSum::findTwoSum(myvec, target);
cout << position.first << " " << position.second << "\n";
return 0;
}
#endif
| true |
eb3e815cac46c317c456c0e5e8d8f5f4182c8195 | C++ | kpusmo/fem | /Headers/ResultsModel.h | UTF-8 | 783 | 2.515625 | 3 | [] | no_license | #ifndef MES_RESULTSMODEL_H
#define MES_RESULTSMODEL_H
#include <QAbstractTableModel>
#include <vector>
#include "Result.h"
class ResultsModel : public QAbstractTableModel {
public:
explicit ResultsModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &index = QModelIndex()) const override;
int columnCount(const QModelIndex &index = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
void setResults(const std::vector<Result> &resultsVector, unsigned rows, unsigned columns);
void nextResult();
void previousResult();
protected:
std::vector<Result> results;
unsigned rows{};
unsigned columns{};
unsigned currentResult{};
};
#endif //MES_RESULTSMODEL_H
| true |
2305324f27cf8c513088a4bc1690ff5f60a14e82 | C++ | CarvalhoBarberino/cppAgit | /Vetor201904271215/main.cpp | UTF-8 | 2,733 | 3.890625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <memory>
//void imprimir(int a); //Cópia - C/C++
//void imprimir(int *a); //Endereço - C/C++
//void imprimir(int &a); //Endereço - C++
//void imprimir(int &&a); //Referencia RValue - C++ 11 >
using namespace std;
template <typename T>
class Vetor
{
T *m_elements;
unsigned int m_size;
public:
Vetor()
{
//Inicializar m_elements e m_size
m_elements = nullptr ;
m_size = 0;
}
// Vetor(const Vetor &v)
// {
// //Criar vetor com tamanho de v.m_size
// //Copiar elementos de v.m_elements
// }
// Vetor(Vetor &&v)
// {
// //Fazer jogada de pointeiros
// }
// Vetor & operator =(const Vetor &v)
// {
// //Deletar o vetor atual
// //Criar vetor com tamanho de v.m_size
// //Copiar elementos de v.m_elements
// }
// Vetor & operator =(Vetor &&v)
// {
// //Fazer jogada de pointeiros
// }
// ~Vetor()
// {
// //Limpa o vetor
// }
// void clear()
// {
// //Limpa o vetor
// }
void push_back(const T &value)
{
//Cria um vetor temporario com m_size + 1
T *temp = new T[m_size + 1];
//Copiar o vetor antigo para o temporario
for(int i = 0; i < m_size; ++i){
temp[i] = m_elements[i];
}
//Inserir o novo elemento no temporario
temp[m_size] = value;
//Deletar o vetor antigo
delete [] m_elements;
//Fazer com que o vetor antigo aponte para o novo
m_elements = temp;
//Incrementar o m_size
++m_size;
}
// void push_back(T &&value)
// {
// //Cria um vetor temporario com m_size + 1
// T *temp = new T[m_size + 1];
// //Copiar o vetor antigo para o temporario
// for(int i = 0; i < m_size; ++i){
// temp[i] = m_elements[i];
// }
// //Mover o novo elemento no temporario
// //Deletar o vetor antigo
// delete [] m_elements;
// //Fazer com que o vetor antigo aponte para o novo
// m_elements = temp;
// //Incrementar o m_size
// ++m_size;
// }
unsigned int size() const
{
//Retorna o numero de elementos do vetor
return m_size;
}
// T &operator [](unsigned int index) const
// {
// //Retorna um elemento dada uma posição
// }
T getElement(int index){
return m_elements[index];
}
};
int main()
{
Vetor<int> x = Vetor<int>();
x.push_back(37);
x.push_back(41);
x.push_back(47);
x.push_back(53);
cout << "----" << endl;
for(unsigned int i = 0; i < x.size(); ++i)
cout << x.getElement(i) << endl;
return 0;
}
| true |
bbe8a1e585fd739beed6322e05d21eec7cca5f02 | C++ | awaybrave/leetcode_solution | /anagrams.cpp | UTF-8 | 651 | 3.515625 | 4 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution{
public:
vector<string> anagrams(vector<string> &strs){
vector<string> result;
for(int i = 0; i < strs.size(); i++){
bool flag = true;
int s = strs[i].size();
for(int j = 0; j <= s/2; j++){
if(strs[i][j] != strs[i][s-j-1]){
flag = false;
break;
}
}
if(flag)
result.push_back(strs[i]);
}
return result;
}
};
int main(){
string a[] = {"abba", "b"};
vector<string> input(a, a+2);
Solution test;
vector<string> result = test.anagrams(input);
for(int i = 0; i < result.size(); i++)
cout << result[i] << endl;
}
| true |
cd449ca3869ce2315f50f99192bc3b1c9194e29a | C++ | HargovindArora/Programming | /Stacks/reverse_stack_using_recursion.cpp | UTF-8 | 651 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<stack>
#define endl '\n'
using namespace std;
void insertAtBottom(stack<int> &s, int x){
if(s.empty()){
s.push(x);
return;
}
int y = s.top();
s.pop();
insertAtBottom(s, x);
s.push(y);
}
void reverseStackRec(stack<int> &s){
if(s.empty()){
return;
}
int x = s.top();
s.pop();
reverseStackRec(s);
insertAtBottom(s, x);
}
int main(){
stack<int> s;
for(int i=1; i<=5; i++){
insertAtBottom(s, i);
}
// reverseStackRec(s);
while(s.empty() == false){
cout << s.top() << " ";
s.pop();
}
return 0;
} | true |
b78265236378bddc84b2c6141e6fa0bfd2f262e4 | C++ | rwols/gintonic | /lib/Graphics/OpenGL/Vertices.cpp | UTF-8 | 27,282 | 2.90625 | 3 | [] | no_license | #include "Graphics/OpenGL/Vertices.hpp"
#include "Graphics/OpenGL/utilities.hpp"
namespace gintonic
{
namespace OpenGL
{
vertex_P::vertex_P(const float px, const float py, const float pz)
{
position[0] = px;
position[1] = py;
position[2] = pz;
}
vertex_P::vertex_P(const vec3f& p)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
}
vertex_P::vertex_P(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
}
void vertex_P::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_P),
(const GLvoid*)offsetof(vertex_P, position));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
}
void vertex_P::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
}
bool vertex_P::operator==(const vertex_P& other) const noexcept
{
return position[0] == other.position[0] &&
position[1] == other.position[1] && position[2] == other.position[2];
}
vertex_PC::vertex_PC(const float px, const float py, const float pz,
const float cx, const float cy, const float cz,
const float cw)
{
position[0] = px;
position[1] = py;
position[2] = pz;
color[0] = cx;
color[1] = cy;
color[2] = cz;
color[3] = cw;
}
vertex_PC::vertex_PC(const vec3f& p, const vec4f& c)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
color[0] = c.x;
color[1] = c.y;
color[2] = c.z;
color[3] = c.w;
}
vertex_PC::vertex_PC(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
color[0] = static_cast<float>(c.x);
color[1] = static_cast<float>(c.y);
color[2] = static_cast<float>(c.z);
color[3] = static_cast<float>(c.w);
}
void vertex_PC::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PC),
(const GLvoid*)offsetof(vertex_PC, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_COLOR, 4, GL_FLOAT, GL_FALSE,
sizeof(vertex_PC),
(const GLvoid*)offsetof(vertex_PC, color));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
}
void vertex_PC::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
}
vertex_PU::vertex_PU(const float px, const float py, const float pz,
const float ux, const float uy)
{
position[0] = px;
position[1] = py;
position[2] = pz;
uv[0] = ux;
uv[1] = uy;
}
vertex_PU::vertex_PU(const vec3f& p, const vec2f& u)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
uv[0] = u.x;
uv[1] = u.y;
}
vertex_PU::vertex_PU(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
uv[0] = static_cast<float>(u.x);
uv[1] = static_cast<float>(u.y);
}
void vertex_PU::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PU),
(const GLvoid*)offsetof(vertex_PU, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TEXCOORD, 2, GL_FLOAT,
GL_FALSE, sizeof(vertex_PU),
(const GLvoid*)offsetof(vertex_PU, uv));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
}
void vertex_PU::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
}
vertex_PN::vertex_PN(const float px, const float py, const float pz,
const float nx, const float ny, const float nz)
{
position[0] = px;
position[1] = py;
position[2] = pz;
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
}
vertex_PN::vertex_PN(const vec3f& p, const vec3f& n)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
normal[0] = n.x;
normal[1] = n.y;
normal[2] = n.z;
}
vertex_PN::vertex_PN(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
normal[0] = static_cast<float>(n.x);
normal[1] = static_cast<float>(n.y);
normal[2] = static_cast<float>(n.z);
}
void vertex_PN::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PN),
(const GLvoid*)offsetof(vertex_PN, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_NORMAL, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PN),
(const GLvoid*)offsetof(vertex_PN, normal));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
}
void vertex_PN::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
}
vertex_PCU::vertex_PCU(const float px, const float py, const float pz,
const float cx, const float cy, const float cz,
const float cw, const float ux, const float uy)
{
position[0] = px;
position[1] = py;
position[2] = pz;
color[0] = cx;
color[1] = cy;
color[2] = cz;
color[3] = cw;
uv[0] = ux;
uv[1] = uy;
}
vertex_PCU::vertex_PCU(const vec3f& p, const vec4f& c, const vec2f& u)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
color[0] = c.x;
color[1] = c.y;
color[2] = c.z;
color[3] = c.w;
uv[0] = u.x;
uv[1] = u.y;
}
vertex_PCU::vertex_PCU(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
color[0] = static_cast<float>(c.x);
color[1] = static_cast<float>(c.y);
color[2] = static_cast<float>(c.z);
color[3] = static_cast<float>(c.w);
uv[0] = static_cast<float>(u.x);
uv[1] = static_cast<float>(u.y);
}
void vertex_PCU::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCU),
(const GLvoid*)offsetof(vertex_PCU, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_COLOR, 4, GL_FLOAT, GL_FALSE,
sizeof(vertex_PCU),
(const GLvoid*)offsetof(vertex_PCU, color));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TEXCOORD, 2, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCU),
(const GLvoid*)offsetof(vertex_PCU, uv));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
}
void vertex_PCU::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
}
vertex_PCUN::vertex_PCUN(const float px, const float py, const float pz,
const float cx, const float cy, const float cz,
const float cw, const float ux, const float uy,
const float nx, const float ny, const float nz)
{
position[0] = px;
position[1] = py;
position[2] = pz;
color[0] = cx;
color[1] = cy;
color[2] = cz;
color[3] = cw;
uv[0] = ux;
uv[1] = uy;
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
}
vertex_PCUN::vertex_PCUN(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
color[0] = c.x;
color[1] = c.y;
color[2] = c.z;
color[3] = c.w;
uv[0] = u.x;
uv[1] = u.y;
normal[0] = n.x;
normal[1] = n.y;
normal[2] = n.z;
}
vertex_PCUN::vertex_PCUN(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
color[0] = static_cast<float>(c.x);
color[1] = static_cast<float>(c.y);
color[2] = static_cast<float>(c.z);
color[3] = static_cast<float>(c.w);
uv[0] = static_cast<float>(u.x);
uv[1] = static_cast<float>(u.y);
normal[0] = static_cast<float>(n.x);
normal[1] = static_cast<float>(n.y);
normal[2] = static_cast<float>(n.z);
}
void vertex_PCUN::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCUN),
(const GLvoid*)offsetof(vertex_PCUN, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_COLOR, 4, GL_FLOAT, GL_FALSE,
sizeof(vertex_PCUN),
(const GLvoid*)offsetof(vertex_PCUN, color));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TEXCOORD, 2, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCUN),
(const GLvoid*)offsetof(vertex_PCUN, uv));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_NORMAL, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PCUN),
(const GLvoid*)offsetof(vertex_PCUN, normal));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
}
void vertex_PCUN::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
}
vertex_PUN::vertex_PUN(const float px, const float py, const float pz,
const float ux, const float uy, const float nx,
const float ny, const float nz)
{
position[0] = px;
position[1] = py;
position[2] = pz;
uv[0] = ux;
uv[1] = uy;
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
}
vertex_PUN::vertex_PUN(const vec3f& p, const vec2f& u, const vec3f& n)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
uv[0] = u.x;
uv[1] = u.y;
normal[0] = n.x;
normal[1] = n.y;
normal[2] = n.z;
}
vertex_PUN::vertex_PUN(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
uv[0] = static_cast<float>(u.x);
uv[1] = static_cast<float>(u.y);
normal[0] = static_cast<float>(n.x);
normal[1] = static_cast<float>(n.y);
normal[2] = static_cast<float>(n.z);
}
void vertex_PUN::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PUN),
(const GLvoid*)offsetof(vertex_PUN, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TEXCOORD, 2, GL_FLOAT,
GL_FALSE, sizeof(vertex_PUN),
(const GLvoid*)offsetof(vertex_PUN, uv));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_NORMAL, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PUN),
(const GLvoid*)offsetof(vertex_PUN, normal));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
}
void vertex_PUN::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
}
vertex_PCUNTB::vertex_PCUNTB(const float px, const float py, const float pz,
const float cx, const float cy, const float cz,
const float cw, const float ux, const float uy,
const float nx, const float ny, const float nz,
const float tx, const float ty, const float tz,
const float bx, const float by, const float bz)
{
position[0] = px;
position[1] = py;
position[2] = pz;
color[0] = cx;
color[1] = cy;
color[2] = cz;
color[3] = cw;
uv[0] = ux;
uv[1] = uy;
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
tangent[0] = tx;
tangent[1] = ty;
tangent[2] = tz;
bitangent[0] = bx;
bitangent[1] = by;
tangent[2] = bz;
}
vertex_PCUNTB::vertex_PCUNTB(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
color[0] = static_cast<float>(c.x);
color[1] = static_cast<float>(c.y);
color[2] = static_cast<float>(c.z);
color[3] = static_cast<float>(c.w);
uv[0] = static_cast<float>(u.x);
uv[1] = static_cast<float>(u.y);
normal[0] = static_cast<float>(n.x);
normal[1] = static_cast<float>(n.y);
normal[2] = static_cast<float>(n.z);
tangent[0] = static_cast<float>(t.x);
tangent[1] = static_cast<float>(t.y);
tangent[2] = static_cast<float>(t.z);
bitangent[0] = static_cast<float>(b.x);
bitangent[1] = static_cast<float>(b.y);
bitangent[2] = static_cast<float>(b.z);
}
void vertex_PCUNTB::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCUNTB),
(const GLvoid*)offsetof(vertex_PCUNTB, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_COLOR, 4, GL_FLOAT, GL_FALSE,
sizeof(vertex_PCUNTB),
(const GLvoid*)offsetof(vertex_PCUNTB, color));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TEXCOORD, 2, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCUNTB),
(const GLvoid*)offsetof(vertex_PCUNTB, uv));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_NORMAL, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PCUNTB),
(const GLvoid*)offsetof(vertex_PCUNTB, normal));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TANGENT, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PCUNTB),
(const GLvoid*)offsetof(vertex_PCUNTB, tangent));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_BITANGENT, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PCUNTB),
(const GLvoid*)offsetof(vertex_PCUNTB, bitangent));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TANGENT);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_BITANGENT);
}
void vertex_PCUNTB::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_COLOR);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TANGENT);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_BITANGENT);
}
vertex_PUNTB::vertex_PUNTB(const float px, const float py, const float pz,
const float ux, const float uy, const float nx,
const float ny, const float nz, const float tx,
const float ty, const float tz, const float bx,
const float by, const float bz)
{
position[0] = px;
position[1] = py;
position[2] = pz;
uv[0] = ux;
uv[1] = uy;
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
tangent[0] = tx;
tangent[1] = ty;
tangent[2] = tz;
bitangent[0] = bx;
bitangent[1] = by;
tangent[2] = bz;
}
vertex_PUNTB::vertex_PUNTB(const vec3f& p, const vec2f& u, const vec3f& n,
const vec3f& t, const vec3f& b)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
uv[0] = u.x;
uv[1] = u.y;
normal[0] = n.x;
normal[1] = n.y;
normal[2] = n.z;
tangent[0] = t.x;
tangent[1] = t.y;
tangent[2] = t.z;
bitangent[0] = b.x;
bitangent[1] = b.y;
bitangent[2] = b.z;
}
vertex_PUNTB::vertex_PUNTB(const vec3f& p, const vec4f& c, const vec2f& u,
const vec3f& n, const vec3f& t, const vec3f& b)
{
position[0] = static_cast<float>(p.x);
position[1] = static_cast<float>(p.y);
position[2] = static_cast<float>(p.z);
uv[0] = static_cast<float>(u.x);
uv[1] = static_cast<float>(u.y);
normal[0] = static_cast<float>(n.x);
normal[1] = static_cast<float>(n.y);
normal[2] = static_cast<float>(n.z);
tangent[0] = static_cast<float>(t.x);
tangent[1] = static_cast<float>(t.y);
tangent[2] = static_cast<float>(t.z);
bitangent[0] = static_cast<float>(b.x);
bitangent[1] = static_cast<float>(b.y);
bitangent[2] = static_cast<float>(b.z);
}
void vertex_PUNTB::enable_attributes() noexcept
{
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_POSITION, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PUNTB),
(const GLvoid*)offsetof(vertex_PUNTB, position));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TEXCOORD, 2, GL_FLOAT,
GL_FALSE, sizeof(vertex_PUNTB),
(const GLvoid*)offsetof(vertex_PUNTB, uv));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_NORMAL, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PUNTB),
(const GLvoid*)offsetof(vertex_PUNTB, normal));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_TANGENT, 3, GL_FLOAT, GL_FALSE,
sizeof(vertex_PUNTB),
(const GLvoid*)offsetof(vertex_PUNTB, tangent));
glVertexAttribPointer(GINTONIC_VERTEX_LAYOUT_BITANGENT, 3, GL_FLOAT,
GL_FALSE, sizeof(vertex_PUNTB),
(const GLvoid*)offsetof(vertex_PUNTB, bitangent));
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TANGENT);
glEnableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_BITANGENT);
}
void vertex_PUNTB::disable_attributes() noexcept
{
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_POSITION);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TEXCOORD);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_NORMAL);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_TANGENT);
glDisableVertexAttribArray(GINTONIC_VERTEX_LAYOUT_BITANGENT);
}
vertex_PCUsg::vertex_PCUsg(const float px, const float py, const float pz,
const float cx, const float cy, const float cz,
const float cw, const float ux, const float uy,
const float shift_value, const float gamma_value)
{
position[0] = px;
position[1] = py;
position[2] = pz;
color[0] = cx;
color[1] = cy;
color[2] = cz;
color[3] = cw;
uv[0] = ux;
uv[1] = uy;
shift = shift_value;
gamma = gamma_value;
}
vertex_PCUsg::vertex_PCUsg(const vec3f& p, const vec4f& c, const vec2f& u,
const float shift_value, const float gamma_value)
{
position[0] = p.x;
position[1] = p.y;
position[2] = p.z;
color[0] = c.x;
color[1] = c.y;
color[2] = c.z;
color[3] = c.w;
uv[0] = u.x;
uv[1] = u.y;
shift = shift_value;
gamma = gamma_value;
}
void vertex_PCUsg::enable_attributes() noexcept
{
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_PCUsg),
(const GLvoid*)offsetof(vertex_PCUsg, position));
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_PCUsg),
(const GLvoid*)offsetof(vertex_PCUsg, color));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_PCUsg),
(const GLvoid*)offsetof(vertex_PCUsg, uv));
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(vertex_PCUsg),
(const GLvoid*)offsetof(vertex_PCUsg, shift));
glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, sizeof(vertex_PCUsg),
(const GLvoid*)offsetof(vertex_PCUsg, gamma));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
}
void vertex_PCUsg::disable_attributes() noexcept
{
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
glDisableVertexAttribArray(4);
}
vertex_text2d::vertex_text2d(const float px, const float py, const float pz,
const float pw)
{
pos_and_texcoord[0] = px;
pos_and_texcoord[1] = py;
pos_and_texcoord[2] = pz;
pos_and_texcoord[3] = pw;
}
vertex_text2d::vertex_text2d(const vec4f& p)
{
pos_and_texcoord[0] = p.x;
pos_and_texcoord[1] = p.y;
pos_and_texcoord[2] = p.z;
pos_and_texcoord[3] = p.w;
}
vertex_text2d::vertex_text2d(const vec2f& pos, const vec2f& texcoord)
{
pos_and_texcoord[0] = pos.x;
pos_and_texcoord[1] = pos.y;
pos_and_texcoord[2] = texcoord.x;
pos_and_texcoord[3] = texcoord.y;
}
void vertex_text2d::enable_attributes() noexcept
{
glVertexAttribPointer(
0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_text2d),
(const GLvoid*)offsetof(vertex_text2d, pos_and_texcoord));
glEnableVertexAttribArray(0);
}
void vertex_text2d::disable_attributes() noexcept
{
glDisableVertexAttribArray(0);
}
std::ostream& operator<<(std::ostream& os, const vertex_P& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PC& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.color[0] << ", " << v.color[1] << ", " << v.color[2]
<< ", " << v.color[3] << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PU& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.uv[0] << ", " << v.uv[1] << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PCU& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.color[0] << ", " << v.color[1] << ", " << v.color[2]
<< ", " << v.color[3] << "], [" << v.uv[0] << ", " << v.uv[1] << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PUN& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.uv[0] << ", " << v.uv[1] << "], [" << v.normal[0] << ", "
<< v.normal[1] << ", " << v.normal[2] << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PCUN& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.color[0] << ", " << v.color[1] << ", " << v.color[2]
<< ", " << v.color[3] << "], [" << v.uv[0] << ", " << v.uv[1] << "], ["
<< v.normal[0] << ", " << v.normal[1] << ", " << v.normal[2] << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PUNTB& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.uv[0] << ", " << v.uv[1] << "], [" << v.normal[0] << ", "
<< v.normal[1] << ", " << v.normal[2] << "], [" << v.tangent[0] << ", "
<< v.tangent[1] << ", " << v.tangent[2] << "], [" << v.bitangent[0]
<< ", " << v.bitangent[1] << ", " << v.bitangent[2] << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PCUNTB& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.color[0] << ", " << v.color[1] << ", " << v.color[2]
<< ", " << v.color[3] << "], [" << v.uv[0] << ", " << v.uv[1] << "], ["
<< v.normal[0] << ", " << v.normal[1] << ", " << v.normal[2] << "], ["
<< v.tangent[0] << ", " << v.tangent[1] << ", " << v.tangent[2] << "], ["
<< v.bitangent[0] << ", " << v.bitangent[1] << ", " << v.bitangent[2]
<< ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_PCUsg& v)
{
os << '[' << v.position[0] << ", " << v.position[1] << ", " << v.position[2]
<< "], [" << v.color[0] << ", " << v.color[1] << ", " << v.color[2]
<< ", " << v.color[3] << "], [" << v.uv[0] << ", " << v.uv[1] << "], ["
<< v.shift << "], [" << v.gamma << ']';
return os;
}
std::ostream& operator<<(std::ostream& os, const vertex_text2d& v)
{
os << '[' << v.pos_and_texcoord[0] << ", " << v.pos_and_texcoord[1] << ", "
<< v.pos_and_texcoord[2] << ", " << v.pos_and_texcoord[3] << ']';
return os;
}
} // end of namespace OpenGL
} // end of namespace gintonic
| true |
a3a61304bfe990aa9311a505e4a032895fea3a4c | C++ | lasradoVinod/Practice | /RDP/points.cpp | UTF-8 | 1,723 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include "points.hpp"
#include <cmath>
points::points(preUnit xPos, preUnit yPos)
{
x = xPos;
y = yPos;
}
preUnit points::getX()
{
return x;
}
preUnit points::getY()
{
return y;
}
void points::getPoints(preUnit * const xPos, preUnit * const yPos )
{
*xPos = x;
*yPos = y;
}
preUnit points::perpDist(points start, points end)
{
preUnit A = x - start.getX();
preUnit B = y - start.getY(); // A and B are the vector representation of start and current point
preUnit C = end.getX() - start.getX();
preUnit D = end.getY() - start.getY(); // C and D are the vector representation of start and end point
preUnit dot = A * C + B * D; // dot product to find exactly where the point on the line segment lies
preUnit len_sq = C * C + D * D; // length of segment squared
preUnit param = -1;
if (len_sq != 0) //in case of 0 length line
param = dot / len_sq; // This is the portion of the segment at which the projection of the point is on the line
else
return -1;
preUnit xx, yy;
// if param is less than 0, it means that the projection is on the left side of line so the shortest dist is between start and point
if (param < 0) {
xx = start.getX();
yy = start.getY();
}
// on the other side
else if (param > 1) {
xx = end.getX();
yy = end.getY();
}
/*Where excatly on the line*/
else {
xx = start.getX() + param * C;
yy = start.getY() + param * D;
}
preUnit dx = x - xx;
preUnit dy = y - yy; //dx and dy is a vector representing the shortest line.
return std::sqrt(dx * dx + dy * dy);
}
void points::operator=(const points& p)
{
this->x = p.x;
this->y = p.y;
}
void points::display ()
{
std::cout << "x: " << x << " y: " << y << std::endl;
} | true |
041962123786eca9ef857a13914d7a31fb0eb27a | C++ | roice3/Magic120Cell | /geometryLib/gl/displayList.cpp | UTF-8 | 969 | 2.953125 | 3 | [
"MIT"
] | permissive | #include <stdafx.h>
#include "displayList.h"
CDisplayList::CDisplayList()
{
m_dl = (GLuint)-1;
}
CDisplayList::~CDisplayList()
{
clear();
}
// NOTE: We don't want to transfer control of our display list when copying or assigning.
CDisplayList::CDisplayList( const CDisplayList & )
{
m_dl = (GLuint)-1;
}
CDisplayList &
CDisplayList::operator = ( const CDisplayList & )
{
m_dl = (GLuint)-1;
return *this;
}
void
CDisplayList::start( bool execute )
{
if( !isRecorded() )
m_dl = glGenLists( 1 );
glNewList( m_dl, execute ? GL_COMPILE_AND_EXECUTE : GL_COMPILE );
}
void
CDisplayList::end() const
{
glEndList();
}
bool
CDisplayList::isRecorded() const
{
return -1 != m_dl;
}
bool
CDisplayList::call() const
{
if( isRecorded() )
{
glCallList( m_dl );
return true;
}
return false;
}
void
CDisplayList::clear()
{
// Delete the existing list if we need to.
if( isRecorded() )
{
glDeleteLists( m_dl, 1 );
m_dl = (GLuint)-1;
}
} | true |
0186c033d2818b52871c206fcfc7c6a2b5eb03ee | C++ | peizhang-cn/ComFluSoM | /Library/MLBM/MLBM.h | UTF-8 | 6,336 | 2.609375 | 3 | [] | no_license | #include "../HEADER.h"
#include <LBM.h>
class MLBM
{
public:
MLBM();
~MLBM();
MLBM(DnQm dnqm, CollisionModel cmodel, bool incompressible, int nx, int ny, int nz, double nu, double dc);
void Init(double rho0, double c0, Vector3d initV);
void Solve(int tt, int ts, int scale);
void WriteFileH5(int n, int scale);
LBM* DomF; // Domain of fluid
LBM* DomS; // Domain of scalar
};
inline MLBM::MLBM(DnQm dnqm, CollisionModel cmodel, bool incompressible, int nx, int ny, int nz, double nu, double dc)
{
DomF = new LBM(dnqm, cmodel, incompressible, nx, ny, nz, nu);
DomS = new LBM(dnqm, cmodel, incompressible, nx, ny, nz, dc);
}
inline void MLBM::Init(double rho0, double c0, Vector3d initV)
{
DomF->Init(rho0, initV);
DomS->InitCDE(c0, initV);
cout << "finish InitCDE" << endl;
DomS->V = DomF->V;
}
inline void MLBM::Solve(int tt, int ts, int scale)
{
for (int t=0; t<tt; ++t)
{
if (t%ts==0)
{
cout << "Time= " << t << endl;
WriteFileH5(t,scale);
}
DomF->CollideSRT();
DomS->CollideSRTCDE();
DomF->ApplyWall();
DomS->ApplyWall();
DomF->Stream();
DomS->Stream();
DomF->ApplyNoGradBC();
DomF->CalRhoV();
DomS->CalRho();
DomF->ApplyVelBC();
}
}
inline void MLBM::WriteFileH5(int n, int scale)
{
stringstream out; //convert int to string for file name.
out << setw(6) << setfill('0') << n;
string file_name_h5 = "MLBM"+out.str()+".h5";
H5File file(file_name_h5, H5F_ACC_TRUNC); //create a new hdf5 file.
hsize_t nx = (DomF->Nx+1)/scale;
hsize_t ny = (DomF->Ny+1)/scale;
hsize_t nz = (DomF->Nz+1)/scale;
int numLat = nx*ny*nz;
hsize_t dims_scalar[3] = {nx, ny, nz}; //create data space.
hsize_t dims_vector[4] = {nx, ny, nz, 3}; //create data space.
int rank_scalar = sizeof(dims_scalar) / sizeof(hsize_t);
int rank_vector = sizeof(dims_vector) / sizeof(hsize_t);
DataSpace *space_scalar = new DataSpace(rank_scalar, dims_scalar);
DataSpace *space_vector = new DataSpace(rank_vector, dims_vector);
double* rho_h5 = new double[numLat];
double* c_h5 = new double[numLat];
double* g_h5 = new double[numLat];
double* vel_h5 = new double[3*numLat];
int len = 0;
// #pragma omp parallel for schedule(static) num_threads(Nproc)
for (size_t k=0; k<nz; k++)
for (size_t j=0; j<ny; j++)
for (size_t i=0; i<nx; i++)
{
rho_h5[len] = 0.;
c_h5[len] = 0.;
g_h5[len] = 0.;
vel_h5[3*len ] = 0.;
vel_h5[3*len+1] = 0.;
vel_h5[3*len+2] = 0.;
int cout = 0;
for (int kk=0; kk<scale; kk++)
for (int jj=0; jj<scale; jj++)
for (int ii=0; ii<scale; ii++)
{
if (i+ii<=(size_t) DomF->Nx && j+jj<=(size_t) DomF->Ny && k+kk<=(size_t) DomF->Nz)
{
rho_h5[len] += DomF->Rho[i+ii][j+jj][k+kk];
c_h5[len] += DomS->Rho[i+ii][j+jj][k+kk];
g_h5[len] += DomF->G[i+ii][j+jj][k+kk][0];
vel_h5[3*len ] += DomF->V[i][j][k](0);
vel_h5[3*len+1] += DomF->V[i][j][k](1);
vel_h5[3*len+2] += DomF->V[i][j][k](2);
cout++;
}
}
rho_h5[len] /= (double) cout;
g_h5[len] /= (double) cout;
vel_h5[3*len ] /= (double) cout;
vel_h5[3*len+1] /= (double) cout;
vel_h5[3*len+2] /= (double) cout;
len++;
}
DataSet *dataset_rho = new DataSet(file.createDataSet("Density", PredType::NATIVE_DOUBLE, *space_scalar));
DataSet *dataset_c = new DataSet(file.createDataSet("Concentration", PredType::NATIVE_DOUBLE, *space_scalar));
DataSet *dataset_g = new DataSet(file.createDataSet("Gamma", PredType::NATIVE_DOUBLE, *space_scalar));
DataSet *dataset_vel = new DataSet(file.createDataSet("Velocity", PredType::NATIVE_DOUBLE, *space_vector));
dataset_rho->write(rho_h5, PredType::NATIVE_DOUBLE);
dataset_c->write(c_h5, PredType::NATIVE_DOUBLE);
dataset_g->write(g_h5, PredType::NATIVE_DOUBLE);
dataset_vel->write(vel_h5, PredType::NATIVE_DOUBLE);
delete space_scalar;
delete dataset_rho;
delete dataset_c;
delete dataset_g;
delete dataset_vel;
delete rho_h5;
delete c_h5;
delete g_h5;
delete vel_h5;
file.close();
string file_name_xmf = "MLBM_"+out.str()+".xmf";
std::ofstream oss;
oss.open(file_name_xmf);
oss << "<?xml version=\"1.0\" ?>\n";
oss << "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n";
oss << "<Xdmf Version=\"2.0\">\n";
oss << " <Domain>\n";
oss << " <Grid Name=\"LBM\" GridType=\"Uniform\">\n";
oss << " <Topology TopologyType=\"3DCoRectMesh\" Dimensions=\"" << nz << " " << ny << " " << nx << "\"/>\n";
oss << " <Geometry GeometryType=\"ORIGIN_DXDYDZ\">\n";
oss << " <DataItem Format=\"XML\" NumberType=\"Float\" Dimensions=\"3\"> 0.0 0.0 0.0\n";
oss << " </DataItem>\n";
oss << " <DataItem Format=\"XML\" NumberType=\"Float\" Dimensions=\"3\"> " << 1.0 << " " << 1.0 << " " << 1.0 << "\n";
oss << " </DataItem>\n";
oss << " </Geometry>\n";
oss << " <Attribute Name=\"Density\" AttributeType=\"Scalar\" Center=\"Node\">\n";
oss << " <DataItem Dimensions=\"" << nz << " " << ny << " " << nx << "\" NumberType=\"Float\" Precision=\"4\" Format=\"HDF\">\n";
oss << " " << file_name_h5 <<":/Density \n";
oss << " </DataItem>\n";
oss << " </Attribute>\n";
oss << " <Attribute Name=\"Concentration\" AttributeType=\"Scalar\" Center=\"Node\">\n";
oss << " <DataItem Dimensions=\"" << nz << " " << ny << " " << nx << "\" NumberType=\"Float\" Precision=\"4\" Format=\"HDF\">\n";
oss << " " << file_name_h5 <<":/Concentration \n";
oss << " </DataItem>\n";
oss << " </Attribute>\n";
oss << " <Attribute Name=\"Velocity\" AttributeType=\"Vector\" Center=\"Node\">\n";
oss << " <DataItem Dimensions=\"" << nz << " " << ny << " " << nx << " 3\" NumberType=\"Float\" Precision=\"4\" Format=\"HDF\">\n";
oss << " " << file_name_h5 <<":/Velocity \n";
oss << " </DataItem>\n";
oss << " </Attribute>\n";
oss << " <Attribute Name=\"Gamma\" AttributeType=\"Scalar\" Center=\"Node\">\n";
oss << " <DataItem Dimensions=\"" << nz << " " << ny << " " << nx << "\" NumberType=\"Float\" Precision=\"4\" Format=\"HDF\">\n";
oss << " " << file_name_h5 <<":/Gamma \n";
oss << " </DataItem>\n";
oss << " </Attribute>\n";
oss << " </Grid>\n";
oss << " </Domain>\n";
oss << "</Xdmf>\n";
oss.close();
} | true |
d3ab06d74b19a4e2bd9a6f16f2e23bceb622529c | C++ | animeshvaibhav/Dynamic-Programming | /LCS_usingIteration.cpp | UTF-8 | 990 | 3.34375 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
string s1,s2;
cout <<"Enter your first string : ";
cin>>s1;
cout<<"Enter your second string : ";
cin>>s2;
int m=s1.length();
int n=s2.length();
int M[m+1][n+1];
for(int i=0;i<=m;i++)
for(int j=0;j<=n;j++)
M[i][j]=0;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s1[i-1]==s2[j-1])
{
M[i][j]=1+M[i-1][j-1];
cout<<endl<<"Equal : "<<s1[i-1]<<" at i="<<i<<" and j= "<<j<<" Subsequence length :"<<M[i][j]<<endl;
}
else{
M[i][j] = max(M[i-1][j],M[i][j-1]);
}
}
}
cout<<endl<<"LCS Matrix : "<<endl<<endl;
for(int i=0;i<=m;i++)
{for(int j=0;j<=n;j++)
cout<<M[i][j]<<" ";
cout<<endl;}
cout<<endl<<"Length of longest common subsequence is : "<<M[m][n]<<endl;
return 0;
}
| true |
c916eb4241f48cf7aae8793a1669abe69ff1b98e | C++ | hoboaki/oldcode | /textga/textga_cpplib/trunk/include/textga/tag/AbstractElement.hpp | SHIFT_JIS | 882 | 3.046875 | 3 | [] | no_license | /**
* @file
* @brief Element̒ۃNXLqB
*/
#pragma once
//------------------------------------------------------------
#include <textga/tag/IElement.hpp>
//------------------------------------------------------------
namespace textga {
namespace tag {
/**
* @brief Element̒ۃNXB
* Õ|C^Ɨvf̎ނێB
*/
class AbstractElement : public IElement
{
public:
AbstractElement( const char* name , ElementKind kind );
virtual ~AbstractElement();
// IElement
virtual const char* name()const;
virtual ElementKind elementKind()const;
private:
const char* const name_;
const ElementKind elementKind_;
};
}}
//------------------------------------------------------------
// EOF
| true |
572ca93a8c65f7d827a0b568d8d69f2b10f7c981 | C++ | akramsameer/Problems | /Codeforces/IQ test.cpp | UTF-8 | 721 | 2.703125 | 3 | [] | no_license | //============================================================================
// Name : Working.cpp
// Author : Akram
// Version :
// Copyright : Your copyright notice
// Description : Code c++
//============================================================================
#include <iostream>
using namespace std;
int n , arr[101];
int main() {
cin >> n ;
for (int i = 0; i < n; ++i) {
cin>> arr[i];
}
int lstodd = 0 , lsteven = 0 , cntodd = 0, cnteven = 0;
for (int k = 0; k < n; ++k) {
if((arr[k] & 1) == 0){
cnteven++;
lsteven = k;
}
else{
cntodd++;
lstodd = k;
}
}
if(cntodd > cnteven){
cout<<lsteven +1 <<endl;
}else{
cout << lstodd +1 <<endl;
}
return 0;
}
| true |
c8013220ccda6840b556db1501b7a4352dee23cc | C++ | rahuls98/cpp-ladder | /Data-Structures/Linked-List/node_int_data_frequency.cpp | UTF-8 | 1,524 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include <unordered_map>
std::unordered_map<int, int> frequency = {};
class Node {
public:
int data;
Node* next;
Node(int data, Node* next){
this->data = data;
this->next = next;
}
};
void traverse(Node** head_ptr) {
Node* temp = (*head_ptr);
while(temp != NULL) {
if(frequency[temp->data] == 0)
frequency[temp->data]=1;
else
frequency[temp->data] += 1;
temp = temp->next;
}
std::cout<<"{ ";
for(auto x: frequency) { std::cout<<x.first<<": "<<x.second<<" "; }
std::cout<<" }"<<std::endl;
}
void print(Node** head_ref) {
Node* temp = (*head_ref);
while(temp != NULL) {
std::cout<<temp->data<<" ";
temp = temp->next;
}
std::cout<<std::endl;
}
void deleteList(Node** head_ptr) {
Node* temp = (*head_ptr);
Node* curr = temp;
while(curr != NULL) {
curr = temp->next;
delete temp;
temp = curr;
}
}
int main() {
Node* last = new Node(50, NULL);
Node* sixth = new Node(40, last);
Node* fifth = new Node(20, sixth);
Node* fourth = new Node(10, fifth);
Node* third = new Node(30, fourth);
Node* second = new Node(20, third);
Node* head = new Node(10, second);
traverse(&head); // { 50: 1 40: 1 30: 1 20: 2 10: 2 }
std::cout<<"\nFrequency of 20: "<<frequency[20]<<std::endl; // Frequency of 20: 2
deleteList(&head); print(&head); // Segmentation fault: 11
return 0;
} | true |
6de355e466c07072f247306233a23a9e6f871a2d | C++ | RaphPich/gimenezpichonwernerxanh | /src/shared/state/Entite.cpp | UTF-8 | 1,003 | 3 | 3 | [] | no_license | #include "Entite.h"
using namespace state;
Entite :: Entite(Caracteristiques& caracteristiques, Position& position,
std::string& nom){
this->caracteristiques = caracteristiques;
this->position = position;
this->nom = nom;
//this->tileCode ;
}
Entite::Entite()
{
nom = "";
position.setX(0);
position.setY(0);
Caracteristiques car{0,0,0,0,0};
caracteristiques = car;
}
Entite :: ~Entite(){}
Caracteristiques& Entite :: getCaracteristiques() {
return this->caracteristiques;
}
void Entite ::setCaracteristiques( Caracteristiques caracteristiques){
this->caracteristiques = caracteristiques;
}
Position& Entite :: getPosition() {
return this->position;
}
void Entite :: setPosition(Position position){
this->position = position;
}
std::string Entite :: getNom() {
return this->nom;
}
void Entite ::setNom(std::string nom){
this->nom = nom;
}
void Entite ::setTileCode(int p_tileCode){
this->tileCode = p_tileCode;
}
int Entite ::getTileCode(){
return this->tileCode;
}
| true |
f429b48940c299daf1d0b8301d527cf5b6b6b644 | C++ | IdarV/Arduino | /Exam03/snake/sdreader.cpp | UTF-8 | 1,077 | 2.671875 | 3 | [] | no_license | #include "sdreader.h"
#define highscorefile_str "A.TXT"
#define notsd_str "!sd"
#define sd_str "sd"
#define nofile_str "no file"
#define file_str "file"
// Initialize sd card
void SDReader::init(int cspin){
if(!SD.begin(cspin)){
Serial.println(notsd_str);
} else{
Serial.println(sd_str);
}
}
// Reads highscore from SD card
uint8_t SDReader::readHighscore(){
// Open the file
highFile = SD.open(highscorefile_str);
uint8_t high = 0;
// Readt the first int from file
if(highFile) {
Serial.println(file_str);
if (highFile.available()) {
high = (uint8_t) highFile.parseInt();
}
highFile.close();
} else{
Serial.println(nofile_str);
}
return high;
}
// Write highscore to file
void SDReader::setHighscore(uint8_t highscore){
// Remove existing file
SD.remove(highscorefile_str);
// Open (create) file again
highFile = SD.open(highscorefile_str, FILE_WRITE);
// Write highscore to it
if(highFile) {
highFile.println((int)highscore);
highFile.close();
} else{
Serial.println(nofile_str);
}
}
| true |
68941b6b1bb652af4a36ff8d3d2ac9aed9f11012 | C++ | jmrocco/Word-Fragment-Organizer | /Message.cpp | UTF-8 | 3,770 | 3.578125 | 4 | [] | no_license | //============================================================================
// Name : Message.cpp
// Author : Juliette Rocco
// Description : Message Ordering
//============================================================================
#include <iostream>
#include "Message.h"
#ifndef MARMOSET_TESTING
int main();
#endif
#ifndef MARMOSET_TESTING
int main() {
Message one;
int input{0};
std::string frag;
while (input != -2)
{
//takes input
std::cin >> input;
//inserts the word fragments as recieved and orders them
if (input >= 0)
{
std::cin >> frag;
one.insert(input,frag);
}
//would print the message so far recieved
if (input == -1)
{
one.print_message();
}
}
std::cout <<"end";
return 0;
}
#endif
//node constructor
Message::Message()
{
head=nullptr;
}
//node deconstructor
Message::~Message()
{
Node *p_head{head};
//deconstructs the nodes
while (p_head != nullptr)
{
Node *temp_node{p_head};
p_head = p_head->p_next;
delete temp_node;
}
delete p_head;
p_head = nullptr;
}
//inserts a node into the list and orders it
void Message::insert( unsigned int id, std::string fragment)
{
//if its going to be the head of the node
if (head == nullptr)
{
head = new Node(id,fragment);
head->p_next = nullptr;
}
//inserts the node in the proper location
else if (id < head->identifier)
{
Node *temp_node{new Node(id,fragment)};
temp_node->p_next= head;
head = temp_node;
}
//assings temp nodes to move things around
else
{
Node *p_head{head};
Node *next{p_head->p_next};
while(next != nullptr && next->identifier<id )
{
p_head = next;
next = next->p_next;
}
Node *temp_node_2{new Node(id, fragment)};
temp_node_2->p_next = next;
p_head->p_next = temp_node_2;
}
}
//prints the message so far recieved
void Message::print_message()
{
unsigned int counter{0};
Node *temp_node = head;
for(Node *p_head{head}; p_head != nullptr; p_head = p_head->get_next())
{
temp_node = p_head;
//prints dots
for(unsigned int count{0}; count < (p_head->identifier - counter); ++count )
{
std::cout <<"... ";
}
//prints EOT if the entire fragment hasn't been recieved yet
if (p_head->get_fragment() != "EOT")
{
std::cout << p_head->get_fragment() << " ";
}
counter = (p_head->identifier ) + 1;
}
//missing fragment
if (temp_node == nullptr || temp_node->fragment != "EOT")
{
std::cout <<"???";
}
std::cout<< std::endl;
}
//constructs the node
Node::Node(unsigned int id, std::string frag )
{
identifier = id;
fragment = frag;
p_next = nullptr;
}
//gets the next node
Node *Node::get_next()
{
return p_next;
}
//returns the word fragment
std::string Node::get_fragment()
{
return fragment;
}
| true |
d40a8bc682dd600137be4eab5ec8c6f1461f5557 | C++ | honeytavis/cpp | /Cpp_Primer/5rd/0320/oriented_obj_thread_poll/src/ThreadPool.cc | UTF-8 | 1,224 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "ThreadPool.h"
#include "WorkThread.h"
#include "Task.h"
#include <unistd.h>
#include <stdlib.h>
ThreadPool::ThreadPool(int threadNum, int bufSize)
: _active(true)
, _threadNum(threadNum)
, _bufSize(bufSize)
, _buf(_bufSize)
{
_vecThreads.reserve(_threadNum);
}
ThreadPool::~ThreadPool()
{
if (_active)
{
stop();
}
}
void ThreadPool::start()
{
for (int idx = 0; idx < _threadNum; ++idx) {
Thread* pThread = new WordThread(*this);
_vecThreads.push_back(pThread);
}
std::vector<Thread*>::iterator it;
for (it = _vecThreads.begin(); it != _vecThreads.end(); ++it) {
(*it)->create();
}
}
void ThreadPool::stop()
{
if (_active) {
while (!_buf.empty()) {
sleep(1);
}
_active = false;
_buf.wakeup_empty();
std::vector<Thread*>::iterator it;
for (it = _vecThreads.begin(); it != _vecThreads.end(); ++it) {
(*it)->join();
delete (*it);
}
_vecThreads.clear();
}
}
void ThreadPool::addTask(Task* pTask)
{
_buf.push(pTask);
}
Task* ThreadPool::getTask()
{
return _buf.pop();
}
void ThreadPool::threadFunc()
{
while(_active) {
Task* pTask = getTask();
if (pTask) {
pTask->process();
}
}
}
| true |
b4820853583274ce1bb84c7bac41e81a647282ed | C++ | jiangyinzuo/icpc | /search/bfs/catch_that_cow.cpp | UTF-8 | 1,374 | 2.84375 | 3 | [] | no_license | #include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int s, e;
bool visited[100002] = {false};
struct Step{
int location;
int count;
};
queue<Step> q;
void bfs()
{
Step step;
step.location = s;
step.count = 0;
q.push(step);
visited[step.location] = true;
while(!q.empty()){
step = q.front();
q.pop();
if(step.location == e) {printf("%d\n", step.count); return;}
++step.count;
if (step.location > e) {
--step.location;
q.push(step);
continue;
}
++step.location;
if(step.location <= 100000 && !visited[step.location]){
q.push(step);
visited[step.location] = true;
}
step.location-=2;
if(step.location>0 && !visited[step.location]){
q.push(step);
visited[step.location] = true;
}
step.location = (step.location + 1)*2;
if(step.location > 0 && step.location <= 100000 && !visited[step.location]){
q.push(step);
visited[step.location] = true;
}
}
}
int main()
{
while(~scanf("%d %d", &s, &e)){
memset(visited, 0, sizeof(visited));
while(!q.empty()) q.pop();
if(e<=s) printf("%d\n", s-e);
else bfs();
}
return 0;
} | true |
0cf474f7348e9fdd82d8d965281d149c5c59cb42 | C++ | MRYoungITO/CPP_Learning | /Definition_Of_Pointers/指针的自减/指针的自减.cpp | GB18030 | 549 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char input[128];
int len;
char tmp;
scanf_s("%s", input, 128);
len = strlen(input);
//1
/*
for(int i=0; i<len/2; i++) {
tmp = input[len-i-1];
input[len-i-1] = input[i];
input[i] = tmp;
}
printf("%s\n", input);
*/
//2
/*
for(int i=0; i<len; i++) {
printf("%c", input[len-i-1]);
}
printf("\n");
*/
//3
char *p = &input[len-1];
for(int i=0; i<len; i++) {
printf("%c", *p--);
}
printf("\n");
system("pause");
return 0;
} | true |
fcae44b12de5be1fc7e5d5b65f50461019072786 | C++ | utkarsh235/CPP-Programming | /Filehandling4.cpp | UTF-8 | 317 | 2.953125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
using namespace std;
class name
{
int a,b,c;
public :
void get()
{
ifstream if2;
if2.open("myfile.txt");
char b;
while(if2.eof())
{
b = if2.get();
cout << b ;
}
if2.close();
}
} ;
int main()
{
name n1;
n1.get();
return 0 ;
}
| true |
5829c1a5b78ce93466c2c39164b0ed1cab2bc864 | C++ | delphix/bpftrace | /src/ast/pass_manager.h | UTF-8 | 1,825 | 3 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace bpftrace {
class BPFtrace;
namespace ast {
class Node;
class SemanticAnalyser;
class Pass;
/**
Result of a pass run
*/
class PassResult
{
public:
static PassResult Error(const std::string &msg);
static PassResult Success(Node *root = nullptr);
// Ok returns whether the pass was successful or not
bool Ok() const
{
return success_;
};
// Error returns the error generated by the pass, if any.
const std::string &Error()
{
return error_;
};
Node *Root() const
{
return root_;
};
private:
bool success_;
std::string error_;
Node *root_ = nullptr;
};
/**
Context/config for passes
Note: Most state should end up in the BPFtrace class instead of here
*/
struct PassContext
{
public:
PassContext(BPFtrace &b) : b(b){};
BPFtrace &b;
private:
// As semantic pass and map creation are separate passes we need this
SemanticAnalyser *semant;
// Only ones allowed to access semant
friend Pass CreateSemanticPass();
friend Pass CreateMapCreatePass();
};
using PassFPtr = std::function<PassResult(Node &, PassContext &)>;
/*
Base pass
*/
class Pass
{
public:
Pass() = delete;
Pass(std::string name, PassFPtr fn) : fn_(fn), name(name){};
virtual ~Pass() = default;
PassResult Run(Node &root, PassContext &ctx)
{
return fn_(root, ctx);
};
private:
PassFPtr fn_;
public:
std::string name;
};
class PassManager
{
public:
PassManager() = default;
void AddPass(Pass p);
[[nodiscard]] std::unique_ptr<Node> Run(std::unique_ptr<Node> n,
PassContext &ctx);
private:
std::vector<Pass> passes_;
};
} // namespace ast
} // namespace bpftrace
| true |
1d0d2a2922b112593032e036967feadf9b45927f | C++ | i20/raytracer | /headers/Vector.hpp | UTF-8 | 883 | 2.859375 | 3 | [] | no_license | #ifndef _VECTOR_HPP
#define _VECTOR_HPP
#include <cstdint>
class Point;
//__device__
class Vector {
private:
float v[4];
public:
static const Vector X;
static const Vector Y;
static const Vector Z;
Vector() = default;
Vector(const float x, const float y, const float z);
Vector(const Point & a, const Point & b);
float & operator[] (const uint8_t i);
const float & operator[] (const uint8_t i) const;
Vector normalize() const;
float get_norm() const;
Vector operator^(const Vector & vector) const;
float operator*(const Vector & vector) const;
Vector operator+(const Vector & vector) const;
Vector operator-(const Vector & vector) const;
Vector operator*(const float e) const;
Vector operator/(const float e) const;
};
#endif
| true |
7213b76224d20158966343fb614e6531e5bece6b | C++ | JJ-ing/osPro | /TASK1/CopyByProcesses/main.cpp | UTF-8 | 2,884 | 2.578125 | 3 | [] | no_license |
#include "head.h"
int main() {
//申请共享内存,创建信号灯并初始化
int shareMemIdA = shmget(KEY_SHARE_MEM_A, sizeof(struct ShareM),IPC_CREAT|0666);
int shareMemIdB = shmget(KEY_SHARE_MEM_B, sizeof(struct ShareM),IPC_CREAT|0666);
int semId = semget(KEY_LIGHT, 4, IPC_CREAT|0666);
if(semId==-1){
printf("SemGet error!");
exit(-1);
}
union semun value;
value.val = 1; //semiId[0] BufA是否可写
if(semctl(semId, 0, SETVAL, value)==-1){
printf("SemCtl error!");
exit(-1);
}
value.val = 0; //semiId[1] BufA是否可读
if(semctl(semId, 1, SETVAL, value)==-1){
printf("SemCtl error!");
exit(-1);
}
value.val = 1; //semiId[2] BufB是否可写
if(semctl(semId, 2, SETVAL, value)==-1){
printf("SemCtl error!");
exit(-1);
}
value.val = 0; //semiId[3] BufB是否可读
if(semctl(semId, 3, SETVAL, value)==-1){
printf("SemCtl error!");
exit(-1);
}
//文件路径
char source_file_path[100];
char destination_file_path[100];
scanf("%s", source_file_path);
scanf("%s", destination_file_path);
//尝试打开文件
int source_fd, destination_fd;
if((source_fd=open(source_file_path,O_RDONLY))==-1){
fprintf(stderr, "Open\'%s\'Error:%s\n", source_file_path, strerror(errno));
return -1;
}
close(source_fd);
if((destination_fd=open(destination_file_path, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR))==-1){
fprintf(stderr, "Open\'%s\'Error:%s\n", destination_file_path, strerror(errno));
return -1;
}
close(destination_fd);
//创建文件誊写子进程
pid_t pid_s_a, pid_a_b, pid_b_d;
int status_s_a, status_a_b, status_b_d;
if((pid_s_a=fork())==0){
//process from source to bufA
char * argv[] = {(char *)"f1", source_file_path, destination_file_path, nullptr};
execv("./f1", argv);
printf("fork1 error!\n");
}
else if((pid_a_b=fork())==0){
//process from bufA to bufB
char * argv[] = {(char *)"f2", source_file_path, destination_file_path, nullptr};
execv("./f2", argv);
printf("fork2 error!\n");
}
else if((pid_b_d=fork())==0){
//process from bufB to destination
char * argv[] = {(char *)"f3", source_file_path, destination_file_path, nullptr};
execv("./f3", argv);
printf("fork3 error!\n");
}
//等待子进程结束
waitpid(pid_s_a, &status_s_a, 0);
waitpid(pid_a_b, &status_a_b, 0);
waitpid(pid_b_d, &status_b_d, 0);
//释放信号灯
if(semctl(semId, 0, IPC_RMID)==-1){
printf("semCtl:%s\n", strerror(errno));
exit(-1);
}
//回收共享内存
shmctl(shareMemIdA, IPC_RMID, 0);
shmctl(shareMemIdB, IPC_RMID, 0);
return 0;
}
| true |
5742b1e12c5968d3e149c6023a0324601a1c2fc2 | C++ | erfenjiao/test01 | /练习/class.cpp | UTF-8 | 1,318 | 3.703125 | 4 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
class Cube
{
public:
void setL(int L)
{
m_L = L;
}
int getL()
{
return m_L;
}
void setW(int W)
{
m_W = W;
}
int getW()
{
return m_W;
}
void setH(int H)
{
m_H = H;
}
int getH()
{
return m_H;
}
int calculateS()
{
return 2*m_L*m_W + 2*m_L*m_H + 2*m_W*m_H;
}
int calculateV()
{
return m_L*m_H*m_W;
}
bool isSame(Cube &c)
{
if(m_H == c.getH() && m_L == c.getL() && m_W == c.getW())
{
return true;
}
return false;
}
private:
int m_L;
int m_W;
int m_H;
} ;
//
//bool isSame(Cube &c1 , Cube &c2)
//{
// if(c1.getL() == c2.getL() && c1.getH()==c2.getH() && c1.getW()==c2.getW())
// {
// return true;
// }
// return false ;
//}
int main()
{
Cube c1;
c1.setL(10);
c1.setH(10);
c1.setW(10);
cout << "c1 's area = " << c1.calculateS() << endl;
cout << "c1 's volume = " << c1.calculateV() << endl;
Cube c2;
c2.setL(10);
c2.setH(10);
c2.setW(11);
int ret = c1.isSame(c2);
if(ret)
{
cout << "c1 && c2 is same" << endl;
}
else
{
cout << "c1 && c2 is not same" << endl;
}
// if(isSame(c1,c2))
// {
// cout << "c1 && c2 is same" << endl;
// }
// else
// {
// cout << "c1 && c2 is not same" << endl;
// }
}
| true |
cd6218d8d841448e04cda3afcfffc9f331d3b5d8 | C++ | shoumique/ai_codes | /dijkstra.cpp | UTF-8 | 3,650 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<vector>
using namespace std;
#define SIZE 100
struct Priority_Queue
{
int node, dis;
bool flag;
} Q[SIZE];
struct node
{
int n, weight;
};
vector<node> adj[SIZE];
int node, edge;
int parent[SIZE];
int dis[SIZE];
int pop()
{
int min = 10000, index = -1;
for(int i = 0; i<node; i++)
{
if(Q[i].dis < min && Q[i].flag == true)
{
min = Q[i].dis;
index = i;
}
}
Q[index].flag = false;
return index;
}
bool isEmpty()
{
//bool flag = true;
for(int i = 0; i < node; i++)
{
if(Q[i].flag == true) // our goal is to find if any node's flag is set to true
return false; // Bcz it will mean there is still a node in the queue
// if we find a node which flag is set to true
// we immediately terminate and return the value
}
return true; // So if the queue is empty this function will return yes (true)
}
void init_Priority_Queue()
{
for(int i = 0; i < node; i++)
{
Q[i].node = i;
Q[i].dis = 9999;
Q[i].flag = true;
dis[i] = 9999;
parent[i] = -1;
}
}
void Dijkstra(int source)
{
cout << "Dijkstra Starts" << endl;
init_Priority_Queue();
dis[source] = 0;
Q[source].dis = 0;
while(isEmpty() != 1)
{
// cout << isEmpty() << endl;
int u = pop();
u = Q[u].node;
cout << "First pop: " << u << endl;
//cout << "Neighbour Size: " << adj[u].size() << endl;
for(int i = 0; i < adj[u].size(); i++)
{
struct node temp;
temp = adj[u][i];
int v = temp.n;
int weight = temp.weight;
if(dis[v] > (dis[u] + weight))
{
dis[v] = dis[u] + weight;
//cout << v << " ";
parent[v] = u;
Q[v].dis = dis[v]; // Updating the priority queue
//cout << Q[v].dis << endl;
}
}
}
}
void printPathUtil(int source, int j)
{
if (parent[j] == -1)
return;
printPathUtil(source, parent[j]);
cout << "->" << j;
}
void printPath(int source)
{
int des;
cout << "source is NODE: " << source << endl;
cout << "Input destination: ";
cin >> des;
cout << endl;
cout << source;
printPathUtil(source, des);
cout << endl;
}
void Graph()
{
int u, v, w, source;
//struct node* temp;
//cout << "Enter number of nodes and edges: ";
//cin >> node >> edge;
//cout << endl;
ifstream infile;
infile.open("dijkstra.txt");
infile >> node >> edge;
for(int i = 0; i < edge; i++)
{
struct node temp;
infile >> u >> v >> w;
//infile >> v;
//infile >> w;
temp.n = v;
temp.weight = w;
adj[u].push_back({v,w});
adj[v].push_back({u,w});
//adj[u].push_back(temp);
}
for(int i = 0; i < node; i++)
{
cout << i;
for(int j = 0; j < adj[i].size(); j++)
{
struct node temp;
temp = adj[i][j];
cout << "->" << temp.n;
}
cout << endl;
}
infile.close();
}
int main()
{
int source;
Graph();
cout << endl;
cout << "Input source: ";
cin >> source;
Dijkstra(source);
cout << endl;
printPath(source);
for(int i = 0; i < node; i++)
cout << "Node cost from source: node[" << i << "] : " << dis[i] << endl;
return 0;
}
| true |
10d4aaacfa67c502eb75e24317bcb82b401558c0 | C++ | BaiGang/codeplex-archived-vrthesis-2010 | /Utils/math/ConvexHull2D.cpp | GB18030 | 4,494 | 2.875 | 3 | [] | no_license | #include "ConvexHull2D.h"
#include <iostream>
ConvexHull2D::ConvexHull2D(void)
{
}
ConvexHull2D::~ConvexHull2D()
{
}
ConvexHull2D::ConvexHull2D(PT2DVEC pts)
{
this->BuildConvexHull(pts);
}
void ConvexHull2D::BuildConvexHull(PT2DVEC pts)
{
int i,j,k=0,top=2;
Point2D tmp;
int inlen;
inlen = pts.size();
Point2D* ch;
ch = new Point2D[inlen];
ur.x = pts[0].x;
ur.y = pts[0].y;
ll.x = pts[0].x;
//ѡȡPointSetyСĵPointSet[k]ĵжȡߵһ
for(i=1;i<inlen;i++)
{
if((pts[i].y<pts[k].y)
||((pts[i].y==pts[k].y)&&(pts[i].x<pts[k].x)))
k=i;
if(pts[i].x>ur.x)
ur.x = pts[i].x;
if(pts[i].y>ur.y)
ur.y = pts[i].y;
if(pts[i].x<ll.x)
ll.x = pts[i].x;
}
ll.y=pts[k].y;
tmp=pts[0];
pts[0]=pts[k];
pts[k]=tmp; //PointSetyСĵPointSet[0]
for(i=1;i<inlen-1;i++) //Զ㰴PointSet[0]ļǴСͬİվPointSet[0]ӽԶ
{
k=i;
for(j=i+1;j<inlen;j++)
if((Multiply(pts[j],pts[k],pts[0])>0)||((Multiply(pts[j],pts[k],pts[0])==0)&&(Distance(pts[0],pts[j])<Distance(pts[0],pts[k]))))
k=j;
tmp=pts[i];
pts[i]=pts[k];
pts[k]=tmp;
}
// ϵĴ뽫㼯ʱ
//std::cout << pts.size() << endl;
//for ( int i = 0; i < pts.size(); i++ )
//{
// std::cout << pts[i].x << " " << pts[i].y << endl;
//}
*ch=pts[0];
*(ch+1)=pts[1];
*(ch+2)=pts[2];
//for ( int i = 0; i < top; i++ )
// std::cout << (ch+i)->x << (ch+i)->y << endl;
//std::cout << top << endl;
for(i=3;i<inlen;i++)
{
//std::cout << i << " " << top << " " << Multiply(pts[i],*(ch+top),*(ch+top-1)) << endl;
while( top > 0 && Multiply(pts[i],*(ch+top),*(ch+top-1)) >= 0 )
{
//if ( i == 3 )
// std::cout << Multiply(pts[i],*(ch+top),*(ch+top-1)) << endl;
//if ( i == 3 && Multiply(pts[i],*(ch+top),*(ch+top-1))>= 0 )
// //cout << ">0" << endl;
// cout << pts[i].x << " " << pts[i].y << " "
// << (ch+top)->x << " " << (ch+top)->y << " "
// << (ch+top-1)->x << " " << (ch+top-1)->y << endl;
// std::cout << "11" << endl;
top--;
}
*(ch+top+1)=pts[i];
top++;
}
//std::cout << top << endl;
for(i=0;i<=top;i++)
{
m_cvPoint.push_back(*(ch+i));
}
delete[] ch;
}
int ConvexHull2D::Multiply(Point2D p1,Point2D p2,Point2D p0)
{
double p = ((p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y));
if ( p > 0 )
return 1;
else if ( p < 0 )
return -1;
//std::cout << p << endl;
return 0;
}
int ConvexHull2D::Dot(Point2D p1,Point2D p2,Point2D p0)
{
double p = ((p1.x-p0.x)*(p2.x-p0.x)+(p2.y-p0.y)*(p1.y-p0.y));
if ( p > 0 )
return 1;
else if ( p < 0 )
return -1;
//std::cout << p << endl;
return 0;
}
float ConvexHull2D::Distance(Point2D p1,Point2D p2)
{
return(sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)));
}
PT2DVEC& ConvexHull2D::GetConvexHullPoints()
{
return m_cvPoint;
}
bool ConvexHull2D::IfInConvexHull(float x, float y)
{
bool res = true;
//һΣÿһ߶2DĻֳΪߣÿһߵĵһ˵ҪԵĵõһʸv
//2άʸչ3άģȻñvˣжϽ3άʸZķǷ仯
//ƵǷ⡣Ҫעǣζ㾿ԾжϷʽӰ졣
float z;
Point2D pt;
pt.x = x;
pt.y = y;
int ptIndex1, ptIndex2;
if (m_cvPoint.size() == 0)
{
return res;
}
else if ( m_cvPoint.size() == 2 )
{
int r = Multiply(m_cvPoint[0], pt, m_cvPoint[1]);
if ( r == 0 && Dot(m_cvPoint[0], m_cvPoint[1], pt ) <= 0 )
{
res = true;
}
else
res = false;
return res;
}
for (int i=0; i<m_cvPoint.size(); i++)
{
ptIndex1 = i;
ptIndex2 = i+1;
if (ptIndex2 == m_cvPoint.size())
{
ptIndex2 = 0;
}
z = Multiply(m_cvPoint[ptIndex2], pt, m_cvPoint[ptIndex1]);
if (z < 0)
{
res = false;
break;
}
}
return res;
}
void ConvexHull2D::GetBoundingBox(float& xMin, float& xMax, float& yMin, float& yMax)
{
xMin = ll.x;
xMax = ur.x;
yMin = ll.y;
yMax = ur.y;
} | true |
4c0a84d4f2648174ba2b565cd79dd9aa913b6b71 | C++ | lhuyuel/LC_CPP | /LC297_Serialize-and-Deserialize-Binary-Tree/solution.cpp | UTF-8 | 1,402 | 3.578125 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string result = "";
queue<TreeNode*> toVisit;
toVisit.push(root);
while (!toVisit.empty()) {
TreeNode *tmp = toVisit.front();
toVisit.pop();
if (tmp) {
result += (to_string(tmp->val) + " ");
toVisit.push(tmp->left);
toVisit.push(tmp->right);
}
else {
result += "null ";
}
}
return result;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<TreeNode*> nodes;
istringstream in(data);
string tmp;
while (in >> tmp) {
if (tmp != "null") nodes.push_back(new TreeNode(stoi(tmp)));
else nodes.push_back(nullptr);
}
int cur = 0, i = 1;
while (i < nodes.size()) {
if (nodes[cur]) {
nodes[cur]->left = nodes[i++];
if (i < nodes.size())
nodes[cur]->right = nodes[i++];
}
++cur;
}
return nodes[0];
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root)); | true |
f3823fca680172a9e5c767c8a899e29f5b74df86 | C++ | Noctivagus19/8INF259_Lab1 | /Data_structure_travail1/Dossier.cpp | ISO-8859-1 | 11,436 | 3.21875 | 3 | [] | no_license | //
// Dvelopp par:
// Jean-Michel Plourde PLOJ07029207
// Jean-Pilippe Lapointe LAPJ16078607
//
#include "Dossier.h"
#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
#define NOMPROF 0
#define ANCIENETE 1
#define COURS 2
#define ETUDIANTS 3
//Variable qui substitue un retour de pointeur null pour les fonctions qui retournent un pointeur
static string vide = "*** La liste est vide ***";
//Constructeur
DossierProfesseur::DossierProfesseur(char* FP)
{
/* Variables Cours */
teteCours = nullptr;
/* Variables Etudiant */
teteEtudiant = nullptr;
/* Variables Professeur*/
teteProf = nullptr;
string nomProf;
int ancienProf = 0;
ifstream dataSource(FP);
if (dataSource)
{
string ligne;
int curseur = 0;
while (getline(dataSource, ligne))
{
switch (curseur) //Structure de sparation des donnes pour la cration des structures
{
case NOMPROF:
{
nomProf = ligne;
curseur++;
break;
}
case ANCIENETE:
{
ancienProf = atoi(ligne.c_str());
curseur++;
break;
}
case COURS:
{
if (ligne[0] == '&')
{
curseur++;
goto labelFin;
}
Cours *c = new Cours();
c->sigle = new string();
*c->sigle = ligne;
c->suivant = teteCours;
teteCours = c;
labelFin:
break;
}
case ETUDIANTS:
{
if (ligne[0] == '&')
{
curseur++;
goto labelFin2;
}
Etudiant *e = new Etudiant();
e->nom = new string();
*e->nom = ligne;
e->suivant = teteEtudiant;
teteEtudiant = e;
break;
labelFin2:
curseur = 0;
Professeur *p = new Professeur();
p->nom = new string();
*p->nom = nomProf;
p->ancien = new int();
*p->ancien = ancienProf;
p->listeCours = teteCours;
p->listeEtudiants = teteEtudiant;
p->suivant = teteProf;
teteProf = p;
teteCours = nullptr;
teteEtudiant = nullptr;
break;
}
}
}
dataSource.close();
}
}
DossierProfesseur::~DossierProfesseur()
{
Professeur *next = teteProf;
while (next)
{
Cours *c = next->listeCours;
while (c)
{
Cours *deleteMe = c;
c = c->suivant;
delete deleteMe;
}
Etudiant *e = next->listeEtudiants;
while (e)
{
Etudiant *deleteMe = e;
e = e->suivant;
delete deleteMe;
}
Professeur *deleteMe = next;
next = next->suivant;
delete deleteMe;
}
}
void DossierProfesseur::afficherListe()
{
Professeur *p = teteProf;
if (p)
{
while (p)
{
Cours *c = p->listeCours;
Etudiant *e = p->listeEtudiants;
std::cout << *p->nom << "\n";
std::cout << "Anciennete: " << *p->ancien << "\nCours enseignes: ";
if (c != nullptr)
{
std::cout << "\n";
while (c)
{
std::cout << *c->sigle << "\n";
c = c->suivant;
}
}
else
{
std::cout << "Ce professeur n'a aucun cours!\n";
}
std::cout << "Etudiants: ";
if (e != nullptr) {
std::cout << "\n";
while (e != nullptr)
{
std::cout << *e->nom << "\n";
e = e->suivant;
}
}
else
{
std::cout << "Ce professeur n'a aucun etudiant!\n";
}
std::cout << "\n";
p = p->suivant;
}
}
else
{
std::cout << "Il n'y a aucun professeur a afficher!\n";
}
}
// Excuter les commandes prsentes dans FT.txt
void DossierProfesseur::executerCommandes(char* FP, char* FT)
{
ifstream dataSource(FT);
if (dataSource.is_open())
{
string line;
string cmdOperator;
string cmdParam;
string startDelim = "[";
string stopDelim = "]";
unsigned firstDelimPos;
unsigned endPosDelim;
unsigned lastDelimPos;
while (getline(dataSource, line))
{
/* Operator extraction */
cmdOperator = line.substr(0, 1);
/* Operator parameter extraction*/
cmdParam = line.substr(line.find(' ') + 1 );
if (cmdOperator == "-")
{
supprimerProf(cmdParam);
}
else if (cmdOperator == "#")
{
std::cout << "Professeur ayant le plus d'etudiants : " << *afficherLeProfPlusEtudiants() << endl;
}
else if (cmdOperator == "*")
{
std::cout << "Le cours le plus demande est: " << *afficherCoursPlusDemande() << endl;
}
else if (cmdOperator == "%")
{
std::cout << "Le nombre de professeurs pour le cours " << cmdParam << " est : " << afficherNbreProfPourUnCours(&cmdParam) << endl;
}
else if (cmdOperator == "$")
{
recopier(FP);
}
std::cout << "\n";
}
}
}
//Cette fonction parcours toutes les structures de Professeurs, compte les tudiants et affiche le prof qui en a le plus
string* DossierProfesseur::afficherLeProfPlusEtudiants()
{
Professeur * courantProf = teteProf;
Etudiant * courantEtudiant;
Professeur * profPlusEtudiants = teteProf;
int cptEtudiants = 0, lePlusEtudiants = 0;
while (courantProf != nullptr) //Parcourir les structures
{
courantEtudiant = courantProf->listeEtudiants;
cptEtudiants = 0;
while (courantEtudiant) //Compteur d'tudiants
{
cptEtudiants++;
courantEtudiant = courantEtudiant->suivant;
}
if (cptEtudiants > lePlusEtudiants) //Sauvegarde le nombre d'tudiants le plus lev et le Professeur associ
{
lePlusEtudiants = cptEtudiants;
profPlusEtudiants = courantProf;
}
courantProf = courantProf->suivant;
}
if (profPlusEtudiants != nullptr) // Affiche le professeur ayant le plus d'tudiants
{
return profPlusEtudiants->nom;
}
else
{
std::cout << "Le dossier ne contient aucun professeur!\n";
return &vide;
}
}
//Cette fonction va parcourir toutes les structures et va charger tous les cours demands dans un vecteur.
//2 autres vecteurs vont contenir le professeur associ et le nombre de demandes.
//Finalement le cours le plus demand (priorit l'anciennet du Professeur, premier rencontr) est affich.
string* DossierProfesseur::afficherCoursPlusDemande()
{
Professeur * courantProf = teteProf;
Professeur * profCoursPlusDemande = courantProf;
Cours * courantCours = nullptr;
Cours * coursPlusDemande = nullptr;
vector<Cours*> vecteurCours(0);
vector<int> vecteurNbCours(0);
vector<Professeur*> vecteurProfs(0);
vector<int> lesPlusDemandes(0);
int a = 0 , b = 0, nombrePlusDemande=0;
while (courantProf != nullptr) //Lecture de tous les Professeurs
{
courantCours = courantProf->listeCours;
bool trouve = false;
while (courantCours != nullptr) //Lecture de tous les Cours
{
for (a = 0; a < vecteurCours.size(); a++) //Parcourir le vecteur de cours
{
bool trouve = false;
if (*vecteurCours[a]->sigle == *courantCours->sigle) //Si le vecteur existe deja
{
vecteurNbCours[a] = vecteurNbCours[a] + 1; //Incrementer le nombre de demande dans le vecteur nombre cours
bool trouve = true;
if (courantProf->ancien > vecteurProfs[a]->ancien) //Assure que le professeur associ au cours est bien celui qui a le plus d'anciennet
{
vecteurProfs[a] = courantProf;
}
}
}
if (trouve == false) //Si le cours n'existe pas dans le vecteur
{
vecteurCours.push_back(courantCours); //Ajouter le cours au vecteur
vecteurProfs.push_back(courantProf); //Ajouter le prof au vecteur
vecteurNbCours.push_back(1); //Ajouter le nombre de cours au vecteur
}
courantCours = courantCours->suivant;
}
courantProf = courantProf->suivant;
}
for (a = 0; a < vecteurNbCours.size(); a++) //Parcourir le vecteur la recherche du nombre de demandes le plus lev
{
if (vecteurNbCours[a] > nombrePlusDemande)
{
nombrePlusDemande = vecteurNbCours[a];
}
}
for (a = 0; a < vecteurNbCours.size(); a++) //Parcourir le vecteur la recherche du ou des cours les plus demands
{
if (vecteurNbCours[a] == nombrePlusDemande)
{
lesPlusDemandes.push_back(a); //Charger le ou les plus demands dans un vecteur
}
}
if (lesPlusDemandes.size() > 1) //Si il y a plus d'un cours dans les plus demands
{
int lePlusAncien = 0;
Professeur * profLePlusAncien = nullptr;
for (a = 0; a < lesPlusDemandes.size(); a++) //Parcourir le vecteur des plus demands
{
if (*vecteurProfs[lesPlusDemandes[a]]->ancien > lePlusAncien) //Verifie l'anciennet des professeurs et charge la premire valeur d'anciennet la plus leve
{
lePlusAncien = *vecteurProfs[lesPlusDemandes[a]]->ancien;
profLePlusAncien = vecteurProfs[lesPlusDemandes[a]];
}
}
for (a = 0; a < lesPlusDemandes.size(); a++) //Parcours le vecteur des cours les plus demands la recherche du Prof ayant le plus d'anciennet
{
if (*vecteurProfs[lesPlusDemandes[a]]->nom == *profLePlusAncien->nom) //Si le prof est trouv, afficher le cours
{
return vecteurCours[lesPlusDemandes[a]]->sigle;
}
}
}
else if (lesPlusDemandes.size() < 1) //Si seulement un cours se trouve dans le vecteur des plus demands, alors afficher
{
std::cout << "Le dossier ne contient aucun professeur!\n";
return &vide;
}
else
{
return vecteurCours[lesPlusDemandes[0]]->sigle;
}
}
void DossierProfesseur::supprimerProf(string nomProf)
{
Professeur *profCourant = teteProf;
Professeur *lastProf = nullptr;
Professeur *deleteMe;
int deleteCount = 0;
while (profCourant)
{
if (nomProf == *profCourant->nom)
{
deleteMe = profCourant;
if (lastProf == nullptr) // Suppression de l'lment de tte
{
lastProf = profCourant->suivant;
teteProf = lastProf;
}
else // Suppression d'un lment une position n > 2
{
lastProf->suivant = profCourant->suivant;
}
profCourant = profCourant->suivant;
std::cout << "Le professeur " << *deleteMe->nom << " a ete supprime!\n";
delete deleteMe;
++deleteCount;
}
else
{
lastProf = profCourant;
profCourant = profCourant->suivant;
}
}
}
//Cette fonction compte le nombre de professeurs qui donnent un cours spcifique
int DossierProfesseur::afficherNbreProfPourUnCours(string* coursDonne)
{
Professeur * courantProf = teteProf;
Cours * courantCours = nullptr;
int nombreProfs = 0;
while (courantProf != nullptr) //Lecture de tous les Professeurs
{
courantCours = courantProf->listeCours;
while (courantCours != nullptr)
{
if (*courantCours->sigle == *coursDonne) //si le cours courant est celui qu'on cherche
{
nombreProfs++; //Incrementer le compteur de profs
courantCours = nullptr;
break;
}
else
{
courantCours = courantCours->suivant;
}
}
courantProf = courantProf->suivant;
}
return nombreProfs;
}
//Fonction d'criture de la liste chaine vers le fichier
void DossierProfesseur::recopier(char* FP)
{
Professeur * courantProf = teteProf;
Cours * courantCours = nullptr;
Etudiant * courantEtudiant = nullptr;
ofstream fichierOut(FP);
if (fichierOut)
{
while (courantProf != nullptr)
{
courantCours = courantProf->listeCours;
courantEtudiant = courantProf->listeEtudiants;
fichierOut << *courantProf->nom << endl << *courantProf->ancien << endl;
while (courantCours != nullptr)
{
fichierOut << *courantCours->sigle << endl;
courantCours = courantCours->suivant;
}
fichierOut << "&" << endl;
while (courantEtudiant != nullptr)
{
fichierOut << *courantEtudiant->nom << endl;
courantEtudiant = courantEtudiant->suivant;
}
fichierOut << "&" << endl;
courantProf = courantProf->suivant;
}
std::cout << "Liste enregistree dans le fichier FP.txt\n";
}
else
{
std::cout << "Erreur d'ouverture du fichier FP en ecriture\n";
}
fichierOut.close();
} | true |
0da1405cda7ed117571646660a603b9d1425bde1 | C++ | liuzixing/scut | /codechef/easy/Factorial.cpp | UTF-8 | 374 | 2.703125 | 3 | [] | no_license | #include <cstdio>
using namespace std;
int five[20];
int main()
{
int T,n,ans;
five[0] = 5;
for (int i = 1;i < 13;i++)
five[i] = five[i - 1] * 5;
scanf("%d",&T);
while (T--)
{
ans = 0;
scanf("%d",&n);
for (int i = 0;i < 13;i++)
ans += n / five[i];
printf("%d\n",ans);
}
}
| true |
e585366b06ba35096adf51752777063df939ea9c | C++ | tistatos/Medusa | /src/texture.cpp | UTF-8 | 15,590 | 2.75 | 3 | [] | no_license |
#include "texture.h"
using namespace pcl;
pcl::texture_mapping::CameraVector Texture::mCameras;
/**
* @deprecated no longer used
* @brief Save file_name to .obj file
* @details long description
*
* @param file_name The desired file name.
* @param tex_mesh The mesh that you want to save.
* @param precision Sets the number of decimals allowed.
* @return None.
*/
/** \brief Save a textureMesh object to obj file */
int Texture::saveOBJFile (const std::string &file_name, const pcl::TextureMesh &tex_mesh, unsigned precision)
{
if (tex_mesh.cloud.data.empty ())
{
PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no data!\n");
return (-1);
}
// Open file
std::ofstream fs;
fs.precision (precision);
fs.open (file_name.c_str());
// Define material file
std::string mtl_file_name = file_name.substr (0, file_name.find_last_of (".")) + ".mtl";
// Strip path for "mtllib" command
std::string mtl_file_name_nopath = mtl_file_name;
mtl_file_name_nopath.erase (0, mtl_file_name.find_last_of ('/') + 1);
/* Write 3D information */
// number of points
int nr_points = tex_mesh.cloud.width * tex_mesh.cloud.height;
int point_size = tex_mesh.cloud.data.size () / nr_points;
// mesh size
int nr_meshes = tex_mesh.tex_polygons.size ();
// number of faces for header
int nr_faces = 0;
for (int m = 0; m < nr_meshes; ++m)
nr_faces += tex_mesh.tex_polygons[m].size ();
// Write the header information
fs << "####" << std::endl;
fs << "# OBJ dataFile simple version. File name: " << file_name << std::endl;
fs << "# Vertices: " << nr_points << std::endl;
fs << "# Faces: " <<nr_faces << std::endl;
fs << "# Material information:" << std::endl;
fs << "mtllib " << mtl_file_name_nopath << std::endl;
fs << "####" << std::endl;
// Write vertex coordinates
fs << "# Vertices" << std::endl;
for (int i = 0; i < nr_points; ++i)
{
int xyz = 0;
// "v" just be written one
bool v_written = false;
for (size_t d = 0; d < tex_mesh.cloud.fields.size (); ++d)
{
int count = tex_mesh.cloud.fields[d].count;
if (count == 0)
count = 1; // we simply cannot tolerate 0 counts (coming from older converter code)
int c = 0;
// adding vertex
if ((tex_mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
tex_mesh.cloud.fields[d].name == "x" ||
tex_mesh.cloud.fields[d].name == "y" ||
tex_mesh.cloud.fields[d].name == "z"))
{
if (!v_written)
{
// write vertices beginning with v
fs << "v ";
v_written = true;
}
float value;
memcpy (&value, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
fs << value;
if (++xyz == 3)
break;
fs << " ";
}
}
if (xyz != 3)
{
PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no XYZ data!\n");
return (-2);
}
fs << std::endl;
}
fs << "# "<< nr_points <<" vertices" << std::endl;
// Write vertex normals
for (int i = 0; i < nr_points; ++i)
{
int xyz = 0;
// "vn" just be written one
bool v_written = false;
for (size_t d = 0; d < tex_mesh.cloud.fields.size (); ++d)
{
int count = tex_mesh.cloud.fields[d].count;
if (count == 0)
count = 1; // we simply cannot tolerate 0 counts (coming from older converter code)
int c = 0;
// adding vertex
if ((tex_mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
tex_mesh.cloud.fields[d].name == "normal_x" ||
tex_mesh.cloud.fields[d].name == "normal_y" ||
tex_mesh.cloud.fields[d].name == "normal_z"))
{
if (!v_written)
{
// write vertices beginning with vn
fs << "vn ";
v_written = true;
}
float value;
memcpy (&value, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
fs << value;
if (++xyz == 3)
break;
fs << " ";
}
}
if (xyz != 3)
{
PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no normals!\n");
return (-2);
}
fs << std::endl;
}
// Write vertex texture with "vt" (adding latter)
for (int m = 0; m < nr_meshes; ++m)
{
if(tex_mesh.tex_coordinates.size() == 0)
continue;
PCL_INFO ("%d vertex textures in submesh %d\n", tex_mesh.tex_coordinates[m].size (), m);
fs << "# " << tex_mesh.tex_coordinates[m].size() << " vertex textures in submesh " << m << std::endl;
for (size_t i = 0; i < tex_mesh.tex_coordinates[m].size (); ++i)
{
fs << "vt ";
fs << tex_mesh.tex_coordinates[m][i][0] << " " << tex_mesh.tex_coordinates[m][i][1] << std::endl;
}
}
int f_idx = 0;
// int idx_vt =0;
PCL_INFO ("Writting faces...\n");
for (int m = 0; m < nr_meshes; ++m)
{
if (m > 0)
f_idx += tex_mesh.tex_polygons[m-1].size ();
if(tex_mesh.tex_materials.size() !=0)
{
fs << "# The material will be used for mesh " << m << std::endl;
//TODO pbl here with multi texture and unseen faces
fs << "usemtl " << tex_mesh.tex_materials[m].tex_name << std::endl;
fs << "# Faces" << std::endl;
}
for (size_t i = 0; i < tex_mesh.tex_polygons[m].size(); ++i)
{
// Write faces with "f"
fs << "f";
size_t j = 0;
// There's one UV per vertex per face, i.e., the same vertex can have
// different UV depending on the face.
for (j = 0; j < tex_mesh.tex_polygons[m][i].vertices.size (); ++j)
{
unsigned int idx = tex_mesh.tex_polygons[m][i].vertices[j] + 1;
fs << " " << idx
<< "/" << 3*(i+f_idx) +j+1
<< "/" << idx; // vertex index in obj file format starting with 1
}
fs << std::endl;
}
PCL_INFO ("%d faces in mesh %d \n", tex_mesh.tex_polygons[m].size () , m);
fs << "# "<< tex_mesh.tex_polygons[m].size() << " faces in mesh " << m << std::endl;
}
fs << "# End of File";
// Close obj file
PCL_INFO ("Closing obj file\n");
fs.close ();
/* Write material defination for OBJ file*/
// Open file
PCL_INFO ("Writing material files\n");
//dont do it if no material to write
if(tex_mesh.tex_materials.size() ==0)
return (0);
std::ofstream m_fs;
m_fs.precision (precision);
m_fs.open (mtl_file_name.c_str ());
// default
m_fs << "#" << std::endl;
m_fs << "# Wavefront material file" << std::endl;
m_fs << "#" << std::endl;
for(int m = 0; m < nr_meshes; ++m)
{
m_fs << "newmtl " << tex_mesh.tex_materials[m].tex_name << std::endl;
m_fs << "Ka "<< tex_mesh.tex_materials[m].tex_Ka.r << " " << tex_mesh.tex_materials[m].tex_Ka.g << " " << tex_mesh.tex_materials[m].tex_Ka.b << std::endl; // defines the ambient color of the material to be (r,g,b).
m_fs << "Kd "<< tex_mesh.tex_materials[m].tex_Kd.r << " " << tex_mesh.tex_materials[m].tex_Kd.g << " " << tex_mesh.tex_materials[m].tex_Kd.b << std::endl; // defines the diffuse color of the material to be (r,g,b).
m_fs << "Ks "<< tex_mesh.tex_materials[m].tex_Ks.r << " " << tex_mesh.tex_materials[m].tex_Ks.g << " " << tex_mesh.tex_materials[m].tex_Ks.b << std::endl; // defines the specular color of the material to be (r,g,b). This color shows up in highlights.
m_fs << "d " << tex_mesh.tex_materials[m].tex_d << std::endl; // defines the transparency of the material to be alpha.
m_fs << "Ns "<< tex_mesh.tex_materials[m].tex_Ns << std::endl; // defines the shininess of the material to be s.
m_fs << "illum "<< tex_mesh.tex_materials[m].tex_illum << std::endl; // denotes the illumination model used by the material.
// illum = 1 indicates a flat material with no specular highlights, so the value of Ks is not used.
// illum = 2 denotes the presence of specular highlights, and so a specification for Ks is required.
m_fs << "map_Kd " << tex_mesh.tex_materials[m].tex_file << std::endl;
m_fs << "###" << std::endl;
}
PCL_INFO ("Closing mtl file\n");
m_fs.close ();
PCL_INFO ("Closed mtl file\n");
return (0);
}
/** \brief Display a 3D representation showing the a cloud and a list of camera with their 6DOf poses */
void Texture::showCameras (pcl::texture_mapping::CameraVector cams, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud)
{
// visualization object
pcl::visualization::PCLVisualizer visu ("cameras");
// add a visual for each camera at the correct pose
for(int i = 0 ; i < cams.size () ; ++i)
{
// read current camera
pcl::TextureMapping<pcl::PointXYZ>::Camera cam = cams[i];
double focal = cam.focal_length;
double height = cam.height;
double width = cam.width;
// create a 5-point visual for each camera
pcl::PointXYZ p1, p2, p3, p4, p5;
p1.x=0; p1.y=0; p1.z=0;
double angleX = RAD2DEG (2.0 * atan (width / (2.0*focal)));
double angleY = RAD2DEG (2.0 * atan (height / (2.0*focal)));
double dist = 0.75;
double minX, minY, maxX, maxY;
maxX = dist*tan (atan (width / (2.0*focal)));
minX = -maxX;
maxY = dist*tan (atan (height / (2.0*focal)));
minY = -maxY;
p2.x=minX; p2.y=minY; p2.z=dist;
p3.x=maxX; p3.y=minY; p3.z=dist;
p4.x=maxX; p4.y=maxY; p4.z=dist;
p5.x=minX; p5.y=maxY; p5.z=dist;
p1=pcl::transformPoint (p1, cam.pose);
p2=pcl::transformPoint (p2, cam.pose);
p3=pcl::transformPoint (p3, cam.pose);
p4=pcl::transformPoint (p4, cam.pose);
p5=pcl::transformPoint (p5, cam.pose);
std::stringstream ss;
ss << "Cam #" << i+1;
visu.addText3D(ss.str (), p1, 0.1, 1.0, 1.0, 1.0, ss.str ());
ss.str ("");
ss << "camera_" << i << "line1";
visu.addLine (p1, p2,ss.str ());
ss.str ("");
ss << "camera_" << i << "line2";
visu.addLine (p1, p3,ss.str ());
ss.str ("");
ss << "camera_" << i << "line3";
visu.addLine (p1, p4,ss.str ());
ss.str ("");
ss << "camera_" << i << "line4";
visu.addLine (p1, p5,ss.str ());
ss.str ("");
ss << "camera_" << i << "line5";
visu.addLine (p2, p5,ss.str ());
ss.str ("");
ss << "camera_" << i << "line6";
visu.addLine (p5, p4,ss.str ());
ss.str ("");
ss << "camera_" << i << "line7";
visu.addLine (p4, p3,ss.str ());
ss.str ("");
ss << "camera_" << i << "line8";
visu.addLine (p3, p2,ss.str ());
}
// add a coordinate system
visu.addCoordinateSystem (1.0);
// add the mesh's cloud (colored on Z axis)
pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> color_handler (cloud, "z");
visu.addPointCloud (cloud, color_handler, "cloud");
// reset camera
visu.resetCamera ();
// wait for user input
visu.spin ();
}
void Texture::applyCameraPose(Kinect* kinect)
{
pcl::TextureMapping<pcl::PointXYZ>::Camera cam;
cam.pose = kinect->getPosition();
cam.pose = cam.pose.inverse();
// camera focal length and size
cam.focal_length=525;
cam.height=480;
cam.width=640;
cam.texture_file = kinect->getFilename();
mCameras.push_back(cam);
}
void Texture::updateTextureFiles(Kinect* kinect)
{
mCameras.at(kinect->getIndex()).texture_file = kinect->getFilename();
}
/**
* @brief The run function for texturing
* @details Where everything happens!
*/
void Texture::applyTexture(pcl::PolygonMesh &triangles, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, std::string modelID) // Att skicka med: PolygonMesh, pcl::PointCloud<pcl::PointNormal>
{
std::cout << "Loading mesh... " << std::endl;
fromPCLPointCloud2 (triangles.cloud, *cloud);
// Create the texturemesh object that will contian our UV-mapped mesh
TextureMesh mesh;
mesh.cloud = triangles.cloud;
std::vector<pcl::Vertices> polygon_1;
// push faces into the texturemesh object
polygon_1.resize (triangles.polygons.size ());
for(size_t i =0; i < triangles.polygons.size (); ++i)
{
polygon_1[i] = triangles.polygons[i];
}
mesh.tex_polygons.push_back(polygon_1);
PCL_INFO ("\tInput mesh contains %d faces and %d vertices\n", mesh.tex_polygons[0].size (), cloud->points.size ());
PCL_INFO ("...Done.\n");
// Load textures and cameras poses and intrinsics
PCL_INFO ("\nLoading textures and camera poses...\n");
PCL_INFO ("\tLoaded %d textures.\n", mCameras.size ());
PCL_INFO ("...Done.\n");
// Display cameras to user
PCL_INFO ("\nDisplaying cameras. Press \'q\' to continue texture mapping\n");
//showCameras(mCameras, cloud);
// Create materials for each texture (and one extra for occluded faces)
mesh.tex_materials.resize (mCameras.size () + 1);
for(int i = 0 ; i <= mCameras.size() ; ++i)
{
pcl::TexMaterial mesh_material;
mesh_material.tex_Ka.r = 0.2f;
mesh_material.tex_Ka.g = 0.2f;
mesh_material.tex_Ka.b = 0.2f;
mesh_material.tex_Kd.r = 0.8f;
mesh_material.tex_Kd.g = 0.8f;
mesh_material.tex_Kd.b = 0.8f;
mesh_material.tex_Ks.r = 1.0f;
mesh_material.tex_Ks.g = 1.0f;
mesh_material.tex_Ks.b = 1.0f;
mesh_material.tex_d = 1.0f;
mesh_material.tex_Ns = 75.0f;
mesh_material.tex_illum = 2;
std::stringstream tex_name;
tex_name << "material_" << i;
tex_name >> mesh_material.tex_name;
if(i < mCameras.size ())
mesh_material.tex_file = mCameras[i].texture_file;
else
mesh_material.tex_file = "occluded.jpg";
mesh.tex_materials[i] = mesh_material;
}
// Sort faces
PCL_INFO ("\nSorting faces by cameras...\n");
pcl::TextureMapping<pcl::PointXYZ> tm; // TextureMapping object that will perform the sort
tm.textureMeshwithMultipleCameras(mesh, mCameras);
PCL_INFO ("Sorting faces by cameras done.\n");
for(int i = 0 ; i <= mCameras.size() ; ++i)
{
PCL_INFO ("\tSub mesh %d contains %d faces and %d UV coordinates.\n", i, mesh.tex_polygons[i].size (), mesh.tex_coordinates[i].size ());
}
// compute normals for the mesh
PCL_INFO ("\nEstimating normals...\n");
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> n;
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud (cloud);
n.setInputCloud (cloud);
n.setSearchMethod (tree);
n.setKSearch (20);
n.compute (*normals);
// Concatenate XYZ and normal fields
pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
PCL_INFO ("...Done.\n");
/*
for(int i = 0; i < cloud_with_normals->size();i++){
pcl::flipNormalTowardsViewpoint (cloud_with_normals->points[i],
Texture::mCameras[0].pose(0,3),
Texture::mCameras[0].pose(1,3),
Texture::mCameras[0].pose(2,3),
cloud_with_normals->points[i].x,
cloud_with_normals->points[i].y,
cloud_with_normals->points[i].z
);
}
*/
pcl::toPCLPointCloud2 (*cloud_with_normals, mesh.cloud);
// pcl::visualization::PCLVisualizer viewer ("surface fitting");
//viewer.addTextureMesh (mesh, "sample mesh");
//while (!viewer.wasStopped ())
//{
// viewer.spinOnce (100);
// boost::this_thread::sleep (boost::posix_time::microseconds (100000));
//}
Texture::saveOBJFile("./scans/" + modelID+".obj", mesh, 5);
}
| true |
f8e784eb680d04daeabd1cc4bd9698f083edb6bf | C++ | starmap0312/leetcode | /longest_substring_wo_repeating2.cpp | UTF-8 | 1,163 | 3.46875 | 3 | [] | no_license | /* - map<char, int> dict;
* - dict[key] = value ==> add if key not in dict, and override if key in dict
* dict[key] ==> if key not in dict, accessing dict[key] will set dict[key] = 0
* - key not in dict ==> dict.find(key) == dict.end()
* dict.count(key) == 0
* - min/max functions ==> min(num1, num2) and max(num1, num2)
*/
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s);
};
int Solution::lengthOfLongestSubstring(string s) {
map<char, int> locations;
int max_prefix_length = 0, max_length = 0;
for(int i = 0; i < s.size(); i++) {
if(locations.find(s[i]) == locations.end()) {
max_prefix_length++;
} else {
int length = i - locations[s[i]];
max_prefix_length = min(length, max_prefix_length + 1);
}
locations[s[i]] = i;
max_length = max(max_prefix_length, max_length);
}
return max_length;
}
int main() {
Solution solution;
string s = "abcabcbb";
cout << solution.lengthOfLongestSubstring(s) << endl;
return 0;
}
| true |
5b881580e5547833874a83897dd29bbe46729e2d | C++ | Omar-Radwan/UVA_Solutions | /Volume 114/11408 - Count DePrimes/11408 - Count DePrimes.cpp | UTF-8 | 3,267 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
#define SETPERCISION cout << fixed << setprecision(12)
#define IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ll long long
#define f first
#define s second
using namespace std;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template<typename T, typename V>
void __print(const pair<T, V> &x) {
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template<typename T>
void __print(const T &x) {
int f = 0;
cerr << '{';
for (auto &i: x) cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template<typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cerr << ", ";
_print(v...);
}
const int RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count();
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int random_int(int l, int r) { return uniform_int_distribution<int>(l, r)(rng); }
int range(int l, int r) { return l + rand() % (r - l + 1); }
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "DEBUG: [" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
//#define ONLINE_JUDGE
void init(int argc, char **argv) {
IO;
if (argc == 2 && !strcmp("input.txt", argv[1])) {
cerr << "reading from in.txt" << endl;
freopen(argv[1], "r", stdin);
}
}
int L = 2, R = 5 * 1e6;
vector<int> values, sum, prime, prefix;
void sum_of_prime_factors() {
values = vector<int>(R + 1);
for (int i = 2; i <= R; i++)
values[i] = i;
sum = vector<int>(R + 1, 0);
prime = vector<int>(R + 1, 1);
for (int i = 2; i * i <= R; i++) {
if (!prime[i]) continue;
for (int j = i * i; j <= R; j += i) {
prime[j] = false;
sum[j] += i;
while (values[j] % i == 0) {
values[j] /= i;
}
}
}
for (int i = 2; i <= R; i++) {
if (values[i] != 1) {
sum[i] += values[i];
values[i] = 1;
}
}
prefix = vector<int>(R + 1, 0);
int maxi = 0;
for (int i = 2; i <= R; i++) {
if (prime[sum[i]] == 1) {
prefix[i]++;
}
prefix[i] += prefix[i - 1];
maxi = max(maxi, sum[i]);
}
}
int main(int argc, char **argv) {
init(argc, argv);
sum_of_prime_factors();
while (true) {
int l, r;
cin >> l;
if (l == 0) break;
cin >> r;
cout << prefix[r] - prefix[l - 1] << "\n";
}
return 0;
}
| true |
a12a38f85a37b729d73ca13ccc17ba66e34dc57f | C++ | basant-kumar/Hackerrank | /Algorithm/pangrams.cpp | UTF-8 | 418 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <algorithm>
#include <string>
using namespace std;
int main(){
string s;
// cin>>s;
getline(cin,s);
s.erase(remove(s.begin(), s.end(), ' '), s.end());
transform(s.begin(), s.end(), s.begin(), ::tolower);
set<char> a(begin(s),end(s));
if(a.size()==26)
cout<<"pangram"<<endl;
else
cout<<"not pangram"<<endl;
return 0;
} | true |
f0aca7f2babdacfdc8d95386b9fede7c805257b3 | C++ | Ckins/c-sicily | /1152/main.cpp | UTF-8 | 3,264 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
struct horse_state {
int cur_pos;
int route[30];
int step;
horse_state() {
cur_pos = 0;
for (int i = 0; i < 30; i++) route[i] = -1;
step = 0;
}
// to construct the next state.
horse_state(int s, int next_pos, int* rou) {
step = s;
cur_pos = next_pos;
for (int i =0; i < 30;i++) {
route[i] = rou[i];
}
route[cur_pos] = step;
}
};
stack<horse_state> my_stack;
void try_move() {
int x = (my_stack.top().cur_pos)/6;
int y = (my_stack.top().cur_pos)%6;
int cur_route[30];
int step = my_stack.top().step+1;
for (int i = 0; i<30; i++) {
cur_route[i] = my_stack.top().route[i];
}
my_stack.pop();
//eight possible way to move on.
//up
if ((x-2>=0) && (y+1 <= 5) && (cur_route[(x-2)*6+y+1] == -1)) {
my_stack.push(horse_state(step, (x-2)*6+y+1, cur_route));
}
//up_right
if ((x-1 >=0) && (y+2 <= 5) && (cur_route[(x-1)*6+y+2] == -1)) {
my_stack.push(horse_state(step, (x-1)*6+y+2, cur_route));
}
//right
//cout << cur_route[x*6+y+2] << endl;
if ((y+2 <= 5) && (x+1 <= 4) && (cur_route[(x+1)*6+y+2] == -1)) {
my_stack.push(horse_state(step, (x+1)*6+y+2, cur_route));
}
//down right
if ((x+2 <=4) && (y+1 <= 5) && (cur_route[(x+2)*6+y+1] == -1)) {
my_stack.push(horse_state(step, (x+2)*6+y+1, cur_route));
}
//down
if ((x+2 <= 4) && (y-1 >= 0)&&(cur_route[(x+2)*6+y-1] == -1)) {
my_stack.push(horse_state(step, (x+2)*6+y-1, cur_route));
}
//down left
if ((x+1 <=4) && (y-2 >= 0) && (cur_route[(x+1)*6+y-2] == -1)) {
my_stack.push(horse_state(step, (x+1)*6+y-2, cur_route));
}
//left
if ((y-2 >= 0) && (x-1 >= 0)&&(cur_route[(x-1)*6+y-2] == -1)) {
my_stack.push(horse_state(step, (x-1)*6+y-2, cur_route));
}
//up_left
if ((x-2 >=0) && (y-1 >= 0) && (cur_route[(x-2)*6+y-1] == -1)) {
my_stack.push(horse_state(step, (x-2)*6+y-1, cur_route));
}
}
int main() {
int start;
cin >> start;
while (start!=-1) {
while (!my_stack.empty()) {
my_stack.pop();
}
int tmp[29];
for (int i = 0; i < 30; i++) tmp[i] = -1;
my_stack.push(horse_state(0, start-1, tmp));
while((!my_stack.empty()) && (my_stack.top().step != 29)) {
try_move();
// cout << my_stack.size() << endl;
// for (int i = 1; i <= 29; i++) {
// for (int j = 0; j <= 29; j++) {
// if (my_stack.top().route[j] == i) {
// cout << " " << j+1;
// }
// }
// }
// cout << endl;
}
if (!my_stack.empty()) {
cout << start;
for (int i = 1; i <= 29; i++) {
for (int j = 0; j <= 29; j++) {
if (my_stack.top().route[j] == i) {
cout << " " << j+1;
}
}
}
} else {
cout << "can not find";
}
cout << endl;
cin >> start;
}
return 0;
}
| true |
254d02eef6e51b95698fb73ed87f2bc31b83e5a7 | C++ | AswinJose8100/Algorithm-Design-and-Data-Structures | /assignment2/human.cpp | UTF-8 | 179 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include "human.h"
human::human(string input1){
choice1=input1;
}
string human::playerchoice(){
return choice1; //returns the choice entered by the player
} | true |
ec56d253562af9db87d158698798fc4bc5fe61df | C++ | Mosh-Bit/programmiersprachen-aufgabenblatt-2 | /source/Uhr.cpp | UTF-8 | 2,975 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "window.hpp"
#include <utility>
#include <cmath>
#include "rectangle.hpp"
#include "circle.hpp"
#include <vector>
#include "color.hpp"
int main(int argc, char* argv[])
{
Window win{std::make_pair(800,800)};
while (!win.should_close()) {
if (win.is_key_pressed(GLFW_KEY_ESCAPE)) {
win.close();
}
auto t = win.get_time()*60;
Vec2 v{0.5,0.5};
Circle uhrkreis{0.49,v};
Circle uhrkreis2{0.01,v};
Circle uhrkreis3{0.005,v};
Circle uhrkreis4{0.0001,v};
color schwarz{0.0,0.0,0.0};
uhrkreis.draw(win,schwarz);
uhrkreis2.draw(win,schwarz);
uhrkreis3.draw(win,schwarz);
uhrkreis4.draw(win,schwarz);
float angel=3.1415*2/60;
float sekunde=t;
float minute=sekunde/60;
float std=t/(12*60);
win.draw_line(0.5,0.5,0.5+sin(angel*sekunde)*0.4,0.5+cos(angel*sekunde)*0.4,0.0,0.0,0.0);
win.draw_line(0.5,0.5,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.501,0.501,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.502,0.502,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.503,0.503,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.504,0.504,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.499,0.499,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.498,0.498,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.497,0.497,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.496,0.496,0.5+sin(angel*minute)*0.49,0.5+cos(angel*minute)*0.45,0.0,0.0,0.0);
win.draw_line(0.5,0.5,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.499,0.499,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.498,0.498,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.497,0.497,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.496,0.496,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.495,0.495,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.494,0.494,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.501,0.501,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.502,0.502,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.503,0.503,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.504,0.504,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.505,0.505,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.draw_line(0.506,0.506,0.5+sin(angel*std)*0.40,0.5+cos(angel*std)*0.30,0.0,0.0,0.0);
win.update();
}
return 0;
} | true |
59bfc8d226860c519d09999b8042e4d5ac88d464 | C++ | zraul/LeetCode | /FlattenBinaryTreeToLinkedList/FlattenBinaryTreeToLinkedList.h | UTF-8 | 445 | 2.578125 | 3 | [] | no_license | //
// Created by 郑巍 on 2020/4/1.
//
#ifndef LEETCODE_FLATTENBINARYTREETOLINKEDLIST_H
#define LEETCODE_FLATTENBINARYTREETOLINKEDLIST_H
#include <iostream>
#include <vector>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x), left(NULL), right(NULL) {}
};
class FlattenBinaryTreeToLinkedList {
public:
void flatten(TreeNode* root);
};
#endif //LEETCODE_FLATTENBINARYTREETOLINKEDLIST_H
| true |
0a7847b2d2a8bed855f75d26f3184b2ae2a94a8d | C++ | sundsx/RevBayes | /src/core/datatypes/phylogenetics/AbstractCharacterData.cpp | UTF-8 | 984 | 2.515625 | 3 | [] | no_license | #include "AbstractCharacterData.h"
#include <sstream>
using namespace RevBayesCore;
std::ostream& RevBayesCore::operator<<(std::ostream& o, const AbstractCharacterData& x) {
std::stringstream s;
// Generate nice header
o << std::endl;
s << x.getDatatype() << " character matrix with " << x.getNumberOfTaxa() << " taxa and " << x.getNumberOfCharacters() << " characters" << std::endl;
o << s.str();
for ( size_t i = 0; i < s.str().length() - 1; ++i )
o << "=";
o << std::endl;
o << "Origination: " << x.getFileName() << std::endl;
o << "Number of taxa: " << x.getNumberOfTaxa() << std::endl;
o << "Number of characters: " << x.getNumberOfCharacters() << std::endl;
o << "Number of included characters: " << x.getNumberOfIncludedCharacters() << std::endl;
o << "Datatype: " << x.getDatatype() << std::endl;
o << std::endl;
return o;
}
| true |
8bc209f08ffb547525d5df078cce83eb84ba7ea1 | C++ | tmittal98/CPP-codes | /binary trees/right_view_left_view.cpp | UTF-8 | 3,904 | 3.875 | 4 | [] | no_license | #include <iostream>
#include <queue>
#include <list>
using namespace std;
class node{
public:
int data;
node *left;
node *right;
node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
node* preorderBuild(){
int data;
cin >> data;
if(data == -1){
return NULL;
}
node *newRoot = new node(data);
newRoot->left = preorderBuild();
newRoot->right = preorderBuild();
return newRoot;
}
void preorderPrint(node* root){
if(root == NULL){
return;
}
cout << root->data << " ";
preorderPrint(root->left);
preorderPrint(root->right);
return;
}
void inorderPrint(node* root){
if(root == NULL){
return;
}
inorderPrint(root->left);
cout << root->data << " ";
inorderPrint(root->right);
return;
}
void postorderPrint(node* root){
if(root == NULL){
return;
}
postorderPrint(root->left);
postorderPrint(root->right);
cout << root->data << " ";
return;
}
int height(node* root){
//base case
if(root == NULL){
return 0;
}
int leftH = height(root->left);
int rightH = height(root->right);
return max(leftH, rightH)+1;
}
void bfs(node* root){
queue<node *> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
node *f = q.front();
if(f == NULL){
cout << endl;
q.pop();
if(q.empty()){
return;
}
else{
q.push(NULL);
continue;
}
}
cout << f->data << " ";
if(f->left){
q.push(f->left);
}
if(f->right){
q.push(f->right);
}
q.pop();
}
}
void rightView(node* root,vector<int> &res,int &max_level,int level){
if(root == NULL){
return;
}
if(level > max_level){
//i am visiting this level first time
res.push_back(root->data);
max_level++;
}
rightView(root->right, res, max_level, level + 1);
rightView(root->left, res, max_level, level + 1);
return;
}
vector<int> rightView2(node* root){
vector<int> res;
res.clear();
if(root == NULL){
return res;
}
list<node *> l;
l.push_back(root);
l.push_back(NULL);
res.push_back(root->data);
while (!l.empty()){
node *f = l.front();
l.pop_front();
if(f == NULL){
if(l.empty()){
return res;
}
node *right = l.back();
res.push_back(right->data);
l.push_back(NULL);
continue;
}
if (f->left){
l.push_back(f->left);
}
if(f->right){
l.push_back(f->right);
}
}
return res;
}
int main(){
node *root = preorderBuild();
preorderPrint(root);
cout << endl;
inorderPrint(root);
cout << endl;
postorderPrint(root);
cout << endl;
cout << "Height of the tree : "<<height(root) << endl;
cout << "level order traversal" << endl;
bfs(root);
// cout << root->data << endl;
// cout << root->left->data << endl;
// cout << root->right->data << endl;
// cout << root->left->left->data << endl;
// cout << root->left->right->data << endl;
vector<int> res;
static int max_level = -1;
rightView(root, res, max_level,0);
cout << "right view of a binary tree " << endl;
for (auto it = res.begin(); it != res.end(); it++){
cout << *it << " ";
}
//Approach 2 of right view using queue
res.clear();
res = rightView2(root);
cout << endl<<"right view of a binary tree " << endl;
for (auto it = res.begin(); it != res.end(); it++){
cout << *it << " ";
}
return 0;
} | true |
a635f453c1c5088ac9fe7728e6e0ebce3a679cdc | C++ | Rkrohit371/Codeforces-solutions | /Array_with_odd_sum.cpp | UTF-8 | 415 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
for(int i=0;i<t;i++){
int n;
cin>>n;
int total=0;
int arr[n],odd=0,even=0;
for(int i=0;i<n;i++){
cin>>arr[i];
if(arr[i]%2==0)
even=1;
else odd=1;
total+=arr[i];
}
if(total%2==0 && even==1 && odd==1)
cout<<"YES"<<endl;
else if(total%2!=0)
cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
} | true |
42c104e13e96321f394fcc98e982c6c9b3e19410 | C++ | ismacaulay/problems | /uva/challenges/CostCutting/TestCostCutting.cxx | UTF-8 | 393 | 2.5625 | 3 | [] | no_license |
#include <gtest/gtest.h>
#include "CostCutting.h"
TEST(TestCostCutting, testKeep)
{
EXPECT_EQ(1, keep(0, 1, 2));
EXPECT_EQ(2, keep(4, 2, 0));
EXPECT_EQ(3, keep(3, 7, 1));
EXPECT_EQ(2, keep(2, 2, 2));
}
TEST(TestCostCutting, testSampleInput)
{
EXPECT_EQ(2000, keep(1000, 2000, 3000));
EXPECT_EQ(2500, keep(3000, 2500, 1500));
EXPECT_EQ(1500, keep(1500, 1200, 1800));
}
| true |
a2c273cdf5c91f8324b7f87cac2fee2b4818adc9 | C++ | kryzthov/gooz | /store/arity.inl.h | UTF-8 | 1,191 | 2.78125 | 3 | [] | no_license | #ifndef STORE_ARITY_INL_H_
#define STORE_ARITY_INL_H_
namespace store {
// static
inline
Arity* Arity::Get(Value value) {
vector<Value> features(1, value);
return GetFromSorted(features);
}
// static
inline
Arity* Arity::Get(Value value1, Value value2) {
vector<Value> features;
features.push_back(value1);
features.push_back(value2);
return Get(features);
}
// static
inline
Arity* Arity::Get(Value value1, Value value2, Value value3) {
vector<Value> features;
features.push_back(value1);
features.push_back(value2);
features.push_back(value3);
return Get(features);
}
// static
inline
Arity* Arity::New(Store* store, uint64 size, Value const * literals) {
return Get(size, literals);
}
inline
uint64 Arity::Map(int64 integer) { // throws FeatureNotFound
return Map(Value::Integer(integer));
}
inline
uint64 Arity::Map(const StringPiece& atom) { // throws FeatureNotFound
return Map(Atom::Get(atom));
}
inline
bool Arity::Has(int64 integer) const noexcept {
return Has(Value::Integer(integer));
}
inline
bool Arity::Has(const StringPiece& atom) const noexcept {
return Has(Atom::Get(atom));
}
} // namespace store
#endif // STORE_ARITY_INL_H_
| true |
3c6929c4eafea392a121b171f3695d0ab84a73ff | C++ | JonJazd/CS162 | /final/Space.hpp | UTF-8 | 705 | 2.546875 | 3 | [] | no_license | #ifndef Space_HPP
#define Space_HPP
#include <string>
using std::string;
class Space{
public:
Space* n;
Space* w;
Space* e;
Space* s;
string entryLine;
bool examined;
bool solved;
bool endRoom;
virtual void examine()=0;
virtual void enter();
virtual int answerIt(int);
virtual void unlock(int);
virtual void setEndRoom();
virtual void setGiveKey();
virtual void display()=0;
virtual void setN(Space*);
virtual void setS(Space*);
virtual void setW(Space*);
virtual void setE(Space*);
virtual void action()=0;
virtual void showDirections()=0;
Space();
virtual ~Space();
};
#endif | true |
41dfa60c285172576d5f49fb3ff8737c78f9a85f | C++ | manuggz/TetrisSdl2 | /src/RandomGenerator.hpp | UTF-8 | 951 | 2.765625 | 3 | [] | no_license | //
// Created by manuggz on 16/12/16.
//
#ifndef TETRIS_RANDOMGENERATOR_HPP
#define TETRIS_RANDOMGENERATOR_HPP
#include <vector>
#include <random>
#include <algorithm>
#include "Tetromino.hpp"
class RandomGenerator{
public:
int getNextFormaTetromino(){
if(mFormaRegresadaIndice >= N_FORMAS){
randomBolsa();
mFormaRegresadaIndice = -1;
}
return mVectorFormasBolsa[++mFormaRegresadaIndice];
}
private:
std::vector<int> mVectorFormasBolsa {
Tetromino::I,
Tetromino::J,
Tetromino::L,
Tetromino::O,
Tetromino::S,
Tetromino::T,
Tetromino::Z,
};
int mFormaRegresadaIndice = N_FORMAS;
void randomBolsa(){
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(mVectorFormasBolsa.begin(), mVectorFormasBolsa.end(), g);
}
};
#endif //TETRIS_RANDOMGENERATOR_HPP
| true |
5c9eb2b97f85ba540e688936c7164253d295bbe8 | C++ | yueyy/PAT | /PAT-Basic/1003.cpp | UTF-8 | 1,107 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
void check(string word){
int p = 0;
int t = 0;
int left = 0;
int middle = 0;
int right = 0;
bool valid = true;
for (int i = 0; i < word.length(); i++){
if (word[i] != 'P' && word[i] != 'A' && word[i] != 'T')
{
valid = false;
}
if (word[i] == 'P')
{
p += 1;
}else if (word[i] == 'T')
{
t += 1;
}else if (word[i] == 'A'){
if ( p == 0 && t == 0)
{
left += 1;
}else if ( p == 1 && t == 0)
{
middle += 1;
}else if ( p == 1 && t == 1){
right += 1;
}
}
}
if (left*middle != right || word.find("A")==string::npos)
{
valid = false;
}
if ( p == 1 && t == 1 && valid==true )
{
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}
int main(){
int count;
cin >> count;
string s[count];
for (int i = 0; i < count; ++i)
{
cin >> s[i];
}
for (int i = 0; i < count; ++i)
{
check(s[i]);
}
}
| true |
18e5f04551ebaf66b40eea0002b03a64f452b4a2 | C++ | ArighnaIITG/DS-AL | /Algorithms/Greedy Algorithms/Job_Sequencing.cpp | UTF-8 | 2,519 | 4.1875 | 4 | [] | no_license | /*
Job Sequencing Problem :
Given an array of jobs where every job has a deadline and associated profit
if the job is finished before the deadline. It is also given that every job takes
single unit of time, so the minimum possible deadline for any job is 1.
How to maximize total profit if only one job can be scheduled at a time.
Example
=======
Input: Five Jobs with following deadlines and profits--
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output: Following is maximum profit sequence of jobs --
c, a, e
We can solve it using "Greedy Algorithm" :
1) Sort all jobs in decreasing order of profit.
2) Initialize the result sequence as first job in sorted jobs.
3) Do following for remaining n-1 jobs
. a) If the current job can fit in the current result sequence
without missing the deadline, add current job to the result.
Else ignore the current job.
Input to this program will be an array of structures.
*/
#include <iostream>
#include <bits/stdc++.h>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct Job
{
char id;
int dead;
int profit;
};
bool compareJobs(Job a, Job b)
{
return (a.profit > b.profit); // We have to sort jobs in descending order.
}
void printJobSequence(Job arr[], int n)
{
//Sort jobs according to the descending order of profit.
sort(arr, arr+n, compareJobs);
int result[n]; // Result sequence
bool slot[n]; // Queries about whether slots are free or not
// Initializing all slots to false now.
for(int i=0; i<n; i++)
slot[i] = false;
// Iterating through all the given jobs
for(int i=0; i<n; i++)
{
// Important - "We are starting from the last possible slot."
for(int j = min(n, arr[i].dead) -1; j>=0; j--)
{
// Find free slots
if(slot[j] == false)
{
result[j] = i; // Add this job to the result sequence
slot[j] = true; // Make this slot occupied.
break;
}
}
}
// Print the result sequence
for(int i=0; i<n; i++)
{
if(slot[i] == true)
cout << arr[result[i]].id << " - ";
}
}
int main()
{
Job arr[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27},
{'d', 1, 25}, {'e', 3, 15}};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Following is maximum profit sequence of jobs -- " << endl;
printJobSequence(arr, n);
return 0;
}
| true |
b58d26a6021d6e9bc4075f7c6271b78164ea8795 | C++ | fieldkit/firmware | /third-party/phylum/src/crc32.cpp | UTF-8 | 1,152 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | #include "phylum.h"
namespace phylum {
static uint32_t crc_table[16] = { 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
#define FLASH_READ_DWORD(x) (*(uint32_t *)(x))
uint32_t crc32_update(uint32_t crc, uint8_t data) {
uint8_t tbl_idx;
tbl_idx = crc ^ (data >> (0 * 4));
crc = FLASH_READ_DWORD(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
tbl_idx = crc ^ (data >> (1 * 4));
crc = FLASH_READ_DWORD(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
return crc;
}
uint32_t crc32_checksum(uint32_t previous, uint8_t const *data, size_t size) {
uint32_t crc = ~previous;
while (size-- > 0) {
crc = crc32_update(crc, *(data++));
}
return ~crc;
}
uint32_t crc32_checksum(uint8_t const *data, size_t size) {
return crc32_checksum((uint32_t)0, data, size);
}
uint32_t crc32_checksum(const char *str) {
return crc32_checksum(0x5c423de, (uint8_t *)str, strlen(str));
}
} // namespace phylum
| true |
dbdf573a4d374e7ef25d3afd4043e163b3a9bef1 | C++ | tjel/infpro-5 | /GUI/src/Widget.cpp | UTF-8 | 924 | 2.890625 | 3 | [] | no_license | #include "include/Widget.hpp"
Widget::Widget()
{
}
void Widget::setPosition(int x, int y)//Ustawianie Pozycji na poctawie x i y;
{
mPosition.x = x;
mPosition.y = y;
}
void Widget::setPosition(SDL_Point Pos)//Ustawianie Pozycji na poctawie Vector2<int>
{
mPosition = Pos;
}
void Widget::setSize(int w, int h)
{
mSize.x = w;
mSize.y = h;
}
void Widget::setSize(SDL_Point Size)
{
mSize.x = Size.x;
mSize.y = Size.y;
}
SDL_Point Widget::GetSize()
{
return mSize;
}
SDL_Point Widget::GetPosition()
{
return mPosition;
}
void Widget::Draw()
{
}
void Widget::handleEvent(SDL_Event * events)
{
}
SDL_Rect Widget::GetRect()
{
SDL_Rect temp {mPosition.x,mPosition.y,mSize.x,mSize.y};
return temp;
}
int Widget::GetMode()
{
return mode;
}
void Widget::setMode(int mMode)
{
mode = mMode;
}
std::shared_ptr<Widget> Widget::GetPtr()
{
return std::shared_ptr<Widget>(this);
}
| true |
13ab4d26a40d18b93eb06513128889ebe9719969 | C++ | wh-forker/game-programmer-road | /algorithms/temp/Code/JobDu_P1000.cpp | GB18030 | 404 | 3.34375 | 3 | [] | no_license | /*
ĿA+BעжǷķCC++Ҫ
*/
#include <iostream>
using namespace std;
int main()
{
int a,b;
while(std::cin >> a)
{
cin>>b;
cout<<a+b<<endl;
}
return 0;
}
/*
#include <stdio.h>
int main()
{
int a,b;
while(scanf("%d%d",&a,&b)!=EOF)
printf("%d\n",a+b );
return 0;
}
| true |
4b2bb2d368c17e54713fe9e6465d7b8830ba42ed | C++ | xiaoqiang0/leetcode | /clone-graph.cc | UTF-8 | 3,141 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <limits>
#include <queue>
#include <map>
#include <set>
using namespace std;
/**
* Definition for undirected graph.
*/
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
vector<UndirectedGraphNode *> v;
queue<UndirectedGraphNode *> Q;
if (node == NULL) return NULL;
Q.push(node);
v.push_back(node);
while (!Q.empty()) {
UndirectedGraphNode *p = Q.front();
vector<UndirectedGraphNode *> n = p->neighbors;
for (int i = 0; i < n.size(); i++){
if (find(v.begin(), v.end(), n[i]) == v.end()){
v.push_back(n[i]);
Q.push(n[i]);
}
}
Q.pop();
}
map<UndirectedGraphNode*, int>add2idx;
vector<vector<int> >idx2nei(v.size(), vector<int>());
vector<UndirectedGraphNode *> idx2add;
for (int i = 0; i < v.size(); i ++){
add2idx[v[i]] = i;
}
for (int i = 0; i < v.size(); i ++){
vector<UndirectedGraphNode *> &n = v[i]->neighbors;
for (int j = 0; j < n.size(); j++){
idx2nei[i].push_back(add2idx[n[j]]);
}
}
for (int i = 0; i < v.size(); i++){
idx2add.push_back(new UndirectedGraphNode(v[i]->label));
}
for (int i = 0; i < v.size(); i++){
vector<int> &nei = idx2nei[i];
for (int j = 0; j < nei.size(); j++)
idx2add[i]->neighbors.push_back(idx2add[nei[j]]);
}
return idx2add[0];
}
};
int main()
{
/*UndirectedGraphNode *node = new UndirectedGraphNode(1);
node->neighbors.push_back(new UndirectedGraphNode(0));
node->neighbors.push_back(new UndirectedGraphNode(2));
node->neighbors[0]->neighbors.push_back(node);
node->neighbors[0]->neighbors.push_back(node->neighbors[1]);
node->neighbors[1]->neighbors.push_back(node);
node->neighbors[1]->neighbors.push_back(node->neighbors[0]);
node->neighbors[1]->neighbors.push_back(node->neighbors[1]);
*/
vector<UndirectedGraphNode *> G;
G.push_back(new UndirectedGraphNode(-3)); //0
G.push_back(new UndirectedGraphNode(-1)); //1
G.push_back(new UndirectedGraphNode(2)); //2
G.push_back(new UndirectedGraphNode(3)); //3
G.push_back(new UndirectedGraphNode(5)); //4
G[0]->neighbors.clear();
G[0]->neighbors.push_back(G[1]);
G[0]->neighbors.push_back(G[3]);
G[0]->neighbors.push_back(G[4]);
G[1]->neighbors.clear();
G[1]->neighbors.push_back(G[2]);
G[1]->neighbors.push_back(G[3]);
G[1]->neighbors.push_back(G[3]);
G[2]->neighbors.clear();
G[2]->neighbors.push_back(G[3]);
G[3]->neighbors.clear();
G[3]->neighbors.push_back(G[4]);
G[4]->neighbors.clear();
Solution S;
S.cloneGraph(G[0]);
return 0;
}
| true |
397251f93217707217ef1dd1795dd22576625da6 | C++ | gianmarcosilluzio/CompetitiveProgramming | /CompetitiveProgramming/code/PreorderTraversal.cpp | UTF-8 | 1,379 | 3.765625 | 4 | [] | no_license | /*
* PreorderTraversal.cpp
*
* Created on: 13 nov 2017
* Author: Gianmarco Silluzio
* Problem: http://practice.geeksforgeeks.org/problems/preorder-traversal-and-bst/0
* Description Solution:
* The idea is find next greater element and after finding next greater (using a stack), if we find a smaller element, then return false.
Time complexity consists of looks each array element --> O(N)
Space complexity (space of array) + space of stack --> O(N)
*/
#include<iostream>
#include<climits>
#include<stack>
#include<vector>
using namespace std;
bool isBSTPreorder(vector<int> vec){
stack<int> s;
int root = INT_MIN;
for (int i = 0; i < vec.size(); i++){
if (vec[i] < root){
return false;
}
while (!s.empty() && vec[i] > s.top()){
root = s.top();
s.pop();
}
s.push(vec[i]);
}
return true;
}
int main() {
std::vector<int> vec;
int test = 0;
cin >> test;
for (int i = 0; i < test; ++i) {
int n = 0;
cin >> n;
vec.reserve(n);
for (int j = 0; j < n; j++) {
int elem = 0;
std::cin >> elem;
vec.push_back(elem);
}
cout << isBSTPreorder(vec) << endl;
vec.clear();
}
return 0;
}
| true |
873b1f732e9b268472e25d1967feebb0b5f034fa | C++ | kelvinismartian/algorithms | /Stackline.cpp | UTF-8 | 1,163 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
template <typename T>
class Stackline{
private:
int theSize;
int capacity;
T* Stack;
public:
Stackline(int size = 0, int capacity_temp = 10): theSize(size), capacity(capacity_temp){
Stack = new T[capacity_temp];
}
~Stackline(){
delete[] Stack;
}
bool isempty(){
return theSize == 0;
}
T pop(){
if(isempty()){
cout << "Stack is empty, nothing to pop...\n";
}
else{
return Stack[--theSize];
}
}
void push(T t){
if(theSize < capacity){
Stack[theSize] = t;
++theSize;
}
else{
cout << "Stack is full...\n";
}
}
T top(){
return Stack[theSize - 1];
}
int size(){
return theSize;
}
};
int main(){
Stackline<int> lt;
lt.push(10);
lt.push(100);
cout << lt.top() << endl;
lt.pop();
cout << lt.top() << endl;
return 0;
}
| true |
26c4ea946db054808825fdb7334aa24140a6e7a2 | C++ | psdhanesh7/Competitive-Coding | /connectingDots.cpp | UTF-8 | 2,948 | 3.71875 | 4 | [] | no_license | // Connecting Dots
// Gary has a board of size NxM. Each cell in the board is a coloured dot. There exist only 26 colours denoted by uppercase Latin characters (i.e. A,B,...,Z). Now Gary is getting bore and wants to play a game. The key of this game is to find a cycle that contain dots of same colour. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:
// 1. These k dots are different: if i ≠ j then di is different from dj.
// 2. k is at least 4.
// 3. All dots belong to the same colour.
// 4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.
// Since Gary is colour blind, he wants your help. Your task is to determine if there exists a cycle on the board.
// Assume input to be 0-indexed based.
// Input Format :
// Line 1 : Two integers N and M, the number of rows and columns of the board
// Next N lines : a string consisting of M characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
// Output Format :
// Return 1 if there is a cycle else return 0
// Constraints :
// 2 ≤ N, M ≤ 50
// Sample Input :
// 3 4
// AAAA
// ABCA
// AAAA
// Sample Output :
// 1
#include<bits/stdc++.h>
using namespace std;
#define MAXN 51
void deleteVisited(bool **visited, int n) {
for(int i = 0; i < n; i++) {
delete [] visited[i];
}
delete [] visited;
}
bool cyclePresent(char board[][MAXN], int n, int m, int row, int col, int startRow, int startCol, int depth, char prevChar, bool **visited) {
if(row >= n || col >= m || row < 0 || col < 0) {
return false;
}
if(row == startRow && col == startCol && depth >= 4) {
return true;
}
if(visited[row][col]) {
return false;
}
if(board[row][col] != prevChar) {
return false;
}
visited[row][col] = true;
if(cyclePresent(board, n, m, row, col+1, startRow, startCol, depth+1, prevChar, visited) || cyclePresent(board, n, m, row, col-1, startRow, startCol, depth+1, prevChar, visited) || cyclePresent(board, n, m, row+1, col, startRow, startCol, depth+1, prevChar, visited) || cyclePresent(board, n, m, row-1, col, startRow, startCol, depth+1, prevChar, visited)){
return true;
}
visited[row][col] = false;
return false;
}
int solve(char board[][MAXN],int n, int m)
{
// Write your code here.
bool **visited = new bool*[n];
for(int i = 0; i < n; i++) {
visited[i] = new bool[m];
for(int j = 0; j < m; j++) {
visited[i][j] = false;
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(cyclePresent(board, n, m, i, j, i, j, 0, board[i][j], visited)) {
deleteVisited(visited, n);
return 1;
}
}
}
deleteVisited(visited, n);
return 0;
}
int main()
{
int N,M,i;
char board[MAXN][MAXN];
cin>>N>>M;
for(i = 0;i < N; i++){
cin>>board[i];
}
cout<<solve(board,N,M)<<endl;
} | true |
17bbda3d4c58e81ddb2c81de87c5136725c3264f | C++ | jinubb/Algorithm | /c++/세 수.cpp | UTF-8 | 401 | 3.078125 | 3 | [] | no_license | #include<stdio.h>
int compare1(int x,int y){
if (x>y)
return x;
else
return y;
}
int compare2(int x, int y, int z){
return (compare1(compare1(x,y),z));
}
int main(void){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
int sol;
if(a==compare2(a,b,c)){
sol = compare1(b,c);
}
else if(b==compare2(a,b,c)){
sol = compare1(a,c);
}
else{
sol = compare1(a,b);
}
printf("%d",sol);
return 0;
}
| true |
f4c9e929ef78ddace66852e9a909ec697a7d1f26 | C++ | wangyongliang/nova | /poj/2619/POJ_2619_2974295_AC_0MS_88K.cpp | UTF-8 | 1,153 | 2.734375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
void f(int &x,int &y,int n,int &flag,int &deep)
{
int xx;
xx=(int) sqrt((double)n);
if(xx*xx==n) xx--;
int sum=(xx)*(xx);
xx++;
deep=xx;
//x=xx;
x=(n-sum)/2+(n-sum)%2;
flag=(n-sum)%2;
if(flag) y=xx-x+1;
else y=xx-x;
}
int main()
{
int n,m;
int ans;
int x1,y1,x2,y2,flag1,flag2,d1,d2;
while(scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
if(n>m) swap(n,m);
f(x1,y1,n,flag1,d1);
f(x2,y2,m,flag2,d2);
// printf("%d %d %d\n",x1,y1,flag1);
// printf("%d %d %d\n",x2,y2,flag2);
if(d1==d2)
{
ans=(x2-x1)*2;
if(flag1==0) ans--;
if(flag2==0) ans++;
}
else
{
if(x2<=x1)
{
ans=(x2-x1)*2;
y1+=(x2-x1);
ans+=(y2-y1)*2-1;
if(flag1) ans++;
if(flag2==0) ans++;
}
else
{
if(y1<=y2)
{
ans=(x2-x1)*2+(y2-y1)*2;
if(flag1==0) ans--;
if(flag2==0) ans++;
}
else
{
ans=(y1-y2)*2;
x1+=(y1-y2);
ans+=(x2-x1)*2-1;
if(flag1) ans++;
if(flag2==0) ans++;
}
}
}
printf("%d\n",ans);
}
return 0;
} | true |
a83cea0182ee1c7b57caedeaad90be09632206e0 | C++ | grokitgames/giga | /Source/Engine/Render/OpenGL/OpenGLDeferredRenderPass.hpp | UTF-8 | 1,003 | 2.609375 | 3 | [] | no_license |
#ifndef opengldeferredrenderpass_hpp
#define opengldeferredrenderpass_hpp
/**
* Built-in deferred rendering pass (combination of previous g-buffer pass + lighting)
*/
class GIGA_API OpenGLDeferredRenderPass : public PostProcessPass {
public:
OpenGLDeferredRenderPass() = default;
~OpenGLDeferredRenderPass() = default;
/**
* Set textures
*/
void SetDiffuseTexture(Texture2D* diffuse) { m_diffuse = diffuse; }
void SetNormalTexture(Texture2D* normal) { m_normal = normal; }
void SetPositionTexture(Texture2D* position) { m_position = position; }
void SetLightingTexture(Texture2D* lighting) { m_lighting = lighting; }
/**
* Render to window
*/
void Render(Scene* scene);
protected:
/**
* Initialize shader
*/
void InitializeShader();
protected:
// Pointers to textures from main render
Texture2D* m_diffuse;
Texture2D* m_normal;
Texture2D* m_position;
Texture2D* m_lighting;
};
#endif
| true |
22c3aa3b1881e23a3a5abd0a513a35ae4db3ab60 | C++ | James-Braun-SFU/reversi-with-AI | /Board.h | UTF-8 | 12,146 | 4.25 | 4 | [] | no_license | // Board.h
// To make it easier to keep track of and display various different piece types.
enum class Square : char {
empty = '.', human = 'o', computer = 'x'
};
// Keeps track of where two squares are in relation to one another.
struct Direction {
int dirRow;
int dirCol;
};
// Keeps track of where on the board a Square is.
struct Location {
int row;
int col;
};
// Board class
class Board {
private:
// The gameboard itself.
vector<vector<Square>> board;
// Keeps track of directions that result in valid moves.
vector<Direction> possibleDirections;
// Holds the positional heuristic value of controlling each square on the board.
vector<vector<int>> posTable;
public:
// Board constructor
Board()
: board(8)
{
// Sets every square on the board to be empty.
for(int i = 0; i < board.size(); i++) {
board[i] = vector<Square>(8, Square::empty);
}
// Sets the four middle squares to standard Reversi starting positions.
board[3][3] = Square::computer;
board[3][4] = Square::human;
board[4][4] = Square::computer;
board[4][3] = Square::human;
}
void clear_board(){
// Sets every square on the board to be empty.
for(int i = 0; i < board.size(); i++) {
board[i] = vector<Square>(8, Square::empty);
}
// Sets the four middle squares to standard Reversi starting positions.
board[3][3] = Square::computer;
board[3][4] = Square::human;
board[4][4] = Square::computer;
board[4][3] = Square::human;
}
// Returns the width of the gameboard.
int width() const {
return board[0].size();
}
// Returns the height of the gameboard.
int height() const {
return board.size();
}
// Returns the game piece at a Square.
// Already assumes the Square is on the board.
Square get(int r, int c) const {
return board[r][c];
}
// Places a Square on the board of a certain type (i.e. Human or Computer).
// Already assumes the board location is valid.
void set(int r, int c, const Square& s) {
board[r][c] = s;
}
// Sets the table containing the positional heuristic value of controlling each square on the board.
void set_positional_table(const vector<vector<int>>& ptbl) {
posTable = ptbl;
}
// Returns the positional worth of a given square.
int get_postional_square_score(Location loc) {
int r = loc.row;
int c = loc.col;
return posTable[r][c];
}
// Calculates the positional strength of the player's board.
// Does this by adding up the positional worth of all the player's pieces
// and subtracting the positional worth of all the opponent's pieces.
int get_positional_board_score(Square s, Square opp) {
int score = 0;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
if (board[r][c] == s) {
score += posTable[r][c];
} else if (board[r][c] == opp) {
score -= posTable[r][c];
}
}
}
return score;
}
// Searches all the squares of the board and returns the number of pieces on it for a given player.
int num_pieces(Square s) const {
int count = 0;
for(int i = 0; i < height(); i++) {
for (int j = 0; j < width(); j++) {
if (board[i][j] == s) {
count++;
}
}
}
return count;
}
// Checks if a Square is on the gameboard or not.
bool on_board(int row, int col) const {
return (0 <= row && row <= 7)
&& (0 <= col && col <= 7);
}
// Checks all Squares of the board to see if a move is available.
bool move_exists(Square s) const {
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
if (valid_move(r, c, s)) {
return true;
}
}
}
return false;
}
// Takes in a string from the user that represents a move.
// Checks to see if the move is valid and prints error helpful error message if it is not.
bool valid_move (string move, Square s) const {
// It's invalid if the user ever enters a string that is not two characters long.
if (move.size() != 2) {
cout << "Invalid move, improper format, please re-enter.\n";
return false;
}
int r = move.at(1)-49;
int c = move.at(0)-97;
// It's invalid if the user enters a Square that is not on the board.
if (!on_board(r, c)) {
cout << "Invalid move, square not on board, please re-enter.\n";
return false;
}
// The Square must be empty for a move to be made on it.
if (board[r][c] != Square::empty) {
cout << "Invalid move, piece already in space, please re-enter.\n";
return false;
}
// If any pieces are flipped by the making of the move then the move is valid.
if (valid_move(r, c, s)){
return true;
} else {
cout << "Invalid move, cannot flip any pieces, please re-enter.\n";
return false;
}
}
// Checks if a move is valid for any direction.
// If any direction would result in pieces being flipped, then it is a valid move.
// n and m represent the vertical and horizontal directions from the Square.
// Assumes Square is on the board.
bool valid_move(int r, int c, Square s) const {
if (board[r][c] != Square::empty) {
return false;
}
for (int n = -1; n < 2; n++) {
for (int m = -1; m < 2; m++) {
if (valid_move(r, c, n, m, s)) {
return true;
}
}
}
return false;
}
// Checks if a move for a player in a certain direction is valid.
// y and x represent the vertical and horizontal coordinates of the Square after moved in the m/n direction
bool valid_move(int r, int c, int n, int m, Square s) const {
int y = r+n;
int x = c+m;
// If moving in that direction takes you off the board, it is not valid.
if (!on_board(y, x)){
return false;
}
// Placing a piece adjacent to another of the same type is not a valid move
// (at least in the direction between the two pieces)
if (get(y, x) == s) {
return false;
}
// Keep moving in the same direction until another anchor piece is found (which makes the move valid)
// Or if you move off the board or hit an empty square then the move is not valid in that direction
while (on_board(y, x)) {
if (get(y, x) == s) {
return true;
} else if (get(y, x) == Square::empty) {
return false;
} else {
y+=n;
x+=m;
}
}
return false;
}
// Returns the number of empty squares on the board.
int num_empty_squares() {
int sum = 0;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
if (board[r][c] == Square::empty) {
sum++;
}
}
}
return sum;
}
// Returns a vector containing all the valid moves the player can make.
vector<Location> get_valid_moves(Square s) const {
vector<Location> valid_moves;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
if (valid_move(r, c, s)) {
valid_moves.push_back(Location{r,c});
}
}
}
return valid_moves;
}
// Returns a random valid move the player can make.
Location get_random_move(Square s) const {
vector<Location> possibilities = get_valid_moves(s);
int index = rand() % possibilities.size();
return possibilities[index];
}
// Returns the best move the player can make using a variety of heuristics.
Location get_combined_move(Square s, Square opp) {
vector<Location> possibilities = get_valid_moves(s);
vector<double> good_moves;
double positional_score;
double opp_moves;
double flipped;
double temp_score;
// The weights of all the heuristics.
// Determined these myself through trial and error.
double w1 = 1;
double w2 = 0.3;
double w3 = 0.8;
double w4 = 0;
vector<double> all_scores;
for (int i = 0; i < possibilities.size(); i++) {
int r = possibilities[i].row;
int c = possibilities[i].col;
// Creates a temporary board to make each move on.
Board tempBoard = *this;
tempBoard.make_move(possibilities[i], s);
// Returns the positional score of the player's pieces after the move has been made.
positional_score = tempBoard.get_positional_board_score(s, opp);
// Returns how many moves the opponent can make after the move has been made.
opp_moves = tempBoard.get_valid_moves(opp).size();
// Returns how many pieces will get flipped after the move has been made.
flipped = calc_score(r, c, s);
// The weights get adjusted during the late-game.
// Again, I created these weights myself through trial and error.
if (num_empty_squares() <= 10) {
w1 = 0.1;
w2 = 0.6;
w3 = 0;
w4 = 4;
}
// Weights the heuristics to generate a single score for a move.
temp_score = (w1 * positional_score) + (w2 * (100 / (opp_moves + 1))) + (w3 * (100 / (flipped + 1))) + (w4 * 100 * flipped);
all_scores.push_back(temp_score);
}
// Determines which moves result in the greatest score.
// Breaks ties randomly.
double max_score = *max_element(all_scores.begin(), all_scores.end());
for (int i = 0; i < all_scores.size(); i++) {
if (all_scores[i] == max_score) {
good_moves.push_back(i);
}
}
int good_index = rand() % good_moves.size();
return possibilities[good_moves[good_index]];
}
// Assumes a valid move is passed in
void make_move(string userMove, Square s) {
int r = userMove.at(1)-49;
int c = userMove.at(0)-97;
Location move {r, c};
make_move(move, s);
}
// First determine which directions can flip pieces,
// then for each direction that works, flip the pieces in that direction (all the ones that are flippable).
void make_move(Location move, Square s) {
int r = move.row;
int c = move.col;
for (int n = -1; n < 2; n++) {
for (int m = -1; m < 2; m++) {
if (valid_move(r, c, n, m, s)) {
possibleDirections.push_back(Direction{n, m});
}
}
}
set(r, c, s);
for (Direction &d : possibleDirections) {
make_move(r, c, d.dirRow, d.dirCol, s);
}
// Clears the possible directions vector for the next move.
possibleDirections.clear();
}
// Flips pieces on the gameboard in a certain direction.
void make_move(int r, int c, int n, int m, Square s) {
int x = c+m;
int y = r+n;
while (board[y][x] != s) {
set(y, x, s);
y+=n;
x+=m;
}
}
// Returns how many pieces would be flipped in a certain direction if a move was made.
int test_move(int r, int c, int n, int m, Square s) const {
int count = 0;
int x = c+m;
int y = r+n;
while (board[y][x] != s) {
count++;
y+=n;
x+=m;
}
return count;
}
// Calculates how many pieces a move would score if made.
// Very similar to the make_move functions.
int calc_score(int r, int c, Square s) {
int count = 0;
if (valid_move(r, c, s)) {
for (int n = -1; n < 2; n++) {
for (int m = -1; m < 2; m++) {
if (valid_move(r, c, n, m, s)) {
possibleDirections.push_back(Direction{n, m});
}
}
}
for (Direction &d : possibleDirections) {
count += test_move(r, c, d.dirRow, d.dirCol, s);
}
possibleDirections.clear();
count++;
}
return count;
}
// Prints the gameboard.
// Includes an A-H and 1-8 coordinate system to help the user.
void print() const {
cout << " ";
for (int i = 0; i < width(); i++) {
char c = 'a' + i;
cout << c << " ";
}
cout << endl;
for(int i = 0; i < height(); i++) {
cout << i + 1 << " ";
for (int j = 0; j < width(); j++) {
cout << char(board[i][j]) << " ";
}
cout << endl;
}
// Prints the number of pieces each player has.
cout << " Player 1 (O): " << num_pieces(Square::human) << endl;
cout << " Player 2 (X): " << num_pieces(Square::computer) << endl;
}
// Prints the gameboard with a new line feed.
void println() const {
print();
cout << endl;
}
// Prints the results of the game after it completes.
// Says who won and what the final score was.
void print_results() const {
cout << "The game is over as no one can make a move.\n";
if (num_pieces(Square::computer) > num_pieces(Square::human)) {
cout << "Player 2 wins by a score of "
<< num_pieces(Square::computer) << " to " << num_pieces(Square::human) << ".\n";
} else if (num_pieces(Square::computer) < num_pieces(Square::human)) {
cout << "Player 1 wins by a score of "
<< num_pieces(Square::human) << " to " << num_pieces(Square::computer) << ".\n";
} else {
cout << "It's a tie as both players scored: "
<< num_pieces(Square::human) << " points.\n";
}
}
}; // Class Board | true |
280bc55173bad2abb5493d3cb3f3213a72986d89 | C++ | InternationalDefy/AdvenTri-Cocos | /Classes/ES_Dash.cpp | GB18030 | 1,830 | 2.625 | 3 | [
"MIT"
] | permissive | #include "Ref2EnemyState.h"
using namespace cocos2d;
CREATE_ENEMYSTATE(ES_Dash);
void ES_Dash::enterFrom(M_EnemyState* stateFrom)
{
getOwner()->getPhysicsBody()->setVelocityLimit(1400.0f);
getOwner()->dash();
}
/*
úڲexitúµstateTo֮
ͬʱжڴͷŲ
*/
void ES_Dash::exitTo(M_EnemyState* stateTo)
{
//run a standred end animation or sth?
//maybe some logic update like
getOwner()->getPhysicsBody()->setVelocityLimit(700.0f);
getOwner()->setState(stateTo);
}
void ES_Dash::initState()
{
_state = AdvenTriEnum::EnemyState::E_STATE_DASH;
setClockTime(0);
setLimitTime(10.0f);
count = 0;
}
void ES_Dash::handleAction(AdvenTriEnum::EnemyAction action)
{
switch (action)
{
case AdvenTriEnum::E_ACTION_DASH:
break;
case AdvenTriEnum::E_ACTION_SKILL1:
exitToGather(1);
break;
case AdvenTriEnum::E_ACTION_SKILL2:
exitToGather(2);
break;
case AdvenTriEnum::E_ACTION_SKILL3:
exitToGather(3);
break;
case AdvenTriEnum::E_ACTION_SKILL4:
exitToGather(4);
break;
case AdvenTriEnum::E_ACTION_ATTACK:
getOwner()->dashAttack();
exitToStandred();
break;
case AdvenTriEnum::E_ACTION_PARRY:
getOwner()->parry();
exitToStandred();
break;
case AdvenTriEnum::E_ACTION_HURT:
onHurt();
exitToStandred();
break;
default:
break;
}
}
void ES_Dash::updateMethod(float dt)
{
count += dt;
if (count > 0.1f)
{
auto sp = Sprite::create("TriAngle.png");
sp->setPosition(getOwner()->getPosition());
sp->setColor(Color3B(255, 0, 0));
sp->setOpacity(128);
sp->runAction(FadeOut::create(0.1f));
sp->setRotation(getOwner()->getRotation());
getOwner()->getParent()->addChild(sp, 0);
count = 0;
return;
}
return;
}
void ES_Dash::onHurt()
{
if (getOwner()->isHurting())
{
return;
}
getOwner()->doHurt();
} | true |
cce314b5768e80fe5a94cad7907b1e4d8f3bdd05 | C++ | rueiminl/Leetcode | /Substring with Concatenation of All Words.cpp | UTF-8 | 1,075 | 2.8125 | 3 | [] | no_license | class Solution {
public:
bool check(string s, multiset<string>& comp) {
unsigned len = (*comp.begin()).length();
multiset<string> strs;
for (unsigned i = 0; i < s.length(); i += len) {
string sub = s.substr(i, len);
if (comp.find(sub) == comp.end())
return false;
strs.insert(sub);
}
return (strs == comp);
}
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> ret;
if (L.empty()) {
for (unsigned i = 0; i < S.length(); i++)
ret.push_back(i);
return ret;
}
multiset<string> comp;
for (unsigned i = 0; i < L.size(); i++) {
comp.insert(L[i]);
}
int len = L.size() * L[0].length();
for (unsigned i = 0; i < S.length(); i++) {
if (i + len > S.length())
break;
if (check(S.substr(i, len), comp))
ret.push_back(i);
}
return ret;
}
}; | true |