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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c2f5f1b0fc1ebc244d009cda2793f6c5045b5398 | C++ | sajalagrawal/BugFreeCodes | /GeeksforGeeks/Largest square formed in a matrix.cpp | UTF-8 | 940 | 2.53125 | 3 | [] | no_license | //https://practice.geeksforgeeks.org/problems/largest-square-formed-in-a-matrix/0
//https://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
//Author- Sajal Agrawal
//sajal.agrawal1997@gmail.com
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MOD 1000000007
#define pb push_back
int main() {
int t,n,m,i,j;
cin>>t;
while(t--){
cin>>n>>m;
int g[n][m];
int dp[n][m]={0},ans=1; //minimum answer is always 1
for(i=0;i<n;i++){
for(j=0;j<m;j++){
cin>>g[i][j];
dp[i][j]=g[i][j];
}
}
for(i=1;i<n;i++){
for(j=1;j<m;j++){
if(g[i][j]==1 and g[i-1][j-1]==1 and g[i-1][j]==1 and g[i][j-1]==1){
dp[i][j]=min(dp[i-1][j-1],min(dp[i][j-1],dp[i-1][j]))+1;
ans=max(ans,dp[i][j]);
}
}
}
cout<<ans<<endl;
}
return 0;
}
| true |
ab8867544602d7e891aba98769804bf4acbe1b02 | C++ | ldematte/projectC | /Operand.h | UTF-8 | 4,756 | 2.796875 | 3 | [] | no_license |
#ifndef _OPERAND_H_INCLUDED_
#define _OPERAND_H_INCLUDED_
#include <iostream>
#include <stdio.h>
#include <string>
#include "common.h"
//cambia se siamo nel compilatore o nella vm
#ifdef COMPILER_ENVIRONMENT
#define STRING_TABLE StringTable::GetSingleton()
#else
#include "VirtualMachine/RTStringTable.h"
#define STRING_TABLE RTStringTable::GetSingleton()
#endif //COMPILER_ENVIRONMENT
#include "compiler/symbol.h"
#include "compiler/StringTable.h"
#include <Object.h>
#define REG_EBP 0
#define REG_EIP 1
#define REG_ESP 2
#define REG_RET 3
#define REG_A 4
#define REG_B 5
#define REG_C 6
#define REG_D 7
#define REG_E 8
#define REG_NUMBER 9
enum OPTYPE
{
//immediate values
OP_TYPE_INT,
OP_TYPE_FLOAT,
OP_TYPE_STRING,
OP_TYPE_ABS_STACK_INDEX,
OP_TYPE_REL_STACK_INDEX,
OP_TYPE_OBJECT, //Object*
OP_TYPE_POINTER, //char*
OP_TYPE_ARRAY,
OP_TYPE_INSTR_INDEX,
OP_TYPE_FUNC,
OP_TYPE_REG,
OP_TYPE_OBJECT_TAG,
OP_TYPE_TYPE_TAG,
//not fully resolved reference to the symbol table
//valid only in I-Code
OP_TYPE_SYMBOL,
OP_TYPE_TYPE
};
class Operand
{
public:
OPTYPE type_id;
union
{
int intLiteral;
float floatLiteral;
int stringLiteralIdx;
//e metterere i SymPtr nel codice intremedio??
int absStackIndex;
int relStackIndex;
int instrIndex;
int funcIndex;
Object* objAddr;
char* pointer;
int regCode;
tag_t objectTag;
TYPE_TYPE typeTag;
//this is valid ONLY in I-Code
SymPtr symbol;
TypePtr type;
};
private:
const char* regCodeToName(int regCode) const
{
switch (regCode)
{
case REG_EBP:
return "_EBP";
case REG_EIP:
return "_EIP";
case REG_ESP:
return "_ESP";
case REG_RET:
return "_RET";
case REG_A:
return "_A";
case REG_B:
return "_B";
case REG_C:
return "_C";
case REG_D:
return "_D";
}
return "_UNKN";
}
public:
Operand() { }
Operand(int i)
{
type_id = OP_TYPE_INT;
intLiteral = i;
}
Operand(Object* o)
{
type_id = OP_TYPE_OBJECT;
objAddr = o;
}
Operand(float f)
{
type_id = OP_TYPE_FLOAT;
floatLiteral = f;
}
Operand(const std::string& s)
{
int idx = StringTable::GetSingleton().insert(s);
stringLiteralIdx = idx;
type_id = OP_TYPE_STRING;
}
Operand(SymPtr sym)
{
symbol = sym;
type_id = OP_TYPE_SYMBOL;
}
Operand(char* p)
{
type_id = OP_TYPE_POINTER;
pointer = p;
}
int retrieveOperandAsInt() const;
float retrieveOperandAsFloat() const;
Operand retrieveOperandAsOperand() const;
char* retrieveOperandAsPointer() const;
char* retrievePointerToOperand() const;
Operand resolveOperand() const;
Operand fullyResolveOperand() const;
void storeOperand(int value);
void storeOperand(float value);
void storeOperand(Operand value);
void storeOperand(char* value);
void storeOperand(Object* value);
void storeStringOperand(int index);
bool isEqual(const Operand& other)
{
return (type_id == other.type_id && absStackIndex == other.absStackIndex);
}
void dump()
{
dump(stderr);
}
void dump(FILE* f)
{
switch(type_id)
{
case OP_TYPE_STRING:
fprintf(f, " \"%s\" ", STRING_TABLE.getString(stringLiteralIdx).c_str());
break;
case OP_TYPE_SYMBOL:
fprintf(f, " %s ", symbol->name.c_str());
break;
case OP_TYPE_FUNC:
fprintf(f, " func #%d ", funcIndex);
break;
case OP_TYPE_REG:
fprintf(f, " REG%s ", regCodeToName(regCode));
//VirtualMachine::GetSingleton().registers[intLiteral].dump(f);
break;
case OP_TYPE_FLOAT:
fprintf(f, " %f ", floatLiteral);
break;
case OP_TYPE_OBJECT_TAG:
fprintf(f, " object no:%d", (int)objectTag);
break;
case OP_TYPE_TYPE_TAG:
fprintf(f, " type no:%d", typeTag);
break;
case OP_TYPE_OBJECT:
fprintf(f, " 0x%x ", (ptrdiff_t)objAddr);
if (objAddr && (objAddr != (Object*)BAD_PTR) )
{
fprintf(f, " (data: 0x%x), ", (ptrdiff_t)objAddr->data);
fprintf(f, " (is: %d,", (int)(objAddr->actualID));
fprintf(f, " was: %d)", (int)(objAddr->originalID));
fprintf(f, " COUNT: %d", objAddr->data->refCount);
}
break;
case OP_TYPE_ARRAY:
fprintf(f, " 0x%x ", (ptrdiff_t)objAddr);
if (objAddr && (objAddr != (Object*)BAD_PTR) )
{
fprintf(f, " ARRAY (data: 0x%x)", (ptrdiff_t)objAddr->getData());
}
break;
case OP_TYPE_POINTER:
fprintf(f, " 0x%x ", (ptrdiff_t)pointer);
break;
default:
fprintf(f, " %d ", intLiteral);
break;
}
}
};
#endif //_OPERAND_H_INCLUDED_
| true |
69df2ed4cd6372a028a716e9bf749d8b541b62de | C++ | WesleyMatthews/Hour-of-CPP | /Conditions/Conditions.cpp | UTF-8 | 798 | 4.5 | 4 | [] | no_license | #include <iostream>
int main()
{
// Creates a double with a value of 3.5
// Doubles are like integers, but with decimal points
double x = 3.5;
// Runs the below code "block" if x > 1
if (x > 1)
{
std::cout << "x > 1\n";
}
// If x == 1 (if x is equal to 1), then this code will run
// Else if is another way of saying "or, if this...then this"
else if (x == 1)
{
std::cout << "x == 1\n";
}
// Otherwise it will run the below code
// Else if is another way of saying "otherwise, then this"
else
{
std::cout << "x < 1\n";
}
// Exercise 3 - Try running the code with "Local Windows". What is the result?
// Now, change the value of x and see how that affects what the console prints
return 0;
} | true |
8a8f9e6ddb64b42d891545b1685328a6c5e93e0d | C++ | jlochman/JForex | /DataController/GenericDataController.h | UTF-8 | 1,054 | 2.609375 | 3 | [] | no_license | /*
* GenericDataController.h
*
* Created on: Jun 22, 2015
* Author: jlochman
*/
#include <vector>
#include "TTree.h"
using namespace std;
#ifndef DATACONTROLLER_GENERICDATACONTROLLER_H_
#define DATACONTROLLER_GENERICDATACONTROLLER_H_
class GenericDataController {
public:
GenericDataController(string branchName);
virtual ~GenericDataController();
void addValue(double x);
void pushForwardValue(double x);
void reverseOrder();
void setValue(int pos, double x);
double getValue(int pos);
string getName();
const string& getClassName() const;
void write(TTree* t, int length, bool first = true);
void read(TTree* t);
void empty();
const vector<double>& getVec() const;
void setVec(const vector<double>& vec);
int getHistNeeded() const;
int getVecSize();
void setVecSize( int vec_size );
virtual void calculate(int maxCount) = 0;
protected:
vector<double> m_vec;
string m_branchName;
string m_className;
int m_calcIncrement;
int histNeeded;
};
#endif /* DATACONTROLLER_GENERICDATACONTROLLER_H_ */
| true |
711470260118cdac22e7fae267fd40546f218f42 | C++ | BlinkDrink/Introduction-To-Programming | /05-Loops/Exercise1_PP.cpp | UTF-8 | 622 | 3.5 | 4 | [] | no_license | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
/*
Да се напише програма, която въвежда цяло положително число n и печата правоъгълен триъгълник от звездички с размер n.
Пример:
Вход: 1
Изход: *
Вход: 3
Изход:
*
* *
* * *
*/
void printTriangle(int n)
{
for (int row = 0; row <= n; row++)
{
for (int k = 0; k < row; k++)
{
cout << '*';
}
cout << endl;
}
}
int main()
{
int n;
cin >> n;
printTriangle(n);
} | true |
4da5072ec353c8c0c9a9f58f09886e96ab6a8923 | C++ | baodijun/pixel | /contrib/simd/ndk-hello-neon/src/helloneon.cpp | UTF-8 | 5,949 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "helloneon-intrinsics.h"
#include "fastMalloc.h"
// return current time in milliseconds
static double now_ms(void)
{
struct timespec res;
clock_gettime(CLOCK_REALTIME, &res);
return 1000.0*res.tv_sec + (double)res.tv_nsec/1e6;
}
// this is a FIR filter implemented in C
static void fir_filter_c(short* output, const short* input, const short* kernel, int width, int kernelSize)
{
int offset = -kernelSize/2;
for (int i=0; i<width; i++) {
int sum = 0;
for (int j=0; j<kernelSize; j++) {
sum += kernel[j]*input[i+offset+j];
}
output[i] = (short)((sum + 0x8000) >> 16);
}
}
static void fir_filter_c_fast(short* output, const short* input, const short* kernel, int width, int kernelSize)
{
int offset = -kernelSize/2;
const short* buf = input + offset;
for (int i=0; i<width; i++) {
int sum = 0;
for (int j=0; j<kernelSize; j++) {
sum += kernel[j]*buf[j];
}
output[i] = (short)((sum + 0x8000) >> 16);
buf++;
}
}
static void perf_fir_filter(const int fir_iterations)
{
printf("-----------------------------\n");
printf("perf with fir_iterations=%d\n", fir_iterations);
printf("-----------------------------\n");
char* str;
char buffer[512];
const int fir_kernel_size = 32;
const int fir_output_size = 2560;
const int fir_input_size = (fir_output_size + fir_kernel_size);
short fir_input_0[fir_input_size];
// fir_input_0相当于是fir_input做padding
const short* fir_input = fir_input_0 + (fir_kernel_size/2);
short fir_output[fir_output_size];
short fir_output_expected[fir_output_size];
static const short fir_kernel[fir_kernel_size] = {
0x10, 0x20, 0x40, 0x70, 0x8c, 0xa2, 0xce, 0xf0, 0xe9, 0xce, 0xa2, 0x8c, 0x70, 0x40, 0x20, 0x10,
0x10, 0x20, 0x40, 0x70, 0x8c, 0xa2, 0xce, 0xf0, 0xe9, 0xce, 0xa2, 0x8c, 0x70, 0x40, 0x20, 0x10
};
// setup FIR input - whatever
{
for (int i=0; i<fir_input_size; i++) {
fir_input_0[i] = (5*i) & 255;
}
fir_filter_c(fir_output_expected, fir_input, fir_kernel, fir_output_size, fir_kernel_size);
}
//---------------------------------------------
// Benchmark small FIR filter loop - C version
//--------------------------------------------
double t_start, t_cost_c, t_cost_c_fast, t_cost_neon, t_cost_neon_fast;
t_start = now_ms();
{
for (int i=0; i<fir_iterations; i++) {
fir_filter_c(fir_output, fir_input, fir_kernel, fir_output_size, fir_kernel_size);
}
}
t_cost_c = now_ms() - t_start;
asprintf(&str, "FIR Filter benchmark:\nC version: %g ms\n", t_cost_c);
strlcpy(buffer, str, sizeof(buffer));
free(str);
//------------------------------------------------
// Benchmark small FIR filter loop - C fast
//------------------------------------------------
strlcat(buffer, "C fast version: ", sizeof(buffer));
t_start = now_ms();
{
for (int i=0; i<fir_iterations; i++) {
fir_filter_c_fast(fir_output, fir_input, fir_kernel, fir_output_size, fir_kernel_size);
}
}
t_cost_c_fast = now_ms() - t_start;
asprintf(&str, "%g ms (x%g faster)\n", t_cost_c_fast, t_cost_c / (t_cost_c_fast < 1e-6 ? 1. : t_cost_c_fast));
strlcat(buffer, str, sizeof(buffer));
free(str);
//------------------------------------------------
// Benchmark small FIR filter loop - Neon version
//------------------------------------------------
strlcat(buffer, "Neon version: ", sizeof(buffer));
t_start = now_ms();
{
for (int i=0; i<fir_iterations; i++) {
fir_filter_neon_intrinsics(fir_output, fir_input, fir_kernel, fir_output_size, fir_kernel_size);
}
}
t_cost_neon = now_ms() - t_start;
asprintf(&str, "%g ms (x%g faster)\n", t_cost_neon, t_cost_c / (t_cost_neon < 1e-6 ? 1. : t_cost_neon));
strlcat(buffer, str, sizeof(buffer));
free(str);
//------------------------------------------------
// Benchmark small FIR filter loop - Neon fast
//------------------------------------------------
strlcat(buffer, "Neon fast version: ", sizeof(buffer));
t_start = now_ms();
{
for (int i=0; i<fir_iterations; i++) {
fir_filter_neon_fast(fir_output, fir_input, fir_kernel, fir_output_size, fir_kernel_size);
}
}
t_cost_neon_fast = now_ms() - t_start;
asprintf(&str, "%g ms (x%g faster)\n", t_cost_neon_fast, t_cost_c / (t_cost_neon < 1e-6 ? 1. : t_cost_neon_fast));
strlcat(buffer, str, sizeof(buffer));
free(str);
// check the result, just in case
{
int fails = 0;
for (int i=0; i<fir_output_size; i++) {
if (fir_output[i] != fir_output_expected[i]) {
if (++fails < 16) {
printf("neon[%d] = %d expected %d", i, fir_output[i], fir_output_expected[i]);
}
}
}
printf("%d fails\n", fails);
}
printf("%s\n", buffer);
}
int main() {
perf_fir_filter(10);
perf_fir_filter(100);
perf_fir_filter(1000);
//perf_fir_filter(10000);
return 0;
}
| true |
dd8bcbb591443c3de03a587fc02d5281123c75c9 | C++ | Garrybest/coding-interviews | /src/q36.cpp | UTF-8 | 933 | 3.078125 | 3 | [] | no_license | /*
* 二叉搜索树与双向链表
* @Author: garryfang
* @Date: 2019-09-05 13:08:52
* @Last Modified by: garryfang
* @Last Modified time: 2019-09-05 13:14:42
*/
#include <utility>
#include "BinaryTreeNode.h"
std::pair<BinaryTreeNode *, BinaryTreeNode *> convertCore(BinaryTreeNode *root)
{
if (!root)
return {nullptr, nullptr};
auto &&left = convertCore(root->left), &&right = convertCore(root->right);
std::pair<BinaryTreeNode *, BinaryTreeNode *> range{root, root};
if (left.second)
{
left.second->right = root;
root->left = left.second;
range.first = left.first;
}
if (right.first)
{
right.first->left = root;
root->right = right.first;
range.second = right.second;
}
return std::move(range);
}
BinaryTreeNode *convert(BinaryTreeNode *root)
{
if (!root)
return nullptr;
return convertCore(root).first;
}
| true |
61cd4cff149897eaf2d65af4792e8bd31b8c9669 | C++ | setsmdeveloper/SETSM | /grid.cpp | UTF-8 | 1,715 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | #include "grid_types.hpp"
template <typename GridType, typename IterType>
Grid<GridType, IterType>::Grid(INDEX width, INDEX height, GridPoint *points[], std::size_t num_points)
{
this->grid = new GridType(width, height, points, num_points);
}
template <typename GridType, typename IterType>
Grid<GridType, IterType>::~Grid()
{
delete this->grid;
}
template <typename GridType, typename IterType>
std::size_t Grid<GridType, IterType>::GetAllTris(std::vector<Tri> *tris)
{
// Loop over all points in triangulation, collecting adjacent triangles
// To prevent 'over-counting' only collect triangle from its smallest vertex
// Should be able to be parallelized, but haven't yet found a good one.
// Be wary, list order does matter
for (auto p_it = this->PointBegin(); p_it != this->PointEnd(); p_it++)
{
Edge *e = this->GetElem(*p_it);
Edge *f = e->twin->dnext->twin->dnext; // If degree of current point is 1 or 2, then f == e
GridPoint p1 = e->orig;
GridPoint p2 = e->twin->orig;
GridPoint p3 = e->twin->dnext->twin->orig;
// Check that degree > 2 or
// at least edge(s) out not parallel
if ((f != e) || !((p1.col - p2.col)*(p1.row - p3.row) == (p1.row - p2.row)*(p1.col - p3.col)))
{
for (auto t_it = this->AdjTriBegin(*p_it); t_it != this->AdjTriEnd(*p_it); t_it++)
{
GridPoint *points = *t_it;
if (LessThanXY(points[0], points[1]) && LessThanXY(points[0], points[2]))
{
Tri temp_tri;
temp_tri.pts[0] = points[0];
temp_tri.pts[1] = points[1];
temp_tri.pts[2] = points[2];
tris->push_back(temp_tri);
}
}
}
}
return tris->size();
}
template class Grid<SparseGrid, SparsePointIter>;
template class Grid<FullGrid, FullPointIter>;
| true |
f891004bbf1dcc5929ae58326fbb52690cba0b8f | C++ | acgtun/gpu-perm | /mpi-perm/option.cpp | UTF-8 | 3,168 | 2.640625 | 3 | [] | no_license | #include "option.h"
void PrintSynopsis() {
printf(
"The input command is incorrect. please reference the following command. \n "
"./MPImapping [reference file or index file] [reads file]\n");
}
int GetStrVal(int argc, char** argv, const char* str, string & strVal) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], str) == 0 && i + 1 <= argc - 1) {
if (argv[i + 1][0] != '-') {
strVal = argv[i + 1];
return 1;
}
}
}
return 0;
}
int ChkStrExist(int argc, char** argv, const char* str) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], str) == 0) {
return 1;
}
}
return 0;
}
void GetNameBeforeDot(const string & strFile, string & fileName) {
int pos = strFile.find_last_of('.');
fileName = strFile.substr(0, pos);
}
void GetReadLength(Option & opt) {
ifstream fin(opt.readsFile.c_str());
if (!fin.good()) {
printf("--ERROR INFO-- reads file open error. %s\n", opt.readsFile.c_str());
exit (EXIT_FAILURE);
}
opt.nNumOfreads = 0;
string strLine;
while (getline(fin, strLine)) {
if (strLine[0] == '>') {
opt.nNumOfreads++;
continue;
}
opt.readLen = strLine.size();
break;
}
while (getline(fin, strLine)) {
if (strLine[0] == '>') {
opt.nNumOfreads++;
continue;
}
if (opt.readLen != strLine.size()) {
printf("--ERROR INFO-- The lengths of the reads are not identical.\n");
exit (EXIT_FAILURE);
}
}
fin.close();
INFO("There are", opt.nNumOfreads, "reads in the reads file");
INFO("The length of the read is", opt.readLen);
}
bool isBuildIndex(const string strVal, const string strFind) {
if (strVal.find(strFind) != string::npos)
return true;
return false;
}
void GetParameter(int argc, char* argv[], Option & opt) {
cout << "--INFO-- Input command:";
for (int i = 0; i < argc; i++) {
cout << " " << argv[i];
}
cout << endl;
/* reference file name */
opt.refFile = argv[1];
cout << "--INFO-- The reference file is " << opt.refFile << endl;
/* determine the index file exist of not */
opt.bIndexExist = 0;
string indexsf = ".sdindex";
if (opt.refFile.size() > indexsf.size()
&& opt.refFile.substr(opt.refFile.size() - indexsf.size()) == indexsf) {
opt.bIndexExist = 1;
}
if (!isBuildIndex(argv[0], "buildindex")) {
opt.readsFile = argv[2];
cout << "--INFO-- The reads file is " << opt.readsFile << "." << endl;
}
/* setting the output file name */
if (GetStrVal(argc, argv, "-o", opt.outputFile) == 0) {
string fileName;
GetNameBeforeDot(opt.readsFile, fileName);
opt.outputFile = fileName;
opt.outputFile += ".out";
}
/* determine whether save the index file or not*/
opt.bSaveIndex = 0;
if (ChkStrExist(argc, argv, "-s")) {
opt.bSaveIndex = 1;
}
if ((GetStrVal(argc, argv, "-s", opt.indexFile) == 0 && opt.bSaveIndex == 1)
|| isBuildIndex(argv[0], "buildindex")) {
string fileName;
opt.bSaveIndex = 1;
GetNameBeforeDot(opt.refFile, fileName);
opt.indexFile = fileName;
opt.indexFile += indexsf;
}
if (opt.bSaveIndex != 1)
GetReadLength(opt);
}
| true |
693863103d6f0d799db248723548e7bd328368bf | C++ | ngoral/improc | /Week 1/Task 1/change_levels.cpp | UTF-8 | 1,789 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <stdexcept>
#include <string>
#include "improc.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
static const unsigned STD_LEVELS_NUMBER = 256;
std::string getImageName(int argc, char** argv)
{
return (argc > 2) ? argv[2] : "no_signal.png";
}
bool isPowerOfTwo(unsigned number)
{
return (number & (number - 1)) == 0;
}
bool LevelValid(unsigned value)
{
return value >= 2 && value <= 256 && isPowerOfTwo(value);
}
unsigned short levelsNumber(int argc, char** argv)
{
if (argc > 1)
{
if (LevelValid(std::stoi(argv[1])))
return std::stoi(argv[1]);
else
throw std::runtime_error("Wrong intensity levels number `" + std::string(argv[1]) + "'");
}
else
throw std::runtime_error("Could not find intensity levels number. Usage: ./change_levels levels_number [image_name] ");
}
cv::Mat changeLevels(const cv::Mat& original, unsigned short int levels)
{
cv::Mat newImage = original.clone();
unsigned short int coefficient = STD_LEVELS_NUMBER / levels; //always power of 2
for(auto pixel = newImage.begin<uchar>(), end = newImage.end<uchar>(); pixel != end; ++pixel)
*pixel = (*pixel / coefficient) * coefficient;
return newImage;
}
int main(int argc, char** argv)
{
try {
unsigned short levels = levelsNumber(argc, argv);
std::string imageName = getImageName(argc, argv);
cv::Mat image = readImage(imageName);
cv::Mat newImage = changeLevels(image, levels);
cv::imwrite("changed" + filenameExtension(imageName), newImage);
showImage(newImage);
return 0;
}
catch (const std::exception& e) {
std::cerr << "change_levels: " << e.what() << std::endl;
return 1;
}
} | true |
a1ce263cd3bd4632166df9888c7d4d0e0562e32e | C++ | wupsi/PP1_2021_Spring | /2018/Midterm, V1/I.cpp | UTF-8 | 372 | 2.765625 | 3 | [] | no_license | // Rightmost set bit
// Перевод в двоичное число
#include <iostream>
using namespace std;
int main(){
int num = 0, ans = 0, d = 1, cnt = 0;
cin >> num;
while(num){
ans += (num % 2) * d;
num /= 2;
d *= 10;
}
while(ans % 10 == 0){
cnt++;
ans /= 10;
}
cout << cnt;
}
| true |
40dd2268deb7ad653ae219c31feadba6f47d0c40 | C++ | alexander-hamme/Tadpole-Tracker-Cpp | /src/util/circular_buffer.h | UTF-8 | 1,112 | 3.4375 | 3 | [] | no_license | //
// Created by alex on 2/7/19.
//
#ifndef SPROJ_CPP_CIRCULARBUFFER_H
#define SPROJ_CPP_CIRCULARBUFFER_H
#endif
#include <vector>
using namespace std;
typedef struct {
int x;
int y;
} Point;
class CircularBuffer {
public:
// explicit CircularBuffer(int cap) // initialize vector with capacity
// : capacity(cap), elements(static_cast<unsigned int>(cap)) {};
CircularBuffer(int cap);
void add(Point pt);
int getFront();
int getRear();
int getSize();
bool isAtCapacity();
bool isEmpty();
vector<Point> getElements();
void printPoints();
private:
const int capacity;
vector<Point> elements;
// elements are inserted into array starting at the end,
// right to left. This allows simple left to right traversal
// by traveling circularly around the array from `front` to `rear`,
// while still accessing the elements in FIFO order of insertion.
int front = capacity; // this is decremented by 1 before the first insertion
int rear = capacity-1; // rear stays at first insertion idx and doesn't change until buffer reaches full capacity
bool at_capacity = false;
};
| true |
9ac728457ab0f49e97507aca5ae84a75cd6303e3 | C++ | sumsuddin/micro-service | /source/request_handlers/request_handler.cpp | UTF-8 | 2,500 | 2.890625 | 3 | [
"MIT"
] | permissive |
#include "request_handler.h"
RequestHandler::RequestHandler(const std::string service_name, const std::string service_version) {
RequestHandler::service_name = service_name;
RequestHandler::service_version = service_version;
}
void RequestHandler::handle_get_request(http_request &message) {
auto path = request_path(message);
if (!path.empty()) {
if (path.size() == 2 && path[0] == "service" && path[1] == "test") {
auto response = json::value::object();
response["response"] = json::value::string("test!");
message.reply(status_codes::OK, response);
} else {
message.reply(status_codes::NotFound, response_path_not_found());
}
} else {
message.reply(status_codes::OK, response_service_info());
}
}
void RequestHandler::handle_post_request(http_request &message) {
auto path = request_path(message);
if (!path.empty()) {
if (path.size() == 2 && path[0] == "service" && path[1] == "test") {
auto response = json::value::object();
response["response"] = json::value::string("test!");
message.reply(status_codes::OK, response);
} else {
message.reply(status_codes::NotFound, response_path_not_found());
}
} else {
message.reply(status_codes::OK, response_service_info());
}
}
void RequestHandler::handle_put_request(http_request &message) {
message.reply(status_codes::NotImplemented, response_not_impl(methods::PUT));
}
std::vector<utility::string_t> RequestHandler::request_path(const http_request & message) {
auto relativePath = uri::decode(message.relative_uri().path());
return uri::split_path(relativePath);
}
json::value RequestHandler::response_not_impl(const http::method & method) {
auto response = json::value::object();
response["http_method"] = json::value::string(method);
response["response"] = json::value::string("Not Implemented");
return response ;
}
json::value RequestHandler::response_path_not_found() {
auto response = json::value::object();
response["response"] = json::value::string("Path Not Found");
return response ;
}
json::value RequestHandler::response_service_info() {
auto response = json::value::object();
response["service_name"] = json::value::string(service_name);
response["version"] = json::value::string(service_version);
response["status"] = json::value::string("ready!");
return response;
} | true |
dcac9fdabf34fce66ce48b080563ff19b0ca8fec | C++ | Allowed/Protheus | /src/Core/Networking/CConnection.cpp | UTF-8 | 528 | 2.609375 | 3 | [] | no_license | #include "CConnection.h"
using namespace Pro;
using namespace Networking;
CBuffer CConnection::recv(){
const auto buffer = inputStack.front();
inputStack.pop();
return move(buffer);
}
void CConnection::send(CBuffer& _buffer){
// clones the buffer to be sent
CBuffer buf(_buffer);
mutex.lock();
outputStack.push(buf);
mutex.unlock();
}
bool CConnection::isConnected(){
return connected.load() ? true : false;
}
unsigned CConnection::peek(){
if (inputStack.empty())
return 0;
return inputStack.front().size();
}
| true |
db41369fe806aef487b5218aa5e54bf94c951a3c | C++ | vadiraj89/CodingPratice | /Test/src/Scheduler.cpp | UTF-8 | 1,007 | 2.875 | 3 | [] | no_license | #include "Scheduler.h"
#include "Job.h"
#include <bits/stdc++.h>
using namespace std;
Scheduler::Scheduler(int t)
{
this->threads = t;
for(int i=0;i<t;i++){
queue<Job *> q ;
this->thread_queue.push_back(q);
}
}
Scheduler::~Scheduler()
{
//dtor
}
//virtual vector<pair<int,Job *>> Scheduler::getPQ(vector<Job *> jobs)=0;
void Scheduler::schedule(vector<Job *> jobs){
vector<pair<int,Job *>> pq = this->getPQ(jobs);
for(auto i:pq){
Job * job = i.second;
time_t currenttime;
time(¤ttime);
if(difftime(currenttime, job->entry_time)<=job->deadline){
int index = 0;
int queue_size = INT_MAX;
for(int i=0;i<this->thread_queue.size();i++){
if(this->thread_queue[i].size()<queue_size){
index = i;
queue_size = this->thread_queue[i].size();
}
}
this->thread_queue[index].push(job);
}
}
}
| true |
136e0817575a039a5ce1de382f9fa3d06f2e3d1a | C++ | sdimosik/spbspu-labs-2020-904-4 | /maksimova.anastasia/A3/main.cpp | UTF-8 | 1,980 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <stdexcept>
#include <string>
#include <memory>
#include "rectangle.hpp"
#include "circle.hpp"
#include "composite-shape.hpp"
int main()
{
try
{
maksimova::Rectangle rec(2, 3, {1, 1});
maksimova::Rectangle rec0(13, 53, {2, 3});
maksimova::Circle circ(3, {6, 6});
maksimova::Shape *rec1 = &rec;
std::cout << "Info about Rectangle1:\n";
rec1->getFrameRect().print();
std::cout << "Area = " << rec1->getArea() << "\n\n";
maksimova::Shape *rec2 = &rec0;
maksimova::point_t position{15, 15};
std::cout << "Info about Rectangle2:\n";
rec2->move(position);
rec2->move(1, 0);
rec2->print();
std::cout << "Area = " << rec2->getArea() << "\n\n";
maksimova::Shape *circ1 = ˆ
std::cout << "Info about Circle1:\n";
circ1->print();
maksimova::point_t position0{25, 13};
circ1->move(position0);
circ1->move(1, 2);
std::cout << "\nAfter the shift\n";
circ1->print();
std::cout << "Area = " << circ1->getArea() << "\n";
std::shared_ptr<maksimova::Shape> shape1 = std::make_shared<maksimova::Rectangle>(rec);
std::shared_ptr<maksimova::Shape> shape2 = std::make_shared<maksimova::Circle>(circ);
std::shared_ptr<maksimova::Shape> shape3 = std::make_shared<maksimova::Rectangle>(rec0);
maksimova::CompositeShape shapes(3);
shapes.addShape(shape1);
shapes.addShape(shape2);
shapes.addShape(shape3);
std::cout << "Composite shape after adding three shapes: ";
shapes.print();
shapes.scale(2);
std::cout << "Composite shape after amplification in two times: ";
shapes.print();
std::cout << "Composite shape after moving: ";
shapes.move({2.5, 12.4});
shapes.print();
maksimova::CompositeShape shapes2 = shapes;
std::cout << "Second composite shape equal to the first: ";
shapes2.print();
}
catch(const std::exception &exc)
{
std::cerr << exc.what() << '\n';
return 1;
}
return 0;
}
| true |
d0cb722577b95fbdbe7b785f164732a70a8c043f | C++ | dingfen/SoftwareWordList | /Project1/GUI/src/WordGraph.cpp | UTF-8 | 3,999 | 3.25 | 3 | [] | no_license | #include "WordGraph.h"
#include <fstream>
#include <cctype>
#include <algorithm>
#include <cstdlib>
unordered_map<string, bool> parseLine(string line)
{
size_t pos;
string alpha("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
unordered_map<string, bool> ret;
pos = line.find_first_not_of(alpha);
while (pos != string::npos)
{
string sub = line.substr(0, pos);
if (sub.size() > 0)
ret.insert(pair<string, bool>(sub, false));
line.erase(0, pos + 1);
pos = line.find_first_not_of(alpha);
}
if (line.size() > 0)
ret.insert(pair<string, bool>(line, false));
return ret;
}
WordGraph::~WordGraph()
{
}
void WordGraph::create(string filename)
{
ifstream fin;
fin.open(filename.c_str(), ios::in);
if (!fin)
{
cerr << "The file " << filename.c_str() << "cannot be found.\n"
<< endl;
exit(1);
}
// 对文件进行分割 一行行地进行
string line;
do
{
getline(fin, line);
unordered_map<string, bool> s = parseLine(line);
words.insert(s.begin(), s.end());
} while (!fin.eof());
// 建立图矩阵
for (auto s : words)
{
char head = s.first.front();
char tail = s.first.back();
head = tolower(head);
tail = tolower(tail);
// cout<<head<<" "<<tail<<endl;
heads.insert(head);
tails.insert(tail);
this->table[head - 'a'][tail - 'a'].push_back(s.first);
}
fin.close();
}
vector<vector<string>> WordGraph::getList()
{
return List;
}
vector<string> WordGraph::wordDFS(char head, char tail, int num)
{
// 遍历所有的单词,然后DFS 求出最长的单词链 并保存
if (head == '\0' && tail == '\0')
{
// 直接求最长链
for (auto w : heads)
{
// 取出首字母
ret.clear();
findLongestWordList(w, num);
}
}
else if (head == '\0' && tail != '\0')
{
ret.clear();
reverseLongestWordList(tail, num);
reverse(max.begin(), max.end());
if(num!=-1)
for(auto &s : List)
reverse(s.begin(), s.end());
}
else if (head != '\0' && tail == '\0')
{
ret.clear();
findLongestWordList(head, num);
}
else
{
ret.clear();
findLongestWordList(head, tail, num);
}
if(max.size() < 2 && List.size() == 0) {
return vector<string>();
}
return max;
}
vector<string> WordGraph::alphaDFS(char head, char tail, int num)
{
if (head == '\0' && tail == '\0')
{
for (auto w : heads)
{
ret.clear();
findLongestAlphaList(w, num);
}
}
else if (head == '\0' && tail != '\0')
{
ret.clear();
reverseLongestAlphaList(tail, num);
reverse(max.begin(), max.end());
}
else if (head != '\0' && tail == '\0')
{
ret.clear();
findLongestAlphaList(head, num);
}
else
{
ret.clear();
findLongestAlphaList(head, tail, num);
}
return max;
}
unordered_map<string, bool> WordGraph::getwords()
{
return this->words;
}
bool WordGraph::isNull()
{
return words.size() == 0;
}
void WordGraph::create(QString text)
{
QStringList lineList = text.split("\n");
// 对文件进行分割 一行行地进行
for (int i=0; i<lineList.size(); i++)
{
string line = lineList.at(i).toStdString();
unordered_map<string, bool> s = parseLine(line);
words.insert(s.begin(), s.end());
}
// 建立图矩阵
for (auto s : words)
{
char head = s.first.front();
char tail = s.first.back();
head = tolower(head);
tail = tolower(tail);
// cout<<head<<" "<<tail<<endl;
heads.insert(head);
tails.insert(tail);
this->table[head - 'a'][tail - 'a'].push_back(s.first);
}
}
| true |
b4930062f0b67213866e6a2df5a516884f4a6dcd | C++ | blacksea3/leetcode | /cpp/leetcode/598. range-addition-ii.cpp | GB18030 | 350 | 2.953125 | 3 | [] | no_license | #include "public.h"
//4ms, 100%
//opsСa b ij˻
class Solution {
public:
int maxCount(int m, int n, vector<vector<int>>& ops) {
if (ops.empty()) return m * n;
int mina = INT_MAX;
int minb = INT_MAX;
for (auto& op : ops)
{
mina = min(mina, op[0]);
minb = min(minb, op[1]);
}
return mina * minb;
}
};
| true |
ba990824b423f8f10853026e678d4584c56c056b | C++ | qiaohaijun/my-leetcode | /solution_pool/345-reverse-vowels-of-a-string/solution.cc | UTF-8 | 701 | 3.5 | 4 | [] | no_license | class Solution {
public:
bool isVowel(char s){
if(s=='a'|| s=='o'|| s=='e'|| s=='i'|| s=='u'){
return true;
}
if(s=='A'|| s=='O'|| s=='E'|| s=='I'|| s=='U'){
return true;
}
return false;
}
string reverseVowels(string s) {
if(s.size()<=1){
return s;
}
int i = 0;
int j = s.size()-1;
while(i<j){
while(!isVowel(s[i]) ){
++i;
}
while(!isVowel(s[j]) ){
--j;
}
if(i<j){
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
++i;
--j;
}
}
return s;
}
};
| true |
3e2b09403432da8442c97e2ed8f6d5d0c5504aa1 | C++ | sajantanand/CSC112 | /Examples/structTest.cpp | UTF-8 | 1,076 | 4.125 | 4 | [] | no_license | //Testing passing of structs with pointers
#include <iostream>
using namespace std;
struct Test
{
int *ptr1;
int *ptr2;
//Test(int x, int y);
Test(int x, int y)
{
cout << "reached constructor" << endl;
ptr1 = new (nothrow) int(x);
ptr2 = new (nothrow) int(x);
cout << "creating struct with address " << this << ", " <<ptr1 << " and " << ptr2 << endl;
};
//Test(const int& x, const int& y) : *ptr1(x), *ptr2(y) {};
~Test()
{
cout << "deleting struct with address " << this << ", " <<ptr1 << " and " << ptr2 << endl;
delete ptr1;
delete ptr2;
};
};
/*Test::Test(int x, int y)
{
cout << "reached constructor" << endl;
(*ptr1) = x;
(*ptr2) = y;
//cout << "creating struct with address " << this << ", " <<ptr1 << " and " << ptr2 << endl;
}*/
void increment(Test tester);
int main()
{
Test first(3,4);
//Test first();
increment(first);
return 0;
}
void increment(Test tester)
{
(*(tester.ptr1))++;
(*(tester.ptr2))++;
cout << "modifying struct with address " << &tester << ", " << tester.ptr1 << " and " << tester.ptr2 << endl;
} | true |
ab52d516180c98ac0cec419ee7d970375d2eea40 | C++ | harshithkrpt/cpp | /cpp_prog_lang_book/6_types_and_declarations/6.2.3.1_signed_unsigned_chars.cpp | UTF-8 | 771 | 3.578125 | 4 | [] | no_license | #include<iostream>
using namespace std;
void f(char c,signed char sc,unsigned char uc){
/* char *pc = &uc; // error
signed char * psc = pc; // error
unsigned char *puc = pc; // error
psc = pus;
*/
}
// assigning too large values to signed values is undefined
void g(char c,signed char sc,unsigned char uc)
{
c = 255; // if plain char are signed and have 8 bits
c = sc; // ok
sc = uc; // implementation-defined if plain chars are signed and if uc’s value is too large
uc = sc; // ok
sc = c; // implementation-defined if plain chars are unsigned and if c’s value is too large
uc = c; // ok
}
int main()
{
signed char sc = -160;
unsigned char uc = sc; // uc == 116 (256-116)
cout << uc;
char count[256];
++count[sc];
++count[uc];
return 0;
}
| true |
da586afeb46b9eaf20e7338b6f34be183f9bcee4 | C++ | DopaminaInTheVein/ItLightens | /Engine/app_modules/gui/gui_utils.h | UTF-8 | 2,207 | 3.015625 | 3 | [] | no_license | #ifndef INC_MODULE_GUI_UTILS_H_
#define INC_MODULE_GUI_UTILS_H_
struct RectNormalized {
float x; float y;
float sx; float sy;
RectNormalized(float _x, float _y, float _sx, float _sy) :
x(_x), y(_y), sx(_sx), sy(_sy) {
assert(_x <= 1.f);
assert(_y <= 1.f);
assert(_sx <= 1.f);
assert(_sy <= 1.f);
}
RectNormalized() : x(0), y(0), sx(1.f), sy(1.f) {}
RectNormalized subRect(RectNormalized sub);
const RectNormalized operator/=(float v);
const RectNormalized& operator/(float v);
const RectNormalized& operator*(float v);
};
struct Rect {
int x; int y;
int sx; int sy;
Rect(int _x, int _y, int _sx, int _sy) :
x(_x), y(_y), sx(_sx), sy(_sy) {}
Rect() : x(0), y(0), sx(100), sy(100) {}
Rect(RectNormalized r);
};
struct Pixel {
int x;
int y;
Pixel() : x(0), y(0) {}
Pixel(int _x, int _y) : x(_x), y(_y) {}
};
namespace Font {
struct TCharacter {
private:
RectNormalized text_coords;
RectNormalized text_coords2;
float space_right; //horizontal size grid
int size; //horizontal size grid
char c;
std::string special_character;
VEC4 color = obtainColorNormFromString("#000000FF");
public:
TCharacter() : text_coords(RectNormalized()), size(0.f) {}
TCharacter(unsigned char c);
TCharacter(std::string special_char);
TCharacter(std::string name, int row, int col, float space_right, float size);
static TCharacter NewLine();
RectNormalized GetTxtCoords() { return text_coords; }
RectNormalized GetTxtCoords2() { return text_coords2; }
int GetSize() { return size; }
float GetSpaceRight() { return space_right; }
VEC4 GetColor() { return isSpecial() ? obtainColorNormFromString("#FFFFFFFF") : color; }
bool IsNewLine() { return c == '\n'; }
bool IsSpace() { return c == ' '; }
void SetColor(std::string new_color) { color = obtainColorNormFromString(new_color); }
bool isSpecial() { return c == '*'; }
int getCharInt() { unsigned char cc = c; return cc; }
};
typedef std::vector<TCharacter> VCharacter;
RectNormalized getTxtCoords(unsigned char c);
VCharacter getVChar(std::string text);
VCharacter formatVChar(VCharacter vchar, float row_size);
}
#endif
| true |
14c168d06cf891719258c84976f14f42214a38ef | C++ | mtboswell/mtboswell-auvc2 | /src/sal/drivers/old/camera/v4l2libex.cpp | UTF-8 | 1,796 | 2.6875 | 3 | [] | no_license | #include "v4l2lib.cpp"
static void
usage (FILE * fp,
int argc,
char ** argv)
{
fprintf (fp,
"Usage: %s [options]\n\n"
"Options:\n"
"-d | --device name Video device name [/dev/video]\n"
"-h | --help Print this message\n"
"-m | --mmap Use memory mapped buffers\n"
"-r | --read Use read() calls\n"
"-u | --userp Use application allocated buffers\n"
"",
argv[0]);
}
static const char short_options [] = "d:hmru";
static const struct option
long_options [] = {
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "mmap", no_argument, NULL, 'm' },
{ "read", no_argument, NULL, 'r' },
{ "userp", no_argument, NULL, 'u' },
{ 0, 0, 0, 0 }
};
int
main (int argc,
char ** argv)
{
dev_name = "/dev/video";
for (;;) {
int index;
int c;
c = getopt_long (argc, argv,
short_options, long_options,
&index);
if (-1 == c)
break;
switch (c) {
case 0: /* getopt_long() flag */
break;
case 'd':
dev_name = optarg;
break;
case 'h':
usage (stdout, argc, argv);
exit (EXIT_SUCCESS);
case 'm':
io = IO_METHOD_MMAP;
break;
case 'r':
io = IO_METHOD_READ;
break;
case 'u':
io = IO_METHOD_USERPTR;
break;
default:
usage (stderr, argc, argv);
exit (EXIT_FAILURE);
}
}
open_device ();
init_device ();
start_capturing ();
capture_loop ();
stop_capturing ();
uninit_device ();
close_device ();
exit (EXIT_SUCCESS);
return 0;
}
| true |
3e25a0f8b0406671643097277e1dc3cca36fc55a | C++ | kidrigger/N-Body-Simulator | /quad.hpp | UTF-8 | 1,001 | 2.734375 | 3 | [] | no_license | //
// quad.hpp
// nbody_bh
//
// Created by Anish Bhobe on 6/29/17.
// Copyright © 2017 Anish Bhobe. All rights reserved.
//
#ifndef quad_h
#define quad_h
#include "Eigen/Core"
using Eigen::Vector3d;
namespace Celestial {
class Quad {
public:
// Center of the quad
Vector3d center;
// Half of the side of the quad
double halfside;
// Side of the quad
double side;
// Constructs a quad as per info
Quad(const Vector3d& center, double side):center(center),halfside(side/2),side(side) {}
// Checks if the quad contains the particular point
// returns true if it does
bool Contains(Vector3d point) {
return (point[0] >= center[0] + halfside ||
point[0] < center[0] - halfside ||
point[1] >= center[1] + halfside ||
point[1] < center[1] - halfside )?false:true;
}
};
}
#endif /* quad_h */
| true |
b0404bab5bbe3cf26a88ba5bc7c045522dabcdab | C++ | Lazer7/Platform-Game | /src/Map.cpp | UTF-8 | 1,512 | 3.0625 | 3 | [] | no_license | #include "Map.h"
#include <iostream>
using namespace std;
/**
Map deconstructor
*/
Map::~Map(){
//dtor
SDL_DestroyTexture(this->spriteSheetTexture);
spriteSheetTexture=NULL;
}
/**
Initalizes the map with image
*/
void Map:: init(const char* spriteMap){
setTexture(spriteMap);
}
/**
Sets Map image
*/
void Map::setTexture(const char* spriteMap){
SDL_Surface* tempSurface = IMG_Load(spriteMap);
spriteSheetTexture = SDL_CreateTextureFromSurface(WindowProperties::renderer, tempSurface);
SDL_FreeSurface(tempSurface);
}
/**
Draws 2 map images onto the renderer
*/
void Map::render(){
render( scrollOffset, 0 );
render( scrollOffset + WindowProperties::windowValue.width, 0 );
}
/**
Draws a map onto the renderer at a given position
*/
void Map::render( int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip ){
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, WindowProperties::windowValue.width, WindowProperties::windowValue.height };
//Set clip rendering dimensions
if( clip != NULL ){
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
//Render to screen
SDL_RenderCopyEx( WindowProperties::renderer, spriteSheetTexture, clip, &renderQuad, angle, center, flip );
}
/**
Updates the Scrolling of the map in the background
*/
void Map::update(){
//Scroll background
--scrollOffset;
if( scrollOffset < -WindowProperties::windowValue.width){
scrollOffset = 0;
}
}
| true |
ba139ba26abfffed9685cf1424b6602ffb2f207a | C++ | dogePrince/oj | /poj/4145/4145.cpp | UTF-8 | 1,020 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int n, k;
int R[1000], C[1000];
double Y[1000];
int check(double v) {
for (int i = 0; i < n; i++) {
Y[i] = R[i] - v * C[i];
}
double sum = 0;
sort(Y, Y + n);
for (int i = k; i < n; i++) {
sum += Y[i];
}
if (sum >= 0) {
return 1;
}
return 0;
}
int main(int argc, char const *argv[]) {
scanf("%d %d", &n, &k);
while (n != 0 && k != 0) {
for (int i = 0; i < n; i++) {
scanf("%d", R+i);
}
for (int i = 0; i < n; i++) {
scanf("%d", C+i);
}
double start = 0;
double end = 1;
double mid;
while (end - start > 1e-4) {
mid = (end + start) / 2;
if (check(mid)) {
start = mid;
}
else {
end = mid;
}
}
printf("%.0lf\n", mid*100);
scanf("%d %d", &n, &k);
}
return 0;
}
| true |
6428c42f43fea3832fa24b983815a7b9f9d32384 | C++ | 543877815/algorithm | /leetcode周赛/6180. Smallest Even Multiple.cpp | UTF-8 | 264 | 2.953125 | 3 | [] | no_license | class Solution {
public:
int gcb(int a, int b)
{
int c = 0;
while(c = a % b)
{
a = b;
b = c;
}
return b;
}
int smallestEvenMultiple(int n) {
return n * 2 / gcb(n, 2);
}
}; | true |
a2ec4ccb0adb906b247629956442f796304548d7 | C++ | XuZhichao1998/SegmentTree-kuangbin | /POJ_2528_poster/poj2528_min.cpp | UTF-8 | 6,049 | 3.375 | 3 | [] | no_license | /*
POJ 2528
Authon: XuZhichao
2021.2.8 18.29
*/
// 线段树维护区间最小值。
// 我们规定原来不贴海报的颜色为0,第i张海报的颜色为i(1<=i<=n)
// 我们将询问离散化。原来不相邻的点离散化后也至少要隔开一个单元(差值>=2),因为这样可以保证不会把原来下放露出的海报完全遮挡
// 如果倒序处理海报。那么在贴每张海报的时候,关心的问题仅仅是当前区间还有没有空白的单元。如果有空白的单元,表示是后面海报没有遮挡的单元。我们直
// 接查询区级最小值,如果最小值M为0,则说明还有空白的地方。
// 查询之后如果M为0,我们答案就+1 然后我们进行更新。把这张海报覆盖的范围全部涂色(区间赋值)即可。涂什么颜色不重要,大于0即可。
// 所以离散化,倒叙处理以后,我们可以转化为简答的 线段树维护区间最小值。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <cassert>
class SegmentTreeColor {
public:
const static int ROOT_INDEX;
const static int INF;
void _init(int max_length);
SegmentTreeColor();
~SegmentTreeColor();
void build(int left, int right, int root);
int update(int left, int right, int root, int update_left, int update_right, int value); //区间赋值
int query(int left, int right, int root, int query_left, int query_right); //查询区间最小值
private:
int * _min_value; //记录区间最小值
bool * _vis; //lazy标签,是否需要push_down
void push_down(int root);
};
const int SegmentTreeColor::ROOT_INDEX = 1; //线段树默认根节点编号为1,后面则可以满足lson = root*2 rson = root*2+1
const int SegmentTreeColor::INF = 1E9; //大于离线询问总数(贴海报总数)即可
SegmentTreeColor::SegmentTreeColor() {
_min_value = NULL;
_vis = NULL;
}
void SegmentTreeColor::_init(int max_length) {
_min_value = new int[max_length+1];
_vis = new bool[max_length+1];
}
SegmentTreeColor::~SegmentTreeColor() {
if (!_min_value) {
delete [] _min_value;
}
if (!_vis) {
delete [] _vis;
}
}
void SegmentTreeColor::build(int left, int right, int root) {
_min_value[root] = 0;
_vis[root] = false;
if (left == right) {
return;
}
int mid = (left + right) >> 1;
build(left, mid, root<<1);
build(mid+1, right, root<<1|1);
}
int SegmentTreeColor::update(int left, int right, int root, int update_left, int update_right, int value) {
if (update_left > right || update_right < left) {
return _min_value[root];
} else if (update_left <= left && right <= update_right) {
_vis[root] = true;
return _min_value[root] = value;
} else {
int mid = (left + right) >> 1;
push_down(root);
int min_lson = update(left, mid, root<<1, update_left, update_right, value);
int min_rson = update(mid+1, right, root<<1|1, update_left, update_right, value);
return _min_value[root] = std::min(min_lson,min_rson);
}
}
int SegmentTreeColor::query(int left, int right, int root, int query_left, int query_right) {
if (query_left > right || query_right < left) {
return SegmentTreeColor::INF;
} else if (query_left <= left && right <= query_right) {
return _min_value[root];
} else {
int mid = (left + right) >> 1;
push_down(root);
int min_lson = query(left, mid, root<<1, query_left, query_right);
int min_rson = query(mid+1, right, root<<1|1, query_left, query_right);
return std::min(min_lson, min_rson);
}
}
void SegmentTreeColor::push_down(int root) {
if (_vis[root]) {
_min_value[root<<1] = _min_value[root<<1|1] = _min_value[root];
_vis[root<<1] = _vis[root<<1|1] = true;
_vis[root] = false;
}
}
const int MAXN = 10000+5;
int main(int argc, const char * argv[]) {
if (argc == 2) {
freopen(argv[1],"r",stdin);
}
int T, n, left, right;
scanf("%d", &T);
std::pair<int,int> * intervals = new std::pair<int,int>[MAXN];
int * arr = new int[MAXN*2];
SegmentTreeColor * ptree = new SegmentTreeColor();
ptree->_init(MAXN*16); //10000个区间,20000个数。离散化要求原先不相邻的也不能相邻,最坏情况为每个数之间都差2,40000,线段树4倍空间
while (T--) {
scanf("%d", &n);
int cnt = 0;
for (int i = 0; i < n; ++i) {
scanf("%d%d", &left, &right);
intervals[i] = std::make_pair(left, right);
arr[cnt++] = left;
arr[cnt++] = right;
}
std::sort(arr, arr+cnt);
cnt = std::unique(arr, arr+cnt) - arr; //cnt为去重后元素的个数
std::map<int,int> mp;
mp[arr[0]] = 1;
int max_length = 1;
for (int i = 1; i < cnt; ++i) {
if (arr[i] == arr[i-1] + 1) {
mp[arr[i]] = ++max_length;
} else {
max_length +=2;
mp[arr[i]] = max_length;
}
}
ptree->build(1, max_length, SegmentTreeColor::ROOT_INDEX);
int ans = 0;
for (int i = n-1; i >= 0; --i) {
left = mp[intervals[i].first];
right = mp[intervals[i].second];
int cur_min = ptree->query(1, max_length, SegmentTreeColor::ROOT_INDEX, left, right);
if (cur_min == 0) { //0代表初始没贴海报的值。表示这个区间还有空的地方没有被后面的覆盖。post[i]可以露出来。
++ans;
}
//最后一个参数i+1代表当前海报的颜色。其实我们并不关心具体什么颜色。传递大于0的任何参数都可以
ptree->update(1, max_length, SegmentTreeColor::ROOT_INDEX, left, right, i+1);
}
printf("%d\n", ans);
}
delete ptree;
delete []intervals;
delete []arr;
if (argc == 2) {
fclose(stdin);
}
return 0;
}
| true |
37052f3ebff3148fb531debb3f051bc433f6b69a | C++ | adityadev31/OOPS_cpp | /oops/8_static_data_members/2.cpp | UTF-8 | 622 | 3.59375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Shopkeeping{
private:
static int sno;
int *array, size;
public:
void incSerial(){ ++sno; }
void add_items(int a){
size = a;
array = new int[size];
for(int i=0; i<size; i++){
cout<<"Enter item-"<<i+1<<"\t";
cin>>array[i];
incSerial();
}
}
void show_details(){
int i=0;
while(i != size){ cout<<sno<<"\t"<<array[i]<<endl; i++; }
}
};
int Shopkeeping::sno;
int main(){
Shopkeeping ob1,ob2,ob3;
ob1.add_items(5);
ob2.add_items(3);
ob1.show_details();
ob2.show_details();
return 0;
}
| true |
4daa59037e7c57c60d259eef348940606d9fb163 | C++ | abhinaba-fbr/CP_utilities | /Heap/MinHeap.hpp | UTF-8 | 2,720 | 3.90625 | 4 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
/* create a MinHeap -
MinHeap mh; O(1)
MinHeap mh(vector<int>); O(n)
MinHeap mh=vector<int>; O(n)
mh.createheapFromVector(vector<int>); // use this only if not initialized O(n)
inserting elements
mh.insert(int); O(log(n))
getting the minimum element
int e=mh.extractMin(); O(log(n));
*/
//************************************Class MinHeap***********************************************
class MinHeap{
private:
void heapifyUp(int);
void heapifyDown(int);
public:
vector<int> heap;
int size;
MinHeap(void);
MinHeap(vector<int>);
void insert(int);
int extractMin(void);
void createHeapFromVector(vector<int>);
};
//****************************************Member Functions****************************************
void MinHeap::heapifyUp(int i){
int parentIndex=(i-1)/2;
while(parentIndex>=0){
if(this->heap[parentIndex]>this->heap[i]){
swap(this->heap[parentIndex],this->heap[i]);
i=parentIndex;
parentIndex=(i-1)/2;
}
else
break;
}
}
void MinHeap::heapifyDown(int i){
int leftChildIndex=2*i+1;
int rightChildIndex=2*i+2;
while(leftChildIndex<this->size || rightChildIndex<this->size){
int smallest=i;
if(this->heap[i]>this->heap[leftChildIndex])
smallest=leftChildIndex;
if(rightChildIndex<this->size){
if(this->heap[i]>this->heap[rightChildIndex] && this->heap[leftChildIndex]>this->heap[rightChildIndex])
smallest=rightChildIndex;
}
if(smallest==i)
break;
swap(this->heap[i],this->heap[smallest]);
i=smallest;
leftChildIndex=2*i+1;
rightChildIndex=2*i+2;
}
}
MinHeap::MinHeap(void){
this->heap={};
this->size=0;
}
MinHeap::MinHeap(vector<int> v){
this->heap=v;
this->size=v.size();
for(int i=this->size/2+1;i>=0;i--)
this->heapifyDown(i);
}
void MinHeap::insert(int n){
this->heap.push_back(n);
this->size++;
this->heapifyUp(this->size-1);
}
int MinHeap::extractMin(void){
if(this->size==0)
return -1;
int minElement=this->heap[0];
swap(this->heap[0],this->heap[this->size-1]);
this->heap.pop_back();
this->size--;
this->heapifyDown(0);
return minElement;
}
void MinHeap::createHeapFromVector(vector<int> v){
this->heap=v;
this->size=v.size();
for(int i=this->size/2+1;i>=0;i--)
this->heapifyDown(i);
} | true |
e9fdfe0e7f01e0aa86cb50cb4aba70e17069addd | C++ | d-pettersson/Raytracer | /apps/silhouette/silhouette.cpp | UTF-8 | 1,346 | 2.546875 | 3 | [] | no_license | #include "include/canvas.h"
#include "include/ray.h"
#include "include/tuple.h"
#include "include/sphere.h"
#include "include/intersection.h"
double wallZ = 10;
double wallSize = 7.0;
int canvasPixels = 100;
double pixelSize = wallSize / canvasPixels;
double half = wallSize / 2;
int main() {
auto rayOrigin = raytracer::Point(0, 0, -5);
auto * canvas = new raytracer::Canvas(canvasPixels, canvasPixels);
auto * color = new raytracer::Color(1, 0, 0);
std::shared_ptr<raytracer::Shape> sphere = std::make_shared<raytracer::Sphere>();
auto * intersection = new raytracer::Intersection();
for (int y = 0; y < canvasPixels; y++) {
double worldY = half - pixelSize * y;
for (int x = 0; x < canvasPixels; x++) {
double worldX = -half + pixelSize * x;
raytracer::Point position = raytracer::Point(worldX, worldY, wallZ);
raytracer::Vector normalized = normalize(position - rayOrigin);
raytracer::Ray ray = raytracer::Ray(rayOrigin, normalized);
std::vector<raytracer::Intersection> xs;
sphere->intersect(ray, xs);
* intersection = hit(xs);
if(intersection->getDistance() > 0) {
canvas->writePixel(x, y, * color);
canvas->saveToFile();
}
}
}
return 0;
} | true |
b934a33f9d8e459ad8d43160d0bf3a3aaec2057b | C++ | Jobbobeun/DZ_METER | /DZ_METER.ino | UTF-8 | 3,566 | 3.09375 | 3 | [] | no_license |
// I/O positions
#define switch_1 2
#define switch_2 3
#define switch_3 4
#define motor_pin_1 7
#define motor_pin_2 8
#define motor_speed_pin 6
#define switch_trigger 5
#define flashing_light 9
// default values
#define homing_speed 255
#define motor_speed_1 255
#define flashing_light_time 300000
// global variabels
int switch_status[5];
int switch_pin[5];
int motor_status; // 0 = off, 1 = clockwise, 2 = counterclockwise
bool trigger;
bool trigger_set = false;
bool homing;
bool flashing_light_status;
long trigger_counter;
int trigger_state_machine;
void setup() {
Serial.begin(9600);
determine_arrays();
set_pinmode();
while (!homing) {
Serial.println("Homing");
read_switch();
homing_cycle();
}
Serial.println("Start program");
}
void loop() {
read_switch();
program_cycle();
}
void motor_set(bool DIRECTION, int SPEED) { // direction true = clockwise, false = counerclockwise
if (DIRECTION) {
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
motor_status = 1;
} else {
{
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
motor_status = 2;
}
}
analogWrite(motor_speed_pin, SPEED);
}
void motor_stop() {
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_1, LOW);
analogWrite(motor_speed_pin, 0);
motor_status = 0;
}
void determine_arrays() {
switch_pin[1] = switch_1;
switch_pin[2] = switch_2;
switch_pin[3] = switch_3;
homing = false;
flashing_light_status = false;
trigger_set = false;
trigger_state_machine = 1;
}
void set_pinmode() {
pinMode(switch_1, INPUT);
pinMode(switch_2, INPUT);
pinMode(switch_3, INPUT);
pinMode(motor_pin_1, OUTPUT);
pinMode(motor_pin_2, OUTPUT);
pinMode(motor_speed_pin, OUTPUT);
pinMode(switch_trigger, INPUT);
pinMode(flashing_light, OUTPUT);
digitalWrite(switch_trigger, HIGH);
digitalWrite(switch_1, HIGH);
digitalWrite(switch_2, HIGH);
digitalWrite(switch_3, HIGH);
}
void read_switch() {
for (int i = 0 ; i < 5; i++) {
if (digitalRead(switch_pin[i]) == 1) {
switch_status[i] = 0;
} else {
switch_status[i] = 1;
}
}
if (digitalRead(switch_trigger) == 1) {
trigger = false;
} else {
trigger_set = true;
trigger = true;
}
}
void set_flashing_light(bool STATUS) {
if (STATUS == true) {
digitalWrite(flashing_light, HIGH);
} else {
digitalWrite(flashing_light, LOW);
}
}
void homing_cycle() {
if (motor_status != 2) {
motor_set(false, homing_speed);
}
if (switch_status[1] == 1) {
motor_stop();
homing = true;
}
}
void program_cycle() {
if (trigger_set) {
switch (trigger_state_machine) {
case 0:
case 1:
if (motor_status != 1) {
motor_set(true, motor_speed_1);
}
if (switch_status[3] == 1) {
motor_stop();
set_flashing_light(true);
trigger_state_machine = 2;
}
break;
case 2:
if (trigger_counter != flashing_light_time) {
trigger_counter ++;
} else {
trigger_counter = 0;
set_flashing_light(false);
trigger_state_machine = 1;
motor_set(false, motor_speed_1);
trigger_set = false;
}
break;
}
} else {
if (motor_status == 0) {
motor_set(true, motor_speed_1);
}
if (switch_status[2] == 1) {
motor_set(false, motor_speed_1);
} else if (switch_status[1] == 1)
{
motor_set(true, motor_speed_1);
}
}
}
| true |
ebbe261f841b0a462f13cdddf16d0b97a1a8c9fb | C++ | amitpingale92/PG-DAC-C-Plus-Plus | /13.TemplateLibrary/StandardTemplateLibrary/2.Adapters/priorityqueuetest.cpp | UTF-8 | 525 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "interval.h"
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
#include <utility>
using namespace std;
using rel_ops::operator>;
int main(void)
{
priority_queue<Interval> store;
//priority_queue<Interval, vector<Interval>, greater<Interval> > store;
store.push(Interval(7, 41));
store.push(Interval(4, 32));
store.push(Interval(5, 53));
store.push(Interval(2, 14));
store.push(Interval(6, 25));
while(!store.empty())
{
cout << store.top() << endl;
store.pop();
}
}
| true |
674cdde380a3d87a5a5ed079d41a146c55ef5bef | C++ | zhiwuba/LocalSearch | /src/search_http_server.cpp | GB18030 | 4,418 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include "search_http_server.h"
#include "search_query.h"
char dec_to_char(int n)
{
if ( 0<=n&&n<=9 )
{
return char('0'+n);
}
else if ( 10<=n&&n<=15 )
{
return char('A'+n-10);
}
else
{
return char(0);
}
}
std::string url_encode(std::string source_url)
{
std::string result;
for ( unsigned int i=0; i<source_url.size(); i++ )
{
char c=source_url[i];
if ( ('0'<=c&&c<='9')||('a'<=c&&c<='z')||('A'<=c&&c<='Z')||c=='.')
{
result+=c;
}
else
{
int j=(int)c;
if ( j<0 )
{
j+=256;
}
result+='%';
result+=dec_to_char((j>>4));
result+=dec_to_char((j%16));
}
}
return result;
}
Search_HttpServer::Search_HttpServer()
{
}
Search_HttpServer::~Search_HttpServer()
{
}
int Search_HttpServer::start_server( int port )
{
int result=0;
m_listen_socket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( m_listen_socket==INVALID_SOCKET )
{
printf("Error: start_server socket() error.");
return -1;
}
int flag=1;
int size=sizeof(flag);
if( SOCKET_ERROR==setsockopt(m_listen_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, size) )
{
return -1;
}
sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
addr.sin_port=htons(port);
result=bind(m_listen_socket,(struct sockaddr*)&addr, sizeof(addr));
if( result==SOCKET_ERROR )
{
closesocket(m_listen_socket);
return -1;
}
result=listen(m_listen_socket, SOMAXCONN);
if( result==SOCKET_ERROR )
{
closesocket(m_listen_socket);
return -1;
}
unsigned int thread_id;
m_thread_handle=thread_create(NULL,0, (THREAD_FUN)&http_server_thread, (void*)this, 0, &thread_id );
return 0;
}
int Search_HttpServer::stop_server()
{
m_exit=true;
shutdown(m_listen_socket ,SD_BOTH);
closesocket(m_listen_socket);
return 0;
}
int Search_HttpServer::http_server_thread_aid()
{
while(false==m_exit)
{
int client_socket=accept(m_listen_socket, NULL,NULL);
if ( INVALID_SOCKET==client_socket )
{
printf("Accept error in http_server_thread_aid. %d \n", lasterror);
continue;
}
std::string question;
std::string answer;
int length=0;
recv_request(client_socket, question);
search_words(question, answer);
send_response(client_socket, answer);
closesocket(client_socket);
}
return 0;
}
#ifdef WIN32
unsigned int Search_HttpServer::http_server_thread(void* param)
#else
void* Search_HttpServer::http_server_thread(void* param)
#endif
{
Search_HttpServer* pthis=(Search_HttpServer*)param;
#ifdef WIN32
return pthis->http_server_thread_aid();
#else
pthis->http_server_thread_aid();
return NULL;
#endif
}
int Search_HttpServer::recv_request(int sock, std::string& question)
{
char buffer[2048];
int ret=recv(sock, buffer, 10240, 0);
if( ret>0 )
{
char buffer2[1024];
char* keyword=strstr(buffer, "GET /?search=");
char* res_end=strstr(buffer, " HTTP/1.1");
int len=res_end-keyword-13;
strncpy(buffer2, keyword+13, len);
buffer2[len]='\0';
question=url_decode(buffer2);
}
return ret;
}
int Search_HttpServer::search_words(std::string quetion, std::string& answer)
{
std::vector<std::string> answer_vec;
g_Query.query(quetion, answer_vec);
for ( int i=0; i< answer_vec.size(); i++ )
{
answer+=(answer_vec[i]+"<br>");
}
return 0;
}
int Search_HttpServer::send_response(int sock, std::string& answer)
{
int ret=send(sock, answer.c_str(), answer.size(), 0);
return ret>0?0:-1;
}
std::string Search_HttpServer::url_decode(std::string source_url)
{
std::string result;
for ( unsigned int i=0;i<source_url.size(); i++ )
{
char c=source_url[i];
if ( c!='%' )
{
result+=c;
}
else
{
//(char_to_dec(source_url[++i])<<4) +char_to_dec(source_url[++i]); Ǵд iֵͬ
int first=(char_to_dec(source_url[++i])<<4);
int second=char_to_dec(source_url[++i]);
int num=first+second;
result+=(char)num;
}
}
return result;
}
int Search_HttpServer::char_to_dec(char c)
{
if ( '0'<=c&&c<='9' )
{
return (int)(c-'0');
}
else if('a'<=c&&c<='f')
{
return (int)(c-'a'+10);
}
else if('A'<=c&&c<='F')
{
return (int)(c-'A'+10);
}
else
{
return -1;
}
}
| true |
4ff39be652b326f4da7025c4499bf3a5aa4a9d27 | C++ | SimplyCrash/A3_Derek_Tran | /Lab11/Lab11/MonsterFactory.cpp | UTF-8 | 879 | 3.140625 | 3 | [] | no_license | /**************************************************
Project: RPG Monsters 2.0
Lab Num: Week 11
Author: Cheryl Howard / Matt Butler
Purpose: MONSTER FACTORY Class file
**************************************************/
#include "MonsterFactory.h"
MonsterFactory* MonsterFactory::instance = nullptr;
MonsterFactory* MonsterFactory::getInstance() {
if (instance == nullptr) {
instance = new MonsterFactory();
}
return instance;
}
Monster* MonsterFactory::createMonster(string name, int health, int num) {
//cout << "Monster being generated" << endl;
Monster* myMonster = nullptr;
switch (num) {
case 0:
myMonster = new Monster(name, health);
break;
case 1:
myMonster = new Vampire(name, health);
break;
case 2:
myMonster = new Zombie(name, health);
break;
default:
cout << "Something went wrong ... oops!\n\n";
}
return myMonster;
}
| true |
dd4f2373b5b79a7a2f2727363cc9834e2eeef7e7 | C++ | stefanofiorentino/nothrow_calls_terminate | /main.cpp | UTF-8 | 284 | 3.296875 | 3 | [] | no_license | #include <iostream>
inline void throw_despite_noexcept_declaration() noexcept
{
throw std::exception{};
}
int main()
{
std::cout << "Hello, World!" << std::endl;
throw_despite_noexcept_declaration();
std::cout << "You'll Never be here!" << std::endl;
return 0;
} | true |
17ce77cca8f0eb9ae1670f62c0c8bfb925536d3b | C++ | HenryLinUCSB/cs16 | /lab08/headers.h | UTF-8 | 819 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class AString {
// You will need to declare:
// 1. 2 constructors (see lab description for details)
// 2. Three (3) member functions (see lab description for details)
// called getAString, cleanUp, countLetters
// one of which is a accessor function, and 2 are mutator functions
// 3. One member variable called StringValue
//
// IMPORTANT: Figure out first which go in public and which in private.
public:
AString();
AString(string str);
void getAString(); // Accessor because it is a "get"
void cleanUp();
void countLetters(int array[]);
private:
string StringValue;
};
// Declare the program function used in the main routine called compareCounts here:
// type compareCounts(arguments);
bool compareCounts(int ca1[], int ca2[]);
| true |
38b4a53fb0ef7fa9eb1bf7e98ff4f402363befc2 | C++ | m0vehyeon/Code-Up-Algorithm | /[기초-종합] 언제까지 더해야할까.cpp | UTF-8 | 199 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int a;
int sum = 0;
int cnt=0;
scanf("%d", &a);
while (sum < a)
{
cnt ++;
sum = sum + cnt;
}
printf("%d\n", cnt);
return 0;
}
| true |
29a2322c0ddc753bf5b19ba72b2521f1fe9c9693 | C++ | AlissonJ/Roteiro-05 | /Data.cpp | UTF-8 | 934 | 3.59375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Data{
private:
int dia;
int mes;
int ano;
public:
void setDia(int d){ //Dia
dia = d;
}
int getDia(){
return dia;
}
void setMes(int m){ //Mes
mes = m;
}
int getMes(){
return mes;
}
void setAno(int a){ //Ano
ano = a;
}
int getAno(){
return ano;
}
Data(int d,int m,int a){
this->dia = d;
this->mes = m;
this->ano = a;
while(dia<1 || dia>31){
cout<< "Informe um dia valido (entre 1 e 31)"<<endl;
cin>>dia;
}while(mes<1 || mes>12){
cout<< "Informe um mes valido (entre 1 e 12)"<<endl;
cin>>mes;
}while(ano<1900 || ano>3500){
cout<< "Informe um ano valido (entre 1900 e 3500)"<<endl;
cin>>ano;
}
}
void avancarDia(){
dia++;
}
};
| true |
67a769bb2dc62ab11dcdd8ce4b24d08cb41b0a76 | C++ | Kitware/vtk-examples | /src/Cxx/Visualization/CreateColorSeriesDemo.cxx | UTF-8 | 20,650 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #include <vtkActor.h>
#include <vtkCellData.h>
#include <vtkColorSeries.h>
#include <vtkFloatArray.h>
#include <vtkLookupTable.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPlaneSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <map>
#include <string>
#include <vector>
namespace {
void CreateLookupTableVTKBlue(vtkLookupTable* lut, int tableSize = 0);
void CreateLookupTableVTKBrown(vtkLookupTable* lut, int tableSize = 0);
void CreateLookupTableVTKRed(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKOrange(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKWhite(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKGrey(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKMagenta(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKCyan(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKYellow(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKGreen(vtkLookupTable* lu, int tableSize = 0);
} // namespace
int main(int argc, char* argv[])
{
std::string seriesName = "Red";
if (argc > 1)
{
seriesName = argv[1];
}
// Provide some geometry.
int resolution = 6;
vtkNew<vtkPlaneSource> aPlane;
aPlane->SetXResolution(resolution);
aPlane->SetYResolution(resolution);
// Create cell data.
vtkNew<vtkFloatArray> cellData;
for (int i = 0; i < resolution * resolution; i++)
{
cellData->InsertNextValue(i);
}
aPlane->Update(); // Force an update so we can set cell data.
aPlane->GetOutput()->GetCellData()->SetScalars(cellData);
vtkNew<vtkNamedColors> colors;
vtkNew<vtkLookupTable> lut;
if (seriesName == "Blue")
{
CreateLookupTableVTKBlue(lut, resolution * resolution + 1);
}
else if (seriesName == "Brown")
{
CreateLookupTableVTKBrown(lut, resolution * resolution + 1);
}
else if (seriesName == "Red")
{
CreateLookupTableVTKRed(lut, resolution * resolution + 1);
}
else if (seriesName == "Orange")
{
CreateLookupTableVTKOrange(lut, resolution * resolution + 1);
}
else if (seriesName == "White")
{
CreateLookupTableVTKWhite(lut, resolution * resolution + 1);
}
else if (seriesName == "Grey")
{
CreateLookupTableVTKGrey(lut, resolution * resolution + 1);
}
else if (seriesName == "Magenta")
{
CreateLookupTableVTKMagenta(lut, resolution * resolution + 1);
}
else if (seriesName == "Cyan")
{
CreateLookupTableVTKCyan(lut, resolution * resolution + 1);
}
else if (seriesName == "Yellow")
{
CreateLookupTableVTKYellow(lut, resolution * resolution + 1);
}
else if (seriesName == "Green")
{
CreateLookupTableVTKGreen(lut, resolution * resolution + 1);
}
else
{
std::cout << "Bad series name: " << seriesName << std::endl;
return EXIT_FAILURE;
}
// Setup actor and mapper.
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetLookupTable(lut);
mapper->SetInputConnection(aPlane->GetOutputPort());
mapper->SetScalarModeToUseCellData();
mapper->SetScalarRange(0, resolution * resolution + 1);
vtkNew<vtkActor> actor;
actor->SetMapper(mapper);
actor->GetProperty()->EdgeVisibilityOn();
// Setup render window, renderer, and interactor.
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer);
renderWindow->SetWindowName("CreateColorSeriesDemo");
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(colors->GetColor3d("SlateGray").GetData());
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
namespace {
void CreateLookupTableVTKBlue(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKBlueColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("alice_blue"));
myColors->AddColor(nc->GetColor3ub("blue"));
myColors->AddColor(nc->GetColor3ub("blue_light"));
myColors->AddColor(nc->GetColor3ub("blue_medium"));
myColors->AddColor(nc->GetColor3ub("cadet"));
myColors->AddColor(nc->GetColor3ub("cobalt"));
myColors->AddColor(nc->GetColor3ub("cornflower"));
myColors->AddColor(nc->GetColor3ub("cerulean"));
myColors->AddColor(nc->GetColor3ub("dodger_blue"));
myColors->AddColor(nc->GetColor3ub("indigo"));
myColors->AddColor(nc->GetColor3ub("manganese_blue"));
myColors->AddColor(nc->GetColor3ub("midnight_blue"));
myColors->AddColor(nc->GetColor3ub("navy"));
myColors->AddColor(nc->GetColor3ub("peacock"));
myColors->AddColor(nc->GetColor3ub("powder_blue"));
myColors->AddColor(nc->GetColor3ub("royal_blue"));
myColors->AddColor(nc->GetColor3ub("slate_blue"));
myColors->AddColor(nc->GetColor3ub("slate_blue_dark"));
myColors->AddColor(nc->GetColor3ub("slate_blue_light"));
myColors->AddColor(nc->GetColor3ub("slate_blue_medium"));
myColors->AddColor(nc->GetColor3ub("sky_blue"));
myColors->AddColor(nc->GetColor3ub("sky_blue_deep"));
myColors->AddColor(nc->GetColor3ub("sky_blue_light"));
myColors->AddColor(nc->GetColor3ub("steel_blue"));
myColors->AddColor(nc->GetColor3ub("steel_blue_light"));
myColors->AddColor(nc->GetColor3ub("turquoise_blue"));
myColors->AddColor(nc->GetColor3ub("ultramarine"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKBrown(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKBrownColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("beige"));
myColors->AddColor(nc->GetColor3ub("brown"));
myColors->AddColor(nc->GetColor3ub("brown_madder"));
myColors->AddColor(nc->GetColor3ub("brown_ochre"));
myColors->AddColor(nc->GetColor3ub("burlywood"));
myColors->AddColor(nc->GetColor3ub("burnt_sienna"));
myColors->AddColor(nc->GetColor3ub("burnt_umber"));
myColors->AddColor(nc->GetColor3ub("chocolate"));
myColors->AddColor(nc->GetColor3ub("deep_ochre"));
myColors->AddColor(nc->GetColor3ub("flesh"));
myColors->AddColor(nc->GetColor3ub("flesh_ochre"));
myColors->AddColor(nc->GetColor3ub("gold_ochre"));
myColors->AddColor(nc->GetColor3ub("greenish_umber"));
myColors->AddColor(nc->GetColor3ub("khaki"));
myColors->AddColor(nc->GetColor3ub("khaki_dark"));
myColors->AddColor(nc->GetColor3ub("light_beige"));
myColors->AddColor(nc->GetColor3ub("peru"));
myColors->AddColor(nc->GetColor3ub("rosy_brown"));
myColors->AddColor(nc->GetColor3ub("raw_sienna"));
myColors->AddColor(nc->GetColor3ub("raw_umber"));
myColors->AddColor(nc->GetColor3ub("sepia"));
myColors->AddColor(nc->GetColor3ub("sienna"));
myColors->AddColor(nc->GetColor3ub("saddle_brown"));
myColors->AddColor(nc->GetColor3ub("sandy_brown"));
myColors->AddColor(nc->GetColor3ub("tan"));
myColors->AddColor(nc->GetColor3ub("van_dyke_brown"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKRed(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKRedColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("alizarin_crimson"));
myColors->AddColor(nc->GetColor3ub("brick"));
myColors->AddColor(nc->GetColor3ub("cadmium_red_deep"));
myColors->AddColor(nc->GetColor3ub("coral"));
myColors->AddColor(nc->GetColor3ub("coral_light"));
myColors->AddColor(nc->GetColor3ub("deep_pink"));
myColors->AddColor(nc->GetColor3ub("english_red"));
myColors->AddColor(nc->GetColor3ub("firebrick"));
myColors->AddColor(nc->GetColor3ub("geranium_lake"));
myColors->AddColor(nc->GetColor3ub("hot_pink"));
myColors->AddColor(nc->GetColor3ub("indian_red"));
myColors->AddColor(nc->GetColor3ub("light_salmon"));
myColors->AddColor(nc->GetColor3ub("madder_lake_deep"));
myColors->AddColor(nc->GetColor3ub("maroon"));
myColors->AddColor(nc->GetColor3ub("pink"));
myColors->AddColor(nc->GetColor3ub("pink_light"));
myColors->AddColor(nc->GetColor3ub("raspberry"));
myColors->AddColor(nc->GetColor3ub("red"));
myColors->AddColor(nc->GetColor3ub("rose_madder"));
myColors->AddColor(nc->GetColor3ub("salmon"));
myColors->AddColor(nc->GetColor3ub("tomato"));
myColors->AddColor(nc->GetColor3ub("venetian_red"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKGrey(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
vtkNew<vtkNamedColors> nc;
myColors->SetColorSchemeByName("VTKGreyColors");
myColors->AddColor(nc->GetColor3ub("cold_grey"));
myColors->AddColor(nc->GetColor3ub("dim_grey"));
myColors->AddColor(nc->GetColor3ub("grey"));
myColors->AddColor(nc->GetColor3ub("light_grey"));
myColors->AddColor(nc->GetColor3ub("slate_grey"));
myColors->AddColor(nc->GetColor3ub("slate_grey_dark"));
myColors->AddColor(nc->GetColor3ub("slate_grey_light"));
myColors->AddColor(nc->GetColor3ub("warm_grey"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKWhite(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
vtkNew<vtkNamedColors> nc;
myColors->SetColorSchemeByName("VTKWhiteColors");
myColors->AddColor(nc->GetColor3ub("antique_white"));
myColors->AddColor(nc->GetColor3ub("azure"));
myColors->AddColor(nc->GetColor3ub("bisque"));
myColors->AddColor(nc->GetColor3ub("blanched_almond"));
myColors->AddColor(nc->GetColor3ub("cornsilk"));
myColors->AddColor(nc->GetColor3ub("eggshell"));
myColors->AddColor(nc->GetColor3ub("floral_white"));
myColors->AddColor(nc->GetColor3ub("gainsboro"));
myColors->AddColor(nc->GetColor3ub("ghost_white"));
myColors->AddColor(nc->GetColor3ub("honeydew"));
myColors->AddColor(nc->GetColor3ub("ivory"));
myColors->AddColor(nc->GetColor3ub("lavender"));
myColors->AddColor(nc->GetColor3ub("lavender_blush"));
myColors->AddColor(nc->GetColor3ub("lemon_chiffon"));
myColors->AddColor(nc->GetColor3ub("linen"));
myColors->AddColor(nc->GetColor3ub("mint_cream"));
myColors->AddColor(nc->GetColor3ub("misty_rose"));
myColors->AddColor(nc->GetColor3ub("moccasin"));
myColors->AddColor(nc->GetColor3ub("navajo_white"));
myColors->AddColor(nc->GetColor3ub("old_lace"));
myColors->AddColor(nc->GetColor3ub("papaya_whip"));
myColors->AddColor(nc->GetColor3ub("peach_puff"));
myColors->AddColor(nc->GetColor3ub("seashell"));
myColors->AddColor(nc->GetColor3ub("snow"));
myColors->AddColor(nc->GetColor3ub("thistle"));
myColors->AddColor(nc->GetColor3ub("titanium_white"));
myColors->AddColor(nc->GetColor3ub("wheat"));
myColors->AddColor(nc->GetColor3ub("white"));
myColors->AddColor(nc->GetColor3ub("white_smoke"));
myColors->AddColor(nc->GetColor3ub("zinc_white"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKOrange(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKOrangeColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("cadmium_orange"));
myColors->AddColor(nc->GetColor3ub("cadmium_red_light"));
myColors->AddColor(nc->GetColor3ub("carrot"));
myColors->AddColor(nc->GetColor3ub("dark_orange"));
myColors->AddColor(nc->GetColor3ub("mars_orange"));
myColors->AddColor(nc->GetColor3ub("mars_yellow"));
myColors->AddColor(nc->GetColor3ub("orange"));
myColors->AddColor(nc->GetColor3ub("orange_red"));
myColors->AddColor(nc->GetColor3ub("yellow_ochre"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKMagenta(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKMagentaColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("blue_violet"));
myColors->AddColor(nc->GetColor3ub("cobalt_violet_deep"));
myColors->AddColor(nc->GetColor3ub("magenta"));
myColors->AddColor(nc->GetColor3ub("orchid"));
myColors->AddColor(nc->GetColor3ub("orchid_dark"));
myColors->AddColor(nc->GetColor3ub("orchid_medium"));
myColors->AddColor(nc->GetColor3ub("permanent_red_violet"));
myColors->AddColor(nc->GetColor3ub("plum"));
myColors->AddColor(nc->GetColor3ub("purple"));
myColors->AddColor(nc->GetColor3ub("purple_medium"));
myColors->AddColor(nc->GetColor3ub("ultramarine_violet"));
myColors->AddColor(nc->GetColor3ub("violet"));
myColors->AddColor(nc->GetColor3ub("violet_dark"));
myColors->AddColor(nc->GetColor3ub("violet_red"));
myColors->AddColor(nc->GetColor3ub("violet_red_medium"));
myColors->AddColor(nc->GetColor3ub("violet_red_pale"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKCyan(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKCyanColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("aquamarine"));
myColors->AddColor(nc->GetColor3ub("aquamarine_medium"));
myColors->AddColor(nc->GetColor3ub("cyan"));
myColors->AddColor(nc->GetColor3ub("cyan_white"));
myColors->AddColor(nc->GetColor3ub("turquoise"));
myColors->AddColor(nc->GetColor3ub("turquoise_dark"));
myColors->AddColor(nc->GetColor3ub("turquoise_medium"));
myColors->AddColor(nc->GetColor3ub("turquoise_pale"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKYellow(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKYellowColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("aureoline_yellow"));
myColors->AddColor(nc->GetColor3ub("banana"));
myColors->AddColor(nc->GetColor3ub("cadmium_lemon"));
myColors->AddColor(nc->GetColor3ub("cadmium_yellow"));
myColors->AddColor(nc->GetColor3ub("cadmium_yellow_light"));
myColors->AddColor(nc->GetColor3ub("gold"));
myColors->AddColor(nc->GetColor3ub("goldenrod"));
myColors->AddColor(nc->GetColor3ub("goldenrod_dark"));
myColors->AddColor(nc->GetColor3ub("goldenrod_light"));
myColors->AddColor(nc->GetColor3ub("goldenrod_pale"));
myColors->AddColor(nc->GetColor3ub("light_goldenrod"));
myColors->AddColor(nc->GetColor3ub("melon"));
myColors->AddColor(nc->GetColor3ub("naples_yellow_deep"));
myColors->AddColor(nc->GetColor3ub("yellow"));
myColors->AddColor(nc->GetColor3ub("yellow_light"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKGreen(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKGreenColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("chartreuse"));
myColors->AddColor(nc->GetColor3ub("chrome_oxide_green"));
myColors->AddColor(nc->GetColor3ub("cinnabar_green"));
myColors->AddColor(nc->GetColor3ub("cobalt_green"));
myColors->AddColor(nc->GetColor3ub("emerald_green"));
myColors->AddColor(nc->GetColor3ub("forest_green"));
myColors->AddColor(nc->GetColor3ub("green"));
myColors->AddColor(nc->GetColor3ub("green_dark"));
myColors->AddColor(nc->GetColor3ub("green_pale"));
myColors->AddColor(nc->GetColor3ub("green_yellow"));
myColors->AddColor(nc->GetColor3ub("lawn_green"));
myColors->AddColor(nc->GetColor3ub("lime_green"));
myColors->AddColor(nc->GetColor3ub("mint"));
myColors->AddColor(nc->GetColor3ub("olive"));
myColors->AddColor(nc->GetColor3ub("olive_drab"));
myColors->AddColor(nc->GetColor3ub("olive_green_dark"));
myColors->AddColor(nc->GetColor3ub("permanent_green"));
myColors->AddColor(nc->GetColor3ub("sap_green"));
myColors->AddColor(nc->GetColor3ub("sea_green"));
myColors->AddColor(nc->GetColor3ub("sea_green_dark"));
myColors->AddColor(nc->GetColor3ub("sea_green_medium"));
myColors->AddColor(nc->GetColor3ub("sea_green_light"));
myColors->AddColor(nc->GetColor3ub("spring_green"));
myColors->AddColor(nc->GetColor3ub("spring_green_medium"));
myColors->AddColor(nc->GetColor3ub("terre_verte"));
myColors->AddColor(nc->GetColor3ub("viridian_light"));
myColors->AddColor(nc->GetColor3ub("yellow_green"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
} // namespace
| true |
c2f94d0dc56275b80b470c2cf6e22b41573a2bc2 | C++ | avast/retdec | /src/bin2llvmir/optimizations/decoder/bbs.cpp | UTF-8 | 3,738 | 2.953125 | 3 | [
"MIT",
"Zlib",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"NCSA",
"WTFPL",
"BSL-1.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | /**
* @file src/bin2llvmir/optimizations/decoder/bbs.cpp
* @brief Decode input binary into LLVM IR.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/bin2llvmir/optimizations/decoder/decoder.h"
using namespace retdec::common;
namespace retdec {
namespace bin2llvmir {
/**
* \return Start address for basic block \p f.
*/
common::Address Decoder::getBasicBlockAddress(llvm::BasicBlock* b)
{
auto likelyIt = _likelyBb2Target.find(b);
if (likelyIt != _likelyBb2Target.end())
{
b = likelyIt->second;
}
auto fIt = _bb2addr.find(b);
return fIt != _bb2addr.end() ? fIt->second : Address();
}
/**
* \return End address for basic block \p b - the end address of the last
* instruction in the basic block.
*/
common::Address Decoder::getBasicBlockEndAddress(llvm::BasicBlock* b)
{
if (b->empty())
{
return getBasicBlockAddress(b);
}
AsmInstruction ai(&b->back());
return ai.isValid() ? ai.getEndAddress() : getBasicBlockAddress(b);
}
/**
* \return Address of the first basic block after address \p a.
*/
common::Address Decoder::getBasicBlockAddressAfter(common::Address a)
{
auto it = _addr2bb.upper_bound(a);
return it != _addr2bb.end() ? it->first : Address();
}
/**
* \return Basic block exactly at address \p a.
*/
llvm::BasicBlock* Decoder::getBasicBlockAtAddress(common::Address a)
{
auto fIt = _addr2bb.find(a);
return fIt != _addr2bb.end() ? fIt->second : nullptr;
}
/**
* \return The first basic block before or at address \p a.
*/
llvm::BasicBlock* Decoder::getBasicBlockBeforeAddress(common::Address a)
{
if (_addr2bb.empty())
{
return nullptr;
}
// Iterator to the first element whose key goes after a.
auto it = _addr2bb.upper_bound(a);
// The first BB is after a -> no BB before a.
if (it == _addr2bb.begin())
{
return nullptr;
}
// No BB after a -> the last BB before a.
else if (it == _addr2bb.end())
{
return _addr2bb.rbegin()->second;
}
// BB after a exists -> the one before it is before a.
else
{
--it;
return it->second;
}
}
/**
* \return The first basic block after address \p a.
*/
llvm::BasicBlock* Decoder::getBasicBlockAfterAddress(common::Address a)
{
auto it = _addr2bb.upper_bound(a);
return it != _addr2bb.end() ? it->second : nullptr;
}
/**
* \return Basic block that contains the address \p a. I.e. \p a is between
* basic blocks's start and end address.
*/
llvm::BasicBlock* Decoder::getBasicBlockContainingAddress(common::Address a)
{
auto* b = getBasicBlockBeforeAddress(a);
if (b == nullptr)
{
return nullptr;
}
llvm::BasicBlock* bbEnd = b;
while (bbEnd->getNextNode())
{
// Next has address -- is a proper BB.
//
if (getBasicBlockAddress(bbEnd->getNextNode()).isDefined())
{
break;
}
else
{
bbEnd = bbEnd->getNextNode();
}
}
Address end = getBasicBlockEndAddress(bbEnd);
return a.isDefined() && end.isDefined() && a < end ? b : nullptr;
}
/**
* Create basic block at address \p a in function \p f right after basic
* block \p insertAfter.
* \return Created function.
*/
llvm::BasicBlock* Decoder::createBasicBlock(
common::Address a,
llvm::Function* f,
llvm::BasicBlock* insertAfter)
{
auto* next = insertAfter ? insertAfter->getNextNode() : nullptr;
while (!(next == nullptr || _bb2addr.count(next)))
{
next = next->getNextNode();
}
auto* b = llvm::BasicBlock::Create(
_module->getContext(),
names::generateBasicBlockName(a),
f,
next);
llvm::IRBuilder<> irb(b);
irb.CreateRet(llvm::UndefValue::get(f->getReturnType()));
addBasicBlock(a, b);
return b;
}
void Decoder::addBasicBlock(common::Address a, llvm::BasicBlock* b)
{
_addr2bb[a] = b;
_bb2addr[b] = a;
}
} // namespace bin2llvmir
} // namespace retdec
| true |
4c19eb042f8ed21c04e1c705f4d4d3c05f153233 | C++ | yscriuf/Certificate | /구구단1/구구단1/소스.cpp | UHC | 580 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
int main(void)
{
int test_case;
int T;
setbuf(stdout, NULL);
scanf("%d", &T);
int arr[100];
for (int i = 0; i < 100; i++) { arr[i] = 0; }
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
arr[i * j] = 1;
}
for (test_case = 1; test_case <= T; ++test_case)
{
int a;
scanf("%d", &a);
if (arr[a] == 1) { printf("#%d Yes\n", test_case); }
else { printf("#%d No\n", test_case); }
}
return 0; // ݵ 0 ؾ մϴ.
} | true |
b2b6b5919ff8831fec70db0274881dcf36a016c6 | C++ | caihj/c11 | /main.cpp | UTF-8 | 353 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
map<string,string> a = {{"key1","value"}, {"key2","value2"}};
a.insert({{"a","b"},{"f","g"}});
a["c"]="d";
a["42343"]="43242";
for(auto k : a) {
cout << k.first << ":" << k.second << endl;
}
return 0;
}
| true |
f4df55a915d129a02d42c4bee44e59bd8e52fabe | C++ | coreydlucas/CIT242-Work | /Project 7/MemoryAddress3/MemoryAddress3.cpp | UTF-8 | 604 | 3.609375 | 4 | [] | no_license | //You Do It MemoryAddress3 pg.209~
#include<iostream>
using namespace std;
int main()
{
int firstNum, secondNum;
const int SIZE = 6;
int nums[SIZE] = { 12, 23, 34, 45, 56, 67 };
int x;
cout << "Enter first number ";
cin >> firstNum;
cout << "Enter second number ";
cin >> secondNum;
cout << "The numbers are " << firstNum << " and " << secondNum << endl;
cout << "The addresses are " << &firstNum << " and " << &secondNum << endl;
for (x = 0; x < SIZE; ++x)
cout << nums[x] << " ";
cout << endl;
for (x = 0; x < SIZE; ++x)
cout << &nums[x] << " ";
cout << endl;
return 0;
} | true |
6ecbb210821c4ddc388652c245294522a20a481d | C++ | ajfabian/3N1M4-Team-Reference | /code/geometry/vantage.cpp | UTF-8 | 3,412 | 3.125 | 3 | [] | no_license | /* Vantage-PointTree
- Arbol metrico para encontrar los puntos mas ceranos a uno dado.
- El ejemplo usa distancia euclidiana, pero (en teoria) funciona con
todas las metricas.
- Tiempo Esperado: Build: O(n lg n). Query: O(lg n).
*/
typedef double type;
struct pt{
type x, y;
bool operator < (const pt& p)const{
return x != p.x ? x < p.x : y < p.y;
}
};
struct node{
pt p;
type th;
node *l, *r;
};
typedef node* pnod;
struct vantage{
pnod root;
vector<pair<type, pt>> v;
/* Solo se usa con kthnn() */
priority_queue<pair<type, pnod>> Q;
/* Solo se usa con nearest(). Inicializar best.fr a INF. Al
final, en best.sc esta el punto mas cercano a p, y en best.fr
la distancia minima al cuadrado. */
pair<type, pt> best;
vantage(vector<pt>& points){
for(auto i: points)
v.pb({0, i});
root = build(0, v.size());
}
pnod build(int x, int xend){
if( x==xend ) return NULL;
swap(v[x], v[ x + rand() % (xend-x) ]);
pt p = v[x++].sc;
if( x==xend ) return new node({p});
for(int i=x; i < xend; i++)
v[i].fr = dist2(p, v[i].sc);
nth_element(v.begin() + x, v.begin() + mid, v.begin() +xend);
return new node({p, sqrt(v[mid].fr), build(x, mid),
build(mid, xend)});
}
void kthnn(pnod t, pt p, int k){
if( !t ) return;
type d = sqrt(dist2(p, t->p));
if( (int)Q.size() < k ) Q.push({d, t});
else if( Q.top().fr > d ){
Q.pop();
Q.push({d, t});
}
if( !t->l && !t->r ) return;
if( d < t->th ){
kthnn(t->l, p, k);
if( (int)Q.size() < k || t->th - d <= Q.top().fr )
kthnn(t->r, p, k);
}
else{
kthnn(t->r, p, k);
if( (int)Q.size() < k || d - t->th <= Q.top().fr )
kthnn(t->l, p, k);
}
}
/* Encuentra los k puntos mas cercanos a p dentro del conjunto */
vector<pt> kthnn(pt p, int k){
vector<pt> ans;
kthnn(root, p, k);
for(; !Q.empty(); Q.pop())
ans.pb(Q.top().sc->p);
reverse(all(ans));
return ans;
}
/* Encuentra el punto mas cercano a p dentro del conjunto */
void nearest(pnod t, pt p){
if( !t ) return;
type d = sqrt(dist2(p, t->p));
if( best.fr > d )
best = {d, t->p};
if( !t->l && !t->r ) return;
if( d < t->th ){
nearest(t->l, p);
if( t->th - d <= best.fr )
nearest(t->r, p);
}
else{
nearest(t->r, p);
if( d - t->th <= best.fr )
nearest(t->l, p);
}
}
/* Funcion Debug */
void print(pnod p){
if( !p ) return;
printf("p = (%.2lf, %.2lf), th = %.2lf",
p->p.x, p->p.y, p->th
);
if( p->l )
printf(", l = (%.2lf, %.2lf)", p->l->p.x, p->l->p.y);
if( p->r )
printf(", r = (%.2lf, %.2lf)", p->r->p.x, p->r->p.y);
printf("\n");
print(p->l); print(p->r);
}
};
| true |
6b63f7ae305ada3c507a2a76cdbb3d683140efb7 | C++ | razvanalex/City-Procedural-Generation | /Source/Laboratoare/Homework3/Camera.cpp | UTF-8 | 2,807 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "Camera.h"
Camera::Camera()
{
position = glm::vec3(0, 2, 5);
forward = glm::vec3(0, 0, -1);
up = glm::vec3(0, 1, 0);
right = glm::vec3(1, 0, 0);
distanceToTarget = 2;
}
Camera::Camera(const glm::vec3 &position, const glm::vec3 ¢er, const glm::vec3 &up)
{
distanceToTarget = 1;
Set(position, center, up);
}
Camera::~Camera()
{ }
// Update camera
void Camera::Set(const glm::vec3 &position, const glm::vec3 ¢er, const glm::vec3 &up)
{
this->position = position;
forward = glm::normalize(center - position);
right = glm::cross(forward, up);
this->up = glm::cross(right, forward);
}
void Camera::MoveForward(float distance)
{
glm::vec3 dir = glm::normalize(glm::vec3(forward.x, 0, forward.z));
}
void Camera::TranslateForward(float distance)
{
position += forward * distance;
}
void Camera::TranslateRight(float distance)
{
glm::vec3 r = glm::vec3(right.x, 0, right.z);
position += right * distance;
}
void Camera::TranslateUpward(float distance)
{
position += up * distance;
}
void Camera::RotateFirstPerson_OX(float angle)
{
glm::vec4 newDir = glm::rotate(glm::mat4(1), angle, right) * glm::vec4(forward, 1);
forward = glm::normalize(glm::vec3(newDir));
up = glm::normalize(glm::cross(right, forward));
}
void Camera::RotateFirstPerson_OY(float angle)
{
glm::vec3 u = glm::vec3(0, glm::abs(up.y), 0);
glm::vec4 newDir = glm::rotate(glm::mat4(1), angle, u) * glm::vec4(forward, 1);
forward = glm::normalize(glm::vec3(newDir));
newDir = glm::rotate(glm::mat4(1), angle, u) * glm::vec4(right, 1);
right = glm::normalize(glm::vec3(newDir));
up = glm::normalize(glm::cross(right, forward));
}
void Camera::RotateFirstPerson_OZ(float angle)
{
glm::vec4 newDir = glm::rotate(glm::mat4(1), angle, forward) * glm::vec4(forward, 1);
forward = glm::normalize(glm::vec3(newDir));
newDir = glm::rotate(glm::mat4(1), angle, forward) * glm::vec4(right, 1);
right = glm::normalize(glm::vec3(newDir));
up = glm::normalize(glm::cross(right, forward));
}
void Camera::RotateThirdPerson_OX(float angle)
{
TranslateForward(distanceToTarget);
RotateFirstPerson_OX(angle);
TranslateForward(-distanceToTarget);
}
void Camera::RotateThirdPerson_OY(float angle)
{
TranslateForward(distanceToTarget);
RotateFirstPerson_OY(angle);
TranslateForward(-distanceToTarget);
}
void Camera::RotateThirdPerson_OZ(float angle)
{
TranslateForward(distanceToTarget);
RotateFirstPerson_OZ(angle);
TranslateForward(-distanceToTarget);
}
glm::mat4 Camera::GetViewMatrix()
{
// Returns the View Matrix
return glm::lookAt(position, position + forward, up);
}
glm::vec3 Camera::GetTargetPosition()
{
return position + forward * distanceToTarget;
}
glm::vec3 Camera::GetPosition()
{
return this->position;
}
| true |
26b799edeca839b504ebb8162c2255fba3d33a08 | C++ | foxness/simple-starcraft | /SimpleStarcraft/entitybase.h | UTF-8 | 387 | 2.78125 | 3 | [] | no_license | #pragma once
#include "vector.h"
#include "gameobject.h"
class EntityBase : public GameObject
{
protected:
Vector position;
EntityBase(const Vector& position_);
public:
const Vector& getPosition() const;
int getId() const;
bool operator==(const EntityBase& other) const;
bool operator!=(const EntityBase& other) const;
private:
int id;
int getNextId() const;
}; | true |
3abad0dd64b1e668750748397c077b2ffcb35528 | C++ | WhiZTiM/coliru | /Archive2/81/dbc4be3ee778d5/main.cpp | UTF-8 | 193 | 2.59375 | 3 | [] | no_license | #include <atomic>
std::atomic<int> bar;
template <typename T>
T Dummy(const std::atomic<T>& val) { return T(); }
auto foo() -> decltype(Dummy(bar))
{
return bar++;
}
int main()
{
} | true |
521360a8771c1804ff28414c33563e3b1b68d61b | C++ | FahJulian/Sonic | /Sonic/src/Sonic/Scene/ECS/ComponentRegistry.cpp | UTF-8 | 2,521 | 2.640625 | 3 | [] | no_license | #include "ComponentRegistry.h"
using namespace Sonic;
Entity ComponentRegistry::AddEntity()
{
return m_NextEntity++;
}
Entity ComponentRegistry::AddEntity(EntityGroup group)
{
Entity entity = m_NextEntity++;
m_EntityGroups[group].push_back(entity);
return entity;
}
EntityGroup ComponentRegistry::AddEntityGroup()
{
return m_NextEntity++;
}
void ComponentRegistry::AddToGroup(EntityGroup group, Entity entity)
{
m_EntityGroups[group].push_back(entity);
}
std::vector<Entity>* ComponentRegistry::GetGroup(EntityGroup group)
{
return &m_EntityGroups[group];
}
void ComponentRegistry::DeactivateEntities(EntityGroup group)
{
for (Entity entity : m_EntityGroups[group])
DeactivateEntity(entity);
DeactivateEntity(group);
}
void ComponentRegistry::ReactivateEntities(EntityGroup group)
{
ReactivateEntity(group);
for (Entity entity : m_EntityGroups[group])
ReactivateEntity(entity);
}
ComponentPool* ComponentRegistry::GetComponentPool(ComponentType type)
{
while (type >= m_ComponentPools.size())
m_ComponentPools.push_back(new ComponentPool(static_cast<ComponentType>(m_ComponentPools.size())));
return m_ComponentPools.at(type);
}
void ComponentRegistry::DeactivateEntity(Entity entity)
{
if (m_Initialized)
EventDispatcher::dispatch(EntityDeactivatedEvent(entity));
auto it = m_ComponentMap.find(entity);
for (ComponentType type : it->second)
{
ComponentPool* pool = GetComponentPool(type);
pool->DeactivateEntity(entity);
}
}
void ComponentRegistry::ReactivateEntity(Entity entity)
{
auto it = m_ComponentMap.find(entity);
for (ComponentType type : it->second)
{
ComponentPool* pool = GetComponentPool(type);
pool->ReactivateEntity(entity);
}
if (m_Initialized)
EventDispatcher::dispatch(EntityReactivatedEvent(entity));
}
void ComponentRegistry::RemoveEntity(Entity entity)
{
if (m_Initialized)
EventDispatcher::dispatch(EntityRemovedEvent(entity));
auto it = m_ComponentMap.find(entity);
if (it == m_ComponentMap.end())
return;
for (ComponentType type : it->second)
{
ComponentPool* pool = GetComponentPool(type);
pool->RemoveEntity(entity);
}
m_ComponentMap.erase(it);
}
void ComponentRegistry::Init()
{
m_Initialized = true;
}
void ComponentRegistry::Destroy()
{
for (ComponentPool* pool : m_ComponentPools)
delete pool;
m_ComponentPools.clear();
m_ComponentMap.clear();
m_NextEntity = 1;
m_EntityGroups.clear();
m_Initialized = false;
for (auto& clearer : m_GroupViewClearers)
clearer();
m_GroupViewClearers.clear();
}
| true |
9b27d8f7bd8f287a64f96ee828db80e8f2392734 | C++ | DatTestBench/Benchine | /Benchine/BenchineCore/Components/ScoreComponent.h | UTF-8 | 442 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Components/BaseComponent.h"
class ScoreComponent final : public BaseComponent
{
public:
ScoreComponent();
virtual ~ScoreComponent() override = default;
DEL_ROF(ScoreComponent)
[[nodiscard]] constexpr auto GetScore() const noexcept-> uint32_t { return m_Score; }
void AddScore(const uint32_t score) { m_Score += score; }
protected:
void Initialize() override;
private:
uint32_t m_Score;
}; | true |
911fce726b8286e4835c07860b57887d55781802 | C++ | KaufmanLabJILA/Chimera-Control-Master | /Chimera/NiawgWaiter.cpp | UTF-8 | 3,490 | 2.8125 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "NiawgWaiter.h"
/*
* This function is called to wait on the NIAWG until it finishes. It will eventually send messages to other threads
* to indicate when it finishes. If the niawg finishes before programming does, it starts outputting the default
* waveform in order to maintain a constant amount of power to the deflection AOMs.
* Return: the function returns -1 if error, -2 if abort, 0 if normal.
// opps it returns an unsigned. Watch out for that, -1 goes to huge number.
*/
unsigned __stdcall NiawgWaiter::niawgWaitThread(void* inputParam)
{
waitThreadInput* input = (waitThreadInput*)inputParam;
ViBoolean isDone = FALSE;
if (NIAWG_SAFEMODE)
{
// basically just pass through with a little wait, as if the niawg ran for 2 seconds then finished.
isDone = TRUE;
Sleep(2000);
}
while (!isDone)
{
if (eAbortNiawgFlag)
{
// aborting
return -2;
}
else
{
try
{
isDone = input->niawg->fgenConduit.isDone();
}
catch (Error&)
{
eWaitError = true;
delete input;
return -1;
}
}
}
if (eAbortNiawgFlag)
{
return -2;
}
if (WaitForSingleObjectEx(eWaitingForNIAWGEvent, 0, true) == WAIT_TIMEOUT)
{
/// then it's not ready. start the default generic waveform to maintain power output to AOM.
try
{
input->niawg->setDefaultWaveformScript( );
input->niawg->turnOn();
}
catch (Error&)
{
eWaitError = true;
delete input;
return -1;
}
}
/// now wait until programming is finished and main thread is ready.
WaitForSingleObject(eWaitingForNIAWGEvent, ULONG(INFINITY));
/// stop the default.
// now it's ready. stop the default.
try
{
input->niawg->turnOff();
}
catch (Error&)
{
eWaitError = true;
delete input;
return -1;
}
delete input;
return 0;
}
void NiawgWaiter::startWaitThread( NiawgController* niawgPtr, profileSettings profile )
{
eWaitError = false;
// create the waiting thread.
waitThreadInput* waitInput = new waitThreadInput;
waitInput->niawg = niawgPtr;
waitInput->profile = profile;
UINT NIAWGThreadID;
eNIAWGWaitThreadHandle = (HANDLE)_beginthreadex( 0, 0, &NiawgWaiter::niawgWaitThread, waitInput, 0, &NIAWGThreadID );
}
void NiawgWaiter::initialize()
{
eWaitingForNIAWGEvent = CreateEvent( NULL, FALSE, FALSE, TEXT( "eWaitingForNIAWGEvent" ) );
}
// waits for waiting thread to finish it's execution. If the niawg finished before the programming, this will return
// immediately. I think that I can get rid of the abort checks in here, this only ever gets called at the very end
// of the experiment and there's no reason for the checks to be this far inside the niawg handling.
void NiawgWaiter::wait( Communicator* comm )
{
systemAbortCheck( comm );
SetEvent( eWaitingForNIAWGEvent );
WaitForSingleObject( eNIAWGWaitThreadHandle, INFINITE );
systemAbortCheck( comm );
// check this flag that can be set by the wait thread.
if (eWaitError)
{
eWaitError = false;
thrower( "ERROR: Error in the wait function!\r\n" );
}
}
/*
* This function checks whether the system abort flag has been set, and if so, sends some messages and returns true. If not aborting, it returns false.
*/
void NiawgWaiter::systemAbortCheck( Communicator* comm )
{
// check if aborting
if ( eAbortNiawgFlag )
{
comm->sendStatus( "Aborted!\r\n" );
thrower( "Aborted!\r\n" );
}
}
| true |
89edb133525e15b13ade716bba866ffe17075fb0 | C++ | ubc333/library | /include/cpen333/process/impl/semaphore_guard.h | UTF-8 | 1,226 | 3.375 | 3 | [
"MIT"
] | permissive | /**
* @file
* @brief Semaphore guard, similar to std::lock_guard
*/
#ifndef CPEN333_PROCESS_SEMAPHORE_GUARD_H
#define CPEN333_PROCESS_SEMAPHORE_GUARD_H
namespace cpen333 {
namespace process {
/**
* @brief Semaphore guard, similar to std::lock_guard
*
* Protects a semaphore's wait/notify using RAII to ensure all resources
* are returned to the system
* @tparam Semaphore basic semaphore that supports wait() and notify()
*/
template<typename Semaphore>
class semaphore_guard {
Semaphore& sem_;
public:
/**
* @brief Constructor, waits on semaphore
* @param sem semaphore to wait on
*/
semaphore_guard(Semaphore& sem) : sem_(sem) {
sem_.wait();
}
// disable copy/move constructors
private:
semaphore_guard(const semaphore_guard&) DELETE_METHOD;
semaphore_guard(semaphore_guard&&) DELETE_METHOD;
semaphore_guard& operator=(const semaphore_guard&) DELETE_METHOD;
semaphore_guard& operator=(semaphore_guard&&) DELETE_METHOD;
public:
/**
* @brief Destructor, automatically notifies semaphore
*/
~semaphore_guard() {
sem_.notify();
}
};
} // process
} // cpen333
#endif //CPEN333_PROCESS_SEMAPHORE_GUARD_SEMAPHORE_H
| true |
e72978d4087b23251244474d4d6be2096216d604 | C++ | MarcoGrimaldo/DSD | /Practica7/c-string.cpp | UTF-8 | 1,392 | 3.25 | 3 | [] | no_license | #include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char* stringAleatorio() {
char letras[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char string[3];
for(int i = 0; i < 3; i++) {
int rand_l = rand() % 25;
string[i] = letras[rand_l];
}
string[3] = ' ';
static char prueba[] = "IPN ";
return string;
}
int buscaIPN(char *cadenota)
{
int con = 0;
/*for (int i = 0; i < strlen(cadenota); i++)
{
if (i != strlen(cadenota)-4)
{
if (cadenota[i] == 'I')
{
//cout << "Encontre I en " << i << endl;
if (cadenota[i+1] == 'P')
{
// cout << "Encontre P en "<< i+1 << endl;
if (cadenota[i+2] == 'N')
{
// cout << "Encontre N en " << i+2 << endl;
con++;
}
}
}
}
}*/
return con;
}
int main()
{
char *cadenota = NULL;
int n = 0;
int cont = 0;
srand(time(NULL));
printf("Teclea n: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
char* aux = stringAleatorio();
cadenota = (char*)realloc(cadenota, (i + 1) * 4);
memcpy(cadenota + (4 * i), aux, 4);
}
printf("\n%d\n",buscaIPN(cadenota));
return 0;
} | true |
ce1f1d9f16cd8b2990950673add3201ebbc69bf9 | C++ | TColon830/OrderFinder | /main.cpp | UTF-8 | 2,375 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <set>
//TColon
//Short program to find the order of an element
using namespace std;
int modulo(int a,int b,int n){
long long x=1,y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%n;
}
y = (y*y)%n; // squaring the base
b /= 2;
}
return x%n;
}
double gcd(double a, double b)
{
if (a < b)
return gcd(b, a);
// base case
if (fabs(b) < 0.001)
return a;
else
return (gcd(b, a - floor(a / b) * b));
}
int power(int base, unsigned int exp){
if (exp == 0)
return 1;
int temp = power(base, exp/2);
if (exp%2 == 0)
return temp*temp;
else
return base*temp*temp;
}
int main (){
int N = 0;
int value = 0;
vector<int> leastOrder;
vector<int> allLeastorders;
int largestleastOrder = 0;
int baseValue = 0;
int arr[25] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
int prime = 77;
int highestPrime = 0;
for (int a = 5; a < 6; a++){
leastOrder.clear();
if (gcd(a,prime-1) == 1){
leastOrder.clear();
cout << endl << "For base: " << a << " and N = " << prime << endl;
for (int b = 1; b < prime; b++){
value = modulo(a,b,prime);
cout << b << "=" << value << " ";
if (value == 1){
cout << b << "=" << value << " ";
leastOrder.push_back(b);
}
}
cout << endl << "leastOrder = " << leastOrder[0] << endl;
allLeastorders.push_back(leastOrder[0]);
if (leastOrder[0] > largestleastOrder){
largestleastOrder = leastOrder[0];
baseValue = a;
highestPrime = prime;
}
leastOrder.clear();
}
}
cout << "Base " << baseValue << " has largest least order of: " << largestleastOrder << " when N = " << prime << endl;
set<int> s;
for (int j = 0; j < allLeastorders.size(); j++)
s.insert(allLeastorders[j]);
cout << endl << endl << "ALL LEAST ORDERS" << endl;
set<int>::iterator it;
for (it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
cout << endl << endl;
sort(allLeastorders.begin(), allLeastorders.end());
allLeastorders.erase( unique(allLeastorders.begin(), allLeastorders.end()), allLeastorders.end() );
for (int k = 0; k < allLeastorders.size(); k++)
cout << allLeastorders[k] << " ";
}//end main()
| true |
9cddf6b36528e2b680c273e1401279c736e38159 | C++ | CyroPCJr/OmegaEngine | /Framework/AI/Inc/ArriveBehaviour.h | UTF-8 | 511 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "SteeringBehavior.h"
namespace Omega::AI
{
class ArriveBehaviour :public SteeringBehavior
{
public:
virtual ~ArriveBehaviour() = default;
Omega::Math::Vector2 Calculate(AI::Agent& agent) override;
Omega::Math::Vector2 Arrive(const AI::Agent& agent, const Omega::Math::Vector2& destination);
void ShowDebugDraw(const Agent& agent) override;
inline void SetSlowRadius(float radius) { mSlowRadius = radius; }
private:
float mSlowRadius = 100.0f;
};
} | true |
9f771db46bdcb0ac9a3d1eca0eb3d5d0be5eb6f0 | C++ | harmboschloo/CocaProject | /cocaUtils/source/LogStringComponent.cpp | UTF-8 | 882 | 2.546875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | #include "LogStringComponent.h"
#include <coca/INode.h>
#include <coca/attributes.h>
LogStringComponent::LogStringComponent()
{
}
LogStringComponent::~LogStringComponent()
{
}
bool LogStringComponent::init( coca::INode& node )
{
node.addAttribute( "prefix", coca::createInputOutputAttribute<std::string>(
coca::makeAccessor( _prefix ) ) );
node.addAttribute( "suffix", coca::createInputOutputAttribute<std::string>(
coca::makeAccessor( _suffix ) ) );
node.addAttribute( "string", coca::createInputAttribute<std::string>(
coca::makeFunction( *this, &LogStringComponent::log ) ) );
return true;
}
void LogStringComponent::onEnabled()
{
}
void LogStringComponent::onDisabled()
{
}
void LogStringComponent::log( std::string data )
{
COCA_INFO( _prefix << data << _suffix );
}
| true |
c8539a22a995a4559d8f8387750d840656a876c5 | C++ | robmcrosby/FelixEngine | /FelixEngine/FelixEngine/Systems/Events/EventListenerSet.h | UTF-8 | 1,516 | 2.75 | 3 | [] | no_license | //
// EventListenerSet.h
// FelixEngine
//
// Created by Robert Crosby on 9/12/17.
// Copyright © 2017 Robert Crosby. All rights reserved.
//
#ifndef EventListenerSet_h
#define EventListenerSet_h
#include "Event.h"
namespace fx {
/** Contains and manages Event Listeners */
class EventListenerSet {
private:
EventListeners _listeners;
public:
EventListenerSet() {}
~EventListenerSet() {clear();}
void clear() {_listeners.clear();}
void clean() {
EventListeners::iterator itr = _listeners.begin();
while (itr != _listeners.end()) {
if ((*itr)->isEmpty())
itr = _listeners.erase(itr);
}
}
void notify(const Event &event) {
EventListeners::iterator itr = _listeners.begin();
while (itr != _listeners.end()) {
if ((*itr)->isEmpty()) {
itr = _listeners.erase(itr);
}
else {
(*itr)->handle(event);
++itr;
}
}
}
void add(EventListener listener) {
for (EventListeners::iterator itr = _listeners.begin(); itr != _listeners.end(); ++itr) {
if (*itr == listener)
return;
}
_listeners.push_back(listener);
}
void remove(EventListener listener) {
EventListeners::iterator itr = _listeners.begin();
while (itr != _listeners.end()) {
if (*itr == listener)
itr = _listeners.erase(itr);
else
++itr;
}
}
};
}
#endif /* EventListenerSet_h */
| true |
f04b14ee9eebfbd27cfea06c0889e7f8e40e0e4b | C++ | pankaj799/cpp_bucket | /pointClass.cpp | UTF-8 | 505 | 3.484375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class pInClass{
int a;
int *p;
public:
void get(){
cout<<"Enter number \n";
cin>>a;
}
void put(){
cout<<a<<endl;
}
};
class pClass{
public:
int a;
};
int main()
{
class pInClass ob,*p;
cout<<"Pointer To Class :"<<endl;
p=&ob;
ob.get();
p->put();
(*p).put();
cout<<"\nPointer To Data Members\n";
cout<<"Enter Number\n";
int pClass::*ptr = &pClass::a;
class pClass o;
cin>>o.a;
cout<<o.*ptr<<endl;
return 0;
}
| true |
e8f3017cde091115fdabc875a075cc6c5740baf6 | C++ | sravankumarpothuraju/A-star | /Astarsearch.hpp | UTF-8 | 614 | 2.9375 | 3 | [] | no_license | //AStar Search.hpp
#pragma once
#include <ctime>
class AStar
{
public:
int a[3][3] = { 0 };
int goal[3][3] = { 0 };
int i, j; //counters
//cost so far, heuristic cost and total cost (f = g + h)
int g, h, f = 0;
AStar *parent;
AStar() {} //Constructor
~AStar() {} //Destructor
void getHeuristic();
bool setChildState();
bool getSuccessors();
void getTotalCost();
bool isGoal();
void solve();
void print();
bool isExplored(AStar &cur);
void printPath(AStar *cur);
bool operator<(const AStar &cur) const;
bool operator==(const AStar &cur) const;
}; | true |
f2583790a91b082cdc5076272ce8ccf69eeeebdf | C++ | Symphonym/Brainless | /Brainless/Brainless/EditorGridMode.cpp | UTF-8 | 11,666 | 2.609375 | 3 | [] | no_license | #include "EditorGridMode.h"
#include "Constants.h"
#include "Utility.h"
#include "Renderer.h"
#include "ResourceLoader.h"
#include "Constants.h"
#include <fstream>
#include <sstream>
#include <iostream>
EditorGridMode::EditorGridMode(TileMap &tilemap)
:
m_tilemap(tilemap),
m_autotilingEnabled(false),
m_currentTile(sf::FloatRect(100, 100, 0, 0), Tile::Ground, sf::Vector2f(Constants::LeftTileOffset, Constants::TopTileOffset))
{
m_highlightShape = sf::RectangleShape(sf::Vector2f(Constants::TileSize, Constants::TileSize));
m_highlightShape.setOutlineThickness(1);
m_currentTile.getSprite().setScale(0.8f, 0.8f);
// Initialize index text
m_indexText.setFont(ResourceLoader::instance().retrieveFont("DefaultFont"));
m_indexText.setString("X: 0 Y: 0");
m_indexText.setPosition(10, 200);
// Initialize autotiling text
m_autotilingText.setFont(ResourceLoader::instance().retrieveFont("DefaultFont"));
m_autotilingText.setPosition(10, 500);
m_autotilingText.setColor(sf::Color::Green);
m_autotilingText.setString("Autotiling: " + std::string((m_autotilingEnabled ? "enabled" : "disabled")));
// Add autotiling ranges
parseAutotilingFile("autotiling/numbersforRoad.txt", "RoadAutotiling");
parseAutotilingFile("autotiling/numbersforWood.txt", "WoodAutotiling");
parseAutotilingFile("autotiling/numbersforGrass.txt", "GrassAutotiling");
parseAutotilingFile("autotiling/numbersforSewer.txt", "SewerAutotiling");
//addAutotilingRange("RoadAutotiling", Tile::Road_Middle,
//{
// AutotilingValue(0, Tile::Road_Down)
//});
m_tileTypes =
{
Tile::Nothing,
Tile::Ground,
Tile::Red,
Tile::Blue,
Tile::Tilt,
Tile::Platform,
Tile::Solid_Invisible,
Tile::Solid_Invisible_Platform,
Tile::Road_Middle,
Tile::Road_Top_Alone,
Tile::Road_Tilt,
Tile::Road_Tilt_Corner,
Tile::Wood_Top_Alone,
Tile::Wood_Tilt,
Tile::Wood_Tilt_Corner,
Tile::Grass_Top_Alone,
Tile::Grass_Tilt,
Tile::Grass_Tilt_Corner,
Tile::Sewer_Top_Alone,
Tile::Sewer_Tilt,
Tile::Sewer_Tilt_Corner
};
}
EditorGridMode::~EditorGridMode()
{
}
bool EditorGridMode::events(const sf::Event &event, const sf::RenderWindow &editorWindow)
{
if (event.type == sf::Event::MouseWheelMoved)
{
// Scroll between block types
//int curIndex = static_cast<int>(m_currentTile.getType());
m_currentTileIndex += event.mouseWheel.delta;
m_currentTileIndex = Utility::clampValue<int>(m_currentTileIndex, 0, m_tileTypes.size() - 1);//Constants::BlockTypeCount - 1);
m_currentTile.setType(m_tileTypes[m_currentTileIndex]);
}
else if (event.type == sf::Event::KeyReleased)
{
if (event.key.code == sf::Keyboard::M)
{
// If Ctrl+M is pressed, refresh autotiling for whole map
if (event.key.control)
{
for (std::size_t x = 0; x < Constants::MapWidth; x++)
{
for (std::size_t y = 0; y < Constants::MapHeight; y++)
{
Tile &tile = m_tilemap.getTile(x, y);
auto itr = m_autotiling.find(tile.getAutotilingRangeName());
// Autotiling range exists
if (itr != m_autotiling.end())
{
int autotilingValue = calculateAutotilingValue(x, y, tile.getAutotilingRangeName());
m_tilemap.getTile(x, y).setType(itr->second[autotilingValue]);
}
}
}
}
// Toggle autotiling
else
{
m_autotilingEnabled = !m_autotilingEnabled;
m_autotilingText.setString("Autotiling: " + std::string((m_autotilingEnabled ? "enabled" : "disabled")));
}
}
}
return false;
}
bool EditorGridMode::update(float deltaTime, const sf::RenderWindow &editorWindow)
{
// Get position of mouse and map it to an index
sf::Vector2i mouseIndex = m_tilemap.positionToIndex(editorWindow.mapPixelToCoords(sf::Mouse::getPosition(editorWindow)));
mouseIndex.x = Utility::clampValue<int>(mouseIndex.x, 0, Constants::MapWidth - 1);
mouseIndex.y = Utility::clampValue<int>(mouseIndex.y, 0, Constants::MapHeight - 1);
// Update index text
m_indexText.setString("X: " + std::to_string(mouseIndex.x) + " Y: " + std::to_string(mouseIndex.y));
// Set position of highlight relative to mouse
m_highlightShape.setPosition(
m_tilemap.getTile(mouseIndex.x, mouseIndex.y).getBounds().left,
m_tilemap.getTile(mouseIndex.x, mouseIndex.y).getBounds().top);
// Change the properties of a tile with left/right mouseclick
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
m_highlightShape.setFillColor(sf::Color::Color(0, 255, 0, 128));
m_highlightShape.setOutlineColor(sf::Color::Color(0, 255, 0, 255));
// Autotiling is enabled and the current tile has an autotiling range
if (m_autotilingEnabled && !m_currentTile.getAutotilingRangeName().empty())
{
auto itr = m_autotiling.find(m_currentTile.getAutotilingRangeName());
// Autotiling range exists
if (itr != m_autotiling.end())
{
int autotilingValue = calculateAutotilingValue(mouseIndex.x, mouseIndex.y, m_currentTile.getAutotilingRangeName());
m_tilemap.getTile(mouseIndex.x, mouseIndex.y).setType(itr->second[autotilingValue]);
std::vector<sf::Vector2i> adjacentIndices = getAdjacentTileIndices(mouseIndex.x, mouseIndex.y);
for (auto &indice : adjacentIndices)
{
Tile& adjacentTile = m_tilemap.getTile(indice.x, indice.y);
if (adjacentTile.getAutotilingRangeName() == m_currentTile.getAutotilingRangeName())
{
int tilingValue = calculateAutotilingValue(indice.x, indice.y, adjacentTile.getAutotilingRangeName());
adjacentTile.setType(itr->second[tilingValue]);
}
}
}
else // Just place tile without autotiling
m_tilemap.getTile(mouseIndex.x, mouseIndex.y).setType(m_currentTile.getType());
}
else
m_tilemap.getTile(mouseIndex.x, mouseIndex.y).setType(m_currentTile.getType());
return true;
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
m_highlightShape.setFillColor(sf::Color::Color(255, 0, 0, 128));
m_highlightShape.setOutlineColor(sf::Color::Color(255, 0, 0, 255));
m_tilemap.getTile(mouseIndex.x, mouseIndex.y).setType(Tile::Nothing);
// Autotile nearby tiles if autotiling is enabled
if (m_autotilingEnabled)
{
std::vector<sf::Vector2i> adjacentIndices = getAdjacentTileIndices(mouseIndex.x, mouseIndex.y);
for (auto &indice : adjacentIndices)
{
Tile& adjacentTile = m_tilemap.getTile(indice.x, indice.y);
auto itr = m_autotiling.find(adjacentTile.getAutotilingRangeName());
// Autotiling range exists
if (itr != m_autotiling.end())
{
int autotilingValue = calculateAutotilingValue(indice.x, indice.y, adjacentTile.getAutotilingRangeName());
m_tilemap.getTile(indice.x, indice.y).setType(itr->second[autotilingValue]);
}
}
}
return true;
}
else
{
m_highlightShape.setFillColor(sf::Color::Color(255, 255, 255, 128));
m_highlightShape.setOutlineColor(sf::Color::Color(255, 255, 255, 255));
return false;
}
}
void EditorGridMode::draw()
{
Renderer::instance().drawAbove(m_highlightShape);
Renderer::instance().drawHUD(m_currentTile.getSprite());
Renderer::instance().drawHUD(m_indexText);
Renderer::instance().drawHUD(m_autotilingText);
}
void EditorGridMode::addAutotilingRange(const std::string &name, Tile::TileTypes defaultValue, const std::vector<AutotilingValue> &autotilingRange)
{
AutotilingData data;
// Initialize with default value
for (std::size_t i = 0; i < data.size(); i++)
data[i] = defaultValue;
// Fill with new autotiling data
for (auto &autotilingValue : autotilingRange)
data[autotilingValue.first] = autotilingValue.second;
// Store the data
m_autotiling[name] = data;
}
int EditorGridMode::calculateAutotilingValue(int x, int y, const std::string &autotilingRangeName)
{
int autotilingValue = 0;
/*
Autotiling bitmap
1 2 4
128 + 8
64 32 16
*/
// Tile to the top left exists
if (y - 1 >= 0 && x - 1 >= 0 && m_tilemap.getTile(x - 1, y - 1).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 1;
// Tile to the top right exists
if (y - 1 >= 0 && x + 1 < Constants::MapWidth && m_tilemap.getTile(x + 1, y - 1).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 4;
// Tile to the bottom right exists
if (y + 1 < Constants::MapHeight && x + 1 < Constants::MapWidth && m_tilemap.getTile(x + 1, y + 1).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 16;
// Tile to the bottom left exists
if (y + 1 < Constants::MapHeight && x - 1 >= 0 && m_tilemap.getTile(x - 1, y + 1).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 64;
// Tile above exists
if (y - 1 >= 0 && m_tilemap.getTile(x, y - 1).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 2;
// Tile below exists
if (y + 1 < Constants::MapHeight && m_tilemap.getTile(x, y + 1).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 32;
// Tile to the left exists
if (x - 1 >= 0 && m_tilemap.getTile(x - 1, y).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 128;
// Tile to the right exists
if (x + 1 < Constants::MapWidth && m_tilemap.getTile(x + 1, y).getAutotilingRangeName() == autotilingRangeName)
autotilingValue += 8;
return autotilingValue;
}
void EditorGridMode::parseAutotilingFile(const std::string &fileName, const std::string &rangeName)
{
std::ifstream reader(fileName);
if (reader.is_open())
{
// Stores the lines of the file to debug for duplicate autotiling values
std::unordered_map<int, std::vector<std::string> > duplicateDebug;
AutotilingData data;
// Default initialize with something obvious, as all values should be set
for (std::size_t i = 0; i < data.size(); i++)
data[i] = Tile::Red;
std::string line;
while (std::getline(reader, line))
{
std::stringstream ss(line);
// Read tiletype at start of line
int tileType = 0;
ss >> tileType;
Tile::TileTypes tileTypeReal = static_cast<Tile::TileTypes>(tileType);;
// Read all the autotiling values this tiletype corresponds to
std::string autotilingValueStr;
ss >> autotilingValueStr;
std::vector<std::string> autotilingValues = Utility::splitString(autotilingValueStr, ',');
for (auto &value : autotilingValues)
{
int val = Utility::stringToNumber<std::size_t>(value);
duplicateDebug[val].push_back(line);
data[val] = tileTypeReal;
}
}
for (auto &debugVal : duplicateDebug)
{
if (debugVal.second.size() != 1)
{
std::cout << "Duplicates of: " << debugVal.first << std::endl;
for (auto &debugLine : debugVal.second)
{
std::cout << debugLine << std::endl;
}
}
}
m_autotiling[rangeName] = data;
}
reader.close();
}
std::vector<sf::Vector2i> EditorGridMode::getAdjacentTileIndices(int x, int y)
{
std::vector<sf::Vector2i> result;
// Tile to the top left exists
if (y - 1 >= 0 && x - 1 >= 0)
result.push_back(sf::Vector2i(x - 1, y - 1));
// Tile to the top right exists
if (y - 1 >= 0 && x + 1 < Constants::MapWidth)
result.push_back(sf::Vector2i(x + 1, y - 1));
// Tile to the bottom right exists
if (y + 1 < Constants::MapHeight && x + 1 < Constants::MapWidth)
result.push_back(sf::Vector2i(x + 1, y + 1));
// Tile to the bottom left exists
if (y + 1 < Constants::MapHeight && x - 1 >= 0)
result.push_back(sf::Vector2i(x - 1, y + 1));
// Tile above exists
if (y - 1 >= 0)
result.push_back(sf::Vector2i(x, y - 1));
// Tile below exists
if (y + 1 < Constants::MapHeight)
result.push_back(sf::Vector2i(x, y + 1));
// Tile to the left exists
if (x - 1 >= 0)
result.push_back(sf::Vector2i(x - 1, y));
// Tile to the right exists
if (x + 1 < Constants::MapWidth)
result.push_back(sf::Vector2i(x + 1, y));
return result;
} | true |
50ff75901fc926fea0b8c1131e73278fb4460f7f | C++ | Hopson97/City-Game | /Editor/Source/App.h | UTF-8 | 1,375 | 2.65625 | 3 | [] | no_license | #ifndef APP_H
#define APP_H
#include <SFML/Graphics.hpp>
#include <vector>
#include "Mouse.h"
enum class Mode
{
Water,
Collision,
Ground
};
enum class State
{
None,
Rectangle
};
class App
{
public:
App ( const std::string& texturePath );
void run();
private:
void checkForClose();
void input ();
void update ();
void draw ();
void switchMode ();
void setUpRect ();
void updateRect ();
void addRect ();
void drawRects ();
void tryRemoveRect ();
void save ();
void iterateRemoveRect ( std::vector<sf::RectangleShape>& rects );
Mode m_currentMode = Mode::Water;
Mouse m_mouse;
State m_state;
sf::RenderWindow m_window;
sf::RectangleShape m_mapSprite;
sf::Font m_font;
sf::Text m_text;
sf::Image mapImage;
std::string m_modeString;
const std::string texturePath;
std::vector<sf::RectangleShape> m_waterRects;
std::vector<sf::RectangleShape> m_groundRects;
std::vector<sf::RectangleShape> m_collisionRects;
sf::RectangleShape m_currentRect;
static
constexpr int WIDTH = 1280,
HEIGHT = 600;
};
#endif // APP_H
| true |
2a688d48dfc5e5cc25b66379a9e1a5e9532bbae7 | C++ | mbfilho/icpc | /Questoes UVA ACM/408 - Uniform Generator.cpp | UTF-8 | 393 | 3.140625 | 3 | [] | no_license | #include <cstdio>
int gcd( int a, int b ){
int mod;
while( b ){
mod = a % b;
a = b;
b = mod;
}
return a;
}
int main(){
int step, mod;
while( scanf( "%d %d", &step, &mod ) != EOF ){
if( gcd( step, mod ) == 1 ){
printf( "%10d%10d Good Choice\n", step, mod );
}else
printf( "%10d%10d Bad Choice\n", step, mod );
printf( "\n" );
}
}
| true |
91f10b12897e72d98364df6b9b922f53b76dbe5c | C++ | VISWESWARAN1998/Academia | /Zoho Interview Questions/Real Interview Questions Conducted on 01.12.2018/VISWESWARAN_CSE/question_four.cpp | UTF-8 | 1,953 | 3.859375 | 4 | [] | no_license | // SWAMI KARUPPASWAMI THUNNAI
#include<iostream>
#include<string>
#include<set>
#include<map>
class sorter
{
private:
std::multiset<int> sorted_elements;
std::map<int, unsigned int> sorted_elements_with_count;
public:
void add(int element);
void add_counts();
void display();
};
void sorter::add(int element)
{
sorted_elements.insert(element);
}
void sorter::add_counts()
{
std::multiset<int>::iterator itr1 = sorted_elements.begin();
std::multiset<int>::iterator itr2 = sorted_elements.end();
for (std::multiset<int>::iterator itr = itr1; itr != itr2; ++itr)
{
if (sorted_elements_with_count.find(*itr) == sorted_elements_with_count.end())
{
sorted_elements_with_count[*itr] = 1;
}
else
{
sorted_elements_with_count[*itr] += 1;
}
}
}
void sorter::display()
{
std::multiset<unsigned int> arrangements;
std::set<int> already_displayed;
std::map<int, unsigned int>::iterator itr1 = sorted_elements_with_count.begin();
std::map<int, unsigned int>::iterator itr2 = sorted_elements_with_count.end();
for (std::map<int, unsigned int>::iterator itr = itr1; itr != itr2; ++itr)
{
arrangements.insert(itr->second);
}
for (std::multiset<unsigned int>::reverse_iterator itr = arrangements.rbegin(); itr != arrangements.rend(); ++itr)
{
for (std::map<int, unsigned int>::iterator map_itr = sorted_elements_with_count.begin(); map_itr != sorted_elements_with_count.end(); ++map_itr)
{
if ((map_itr->second == *itr) && (already_displayed.find(map_itr->first) == already_displayed.end()))
{
already_displayed.insert(map_itr->first);
for (int i = 0; i < *itr; i++) {
std::cout << map_itr->first << ", ";
}
}
}
}
}
int main()
{
std::cout << "How many elements: ";
int count;
sorter sort;
std::cin >> count;
for (int i = 0; i < count; i++)
{
std::cout << "element " << i + 1 << ": ";
int element;
std::cin >> element;
sort.add(element);
}
sort.add_counts();
sort.display();
std::cin >> count;
} | true |
7f2f202cc5531ac799c2a79beba1c22ecc8c072c | C++ | radii-dev/ps_study | /BaekJoon/KOI/KOI2018/Drawarrow/Drawarrow.cpp | UTF-8 | 1,662 | 3.34375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
struct dot {
int location;
int color;
};
int makeArrow(vector<int>* dots, int targetLocation) {
if (dots->at(targetLocation) == -1)
return 0;
else {
int len = 0;
int tmploc[2] = { targetLocation - len, targetLocation + len };
bool findArrow = false;
do {
len++;
if (tmploc[0] >= 0)
tmploc[0]--;
else tmploc[0] = -1;
if (tmploc[1] >= 0 && tmploc[1] <= dots->size())
tmploc[1]++;
else tmploc[1] = -1;
if (tmploc[0] < 0) {
if (tmploc[1] < dots->size() && dots->at(targetLocation) == dots->at(tmploc[1]))
findArrow = true;
}
else if (tmploc[1] < 0) {
if (tmploc[0] < dots->size() && dots->at(targetLocation) == dots->at(tmploc[0]))
findArrow = true;
}
else {
if ((tmploc[0] < dots->size() && dots->at(targetLocation) == dots->at(tmploc[0])) || (tmploc[1] < dots->size() && dots->at(targetLocation) == dots->at(tmploc[1])))
findArrow = true;
}
} while (!findArrow);
return len;
}
}
int sumArrowlen(vector<int>* dots) {
int sum = 0;
for (int i = 0; i < dots->size(); i++)
sum += makeArrow(dots, i);
return sum;
}
int main() {
int num = 0;
int max = 0;
dot tmp;
cin >> num;
vector<dot> tmpdots;
for (int i = 0; i < num; i++) {
cin >> tmp.location;
cin >> tmp.color;
if (tmp.location > max)
max = tmp.location;
tmpdots.push_back(tmp);
}
vector<int>* dots = new vector<int>(max + 1);
for (vector<int>::iterator it = dots->begin(); it < dots->end(); it++)
*it = -1;
for (int i = 0; i < num; i++) {
dots->at(tmpdots.at(i).location) = tmpdots.at(i).color;
}
cout << sumArrowlen(dots);
} | true |
723fe2c0b0df721df8178d9e95779ac910828376 | C++ | tliu526/ireg_CA | /Graph.tpp | UTF-8 | 3,149 | 3.546875 | 4 | [] | no_license | /*
Implementing the adjacency list graph.
(c) 2015 Tony Liu.
*/
#include <iostream>
using namespace std;
template<class T, class D>
T Graph<T,D>::add_vertex(T label, D data) {
if(dict.count(label) == 0) { //we need to add the vertex to the graph
Vertex v(label, data);
dict[label] = v;
}
return label;
}
template<class T, class D>
void Graph<T,D>::remove_vertex(T label){
if (dict.count(label) == 1){
dict.erase(label);
}
}
template<class T, class D>
void Graph<T,D>::add_edge(T label1, T label2){
if ((dict.count(label1) == 1) && (dict.count(label2) == 1)) {
//we're undirected, so need to add to each other's neighbor list
dict[label1].add_neighbor(label2);
dict[label2].add_neighbor(label1);
}
}
template<class T, class D>
void Graph<T,D>::remove_edge(T label1, T label2){
if ((dict.count(label1) == 1) && (dict.count(label2) == 1)) {
//we're undirected, so need to add to each other's neighbor list
dict[label1].remove_neighbor(label2);
dict[label2].remove_neighbor(label1);
}
}
template<class T, class D>
void Graph<T,D>::print_adj_list() {
float avg = 0;
typename map<T, Vertex>::iterator map_it;
for (map_it = dict.begin(); map_it != dict.end(); map_it++) {
cout << map_it->first;
Vertex v = map_it->second;
avg += v.get_neighbors()->size();
typename list<T>::iterator list_it;
for (list_it = v.get_neighbors()->begin(); list_it != v.get_neighbors()->end(); list_it++) {
cout << "->" << *list_it;
}
cout << endl;
}
cout << "Average degree: " << avg / dict.size() << endl;
}
template<class T, class D>
D* Graph<T,D>::get_data(T label){
return dict[label].get_data();
}
template<class T, class D>
list<T> *Graph<T,D>::get_neighbors(T label){
return dict[label].get_neighbors();
}
template<class T, class D>
vector<T> Graph<T,D>::get_vert_labels(){
vector<T> labels;
typename map<T, Vertex>::iterator dict_it;
for(dict_it = dict.begin(); dict_it != dict.end(); dict_it++){
labels.push_back(dict_it->first);
}
return labels;
}
/**** VERTEX IMPLEMENTATION ****/
template<class T, class D>
Graph<T,D>::Vertex::Vertex(T l, D d) {
label = l;
data = d;
}
template<class T, class D>
T Graph<T,D>::Vertex::get_label(){
return label;
}
template<class T, class D>
D* Graph<T,D>::Vertex::get_data() {
return &data;
}
template<class T, class D>
void Graph<T,D>::Vertex::add_neighbor(T label) {
if(count(neighbors.begin(), neighbors.end(), label) == 0) {
neighbors.push_back(label);
}
}
template<class T, class D>
void Graph<T,D>::Vertex::remove_neighbor(T label) {
if(count(neighbors.begin(), neighbors.end(), label) > 0) {
neighbors.remove(label);
}
}
template<class T, class D>
list<T> *Graph<T,D>::Vertex::get_neighbors() {
return &neighbors;
}
/*
//debugging
int main() {
Graph<int, int> g;
int a = g.add_vertex(1,2);
int b = g.add_vertex(2,2);
int c = g.add_vertex(3,2);
int d = g.add_vertex(4,2);
g.add_edge(a,b);
g.add_edge(b,c);
g.add_edge(c,d);
g.add_edge(d,a);
g.print_adj_list();
}
*/ | true |
48fa4a9c28ef06c36ca851e1f7af4e800f6e9e2e | C++ | jencmart/bi-aps | /Verilog/aps/assemblyHexCompiler/main.cpp | UTF-8 | 11,029 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <map>
#include <bitset>
using namespace std;
class UnknownOperand
{
string m_op;
public:
explicit UnknownOperand( string & op) : m_op(op) {}
friend ostream &operator<<(ostream &os, const UnknownOperand &operand) {
os << "Error : '" << operand.m_op << "'" << endl;
return os;
}
};
char getHexCharacter(const string & str)
{
if(str == "1111") return 'F';
else if(str == "1110") return 'E';
else if(str == "1101") return 'D';
else if(str == "1100") return 'C';
else if(str == "1011") return 'B';
else if(str == "1010") return 'A';
else if(str == "1001") return '9';
else if(str == "1000") return '8';
else if(str == "0111") return '7';
else if(str == "0110") return '6';
else if(str == "0101") return '5';
else if(str == "0100") return '4';
else if(str == "0011") return '3';
else if(str == "0010") return '2';
else if(str == "0001") return '1';
else if(str == "0000") return '0';
else if(str == "111") return '7';
else if(str == "110") return '6';
else if(str == "101") return '5';
else if(str == "100") return '4';
else if(str == "011") return '3';
else if(str == "010") return '2';
else if(str == "001") return '1';
else if(str == "000") return '0';
else if(str == "11") return '3';
else if(str == "10") return '2';
else if(str == "01") return '1';
else if(str == "00") return '0';
else if(str == "1" ) return '1';
else return '0';
}
string byteFromRegNum( string s)
{
s.erase(0,1);
auto reg =(unsigned) stoi(s);
return bitset< 5 >( reg ).to_string();
}
void parse(vector<string> & tokens, vector<string> & dataToWrite, map<string, string> & defines, map<string, int> & addr, int instrPos )
{
string binaryString;
/// s-t-d style instructions
if(tokens[0] == "add" ||
tokens[0] == "sub" ||
tokens[0] == "and" ||
tokens[0] == "or" ||
tokens[0] == "slt" ||
tokens[0] == "addu.qb" ||
tokens[0] == "addu_s.qb"
)
{
if(tokens[0] == "addu.qb" || tokens[0] == "addu_s.qb")
binaryString += "011111";
else
binaryString += "000000";
string d = tokens[1];
string s = tokens[2];
string t = tokens[3];
// save s
if(s[0] == '$')
binaryString += byteFromRegNum(s);
else
binaryString += byteFromRegNum( defines.find(s)->second);
// save t
if(t[0] == '$')
binaryString += byteFromRegNum(t);
else
binaryString += byteFromRegNum( defines.find(t)->second);
// save d
if(d[0] == '$')
binaryString += byteFromRegNum(d);
//save rest...
else
binaryString += byteFromRegNum( defines.find(d)->second);
if (tokens[0] == "add")
binaryString += "00000100000";
else if(tokens[0] == "sub")
binaryString += "00000100010";
else if(tokens[0] == "and")
binaryString += "00000100100";
else if(tokens[0] == "or")
binaryString += "00000100101";
else if(tokens[0] == "slt")
binaryString += "00000101010";
else if(tokens[0] == "addu.qb")
binaryString += "00000010000";
else if(tokens[0] == "addu_s.qb")
binaryString += "00100010000";
}
else if ( tokens[0] == "sllv" ||
tokens[0] == "srlv" ||
tokens[0] == "srav")
{
binaryString += "000000";
string d = tokens[1];
string t = tokens[2];
string s = tokens[3];
// save s
if(s[0] == '$')
binaryString += byteFromRegNum(s);
else
binaryString += byteFromRegNum( defines.find(s)->second);
// save t
if(t[0] == '$')
binaryString += byteFromRegNum(t);
else
binaryString += byteFromRegNum( defines.find(t)->second);
// save d
if(d[0] == '$')
binaryString += byteFromRegNum(d);
//save rest...
else
binaryString += byteFromRegNum( defines.find(d)->second);
if(tokens[0] == "sllv")
binaryString += "00000000100";
else if(tokens[0] == "srlv")
binaryString += "00000000110";
else if(tokens[0] == "srav")
binaryString += "00000000111";
}
else if(tokens[0] == "addi")
{
// save infix
binaryString += "001000";
string t = tokens[1];
string s = tokens[2]; // ano ok
string imm = tokens[3];
// save s
if(s[0] == '$')
binaryString += byteFromRegNum(s);
else
binaryString += byteFromRegNum( defines.find(s)->second);
// save t
if(t[0] == '$')
binaryString += byteFromRegNum(t);
else
binaryString += byteFromRegNum( defines.find(t)->second);
// save imm todo done - muze byt adresa...
if( ! isdigit(imm[0]))
binaryString += bitset< 16 >( (unsigned long)addr.find(imm)->second ).to_string();
else
binaryString += bitset< 16 >( (unsigned) stoi(imm) ).to_string();
}
/// LW SW
else if(tokens[0] == "lw" || tokens[0] == "sw") // todo - zatim nepotrebuji, ale do lw, sw take muze jit offset jako adr ?
{
if(tokens[0] == "lw" )
binaryString += "100011";
else
binaryString += "101011";
string t = tokens[1];
string offset;
string s;
string tmp = tokens[2];
//todo
for(int i = 0 ; i < tokens[2].size() ; ++i)
{
if(tokens[2][i] == '(')
{
offset = tokens[2].substr(0,i);
s = tokens[2].substr(i+1, tmp.size() - (i+2));
break;
}
}
// save s
if(s[0] == '$')
binaryString += byteFromRegNum(s);
else
binaryString += byteFromRegNum( defines.find(s)->second);
// save t
if(t[0] == '$')
binaryString += byteFromRegNum(t);
else
binaryString += byteFromRegNum( defines.find(t)->second);
// save imm
binaryString += bitset< 16 >( (unsigned) stoi(offset) ).to_string();
}
else if(tokens[0] == "beq")
{
binaryString += "000100";
string s = tokens[1];
string t = tokens[2];
string offset = tokens[3];
// save s
if(s[0] == '$')
binaryString += byteFromRegNum(s);
else
binaryString += byteFromRegNum( defines.find(s)->second);
// save t
if(t[0] == '$')
binaryString += byteFromRegNum(t);
else
binaryString += byteFromRegNum( defines.find(t)->second);
if( ! isdigit(offset[0])) // todo done - offset CYHBA
binaryString += bitset< 16 >( (unsigned long)addr.find(offset)->second - instrPos - 1).to_string();
else
// save offset
binaryString += bitset< 16 >( (unsigned) stoi(offset) ).to_string();
}
else if(tokens[0] == "jal")
{
binaryString += "000011";
string target = tokens[1];
if( ! isdigit(target[0])) // todo done target - adresa naprimo - ok
binaryString += bitset< 26 >( (unsigned long)addr.find(target)->second ).to_string(); // NESMI SE NASOBIT 4MA KOKOTE
else
binaryString += bitset< 26 >( (unsigned) stoi(target) ).to_string();
}
else if(tokens[0] == "jr")
{
binaryString += "000111";
string s = tokens[1];
// save s
if(s[0] == '$')
binaryString += byteFromRegNum(s);
else
binaryString += byteFromRegNum( defines.find(s)->second);
binaryString += "000000000000000001000";
}
else
{
throw UnknownOperand(tokens[0]);
}
string hexString;
hexString += getHexCharacter(binaryString.substr (0,4) );
hexString += getHexCharacter(binaryString.substr (4,4) );
hexString += getHexCharacter(binaryString.substr (8,4) );
hexString += getHexCharacter(binaryString.substr (12,4) );
hexString += getHexCharacter(binaryString.substr (16,4) );
hexString += getHexCharacter(binaryString.substr (20,4) );
hexString += getHexCharacter(binaryString.substr (24,4) );
hexString += getHexCharacter(binaryString.substr (28,4) );
dataToWrite.emplace_back(hexString);
}
int main()
{
map<string, string> defines;
vector<string> dataToWrite;
map<string, int> addr;
vector<vector<string>> instructions;
while(true)
{
string str; getline(cin, str);
if(cin.eof())
break;
if(str == "exit")
break;
for(auto & c : str) // change commas to spaces
if(c ==',' )
c = ' ';
vector<string> tokens;
istringstream iss(str);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));
if(tokens.empty() || (tokens[0][0] == '/' && tokens[0][1] == '/' ) || tokens[0][0] == '.' )
continue;
else if(tokens[0] == "#define") // define value defined by define
{
defines[tokens[1]] = tokens[2]; // {#define s0 $20}
continue;
}
else if(tokens[0].back() == ':') // bude to adresa ;
{
tokens[0].erase(tokens[0].size() - 1); // odstran dvojtecku
addr[tokens[0]] = (int)instructions.size();
}
else
{
instructions.emplace_back(tokens);
}
}
for(int i = 0 ; i < (int)instructions.size() ; ++i)
{
try {
parse(instructions[i], dataToWrite, defines, addr, i);
}catch (UnknownOperand & x)
{
cout << x;
return 1;
}
}
for(auto & s : dataToWrite)
{
cout << s << endl;
}
// if(dataToWrite.size() < 64)
// {
// for(int i = (int)dataToWrite.size() ; i < 64 ; ++i)
// cout << "00000000" << endl;
// }
return 0;
}
/***
*
#define t0 $1
addi t0 $0 3
addi $2 $0 5
addi $3 $0 8
add $4 $1 $2
beq $3 $4 5
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
***/ | true |
2adc2a569b6c22a26b18f8ca54d9b0181a3af630 | C++ | MinByeongChan/myMBC | /Codingtest/Baekjoon/1699_AddOfExponentiation.cpp | UTF-8 | 620 | 3.25 | 3 | [] | no_license | #include <iostream>
#define MAX 100001
using namespace std;
//sdad제곱 함수
int EXPO(int a){
return a*a;
}
//최솟값 함수
int MIN(int a, int b){
return a>b ? b : a;
}
int dp[MAX];
// 동전 2문제와 동일하게 접근
int main(int argc, char** argv) {
//변수 선언
int N; // 어떤 자연수
//INPUT
cin >> N;
if(N < 1) return -1;
dp[0] = 0;
for(int i=1; i<=N; i++){
dp[i] = MAX;
}
for(int i=0; i<N/2; i++){
for(int j=EXPO(i+1); j<=N; j++){
dp[j] = MIN(dp[j], dp[j - EXPO(i+1)] + 1);
cout << EXPO(i+1) << " : "<< dp[j] << endl;
}
}
cout << dp[N];
return 0;
}
| true |
e2dc2c267faa5f53d8b24717bd3b428e45285481 | C++ | Junber/LD-38 | /Enemy_types.cpp | UTF-8 | 2,218 | 2.90625 | 3 | [] | no_license | // stage 1
{
Enemy_type* e = new Enemy_type;
e->arms=0;
e->blood_per_arm=0;
e->strenght_per_arm=3;
e->blood=5;
e->tex="Armless Degenerate";
e->number = 3;
e->min_radius = 1;
e->max_radius = 10;
e->arm_name = "";
e->explosion_radius = 7;
enemy_types.push_back(e);
start_monster = e;
}
{
Enemy_type* e = new Enemy_type;
e->arms=1;
e->blood_per_arm=5;
e->strenght_per_arm=5;
e->blood=10;
e->tex="One-Armed Bandit";
e->number = 1;
e->min_radius = 1;
e->max_radius = 10;
e->arm_name = "Normal Arm";
e->explosion_radius = 7;
enemy_types.push_back(e);
}
// stage 2
{
Enemy_type* e = new Enemy_type;
e->arms=0;
e->blood_per_arm=0;
e->strenght_per_arm=3;
e->blood=5;
e->tex="Armless Degenerate";
e->number = 5;
e->min_radius = 11;
e->max_radius = 20;
e->arm_name = "";
e->explosion_radius = 7;
enemy_types.push_back(e);
}
{
Enemy_type* e = new Enemy_type;
e->arms=1;
e->blood_per_arm=5;
e->strenght_per_arm=5;
e->blood=10;
e->tex="One-Armed Bandit";
e->number = 3;
e->min_radius = 11;
e->max_radius = 20;
e->arm_name = "Normal Arm";
e->explosion_radius = 7;
enemy_types.push_back(e);
}
{
Enemy_type* e = new Enemy_type;
e->arms=2;
e->blood_per_arm=3;
e->strenght_per_arm=3;
e->blood=3;
e->tex="Weak Guy";
e->number = 3;
e->min_radius = 11;
e->max_radius = 20;
e->arm_name = "Weak Arm";
e->explosion_radius = 9;
enemy_types.push_back(e);
}
//stage 3
{
Enemy_type* e = new Enemy_type;
e->arms=2;
e->blood_per_arm=3;
e->strenght_per_arm=7;
e->blood=15;
e->tex="Cripple Crew Soldier";
e->number = 5;
e->min_radius = 21;
e->max_radius = 30;
e->arm_name = "Soldiers Arm";
e->explosion_radius = 9;
enemy_types.push_back(e);
}
{
Enemy_type* e = new Enemy_type;
e->arms=2;
e->blood_per_arm=3;
e->strenght_per_arm=3;
e->blood=3;
e->tex="Weak Guy";
e->number = 3;
e->min_radius = 21;
e->max_radius = 30;
e->arm_name = "Weak Arm";
e->explosion_radius = 9;
enemy_types.push_back(e);
}
| true |
5deed633949ae31348379e1bfbf790a58520433f | C++ | rajpratyush/Hacktober-CP-contributions | /SPOJ_LIST/Range_Sum.cpp | UTF-8 | 919 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
#define ll long long
ll bit[1000005]={0};
ll n;
//writing code for moving in backward dir^ storing in reverse order
void update(ll i, ll val){
while(i>0){
bit[i]+=val;
i=i-(i&(-i));//from i to 0 index where sum will get added
}
}
//calculates sum from 1 to i
ll query(ll i){
i=n-i+1;
ll sum=0;
while(i<=n){
sum+=bit[i];
i=i+(i&(-i));//search further from where i has caused sum
}
return sum;
}
int main() {
ll m;
cin>>n;
for(int i=n;i>=1;i--){//indexing always from 1
cin>>m;
update(i,m);//build BIT
}
//queries
ll q,l,r,s;
cin>>q;
while(q--){
cin>>s;
if(s==1){
cin>>l>>r;
cout<<query(r)-query(l-1)<<endl;
}
else{
ll x;
cin>>x;n++;
update(n,x);
}
}
}
| true |
266c53ba50a195e44df96a68d5af9908c407eebe | C++ | Sevzera/aeds1-cefet | /jogoDasCaixas.cpp | UTF-8 | 3,669 | 3.234375 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
// Le o nome do arquivo
string nome;
cout << "Digite o nome do arquivo de entrada: ";
cin >> nome;
// Abre o arquivo e atribui todo seu conteudo a uma string
ifstream file(nome);
if (!file)
{
cout << "Arquivo inexistente.";
putchar('\n');
return 0;
}
string fullText;
for (string line; getline(file, line);)
{
fullText += line;
fullText += '\n';
}
if (fullText == "")
{
cout << "Arquivo vazio.";
putchar('\n');
return 0;
}
// Pega o numero de linhas da "escada" apresentado pelo arquivo e o converte em um numero inteiro
string rowsStr = "";
int i = 0;
do
{
rowsStr.push_back(fullText[i]);
i++;
} while (fullText[i] != '\n');
int rowsInt = stoi(rowsStr);
// int rowsInt = atoi(rowsStr.c_str());
if (rowsInt == 1)
{
cout << "Resposta: fileira 1, caixa 1.";
putchar('\n');
return 0;
}
else if (rowsInt == 0)
{
cout << "Resposta: fileira 0, caixa 0.";
putchar('\n');
return 0;
}
// Pega os numeros seguintes e coloca um em cada posicao de um vetor de inteiros
int *n = (int *)calloc(800, sizeof(int));
int k = 0;
int fullTextLength = fullText.length();
string currentNumber = "";
for (int j = i + 1; j < fullTextLength; j++)
{
if (fullText[j] != ' ' && fullText[j] != '\n')
{
currentNumber.push_back(fullText[j]);
}
else
{
n[k] = stoi(currentNumber);
// n[k] = atoi(currentNumber.c_str());
k++;
currentNumber.erase();
currentNumber.shrink_to_fit();
}
}
// Cria uma matriz de tamanho rowsInt x rowsInt preenchida com 0's
int **m = (int **)calloc(rowsInt, sizeof(int *));
for (int i = 0; i < rowsInt; i++)
{
m[i] = (int *)calloc(rowsInt, sizeof(int));
}
// Preenche a matriz com os numeros do vetor n de forma que componham uma "escada"
int j = 0;
int it = 1;
int l = 0;
for (int i = 0; i < rowsInt; i++)
{
for (j = 0; j < it; j++)
{
m[i][j] = n[l];
l++;
}
it++;
}
// Define as variaveis necessarias para armazenar a posicao e valor do ganhador
it = 1;
j = 0;
i = 0;
int currentValue = 0;
int rowValue = 0;
int winnerValue = 0;
int winnerRow = 0;
int winnerBox = 0;
// Trata a excecao da posicao [0][0] ser a ganhadora
winnerValue = m[i][j];
winnerRow = 1;
winnerBox = 1;
// Visita cada posicao relevante da matriz, somando todas as anteriores, e entao remove o valor das outras posicoes da mesma linha
for (i = 1; i < rowsInt; i++)
{
it++;
for (j = 0; j < it; j++)
{
rowValue = rowValue + m[i][j];
currentValue = currentValue + m[i][j];
// Compara o valor final da posicao analisada com o atual ganhador
if ((currentValue + m[i][j] - rowValue + m[0][0]) > winnerValue)
{
winnerValue = currentValue - rowValue + m[i][j] + m[0][0];
winnerRow = i + 1;
winnerBox = j + 1;
}
}
rowValue = 0;
}
free(m);
// cout << "Valor: " << winnerValue << endl;
cout << "Resposta: fileira " << winnerRow << ", caixa " << winnerBox << ".";
putchar('\n');
return 0;
}
| true |
b288562208086e71d0c8d899b9edde97115ef37a | C++ | bjornpostema/fluid-survival-tool | /src/model/GeometryHelper.cpp | UTF-8 | 10,605 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* GeometryHelper.cpp
*
* Created on: Mar 6, 2013
* Author: hamed
*/
#include "GeometryHelper.h"
namespace model {
Polygon* GeometryHelper::reform(Polygon* poly, Interval interval) {
return NULL;
}
RegionState GeometryHelper::getTimeAndDirection(DtrmEvent* dtrmRegion,Formula* formula, double& t, Direction& dir) {
/*
* \f$ x \geq c => f_0 - \beta*d + d*t \geq c \f$ in which f_0 is the level of fluid place at the moment of entering this region.
* and \beta is the time of entering this region. Therefore:
* if d = 0:
* if f_0 \geq c => entire region
* o.w. Nothing
* if d > 0
* t > (c-f_0)/d + \beta
* if d < 0
* t < (c-f_0)/d + \beta
*/
/* Checking if we have combination of formulas. if the discrete part holds it holds in all the region. and if not in no where.
* IMPORTANT: we assume and between discrete and continuous formulas.
*/
// std::cout << "formula->getType(): " << formula->getType() << std::endl;
if (formula->getType() == COMBI){
AtomDisFormula* disFormula = ((ADFormula*)formula)->disFormula;
if (dtrmRegion->postRegionMarking->tokens[disFormula->getPlaceIndex()] != disFormula->getN())
return NONE;
}
AtomContFormula* atomConProp;
if (formula->getType() == COMBI){
atomConProp = ((ADFormula*)formula)->contFormula;
}else
atomConProp = ((AtomContFormula*)formula);
double f0 = dtrmRegion->postRegionMarking->fluid0[model->places[atomConProp->getPlaceIndex()].idInMarking];
double d = dtrmRegion->postRegionMarking->fluidPlaceDeriv[model->places[atomConProp->getPlaceIndex()].idInMarking];
if (d == 0){
if (f0 >= atomConProp->getC())
return ENTIRE;
else
return NONE;
}else {
dir = (d > 0) ? UP : DOWN;
// std::cout << "atomConProp->getC(): " << atomConProp->getC() << "f0: " << f0 << "d: " << d << "dtrmRegion->time: " << dtrmRegion->time << std::endl;
t = (atomConProp->getC() - f0)/d + dtrmRegion->time;
}
if ((dir == UP && t > dtrmRegion->nextDtrmEvent->time) && (dir == DOWN && t < dtrmRegion->time))
return NONE;
else if ((dir == UP && (t <= dtrmRegion->time)) || (dir == DOWN && (t >= dtrmRegion->nextDtrmEvent->time)))
return ENTIRE;
else
return PART;
}
void GeometryHelper::drawPolygon(cv::Mat& im, Polygon* poly, const int scale, cv::Scalar color) {
for (unsigned int i = 0; i < poly->segments->size(); i++){
cv::Point p1(poly->segments->at(i)->p1.X * scale, poly->segments->at(i)->p1.Y * scale);
cv::Point p2(poly->segments->at(i)->p2.X * scale, poly->segments->at(i)->p2.Y * scale);
cv::line(im, p1, p2, color, 1);
}
}
void GeometryHelper::drawVerticalLine(cv::Mat& im, double t, Direction dir, const int scale, cv::Scalar color) {
cv::Point p1(t*scale, t*scale);
cv::Point p2(model->MaxTime*scale, t*scale);
if (dir == UP)
cv::line(im, p1, p2, color, 1, 4);
else
cv::line(im, p1, p2, color, 1);
}
GeometryHelper::~GeometryHelper() {
// TODO Auto-generated destructor stub
}
Polygon* GeometryHelper::createPolygon(Region* region, Formula* formula) {
// TODO: Currently I have assumed that the given formula is an atomic continuous property.
/* \f$ x = f_0 + f_1s \f$ when entering the region and \f$ t = \alpha s + \beta \f$ is the underlying segment,and \f$ d \f$ is the drift.
*
* if d != 0:
* the corresponding line for formula \f$ x \geq c\f$ is \f$ t = (\alpha -f_1/d)s + (\beta + c/d - f_0/d) \f$
* if \f$ d > 0 => t \geq as+b \f$ and if \f$ d < 0 => t \leq as+b \f$
*
* if d = 0 and \f$ f_1 \neq 0 \f$:
* if \f$ f_1 > 0 => s \geq (c-f_0)/f_1 \f$ and if \f$ f_1 <0 => s \leq (c-f_0)/f_1\f$
*
* if f_1 = 0:
* all the region if f_0 \geq c
* nothing o.w.
*
*/
if (formula->getType() == COMBI){
AtomDisFormula* disFormula = ((ADFormula*)formula)->disFormula;
if (region->marking->tokens[disFormula->getPlaceIndex()] != disFormula->getN())
return NULL;
}
AtomContFormula* atomConProp;
if (formula->getType() == COMBI){
atomConProp = ((ADFormula*)formula)->contFormula;
}else
atomConProp = ((AtomContFormula*)formula);
double f0 = region->marking->fluid0[model->places[atomConProp->getPlaceIndex()].idInMarking];
double f1 = region->marking->fluid1[model->places[atomConProp->getPlaceIndex()].idInMarking];
double d = region->marking->fluidPlaceDeriv[model->places[atomConProp->getPlaceIndex()].idInMarking];
// std:: cout << "f0: "<< f0 << " f1: " << f1 << " d: "<< d << std::endl;
Polygon* poly;
Line propLine;
if (IS_ZERO(d)){
if (!IS_ZERO(f1)){
propLine.X = (atomConProp->getC() - f0)/f1;
Direction upOrDown = (f1 > 0)?UP:DOWN;
poly = splitRegion(region, &propLine, upOrDown);
}
else if (f0 >= atomConProp->getC())
poly = regionToPoly(region);
else
poly = NULL;
} else{
double a = region->lowerBoundry->a - f1/d;
double b = region->lowerBoundry->b + (atomConProp->getC() - f0)/d;
propLine.a = a;
propLine.b = b;
Direction upOrDown = (d > 0)?UP:DOWN;
poly = splitRegion(region, &propLine, upOrDown);
}
return poly;
}
Polygon* GeometryHelper::splitRegion(Region* region, Line* line, Direction direction) {
Polygon* poly = new Polygon();
// region->print(std::cout);
for (unsigned int i = 0; i < region->eventSegments->size(); i++)
addToPolygon(poly, region->eventSegments->at(i)->timeSegment, line, direction);
addToPolygon(poly, region->leftBoundry, line, direction);
addToPolygon(poly, region->rightBoundry, line, direction);
addToPolygon(poly, region->lowerBoundry, line, direction);
Point p1, p2;
if (region->intersect(*line, p1, p2))
poly->segments->push_back(new Segment(p1, p2));
return poly;
}
Polygon* GeometryHelper::regionToPoly(Region* region) {
Polygon* poly = new Polygon();
for (unsigned int i = 0; i < region->eventSegments->size(); i++){
if (region->eventSegments->at(i)->timeSegment->p1 != region->eventSegments->at(i)->timeSegment->p2)
poly->segments->push_back(region->eventSegments->at(i)->timeSegment);
}
if (region->leftBoundry->p1 != region->leftBoundry->p2) poly->segments->push_back(region->leftBoundry);
if (region->rightBoundry->p1 != region->rightBoundry->p2) poly->segments->push_back(region->rightBoundry);
if (region->lowerBoundry->p1 != region->lowerBoundry->p2) poly->segments->push_back(region->lowerBoundry);
return poly;
}
void GeometryHelper::addToPolygon(Polygon* poly, Segment* seg, Line* line, Direction direction) {
Point intersection;
if (seg->intersect(*line, intersection)){
if ((direction == UP && line->isUp(seg->p1)) || (direction == DOWN && !line->isUp(seg->p1)) ){
if (intersection != seg->p1)
poly->segments->push_back(new Segment(seg->p1, intersection));
}
else
if (intersection != seg->p2)
poly->segments->push_back(new Segment(seg->p2, intersection));
}else if((direction == UP && line->isUp(seg->p1) && line->isUp(seg->p2)) || (direction == DOWN && !line->isUp(seg->p1) && !line->isUp(seg->p2)) ){
poly->segments->push_back(seg);
}
}
Polygon* GeometryHelper::cropPolygon(Polygon* poly, double t, Direction dir) {
if (poly == NULL || poly->segments->size() == 0) return NULL;
Polygon* newPoly = new Polygon();
Line* line = new Line(0, t);
Point p1, p2;
if (poly->intersect(line, p1, p2)){
for (unsigned int i = 0; i < poly->segments->size(); i++)
addToPolygon(newPoly, poly->segments->at(i), line, dir);
newPoly->segments->push_back(new Segment(p1, p2));
}else{
if ((dir == DOWN && !line->isUp(poly->segments->at(0)->p1)) || (dir == UP && line->isUp(poly->segments->at(0)->p1))){
for (unsigned int i = 0; i < poly->segments->size(); i++)
newPoly->segments->push_back(poly->segments->at(i));
}else
newPoly = NULL;
}
return newPoly;
}
bool GeometryHelper::isPolyContainPt(Polygon* poly, Point* p) {
for (unsigned int i = 0; i < poly->segments->size(); i++){
if (poly->segments->at(i)->p1 == *p || poly->segments->at(i)->p2 == *p)
return true;
}
return false;
}
IntervalSet* GeometryHelper::getIntersectionIntervals(Polygon* poly, Segment* segment) {
Point intPt1, intPt2;
int numIntersection = 0;
// std::cout << "---------------------------" << std::endl;
// poly->print();
for (unsigned int i = 0; i < poly->segments->size(); i++){
Point intPt;
IntersectionStatus inStatus = poly->segments->at(i)->intersect2(*segment, intPt);
if ( inStatus == ALL){
Interval i1(segment->p1.X, segment->p2.X);
Interval i2(poly->segments->at(i)->p1.X, poly->segments->at(i)->p2.X);
Interval res;
i1.intersect(i2, res);
IntervalSet* ret = new IntervalSet();
ret->intervals.push_back(res);
return ret;
} else if(inStatus == NO) continue;
if (numIntersection == 0) { intPt1 = intPt; numIntersection++;}
else if (numIntersection == 1 ) { intPt2 = intPt; numIntersection++;}
else break;
}
if (numIntersection < 2) return NULL; //No intersection
else {Interval I(intPt1.X, intPt2.X); IntervalSet* ret = new IntervalSet(); ret->intervals.push_back(I); return ret;}
}
IntervalSet* GeometryHelper::getIntersectionIntervals(Polygon* poly1, Polygon* poly2) {
Point intPt1, intPt2;
int numIntersection = 0;
IntervalSet* ret = new IntervalSet();
for (unsigned int i = 0; i < poly1->segments->size(); i++){
for (unsigned int j = 0; j < poly2->segments->size(); j++){
Point intPt;
IntersectionStatus inStatus = poly1->segments->at(i)->intersect2(*poly2->segments->at(j), intPt);
if (inStatus == ALL){
Interval i1(poly1->segments->at(i)->p1.X, poly1->segments->at(i)->p2.X);
Interval i2(poly2->segments->at(j)->p1.X, poly2->segments->at(j)->p2.X);
Interval res;
i1.intersect(i2, res);
ret->intervals.push_back(res);
break;
}
if (inStatus == POINT && numIntersection == 0) {
intPt1 = intPt;
numIntersection++;
}
else if (inStatus == POINT && numIntersection == 1 ) {
intPt2 = intPt;
numIntersection++;
}
}
if (numIntersection ==2){
Interval I(intPt1.X, intPt2.X);
ret->intervals.push_back(I);
}
}
// std::cout << "ret: ";
// ret->print();
ret->removeRedundency();
return ret;
}
}
| true |
5730dd46c28c1d65a1a8b21492c7e8efc6210fe2 | C++ | MughalUsama/Data-Structures-and-Algorithms | /Lab 4/Project2/Project2/main.cpp | UTF-8 | 1,227 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include "myStack.h"
#include "myStack.cpp"
Stack<int> sort(const Stack<int>& s)
{
Stack<int> newStack;
int * tempData = new int[s.getNoOfElements()];
newStack = s;
for (int i = 0; i < s.getNoOfElements(); i++)
{
tempData[i] = newStack.top();
newStack.pop();
}
for (int i = 0; i < s.getNoOfElements(); i++)
{
for (int i = 0; i < s.getNoOfElements(); i++)
{
int temp, smallest = i;
for (int j = i; j < s.getNoOfElements(); j++)
{
if (tempData[smallest] > tempData[j])
{
smallest = j;
}
}
temp = tempData[i];
tempData[i] = tempData[smallest];
tempData[smallest] = temp;
}
}
for (int i = 0; i < s.getNoOfElements(); i++)
{
newStack.push(tempData[i]);
}
return newStack;
}
int getPermutation()
{
Stack<int>s;
int noOfElements,num;
cin >> noOfElements;
for (int i = 0; i < noOfElements; i++)
{
cin >> num;
s.push(num);
}
s=sort(s);
int pairs = noOfElements-1;
for (int i = 0; i < noOfElements-1; i++)
{
num = s.top();
s.pop();
if (num==s.top())
{
pairs--;
}
}
return pairs;
}
int main()
{
char n1[7] = "123000";
char n2[5] = "";
cout << getPermutation();
system("pause");
cout << "\n";
return 0;
} | true |
0d681e4b1ba1306e9d860427ad2df4a08e884300 | C++ | jrouwe/JoltPhysics | /Jolt/Geometry/Ellipse.h | UTF-8 | 2,569 | 3.15625 | 3 | [
"MIT"
] | permissive | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Math/Float2.h>
JPH_NAMESPACE_BEGIN
/// Ellipse centered around the origin
/// @see https://en.wikipedia.org/wiki/Ellipse
class Ellipse
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Construct ellipse with radius A along the X-axis and B along the Y-axis
Ellipse(float inA, float inB) : mA(inA), mB(inB) { JPH_ASSERT(inA > 0.0f); JPH_ASSERT(inB > 0.0f); }
/// Check if inPoint is inside the ellipsse
bool IsInside(const Float2 &inPoint) const
{
return Square(inPoint.x / mA) + Square(inPoint.y / mB) <= 1.0f;
}
/// Get the closest point on the ellipse to inPoint
/// Assumes inPoint is outside the ellipse
/// @see Rotation Joint Limits in Quaterion Space by Gino van den Bergen, section 10.1 in Game Engine Gems 3.
Float2 GetClosestPoint(const Float2 &inPoint) const
{
float a_sq = Square(mA);
float b_sq = Square(mB);
// Equation of ellipse: f(x, y) = (x/a)^2 + (y/b)^2 - 1 = 0 [1]
// Normal on surface: (df/dx, df/dy) = (2 x / a^2, 2 y / b^2)
// Closest point (x', y') on ellipse to point (x, y): (x', y') + t (x / a^2, y / b^2) = (x, y)
// <=> (x', y') = (a^2 x / (t + a^2), b^2 y / (t + b^2))
// Requiring point to be on ellipse (substituting into [1]): g(t) = (a x / (t + a^2))^2 + (b y / (t + b^2))^2 - 1 = 0
// Newton raphson iteration, starting at t = 0
float t = 0.0f;
for (;;)
{
// Calculate g(t)
float t_plus_a_sq = t + a_sq;
float t_plus_b_sq = t + b_sq;
float gt = Square(mA * inPoint.x / t_plus_a_sq) + Square(mB * inPoint.y / t_plus_b_sq) - 1.0f;
// Check if g(t) it is close enough to zero
if (abs(gt) < 1.0e-6f)
return Float2(a_sq * inPoint.x / t_plus_a_sq, b_sq * inPoint.y / t_plus_b_sq);
// Get derivative dg/dt = g'(t) = -2 (b^2 y^2 / (t + b^2)^3 + a^2 x^2 / (t + a^2)^3)
float gt_accent = -2.0f *
(a_sq * Square(inPoint.x) / Cubed(t_plus_a_sq)
+ b_sq * Square(inPoint.y) / Cubed(t_plus_b_sq));
// Calculate t for next iteration: tn+1 = tn - g(t) / g'(t)
float tn = t - gt / gt_accent;
t = tn;
}
}
/// Get normal at point inPoint (non-normalized vector)
Float2 GetNormal(const Float2 &inPoint) const
{
// Calculated by [d/dx f(x, y), d/dy f(x, y)], where f(x, y) is the ellipse equation from above
return Float2(inPoint.x / Square(mA), inPoint.y / Square(mB));
}
private:
float mA; ///< Radius along X-axis
float mB; ///< Radius along Y-axis
};
JPH_NAMESPACE_END
| true |
8542c9805ca7fc4beecdc6a6219ce40a65f9f6f3 | C++ | ghulamghousdev/Data-Structures-CPP | /cQueue/cQueue/cStack.cpp | UTF-8 | 2,397 | 4.125 | 4 | [] | no_license | /*
Implementation file for cStack class
*/
#include "cStack.h"
#include <iostream>
using namespace std;
/*
Default constructor of STACK class to make top data member of STACK class NULL
*/
cStack::cStack() :top(NULL) {}
/*
Parameterized Constructor
*/
cStack::cStack(cNode *&ptr) : top(ptr) {
top->nextNode = NULL;
ptr = NULL;
}
/*
Function to check if Stack is not empty
*/
bool cStack::isNotEmpty() const {
if (top != NULL) { //if STACK is not empty returning true
return true;
}
else {//if STACK is empty returning false
return false;
}
}
/*
Function to check if stack is empty
*/
bool cStack::isEmpty() const {
if (top == NULL) {//if STACK is empty returning true
return true;
}
else {//if STACK is not empty returning false
return false;
}
}
/*
Cascaded push function which addes a new node to Stack at top
*/
cStack & cStack::push(cNode *&ptr) {
ptr->nextNode = top;
top = ptr;
ptr = NULL;
return *this;
}
/*
Cascaded pop function which removes the lastest node from Stack
*/
cNode * cStack::pop() {
cNode *ptr;
ptr = top;
top = top->nextNode;
ptr->nextNode = NULL;
return ptr;
}
/*
Function to print all the elements present in the Stack
*/
void cStack::print() const {
if (isEmpty()) { //Checking if the STACK is empty
cout << "There is no element." << endl;
}
else {
cout << "All the elements are: ";
cNode *ptr; //Declaring a runner pointer to move through
ptr = top;
while (ptr) { //Moving through the STACK and printing the data of each node present in the STACK
ptr->print();
ptr = ptr->nextNode;
}
cout << "\n\n";
}
}
/*
Self Defined Copy Constructor to avoid shallow copy
*/
cStack::cStack(const cStack & src) {
this->top = src.top;
if (src.top) {
cNode *sPtr, *dPtr;
dPtr = top = new cNode(*src.top);
sPtr = src.top->nextNode;
while (sPtr) {
dPtr->nextNode = new cNode(*src.top);
sPtr = sPtr->nextNode;
dPtr = dPtr->nextNode;
}
}
}
/*
Assignment Operator overloaded
*/
cStack & cStack::operator = (const cStack & rObj) {
if (this == &rObj) {
return *this;
}if (true) {
cStack temp;
temp.top = top;
}
if (true) {
cStack temp;
temp = rObj;
top = temp.top;
temp.top = NULL;
return *this;
}
}
//Destructor to return the heap memory used during the program
cStack::~cStack() {
cNode *ptr = top;
while (ptr) {
ptr = ptr->nextNode;
delete top;
top = ptr;
}
}
#pragma once | true |
56a3ef838fde10ce728f664448e9659ab8245640 | C++ | Ric-27/TETRIC | /logic.cpp | UTF-8 | 9,733 | 2.546875 | 3 | [] | no_license | #include "logic.hpp"
#include <iostream>
Logic::Logic(int argX, int argY){
coorZero.setX(argX/2 - 1);
coorZero.setY(amount_of_pixels - 1);
colorMatrix.resize(argX * argY);
logicMatrix.resize(argX * argY);
nextMatrix.resize(6*4);
logicX = argX;
logicY = argY;
score = 0;
level = 0;
rows = 0;
localRows = 0;
slowness = initial_speed;
special_counter = 0;
hardDrop = false;
status = 0;
Tetromino newPiece(coorZero,0);
nextPiece = newPiece;
newTetromino();
}
vector<string> Logic::getMatrix() const{
return colorMatrix;
}
vector<string> Logic::getNext(){
return nextMatrix;
}
int Logic::getScore(){
return score;
}
int Logic::getLevel(){
return level;
}
int Logic::getRows(){
return rows;
}
int Logic::GetSlowness(){
return slowness;
}
void Logic::setStatus(int arg){
status = arg;
}
int Logic::getStatus(){
return status;
}
void Logic::newTetromino(){
special_counter++;
activePiece = nextPiece;
savedPos = activePiece.getPixels();
if (special_counter > count_spawn_special)
{
special_counter = 0;
Tetromino newPiece(coorZero,(-2));
nextPiece = newPiece;
} else {
Tetromino newPiece(coorZero,nextPiece.GetId());
nextPiece = newPiece;
}
fillNextMatrix();
updateMatrix();
}
void Logic::fillNextMatrix(){
vector<Pixel> positions = nextPiece.getPixels();
Pixel ref = positions[0];
Pixel newRef;
newRef.setX(2);
newRef.setY(2);
for (unsigned i = 0; i < nextMatrix.size(); i++)
{
nextMatrix[i] = "";
}
for (unsigned i = 0; i < positions.size(); i++)
{
positions[i].setX(positions[i].getX() - ref.getX() + newRef.getX());
positions[i].setY(positions[i].getY() - ref.getY() + newRef.getY());
nextMatrix[positions[i].getX() + 6 * positions[i].getY()] = nextPiece.getColor();
}
}
void Logic::updateMatrix(){
Overlay();
vector<Pixel> positions = activePiece.getPixels();
if(!locked)
{
for (unsigned i = 0; i < prev_overlay.size(); i++)
{
colorMatrix[prev_overlay[i].getX() + logicX * prev_overlay[i].getY()] = "";
}
}
for (unsigned i = 0; i < curr_overlay.size(); i++)
{
colorMatrix[curr_overlay[i].getX() + logicX * curr_overlay[i].getY()] = overlay_color;
}
for (unsigned i = 0; i < savedPos.size(); i++)
{
colorMatrix[savedPos[i].getX() + logicX * savedPos[i].getY()] = "";
}
for (unsigned i = 0; i < positions.size(); i++)
{
colorMatrix[positions[i].getX() + logicX * positions[i].getY()] = activePiece.getColor();
}
}
void Logic::moveTetromino(char keycode){
int modX = 0;
int modY = 0;
bool invalidMove = false;
locked = false;
switch (keycode)
{
case 'd':
modY = 1;
break;
case 'l':
modX = -1;
break;
case 'r':
modX = 1;
break;
}
savedPos = activePiece.getPixels();
vector<Pixel> newPos = savedPos;
for (unsigned i = 0; i < newPos.size(); i++)
{
newPos[i].modX(modX);
newPos[i].modY(modY);
}
for (unsigned i = 0; i < newPos.size(); i++)
{
if (newPos[i].getX() >= logicX || newPos[i].getX() < 0 || newPos[i].getY() >= logicY || logicMatrix[newPos[i].getX() + logicX * newPos[i].getY()] == true) //preventing side moves
{
invalidMove = true;
if(keycode == 'd')
{
locked = true;
}
}
}
if (invalidMove == true || locked == true)
{
activePiece.setPixels(savedPos);
if (locked == true)
{
hardDrop = false;
for (unsigned i = 0; i < savedPos.size(); i++)
{
logicMatrix[savedPos[i].getX() + logicX * savedPos[i].getY()] = true;
}
updateMatrix();
CheckGameOver();
deleteRow();
newTetromino();
}
} else {
activePiece.setPixels(newPos);
}
updateMatrix();
}
void Logic::rotateTetromino(){
locked = false;
int biggestYRef = -1;
int biggestXRef = -1;
int biggestY = -1;
int biggestX = -1;
savedPos = activePiece.getPixels();
Pixel refPixel = savedPos[0];
vector<Pixel> newPos = savedPos;
bool invalidMove;
bool topOut = false;
for (unsigned i = 0; i < newPos.size(); i++) //correction
{
biggestYRef = (newPos[i].getY() > biggestYRef) ? newPos[i].getY() : biggestYRef;
biggestXRef = (newPos[i].getX() > biggestXRef ) ? newPos[i].getX() : biggestXRef;
}
for (unsigned i = 0; i < newPos.size(); i++)
{
newPos[i] = newPos[i] - refPixel;
newPos[i].Rotate();
newPos[i] = newPos[i] + refPixel;
}
for (unsigned i = 0; i < newPos.size(); i++) //correction
{
biggestY = (newPos[i].getY() > biggestY) ? newPos[i].getY() : biggestY;
biggestX = (newPos[i].getX() > biggestX) ? newPos[i].getX() : biggestX;
}
int modY = biggestYRef - biggestY;
int modX = biggestXRef - biggestX;
for (unsigned i = 0; i < newPos.size(); i++)
{
newPos[i].modX(modX);
newPos[i].modY(modY);
}
int correction = 1;
do {
invalidMove = false;
for (unsigned i = 0; i < newPos.size(); i++)
{
if (newPos[i].getX() < 0)
{
invalidMove = true;
break;
}
}
if(invalidMove)
{
for (unsigned i = 0; i < newPos.size(); i++)
{
newPos[i].modX(correction);
}
}
}
while(invalidMove);
invalidMove = false;
for (unsigned i = 0; i < newPos.size(); i++)
{
if (logicMatrix[newPos[i].getX() + logicX * newPos[i].getY()] == true) //deleting another piece
{
invalidMove = true;
break;
}
}
if (invalidMove || topOut)
{
activePiece.setPixels(savedPos);
} else {
activePiece.setPixels(newPos);
}
updateMatrix();
}
void Logic::deleteRow(){
vector<int> rowsToCheck, rowsToDelete;
bool canBeDeleted;
for (unsigned i = 0; i < savedPos.size(); i++)
{
if ((find(rowsToCheck.begin(),rowsToCheck.end(),savedPos[i].getY())) == rowsToCheck.end())
{
rowsToCheck.insert(rowsToCheck.end(),savedPos[i].getY());
}
}
for (unsigned j = 0; j < rowsToCheck.size(); j++)
{
int jj = rowsToCheck[j];
canBeDeleted = true;
for (int i = 0; i < logicX; i++)
{
if (logicMatrix[i + logicX * jj] == 0)
{
canBeDeleted = false;
break;
}
}
if (canBeDeleted)
{
rowsToDelete.insert(rowsToDelete.end(),rowsToCheck[j]);
}
}
if (rowsToDelete.size() > 0)
{
rows += rowsToDelete.size();
localRows += rowsToDelete.size();
CalcScore(rowsToDelete.size());
CalcLevel();
sort(rowsToDelete.begin(),rowsToDelete.end());
for (unsigned j = 0; j < rowsToDelete.size(); j++)
{
for (int k = rowsToDelete[j]; k > 0; k--)
{
for (int i = 0; i < logicX; i++)
{
colorMatrix[i + logicX * k] = colorMatrix[i + logicX * (k - 1)];
logicMatrix[i + logicX * k] = logicMatrix[i + logicX * (k - 1)];
}
}
}
}
}
void Logic::CalcLevel(){
while (localRows >= rows_to_level)
{
level++;
CalcSlowness();
localRows -= rows_to_level;
}
}
void Logic::CalcSlowness(){
slowness = (slowness > min_speed) ? slowness - step_speed : min_speed;
}
void Logic::CalcScore(int argRows){
switch (argRows)
{
case 1:
score += 40*(level+1);
break;
case 2:
score += 100*(level+1);
break;
case 3:
score += 300*(level+1);
break;
case 4:
score += 1200*(level+1);
break;
}
}
void Logic::CheckGameOver(){
for (int i = 0; i < logicX; i++)
{
if (logicMatrix[i + logicX * (logicY - height - 1)] == 1)
{
status = 4;
break;
}
}
}
void Logic::CleanUp(){
for (int i = 0; i < logicX * logicY; i++)
{
colorMatrix[i] = "";
logicMatrix[i] = false;
}
score = 0;
level = 0;
rows = 0;
localRows = 0;
slowness = initial_speed;
status = 0;
Tetromino newPiece(coorZero,0);
nextPiece = newPiece;
newTetromino();
}
void Logic::Overlay(){
prev_overlay = curr_overlay;
curr_overlay = activePiece.getPixels();
bool active = true;
while (active)
{
for (unsigned i = 0; i < curr_overlay.size(); i++)
{
curr_overlay[i].modY(1);
}
for (unsigned i = 0; i < curr_overlay.size(); i++)
{
if (curr_overlay[i].getY() >= logicY || logicMatrix[curr_overlay[i].getX() + logicX * curr_overlay[i].getY()] == true)
{
active = false;
break;
}
}
}
for (unsigned i = 0; i < curr_overlay.size(); i++)
{
curr_overlay[i].modY(-1);
}
}
void Logic::ActivateHardDrop(){
hardDrop = true;
while (hardDrop)
{
moveTetromino('d');
}
}
Logic::~Logic(){
}
| true |
44453872d1d04f92538f4330599ffe3c308e391c | C++ | mochammadfawwaz/Program-Kreativitas-Mahasiswa | /0.3_-_Sensor_PH/0.3_-_Sensor_PH.ino | UTF-8 | 712 | 2.515625 | 3 | [] | no_license | const int ph_Pin = A0;
float Po = 0;
float pH_step;
int nilai_analog_PH;
double TeganganPH;
// kalibrasi
float PH4 = 0.85;
float PH7 = 1.78;
float PH9 = 2.67;
void setup() {
// put your setup code here, to run once:
pinMode(ph_Pin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
nilai_analog_PH = analogRead(ph_Pin);
Serial.print("Nilai ADC pH: ");
Serial.println(nilai_analog_PH);
TeganganPH = 5 / 1024.0 * nilai_analog_PH;
Serial.print("Tegangan: ");
Serial.println(TeganganPH, 3);
pH_step = (PH9 - PH7 ) / 3;
Po = 7.00 + ((PH7 - TeganganPH) / pH_step) + 5;
Serial.print("Nilai PH cairan: ");
Serial.println(Po,2);
delay(500);
}
| true |
ec00ced64e6d9ebfee27a1832964fb80c50f324e | C++ | aoibird/pc | /cpc/exercise3-5_droppingtests.cpp | UTF-8 | 979 | 2.53125 | 3 | [
"MIT"
] | permissive | // POJ 2976
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const double ERR = 0.00001;
const int MAXN = 1000+10;
PII T[MAXN];
double S[MAXN];
int N, K;
bool can(double x)
{
for (int i = 0; i < N; i++) S[i] = T[i].first - x * T[i].second;
sort(S, S+N);
double sum = 0;
for (int i = 0; i < K; i++) sum += S[N-i-1];
return sum >= 0;
}
int main()
{
while (scanf("%d%d", &N, &K) == 2) {
if (N == 0 && K == 0) break;
for (int i = 0; i < N; i++) scanf("%d", &T[i].first);
for (int i = 0; i < N; i++) scanf("%d", &T[i].second);
K = N - K;
double lb = 0, ub = 1000;
while ((ub-lb) > ERR) {
double mid = (lb+ub)/2;
if (can(mid)) { lb = mid; }
else { ub = mid; }
}
printf("%.0lf\n", (100 * lb));
}
}
| true |
aa3a308b16abafc25a095ca512fe17314a0b721a | C++ | aureus5/CPPproject | /AirplaneSensorCPPproject/Signal.h | UTF-8 | 383 | 2.890625 | 3 | [] | no_license | #ifndef PROJECT2_SIGNAL_H
#define PROJECT2_SIGNAL_H
#include "Time.h"
namespace Project2
{
class Signal
{
public:
Signal(double valueOffset, Time &timeOffset);
virtual double getVoltageAtTime(Time &t) const=0;
protected:
double getVoltageOffset() const;
Time getTimeOffset() const;
private:
double voltageOffset;
Time timeOffset;
};
}
#endif | true |
37641abe1787e1d3403a83112a5b462eb508c637 | C++ | irina-suslova/Lab_3 | /Lab_3/complex.h | UTF-8 | 2,756 | 3.515625 | 4 | [] | no_license | #ifndef COMPLEX_H
#define COMPLEX_H
#include<iostream>
#include<cmath>
class Complex {
private:
double Re;
double Im;
public:
Complex(double Re = 0.0, double Im = 0.0) {
this->Re = Re;
this->Im = Im;
}
Complex(const Complex& z) {
this->Re = z.Re;
this->Im = z.Im;
}
void Set(double Re, double Im) {
this->Re = Re;
this->Im = Im;
}
double GetRe() {
return Re;
}
double GetIm() {
return Im;
}
float abs() {
return sqrt(Re*Re + Im*Im);
}
Complex& operator+(const Complex& z) {
Complex *r = new Complex(this->Re, this->Im);
r->Re += z.Re;
r->Im += z.Im;
return *r;
}
Complex& operator*(const Complex& z) {
// (a + b i)(c + d i) = ac + ad i + bc i - bd
Complex *r = new Complex;
r->Re = this->Re * z.Re - this->Im * z.Im;
r->Im = this->Im * z.Re + this->Re * z.Im;
return *r;
}
Complex& operator*(const int& a) {
Complex *r = new Complex;
r->Re = this->Re * a;
r->Im = this->Im * a;
return *r;
}
Complex& operator/(const Complex& z) {
try {
if (z.Re == 0 && z.Im == 0)
throw "Division by zero";
Complex *r = new Complex;
Complex a(z.Re, -z.Im);
*r = *this * a;
r->Re /= (z.Re * z.Re + z.Im * z.Im);
r->Im /= (z.Re * z.Re + z.Im * z.Im);
return *r;
}
catch (const char *error) {
std::cout << error << std::endl;
}
return *this;
}
bool operator!=(const Complex &z) {
if (this->Re == z.Re && this->Im == z.Im)
return false;
return true;
}
bool operator==(const Complex &z) {
if (this->Re == z.Re && this->Im == z.Im)
return true;
return false;
}
bool operator<(const Complex &z) {
if (Re*Re + Im*Im < z.Re*z.Re + z.Im*z.Im)
return true;
return false;
}
bool operator>(const Complex &z) {
if (Re*Re + Im*Im >= z.Re*z.Re + z.Im*z.Im)
return true;
return false;
}
friend std::ostream& operator<< (std::ostream &out, const Complex &z) {
out << "(" << z.Re << "+" << z.Im << "i)";
return out;
}
~Complex() = default;
};
Complex COMPLEX_INF {10e8, 10e8};
Complex randomComplex() {
int max = 10e8;
Complex* z = new Complex;
double re = rand() % max;
double im = rand() % max;
z->Set(re, im);
return *z;
}
std::string to_string(Complex &z) {
return "(" + std::to_string(z.GetRe()) + "+" + std::to_string(z.GetIm()) + "i)";
}
#endif // COMPLEX_H
| true |
8d1811d47076a229e0edc279178e4ed806899d1b | C++ | yosoufe/CarND-PID-Control-Project | /src/PID.cpp | UTF-8 | 1,932 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "PID.h"
using namespace std;
/*
* TODO: Complete the PID class.
*/
PID::PID() {
#ifdef WITH_GNUPLOT
error_file = std::fopen("error","w");
std::fclose(error_file);
control_terms_file = std::fopen("control_terms","w");
std::fclose(control_terms_file);
gp_ = popen("gnuplot -persist" , "w");
#endif
}
PID::~PID() {}
void PID::Init(double Kp, double Ki, double Kd,int d_buf_size) {
this->Kp = Kp;
this->Ki = Ki;
this->Kd = Kd;
p_error = 0;
i_error = 0;
d_error = 0;
pre_error = -0.7598;
d_bufer_size_ = d_buf_size;
d_buffer = new double[d_bufer_size_];
d_sum = 0;
d_idx = 0;
}
void PID::UpdateError(double error) {
p_error = error;
i_error += error;
d_error = error - pre_error;
if (isFirstUpdate){
d_error = 0;
isFirstUpdate = false;
}
d_sum -= d_buffer[d_idx];
d_buffer[d_idx]=d_error;
d_sum += d_buffer[d_idx];
d_error = d_sum/d_bufer_size_;
d_idx++;
if (d_idx>= d_bufer_size_)
d_idx = 0;
pre_error = error;
}
double PID::getControlCommand() {
control = Kp * p_error + Ki * i_error + Kd * d_error;
#ifdef WITH_GNUPLOT
updateGraphFromFile();
#endif
return control;
}
#ifdef WITH_GNUPLOT
void PID::updateGraphFromFile(){
error_file = std::fopen("error","a");
if(error_file != NULL){
std::string toWrite = std::to_string(p_error) + '\n'; // error
std::fwrite(toWrite.c_str(),1,toWrite.length(),error_file);
std::fclose(error_file);
}
control_terms_file = std::fopen("control_terms","a");
if(control_terms_file != NULL){
std::string toWrite = std::to_string(control) + ' ' + // control
std::to_string(p_error * Kp) + ' ' + // p_term
std::to_string(i_error * Ki) + ' ' + // i_term
std::to_string(d_error * Kd) + '\n'; // d_term
std::fwrite(toWrite.c_str(),1,toWrite.length(),control_terms_file);
std::fclose(control_terms_file);
}
if (gp_!=NULL){
fprintf(gp_ , "call '../plotScript.gp'\n");
std::fflush(gp_);
}
}
#endif
| true |
9f5d48da23c166382fc40507ca6597b6c1071c89 | C++ | EmonZaman/UVA | /465 - Overflow.cpp | UTF-8 | 579 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
double a,b;
char c;
while(1)
{
char s[2000000];
gets(s);
puts(s);
sscanf(s,"%lf %c %lf", &a, &c, &b);
// cout<<a<<" "<<c<<" "<<b<<endl;
if(a>2147483647)
puts("first number too big");
if(b>2147483647)
puts("second number too big");
if(c=='+' && a+b>2147483647)
puts("result too big");
if(c=='*' && a*b>2147483647)
puts("result too big");
}
}
| true |
b987377eeec00fb5a150fb54030669bafc16c507 | C++ | savannadodson/3013-Algorithms-Dodson | /Assignments/P02/main.cpp | UTF-8 | 10,053 | 3.296875 | 3 | [] | no_license | /*****************************************************************************
*
* GOT HELP FROM A TUTOR
*
* Author: Savanna Dodson
* Email: smdodson1105@my.msutexas.edu
* Label: P02
* Title: Processing in Linear Time
* Course: 3013 algorithims
* Semester: Spring 2021
*
* Description:
* Read in a file of dictionary words and create a linked list of them. * Time how long it takes to do this. Then getch in character and pull up
* the first 10 search results. Time how long it takes to do this too.
*
* Usage:
* Type in a word to search for. Use backspace if neccessary. Type a
* capital z to quit the program.
*
* Files: main.cpp
* dictionary.txt
* getch.hpp
* termcolor.hpp
* timer.hpp
*****************************************************************************/
#include "mygetch.hpp"
#include "termcolor.hpp"
#include "timer.hpp"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/**
* Description:
* Originally wrote this to count size of input file so
* I could allocate enough memory for an array of strings
* but I went with a vector below. But I'm keeping it and
* using it anyway!
* Params:
* string file_name - file to get the line count
*
* Returns:
* int - line count
*/
// int CountLines(string file_name) {
// ifstream inFile(file_name);
// return count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
// }
/**
* Struct wordNode
*
* Description:
* creates a object that holds a word
*
* Public Methods:
* wordNode()
*
* Private Methods:
* None
*
*
* Usage:
*
* object that holds a word
*/
struct wordNode
{
string word;
//create pointer
wordNode* next;
wordNode()
{
word = "";
next = NULL;
}
};
class wordNodes
{
private:
wordNode* head;
wordNode* tail;
//number of words in the list
int numWords;
public:
//constructor wordNode
wordNodes()
{
head = NULL;
tail = NULL;
numWords = 0;
}
/**
* Public: numWords
*
* Description:
* gets the number of words in the linked * lists
*
* Params:
* None
*
* Returns:
* int num: the number/size of words in * * the list
*
*
*
*/
//getter
int getnumWords()
{
return numWords;
}
/**
* Public: addWord
*
* Description:
* Adds a word onto the linked list of
* nodes
*
* Params:
* wordNode* : pointer to the word/object
*
* Returns:
* None
*
*
*/
void addWord(wordNode* word)
{
//if head has nothing in it
if(head == NULL)
{
head = tail = word;
}
else
{
//if head does have something/word in it
//point the new word to the next position
tail -> next = word;
tail = word;
}
//increment the list of words
numWords++;
}
/**
* Public: findWords
*
* Description:
* finds the words in the dictionary input * that match whats typed and add to the * linked list
*
* Params:
* string substring : letter that is read * in
*
* Returns:
* vector<string> matches : vector of the * matches found from the input
*
*
*
*/
vector<string> findWords(string substring)
{
//holds the matches that are found from the //input
vector<string> matches;
wordNode* curr = head;
//size of word
int length;
//add words to linked list until no more //matches
while(curr != NULL)
{
string temp = " ";
temp = curr -> word;
length = substring.length();
if(temp.substr(0,length)==substring)
{
matches.push_back(temp);
}
curr = curr->next;
}
return matches;
}
/**
* Public: Print
*
* Description:
* prints the linked list of the
* words/matches
* Params:
* None
*
* Returns:
* None
*
*/
void Print()
{
wordNode* curr = head;
//prints words out until the end of the list
while(curr != NULL)
{
cout << curr -> word << endl;
curr = curr -> next;
}
}
};
/**
* Description:
* Loads a file of strings (words, names, whatever) reading them in
* with one word per line. So words must be delimited by newlines '\n'
* Params:
* string file_name - file to get the line count
*
* Returns:
* int - line count
*/
// vector<string> LoadAnimals(string file_name) {
// ifstream fin; // file to get animal names
// int count = (CountLines(file_name) + 1); // get size of input file
// vector<string> array(count); // allocate vector of correct size
// fin.open("animal_names.txt"); // open file for reading
// // knowing the size of the file lets us treat
// // it like an array without using .push_back(value)
// for (int i = 0; i < count; i++) {
// fin >> array[i]; // read in animals
// for (auto &c : array[i]) { // c++ 11 style loop
// c = tolower(c); // lowercase the animal name
// }
// }
// return array;
// }
/**
* Description:
* Finds partial matches in an array of strings and returns them. It
* doesn't matter where in the string the match is.
* Params:
* vector<string> array - array to search
* string substring - substring to search for in each word
*
* Returns:
* vector<string> - holding all the matches to substring
*/
// vector<string> FindAnimals(vector<string> array, string substring) {
// vector<string> matches; // to hold any matches
// size_t found; // size_t is an integer position of
// // found item. -1 if its not found.
// for (int i = 0; i < array.size(); i++) { // loop through array
// found = array[i].find(substring); // check for substr match
// if (found != string::npos) { // if found >= 0 (its found then)
// matches.push_back(array[i]); // add to matches
// }
// }
// return matches;
// }
int main()
{
//opening the input file
ifstream infile;
infile.open("dictionary.txt");
wordNodes list;
int numberWords;
char k; // holder for character being typed
string word = ""; // var to concatenate letters to
vector<string> LoadDictionary; // array of animal names
vector<string> matches; // any matches found in vector of animals
vector<string> FirstMatches(10);
// ofstream fout("temp.txt");
Timer T; // create a timer
Timer secondTime; //timer to match words
T.Start(); // start it
//read the words from input to the
//end of the input
while(!infile.eof())
{
string words;
infile >> words;
LoadDictionary.push_back(words);
}
//creating the linked list of the words
for(int i = 0; i < LoadDictionary.size(); i++)
{
wordNode* temp = new wordNode;
string holdWord = LoadDictionary[i];
temp -> word = holdWord;
list.addWord(temp);
}
T.End(); // end the current timer
// print out how long it took to load the animals file
cout << T.Seconds() << " seconds to read in and print json" << endl;
cout << T.MilliSeconds() << " milli to read in and print json" << endl;
cout << "Type keys and watch what happens. Type capital Z to quit." << endl;
// While capital Z is not typed keep looping
while ((k = getch()) != 'Z')
{
cout << termcolor::magenta << "Substring typed: " << termcolor::reset;
// Tests for a backspace and if pressed deletes
// last letter from "word".
if ((int)k == 127)
{
if (word.size() > 0)
{
word = word.substr(0, word.size() - 1);
}
} else
{
// Make sure a letter was pressed and only letter
if (!isalpha(k))
{
cout << "Letters only!" << endl;
continue;
}
// We know its a letter, lets make sure its lowercase.
// Any letter with ascii value < 97 is capital so we
// lower it.
if ((int)k < 97)
{
k -= 32;
}
word += k; // append char to word
}
//start the second timer
secondTime.Start();
// Find any words in the array that partially match
// our substr word
matches = list.findWords(word);
secondTime.End();
//end of the second timer
numberWords = matches.size();
if ((int)k != 32)
{
//if k is not a space print it
//make the text colorful
cout << termcolor::blue << termcolor::blue << word << endl << termcolor::reset;
cout << numberWords << " words found in " << secondTime.Seconds() << " seconds" << '\n';
// This prints out all found matches
//prints first 10 matches found
if(matches.size() > 10)
{
for(int i = 0; i < 10; i++)
{
cout << termcolor::bright_red;
//put into an array
FirstMatches[i] = matches[i];
//print out the array
cout << FirstMatches[i] << " ";
cout << termcolor::reset;
}
}
else
{
for(int i = 0; i < numberWords; i++)
{
cout << termcolor::bright_red;
//put into an array
FirstMatches[i] = matches[i];
//print out the array
cout << FirstMatches[i] << " ";
cout << termcolor::reset;
}
}
cout << '\n' << '\n';
}
}
return 0;
}
| true |
9f9305849a05d57898491455833266caba333d5f | C++ | EthanCYQ/OJ | /hdu2141.cpp | GB18030 | 1,452 | 2.96875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[505], b[505], c[505];
int value[505*505];
int l, m, n, s, index;
int cnt=0;
bool c_binary_search(int v)
{
int l=0, r=index-1;
while(l <= r)
{
int m = (l+r)/2;
if(value[m]<v)
l = m + 1;
else if(value[m]>v)
r = m - 1;
else
return true;
}
return false;
}
int main()
{
while(scanf("%d%d%d", &l,&m,&n)!=EOF)
{
cnt++;
for(int i=0;i<l;i++)
scanf("%d",&a[i]);
for(int i=0;i<m;i++)
scanf("%d",&b[i]);
for(int i=0;i<n;i++)
scanf("%d",&c[i]);
index = 0;
for(int i=0;i<l;i++)
for(int j=0;j<m;j++)
value[index++] = a[i]+b[j];
sort(value, value+index);
scanf("%d", &s);
printf("Case %d:\n", cnt);
while(s--)
{
int sum;
scanf("%d", &sum);
bool findFlag = false;
for(int i=0;i<n;i++)
{
if(c_binary_search(sum-c[i])) //öֲ鳤ȸvalue
{ //ʱ临Ӷȸ
findFlag = true;
break;
}
}
if(!findFlag)
printf("NO\n");
else
printf("YES\n");
}
}
}
| true |
4e45800be15476c1d1a01b8a518ab5d675c75b67 | C++ | ljz/encryption_system | /me - 副本 (6)/RSAKeyPairDLG.cpp | GB18030 | 17,541 | 2.640625 | 3 | [] | no_license | // RSAKeyPairDLG.cpp : ʵļ
//
#include "stdafx.h"
#include "me.h"
#include "RSAKeyPairDLG.h"
// CRSAKeyPairDLG Ի
IMPLEMENT_DYNAMIC(CRSAKeyPairDLG, CDialog)
CRSAKeyPairDLG::CRSAKeyPairDLG(CWnd* pParent /*=NULL*/)
: CDialog(CRSAKeyPairDLG::IDD, pParent)
, m_strPublicKey(_T(""))
, m_strPrivateKey(_T(""))
{
//SKLENGTH = 4; //˽Կij
}
CRSAKeyPairDLG::~CRSAKeyPairDLG()
{
}
void CRSAKeyPairDLG::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PublicKey, m_strPublicKey);
DDX_Text(pDX, IDC_PrivateKey, m_strPrivateKey);
}
/*---------------------------------------------------------------------------
ܣָԶĴ0ʼ
ڲA
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::SetZero(byteint A)
{
memset(A,0,DATALENGTH); //ϵͳгʼ
}
*/
/*---------------------------------------------------------------------------
ܣõһķλ
ڲvalidtemp
ֵзλ
----------------------------------------------------------------------------*/
/*
int CRSAKeyPairDLG::IntValid(byteint validtemp)
{
int i=0;
while(validtemp[i]==0 && i<DATALENGTH)
i++;
return DATALENGTH-i;
}
*/
/*---------------------------------------------------------------------------
ܣȽABĴС
ڲAʹB
ֵA>B:return 1 ; A=B:return 0 ; A<B:return -1
----------------------------------------------------------------------------*/
/*
int CRSAKeyPairDLG::IntCmp(byteint A,byteint B)
{
int stat;
stat=memcmp(A,B,DATALENGTH); //ϵͳ
if(stat==0)
return 0;
if(stat>0)
return 1;
return -1;
}
*/
/*---------------------------------------------------------------------------
ܣABĽCУD
ڲABCD
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::SetMode(byteint A,byteint B,byteint C,byteint D)
{
int i,j,k;
int valid_1,valid_2,valid,sbits,cmpval;
byteint buf1,buf2;
SetZero(buf1); SetZero(buf2);
SetZero(D); //Dʼ
IntCpy(C,A); //AC
valid_2=IntValid(B); //B()λ,
while((cmpval=IntCmp(C,B))>0) //Ϊ,ÿһξжǷC>B,ͼ
{
valid_1=IntValid(C); //C()λ,ΪλѭDZ仯
//(C-B)ȻC
valid=valid_1-valid_2; //CijBijȵIJֵСΪ0
if(valid>0) //ȳλ
{
i=DATALENGTH-valid_1; //ǰĸ
j=DATALENGTH-valid_2; //ǰĸ±ָʾ
sbits=0;
for(k=j;k<DATALENGTH;k++)
{
if(C[i]>B[j]) //CBλʼαȽ϶ӦλĴСжǷ
break;
if(C[i]<B[j])
{
sbits=1; //ôCһλ
break;
}
i++;j++; //CBλʱ,ͱȽ϶ߵĴθλ
}
valid=valid-sbits;
SetZero(buf1); //buf1
for(i=valid;i<DATALENGTH;i++)
{
j=i-valid;
buf1[j]=B[i]; //buf1дŵBλ֮õֵ
//,BƺλCλ,
//CĴθλ
}
}
else
IntCpy(buf1,B); //CBλͬʱ,ֱӰB뻺buf1
D[DATALENGTH-1-valid]++; //ﱣijһλļĴÿһξͼ1
Substract(C,buf1,buf2); //CijBijȵIJǷ0ҪֱC<=B
IntCpy(C,buf2);
}
if(cmpval==0) //
{
SetZero(C); //Ϊ0
D[DATALENGTH-1]++; //Ϊ1
}
}
*/
/*---------------------------------------------------------------------------
ܣúʮƵĴתɶƵ
ڲתĴBƽflag[400]
ֵ
----------------------------------------------------------------------------*/
/*void CRSAKeyPairDLG::TransBi(byteint B,signed char flag[400])
{
byteint buf;
byteint result;
byteint temp;
int i;
SetZero(buf); SetZero(result); SetZero(temp);
memset(flag,0,400); //flag
i=399;
IntCpy(buf,B); //Bbuf
while(IntCmp(buf,ZEROVALUE)==1) //bufΪ0
{
SetMode(buf,TWOVALUE,temp,result); //bufдģ2㣬resultУtemp
flag[i]=temp[DATALENGTH-1];
IntCpy(buf,result); //̼ģ2
i--;
}
flag[i]=-1; //һ־λĿʼ
}
*/
/*---------------------------------------------------------------------------
ܣBAУʵת
ڲAB
ֵ
----------------------------------------------------------------------------*/
//ܣBAʵת
/*void CRSAKeyPairDLG::LoadInt(byteint A,mtype B)
{
int i,j;
SetZero(A); //Aʼ
i=DATALENGTH-1;
j=MLENGTH-1;
while(j>0) //ѭλ
{
A[i--]=B[j--];
}
}
*/
/*---------------------------------------------------------------------------
ܣABˣC AB->C
ڲAͳBC
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::Multiply(byteint A,byteint B,byteint C)
{
int i,j,w;
int X,Y,Z;
int Avalid=0; //Avalid=validating bits of A
int Bvalid=0; //Avalid=validating bits of B
while (A[Avalid]==0 && Avalid<DATALENGTH)
Avalid++; //Avalid
while (B[Bvalid]==0 && Bvalid<DATALENGTH)
Bvalid++; //Bvalid
SetZero(C); //Cʼ
for(i=DATALENGTH-1;i>=Avalid;i--)
for(j=DATALENGTH-1;j>=Bvalid;j--) //λ
{
X=A[i]*B[j];
Y=X/10;
Z=X-10*Y;
w=i+j-(DATALENGTH-1);
C[w]=C[w]+Z;
C[w-1]=C[w-1]+(C[w]/10)+Y;
C[w]=C[w]-(C[w]/10)*10;
}
return;
}
*/
/*---------------------------------------------------------------------------
ܣúģ㷨AΪģΪcƵָBflag
ڲAģCDflag[400]
ֵA^B=1(mod C),1A^B=p-1(mod C),20
----------------------------------------------------------------------------*/
/*
int CRSAKeyPairDLG::PowerMode(byteint A,byteint C,byteint D,signed char flag[400])
{
byteint buf;
byteint result;
byteint temp,P;
int i;
SetZero(D); SetZero(buf); SetZero(result); SetZero(temp); SetZero(P); //D
IntCpy(temp,A); //Aֵtemp
if(flag[399]==1) //λΪ1flag[i]ֻ10
IntCpy(result,A);
else //λΪ0Ϊ1
IntCpy(result,ONEVALUE);
i=398;
while(flag[i]!=-1) //жǷѾָͷ
{
Multiply(temp,temp,buf); //temp*temp->buf
SetMode(buf,C,temp,P); //buf%c->temp,->p
if(flag[i]!=0) //λ0ǰһһλĽг˷
{ //ΪλģڸһλУֻҪһ
Multiply(temp,result,buf); //ƽ㣬ͿԵõһλģ
SetMode(buf,C,result,P);
}
i--;
} //resultдŵս
IntCpy(buf,C);
IntCpy(D,result);
Substract(buf,ONEVALUE,temp);
if(IntCmp(result,ONEVALUE)==0) //p mod n=1жǷA^B=1(mod C)
return 1;
if(IntCmp(result,temp)==0) //p mod n=-1[p-1=-1(mod p)]жǷA^B=p-1(mod C)
return 2;
return 0;
}
*/
/*---------------------------------------------------------------------------
ܣزһΪnumλ0RandomA
ڲAnum
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::IntRandom(byteint RandomA,int num)
{
int i;
SetZero(RandomA); //RandomA
while(!(RandomA[DATALENGTH-1]%2)) //ж֤RandomAһλ
RandomA[DATALENGTH-1]=rand()%10; //һλż²һλ
while(!(RandomA[DATALENGTH-num])) //ж֤RandomAλ0
RandomA[DATALENGTH-num]=rand()%10;//λ0,²λ
i=DATALENGTH-2;
while(i>=DATALENGTH-num+1) //ѭӴελʼθλλϵ
RandomA[i--]=rand()%10;
}
*/
/*---------------------------------------------------------------------------
ܣBA
ڲAB
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::IntCpy(byteint A,byteint B)
{
memcpy(A,B,DATALENGTH); //ϵͳɿ
}
*/
/*---------------------------------------------------------------------------
ܣSAȥSBSC
ڲSASBSC
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::Substract(byteint SA,byteint SB,byteint SC)
{
byteint buf;
int i,j;
int X;
IntCpy(buf,SA); //SAݿbuf
SetZero(SC); //SCʼ
for(i=DATALENGTH-1;i>=0;i--)
{
if(buf[i]<SB[i]) //λ
{
buf[i]=buf[i]+10; //λ1
if(buf[i-1]>0) //λֱӼ1
(buf[i-1])--;
else //һֱҵλ
{
j=i-1;
while(buf[j]==0) //jԽ磬Ϊ֤λΪ0
buf[j--]=9;
buf[j]=buf[j]-1;
}
}
X=buf[i]-SB[i]; //λĽSC
SC[i]=X;
}
}
*/
/*---------------------------------------------------------------------------
ܣúӼ[1,b-1]вɸڼModel[]
ڲ
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::Mdata()
{
int i,j; //Randomly choose a set of 100 numbers in [1,b-1]
int k=MLENGTH-2;
memset(Model,0,TESTNUM*MLENGTH); //㣬гʼ
srand( (unsigned)time( NULL ) ); //ijʼ
for(i=0;i<TESTNUM;i++) //TESTNUMΪҪĸ
{
for(j=MLENGTH-1;j>=k;j--)
{
Model[i][j]=rand()%10; //עijе
}
if((memcmp(Model[i],mZEROVALUE,MLENGTH))==0)
i--;
k--; //֤Ϊ0
if (k<0) k=MLENGTH-2;
}
}
*/
/*---------------------------------------------------------------------------
ܣһ
ڲPrm
ֵɹ0
----------------------------------------------------------------------------*/
/*
int CRSAKeyPairDLG::Prime(byteint Prm)
{
int i,k,ok;
signed char flag[400];
byteint A,B,D,buf1,buf2;
SetZero(A); SetZero(B); SetZero(D); SetZero(buf1); SetZero(buf2);
while(1) //һֱѭֱҵһΪֹ
{
int pass=0;
srand( (unsigned)time( NULL ) ); //ʼsrand
IntRandom(B,MLENGTH); //һB try b if prime,Bһ
IntCpy(Prm,B); //Bprm C=N result prime
Substract(B,ONEVALUE,buf1); //B-ONEVALUEĽŵbuf1
SetMode(buf1,TWOVALUE,buf2,B); //B=(B-1)/2,buf2=(B-1)/2=0
TransBi(B,flag); //BתΪƴ
ok=1;
for(i=0;i<TESTNUM;i++)
{
LoadInt(A,Model[i]); //Modelеĵi+1ȡA
k=PowerMode(A,Prm,D,flag); //(A^flag) mod Prm ->D
if(k!=1 && k!=2) //ж
{
ok=0;
break;
}
if(k==1) //ж1G=A^(n-1)/2=1
{
}
if(k==2) //ж2G=A^(n-1)/2=p-1
{
}
}
if (ok)//if(ok && pass_2)
{
return 0;
}//forѭIntRandom(B,MLENGTH)BǷһ
}
}
*/
/*---------------------------------------------------------------------------
ܣģR
ڲpqģR
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::ComputingR(byteint p,byteint q,byteint R)
{
Multiply(p,q,R); // R=p*q, public mode number
}
*/
/*---------------------------------------------------------------------------
ܣ$(r)
ڲpqģ$(r)Rvalue
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::ComputingRvalue(byteint p,byteint q,byteint Rvalue)
{
byteint buf1,buf2;
SetZero(buf1); SetZero(buf2);
Substract(p,ONEVALUE,buf1); // buf1=p-1
Substract(q,ONEVALUE,buf2); // buf2=q-1
Multiply(buf1,buf2,Rvalue); // Rvalue=(p-1)*(q-1)
}
*/
/*---------------------------------------------------------------------------
ܣABĽC
ڲA,B,C
ֵ
----------------------------------------------------------------------------*/
/*
void CRSAKeyPairDLG::Plus(byteint A,byteint B,byteint C)
{
int i;//,w;
int X,Y,Z,m,n,valid;
m=IntValid(A); //Aij
n=IntValid(B); //Bij
valid=(m>n)?m+1:n+1; //ʱҪΪ
SetZero(C); //C
for(i=DATALENGTH-1;i>=DATALENGTH-valid;i--)
{
X=A[i]+B[i]; //λ
Y=X/10;
Z=X-10*Y;
C[i]=C[i]+Z; //λ
C[i-1]=C[i-1]+Y;
}
}
*/
/*---------------------------------------------------------------------------
ܣ㹫ԿPK
ڲ$(r)ֵRvalueУ˽ԿSKԿPK
ֵɹҵ1
----------------------------------------------------------------------------*/
/*
int CRSAKeyPairDLG::ComputingPK(byteint Rvalue,byteint SK,byteint PK)
{
int i;
SKLENGTH=4; //˽Կij
byteint PA,PB,PC,buf1,temp,buf2;
SetZero(PK); SetZero(PA); SetZero(PB); SetZero(PC); SetZero(buf1); //ʼ
SetZero(temp); SetZero(buf2);
while(1)
{
IntRandom(SK,SKLENGTH); //һΪGenerated secret key
IntCpy(PB,SK);
IntCpy(PA,Rvalue);
while(1)
{
SetMode(PA,PB,PC,PK); //PA=PB*PK+PC
i=IntCmp(PC,ONEVALUE);
if(i==0) //PC=1, i=0
break; //ǻʵ
i=IntCmp(PC,ZEROVALUE);
if(i==0)
{
i=-1; //PC=0,i=-1
break; //㻥ѭһ
}
IntCpy(PA,PB); //ŷĶж
IntCpy(PB,PC);
}
if(i==0) //㣬ѭ
break;
}
IntCpy(temp,ONEVALUE);
IntCpy(PA,Rvalue);
IntCpy(PB,SK);
while(1)
{
Multiply(PA,temp,buf1); //buf1=PA*temp
Plus(buf1,ONEVALUE,buf2);//buf2=(PA*temp)+1
SetMode(buf2,PB,buf1,PK);//buf=((PA*temp)+1)%PB
if(IntCmp(buf1,ZEROVALUE)==0)
break;
Plus(temp,ONEVALUE,buf1);
IntCpy(temp,buf1);
}
return 1; //SK and PK found
}
*/
/*---------------------------------------------------------------------------
ܣһAתΪӦַʽ
ڲA
ֵӦַ
----------------------------------------------------------------------------*/
/*
CString CRSAKeyPairDLG::PrtInt(byteint A)
{
int int i=0;
int m,n;
while(i<DATALENGTH && A[i]==0) //ʼĿհ0
i++;
if(i<DATALENGTH)
m=DATALENGTH-i; //õĴ
n=0;
//עiѾеһԪصĶӦλã
CString str=""; //ѭǴ
//ŵλʼ
while(i<DATALENGTH)
{
str += (A[i++]+'0');
}
return str;
}
*/
BEGIN_MESSAGE_MAP(CRSAKeyPairDLG, CDialog)
END_MESSAGE_MAP()
// CRSAKeyPairDLG Ϣ
| true |
4b4858f94a841559824020c946b3704a5b063b68 | C++ | jiteshsingla1999/Competitive_code | /Backtracking/candle_distribution.cpp | UTF-8 | 719 | 2.953125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int func(int * arr, int n)
{
for(int m=0;m<n;m++)
{
int temp1 = arr[m];
int temp2 = arr[n-1];
int diff = temp2-temp1;
if(diff>temp1)
{
continue;
}
else
{
return temp1;
}
}
}
int main() {
// Write your code here
int test;
cin >> test;
while(test--)
{
int n,k;
cin >> n >> k;
int * arr = new int[n];
for(int i=0;i<n;i++)
cin >> arr[i];
sort(arr,arr+n);
if(k<n)
{
int diff = n-k;
cout << func(arr+(diff), k);
}
else if(n==k)
{
cout << func(arr,n);
}
else
{
}
}
}
| true |
276c2e7d038abe5edc64cb2d789ff5931141c1f9 | C++ | joaopaulocastilho/aBNT-Codes | /URI/URI2547-NINJA.cpp | UTF-8 | 258 | 2.5625 | 3 | [] | no_license | #include <stdio.h>
int main(void){
int n, x, amin, amax, ans;
while(scanf("%d %d %d", &n, &amin, &amax) != EOF){
for(ans = 0; n; n--){
scanf("%d", &x);
if(x >= amin && x <= amax) ans++;
}
printf("%d\n", ans);
}
return 0;
}
| true |
4969e33e5e3f73eb216d001139924367b3ab9b42 | C++ | isberg1/Project-C_plusplus-IMT1082-group-35 | /STATISTIKK.H | UTF-8 | 652 | 2.5625 | 3 | [] | no_license | #if !defined(__STATISTIKK_H)
#define __STATISTIKK_H
#include"CONST.H"
#include"FUNKSJONER.H"
class Statisikk
{
protected:
int sistebrukt; // Teller.
char nasjonsForkort[MAXNASJONER + 1][NASJONLEN +1]; // Array med nasjonsforkortelser.
public:
Statisikk(); // Constructor, nullstiller array.
void sorter1(int array[]); // Sorterer nasjonsForkort array og en medsendt int array.
void omsorter(int teller, int array[]); // Omsorterer nasjonsForkort array og en medsendt int array.
};
// Ny nasjon kommer fra poeng eller medalje
// All validering av riktig nasjon skjer i OvelseObj.
#endif
| true |
a4ec9acffefa3f1d6595d809f2d9c106e6a67ea5 | C++ | bowcharn/leetcode | /lt_022_generate_parentheses.cpp | UTF-8 | 2,577 | 4.03125 | 4 | [] | no_license | /*
Given n pairs of parentheses, write a function to generate all combinations of
well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
注:函数parens利用了bit pattern , 简直好的不得了
A bit pattern like:
10101100
Can be intepreted as:
()()(())
The function cycles through all bit patterns of the appropriate length and
eliminates those that fail the three tests described below.
The tests depend on calculating the sums of the bit patterns,
with 0 being replaced by -1.
e.g. sum(1100) = 1 + 1 - 1 - 1 = 0
Here are the tests:
(1) sum(bitpattern) = 0
Here is an example which fails:
sum(1110) = 1 + 1 + 1 - 1 = 2
(2) All partial sums must be >= 0.
Here is an example which fails:
bitpattern = 1001
sum(1) = 1
sum(10) = 1 - 1 = 0
sum(100) = 1 - 1 - 1 = -1 *
sum(1001) = 1 - 1 - 1 + 1 = 0
(3) All partial sums must <= pairs/2
Here is an exmple which fails:
bitpattern = 1110
sum(1) = 1
sum(11) = 1 + 1 = 2
sum(111) 1 + 1 + 1 = 3 *
sum(111) = 1 + 1 + 1 - 1 = 2
To make the code a little bit more efficient, we ignore the first and
last parantheses, because the first will always be
'(' and the last will always be ')'.
*/
#include <vector>
#include <string>
#include <iostream>
#include <cstdio>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n == 0)
return res;
solve_rec(n, 1, 0, "(", res);
return res;
}
void solve_rec(int n , int l_n , int r_n, string str, vector<string>& res)
{
if(l_n == r_n && l_n == n){
res.push_back(str);
return;
}
if(l_n < n)
{
solve_rec(n, l_n +1, r_n, str + "(", res);
// cout<<"l-> "<<str + "("<<"\n";
}
if(r_n < l_n)
{
solve_rec(n, l_n , r_n +1, str + ")", res);
// cout<<"r-> "<<str + ")"<<"\n";
}
}
};
void parens(int pairs)
{
int i, j, s, n = 2*(pairs - 1);
for (i = 0; i < 1 << n; i++) {
for (s = 1, j = 0; (j < n) && (s >= 0) && (s <= pairs); j++)
s += ((i >> j) & 1) ? 1 : -1;
cout<<"i = "<<i<<", j = "<<j<<", s = "<<s<<endl;
if ((j != n) || (s != 1))
continue;
putchar('(');
for (j = 0; j < n; j++)
((i >> j) & 1) ? putchar('(') : putchar(')');
printf(")\n");
}
}
int main(){
Solution solu;
solu.generateParenthesis(1);
parens(3);
return 0;
}
| true |
ab88928bfeabfa0373ee8cb40cdb8650fb69e60b | C++ | htiek/cs106b-lecture-demos | /Lecture 08/SierpinskiCarpet/SierpinskiCarpet.cpp | UTF-8 | 4,173 | 3.453125 | 3 | [] | no_license | /*
* File: SierpinskiCarpet.cpp
* ---------------
* A program that draws the Sierpinski Carpet fractal.
*/
#define COUNT_SQUARES
#include <iostream>
#include <string>
#include "gwindow.h"
#include "gobjects.h"
#include "gthread.h"
using namespace std;
/* Draws a square in the window, given the coordinates
* of the upper-left corner.
*/
void drawSquare(double x, double y,
double sideLength);
/* Draws a Sierpinski carpet of the given order.
* Returns how many total squares were drawn.
*/
// Draw an order-2 Sierpinski carpet (squares = 24)
int drawCarpet(double x, double y,
double sideLength,
int order) {
/* Base Case: An order-0 carpet is just a filled
* square.
*/
if (order == 0) {
drawSquare(x, y, sideLength);
return 1;
}
/* Recursive Case: Draw eight smaller Sierpinski
* carpets, arranged in a square, with the center
* square left off.
*/
else {
int squares = 0;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
/* Skip the center square. */
if (!(row == 1 && col == 1)) {
double newSide = sideLength / 3;
double newX = x + col * newSide;
double newY = y + row * newSide;
squares += drawCarpet(newX, newY,
newSide,
order - 1);
}
}
}
return squares;
}
}
/* Constants controlling the window size. */
const double kWindowWidth = 1000;
const double kWindowHeight = 800;
/* Margin from window sides to content area. */
const double kMargin = 40;
/* Colors! */
const string kBackgroundColor = "white";
const string kRectangleColor = "#400080";
/* Maximum order to draw. */
const double kMaxOrder = 5;
void clear();
void repaintWindow();
/* Yikes, global variables! This is normally a big
* no-no, but we've chosen to do it here because we
* want the lecture to focus on the recursion
* mechanics rather than the logic of working with
* windows.
*/
GWindow* theWindow;
/* Main program */
int main() {
GWindow window(kWindowWidth, kWindowHeight);
window.setExitOnClose(true);
theWindow = &window;
while (true) {
for (int order = 0; order <= kMaxOrder; order++) {
clear();
window.setTitle("Sierpinski Carpet of Order " + to_string(order));
/* Determine the width and height of the square to draw. */
double width = window.getCanvasWidth() - 2 * kMargin;
double height = window.getCanvasHeight() - 2 * kMargin;
double size = min(width, height);
/* Determine position. */
double x = (window.getCanvasWidth() - size) / 2.0;
double y = (window.getCanvasHeight() - size) / 2.0;
#ifdef COUNT_SQUARES
int numSquares =
#endif
drawCarpet(x, y, size, order);
#ifdef COUNT_SQUARES
cout << " An order-" << order << " Sierpinski carpet is made "
<< "of " << numSquares << " square(s)." << endl;
#endif
pause(2000);
}
}
}
/* This somewhat clunky-looking function is
* designed to repaint the window immediately
* so that if we step through this code in
* the debugger, the window is responsive and
* shows the squares we're drawing. This is basically
* a hack around our libraries; you aren't
* expected to understand how this works.
*/
void repaintWindow() {
GThread::runOnQtGuiThread([&] {
theWindow->repaint();
});
}
/* Clears the graphics contents from the window. */
void clear() {
theWindow->clearCanvasPixels();
repaintWindow();
}
void drawSquare(double x, double y,
double size) {
theWindow->setColor(kRectangleColor);
theWindow->fillRect(x, y, size, size);
repaintWindow();
}
| true |
1b74ed08214c52a01769a718831d5f435beaa351 | C++ | sailesh2/CompetitiveCode | /2017/cf410D1.cpp | UTF-8 | 1,508 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
bool fun(int a,int b){
return a>b;
}
int main(){
int n;
cin>>n;
int arr[n],brr[n];
long long int sum[n],sa=0,sb=0;
map<long long int,vector<int> > mp;
map<long long int,vector<int> >::iterator mapIt;
for(int i =0;i<n;i++){
cin>>arr[i];
}
for(int i =0;i<n;i++){
cin>>brr[i];
}
vector<int> v;
for(int i =0;i<n;i++){
vector<int> v1;
sum[i] = arr[i] + brr[i];
mapIt = mp.find(sum[i]);
if(mapIt!=mp.end()) {
v1 = mapIt->second;
mp.erase(mapIt);
}
v1.push_back(i);
mp.insert(make_pair<long long int,vector<int> >(sum[i],v1));
sa = sa +arr[i];
sb = sb +brr[i];
}
sort(sum,sum+n,fun);
long long int sma=0,smb=0;
vector<int> ans;
int ctr =0;
for(int i =0;i<n;i++){
mapIt = mp.find(sum[i]);
v = mapIt->second;
ans.push_back(v.at(0));
sma = sma +arr[v.at(0)];
smb = smb +brr[v.at(0)];
v.erase(v.begin());
mp.erase(mapIt);
if(v.size() > 0)
mp.insert(make_pair(sum[i],v));
if(2*sma>sa && 2*smb>sb){
ctr = i+1;
break;
}
}
cout<<ctr<<"\n";
for(int i=0;i<ans.size();i++){
cout<<ans.at(i)+1<<" ";
}
return 0;
}
| true |
dc0ab2f3ba1091dd033fc29e9698d1aace6a1723 | C++ | QtWorks/cosnetaViewer | /RoomManager/roommanager.cpp | UTF-8 | 2,753 | 2.734375 | 3 | [] | no_license | // Qt
#include <QDebug>
// Application
#include "roommanager.h"
#include "room.h"
// Constructor
RoomManager::RoomManager(QObject *parent) : QAbstractListModel(parent),
m_iCurrentRoomIndex(0)
{
// Add first room
for (int i=0; i<5; i++)
addRoom();
}
// Startup
bool RoomManager::startup()
{
return true;
}
// Shutdown
void RoomManager::shutdown()
{
}
// Return role names
QHash<int, QByteArray> RoomManager::roleNames() const
{
QHash<int, QByteArray> hRoleNames;
hRoleNames[RoomObject] = "roomObject";
return hRoleNames;
}
// Return count
int RoomManager::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return count();
}
// Return data
QVariant RoomManager::data(const QModelIndex &index, int role) const
{
// Check index
if (!index.isValid())
return QVariant();
// Check bounds
if ((index.row() < 0) || (index.row() > (count()-1)))
return QVariant();
// Get room
Room *pRoom = m_vRooms[index.row()];
// Return value for role
if (role == RoomObject)
return qVariantFromValue(pRoom);
return QVariant();
}
// Return current room index
int RoomManager::currentRoomIndex() const
{
return m_iCurrentRoomIndex;
}
// Set current room index
void RoomManager::setCurrentRoomIndex(int iRoomIndex)
{
if ((iRoomIndex >= 0) && (iRoomIndex < count()))
{
m_iCurrentRoomIndex = iRoomIndex;
emit currentRoomIndexChanged();
}
}
// Return current room
QObject *RoomManager::currentRoom() const
{
if ((m_iCurrentRoomIndex >= 0) && (m_iCurrentRoomIndex < count()))
{
Room *pCurrentRoom = m_vRooms[m_iCurrentRoomIndex];
return pCurrentRoom;
}
return NULL;
}
// Add room
void RoomManager::addRoom()
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
Room *pRoom = new Room();
QString sRoomName = QString("Room%1").arg(m_vRooms.size()+1);
pRoom->setName(sRoomName);
m_vRooms << pRoom;
endInsertRows();
}
// Remove current room
void RoomManager::removeCurrentRoom()
{
// Keep at least one desk
if (count() > 1)
removeRoom(m_iCurrentRoomIndex);
}
// Remove room
void RoomManager::removeRoom(int iRoomIndex)
{
if ((iRoomIndex >= 0) && (iRoomIndex < count()))
{
bool bIsLastRoom = (iRoomIndex == count()-1);
beginRemoveRows(QModelIndex(), iRoomIndex, iRoomIndex);
Room *pRoom = m_vRooms.takeAt(iRoomIndex);
delete pRoom;
endRemoveRows();
if (m_vRooms.size() == 1)
setCurrentRoomIndex(0);
else
if (bIsLastRoom)
setCurrentRoomIndex(m_vRooms.size()-1);
}
}
// Return count
int RoomManager::count() const
{
return m_vRooms.size();
}
| true |
97b2503b314b05bc698840e3301b69f34bf1b8ef | C++ | zhangrongzhao/CPlusPlusTemplates | /src/C++.Templates/Part.4/Chapter.21/Tuple/Tuple.h | WINDOWS-1252 | 2,860 | 2.671875 | 3 | [] | no_license | #include "../stdafx.h"
#ifndef TUPLE_H
#define TUPLE_H
#include "../Traits/typeop.h"
#include "../Duo/Duo.h"
#include "../Duo/Duo2.h"
#include "../Duo/DuoValue.h"
class NullT{};
template<typename P1,
typename P2=NullT,
typename P3=NullT,
typename P4=NullT,
typename P5=NullT>
class Tuple:public Duo<P1,typename Tuple<P2,P3,P4,P5,NullT>::BaseT >{
public:
typedef Duo<P1,typename Tuple<P2,P3,P4,P5,NullT>::BaseT> BaseT;
Tuple(){}
Tuple(typename TypeOp<P1>::RefConstT a1,
typename TypeOp<P2>::RefConstT a2,
typename TypeOp<P3>::RefConstT a3 = NullT(),
typename TypeOp<P4>::RefConstT a4 = NullT(),
typename TypeOp<P5>::RefConstT a5 = NullT()
) :BaseT(a1, Tuple<P2, P3, P4, P5, NullT>(a2, a3, a4, a5)){
}
};
//ݹڣ
template<typename P1,typename P2>
class Tuple<P1,P2,NullT,NullT,NullT>:public Duo<P1,P2>{
public:
typedef Duo<P1, P2> BaseT;
Tuple(){}
Tuple(typename TypeOp<P1>::RefConstT a1,
typename TypeOp<P2>::RefConstT a2,
typename TypeOp<NullT>::RefConstT a3 = NullT(),
typename TypeOp<NullT>::RefConstT a4 = NullT(),
typename TypeOp<NullT>::RefConstT a5 = NullT())
:BaseT(a1,a2){
}
};
template<typename P1>
class Tuple<P1, NullT, NullT, NullT, NullT> :public Duo<P1, void>{
public:
typedef Duo<P1, void> BaseT;
Tuple(){}
Tuple(typename TypeOp<P1>::RefConstT a1,
typename TypeOp<NullT>::RefConstT a2 = NullT(),
typename TypeOp<NullT>::RefConstT a3 = NullT(),
typename TypeOp<NullT>::RefConstT a4 = NullT(),
typename TypeOp<NullT>::RefConstT a5 = NullT())
:BaseT(a1){
}
};
template<typename T1>
inline Tuple<T1> make_tuple(T1 const& a1){
return Tuple<T1>(a1);
}
template<typename T1,typename T2>
inline Tuple<T1, T2> make_tuple(T1 const& a1,T2 const& a2){
return Tuple<T1, T2>(a1,a2);
}
template<typename T1, typename T2,typename T3>
inline Tuple<T1, T2,T3> make_tuple(T1 const& a1, T2 const& a2,T3 const& a3){
return Tuple<T1, T2,T3>(a1, a2,a3);
}
template<typename T1, typename T2, typename T3,typename T4>
inline Tuple<T1, T2, T3,T4> make_tuple(T1 const& a1, T2 const& a2, T3 const& a3,T4 const& a4){
return Tuple<T1, T2, T3,T4>(a1, a2, a3,a4);
}
template<typename T1, typename T2, typename T3, typename T4,typename T5>
inline Tuple<T1, T2, T3, T4,T5> make_tuple(T1 const& a1, T2 const& a2, T3 const& a3, T4 const& a4,T5 const& a5){
return Tuple<T1, T2, T3, T4,T5>(a1, a2, a3, a4,a5);
}
void test_tuple(){
//Tuple<int> t1;
//val<1>(t1) += 42;
//int nResult = t1.value1();
//Tuple<bool, int> t2;
//bool bResult = val<1>(t2);
//bResult = t2.value1();
Tuple<bool, int, double> t3;
//val<1>(t3) = true;
//val<2>(t3) = 42;
//val<3>(t3) = 0.2;
//t3 = make_tuple(false,23,13.13);
//bool b1 = val<1>(t3);
//int n1 = val<2>(t3);
//double d1 = val<3>(t3);
Tuple<bool, int, float, double> t4;
val<4>(t4);
t4.value2().value2().value2();
}
#endif//TUPLE_H | true |
13cd0853a79ba21a1c147218d72f5014a54e83c4 | C++ | sarguments/OOP_Shooting_Suomi | /shooting_Suomi/shooting_Suomi/Player.cpp | UHC | 960 | 2.71875 | 3 | [] | no_license | #include "stdafx.h"
#include "Base.h"
#include "Player.h"
#include "Scene.h"
#include "GameScene.h"
CPlayer::CPlayer(CGameScene* pScene)
{
_pGameScene = pScene;
// ÷̾ ʱȭ
_x = dfSCREEN_WIDTH / 2;
_y = dfSCREEN_HEIGHT - 5;
_type = eObjType::Player;
}
CPlayer::~CPlayer()
{
}
void CPlayer::Action()
{
KeyProcess();
}
void CPlayer::Draw()
{
SpriteDraw(_x, _y, 'U');
}
void CPlayer::Move(eDir param)
{
switch (param)
{
case eDir::Left:
{
_x--;
}
break;
case eDir::Right:
{
_x++;
}
break;
}
}
void CPlayer::KeyProcess()
{
if ((GetAsyncKeyState(VK_RIGHT) & 0x8000)) // RR
{
if (!CheckPos(_x + 1, _y))
{
return;
}
Move(eDir::Right);
}
if ((GetAsyncKeyState(VK_LEFT) & 0x8000)) // LL
{
if (!CheckPos(_x - 1, _y))
{
return;
}
Move(eDir::Left);
}
if ((GetAsyncKeyState(VK_SPACE) & 0x8000))
{
Shot();
}
}
void CPlayer::Shot()
{
_pGameScene->CreateBullet(eObjType::Player, _x, _y - 1);
} | true |
ac23bf0bdad27d1f4f60c000e96b9148e4f6b8af | C++ | nneesshh/mytoolkit | /src_vc141/core/SimpleCalendar.cpp | UTF-8 | 3,510 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | //------------------------------------------------------------------------------
// SimpleCalendar.cpp
// (C) 2016 n.lee
//------------------------------------------------------------------------------
#include "SimpleCalendar.h"
//------------------------------------------------------------------------------
/**
*/
CSimpleCalendar::CSimpleCalendar() {
Init(time(nullptr));
}
//------------------------------------------------------------------------------
/**
*/
CSimpleCalendar::CSimpleCalendar(time_t tmNow) {
Init(tmNow);
}
//------------------------------------------------------------------------------
/**
*/
CSimpleCalendar::~CSimpleCalendar() {
}
//------------------------------------------------------------------------------
/**
*/
void
CSimpleCalendar::Init(time_t tmNow) {
int wday, mday;
int year, mon;
// today
struct tm tm_ = FormatDate(tmNow, _rule._chToday, sizeof(_rule._chToday));
// mday
mday = tm_.tm_mday;
// wday -- Sunday is the tm_wday beginning, but we use Monday as our week beginning
wday = ((tm_.tm_wday - 1) + 7) % 7;
// year
year = tm_.tm_year;
// mon
mon = tm_.tm_mon;
// day
_rule._today = mktime(&tm_);
_rule._today_mon_in_year = tm_.tm_mon + 1;
_rule._today_day_in_month = tm_.tm_mday;
_rule._yesterday = _rule._today - DAY_SECONDS;
_rule._tomorrow = _rule._today + DAY_SECONDS;
// weekday
_rule._weekday = _rule._today - wday * DAY_SECONDS;
_rule._weekdayPre = _rule._weekday - 7 * DAY_SECONDS;
_rule._weekdayPost = _rule._weekday + 7 * DAY_SECONDS;
// monthday
_rule._monthday = _rule._today - (mday - 1) * DAY_SECONDS;
tm_.tm_year = year;
tm_.tm_mon = mon - 1;
tm_.tm_mday = 1;
_rule._monthdayPre = mktime(&tm_);
tm_.tm_year = year;
tm_.tm_mon = mon + 1;
tm_.tm_mday = 1;
_rule._monthdayPost = mktime(&tm_);
// yesterday
FormatDate(_rule._yesterday, _rule._chYesterday, sizeof(_rule._chYesterday));
// tomorrow
FormatDate(_rule._tomorrow, _rule._chTomorrow, sizeof(_rule._chTomorrow));
// weekday
FormatDate(_rule._weekday, _rule._chWeekday, sizeof(_rule._chWeekday));
// weekday pre
FormatDate(_rule._weekdayPre, _rule._chWeekdayPre, sizeof(_rule._chWeekdayPre));
// weekday post
FormatDate(_rule._weekdayPost, _rule._chWeekdayPost, sizeof(_rule._chWeekdayPost));
// monthday
FormatDate(_rule._monthday, _rule._chMonthday, sizeof(_rule._chMonthday));
// monthday pre
FormatDate(_rule._monthdayPre, _rule._chMonthdayPre, sizeof(_rule._chMonthdayPre));
// monthday post
FormatDate(_rule._monthdayPost, _rule._chMonthdayPost, sizeof(_rule._chMonthdayPost));
}
//------------------------------------------------------------------------------
/**
*/
void
CSimpleCalendar::Update(time_t tmNow) {
if (tmNow - _rule._today >= DAY_SECONDS) {
Init(_rule._today + DAY_SECONDS);
}
}
//------------------------------------------------------------------------------
/**
*/
bool
CSimpleCalendar::IsYesterday(const char *sDay) {
return IsYesterday(StringToDate(sDay));
}
//------------------------------------------------------------------------------
/**
*/
bool
CSimpleCalendar::IsToday(const char *sDay) {
return IsToday(StringToDate(sDay));
}
//------------------------------------------------------------------------------
/**
*/
bool
CSimpleCalendar::IsTomorrow(const char *sDay) {
return IsTomorrow(StringToDate(sDay));
}
/* -- EOF -- */ | true |
c06be716c28d9b0a3b8b955330218022b4104310 | C++ | JimouChen/algorithm-competition-training | /course/CPPLearning/exp/exp3/task33.cpp | GB18030 | 770 | 3.921875 | 4 | [
"MIT"
] | permissive | # include <iostream>
using namespace std;
class Student {
private:
double score;
static double total;
static int count;
public:
void scoreTotal(double s);
static int person();
static double average();
};
double Student::total = 0;
int Student::count = 0;
void Student::scoreTotal(double s) {
score = s;
total += score;
count++;
}
int Student::person() {
return count;
}
double Student::average() {
return total / count;
}
int main() {
Student student[3];//ɸѧ
student[0].scoreTotal(92);
student[1].scoreTotal(94);
student[2].scoreTotal(96);
cout << "ѧ:" << Student::person() << endl;
cout << "ѧƽ:" << Student::average() << endl;
return 0;
} | true |
c56f78615e9b19cfc027f5f4d86feaa1607cf089 | C++ | PiasTanmoy/Codeforces | /codeforces 445B.cpp | UTF-8 | 821 | 2.65625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int n, m;
int mat[55][55];
unsigned long long int dan=1;
vector<int> G[55];
int visited[55];
int counter=0;
void input()
{
cin>>n>>m;
int x,y;
for(int i=0; i<m; i++){
cin>>x>>y;
mat[x][y]=1;
mat[y][x]=1;
G[x].push_back(y);
G[y].push_back(x);
}
}
void dfs(int u)
{
visited[u]=1;
for(int v=1; v<=n; v++){
if(mat[u][v] && !visited[v])
dfs(v);
}
}
void start()
{
for(int i=1; i<=n; i++){
if(!visited[i]){
counter++;
dfs(i);
}
}
}
void cal()
{
for(int i=1; i<=n-counter; i++)
dan*=2;
cout<<dan;
}
int main()
{
input();
start();
cal();
return 0;
}
| true |
b12649e97a19c17744813118f03fd56de84bf596 | C++ | JJJVic/ps6 | /baxter_moves_library/include/baxter_moves_library/my_interesting_moves.h | UTF-8 | 1,156 | 2.59375 | 3 | [] | no_license | /* Copyright 2015 YQJ */
#ifndef MY_INTERESTING_MOVES_H
#define MY_INTERESTING_MOVES_H
#include <ros/ros.h>
#include <Eigen/Eigen>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <Eigen/Eigenvalues>
typedef Eigen::Matrix<double, 7, 1> Vectorq7x1;
class InterestingMoves
{
public:
ros::NodeHandle nh_;
int g_count;
explicit InterestingMoves(ros::NodeHandle *nh);
/**
* This will give the baxter robot the command to extend its right arm
*/
void set_goal_extend_arm();
/**
* This will give the baxter robot the command to bend its right elbow
*/
void set_goal_bend_arm();
/**
* This will give the baxter robot the command to wave its right arm
*/
void set_goal_wave_arm();
/**
* This will give the baxter robot the command to put down its right arm
*/
void set_goal_putdown_arm();
private:
/**
* This will calculate the trajectories and send the goal trajectory to the action server
* @param position: the desired position for the robot to go to
*/
void find_and_send_trajectory(Vectorq7x1 position);
};
#endif // MY_INTERESTING_MOVES_H
| true |
85ee7d4748051783d53c40c51dd8b6be187c91be | C++ | jeremy1357/Zombie-Onslaught | /SE_Game_Project/SoundDelegate.h | UTF-8 | 743 | 2.5625 | 3 | [] | no_license | #pragma once
#include <string>
#include <map>
#include <SDL/SDL_mixer.h>
#include <vector>
struct AudioFile {
AudioFile(const std::string& name, Mix_Chunk* audioData) {
this->name = name;
this->audioData = audioData;
}
std::string name;
Mix_Chunk* audioData;
int channel = -1;
};
class SoundDelegate
{
public:
SoundDelegate();
~SoundDelegate();
void init_sound_delegate(const std::string& soundPathway);
void load_audio(const std::string& name);
void play_effect(int key, int times = 0);
void stop_effect(int key);
void play_music(int key);
void stop_music(int key);
int get_key(const std::string& name);
private:
std::string m_soundPathway;
std::map <int, AudioFile> m_audioFiles;
std::vector<int> m_usedChannels;
};
| true |
749ae675cb86ce125059ef48f382a272c33795d3 | C++ | longlt2/GLESFrameWork | /NewTrainingFramework/Game/Physic/Circle.cpp | UTF-8 | 1,954 | 3.0625 | 3 | [] | no_license | #include "Circle.h"
#include "Physic.h"
#include "VideoDriver.h"
Circle::Circle() : Object()
{
m_radius = 0;
type = OBJECT_TYPE_CIRCLE;
}
Circle::Circle( int radius )
{
m_radius = radius;
type = OBJECT_TYPE_CIRCLE;
}
Circle::Circle( int x, int y, int radius ) : Object( x, y, 0 , glm::vec2( 0,0 ) )
{
m_radius = radius;
type = OBJECT_TYPE_CIRCLE;
}
Circle::Circle( int x, int y, int mass, glm::vec2 const & velocity, int radius ) : Object( x, y, mass , velocity )
{
m_radius = radius;
type = OBJECT_TYPE_CIRCLE;
}
Circle::Circle( glm::vec2 const &p, int radius ) : Object( p, 0, glm::vec2( 0,0 ) )
{
m_radius = radius;
type = OBJECT_TYPE_CIRCLE;
}
Circle::Circle( glm::vec2 const &p, int mass, glm::vec2 const & velocity, int radius ) : Object( p, mass, velocity )
{
m_radius = radius;
type = OBJECT_TYPE_CIRCLE;
}
Circle::Circle( Circle const &cl )
{
m_position = cl.m_position;
m_radius = cl.m_radius;
type = OBJECT_TYPE_CIRCLE;
}
Circle::~Circle()
{
}
void Circle::Update( float frameTime )
{
Object::Update( frameTime );
if( ( m_position.x < m_radius ) )
{
m_position.x = ( float )m_radius;
}
else if( ( m_position.x + m_radius ) > gWIDTH )
{
m_position.x = ( float )( gWIDTH - m_radius );
}
if( ( m_position.y < m_radius ) )
{
m_position.y = ( float )m_radius;
}
else if( ( m_position.y + m_radius ) > gHEIGHT )
{
m_position.y = ( float )( gHEIGHT - m_radius );
}
}
bool Circle::isInside( glm::vec2 const &p ) const
{
double rs = sqrt( ( ( p.x - m_position.x ) * ( p.x - m_position.x ) ) + ( ( p.y - m_position.y ) * ( p.y - m_position.y ) ) ) * ODD_RATE;
if( rs > m_radius )
{
return false;
}
return true;
}
void Circle::Render( GUtils::VideoDriver *video, float prediction ) const
{
video->DrawCircle( m_position + m_velocity * prediction, m_radius );
}
| true |
b29d20f1fdf802ec8986722ece4db87cc721533a | C++ | LewisBray/TetrisAI | /src/tetris.h | UTF-8 | 1,298 | 2.625 | 3 | [] | no_license | #ifndef TETRIS_H
#define TETRIS_H
#include "colour.h"
#include "maths.h"
#include "types.h"
namespace Tetris {
struct Tetrimino {
struct Blocks {
static constexpr i32 COUNT = 4;
Coordinates top_left_coordinates[COUNT];
};
enum Type { T = 0, L = 1, RL = 2, S = 3, Z = 4, SQUARE = 5, LONG = 6, COUNT = 7 };
Blocks blocks;
Vec2 centre;
Type type;
};
enum Rotation { CLOCKWISE = 0, ANTI_CLOCKWISE = 1 };
Colour piece_colour(Tetrimino::Type type);
Tetrimino construct_tetrimino(Tetrimino::Type type, const Coordinates& top_left);
Tetrimino shift(Tetrimino tetrimino, const Coordinates& shift);
Tetrimino rotate(Tetrimino tetrimino, Rotation rotation);
struct Grid {
using Cell = Colour;
static constexpr i32 ROW_COUNT = 18;
static constexpr i32 COLUMN_COUNT = 10;
Cell cells[ROW_COUNT][COLUMN_COUNT];
};
bool is_empty_cell(const Grid::Cell& grid_cell);
i32 remove_completed_rows(Grid& grid); // TODO: don't like mutable ref
bool collision(const Tetrimino& tetrimino, const Grid& grid);
void merge(const Tetrimino& tetrimino, Grid& grid); // TODO: ditto
bool resolve_rotation_collision(Tetrimino& tetrimino, const Grid& grid);
}
#endif
| true |