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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9b27936c6337cdaff5b565cef294ffcfc286d73f | C++ | gwonii/algorithm | /Code/c++/Backjun/HappyAlgo/1_dataStructure_base/11655/code_11655.cpp | UTF-8 | 1,040 | 3.140625 | 3 | [] | no_license | //
// Created by hoho on 2019-08-19.
//
#include "code_11655.h"
#include <iostream>
#include <stack>
#include <string>
using namespace std;
string inputString_11655;
char lowerChanger(char content) {
int tempContent = (int) content;
for (int i = 0; i < 13; i++) {
if (tempContent == 122) {
tempContent = 97;
} else {
tempContent++;
}
}
return (char) tempContent;
}
char upperChanger(char content) {
int tempContent = (int) content;
for (int i = 0; i < 13; i++) {
if (tempContent == 90) {
tempContent = 65;
} else {
tempContent++;
}
}
return (char) tempContent;
}
void method_11655() {
getline(cin, inputString_11655);
for (char & i : inputString_11655) {
if(i >= 'A' && i <= 'Z') {
i = upperChanger(i);
} else if (i >= 'a' && i <= 'z') {
i = lowerChanger(i);
}
}
for (char i : inputString_11655) {
cout << i;
}
} | true |
b02223e6b6cf2b65d3837a2d4a3d4fb9f2f250a3 | C++ | bernatixer/PRO2-Practice | /ParCrom.cc | UTF-8 | 1,228 | 3.453125 | 3 | [] | no_license | #include "ParCrom.hh"
ParCrom::ParCrom() {
//
}
void ParCrom::reproduir(const int li, const int k, vector<int> mare, vector<int> pare) {
for (int i = k; i < li; ++i) {
int aux = mare[i];
mare[i] = pare[i];
pare[i] = aux;
}
parell.first = mare;
parell.second = pare;
}
void ParCrom::llegir(const int li) {
vector<int> v1(li);
parell.first = v1;
parell.second = v1;
for (int i = 0; i < li; ++i) cin >> (parell.first)[i];
for (int i = 0; i < li; ++i) cin >> (parell.second)[i];
}
void ParCrom::llegir_sexual(const int l1, const int l2) {
vector<int> v1(l1);
vector<int> v2(l2);
parell.first = v1;
parell.second = v2;
for (int i = 0; i < l1; ++i) cin >> (parell.first)[i];
for (int i = 0; i < l2; ++i) cin >> (parell.second)[i];
}
void ParCrom::escriure_primer(const int li) const {
for (int i = 0; i < li-1; ++i) cout << (parell.first)[i] << " ";
cout << (parell.first)[li-1] << endl;
}
void ParCrom::escriure_segon(const int li) const {
for (int i = 0; i < li-1; ++i) cout << (parell.second)[i] << " ";
cout << (parell.second)[li-1] << endl;
}
vector<int> ParCrom::primer() const {
return parell.first;
}
vector<int> ParCrom::segon() const {
return parell.second;
}
| true |
f8ea9a5654d94eedfbd4a4f1df71c50410c4a6e1 | C++ | enryu100/ICT397_Main_Project | /BiteClub/BiteClub/ObjLoader.cpp | UTF-8 | 2,689 | 3.03125 | 3 | [] | no_license | #include "ObjLoader.h"
#include <fstream>
#include <string>
#include <sstream>
using namespace loader;
using namespace std;
using namespace types;
bool loader::loadObj(const char* path, vector<Vector3D> & outVertices, vector<Vector2D> & outUVs, vector<Vector3D> & outNormals){
vector<unsigned int> vertexIndices, uvIndices, normalIndices;
vector<Vector3D> tempVertices, tempNormals;
vector<Vector2D> tempUVs;
string lineHeader;
ifstream file(path, ios::in);
if(!file)
return false;
while(getline(file, lineHeader)){
if(lineHeader.substr(0, 2) == "v "){
Vector3D vertex;
istringstream str(lineHeader.substr(2));
str >> vertex.x;
str >> vertex.y;
str >> vertex.z;
tempVertices.push_back(vertex);
}
else if(lineHeader.substr(0, 3) == "vt "){
Vector2D uv;
istringstream str(lineHeader.substr(2));
str >> uv.x;
str >> uv.y;
tempUVs.push_back(uv);
}
else if(lineHeader.substr(0, 3) == "vn "){
Vector3D normal;
istringstream str(lineHeader.substr(2));
str >> normal.x;
str >> normal.y;
str >> normal.z;
tempNormals.push_back(normal);
}
else if(lineHeader.substr(0, 2) == "f "){
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
// UV indices aren't working in the test model, so they've been removed.
istringstream str(lineHeader.substr(2));
str >> vertexIndex[0];
str.ignore(1, '/');
//str >> uvIndex[0];
str.ignore(1, '/');
str >> normalIndex[0];
str >> vertexIndex[1];
str.ignore(1, '/');
//str >> uvIndex[1];
str.ignore(1, '/');
str >> normalIndex[1];
str >> vertexIndex[2];
str.ignore(1, '/');
//str >> uvIndex[2];
str.ignore(1, '/');
str >> normalIndex[2];
vertexIndices.push_back(vertexIndex[0]);
vertexIndices.push_back(vertexIndex[1]);
vertexIndices.push_back(vertexIndex[2]);
//uvIndices.push_back(uvIndex[0]);
//uvIndices.push_back(uvIndex[1]);
//uvIndices.push_back(uvIndex[2]);
normalIndices.push_back(normalIndex[0]);
normalIndices.push_back(normalIndex[1]);
normalIndices.push_back(normalIndex[2]);
}
}
file.close();
for(int index = 0; index < vertexIndices.size() && index < tempVertices.size(); index++){
if(vertexIndices[index] - 1 >= 0)
outVertices.push_back(tempVertices[vertexIndices[index] -1]);
}
/*
for(int index = 0; index < uvIndices.size() && index < tempUVs.size(); index++){
if(uvIndices[index] - 1 >= 0)
outUVs.push_back(tempUVs[uvIndices[index] -1]);
}
*/
for(int index = 0; index < normalIndices.size() && index < tempNormals.size(); index++){
if(normalIndices[index] - 1 >= 0)
outNormals.push_back(tempNormals[normalIndices[index] -1]);
}
return true;
} | true |
a6e66855248c1936b21b2cd3cd4a21ed00478ad8 | C++ | skdn159/BattlesProj | /BattleShip_pp/BattleShip_pp.cpp | UHC | 1,714 | 2.890625 | 3 | [] | no_license | // BattleShip_pp.cpp : ܼ α մϴ.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include <time.h>
#include<ctime>
#include<cstdlib>
#include<list>
#include"Destroyer.h"
#include"GameManager.h"
#include"player.h"
int _tmain(int argc, _TCHAR* argv[])
{
/*
srand((unsigned int)time(NULL)); //time ̿ seed
std::string strResult[] = { "Hit", "MISS", "DESTROY" };
std::vector<std::string>ships;
ships.push_back("Aircraft Carrier");
ships.push_back("Battle Ship");
ships.push_back("Cruiser");
ships.push_back("Destroyer 1");
ships.push_back("Destroyer 2");
std::string strGuess;
int resultpicked;
int pickedDestroyedShips;
Ship myship;
Destroyer destroyer1, destroyer2;
destroyer1.HitCheck();
GameManager gm;
gm.SetStatus(gamestarted);
std::cout << gm.getStatus()<< std::endl;
while (!ships.empty())
{
resultpicked = rand() % _countof(strResult);
std::cin >> strGuess;
std::cout << strResult[(resultpicked)] << std::endl;
if (resultpicked == 2){ // . ϸ ?
pickedDestroyedShips = rand() % ships.size();
std::cout << ships[pickedDestroyedShips] << std::endl;
ships.erase(ships.begin() + pickedDestroyedShips);
std::cout << " : ";
for ( int i = 0; i < ships.size(); i++){
std::cout << ships[i] << " /"; //?? ȴ. vector Ư¡
}
std::cout << std::endl;
}
}
std::cout << "====== GameOver ======" << std::endl;
fflush(stdin);*/
srand((unsigned int)time(NULL));
Player player;
player.SetupShips();
player.PrintShips();
getchar();
return 0;
}
| true |
0c3c7b5b59242739999550f1d0a1277d763e1784 | C++ | meyerpa/CPlusPlus | /CSIS 252/Brekke's Files/func3.cpp | UTF-8 | 1,803 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
const int arraysize=5;
const int sentinel=-999;
// function prototypes
// comment: in prototypes, parameter names are not needed
int biggest(const int numbers[],int count);
void output(const int numbers[],int count);
int search(const int numbers[],int count, int searchValue);
void read(int numbers[], int& count);
int main()
{
int numbers[arraysize];
int count;
read(numbers,count);
output(numbers,count);
output(numbers,count);
output(numbers,count);
cout << "biggest is " << biggest(numbers,count) << endl;
int searchValue;
cout << "enter a value to search for: ";
cin >> searchValue;
int position = search(numbers,count,searchValue);
if (position >= 0)
cout << searchValue << " found at position " << position << endl;
else
cout << searchValue << " not found\n";
return 0;
}
void read(int numbers[], int& count)
{
count = 0; // since it wasn't function input
cout << "enter ints, " << sentinel << " to quit: ";
int num;
cin >> num;
while (num != sentinel && count < arraysize)
{
numbers[count] = num;
count++;
cin >> num;
}
}
int biggest(const int numbers[],int count)
{
int biggest = numbers[0];
for (int i=0; i<count; i++)
if (numbers[i] > biggest)
biggest = numbers[i];
return biggest;
}
void output(const int numbers[],int count)
{
cout << "Array: ";
for (int i=0; i<count; i++)
cout << numbers[i] << ' ';
cout << endl;
}
int search(const int numbers[],int count, int searchValue)
{
bool found=false;
int pos=0;
while (!found && pos<count)
{
if (numbers[pos] == searchValue)
found = true;
else
pos++;
}
if (found)
return pos;
else
return -1;
}
| true |
1dca27cec132d169d6fcf60671a690b0c28dafd0 | C++ | YangboLong/CLRS | /ch8.cpp | UTF-8 | 2,070 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <vector>
class Solution{
public:
// clrs p195
void CountingSort(std::vector<int> &A, int B[], int k){
std::vector<int> C;
for(int i = 0; i <= k; i++){
C.push_back(0);
}
for(int j = 0; j < A.size(); j++){
C[A[j]]++;
}
for(int i = 1; i <= k; i++){
C[i] += C[i-1];
}
for(int j = A.size() - 1; j >= 0; j--){
B[C[A[j]] - 1] = A[j];
C[A[j]]--;
}
/*for(int j = 0; j < A.size(); j++){
B[C[A[j]] - 1] = A[j];
C[A[j]]--;
}*/
}
// clrs p198
void RadixSort(std::vector<int> &A, int d){
int exp = 1;
int C[10];
/*int *B = new int[A.size()];
for(int i = 0; i < A.size(); i++){
B[i] = 0;
}*/
for(int i = 0; i < 10; i++){
C[i] = 0;
}
for(int digits = 0; digits < d; digits++){
int *B = new int[A.size()];
for(int j = 0; j < A.size(); j++){
C[(A[j]/exp) % 10]++;
}
for(int i = 1; i < 10; i++){
C[i] += C[i-1];
}
for(int j = A.size() - 1; j >= 0; j--){
B[C[(A[j]/exp) % 10] - 1] = A[j];
C[(A[j]/exp) % 10]--;
}
for(int k = 0; k < A.size(); k++){
A[k] = B[k];
//B[k] = 0;
}
for(int i = 0; i < 10; i++){
C[i] = 0;
}
exp *= 10;
delete [] B;
}
//delete [] B;
}
};
int main(){
Solution sln;
int inta[] = {2, 5, 3, 0, 2, 3, 0, 3};
std::vector<int> A(inta, inta + sizeof(inta) / sizeof(int));
int B[8];
std::cout << "Unsorted array A entries: ";
for(int i = 0; i < A.size(); i++){
std::cout << A[i] << " ";
}
std::cout << std::endl;
sln.CountingSort(A, B, 5);
std::cout << "Sorted array B entries: ";
for(int i = 0; i < 8; i++){
std::cout << B[i] << " ";
}
std::cout << std::endl;
int intd[] = {32, 4, 657, 839, 436, 720, 355};
std::vector<int> D(intd, intd + sizeof(intd) / sizeof(int));
std::cout << "Unsorted array D entries: ";
for(int i = 0; i < D.size(); i++){
std::cout << D[i] << " ";
}
std::cout << std::endl;
sln.RadixSort(D, 3);
std::cout << "Sorted array D entries: ";
for(int i = 0; i < D.size(); i++){
std::cout << D[i] << " ";
}
std::cout << std::endl;
return 0;
} | true |
c13d9813017f7aed7f75ce5a50ea713ce91f651e | C++ | NikitaBalasahebRaut/ThisPointer | /DemoThisPtr.cpp | UTF-8 | 1,330 | 4.78125 | 5 | [] | no_license | //program to demonstrate the concept of this pointer
//if you want to assign the local variable value to the data members then you won’t be able to do until unless you use this pointer
//because the compiler won’t know that you are referring to object’s data members
#include <iostream>
using namespace std;
class Demo
{
private:
int num; //data member
char ch;
public:
void setMyValues(int num, char ch) //member function contain local variable
{
this->num =num; //assign the local variable value to the data members
this->ch=ch;
}
void displayMyValues()
{
cout<<num<<endl;
cout<<ch;
}
};
int main()
{
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
return 0;
}
/*
output
100
A
*/
/*
program Explanation
Here you can see that we have two data members num and ch. In member function setMyValues() we have two local variables having same name as data members name.
In such case if you want to assign the local variable value to the data members then you won’t be able to do until unless you use this pointer,
because the compiler won’t know that you are referring to object’s data members unless you use this pointer. This is one of the example where you must use this pointer.
*/ | true |
72baab31f3333047443a3cd4d361fb61dbc86321 | C++ | FattyMieo/GameEngine | /GameEngine/TransparencyAffectorOverLifespan.cpp | UTF-8 | 696 | 2.59375 | 3 | [] | no_license | #include "TransparencyAffectorOverLifespan.h"
TransparencyAffectorOverLifespan::TransparencyAffectorOverLifespan() : ParticleAffectorOverLifespan<unsigned int>()
{
lifespanValue[0.0f] = 255;
lifespanValue[1.0f] = 255;
}
TransparencyAffectorOverLifespan::~TransparencyAffectorOverLifespan()
{
}
void TransparencyAffectorOverLifespan::UpdateParticle(ParticleObject* particle, float deltaTime)
{
unsigned int a, b;
float t;
float t0 = particle->GetLife() / particle->GetFullLife();
if (CalculateBounds(t0, a, b, t))
{
Color origColor = particle->GetSprite().GetColor();
origColor.a = (GLubyte)MathExtension::Lerp((int)a, (int)b, t);
particle->GetSprite().SetColor(origColor);
}
} | true |
81197c196d63a5f69d760fc15376d5130bf89abf | C++ | rickarkin/PyMesh-win | /tests/tools/MeshUtils/IsolatedVertexRemovalTest.h | UTF-8 | 1,928 | 2.71875 | 3 | [] | no_license | /* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */
#pragma once
#include <iostream>
#include <MeshUtils/IsolatedVertexRemoval.h>
#include <TestBase.h>
class IsolatedVertexRemovalTest : public TestBase {
protected:
void add_extra_vertex_and_check(MeshPtr mesh) {
const size_t dim = mesh->get_dim();
const size_t num_vertices = mesh->get_num_vertices();
const size_t num_faces = mesh->get_num_faces();
const size_t vertex_per_face = mesh->get_vertex_per_face();
MatrixFr vertices = Eigen::Map<MatrixFr>(
mesh->get_vertices().data(), num_vertices, dim);
MatrixIr faces = Eigen::Map<MatrixIr>(
mesh->get_faces().data(), num_faces, vertex_per_face);
MatrixFr modified_vertices(num_vertices+1, dim);
modified_vertices.block(1,0, num_vertices, dim) = vertices;
modified_vertices.row(0) = VectorF::Zero(dim);
MatrixIr modified_faces = faces + MatrixIr::Ones(num_faces, vertex_per_face);
IsolatedVertexRemoval remover(modified_vertices, modified_faces);
remover.run();
MatrixFr result_vertices = remover.get_vertices();
MatrixIr result_faces = remover.get_faces();
VectorI ori_vertex_indices = remover.get_ori_vertex_indices();
VectorI tar_vertex_indices =
MatrixUtils::range<VectorI>(num_vertices).array() + 1;
ASSERT_MATRIX_EQ(vertices, result_vertices);
ASSERT_MATRIX_EQ(faces, result_faces);
ASSERT_MATRIX_EQ(tar_vertex_indices, ori_vertex_indices);
}
};
TEST_F(IsolatedVertexRemovalTest, 2D) {
MeshPtr mesh = load_mesh("square_2D.obj");
add_extra_vertex_and_check(mesh);
}
TEST_F(IsolatedVertexRemovalTest, 3D) {
MeshPtr mesh = load_mesh("cube.msh");
add_extra_vertex_and_check(mesh);
}
| true |
6ac750b89463dbfda284002b65e2e03cc3d47e69 | C++ | abicorios/MyCppExercises | /c6e16atoi/c6e16atoi/c6e16atoi.cpp | WINDOWS-1251 | 1,077 | 3.296875 | 3 | [
"Unlicense"
] | permissive | // c6e16atoi.cpp: .
//
#include "stdafx.h"
#include <iostream>
//#include <string>
using namespace std;
int main()
{
int atoi(char*);
cout << atoi("45") << " " << 45 << '\n';
cout << atoi("077") << " " << 077 << '\n';
cout << atoi("0xf")<<" "<< 0xf << '\n';
}
int atoi(char*c)
{
int l= strlen(c);
int number = 0;
int d(char);
if(c[0]!='0')
for (int i = 0; i < l; i++) number += d(c[l-i-1]) * pow(10, i);
else
if(c[0]== '0' && c[1]!='x')
for (int i = 1; i < l; i++) number += d(c[l - i]) * pow(8, i-1);
else
if(c[0] == '0' && c[1] == 'x')
for (int i = 2; i < l; i++) number += d(c[l - i+1]) * pow(16, i - 2);
else
{
cout << "myerror, it is not a number\n";
return 0;
}
return number;
}
int d(char c)
{
if (c >= '0'&&c <= '9')
return c - '0';
else
if (c >= 'a'&&c <= 'f')
return c - 'a'+10;
else
if (c >= 'A'&&c <= 'F')
return c - 'A'+10;
else
{
cout << "myerror, it is not a number\n";
return 0;
}
}
| true |
940e7a68e508e325d072acd3b838158d0dca56e1 | C++ | iiSky101/rmsk2 | /permutation.h | UTF-8 | 5,917 | 3 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /***************************************************************************
* Copyright 2017 Martin Grap
*
* 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.
***************************************************************************/
/*! \file permutation.h
* \brief Provides an interface for a class that implements permutations over non-negative integers.
*/
#ifndef __permuation_h__
#define __permuation_h__
#include<vector>
#include<set>
#include<utility>
#include<transforms.h>
#include<rand_gen.h>
using namespace std;
/*! \brief A class that abstracts the notion of a permutation of the numbers 0 ... n-1.
*
* A permutation is a bijective mapping of the integers 0 ... n-1 onto themselves. n is called the size of the permutation.
* Permutations are used all over rmsk. A physical rotor for instance is a permutation which is implemented by wiring
* contacts that are placed on different sides of a thin cylinder. A permutation is also the simplest form of
* encryption_transform that rmsk provides. This class implements a permutation.
*
* This class makes use of the fact that each vector or array of type unsigned int and length n implicitly specifies a mapping of the integers
* between 0 and n-1 to the set of all unsigned integers. The result of the mapping of some value k, 0 <= k <= n-1 is simply the value of the array/vector
* at position k. Therefore the array/vector specifies a mapping of the values 0 ... n-1 onto themselves if it only contains values between
* 0 and n-1. On top of that it specifies a permutation if it contains each value between 0 and n-1 exactly once.
*/
class permutation : public encryption_transform {
public:
/*! \brief Copy constructor.
*/
permutation(const permutation& p);
/*! \brief Constructs a permutation from a vector of unsigned integers.
*/
permutation(const vector<unsigned int>& vec);
/*! \brief Constructs a permutation from a C-style array of length size given in the parameter vec.
*/
permutation(unsigned int *vec, unsigned int size);
/*! \brief Default constructor: Constructs a permutation of size 0. Permutations of size 0 can not be used to encrypt() and decrypt().
*/
permutation() { perm = NULL; inv_perm = NULL; perm_size = 0; }
/*! \brief Applies the permutation to the value given in the parameter in_char.
*/
virtual unsigned int encrypt(unsigned int in_char) { return perm[in_char]; }
/*! \brief Applies the inverse permutation to the value given in the parameter in_char.
*/
virtual unsigned int decrypt(unsigned int in_char) { return inv_perm[in_char]; }
/*! \brief Returns the size of the permutation.
*/
virtual unsigned int get_size() { return perm_size; }
/*! \brief If this permutation specifies a valid involution the set cycle_pairs is filled with the commutations that make up the involution.
* Otherwise the set is cleared.
*/
virtual void test_for_involution(set<pair<unsigned int, unsigned int> >& cycle_pairs);
/*! \brief Inline version of encrypt().
*/
inline unsigned int permute(unsigned int c) { return perm[c]; }
/*! \brief Fills the parameter v with a representation of this permutation.
*/
virtual void to_vec(vector<unsigned int>& v);
/*! \brief Returns a permutation object that implements the inverse of this permutation.
*/
virtual permutation get_inverse();
/*! \brief Switches this permutation to its inverse.
*/
virtual void switch_to_inverse() { unsigned int *temp = perm; perm = inv_perm; inv_perm = temp; }
/*! \brief Modifies this permutation by swapping the values on the positions given by the parameter swaps.
*/
virtual void modify(vector<unsigned int>& swaps);
/*! \brief Prints a representation of this permutation to stdout.
*/
virtual void print();
/*! \brief Inline version of decrypt().
*/
inline unsigned int inv(unsigned int c) { return inv_perm[c]; }
/*! \brief Returns a permutation object representing a permutation of a given size that has been randomly chosen using the specified random_generator.
*/
static permutation get_random_permutation(random_generator& in, unsigned int size);
/*! \brief Returns the permutation of the specified size that maps each number between 0 and size-1 to itself.
*/
static permutation get_identity(unsigned int size);
/*! \brief Assignment operator.
*/
virtual permutation& operator=(const permutation& p);
/*! \brief Destructor.
*/
virtual ~permutation() { delete[] perm; delete[] inv_perm; }
protected:
/*! \brief Helper method that fills perm and inv_perm and set perm_size.
*/
virtual void set_permutation(const vector<unsigned int>& vec);
/*! \brief Uses the data members of the permutation given in parameter p to set the members of this permutation.
*/
void copy(const permutation& p);
/*! \brief Size of this permutation.
*/
unsigned int perm_size;
/*! \brief Mapping that specifies the permutation.
*/
unsigned int *perm;
/*! \brief Mapping that specifies the inverse permutation.
*/
unsigned int *inv_perm;
};
#endif /* __permuation_h__ */
| true |
8cd74bb90993450b723f613acc917edd906efee9 | C++ | Demongo2009/TIN_TorrentLikeP2P | /src/structs/ResourceInfo.cpp | UTF-8 | 2,711 | 3.3125 | 3 | [] | no_license | #include "../../include/structs/ResourceInfo.h"
ResourceInfo ResourceInfo::deserializeResource(const char *message, bool toVector,int *dataPointer) {
std::string resourceName;
unsigned long long sizeInBytes;
std::size_t revokeHash;
std::string builder;
unsigned short charIndex=0;
char currCharacter=message[charIndex];
while(currCharacter && currCharacter!=SEPARATOR){
resourceName+=currCharacter;
currCharacter=message[++charIndex];
}
if(!currCharacter) {
return ResourceInfo(resourceName);
}
currCharacter=message[++charIndex];
std::string revokeHashBuilder;
while(currCharacter && currCharacter!=SEPARATOR){
if(isdigit(currCharacter)) {
revokeHashBuilder += currCharacter;
}else {
throw std::runtime_error("invalid number while reading revoking hash (character is not a digit): ");
}
currCharacter=message[++charIndex];
}
try {
std::stringstream ss(revokeHashBuilder);
ss>>revokeHash;
}
catch (std::exception& exception){
throw std::runtime_error("exceeded number value limit or invalid character read while reading resource revoke hash");
}
if(!currCharacter) {
throw std::runtime_error("unexpected end of serialized data while reading resource name");
}
currCharacter=message[++charIndex];
std::string sizeBuilder;
while(currCharacter && currCharacter!=SEPARATOR){
if(isdigit(currCharacter)) {
sizeBuilder += currCharacter;
}
else {
throw std::runtime_error("invalid number while reading resource size (character is not a digit)");
}
currCharacter=message[++charIndex];
}
try {
sizeInBytes = std::stoull(sizeBuilder);
}
catch (std::exception& exception){
throw std::runtime_error("exceeded number value limit or invalid character read while reading resource size");
}
if(toVector) {
*dataPointer += charIndex;
}
if(charIndex > MAX_MESSAGE_SIZE) {
throw std::runtime_error("message exceeded maximum length!");
}
return ResourceInfo(resourceName, sizeInBytes, revokeHash);
}
std::vector<ResourceInfo> ResourceInfo::deserializeVectorOfResources(char *message){
int charIndex = 0;
std::vector<ResourceInfo> resources;
while (message[charIndex] && charIndex <= MAX_MESSAGE_SIZE){
resources.push_back(std::move(deserializeResource(message + charIndex, true, &charIndex)));
charIndex++;
}
if(charIndex > MAX_MESSAGE_SIZE) {
throw std::runtime_error("message exceeded maximum length!");
}
return resources;
} | true |
54d059c732b9de20cf7b04a87558342de1ea611f | C++ | mavaL/MiniCraft | /Kratos/Src/AI/BehaviorTree/Behavior.h | GB18030 | 846 | 2.609375 | 3 | [] | no_license | /********************************************************************
created: 28:3:2013 1:35
filename Behavior.h
author: maval
purpose: BehaviorʾActionNodeִеһΪ.
пܵΪ,λκʱһijһΪ
*********************************************************************/
#ifndef Behavior_h__
#define Behavior_h__
#include "KratosPrerequisites.h"
namespace Ogre
{
class Any;
}
namespace Kratos
{
///Ϊ
class aiBehavior
{
public:
aiBehavior() {}
virtual ~aiBehavior() {}
public:
virtual void Execute(Ogre::Any& owner) = 0;
virtual void Update(Ogre::Any& owner, float dt) {}
virtual void Exit(Ogre::Any& owner) {}
private:
aiBehavior(const aiBehavior&);
aiBehavior& operator= (const aiBehavior&);
};
}
#endif // Behavior_h__ | true |
59f1826901b9bddde9afff77f852e9cbf306323a | C++ | 2youngjae/Programmers | /메뉴리뉴얼.cpp | UTF-8 | 1,927 | 3.328125 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
void addSubSet(map<string, int> &m, string &s, int idx, string subStr)
{
if (idx == s.size())
return;
string cur = subStr + s[idx];
if (m.count(cur) == 0)
{
m[cur] = 1;
}
else
{
m[cur]++;
}
for (int i = idx + 1; i < s.size(); i++)
{
addSubSet(m, s, i, cur);
}
}
vector<string> solution(vector<string> orders, vector<int> course)
{
vector<string> answer;
map<string, int> m;
for (int i = 0; i < orders.size(); i++)
{
sort(orders[i].begin(), orders[i].end());
for (int j = 0; j < orders[i].size(); j++)
{
addSubSet(m, orders[i], j, "");
}
}
for(int i = 0 ; i < course.size(); i++){
int maxCount = 0;
for(map<string, int>::iterator iter = m.begin(); iter != m.end(); iter++)
{
if(iter->first.size() == course[i])
{
maxCount = max(maxCount, iter->second);
}
}
if(maxCount < 2) continue;
for(map<string, int>::iterator iter = m.begin(); iter != m.end(); iter++)
{
if(iter->first.size() == course[i] && iter->second == maxCount)
{
answer.push_back(iter->first);
}
}
}
sort(answer.begin(), answer.end());
return answer;
}
int main()
{
vector<string> orders = {
"ABCFG",
"AC",
"CDE",
"ACDE",
"BCFG",
"ACDEH"};
vector<int> course = {2, 3, 4};
vector<string> answer = solution(orders, course);
cout << "===answer===" << endl;
for (int i = 0; i < answer.size(); i++)
{
cout << answer[i] << endl;
}
return 0;
} | true |
701be6f03d778b539450761d61a93f2b9c00ab1a | C++ | tonyzhang1231/data-structure-and-alg-practice-cpp-java | /cpp/001. two sum.cpp | UTF-8 | 453 | 2.8125 | 3 | [] | no_license | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> v2i;
vector<int> res;
for (int i=0;i<nums.size();i++){
if (v2i.find(nums[i])!= v2i.end()){
res.push_back(v2i[nums[i]]);
res.push_back(i);
return res;
}else{
v2i[target - nums[i]] = i;
}
}
return res;
}
}; | true |
97b8218342e12ceed127d9d73d8c220860ccef10 | C++ | RealAlpha/ArduCOSMOS | /src/linkedlist.h | UTF-8 | 7,012 | 3.546875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | /*
* This file contains a simple implementation of a linked list, and will be used in the code when the C++ Standard Library has not been marked as available by the user.
* If your toolchain supports the C++ Standard Library, and more specifically, std::vector, then please uncomment the WITH_STD_LIB define in arducosmos.h, which will result in that being used instead of this library.
*
* NOTE: This linked list was primarily implemented as a way to avoid (unrequired) third-party libraries, more specifically, ArduinoSTL (which is a great library by the way, but depending on it for something as simple as this was considered not necissery)
*/
#ifndef ARDUCOSMOS_LINKEDLIST_H_
#define ARDUCOSMOS_LINKEDLIST_H_
// LinkedList may be used by other libraries too, so we are wrapping it in the ArduCOSMOS namespace.
namespace NS_ArduCOSMOS
{
// NOTE: We'll only be implementing the required functions (add to and iteration at the time of writing this comment), so this isn't a fully-fledged linked list function. Templating used since this is
template <typename T> class LinkedList
{
public:
// Simple struct to store the required data and a pointer to the next node. If the pointer to the next node is null, it is the final node in the list.
struct ListNode
{
public:
T data;
ListNode *next = nullptr;
// Is the current node the last item in the list?
bool IsLast()
{
// A node is the last in the list if there isn't a next element -> next is a nullptr
return next == nullptr;
}
};
// Iterator class
/// NOTE: Helps abstract things and avoid pointers // helps a more streamlined interface
class Iterator
{
public:
// Default constructor; takes in a node: the node at which this iterator is pointing.
Iterator(ListNode *Node)
{
this->Node = Node;
}
// Overload the ++ operator so we can use it to iterate.
Iterator operator++(int)
{
// Is the current node valid, or not? (for example: is this beyond the end of the list?)
if (!Node) { return Iterator(nullptr); }
// Return an iterator to the next node
return Iterator(Node->next);
}
// Overload the dereference operator(s) to return the data so we can use it with the same code as std::vector
T &operator->()
{
// Is the current node valid, or not? (for example: is this beyond the end of the list?)
/// NOTE: If there are any exceptions about a constructor of a type not existing, make sure you have a default no-parameter constructor available in case you iterate over the end of a list // it needs to return a blank item.
/// NOTE II: The below is generally Bad Practive / "Evil", but Node should never be a nullptr anyway, or the user'll have iterated too far and still requested the data.
if (!Node)
{
T badPracticeButRequired = T();
return badPracticeButRequired;
}
// Since the current node is valid, we can safely return it's data
return Node->data;
}
// NOTE: You may need to use **it to first dereference the ListNode, and then hit this operator to get the data. You won't hit this when using
T &operator*()
{
// Is the current node valid, or not? (for example: is this beyond the end of the list?)
/// NOTE: If there are any exceptions about a constructor of a type not existing, make sure you have a default no-parameter constructor available in case you iterate over the end of a list // it needs to return a blank item.
/// NOTE II: The below is generally Bad Practive / "Evil", but Node should never be a nullptr anyway, or the user'll have iterated too far and still requested the data.
if (!Node)
{
T badPracticeButRequired = T();
return badPracticeButRequired;
}
// Since the current node is valid, we can safely return it's data
return Node->data;
}
// Gets the "low-level" list node "representation. Used for passing to erase.
ListNode *GetLowLevel()
{
return Node;
}
// TODO: Override the is valid (ie if (someIterator)) operator so we don't go beyond the end.
operator bool() const
{
return Node != nullptr;
}
private:
// The node this iterator is currently pointing at.
ListNode *Node;
};
public:
// Returns an iterator made from the first node in the list.
/// NOTE: small b used to be virtually identical to the std::vector library.
Iterator begin()
{
return Iterator(firstNode);
}
// Appends an item (to the start of) the list.
void push_back(T data)
{
// Allocate some memory for the new node.
ListNode *newNode = new ListNode();
if (!newNode) { return; }
// Set the data of the new item to the requested data
newNode->data = data;
// Insert it into the linked list at the front
newNode->next = firstNode;
firstNode = newNode;
}
// Erase the whole linked list
void erase()
{
// A wrapper for the recursive erase function. NOTE: firstNode can safely be a nullptr.
erase_r(firstNode);
}
// Erase a single item in a linked list.
void erase(ListNode *node)
{
// Keep track of the current and previous node.
ListNode *previous = nullptr;
ListNode *trav = firstNode;
while (trav != nullptr)
{
// Is this the node we should erase?
if (trav == node)
{
// We need to erase this node!
// Is there a previous node? (wecan assume trav is not a nullptr -> is valid)
if (previous != nullptr)
{
// Since we'll be removing this node, we want to make sre the previous node links to the next node so we don't loose any data.
previous->next = trav->next;
// We don't need to do anything else because this is NOT a doubly linked list and the list can still be iterated. We'll delete/remove this node down below.
}
else
{
// No previous node, so we need to erase the first item in the list -> delete this node, and set the first node to the next item.
/// NOTE: If next is a nullptr that causes no issues, so we don't need any checking.
firstNode = node->next;
}
// Now that we've safely stored the rest of the list, delete this node to free up the memory
delete node;
// Finished all of the required things, so return out of the function.
return;
}
// Update the loop to go to the next node in the list.
previous = trav;
trav = trav->next;
}
}
private:
// Erase the linked list including the specified node and all nodes following it.
/// NOTE: Private because we don't want half the linked list to be erased and next not being a nullptr -> cause segfaults.
void erase_r(ListNode *node)
{
// Is this the last item? (if so no need to erase or continue further down)
if (node == nullptr)
{
return;
}
else
{
// Traverse down first deleting child nodes, and then delete itself.
erase_r(node->next);
delete node;
}
}
// TODO: Deal with cleanup in the deconstructor!
private:
ListNode *firstNode = nullptr;
};
};
#endif
| true |
365bbf176cc8ef10e633904dc8310a0c7dcc58d3 | C++ | ChristianLebeda/HomSub | /homomorphism/include/homomorphism/spasm_decomposition.h | UTF-8 | 1,201 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef HOMOMORPHISM_SPASMDECOMPOSITION_H_
#define HOMOMORPHISM_SPASMDECOMPOSITION_H_
#include "homomorphism/graph.h"
#include "homomorphism/spasm.h"
#include "homomorphism/tree_decomposition.h"
#include "homomorphism/tree_width_solver.h"
struct SpasmDecompositionEntry : SpasmEntry {
std::shared_ptr<TreeDecomposition> decomposition;
};
class SpasmDecomposition
{
public:
SpasmDecomposition(std::vector<SpasmDecompositionEntry> graphs, std::shared_ptr<Graph> graph, size_t width) : graphDecomps_(graphs), graph_(graph), width_(width) {}
static std::shared_ptr<SpasmDecomposition> decomposeSpasm(std::shared_ptr<Spasm> sp);
static std::shared_ptr<SpasmDecomposition> decomposeSpasm(std::shared_ptr<Spasm> sp, TreeWidthSolver& tws);
static std::shared_ptr<SpasmDecomposition> fromFile(std::string path);
static std::shared_ptr<SpasmDecomposition> deserialize(std::istream& input);
size_t size();
std::string serialize();
SpasmDecompositionEntry& operator[](std::size_t position);
std::shared_ptr<Graph> graph();
size_t width();
private:
std::vector<SpasmDecompositionEntry> graphDecomps_;
std::shared_ptr<Graph> graph_;
size_t width_;
};
#endif
| true |
f71e4c1f3ac5a88e4a7f0e2b74f1061a7159f46a | C++ | fylr/algorithm | /codeup/100000576/D.cpp | UTF-8 | 455 | 2.515625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int N, M, i, j, num, num_list[102];
while (scanf("%d", &N) != EOF) {
for (i = 0; i < N; i++) {
scanf("%d", &num_list[i]);
}
scanf("%d", &M);
for (i = 0; i < M; i++) {
scanf("%d", &num);
for (j = 0; j < N; j++) {
if (num == num_list[j]) break;
}
if (j < N)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
| true |
d876de060a54a60bd6a28e7904d664f9965a7d1a | C++ | jeliser/sandbox | /interview/fibonacci/src/fibonacci.cpp | UTF-8 | 288 | 2.90625 | 3 | [] | no_license | #include <iostream>
////////////////////////////////////////
// Put instructions here.
////////////////////////////////////////
int main() {
// Print out the results from [0, 20) for template types: uint16_t, int32_t, string, and float.
std::cout << "Hello World!";
return 0;
}
| true |
2796186babfa791b9b010eb880baa4a5d691e3e1 | C++ | aerosayan/xndarr | /src/xndarr/expression/vecexpr.cpp | UTF-8 | 819 | 2.734375 | 3 | [] | no_license | //-//////////////////////////////////////////////////////////////////////////-//
// @file vecexpr.cpp
// @info Vector expression.
// @author Sayan Bhattacharjee
// @date 4-AUG-2019
//-//////////////////////////////////////////////////////////////////////////-//
// Constructor
XNDARR_EXPRESSION_LTSIG
XNDARR_EXPRESSION_STSIG
::expression(LHS lhs,RHS rhs )
: lhs_(std::forward<LHS>(lhs)),
rhs_(std::forward<RHS>(rhs))
{
}
// Copy constructor
XNDARR_EXPRESSION_LTSIG
XNDARR_EXPRESSION_STSIG
::expression(XNDARR_EXPRESSION_STSIG & other)
{
lhs_ = other.lhs_;
rhs_ = other.rhs_;
}
// Move constructor
XNDARR_EXPRESSION_LTSIG
XNDARR_EXPRESSION_STSIG
::expression(XNDARR_EXPRESSION_STSIG && other)
: lhs_(std::forward<decltype(other.lhs_)>(other.lhs_)),
rhs_(std::forward<decltype(other.rhs_)>(other.rhs_))
{
}
| true |
db43ae4f31f98a8c4bcaa01545afd268b608bac4 | C++ | tannalynn/CST211-DataStructs | /Lab - Hash Table/L7 - Hash Table/Source.cpp | UTF-8 | 2,102 | 3.109375 | 3 | [] | no_license | /***************************************************************************************************
* Author: Tanna McClure
* File: Source.cpp
* Date Created: 3/10/2015
*
* Overview:
* tests hash table class
*
* Input:
* none
*
* Output:
* results of test
*
***************************************************************************************************/
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <string>
#include "HashTable.h"
using std::cout;
using std::cin;
using std::string;
struct Book
{
Book(char * t, char * a, int p): m_title(t), m_author(a), m_pages(p) { }
Book() { }
string m_title;
string m_author;
int m_pages;
};
int asciihash(string i);
int hash2(string i);
void display(const Book & book);
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
HashTable<string, Book> table(asciihash); //ctor
table.Insert("0001", Book("title" , "author" , 1)); //insert
table.Insert("0082", Book("title2", "author2", 2));
table.Insert("0003", Book("title3", "author3", 3));
table.Insert("0934", Book("title4", "author4", 4));
table.Insert("0005", Book("title5", "author5", 5));
table.Insert("0006", Book("title6", "author6", 6));
table.Insert("0307", Book("title7", "author7", 7));
table.Insert("0008", Book("title8", "author8", 8));
table.Insert("0008", Book("title9", "author9", 9));
table["0005"].m_title = "chicken nuggets"; //[]
HashTable<string, Book> copy(table); //copy ctor
copy.SetHash(hash2); //set hash
table = copy; // =
copy.SetSize(4); //set size
copy.Delete("0082"); //delete
copy.Delete("0934");
copy.Delete("0008");
copy.Traverse(display); //traverse
cin.get();
return 0;
}
int asciihash(string str)
{
int h = 0;
for (int i(0); i < str.size(); i++)
h += str.c_str()[i] * str.c_str()[i];
return h;
}
int hash2(string str)
{
int h = 0;
for (int i(0); i < str.size(); i++)
h += str.c_str()[i];
return h;
}
void display(const Book & book)
{
cout << book.m_title << " by " << book.m_author << " pages: " << book.m_pages << "\n";
} | true |
68d5253a985ef431a77563e4c7b25d72b2699cb4 | C++ | GA239/robolabwp | /RoboLabWP/RoboLabWPComp/Model/Game/Game Objects/MZRotatingCell.cpp | UTF-8 | 1,371 | 3.09375 | 3 | [] | no_license | #include "pch.h"
#include "MZRotatingCell.h"
MZRotatingCell::MZRotatingCell(MZPosition* position, MZCell* cell, MZRotationDirection rotationDirection)
{
_position = new MZPosition(*position);
_cell = cell;
_rotationDirection = rotationDirection;
}
MZRotatingCell::~MZRotatingCell(void)
{
if(_cell != NULL)
{
delete(_cell);
}
if(_position != NULL)
{
delete(_position);
_position = NULL;
}
}
MZPosition* MZRotatingCell::position()
{
return _position;
}
bool MZRotatingCell::hasWallAtDirection(MZDirection direction)
{
return _cell->hasWallAtDirection(direction);
}
MZRotationDirection MZRotatingCell::rotationDirection()
{
return _rotationDirection;
}
void MZRotatingCell::toggle()
{
MZCell *newValue;
if(_rotationDirection == CLOCKWISE)
{
bool isDown = _cell->hasWallAtDirection(DOWN);
MZByte walls = _cell->wallsValue();
walls = walls << 1;
if(isDown)
{
walls = walls & 1;
walls = walls & (1 << 4);
}
//newValue = [[MZCell alloc] initWithWallsValue:walls];
newValue = new MZCell(walls);
}
else
{
BOOL isLeft = _cell->hasWallAtDirection(LEFT);
MZByte walls = _cell->wallsValue();
walls = walls >> 1;
if(isLeft)
walls = walls & (1 << DOWN);
newValue = new MZCell(walls);
}
_cell = newValue;
} | true |
c95975e34f3c3fddef9adc02dc94f03fec2fe4a1 | C++ | turoniol/MapCreator | /scene/scene.cpp | UTF-8 | 2,901 | 2.625 | 3 | [] | no_license | #include "scene.h"
#include <QDebug>
#include <QPicture>
bool Scene::createMap(const int w, const int h, QString &name)
{
_width = w;
_height = h;
if (map != nullptr)
delete map;
if (editBlock != nullptr)
delete editBlock;
map = new Map;
editBlock = new BlockEditor();
if (map->loadMapFromFile(name)) {
displayMap();
map->setBlocksNeighbours();
unsigned y = map->getGraphicHeight(),
x = map->getGraphicWidth();
setSceneRect(0, 0, x, y);
return true;
}
else {
delete map;
delete editBlock;
editBlock = nullptr;
map = nullptr;
return false;
}
}
void Scene::createEmptyMap(const int x, const int y)
{
if(map != nullptr)
delete map;
if (editBlock != nullptr)
delete editBlock;
map = new Map;
editBlock = new BlockEditor();
map->createEmptyMap(x, y);
displayMap();
map->setBlocksNeighbours();
unsigned h = map->getGraphicHeight(),
w = map->getGraphicWidth();
setSceneRect(0, 0, w, h);
}
bool Scene::existMap()
{
if (map == nullptr)
return false;
else
return true;
}
void Scene::displayMap()
{
map->displayMap();
for(auto &obj : map->getMapVector()) {
this->addItem(&obj);
}
this->addItem(editBlock);
}
void Scene::saveMap(const QString& name)
{
if (existMap()) {
map->saveMap(name);
emit saved();
}
}
void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
int x = event->scenePos().x(),
y = event->scenePos().y();
x -= x % Block::getPixmapSize();
y -= y % Block::getPixmapSize();
if (existMap() && inScene(x, y) && QPointF(x, y) != editBlock->pos()) {
editBlock->setPosition(x, y, &map->getBlockByCoordinate(x, y));
if (event->buttons() == Qt::LeftButton) {
changeType(&map->getBlockByCoordinate(x, y));
}
}
}
void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (editBlock != nullptr) {
Block *block = &map->getBlockByCoordinate(editBlock->x(), editBlock->y());
if (event->button() == Qt::LeftButton) {
changeType(block);
}
else if (event->button() == Qt::RightButton) {
editBlock->rotate();
editBlock->setPix(block);
}
}
}
void Scene::keyPressEvent(QKeyEvent *event)
{
if (editBlock != nullptr) {
if (event->key() == Qt::Key_Space) {
editBlock->retype();
editBlock->setPix(&map->getBlockByCoordinate(editBlock->x(), editBlock->y()));
}
}
}
void Scene::changeType(Block *block)
{
block->setType(editBlock->getTempType());
block->setPix();
block->repixNeighbors();
editBlock->setPix(block);
}
bool Scene::inScene(qreal x, qreal y)
{
return (x >= 0 && y >= 0) && ( x < map->getGraphicWidth() && y < map->getGraphicHeight());
}
Scene::Scene() {
map = nullptr;
}
Scene::~Scene() {
if (map != nullptr)
delete map;
}
| true |
7072f42cfcfb13afbef1ffcbba9d26d980fe430a | C++ | aary/buck-shared-library-error-report | /test.cpp | UTF-8 | 276 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <cassert>
#include <tbb/concurrent_queue.h>
int main() {
auto q = tbb::concurrent_queue<int>{};
q.push(1);
auto top_value = int{};
assert(q.try_pop(top_value));
assert(top_value == 1);
assert(q.empty());
return 0;
}
| true |
801d5a50362ac6c5b7db4fbbdc6fe4d49e25f9b3 | C++ | SkilletHalestorm/Kuzmenko_Oleg | /PACMAN 2.0/GameLoop.cpp | UTF-8 | 556 | 2.5625 | 3 | [] | no_license | #include "GameLoop.h"
#include "Player.h"
#include <conio.h>
#include "Field.h"
void GameLoop::Start()
{
Player player;
player.PlaceOnField(1, 1);
Field field;
field.CreateField();
while (true)
{
if (_kbhit())
{
keyButton = _getch();
switch (keyButton)
{
case 'd':
{
player.MoveRight();
break;
}
case 's':
{
player.MoveDown();
break;
}
case 'a':
{
player.MoveLeft();
break;
}
case 'w':
{
player.MoveUp();
break;
}
}
}
}
} | true |
09c246a3ca2cf86ac688010a5e61d5f0836285aa | C++ | wataruiwabuchi/competitive_programming | /atcoder/abc137_c.cpp | UTF-8 | 648 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;
#define MOD int(1e9 + 7)
int main()
{
int N;
vector<string> S;
map<string, long long> mp;
long long count = 0;
cin >> N;
for (int i = 0; i < N; i++)
{
string t;
cin >> t;
sort(t.begin(), t.end());
auto itr = mp.find(t);
if (itr != mp.end())
mp[t] += 1;
else
mp[t] = 1;
}
for (auto itr = mp.begin(); itr != mp.end(); ++itr)
count += itr->second * (itr->second - 1) / 2;
cout << count << endl;
} | true |
7613309c144561d022efbd1e6f26b6bb47007547 | C++ | Oksanatishka/42_Piscine_CPP | /D08 - STL/ex03/includes/Minus.hpp | UTF-8 | 368 | 2.609375 | 3 | [] | no_license | #ifndef MINUS_HPP
#define MINUS_HPP
#include <ICommands.hpp>
class Minus : public ICommands {
public:
Minus( void );
Minus( std::list<int>::iterator & );
Minus( const Minus &toCopy );
virtual ~Minus( void );
Minus &operator=( const Minus &toCopy );
virtual void exec( void );
private:
std::list<int>::iterator *_it;
};
#endif // End of MINUS_HPP
| true |
c600fb371036a120b82ed3eed7c8a7e97f77ac69 | C++ | topcodingwizard/code | /zerojudge/d579.cpp | UTF-8 | 689 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int main() {
char a[50];
while (memset(a, -1, sizeof(a)) && fgets(a, sizeof(a), stdin)) {
int i, count = 5;
for (i = 0; a[i] != '.' && a[i] > 0 && a[i] != '\n'; i++)
;
if (a[i] != '.') {
a[i] = '.';
count--;
}
for (i; a[i] > 0 && a[i] != '\n'; i++) count--;
while (count--) a[i++] = '0';
printf("|");
for (int j = 0; a[j] > 0 && a[j] != '\n'; j++) printf("%c", a[j]);
printf("|=");
if (a[0] != '-') printf("%c", a[0]);
for (int j = 1; a[j] > 0 && a[j] != '\n'; j++) printf("%c", a[j]);
printf("\n");
}
}
| true |
cbb879fa65e7547a33f34c8a635f42921a151824 | C++ | Kheya28/CPP | /Graph/Graph problem solutions/LightOJ - 1049(One Way Roads).cpp | UTF-8 | 1,280 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define vec2 vector<vector<ll> >
#define vec1 vector<ll>
ll maxNode=101;
ll total=0;
ll c[101][101];
ll mark[101];
ll ans;
ll s;
void bfs(vec2 &g)
{
ll tot1=0;
vector<ll>mark(maxNode);
queue<ll>q;
q.push(s);
mark[s]=1;
while(q.empty()==0)
{
ll p=q.front();
q.pop();
for(ll i=0;i<g[p].size();i++)
{
ll x=g[p][i];
if(mark[x]==0)
{
q.push(x);
mark[x]=1;
//cout<<"p"<<endl;
tot1+=c[p][x];
}
}
}
//cout<<tot1<<endl;
ans=min(tot1,total-tot1);
}
int main()
{
ll t;
cin>>t;
for(ll tc=1;tc<=t;tc++)
{
total=0;
ll n;
cin>>n;
vec2 g(101);
for(ll i=0;i<=100;i++)
{
for(ll j=0;j<=100;j++)
{
c[i][j]=0;
}
}
for(ll i=1;i<=n;i++)
{
ll x,y,z;
cin>>x>>y>>z;
total+=z;
g[x].push_back(y);
if(i==1)
s=y;
else
g[y].push_back(x);
c[y][x]=z;
}
//cout<<total<<endl;
bfs(g);
//cout<<ans<<endl;
cout<<"Case "<<tc<<": "<<ans<<endl;
}
}
/*
input:
2
3
1 3 1
1 2 1
3 2 1
3
1 3 1
1 2 5
3 2 1
output:
Case 1: 1
Case 2: 2
*/
| true |
7df1274b6134855910fcb399403d80060425da0c | C++ | claytongreen/Compiler | /Source/Compiler/semantic_analyzer.cpp | UTF-8 | 3,185 | 2.5625 | 3 | [] | no_license | // Author: Clayton Green (kgreen1@unbc.ca)
// Visual Studio complains about using fopen() because it is deprecated and
// suggests using fopen_s() but G++ only has fopen().
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "ast_node_full_visitor.h"
#include "ast_node_init_visitor.h"
#include "semantic_analyzer.h"
SemanticAnalyzer::SemanticAnalyzer(ASTNode *root,
const std::string &filename,
Administrator *administrator)
: root_(root), symbol_table_(), administrator_(administrator),
filename_(filename) {
error_free_ = true;
}
void SemanticAnalyzer::InitTraversal() {
ASTNodeInitVisitor *visitor = new ASTNodeInitVisitor(&symbol_table_, filename_, administrator_);
root_->Accept(visitor);
error_free_ = visitor->error_free();
// Make sure "int main(void)" is the last declaration
const FunctionDeclarationNode *last_declaration = dynamic_cast<const FunctionDeclarationNode*>((symbol_table_.identifier_table_.end()-1)->DecPtr);
if (last_declaration == NULL) {
administrator_->messenger()->AddError(filename_, 0, "Last Declaration must be 'int main(void)'");
error_free_ = false;
} else if (last_declaration->type() != Token::INT ||
Administrator::spelling_table[last_declaration->identifier()].compare("main") != 0 ||
last_declaration->parameters() != NULL) {
administrator_->messenger()->AddError(filename_, last_declaration->line_number(), "Last Declaration must be 'int main(void)'");
error_free_ = false;
}
administrator_->messenger()->PrintMessage(symbol_table_.ToString());
}
void SemanticAnalyzer::FullTraversal() {
ASTNodeFullVisitor *visitor = new ASTNodeFullVisitor(&symbol_table_, filename_, administrator_);
root_->Accept(visitor);
error_free_ = visitor->error_free();
}
SemanticAnalyzer::SymbolTable::SymbolTable() : acces_table_(), identifier_table_() {
InitSymbolTable();
}
void SemanticAnalyzer::SymbolTable::InitSymbolTable() {
acces_table_.reserve(Administrator::spelling_table.size());
acces_table_.assign(Administrator::spelling_table.size(), 0);
SymbolTable::IdentificationTableEntry entry;
entry.L = 0;
entry.DecPtr = NULL;
entry.Next = 0;
entry.LexI = -1;
identifier_table_.push_back(entry);
}
std::string SemanticAnalyzer::SymbolTable::ToString() const {
std::string table = "Symbol Table\nIdentifier Table:\nIdI: L DecPtr Next LexI Identifier:\n";
int count = 0;
auto it = identifier_table_.begin();
const auto end = identifier_table_.end();
char buf[50];
while (it != end) {
if (it->LexI == -1) {
sprintf(buf, "%-5i%-3i%-7s%-5i%-5i%-12s\n", count++, it->L, " -", it->Next, -1, "NULL");
table += buf;
} else {
sprintf(buf, "%-5i%-3i%-7s%-5i%-5i%-12s\n", count++, it->L, " -", it->Next, it->LexI, Administrator::spelling_table[it->LexI].c_str());
table += buf;
}
++it;
}
table += "\nAccess Table:\nIdentifier: LexI: IdI\n";
count = 0;
for (unsigned int i = 0; i < acces_table_.size(); ++i) {
sprintf(buf, "%-12s%-6i%-4i\n", Administrator::spelling_table[i].c_str(), i, acces_table_.at(i));
table += buf;
}
return table;
}
| true |
deb48ebdfed956a7ae218154a76caeca3446ee27 | C++ | juicetin/superstickmanpt2 | /obstacle.cpp | UTF-8 | 516 | 2.75 | 3 | [] | no_license | #include "obstacle.h"
Obstacle::Obstacle(obstacleInfo obstacle_info, gameInfo *game_info) :
m_y(obstacle_info.start_y), m_spacing(obstacle_info.spacing),
m_speed(obstacle_info.speed), m_game_info(game_info),
m_obstacle_info(obstacle_info)
{
}
int Obstacle::getY() const
{
return m_y;
}
int Obstacle::getSpacing() const
{
return m_spacing;
}
int Obstacle::getX() const
{
return m_x;
}
void Obstacle::setX(int x)
{
m_x = x;
}
void Obstacle::setSpacing(int spacing)
{
m_spacing = spacing;
}
| true |
8c913e6089f6b30c74f7a4d574f6d622b48c5d68 | C++ | payaldhakulkar/cv_code | /blend.cpp | UTF-8 | 1,324 | 2.515625 | 3 | [] | no_license | #include<opencv/highgui.h>
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char **argv)
{
int i, j;
Mat image1, image2;
image1 = imread("/home/payald/opencv/opencv/samples/data/board.jpg", IMREAD_GRAYSCALE);
image2 = imread("/home/payald/opencv/opencv/samples/data/aero1.jpg", IMREAD_GRAYSCALE);
imshow("Image1", image1);
waitKey(0);
imshow("Image2", image2);
waitKey(0);
unsigned char *temp1 = (unsigned char *)(image1.data);
unsigned char *temp2 = (unsigned char *)(image2.data);
//unsigned char *new_image = (unsigned char *)(ouput_image.data);
Size s = image1.size();
int width = s.width;
int height = s.height;
Mat ouput_image(height,width, CV_8UC1); //Scalar(0,0,0));
for (i=0 ; i<height ; i++)
{
for(j=0 ; j<width ; j++)
{
if(temp1[(i*width)+j] + temp2[(i*width)+j] > 255)
ouput_image.data[(i*width)+j] = 255;
else
ouput_image.data[(i*width)+j] = temp1[(i*width)+j] + temp2[(i*width)+j];
}
}
Size out_size = ouput_image.size();
int out_width = out_size.width;
int out_height = out_size.height;
printf("Output w and h are %d %d\n", out_width, out_height);
imshow("Blend Image", ouput_image);
waitKey(0);
//printf("Pointer value %d\n", temp[400]);
return 0;
}
| true |
32180c1d9d43911ef6a0f8f0c39ae71cf3e38d22 | C++ | ksaveljev/UVa-online-judge | /10299.cpp | UTF-8 | 550 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int phi(int n) {
int result = n;
if (n == 1)
return 0;
if (n % 2 == 0) {
while (n % 2 == 0)
n /= 2;
result -= result / 2;
}
for (int i = 3, sq = sqrt(n); i <= sq; i += 2) {
if (n % i == 0) {
while (n % i == 0)
n /= i;
result -= result / i;
}
}
if (n > 1)
result -= result / n;
return result;
}
int main(void) {
int n;
while (cin >> n) {
if (n == 0)
break;
cout << phi(n) << endl;
}
return 0;
}
| true |
e8b4ffcfd3cfe8a9615c74de7662ac573022a394 | C++ | jesuswr/Multilayer-Perceptron | /src/multilayer_perceptron.cpp | UTF-8 | 5,361 | 2.625 | 3 | [
"MIT"
] | permissive | #include "multilayer_perceptron.hpp"
#include "perceptron.hpp"
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <iostream>
using namespace std;
multilayer_perceptron::multilayer_perceptron(int inp_sz, int hidden_sz, int out_sz,
long double etha, long double alpha, long double w_range, long double a) {
// Set rand seed so we can set random weights
srand(time(NULL));
// Create perceptrons in the hidden layer
for (int i = 0; i < hidden_sz; ++i) {
perceptron aux(inp_sz, etha, alpha, w_range, a);
hidden_layer.push_back(aux);
}
// Create perceptrons in the output layer
for (int i = 0; i < out_sz; ++i) {
perceptron aux(hidden_sz, etha, alpha, w_range, a);
output_layer.push_back(aux);
}
}
void multilayer_perceptron::propagate_forward(const vector<long double> &inp) {
int hidden_sz = hidden_layer.size();
int output_sz = output_layer.size();
vector<long double> hidden_y(hidden_sz);
// Calculate the output of the hidden layer and save it, using the input
for (int i = 0; i < hidden_sz; ++i) {
hidden_layer[i].sigma(inp);
hidden_y[i] = hidden_layer[i].get_y();
}
// Calculate the output of the output layer using the hidden layer output
for (int i = 0; i < output_sz; ++i) {
output_layer[i].sigma(hidden_y);
}
}
void multilayer_perceptron::propagate_backward(const vector<long double> &d) {
int hidden_sz = hidden_layer.size();
int output_sz = output_layer.size();
// Calculate local gradient of output layer with the desired output
for (int i = 0; i < output_sz; ++i) {
output_layer[i].compute_output_gradient(d[i]);
}
// Calculate local gradient of hidden layer with the local gradients
// of the output layer
for (int i = 0; i < hidden_sz; ++i) {
long double sum_grad_w = 0;
for (int j = 0; j < output_sz; ++j) {
sum_grad_w +=
output_layer[j].get_local_gradient() * output_layer[j].get_w(i);
}
hidden_layer[i].compute_hidden_gradient(sum_grad_w);
}
}
void multilayer_perceptron::update_weights(const vector<long double> &inp) {
int hidden_sz = hidden_layer.size();
int output_sz = output_layer.size();
vector<long double> hidden_y(hidden_sz);
// Train the hidden layer and save their output to train the output layer
for (int i = 0; i < hidden_sz; ++i) {
hidden_layer[i].train(inp);
hidden_y[i] = hidden_layer[i].get_y();
}
// Train the output layer with the hidden layer output
for (int i = 0; i < output_sz; ++i) {
output_layer[i].train(hidden_y);
}
}
error_data multilayer_perceptron::train(input_data train_data, input_data test_data,
int num_epochs) {
vector<long double> train_error, test_error;
int n = train_data.size();
int m = test_data.size();
int out_sz = output_layer.size();
for (int k = 0; k <= num_epochs; ++k) {
long double avg_error_train = 0, avg_error_test = 0;
// Get output with testing data and compute average error
for (int i = 0; i < m; ++i) {
propagate_forward(test_data[i].first);
for (int j = 0; j < out_sz; ++j) {
long double e = test_data[i].second[j] - output_layer[j].get_y();
avg_error_test += e * e;
}
}
avg_error_test = avg_error_test / (2.0 * m);
test_error.push_back(avg_error_test);
// Get output with training data and compute average error
for (int i = 0; i < n; ++i) {
propagate_forward(train_data[i].first);
for (int j = 0; j < out_sz; ++j) {
long double e = train_data[i].second[j] - output_layer[j].get_y();
avg_error_train += e * e;
}
}
avg_error_train = avg_error_train / (2.0 * n);
train_error.push_back(avg_error_train);
// Train the perceptrons with training data
for (int i = 0; i < n; ++i) {
propagate_forward(train_data[i].first);
propagate_backward(train_data[i].second);
update_weights(train_data[i].first);
}
printf("Cycle number %d complete.\n", k);
}
return {train_error, test_error};
}
long double multilayer_perceptron::test1(input_data test_data) {
int out_sz = output_layer.size();
int n = test_data.size();
long double percentage = 0;
for (int i = 0; i < n; ++i) {
// Get the output with the test data
propagate_forward(test_data[i].first);
bool good = true;
for (int j = 0; j < out_sz; ++j) {
long double y = output_layer[j].get_y();
long double d = test_data[i].second[j];
if ( y >= 0.9 ) {
// if output is >= 0.9 but desired output is 0, is bad
if ( d <= 0.1 ) {
good = false;
}
}
else if ( y <= 0.1 ) {
// if output is <= 0.1 but desired output is 1, is bad
if ( d >= 0.9 ) {
good = false;
}
}
else {
// if 0.1 < output < 0.9, is bad
good = false;
}
}
if ( good ) {
percentage++;
}
}
return percentage / n;
}
long double multilayer_perceptron::test2(input_data test_data) {
int out_sz = output_layer.size();
int n = test_data.size();
long double percentage = 0;
for (int i = 0; i < n; ++i) {
propagate_forward(test_data[i].first);
long double mx = -1;
int mxi;
for (int j = 0; j < out_sz; ++j) {
long double y = output_layer[j].get_y();
// Get the index of the neuron with max output
if ( mx < y ) {
mx = y;
mxi = j;
}
}
// If the number that the neurn represents is 1 in the desired output
// sum a good classification
if ( test_data[i].second[mxi] > 0.9 ) {
percentage++;
}
}
return percentage / n;
}
| true |
f5250b65be5c1ece0a50fd0850c7c30408b174da | C++ | binism/MyPainter | /src/lineclip.cpp | UTF-8 | 3,734 | 2.84375 | 3 | [] | no_license | #include "lineclip.h"
LineClip::LineClip(QObject *parent) : Shape(parent){
shapeName = "LineClip";
shapeCode = Shape::LineClip;
isUsedTag = false;
}
OutCode LineClip::ComputeOutCode(QPoint p){
OutCode code;
code = INSIDE; // initialised as being inside of [[clip window]]
if (p.x() < left) // to the left of clip window
code |= LEFT;
else if (p.x() > right) // to the right of clip window
code |= RIGHT;
if (p.y() < top) // below the clip window
code |= BOTTOM;
else if (p.y() > bottom) // above the clip window
code |= TOP;
return code;
}
bool LineClip::CohenSutherlandLineClip(Shape *line){
QPoint s = line->getStart();
QPoint e = line->getEnd();
OutCode outcode0 = ComputeOutCode(s);
OutCode outcode1 = ComputeOutCode(e);
bool accept = false;
while(true){
if (!(outcode0 | outcode1)) { // Bitwise OR is 0. Trivially accept and get out of loop
accept = true;
break;
}
else if(outcode0 & outcode1){ // Bitwise AND is not 0. Trivially reject and get out of loop
break;
} else {
s = line->getStart();
e = line->getEnd();
// failed both tests, so calculate the line segment to clip
// from an outside point to an intersection with clip edge
//QPoint tmp;
// At least one endpoint is outside the clip rectangle; pick it.
OutCode outcodeOut = outcode0 ? outcode0 : outcode1;
// Now find the intersection point;
// use formulas y = s.y() + slope * (x - s.x()), x = s.x() + (1 / slope) * (y - s.y())
int x= 0,y = 0;
if (outcodeOut & TOP) { // point is above the clip rectangle
x = s.x() + (e.x() - s.x()) * (bottom - s.y()) / (e.y() - s.y());
y = bottom;
}else if (outcodeOut & BOTTOM) { // point is below the clip rectangle
x = s.x() + (e.x() - s.x()) * (top - s.y()) / (e.y() - s.y());
y = top;
} else if (outcodeOut & RIGHT) { // point is to the right of clip rectangle
y = s.y() + (e.y() - s.y()) * (right - s.x()) / (e.x() - s.x());
x = right;
} else if (outcodeOut & LEFT) { // point is to the left of clip rectangle
y = s.y() + (e.y() - s.y()) * (left - s.x()) / (e.x() - s.x());
x = left;
}
// Now we move outside point to intersection point to clip
// and get ready for next pass.
QPoint tmp;
if (outcodeOut == outcode0) {
tmp.setX(x);
tmp.setY(y);
line->setStart(tmp);
line->setEnd(e);
outcode0 = ComputeOutCode(tmp);
} else {
tmp.setX(x);
tmp.setY(y);
line->setStart(s);
line->setEnd(tmp);
outcode1 = ComputeOutCode(tmp);
}
}
}
return accept;
}
bool LineClip::isUsed(){
return isUsedTag;
}
void LineClip::paint(QPainter &painter) const{
//painter.drawPoint(tagPoint);
QPoint p0, p1, p2, p3;
p0.setX(start.x());
p0.setY(start.y());
p1.setX(start.x());
p1.setY(end.y());
p2.setX(end.x());
p2.setY(end.y());
p3.setX(end.x());
p3.setY(start.y());
drawLineDDA(painter,p0,p1);
drawLineDDA(painter,p1,p2);
drawLineDDA(painter,p2,p3);
drawLineDDA(painter,p3,p0);
return;
}
void LineClip::setUsedTrue(){
isUsedTag = true;
}
void LineClip::setUsedFalse(){
isUsedTag = false;
}
| true |
5137192044526b2a951bd070363751b95cfceca1 | C++ | davisking/dlib | /tools/imglab/src/convert_idl.cpp | UTF-8 | 4,269 | 2.671875 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
#include "convert_idl.h"
#include "dlib/data_io.h"
#include <iostream>
#include <string>
#include <dlib/dir_nav.h>
#include <dlib/time_this.h>
#include <dlib/cmd_line_parser.h>
using namespace std;
using namespace dlib;
namespace
{
using namespace dlib::image_dataset_metadata;
// ----------------------------------------------------------------------------------------
inline bool next_is_number(std::istream& in)
{
return ('0' <= in.peek() && in.peek() <= '9') || in.peek() == '-' || in.peek() == '+';
}
int read_int(std::istream& in)
{
bool is_neg = false;
if (in.peek() == '-')
{
is_neg = true;
in.get();
}
if (in.peek() == '+')
in.get();
int val = 0;
while ('0' <= in.peek() && in.peek() <= '9')
{
val = 10*val + in.get()-'0';
}
if (is_neg)
return -val;
else
return val;
}
// ----------------------------------------------------------------------------------------
void parse_annotation_file(
const std::string& file,
dlib::image_dataset_metadata::dataset& data
)
{
ifstream fin(file.c_str());
if (!fin)
throw dlib::error("Unable to open file " + file);
bool in_quote = false;
int point_count = 0;
bool in_point_list = false;
bool saw_any_points = false;
image img;
string label;
point p1,p2;
while (fin.peek() != EOF)
{
if (in_point_list && next_is_number(fin))
{
const int val = read_int(fin);
switch (point_count)
{
case 0: p1.x() = val; break;
case 1: p1.y() = val; break;
case 2: p2.x() = val; break;
case 3: p2.y() = val; break;
default:
throw dlib::error("parse error in file " + file);
}
++point_count;
}
char ch = fin.get();
if (ch == ':')
continue;
if (ch == '"')
{
in_quote = !in_quote;
continue;
}
if (in_quote)
{
img.filename += ch;
continue;
}
if (ch == '(')
{
in_point_list = true;
point_count = 0;
label.clear();
saw_any_points = true;
}
if (ch == ')')
{
in_point_list = false;
label.clear();
while (fin.peek() != EOF &&
fin.peek() != ';' &&
fin.peek() != ',')
{
char ch = fin.get();
if (ch == ':')
continue;
label += ch;
}
}
if (ch == ',' && !in_point_list)
{
box b;
b.rect = rectangle(p1,p2);
b.label = label;
img.boxes.push_back(b);
}
if (ch == ';')
{
if (saw_any_points)
{
box b;
b.rect = rectangle(p1,p2);
b.label = label;
img.boxes.push_back(b);
saw_any_points = false;
}
data.images.push_back(img);
img.filename.clear();
img.boxes.clear();
}
}
}
// ----------------------------------------------------------------------------------------
}
void convert_idl(
const command_line_parser& parser
)
{
cout << "Convert from IDL annotation format..." << endl;
dlib::image_dataset_metadata::dataset dataset;
for (unsigned long i = 0; i < parser.number_of_arguments(); ++i)
{
parse_annotation_file(parser[i], dataset);
}
const std::string filename = parser.option("c").argument();
save_image_dataset_metadata(dataset, filename);
}
| true |
6d1ca0b8cc5a58ebc48ec16427cae4eeaf8f0f4f | C++ | rkokan/HackerRank | /Search/Sherlock and Array/main.cpp | UTF-8 | 940 | 2.734375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int T;
cin >> T;
while(T--){
int N ;
cin >> N;
int *A;
A = (int*)malloc(N*sizeof(int));
long long int sum = 0;
for(int i = 0 ; i < N ; i++){
cin >> A[i];
sum += A[i];
}
long long int pom_sum = 0;
sum -= A[0];
if(0 == sum || sum + 2*A[0] - A[N-1] == 0)
cout << "YES" << endl;
else{
int index = 0;
for(int i = 1 ; i < N ; i++){
pom_sum += A[i-1];
sum -= A[i];
if(pom_sum == sum){
cout << "YES" << endl;
index = 1;
break;
}
}
if(index == 0)
cout << "NO" << endl;
}
}
return 0;
}
| true |
c1c0812f1ccd109aa7dc18884e56f9ce64c49c70 | C++ | abel-souss/aurora | /math/mathlib/src/geometry/triangle/triangle2.cpp | UTF-8 | 9,018 | 2.90625 | 3 | [] | no_license | #include "geometry/triangle/triangle2.h"
tri2_t tri2_new (const vec2_t* pt1_pi, const vec2_t* pt2_pi, const vec2_t* pt3_pi)
{
tri2_t tri;
vec2_copy(&(tri.pts[0]), *pt1_pi);
vec2_copy(&(tri.pts[1]), *pt2_pi);
vec2_copy(&(tri.pts[2]), *pt3_pi);
return tri;
}
void tri2_set (tri2_t* tri_po, const vec2_t* pt1_pi, const vec2_t* pt2_pi, const vec2_t* pt3_pi)
{
vec2_copy(&(tri_po->pts[0]), *pt1_pi);
vec2_copy(&(tri_po->pts[1]), *pt2_pi);
vec2_copy(&(tri_po->pts[2]), *pt3_pi);
}
tri2_t tri2_scale (const tri2_t* tri_pi, const double n_i)
{
tri2_t tri;
vec2_t center;
int i;
center.x = (tri_pi->pts[0].x + tri_pi->pts[1].x + tri_pi->pts[2].x) / 3.0;
center.y = (tri_pi->pts[0].y + tri_pi->pts[1].y + tri_pi->pts[2].y) / 3.0;
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_sum(center, vec2_scale(vec2_diff(tri_pi->pts[i], center), n_i));
}
return tri;
}
tri2_t tri2_move (const tri2_t* tri_pi, const vec2_t* vec_pi)
{
tri2_t tri;
int i;
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_sum(tri_pi->pts[i], *vec_pi);
}
return tri;
}
double tri2_perimeter (const tri2_t* tri_pi)
{
double sides[3];
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
return sides[0] + sides[1] + sides[2];
}
double tri2_area (const tri2_t* tri_pi)
{
double sides[3];
double s;
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
s = (sides[0] + sides[1] + sides[2]) / 2.0;
return math_sqrt(s * (s - sides[0]) * (s - sides[1]) * (s - sides[2]));
}
tri2_t tri2_rotate_deg (const tri2_t* tri_pi, const vec2_t* org_i, const double r)
{
double a = math_deg_to_rad(r);
double cosa = math_cos_rad(a);
double sina = math_sin_rad(a);
tri2_t tri;
int i = 0;
if (org_i != NULL) {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_diff(tri_pi->pts[i], *org_i);
tri.pts[i] = vec2_new(cosa * tri.pts[i].x - sina * tri.pts[i].y, sina * tri.pts[i].x + cosa * tri.pts[i].y);
tri.pts[i] = vec2_sum(tri.pts[i], *org_i);
}
} else {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_new(cosa * tri_pi->pts[i].x - sina * tri_pi->pts[i].y, sina * tri_pi->pts[i].x + cosa * tri_pi->pts[i].y);
}
}
return tri;
}
tri2_t tri2_rotate_rad (const tri2_t* tri_pi, const vec2_t* org_i, const double r)
{
double a = r;
double cosa = math_cos_rad(a);
double sina = math_sin_rad(a);
tri2_t tri;
int i = 0;
if (org_i != NULL) {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_diff(tri_pi->pts[i], *org_i);
tri.pts[i] = vec2_new(cosa * tri.pts[i].x - sina * tri.pts[i].y, sina * tri.pts[i].x + cosa * tri.pts[i].y);
tri.pts[i] = vec2_sum(tri.pts[i], *org_i);
}
} else {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_new(cosa * tri_pi->pts[i].x - sina * tri_pi->pts[i].y, sina * tri_pi->pts[i].x + cosa * tri_pi->pts[i].y);
}
}
return tri;
}
tri2_t tri2_rotate_orthogonal (const tri2_t* tri_pi, const vec2_t* org_i, const int direct)
{
tri2_t tri;
int i = 0;
if (direct) {
if (org_i != NULL) {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_diff(tri_pi->pts[i], *org_i);
tri.pts[i] = vec2_new(-1.0 * tri.pts[i].y, tri.pts[i].x);
tri.pts[i] = vec2_sum(tri.pts[i], *org_i);
}
} else {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_new(-1.0 * tri_pi->pts[i].y, tri_pi->pts[i].x);
}
}
} else {
if (org_i != NULL) {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_diff(tri_pi->pts[i], *org_i);
tri.pts[i] = vec2_new(tri.pts[i].y, -1.0 * tri.pts[i].x);
tri.pts[i] = vec2_sum(tri.pts[i], *org_i);
}
} else {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_new(tri_pi->pts[i].y, -1.0 * tri_pi->pts[i].x);
}
}
}
return tri;
}
tri2_t tri2_rotate_opposite (const tri2_t* tri_pi, const vec2_t* org_i)
{
tri2_t tri;
int i = 0;
if (org_i != NULL) {
for (i = 0; i < 3; ++i) {
tri.pts[i] = vec2_diff(tri_pi->pts[i], *org_i);
tri.pts[i].x = -1.0 * tri.pts[i].x;
tri.pts[i].y = -1.0 * tri.pts[i].y;
tri.pts[i] = vec2_sum(tri.pts[i], *org_i);
}
} else {
tri.pts[i].x = -1.0 * tri_pi->pts[i].x;
tri.pts[i].y = -1.0 * tri_pi->pts[i].y;
}
return tri;
}
int tri2_is_valid (const tri2_t* tri_pi)
{
double sides[3];
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
return ((sides[0] + sides[1]) > sides[2]) &&
((sides[0] + sides[2]) > sides[1]) &&
((sides[1] + sides[2]) > sides[0]);
}
int tri2_is_right (const tri2_t* tri_pi)
{
double sides[3];
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
sides[0] *= sides[0];
sides[1] *= sides[1];
sides[2] *= sides[2];
return ((sides[0] + sides[1]) == sides[2]) ||
((sides[0] + sides[2]) == sides[1]) ||
((sides[1] + sides[2]) == sides[0]);
}
int tri2_is_equilateral (const tri2_t* tri_pi)
{
double sides[3];
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
return (sides[0] == sides[1]) && (sides[0] == sides[2]);
}
int tri2_is_isosceles (const tri2_t* tri_pi)
{
double sides[3];
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
return (sides[0] == sides[1]) ||
(sides[0] == sides[2]) ||
(sides[1] == sides[2]);
}
int tri2_is_scalene (const tri2_t* tri_pi)
{
double sides[3];
sides[0] = vec2_distance(tri_pi->pts[0], tri_pi->pts[1]);
sides[1] = vec2_distance(tri_pi->pts[1], tri_pi->pts[2]);
sides[2] = vec2_distance(tri_pi->pts[2], tri_pi->pts[0]);
return (sides[0] != sides[1]) &&
(sides[0] != sides[2]) &&
(sides[1] != sides[2]);
}
int tri2_is_congruent (const tri2_t* tri1_pi, const tri2_t* tri2_pi)
{
double sides1[3], sides2[3];
int i, j, idx1, idx2;
int congruent;
sides1[0] = vec2_distance(tri1_pi->pts[0], tri1_pi->pts[1]);
sides1[1] = vec2_distance(tri1_pi->pts[1], tri1_pi->pts[2]);
sides1[2] = vec2_distance(tri1_pi->pts[2], tri1_pi->pts[0]);
sides2[0] = vec2_distance(tri2_pi->pts[0], tri2_pi->pts[1]);
sides2[1] = vec2_distance(tri2_pi->pts[1], tri2_pi->pts[2]);
sides2[2] = vec2_distance(tri2_pi->pts[2], tri2_pi->pts[0]);
congruent = 0;
for (i = 0; i < 3; ++i) {
if (sides1[0] == sides2[i]) {
congruent = 1;
idx1 = i;
break;
}
}
if (!congruent) {
return 0;
}
congruent = 0;
for (i = 0; i < 3, i != idx1; ++i) {
if (sides1[1] == sides2[i]) {
congruent = 1;
idx2 = i;
break;
}
}
if (!congruent) {
return 0;
}
congruent = 0;
for (i = 0; i < 3, i != idx1, i != idx2; ++i) {
if (sides1[2] == sides2[i]) {
congruent = 1;
break;
}
}
return congruent;
}
int tri2_is_similar (const tri2_t* tri1_pi, const tri2_t* tri2_pi)
{
double sides1[3], sides2[3];
double ratios[9];
int i, j;
sides1[0] = vec2_distance(tri1_pi->pts[0], tri1_pi->pts[1]);
sides1[1] = vec2_distance(tri1_pi->pts[1], tri1_pi->pts[2]);
sides1[2] = vec2_distance(tri1_pi->pts[2], tri1_pi->pts[0]);
sides2[0] = vec2_distance(tri2_pi->pts[0], tri2_pi->pts[1]);
sides2[1] = vec2_distance(tri2_pi->pts[1], tri2_pi->pts[2]);
sides2[2] = vec2_distance(tri2_pi->pts[2], tri2_pi->pts[0]);
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
ratios[(3 * i) + j] = sides1[i] / sides2[j];
}
}
if ((ratios[0] == ratios[4] == ratios[8])
|| (ratios[0] == ratios[5] == ratios[7])
|| (ratios[1] == ratios[3] == ratios[8])
|| (ratios[1] == ratios[5] == ratios[6])
|| (ratios[2] == ratios[3] == ratios[7])
|| (ratios[2] == ratios[4] == ratios[6])) {
return 1;
}
return 0;
}
| true |
2f27ff42d1d5ff938354c5508e4c166f72ab0c37 | C++ | loobahpng/programming_practice | /CPE/20170523_Q2.cpp | UTF-8 | 931 | 2.9375 | 3 | [] | no_license | // 2017/05/23 Q2 12195: Jingle Composing
#include <iostream>
#include <string>
using namespace std;
int main(){
string input;
cin>>input;
while (input!="*"){
int correct=0; //number of measures with correct duration
int duration=0; //make full duration 64
for (int i=0;i<input.size();i++){
if (i==0) continue;
if (input[i]=='W') duration=duration+64;
if (input[i]=='H') duration=duration+32;
if (input[i]=='Q') duration=duration+16;
if (input[i]=='E') duration=duration+8;
if (input[i]=='S') duration=duration+4;
if (input[i]=='T') duration=duration+2;
if (input[i]=='X') duration=duration+1;
if (input[i]=='/') {
if (duration==64)correct=correct+1;
duration=0;}
}
cout<<correct<<endl;
cin>>input;
}
}
| true |
090fa606553a0d30b7e878a221314e8c2e64fc26 | C++ | Gokula-Krish/Practice | /m2.cpp | UTF-8 | 1,037 | 3.3125 | 3 | [] | no_license | #include<iostream>
#define r 1000
#define c 1000
void Spiral(int a[r][c],int m,int n)
{
int k=0,l=0;
while(k<m && l<n)
{
for(int i=k;i<n;i++)
{
printf("%d ",a[k][i]);
}k++;
for(int i=k;i<m;i++)
{
printf("%d ",a[i][n-1]);
}n--;
if(k<m)
{
for(int i=0;i>=l;--i)
{
printf("%d ",a[m-1][i]);
}m--;
}
if(l<n)
{
for(int i=m-1;i>=k;--i)
{
printf("%d ",a[i][l]);
}l++;
}
}
}
int main()
{
int ar[r][c];
int m,n;
printf("Enter the number of rows and columns :");
scanf("%d %d",&m,&n);
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&ar[i][j]);
}
}
printf("The matrix is: ");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",ar[i][j]);
}printf("\n");
}
Spiral(ar,m,n);
} | true |
32e89d3151de2c5c575d7c4894456a822236547a | C++ | aschiffer186/Analysis | /include/wrappers.hh | UTF-8 | 906 | 2.59375 | 3 | [] | no_license | #ifndef WRAPPERS_HH
#define WRAPPERS_HH
#include <gsl/gsl_spline.h>
#include <gsl/gsl_roots.h>
#include <memory>
#include <vector>
struct spline_deleter
{
void operator()(gsl_spline* ptr) const
{
gsl_spline_free(ptr);
}
};
struct root_fsolver_deleter
{
void operator()(gsl_root_fsolver* ptr) const
{
gsl_root_fsolver_free(ptr);
}
};
typedef std::shared_ptr<gsl_spline> spline_ptr;
typedef std::unique_ptr<gsl_root_fsolver, root_fsolver_deleter> fsolver_ptr;
template<typename... _ArgsTp>
spline_ptr make_spline_ptr(_ArgsTp&&... args)
{
gsl_spline* ptr = gsl_spline_alloc(std::forward<_ArgsTp>(args)...);
return spline_ptr(ptr, spline_deleter());
}
template<typename... _ArgsTp>
fsolver_ptr make_fsolver_ptr(_ArgsTp&&... args)
{
gsl_root_fsolver* ptr = gsl_root_fsolver_alloc(std::forward<_ArgsTp>(args)...);
return fsolver_ptr(ptr);
}
#endif | true |
a4555406988bd3187f01d3cb4b3d6f289b8813ae | C++ | cheerayhuang/leetcode | /isomorphic-word/isomorphic-word.cc | UTF-8 | 1,015 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
class Solution {
public:
bool isIsomorphic(string pattern, string str) {
//if (pattern.size() == 0 && str.size() == 0) return true;
if (str.size() != pattern.size()) return false;
map<char, char> dict;
map<char, char> dict2;
auto iter = str.begin();
for(auto ch : pattern) {
if ((dict.find(ch) == dict.end()) && (dict2.find(*iter) == dict2.end())) {
dict[ch] = *iter;
dict2[*iter] = ch;
++iter;
continue;
}
if (dict.count(ch) && dict[ch] != *iter) return false;
if (dict2.count(*iter) && dict2[*iter] != ch) return false;
++iter;
}
return true;
}
};
int main() {
Solution s;
cout << s.wordPattern("title", "paper") << endl;
cout << s.wordPattern("egg", "add") << endl;
return 0;
}
| true |
dcc4efdcccfa41668007f88dbf6b7938cb09e3ed | C++ | mlong-abb/libdlibxx | /src/dlibxx.cxx | UTF-8 | 996 | 2.578125 | 3 | [
"BSD-2-Clause",
"BSD-2-Clause-Views"
] | permissive | #include <dlibxx.hxx>
namespace dlibxx {
handle::handle(std::string const& name)
: name_(name)
{
this->load(name_);
}
handle::~handle()
{
this->close();
}
void handle::resolve_policy(::dlibxx::resolve rt)
{
resolve_time_ = rt;
}
void handle::set_options(::dlibxx::options opts)
{
resolve_options_ = opts;
}
void handle::load(std::string const& name)
{
this->close();
int resolve_flag =
static_cast<int>(resolve_time_) | static_cast<int>(resolve_options_);
// Clear previous errors.
::dlerror();
if (name.size() == 0)
handle_ = ::dlopen(NULL, resolve_flag);
else
handle_ = ::dlopen(name.c_str(), resolve_flag);
char* error_message = ::dlerror();
if (error_message != NULL)
{
error_ = error_message;
return;
}
name_ = name;
}
std::string const& handle::get_lib_name() const
{
return name_;
}
std::string const& handle::error() const
{
return error_;
}
void handle::close()
{
if (handle_)
::dlclose(handle_);
handle_ = nullptr;
}
} // namespace dlibxx
| true |
344d2ad759287ccaee17e0ba51d0570155005029 | C++ | snshamwow/CSC-1101-Labs | /Lab10-02.cpp | UTF-8 | 2,289 | 3.203125 | 3 | [] | no_license | //==========================================================
//
// Title: Planet Calculator
// Course: CSC 1101
// Lab Number: 10-02
// Author: Sadeem Shamoun
// Date: 10/21/19
// Description:
// Planet calclulator
//
//==========================================================
#include <cstdlib> // For several general-purpose functions
#include <fstream> // For file handling
#include <iomanip> // For formatted output
#include <iostream> // For cin, cout, and system
#include <string> // For string data type
using namespace std; // So "std::cout" may be abbreviated to "cout"
int main()
{
// Declare variables
ifstream inFile;
int lineCount;
int tokenCount;
string planet;
double diameter;
double length;
// Declare constants
const string planets = "planets.txt";
const int COLFMT1 = 11;
const int COLFMT2 = 15;
const int COLFMT3 = 15;
cout << fixed << setprecision(1);
// Attempt to open input file
inFile.open(planets);
if (!inFile.is_open())
cout << "Error: unable to open file '"
<< planets << "'." << endl << endl;
else
{
// Print read messsage
cout << "Reading tokens from file '" << planets
<< "' ..." << endl << endl;
//header
getline(inFile, planet);
cout << setw(COLFMT1) << left << "Planet"
<< setw(COLFMT2+4) << right << "Diameter"
<< setw(COLFMT3+5) << right << "Length"
<< endl;
cout << "--------------------------------------------------\n";
// Loop to read from input file
lineCount = 1;
tokenCount = 0;
while (inFile.good())
{
inFile >> planet;
inFile >> diameter;
inFile >> length;
//data
cout << setw(COLFMT1) << left << planet
<< setw(COLFMT2) << right << diameter << "(mi)"
<< setw(COLFMT3) << right << length << "(hr)"
<< endl;
//converted data
cout << setw(COLFMT1) << left << " "
<< setw(COLFMT2) << right << diameter * 5280 << "(ft)"
<< setw(COLFMT3) << right << length * 60 << "(min)"
<< endl;
lineCount = lineCount + 1;
tokenCount = tokenCount + 3;
}
// Close input file
inFile.close();
cout << endl << lineCount << " line(s) and "
<< tokenCount << " token(s) read from file '"
<< planets << "'." << endl << endl;
}
} | true |
34543b2a99e75f238cc23e7c4d0f5e1b4f466531 | C++ | siargey-pisarchyk/AICup-2015 | /Cell.h | UTF-8 | 692 | 2.890625 | 3 | [] | no_license | #ifndef CELL_H
#define CELL_H
#include "CommonDefines.h"
using namespace model;
struct Cell
{
public:
Cell() = default;
Cell(int x, int y);
bool operator<(Cell const & other) const;
bool operator==(Cell const & other) const;
bool operator!=(Cell const & other) const;
Cell GetNeibor(Direction const dir) const;
int m_x;
int m_y;
};
Cell GetCell(double const dX, double const dY, Game const & game);
Cell GetCell(Unit const & unit, Game const & game);
template <class TAr>
TAr & operator<< (TAr & ar, Cell const & cell)
{
ar << cell.m_x << " " << cell.m_y;
return ar;
}
Direction GetDirection(Cell const & from, Cell const & to);
#endif // CELL_H
| true |
4b38ab6d086a66a9ff76579f62d384bc03eb1a73 | C++ | shafitek/Parallel-Seam-Carving-on-GPU | /src/CPUCarver.cpp | UTF-8 | 2,304 | 2.703125 | 3 | [] | no_license | #include "CPUCarver.h"
CPUCarver::CPUCarver(const char *img_path, const bool &reduce)
: SeamCarver(img_path, reduce){};
void CPUCarver::computeEnergyImage() {
auto start = std::chrono::high_resolution_clock::now();
const cv::Mat img = getImage();
cv::Mat efm(img.rows, img.cols, img.type());
for(int i = 0; i < efm.rows; i++) {
for(int j = 0; j < efm.cols; j++) {
efm.at<unsigned char>(i, j) = std::abs(img.at<unsigned char>(i, j) - img.at<unsigned char>(i, j + 1)) +
std::abs(img.at<unsigned char>(i, j) - img.at<unsigned char>(i + 1, j)) +
std::abs(img.at<unsigned char>(i, j) - img.at<unsigned char>(i + 1, j + 1));
}
}
efm.convertTo(efm, CV_64F);
this->energy_img = efm;
auto end = std::chrono::high_resolution_clock::now();
double diff = (double)std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
setExecutionTime(diff);
}
void CPUCarver::computeEnergyMap()
{
auto start = std::chrono::high_resolution_clock::now();
cv::Mat &eimg = this->energy_img;
cv::Mat emap = cv::Mat::zeros(eimg.rows, eimg.cols, CV_64F);
eimg.row(0).copyTo(emap.row(0));
for (int i = 1; i < emap.rows; i++)
{
for (int j = 1; j < emap.cols - 1; j++)
{
emap.at<double>(i, j) = eimg.at<double>(i, j) +
std::min(emap.at<double>(i - 1, j - 1),
std::min(emap.at<double>(i - 1, j),
emap.at<double>(i - 1, j + 1)));
}
emap.at<double>(i, 0) = eimg.at<double>(i, 0) +
std::min(emap.at<double>(i - 1, 0),
emap.at<double>(i - 1, 1));
emap.at<double>(i, eimg.cols - 1) =
eimg.at<double>(i, eimg.cols - 1) +
std::min(emap.at<double>(i - 1, emap.cols - 2),
emap.at<double>(i - 1, emap.cols - 1));
}
this->energy_map = emap;
auto end = std::chrono::high_resolution_clock::now();
double diff = (double)std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
setExecutionTime(diff);
}
| true |
a22f9c354ba7e91812ab0cdf35b8de324f90df2e | C++ | mtaost/serial-controlled-relay-board | /arduino/Serial_Controlled_Relay_board/Serial_Controlled_Relay_board.ino | UTF-8 | 12,102 | 3.3125 | 3 | [
"MIT"
] | permissive | /*
Serial Relay Controller
Author: Michael Tao
Date: 8/9/2018
Credit to https://github.com/kroimon/Arduino-SerialCommand for inspiration for serial command line interpreter
*/
#include <SoftwareSerial.h>
#define NUM_COMMANDS 5
#define BUFFER_SIZE 64
#define MAX_COMMAND_SIZE 16
#define MAX_JUMPER_NAME_SIZE 16
#define NUM_JUMPERS 8
#define BAUD_RATE 115200
#define PROMPT "# "
#define DELIMINATOR " "
// Pin definitions
// These are specific to how the board is routed so they're here for reference
#define J1_PIN 9
#define J2_PIN 8
#define J3_PIN 7
#define J4_PIN 6
#define J5_PIN 5
#define J6_PIN 4
#define J7_PIN 3
#define J8_PIN 2
#define TX 10
#define RX 11
#define STATUS_LED 12
SoftwareSerial softSerial = SoftwareSerial(RX, TX);
// Buffer for storing input so far
char buffer[BUFFER_SIZE];
int buffPos = 0;
// Counter to newest position in command list
int numCommands = 0;
// Struct to keep track of command names and their function call
struct Command {
char name[MAX_COMMAND_SIZE];
void (*function)();
};
Command commandList[NUM_COMMANDS];
// Struct to keep track of jumper names and their state
struct Jumper {
char name[MAX_JUMPER_NAME_SIZE];
int pin;
boolean state = false; // true for on, false for off
};
Jumper jumperList[NUM_JUMPERS];
// Flag to keep track of whether we've sent the prompt or not
boolean prompt_sent;
// Terminal character (generally set to \r)
char term;
// Something for strtok_r to remember what it last tokenized. See strtok_r documentation for details
char* last;
void setup() {
pinMode(STATUS_LED, OUTPUT);
pinMode(J1_PIN, OUTPUT);
pinMode(J2_PIN, OUTPUT);
pinMode(J3_PIN, OUTPUT);
pinMode(J4_PIN, OUTPUT);
pinMode(J5_PIN, OUTPUT);
pinMode(J6_PIN, OUTPUT);
pinMode(J7_PIN, OUTPUT);
pinMode(J8_PIN, OUTPUT);
softSerial.begin(BAUD_RATE);
// Setup callbacks for commands
addCommand("help", help);
addCommand("set", set);
addCommand("status", status);
addCommand("rename", rename);
addCommand("reset", reset);
softSerial.println('\f');
softSerial.println("Serial Relay Controller ready");
blink(3);
// Set jumper values to their defaults
defaultJumperInit();
// Establish the buffer and other strings reader needs to function
initReader();
}
// In the loop, we send the prompt if it hasn't been sent, and then just call readSerial() to wait for user input
void loop() {
if (!prompt_sent) {
softSerial.print(PROMPT);
prompt_sent = true;
blink(1);
}
readSerial();
}
// Just prints user manual
void help() {
softSerial.println("Available commands: ");
softSerial.println(" set jumper_name|all {on|off}");
softSerial.println(" Sets jumper with name 'jumper_name' on or off. If jumper name is 'all', will set all jumpers.\n");
softSerial.println(" status [jumper_name]");
softSerial.println(" Shows whether jumper is on or off. If no jumper or 'all' is provided, will display all jumper statuses\n");
softSerial.println(" rename old_name new_name");
softSerial.println(" Renames a jumper. Cannot use an existing name or 'all'\n");
softSerial.println(" reset");
softSerial.println(" Resets jumper names back to defaults. Sets all jumpers to off.\n");
softSerial.println(" help");
softSerial.println(" Displays this help dialogue.");
}
// Blink method for visual confirmation that things are working. Not really used though
void blink(int i) {
while (i > 0) {
digitalWrite(STATUS_LED, HIGH);
delay(100);
digitalWrite(STATUS_LED, LOW);
delay(100);
i--;
}
}
// Sets a jumper to on or off. This is called after the "set" part of the command has been consumed, so jumperName and state are obtained
// by calling nextToken() which will consume the next two tokens (if there are any)
void set() {
char *jumperName = nextToken();
char *state = nextToken();
int jumper_index;
boolean setTo;
boolean lastState;
if (jumperName == NULL) {
softSerial.println("Missing jumper");
softSerial.println("Syntax: set jumper {on/off}");
softSerial.println(" set all {on/off}");
return;
}
if (state == NULL) {
softSerial.println("Please specify a value for state");
softSerial.println("Syntax: set jumper {on/off}");
softSerial.println(" set all {on/off}");
return;
}
if (strcmp(state, "on") == 0) {
setTo = true;
}
else if (strcmp(state, "off") == 0) {
setTo = false;
}
// If we don't match on or off, invalid state
else {
softSerial.println("Please specify either 'on' or 'off'");
return;
}
// Get the index of the jumper we're looking for
jumper_index = findJumper(jumperName);
// If we don't find the jumper name
if (jumper_index == -1) {
// If jumper name is all (case insensitive), loop through all jumpers and set them
if (strcmp(strlwr(jumperName), "all") == 0) {
for (int i = 0; i < NUM_JUMPERS; i++) {
Jumper j = jumperList[i];
lastState = j.state;
j.state = setTo;
jumperList[i] = j;
softSerial.print(j.name);
softSerial.print("\t: ");
lastState ? softSerial.print("ON ") : softSerial.print("OFF");
softSerial.print(" -> ");
setTo ? softSerial.println("ON") : softSerial.println("OFF");
updateState(i);
}
}
// Otherwise for jumper_index == -1, jumper is invalid
else {
softSerial.print(jumperName);
softSerial.println(" is not a valid jumper");
softSerial.println("Use 'status' for a list of valid jumpers");
}
}
// If we have a jumper index, set the jumper
else {
Jumper j = jumperList[jumper_index];
lastState = j.state;
j.state = setTo;
jumperList[jumper_index] = j;
softSerial.print(jumperName);
softSerial.print(": ");
lastState ? softSerial.print("ON") : softSerial.print("OFF");
softSerial.print(" -> ");
setTo ? softSerial.println("ON") : softSerial.println("OFF");
updateState(jumper_index);
}
}
// Renames a jumper, cannot name a jumper any variation of 'all' to avoid confusion with the keyword used in 'set all on/off'
void rename() {
char *oldName = nextToken();
char *newName = nextToken();
int jumperIndex;
if (oldName == NULL) {
softSerial.println("Missing jumper_name");
softSerial.println("Syntax: rename jumper_name new_name");
return;
}
if (newName == NULL) {
softSerial.println("Missing new_name");
softSerial.println("Syntax: rename jumper_name new_name");
return;
}
// Do not allow a jumper to be named "ALL"
if (strcmp(newName, "all") == 0) {
softSerial.println("Jumper cannot be named 'all'");
return;
}
jumperIndex = findJumper(oldName);
// Invalid jumper option
if (jumperIndex == -1) {
softSerial.print(oldName);
softSerial.println(" is not a valid jumper");
}
// New jumper name already exists
else if (findJumper(newName) != -1) {
softSerial.print(newName);
softSerial.println(" already exists! Please pick a different name.");
}
// Otherwise, rename jumper
else {
strcpy(jumperList[jumperIndex].name, newName);
softSerial.print(oldName);
softSerial.print(" renamed to: ");
softSerial.println(newName);
}
}
// Call init again and reset jumpers to their starting values
void reset() {
defaultJumperInit();
softSerial.println("Jumper names reset to default values");
softSerial.println("All jumpers now off");
}
// Shows the status of a jumper, or all jumpers
void status() {
char *jumperName = nextToken();
int jumperIndex;
boolean state;
// If no argument is provided, or the argument is all, list all jumpers
if (jumperName == NULL || strcmp(jumperName, "all") == 0) {
char *name;
for (int i = 0; i < NUM_JUMPERS; i++) {
state = jumperList[i].state;
name = jumperList[i].name;
softSerial.print(name);
softSerial.print("\t:");
state ? softSerial.println("ON") : softSerial.println("OFF");
}
return;
}
jumperIndex = findJumper(jumperName);
// Invalid jumper option
if (jumperIndex == -1) {
softSerial.print(jumperName);
softSerial.println(" is not a valid jumper");
}
else {
state = jumperList[jumperIndex].state;
softSerial.print(jumperName);
softSerial.print("\t:");
state ? softSerial.println("ON") : softSerial.println("OFF");
}
}
// Applies state of jumper to respective digital pin
// Assumes jumperIndex is valid
void updateState(int jumperIndex) {
boolean state;
String str;
int pin;
state = jumperList[jumperIndex].state;
pin = jumperList[jumperIndex].pin;
// softSerial.print("Wrote ");
// str = state ? "ON" : "OFF";
// softSerial.print(str);
// softSerial.print(" to pin ");
// softSerial.println(pin);
digitalWrite(pin, state);
}
// Input name of jumper, returns index of jumper in jumperList
// Returns -1 if not found
int findJumper(char *jumperName) {
int curr_jumper;
boolean found_jumper = false;
for (curr_jumper = 0; curr_jumper < NUM_JUMPERS; curr_jumper++) {
if (strcmp(jumperName, jumperList[curr_jumper].name) == 0) {
found_jumper = true;
break;
}
}
return found_jumper ? curr_jumper : -1;
}
void addCommand(const char *command, void (*function)()) {
strncpy(commandList[numCommands].name, command, MAX_COMMAND_SIZE);
commandList[numCommands].function = function;
numCommands++;
}
void readSerial() {
while (softSerial.available() > 0) {
char nextChar;
char* token;
boolean matched = false;
nextChar = softSerial.read();
// If the next character matches the term (probably '\r'), process command
if (nextChar == term) {
prompt_sent = false;
softSerial.println();
buffPos = 0;
// Tokenize what we have so far and get the first token separated by deliminator (probably " ")
token = strtok_r(buffer, DELIMINATOR, &last);
// Empty string input, ignore
if (token == NULL) {
return;
}
else {
for (int i = 0; i < NUM_COMMANDS; i++) {
if (strcmp(token, commandList[i].name) == 0) {
(*commandList[i].function)();
softSerial.println();
clearBuffer();
matched = true;
break;
}
}
}
if (matched == false) {
softSerial.print('\r');
softSerial.print(buffer);
softSerial.println(" is not a valid command");
softSerial.println("Enter 'help' for available commands\n");
clearBuffer();
}
}
// When user presses backspace, delete character off buffer and reflect change in terminal
if (nextChar == '\b') {
if (buffPos > 0) {
buffer[--buffPos] = '\0';
softSerial.print("\b \b");
}
}
// If the input character is printable, add it to the buffer and send character to terminal
if (isprint(nextChar)) {
if (buffPos < BUFFER_SIZE - 1) { // Prevent overflow and clobbering memory
buffer[buffPos++] = nextChar;
buffer[buffPos] = '\0';
softSerial.print(nextChar);
}
}
}
}
// Initialize some starting values
void initReader() {
prompt_sent = false;
term = '\r';
memset(buffer, 0, BUFFER_SIZE);
}
// Reset the buffer, easiest thing to do is to set first char in array to null terminator \0
void clearBuffer() {
buffPos = 0;
buffer[buffPos] = '\0';
}
// Consumes the next token in the command. This works since strtok_r remembers its last tokenized string if it is passed in NULL
char *nextToken() {
char *nextToken;
nextToken = strtok_r(NULL, " ", &last);
return nextToken;
}
// Initialize jumper names to default values. A little hard coded
void defaultJumperInit() {
char *names[8] = {"J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8"};
int pins[8] = {J1_PIN, J2_PIN, J3_PIN, J4_PIN, J5_PIN, J6_PIN, J7_PIN, J8_PIN};
for (int i = 0; i < NUM_JUMPERS; i++) {
strcpy(jumperList[i].name, names[i]);
Jumper j = jumperList[i];
j.state = false;
j.pin = pins[i];
jumperList[i] = j;
updateState(i);
}
}
| true |
2f026fbb44650ad1f67064aaf023cf1639c45961 | C++ | tlvb/dmx512usb_software | /src/serial.cc | UTF-8 | 2,209 | 2.515625 | 3 | [] | no_license | #include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <linux/serial.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "serial.hh"
namespace dmx512usb_software {
Serial::Serial(const std::string &device, int baudrate) {
portopen = false;
sfd = open_port(device);
if (ok)
config_port(sfd, baudrate);
}
Serial::~Serial(void) {
if (portopen)
close(sfd);
}
bool Serial::is_ok(void) {
return ok;
}
std::string Serial::get_log(void) {
return log.str();
}
int Serial::get_actual_baudrate(void) {
return baudrate;
}
int Serial::writebytes(uint8_t *data, unsigned n) {
return write(sfd, data, n);
}
int Serial::readbytes(uint8_t *data, unsigned n) {
return read(sfd, data, n);
}
int Serial::open_port(const std::string &device) {
int sfd = open(device.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (sfd == -1) {
ok = false;
log << "unable to open port \"" << device << "\"" << std::endl;
}
else {
fcntl(sfd, F_SETFL, 0);
ok = true;
log << "port \"" << device << "\" open" << std::endl;
portopen = true;
}
return sfd;
}
void Serial::config_port(int sfd, int baudrate) {
struct termios tos;
struct serial_struct ss;
int ret;
ioctl(sfd, TIOCGSERIAL, &ss);
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (baudrate / 2)) / baudrate;
this->baudrate = ss.baud_base / ss.custom_divisor;
if (this->baudrate < baudrate * 98 / 100 || this->baudrate > baudrate * 102 / 100) {
ok = false;
log << "Cannot set serial port baudrate to " << baudrate << " Closest possible is " << this->baudrate << std::endl;
}
ret = ioctl(sfd, TIOCSSERIAL, &ss);
cfsetispeed(&tos, B38400);
cfsetospeed(&tos, B38400);
tos.c_cflag &= ~(PARENB | CSTOPB | CSIZE);
tos.c_cflag |= CS8;
tos.c_cflag |= CRTSCTS;
tos.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tos.c_iflag &= ~(INPCK | IGNPAR | PARMRK | ISTRIP | IXON | IXOFF);
tos.c_iflag &= ~(IXANY | BRKINT | INLCR | IGNCR | ICRNL | IUCLC | IMAXBEL);
tos.c_oflag &= ~OPOST;
ret = tcsetattr(sfd, TCSANOW, &tos);
if (ret != 0) {
ok = false;
log << "tcsetattr returned nonzero" << std::endl;
}
}
}
| true |
13149d4b36a6697b918bd7f76d7c52b048652f6e | C++ | gaodechen/OI_History | /problems/luogu1265.cpp | UTF-8 | 880 | 2.796875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int N = 5e3 + 5;
struct Point
{
double x, y;
} p[N];
struct Item
{
int v;
double d;
Item( int v, double d ): v( v ), d( d )
{
}
bool operator < ( const Item &b ) const
{
return d > b.d;
}
} ;
inline double Distance( const Point &a, const Point &b )
{
double d1 = a.x - b.x;
double d2 = a.y - b.y;
return sqrt( d1 * d1 + d2 * d2 );
}
int n;
priority_queue< Edge > q[N];
int main()
{
freopen( "a.in", "r", stdin );
scanf( "%d", &n );
for( int i = 1; i <= n; i ++ )
cin >> p[i].x >> p[i].y;
for( int i = 1; i <= n; i ++ )
for( int j = 1; j <= n; j ++ )
q.push( Item( j, Distance( p[i], p[j] ) );
return 0;
}
| true |
f452d8a8da74a5077eee42e33c7d3837ccbbcba4 | C++ | 66112/Signal | /Sigchild/test.cc | UTF-8 | 677 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
using namespace std;
void handler(int signo)
{
if(pid_t ret=(wait(NULL)) != -1)
{
cout << "child exit process" << ret <<endl;
}
}
int main()
{
struct sigaction act,oact;
act.sa_handler=handler;
act.sa_flags=0;
sigemptyset(&act.sa_mask);
sigaction(SIGCHLD,&act,&oact);
pid_t id = fork();
if(id == 0)
{
cout << "i am child run..." << endl;
sleep(3);
_exit(1);
}
else{
while(1)
{
cout << "i am a parent:"<<getpid()<<endl;
sleep(1);
}
}
}
| true |
2118ea50176a484ce5171e9eda9a2fc91508d9ba | C++ | Jia-Joe/OJ_hihoCoder_LeetCode_Sword2Offer | /LeetCode160_166_191_198_206/L160.cpp | UTF-8 | 978 | 3.125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p1=headA, *p2=headB, *ps, *pl;
if(!p1||!p2) return NULL;
while(p1->next&&p2->next){
p1=p1->next;
p2=p2->next;
}
int dif=0;
if(!p1->next){
while(p2->next){
p2=p2->next;
dif++;
}
if(p1!=p2) return NULL;
ps=headA; pl=headB;
}
else{
while(p1->next){
p1=p1->next;
dif++;
}
if(p1!=p2) return NULL;
ps=headB; pl=headA;
}
while(dif--) pl=pl->next;
while(pl!=ps){
pl=pl->next;
ps=ps->next;
}
return pl;
}
}; | true |
e642732b79ffc4bd6230beef81aac89a8e94738a | C++ | eduaglz/RoboticsTec | /Control/Robotics/PWM.cpp | UTF-8 | 4,366 | 3.015625 | 3 | [] | no_license | /*
* PWM.cpp
*
* Created: 9/20/2015 11:58:15 PM
* Author: Eduardo
*/
#include "PWM.h"
#include <avr/io.h>
PWM::PWM() {
}
// default constructor
PWM::PWM(Timer timer, Channel channel, int frequency, int dutyCycle, int prescaler) :Frequency(frequency), DutyCycle(dutyCycle), Prescaler(prescaler)
{
// Get the address for the registers of the selected Timer and Channel
// We need to get the address for the registers:
// TCCR: Timer/Counter Control Register
// DDR: Data Direction Register ( We need to set the pin as OUTPUT )
// WGM: Waveform Generation Mode
// ICR: Input Control Register
// COM: Compare Output Mode
/**/
switch (timer) {
case TIMER_1:
ControlRegA = &TCCR1A;
ControlRegB = &TCCR1B;
DDR = &DDRB;
WGM0 = WGM10;
WGM1 = WGM11;
WGM2 = WGM12;
WGM3 = WGM13;
ICR = &ICR1;
// Set the channel to be used
switch (channel)
{
case CHANNEL_A:
OCR = &OCR1A;
COM0 = COM1A0;
COM1 = COM1A1;
OutBit = PB5;
break;
case CHANNEL_B:
OCR = &OCR1B;
COM0 = COM1B0;
COM1 = COM1B1;
OutBit = PB6;
break;
case CHANNEL_C:
OCR = &OCR1C;
COM0 = COM1C0;
COM1 = COM1C1;
OutBit = PB7;
break;
}
break;
case TIMER_3:
ControlRegA = &TCCR3A;
ControlRegB = &TCCR3B;
DDR = &DDRE;
WGM0 = WGM30;
WGM1 = WGM31;
WGM2 = WGM32;
WGM3 = WGM33;
ICR = &ICR3;
// Set the channel to be used
switch (channel)
{
case CHANNEL_A:
OCR = &OCR3A;
COM0 = COM3A0;
COM1 = COM3A1;
OutBit = PE3;
break;
case CHANNEL_B:
OCR = &OCR3B;
COM0 = COM3B0;
COM1 = COM3B1;
OutBit = PE4;
break;
case CHANNEL_C:
OCR = &OCR3C;
COM0 = COM3C0;
COM1 = COM3C1;
OutBit = PE5;
break;
}
break;
case TIMER_4:
ControlRegA = &TCCR4A;
ControlRegB = &TCCR4B;
DDR = &PORTH;
WGM0 = WGM40;
WGM1 = WGM41;
WGM2 = WGM42;
WGM3 = WGM43;
ICR = &ICR4;
// Set the channel to be used
switch (channel)
{
case CHANNEL_A:
OCR = &OCR4A;
COM0 = COM4A0;
COM1 = COM4A1;
OutBit = PH3;
break;
case CHANNEL_B:
OCR = &OCR4B;
COM0 = COM4B0;
COM1 = COM4B1;
OutBit = PH4;
break;
case CHANNEL_C:
OCR = &OCR4C;
COM0 = COM4C0;
COM1 = COM4C1;
OutBit = PH5;
break;
}
break;
case TIMER_5:
ControlRegA = &TCCR5A;
ControlRegB = &TCCR5B;
DDR = &PORTL;
WGM0 = WGM50;
WGM1 = WGM51;
WGM2 = WGM52;
WGM3 = WGM53;
ICR = &ICR5;
// Set the channel to be used
switch (channel)
{
case CHANNEL_A:
OCR = &OCR5A;
COM0 = COM5A0;
COM1 = COM5A1;
OutBit = PL3;
break;
case CHANNEL_B:
OCR = &OCR5B;
COM0 = COM5B0;
COM1 = COM5B1;
OutBit = PL4;
break;
case CHANNEL_C:
OCR = &OCR5C;
COM0 = COM5C0;
COM1 = COM5C1;
OutBit = PL5;
break;
}
break;
}
TimerSetup();
SetFrequency(frequency);
SetDutyCycle(dutyCycle);
} //PWM
// Sets the values of the control register for the Timer
void PWM::TimerSetup()
{
uint8_t prescaleMode = 0;
switch (Prescaler) {
case 0:
prescaleMode = 0;
break;
case 1:
prescaleMode = 1;
break;
case 8:
prescaleMode = 2;
break;
case 64:
prescaleMode = 3;
break;
case 256:
prescaleMode = 4;
break;
case 1024:
prescaleMode = 5;
break;
default:
prescaleMode = 1;
}
// Set WGM = 14 (Fast PWM)
// Set Output to Inverting Mode COM = 2
// Set the Timer pin to OUTPUT
noInterrupts();
*ControlRegA |= _BV(WGM1) | _BV(COM1);
*ControlRegA &= 0xFE;
*ControlRegB |= _BV(WGM3) | _BV(WGM2) | prescaleMode;
*DDR |= _BV(OutBit);
interrupts();
}
void PWM::SetFrequency(int frequency) {
int f = F_CPU / (Prescaler * frequency) - 1;
*ICR = (uint16_t)f;
}
void PWM::SetDutyCycle(float dutyCycle) {
if (dutyCycle < 0)
{
DutyCycle = 0;
*OCR = 0;
return;
}
else if (dutyCycle > 100)
DutyCycle = 100;
else
DutyCycle = dutyCycle;
//Serial.print("DutyCycle: ");
//Serial.print(dutyCycle);
//Serial.print(" ICR: ");
//uint16_t t = *ICR;
//Serial.println(DutyCycle);
//Serial.println(*ICR);
//Serial.print(" OCR: ");
//Serial.print(*OCR, DEC);
//Serial.print(" new OCR:");
//Serial.println(*OCR, DEC);
//Serial.println(*ICR, DEC);
//Serial.println(TCCR1A);
//Serial.println(*ControlRegB, DEC);
uint16_t result = (uint16_t)((DutyCycle / 100.0) * (*ICR));
//Serial.println(result);
*OCR = result;
//Serial.println(*OCR, DEC);
}
| true |
2daddec177e12f58f60d40f41b62011c884cc1d3 | C++ | heromapwrd/DesignPattern | /BehevioralPatterns/Command/Invoker.cpp | UTF-8 | 449 | 2.859375 | 3 | [] | no_license | #include "Invoker.h"
#include <iostream>
using namespace std;
Invoker::Invoker()
{
cout << endl << "Invoker Constructor!" << endl;
}
Invoker::~Invoker()
{
cout << endl << "Invoker Destructor!" << endl;
}
void Invoker::SetCommand(Command* pCommand)
{
m_pCommand = pCommand;
}
Command* Invoker::GetCommand()
{
return m_pCommand;
}
void Invoker::Invoke()
{
cout << endl << "Invoke Invoke!" << endl;
if (m_pCommand)
m_pCommand->Excute();
}
| true |
6a26005757e32bc167c885b727863d6e82db4fb1 | C++ | Thejulfi/Ouiv_Deep_Sleep | /DeepSleep_ZeroPowerConsumption/DeepSleep_ZeroPowerConsumption.ino | UTF-8 | 1,237 | 2.59375 | 3 | [] | no_license | #include "ZeroPowerManager.h"
const byte interruptPin = 1;
//FLags de gestion du mode de fonctionnement
volatile int SLEEP_FLAG; //1 si autorisé à dormir, 0 sinon
#define Rled 2
void blink() {
SLEEP_FLAG = 0;
}
void setup()
{
zpmRTCInit();
pinMode(Rled, OUTPUT);
/*
* To get to datasheet power levels the I/O must be disabled
*/
zpmPortDisableDigital();
zpmPortDisableSPI();
zpmPortDisableUSB();
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING);
SLEEP_FLAG = 0;
}
void loop()
{
/*
* Stay in each power state for about a second.
*/
if(SLEEP_FLAG){
zpmSleep();
}else{
for(int i = 0;i<10;i++){
digitalWrite(Rled, HIGH);
delay(500);
digitalWrite(Rled, LOW);
delay(500);
}
SLEEP_FLAG = 1;
}
// zpmCPUClk48M();
// delay(1000);
//
// zpmCPUClk8M();
// delay(1000);
//
// zpmCPUClk32K();
// delay(1000);
//
/*
* There is no interrupt handler (callback = NULL). Execution will
* resume from the sleep instruction.
*/
//uint32_t now = zpmRTCGetClock();
//zpmRTCInterruptAt(now + 1000, NULL);
}
| true |
73694f17fcf400707475c64bb15bdc2f7171568a | C++ | srane96/Data-Structure-and-Algorithms-Using-Cpp-and-Python | /Cpp/permutations_recursion.cpp | UTF-8 | 836 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <vector>
// print the permutations
void printPerm(std::vector<int> arr) {
for(int a:arr)
std::cout << a << " ";
std::cout << std::endl;
}
// calculate permutation of all elements of a sequence recursively
void displayPermutations(std::vector<int> arr, std::vector<int> perm, std::vector<bool> visited) {
if(perm.size() == arr.size()) {
printPerm(perm);
}
for(int i=0; i<arr.size(); i++) {
if(visited[i])
continue;
else {
perm.push_back(arr[i]);
visited[i] = true;
displayPermutations(arr, perm,visited);
visited[i] = false;
perm.pop_back();
}
}
}
int main() {
std::vector<int> arr{1,2,3,4};
std::vector<int> perm;
std::vector<bool> visited(arr.size(),false);
displayPermutations(arr,perm,visited);
}
| true |
760426b87c12a885f6d51c8ee31922fa604019ce | C++ | ihchoi95/codereview | /node.cc | UTF-8 | 1,456 | 3.46875 | 3 | [] | no_license | // Copyright 2018 <Author>
#include "node.h"
Node::Node(char data) {
prev = next = nullptr;
value = data;
return;
}
char Node::GetData() {
return value;
}
Node* Node::GetPreviousNode() {
return this->prev;
}
Node* Node::GetNextNode() {
return this->next;
}
Node* Node::InsertPreviousNode(char data) {
Node* newNode = new Node(data);
Node* oldPrevNode = this->prev;
if (oldPrevNode) {
oldPrevNode->next = newNode;
}
newNode->prev = oldPrevNode;
newNode->next = this;
this->prev = newNode;
return newNode;
}
Node* Node::InsertNextNode(char data) {
Node* newNode = new Node(data);
Node* oldNextNode = this->next;
this->next = newNode;
newNode->prev = this;
newNode->next = oldNextNode;
if (oldNextNode) {
oldNextNode->prev = newNode;
}
return newNode;
}
bool Node::ErasePreviousNode() {
Node* deleteNode = this->prev;
Node* newPrevNode = nullptr;
if (deleteNode == nullptr)
{
return false;
}
newPrevNode = deleteNode->prev;
this->prev = newPrevNode;
if (newPrevNode != nullptr) {
newPrevNode->next = this;
}
delete deleteNode;
return true;
}
bool Node::EraseNextNode() {
Node* deleteNode = this->next;
Node* newNextNode = nullptr;
if (deleteNode == nullptr) {
return false;
}
newNextNode = deleteNode->next;
this->next = newNextNode;
if (newNextNode != nullptr) {
newNextNode->prev = this;
}
delete deleteNode;
return true;
}
| true |
f96899668fde59dad0ea7b7dc338e0762ba63bb5 | C++ | marc-hanheide/cogx | /subarchitectures/comsys/branches/stable-for-binder-7/src/mercury-c++/abduction/server-mk2/StringToSlice.cc | UTF-8 | 6,093 | 2.953125 | 3 | [] | no_license | #include "StringToSlice.h"
using namespace std;
using namespace Abducer;
void
parseAndAddTermSeq(vector<Token *>::iterator & it, vector<TermPtr> & args)
{
vector<Token *>::iterator orig = it;
TermPtr arg = parseTerm(it);
if (arg) {
args.push_back(arg);
if ((*it)->type() == Comma) {
it++;
parseAndAddTermSeq(it, args);
}
}
else {
// error in the child, abort too
it = orig;
}
}
void
parseAndAddModalitySeq(vector<Token *>::iterator & it, vector<ModalityPtr> & args)
{
vector<Token *>::iterator orig = it;
ModalityPtr arg = parseModality(it);
if (arg) {
args.push_back(arg);
if ((*it)->type() == Comma) {
it++;
parseAndAddModalitySeq(it, args);
}
}
else {
// error in the child, abort too
it = orig;
}
}
Abducer::TermPtr
parseTerm(vector<Token *>::iterator & it)
{
vector<Token *>::iterator orig = it;
if ((*it)->type() == VariableName) {
VariableNameToken * varTok = (VariableNameToken *) *it;
VariableTermPtr vt = new VariableTerm();
vt->type = Variable;
vt->name = varTok->name();
it++;
return vt;
}
if ((*it)->type() == Atom) {
AtomToken * atomTok = (AtomToken *) *it;
FunctionTerm * ft = new FunctionTerm();
ft->type = Function;
ft->functor = atomTok->value();
it++;
if ((*it)->type() == OpenParenthesis) {
it++;
parseAndAddTermSeq(it, ft->args);
if ((*it)->type() == CloseParenthesis) {
// ok
it++;
return ft;
}
else {
// closing parenthesis expected
it = orig;
return NULL;
}
}
else {
// no arguments apparently
return ft;
}
}
it = orig;
return NULL;
}
Abducer::PredicatePtr
parsePredicate(vector<Token *>::iterator & it)
{
vector<Token *>::iterator orig = it;
PredicatePtr p = new Predicate();
if ((*it)->type() == Atom) {
AtomToken * psymTok = (AtomToken *) *it;
p->predSym = psymTok->value();
it++;
if ((*it)->type() == OpenParenthesis) {
it++;
parseAndAddTermSeq(it, p->args);
if ((*it)->type() == CloseParenthesis) {
it++;
if ((*it)->type() == Dot) {
// ok
it++;
return p;
}
else {
// syntax error, dot expected
it = orig;
return NULL;
}
}
else {
// closing parenthesis expected
it = orig;
return NULL;
}
}
else if ((*it)->type() == Dot) {
// ok
it++;
return p;
}
else {
// syntax error, dot expected
it = orig;
return NULL;
}
}
else {
// syntax error, atom expected
it = orig;
return NULL;
}
}
ModalisedFormulaPtr
parseModalisedFormula(vector<Token *>::iterator & it)
{
vector<Token *>::iterator orig = it;
ModalisedFormulaPtr mf = new ModalisedFormula();
vector<ModalityPtr> mod;
if ((*it)->type() == OpenCurlyBracket) {
it++;
parseAndAddModalitySeq(it, mod);
if ((*it)->type() == CloseCurlyBracket) {
// ok
it++;
mf->m = mod;
}
else {
it = orig;
return NULL;
}
}
PredicatePtr p = parsePredicate(it);
if (p) {
mf->p = p;
return mf;
}
else {
it = orig;
return NULL;
}
}
Abducer::Agent
tokenToAgent(const Token * tok)
{
// cerr << "tokenToAgent: \"" << tok->toMercuryString() << "\"" << endl;
if (tok->type() == Atom) {
AtomToken * atok = (AtomToken *) tok;
if (atok->value() == "h") {
// cerr << " human" << endl;
return human;
}
else {
// cerr << " robot" << endl;
return robot;
}
}
else {
// cerr << "not an atom!! type" << tok->type() << endl;
return human;
}
}
Abducer::ModalityPtr
parseModality(std::vector<Token *>::iterator & it)
{
vector<Token *>::iterator orig = it;
if ((*it)->type() == Atom) {
AtomToken * atomTok = (AtomToken *) *it;
if (atomTok->value() == string("i")) {
it++;
InfoModalityPtr im = new InfoModality();
im->type = Info;
return im;
}
else if (atomTok->value() == string("event")) {
it++;
EventModalityPtr em = new EventModality();
em->type = Event;
return em;
}
else if (atomTok->value() == string("intention")) {
it++;
IntentionModalityPtr im = new IntentionModality();
im->type = Intention;
return im;
}
else if (atomTok->value() == string("att")) {
it++;
AttStateModalityPtr am = new AttStateModality();
am->type = AttState;
return am;
}
else if (atomTok->value() == string("generate")) {
it++;
GenerationModalityPtr gm = new GenerationModality();
gm->type = Generation;
return gm;
}
else if (atomTok->value() == string("understand")) {
it++;
UnderstandingModalityPtr um = new UnderstandingModality();
um->type = Understanding;
return um;
}
else if (atomTok->value() == string("k")) {
it++;
KModalityPtr km = new KModality();
km->type = K;
if ((*it)->type() == OpenParenthesis) {
it++;
it++; // skip the "now" atom
it++; // skip the comma
if ((*it)->type() == Atom) {
AtomToken * shareTok = (AtomToken *) *it;
// cerr << (*it)->toMercuryString() << endl;
it++;
// cerr << (*it)->toMercuryString() << endl;
it++; // skip '('
// cerr << (*it)->toMercuryString() << endl;
if (shareTok->value() == "private") {
// cerr << "private" << endl;
km->share = Private;
km->ag = tokenToAgent(*it);
km->ag2 = km->ag;
it++;
it++; // skip ')'
}
else if (shareTok->value() == "attrib") {
// cerr << "attrib" << endl;
km->share = Attribute;
km->ag = tokenToAgent(*it);
it++;
it++; // skip ','
km->ag2 = tokenToAgent(*it);
it++;
it++; // skip ')'
}
else if (shareTok->value() == "mutual") {
// cerr << "mutual" << endl;
km->share = Mutual;
km->ag = tokenToAgent(*it);
it++;
it++; // skip ','
km->ag2 = tokenToAgent(*it);
it++;
it++; // skip ')'
}
if ((*it)->type() == CloseParenthesis) {
it++;
return km;
}
else {
it = orig;
return NULL;
}
}
else {
it = orig;
return NULL;
}
}
else {
it = orig;
return NULL;
}
}
else {
it = orig;
return NULL;
}
}
else {
it = orig;
return NULL;
}
}
| true |
7250c06e9b241792094679e2bfc17d256aacd4a7 | C++ | codingzhoushuai/lesson | /hello_namespace/Main.cpp | GB18030 | 955 | 3.265625 | 3 | [] | no_license | #include<iostream>
// #include<stdlib.h> system("pause"); ʹ÷ֹ̨
// #include<windows.h> Sleep("5000"); ʹ÷ֹ̨
using namespace std;
namespace Computer
{
int i;
void f()
{
cout << "Computer ::f " << endl;
}
}
namespace Information
{
int i;
void f()
{
cout << "Informationr ::f " << endl;
}
}
/*using namespace Computer;*/
using Computer::i;
using Computer::f; //usingָö ͵45жӦɿʹó
//using namespace Information; //using namespace Information;ռͻ
int main()
{
auto i = 100;
auto d = 3.14;
auto s = "hello";
cout << d << endl;
cout << i*100 << endl;
//auto k; ûиֵƵ
/*//Computer::i = 100;
i = 100;
cout << i << endl;
//cout << Computer::i << endl;
Information::i=200;
f();
Information::f();
Computer::f();*/
cin.get();
cin.get();
} | true |
b05e8cd23344bb1018ac8a6e4870328cca2cc811 | C++ | GDMiao/Class8 | /Class8Online/CNetwork/Protocols/MobileConnectClassReq.h | UTF-8 | 1,301 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef __GNET_MOBILECONNECTCLASSREQ_H
#define __GNET_MOBILECONNECTCLASSREQ_H
#include "rpcdefs.h"
#include "state.hxx"
namespace GNET
{
class MobileConnectClassReq : public GNET::Protocol
{
public:
enum { PROTOCOL_TYPE = 1034 };
int64_t userid;
Octets devicename;
Octets code;
public:
MobileConnectClassReq() { type = PROTOCOL_TYPE; }
MobileConnectClassReq(void*) : Protocol(PROTOCOL_TYPE) { }
MobileConnectClassReq (int64_t l_userid, const Octets& l_devicename, const Octets& l_code)
: userid(l_userid),
devicename(l_devicename),
code(l_code)
{
type = PROTOCOL_TYPE;
}
MobileConnectClassReq(const MobileConnectClassReq &rhs)
: Protocol(rhs),
userid(rhs.userid),
devicename(rhs.devicename),
code(rhs.code){ }
OctetsStream& marshal(OctetsStream& os) const
{
os << userid;
os << devicename;
os << code;
return os;
}
const OctetsStream& unmarshal(const OctetsStream& os)
{
os >> userid;
os >> devicename;
os >> code;
return os;
}
virtual Protocol* Clone() const { return new MobileConnectClassReq(*this); }
int PriorPolicy( ) const { return 1; }
bool SizePolicy(size_t size) const { return size <= 1024; }
void Process(Manager *manager, Manager::Session::ID sid)
{
// TODO
}
};
}
#endif | true |
a1584701c3df7a2004374fa6ec5c8eea785202da | C++ | Vermeille/Kulay | /ast/instr.cpp | UTF-8 | 456 | 2.796875 | 3 | [] | no_license | #include "ast.h"
Instr::Instr(Decls* let, InstrBody* body, Decls* where)
: let_(let), body_(body), where_(where) {
}
void Instr::PrettyPrint() const {
std::cout << "{";
if (let_) {
std::cout << "let [";
let_->PrettyPrint();
std::cout << "] in ";
}
body_->PrettyPrint();
if (where_) {
std::cout << " where [";
where_->PrettyPrint();
std::cout << "]";
}
std::cout << ";}";
}
| true |
2a5038abcfdf548e132c66d166f0aebcf6b8922f | C++ | Anne-ClaireFouchier/ImageProcessingComputerVision | /AVSA/Foreground_segmentation/src/fgseg.cpp | UTF-8 | 8,423 | 2.546875 | 3 | [] | no_license | /* Applied Video Sequence Analysis (AVSA)
*
* LAB1.0: Background Subtraction - Unix version
* fgesg.cpp
*
* Authors: José M. Martínez (josem.martinez@uam.es), Paula Moral (paula.moral@uam.es) & Juan Carlos San Miguel (juancarlos.sanmiguel@uam.es)
* VPULab-UAM 2020
*/
#include <opencv2/opencv.hpp>
#include "fgseg.hpp"
using namespace fgseg;
cv::Mat accumulate (cv::Mat m) {
cv::Mat s[3];
split(m, s);
for (cv::Mat i : s)
i = i / 255;
s[0] = s[0] + s[1] + s[2];
s[0] = s[0] > 0;
return s[0];
}
cv::Mat triple (cv::Mat m) {
vector<cv::Mat> t = {m, m, m};
cv::Mat result;
cv::merge (t, result);
return result;
}
//default constructor
bgs::bgs(double threshold, bool rgb)
{
_rgb = rgb;
_threshold = threshold;
_alpha = 0;
_selective_update = false;
_threshold_ghosts = 0;
}
bgs::bgs(double threshold, double alpha, bool selective_bkg_update,bool rgb)
{
_rgb = rgb;
_threshold = threshold;
_alpha = alpha;
_selective_update = selective_bkg_update;
_threshold_ghosts = 0;
}
bgs::bgs(double threshold, double alpha, bool selective_bkg_update, int threshold_ghosts, bool rgb)
{
_rgb = rgb;
_threshold = threshold;
_alpha = alpha;
_selective_update = selective_bkg_update;
_threshold_ghosts = threshold_ghosts;
}
//default destructor
bgs::~bgs(void)
{
}
//method to initialize bkg (first frame - hot start)
void bgs::init_bkg(cv::Mat Frame)
{
if (_shadowdetection)
_rgb = true;
if (!_rgb) {
cvtColor (Frame, _bkg, cv::COLOR_BGR2GRAY);
_counter = cv::Mat::zeros(_bkg.size(), CV_8UC1);
_diff = cv::Mat::zeros(_bkg.size(), CV_8UC1);
} else {
Frame.copyTo(_bkg);
_counter = cv::Mat::zeros(_bkg.size(), CV_8UC3);
_diff = cv::Mat::zeros(_bkg.size(), CV_8UC3);
}
_bgsmask = cv::Mat::zeros(_bkg.size(), CV_8UC1);
if (_simplegaussian) {
_bkg.copyTo(_mu);
_mu.convertTo(_mu, CV_32F);
cv::Scalar std_init, mean;
cv::meanStdDev(_bkg, mean, std_init);
//cout << mean << "\n" << std_init;
_std = cv::Mat(_bkg.size(), CV_32F, Scalar(std_init[0]));
}
if (_multimodal)
_gmm.init (_bkg, 0.3, 3);
}
//method to perform BackGroundSubtraction
void bgs::bkgSubtraction(cv::Mat Frame)
{
if (!_rgb){
cvtColor (Frame, _frame, cv::COLOR_BGR2GRAY);
if (_simpledetection || _ghosting || _selective_update) {
// simply take the difference between the background end current frame and create a mask by threesholding the result
absdiff(_bkg, _frame, _diff);
_bgsmask = _diff > _threshold;
}
if (_selective_update) {
// create a logical mask, we'll use this to only update those pixels that count as foreground
cv::Mat bkg_logical = _bgsmask / 255; // 1 is foreground
// apply the update to the selected pixels
_bkg = bkg_logical.mul(_alpha*_frame+(1-_alpha)*_bkg) + (1 - bkg_logical).mul(_bkg);
}
if (_ghosting) {
cv::Mat bkg_logical = _bgsmask / 255; // 1 is foreground
// increase the counter if it's foreground
_counter += bkg_logical;
// zero out counter if it's not foreground
_counter = _counter.mul (bkg_logical);
// if the counter reaches the threshold we have to change those pixels
cv::Mat pixels_to_change = ((_counter > _threshold_ghosts) == 255) / 255;
// zero out the pixels in background that we're going to update and update and replace them with the ones from the curent frame
_bkg = _bkg.mul(1 - pixels_to_change);
_bkg += _frame.mul(pixels_to_change);
// if we changed a pixel, we zero the counter
_counter = _counter.mul(1 - pixels_to_change);
}
if (_simplegaussian) {
// need to convert frame to float to to get every result as float
_frame.convertTo(_frame, CV_32F);
// calculate the distance between stored means and current frame
cv::Mat dist = abs(_mu - _frame);
//cout << "dist: " << sum(dist) << "\n";
// check if the distance is bigger than a given times the standard deviation
cv::Mat diff = (dist > _std_coeff * _std);
// if it's bigger it means it's foreground, so it's the same as background substraction mask
diff.copyTo(_bgsmask);
//cout << "bgs: " << sum(_bgsmask / 255) << "\n";
//cout << "diff: " << sum(diff) << "\n";
// create a logical (0 or 1) matrix with flaoting values, we'll use this to only update the pixels that are foreground
diff = diff / 255;
diff.convertTo(diff, CV_32F);
//cout << "diff: " << sum(diff) << "\n";
//cout << type2str(diff.type()) << "\n";
//cout << "_mu1: " << sum(_mu) << "\n";
//cout << "_std1: " << sum(_std) << "\n";
// apply the update on the selected pixels
_mu = diff.mul(_alpha * _frame + (1 - _alpha) * _mu) + (1.0 - diff).mul(_mu);
//cv::Mat newstd;
//sqrt(_alpha * ((_frame - _mu).mul(_frame - _mu)) + (1.0 - _alpha) * _std.mul(_std), newstd);
//cout << "_std1: " << sum(newstd) << "\n";
//cout << type2str(newstd.type()) << "\n";
//_std = diff.mul(newstd) + (1.0 - diff).mul(_std);
sqrt(diff.mul(_alpha * ((_frame - _mu).mul(_frame - _mu)) + (1.0 - _alpha) * _std.mul(_std)) + (1.0 - diff).mul(_std).mul(_std), _std);
//cout << "_mu2: " << sum(_mu) << "\n";
//cout << "_std2: " << sum(_std) << "\n";
}
if (_multimodal) {
_gmm.getFGMask (_frame, _bgsmask);
}
} else {
// almost the same as non-rgb, with small modifications to work with three chanel matrices
cv::Mat ones(_counter.size(), CV_8UC3, Scalar(1, 1, 1)); // helper matrix
if (_simpledetection || _ghosting || _selective_update || _shadowdetection) {
Frame.copyTo(_frame);
_diff = abs(_frame - _bkg);
_bgsmask = accumulate (_diff > _threshold);
}
if (_selective_update) {
cv::Mat bkg_logical = triple(_bgsmask / 255);
cv::Mat bkg_save;
_bkg.copyTo(bkg_save);
_bkg = bkg_logical.mul(_alpha*_frame+(1-_alpha)*_bkg) + (ones - bkg_logical).mul(_bkg);
//_bkg = bkg_save.mul((_bkg==0)/255)+_bkg;
}
if (_ghosting) {
cv::Mat bkg_logical = triple(_bgsmask / 255); // 1 is foreground
_counter += bkg_logical;
_counter = _counter.mul (bkg_logical);
//cout << "counter: " << sum(_counter) << "\n";
//cout << "bkg: " << sum(bkg_logical) << "\n";
cv::Mat pixels_to_change = ((_counter > _threshold_ghosts) == 255) / 255;
_bkg = _bkg.mul(ones - pixels_to_change);
_bkg += _frame.mul(pixels_to_change);
_counter = _counter.mul(ones - pixels_to_change);
//cout << "counter: " << sum(_counter) << "\n";
}
}
}
//method to detect and remove shadows in the BGS mask to create FG mask
void bgs::removeShadows()
{
_bgsmask.copyTo(_shadowmask);
if (_shadowdetection) {
// convert background and frame to HSV colorspace and split the 3 chanels
cv::Mat bkg_hsv, bkg_hsv_split[3];
cv::Mat frame_hsv, frame_hsv_split[3];
cvtColor (_bkg, bkg_hsv, cv::COLOR_BGR2HSV);
cvtColor (_frame, frame_hsv, cv::COLOR_BGR2HSV);
split (bkg_hsv, bkg_hsv_split);
split (frame_hsv, frame_hsv_split);
// first part of the equation, need to convert matrices to floating point to do the division, then we do the comparison
// with alpha, beta and convert the results back to uchar for further usage (it's a logical result, no need for flaoting points)
// we reuse the variables along the way to save memory and shorten code lenght
cv::Mat image_value, background_value;
frame_hsv_split[2].convertTo(image_value, CV_32F);
bkg_hsv_split[2].convertTo(background_value, CV_32F);
image_value = image_value / background_value;
background_value = image_value < b;
image_value = image_value > a;
image_value.convertTo(image_value, CV_8UC1);
background_value.convertTo(background_value, CV_8UC1);
// calculate the three parts of the consition separatly and logically and them together
cv::Mat value = ((image_value / 255 + background_value / 255) > 1) / 255;
cv::Mat saturation = (abs (frame_hsv_split[1] - bkg_hsv_split[1]) < tau_s) / 255;
cv::Mat hue = (cv::min (cv::Mat (abs (frame_hsv_split[0] - bkg_hsv_split[0])), cv::Mat (360 - abs (frame_hsv_split[0] - bkg_hsv_split[0]))) < tau_h) / 255;
cv::Mat shadow = ((value + saturation + hue) == 3) / 255;
//cout << "value: " << sum(value) << "\n";
//cout << "saturation: " << sum(saturation) << "\n";
//cout << "hue: " << sum(hue) << "\n";
//cout << "shadow: " << sum(shadow) << "\n";
// we take only those pixels that were indentified as foreground
_shadowmask = (shadow.mul (_bgsmask / 255)) * 255;
} else {
absdiff (_bgsmask, _bgsmask, _shadowmask);
}
absdiff(_bgsmask, _shadowmask, _fgmask); // eliminates shadows from bgsmask
}
//ADD ADDITIONAL FUNCTIONS HERE
| true |
152829e21d67f0dfa03a51b2426b67ada6dbba3c | C++ | AYOKINYA/Algorithm | /leetcode/Binary/countBits.cpp | UTF-8 | 455 | 3.078125 | 3 | [] | no_license | // #include <vector>
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
for (int i = 1; i <= num; ++i)
{
int count = 0;
int val = i;
while (val != 0)
{
if (val & 1)
++count;
val = val >> 1;
}
res.push_back(count);
}
return res;
}
}; | true |
a6d0633ed4084c2a253a2dca3ec852e3284c9791 | C++ | ShinoharaYuuyoru/In-Class_Projects | /Projects in Grade 1 (VS2013)/School Projects/88.PID2 - 开心的金明/88.PID2 - 开心的金明/源.cpp | GB18030 | 629 | 2.78125 | 3 | [] | no_license | #include "stdio.h"
#define X 30
int N, m;//N:Ǯ<30000 mԹĶ<25
int price[X], level[X];//ӦƷ۸͵ȼ
int sum[30000] = { 0 };
int main()
{
int mcnt;//Ʒ
int money;
scanf("%d%d", &N, &m);//Ϣ
for (mcnt = 0; mcnt < m; mcnt++)
{
scanf("%d%d", &price[mcnt], &level[mcnt]);
}
for (mcnt = 0; mcnt < m; mcnt++)
{
for (money = N; money >= price[mcnt]; money--)
{
if (sum[money - price[mcnt]] + price[mcnt] * level[mcnt]>sum[money])
{
sum[money] = sum[money - price[mcnt]] + price[mcnt] * level[mcnt];
}
}
}
printf("%d\n", sum[N]);
} | true |
8b890c3333c9d37921c1ccc05183c78a523af9d8 | C++ | Sissinothere/New_Calculator | /StringReader.cpp | UTF-8 | 6,377 | 2.953125 | 3 | [] | no_license | //============================================================================
// Name : StringReader.cpp
// Author : John Harrison
// Version :
// Copyright : Do not distribute
// Description : Hello World in C++, Ansi-style
//============================================================================
#include "StringReader.h"
#include "NobracketString.h"
#include <iostream>
#include <vector>
#include<cmath>
#include<string>
#include<cstring>
#include<sstream>
#include <stdlib.h>
using namespace std;
//pass a string to nobracketstring without parenthesis
//replace result and get rid of parenthesis and get next set of parens.
StringReader::StringReader(string input){
this->input = input;
complexC = 0;
}
void StringReader::Inject(){
int tempL= input.length();
for (int i = 0; i < input.length();i++){
tempL= input.length();
if (input.at(i)=='-'&&input.at(i-1)=='-'){
////cout << "before erase "<<input<<endl;
input.erase(i,1);
input.erase(i-1,1);
input.insert(i-1,1,'+');
}
if (tempL!=input.length()) i =0;
}
////cout << input<<endl;
tempL= input.length();
for (int i = 0; i < input.length();i++){
tempL= input.length();
if ((input.at(i)=='-'&&(int(input.at(i-1)) <= 57 && int(input.at(i-1)) >= 48))||(input.at(i)=='-'&&(int(input.at(i-1)) <= 105 && int(input.at(i-1)) >= 100))){
input.insert(i,1,'+');
}
if (tempL!=input.length()) i =0;
}
////cout << input<<endl;
}
bool StringReader::isParen(){
for(int i= 0; i < input.length(); i++){
if(input.at(i) == '('){
return true;
}
}
return false;
}
string StringReader::Parenthesis(){
int startPos;
int endPos;
string result = "";
if (!isParen()){
return "no more parenthesis";
}
if (!isParen()){
return "no more parenthesis";
}
for (int i =0;i < input.length();i++){
if (input.at(i)==')'){
input.erase(i,1);
i--;
endPos = i-1;//sets start position for in paren calculations
for(i; i >=0; i--){
if(input.at(i) == '('){
input.erase(i,1);
startPos = i;
for (startPos; startPos<=endPos;startPos++){
result += input.at(startPos);
input.erase(i,1);
endPos--;
startPos--;
}
NobracketString* nbr = new NobracketString(result);
stringstream fa;
fa<<result << " = "<< nbr->getFinalAnswer();
finalAnswer = fa.str();
nbr->ansIsComplex();
cout<<"============================================="<<endl;
cout<<"the answer is:"<<endl;
cout<<result + " = "<< nbr->getFinalAnswer()<<endl;
cout<<"============================================="<<endl;
//test if there is anything except 0-9, if there is, add square brackets
//if there is sqaure brackets you test if there is anything to distribute
////////////////////////////////////////////////////////////////
//this does distribution below
///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
int lengthy= input.length();
if(lengthy >2){
////cout << "this is the last thing of input hopefully : "<<input.at(lengthy-2)<<endl;
}
string ifComplex;
if(lengthy >2){
if ((nbr->ansIsComplex()&&input.at(lengthy-2)=='*'&&complexC <1)||(nbr->ansIsComplex()&&input.at(lengthy-2)=='/'&&complexC <1)){
if(input.at(lengthy-2)=='/') {isDiv = true;}else{
isDiv = false;
}
complexC++;
string resulty = input;
stringstream cp;
cp << '[';
cp << nbr->getFinalAnswer();
cp << ']';
input.insert(endPos+1,cp.str());
ifComplex = input;
ifComplex.erase(ifComplex.begin());
ifComplex.erase(ifComplex.end()-1);
//maybe look for only final pair of parenthesis before handling foiling
stringstream comp;
string dist;
int tempsub =2;
for(int k = 0; k < ifComplex.length();k++){
if (ifComplex.at(k)=='['){
ifComplex.erase(ifComplex.begin()+k);
if (ifComplex.at(k-1)=='*'||ifComplex.at(k-1)=='/'){
ifComplex.erase(ifComplex.begin()+k-1);
comp << ifComplex.at(k-2);
dist += ifComplex.at(k-2);
ifComplex.erase(ifComplex.begin()+k-2);
if(lengthy>6){
if(ifComplex.at(k-3)!='+'){// add stuff for * maybe
comp << ifComplex.at(k-3);
dist +=ifComplex.at(k-3);
tempsub+=1;
}
}
if (isDiv){
comp << '/';
}else{
comp << '*';
}
//cout << ifComplex<<endl;
int erase = 0;
for(int z = k-tempsub; z < ifComplex.length()&&ifComplex.at(z)!='+';z++){
comp << ifComplex.at(z);
erase++;
}
ifComplex.erase(ifComplex.begin()+k-tempsub,ifComplex.begin()+erase+lengthy-4);//has erase +2
comp << ifComplex.at(k-tempsub);
ifComplex.erase(ifComplex.begin()+k-tempsub);
//cout << "this is k: "<<k<<"this is tempsub: "<<tempsub<<endl;
int erase2;
for (int v = k-tempsub; ifComplex.at(v)!= ']';v++){
comp << ifComplex.at(v);
erase2++;
}
if (isDiv){
comp << '/';
}else{
comp << '*';
}
comp << dist;
ifComplex.erase(ifComplex.begin()+k-tempsub,ifComplex.begin()+erase2+lengthy-3);//was +3
string here = comp.str();
ifComplex.insert(k-tempsub, here);
}
}
}
resulty.insert(endPos+1,ifComplex);
stringstream theEnd;
theEnd << '(';
theEnd << ifComplex;
theEnd << ')';
input = theEnd.str();
//add parens to input
return Parenthesis();
}
}
////////////////////////////////////////////////////////////
//end of distribution handling
/////////////////////////////////////////////
////////////////////////
if (complexC==1){
complexC++;
stringstream adp;
adp <<'(';
adp << nbr->getFinalAnswer();
adp<<')';
input = adp.str();
return Parenthesis();
}
input.insert(endPos+1,nbr->getFinalAnswer());
return Parenthesis();
}
}
}
}
//make revcursive base cases
return "";
}
string StringReader::getFinalAnswer(){
return finalAnswer;
}
| true |
1a7bc8f8f6dd56193fe12b232f756af48fdf1bd0 | C++ | lysgwl/QtProject | /QDemo1/widget/ScreenShotView.cpp | UTF-8 | 5,197 | 2.59375 | 3 | [] | no_license | #include "ScreenShotView.h"
CScreenShotView::CScreenShotView(QWidget *parent)
: QWidget(parent)
{
m_pSpinBox = nullptr;
m_pCheckBox = nullptr;
m_pScreenImageLabel = nullptr;
m_pNewScreenShotBtn = nullptr;
m_pSaveScreenShotBtn = nullptr;
}
void CScreenShotView::initUI()
{
QVBoxLayout *pLayout = new QVBoxLayout(this);
if (pLayout != nullptr)
{
m_pScreenImageLabel = new QLabel(this);
if (m_pScreenImageLabel != nullptr)
{
m_pScreenImageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_pScreenImageLabel->setAlignment(Qt::AlignCenter);
const QRect screenGeometry = QApplication::desktop()->screenGeometry(this);
m_pScreenImageLabel->setMinimumSize(screenGeometry.width()/8, screenGeometry.height()/8);
pLayout->addWidget(m_pScreenImageLabel);
}
QGroupBox *pGroupBox = new QGroupBox(tr("---"), this);
if (pGroupBox != nullptr)
{
m_pSpinBox = new QSpinBox(pGroupBox);
m_pSpinBox->setSuffix(tr("s"));
m_pSpinBox->setMaximum(60);
m_pCheckBox = new QCheckBox(tr("Hide Windows"), pGroupBox);
QGridLayout *pGridLayout = new QGridLayout(pGroupBox);
pGridLayout->addWidget(new QLabel(tr("Screenshot Delay:"), this), 0, 0);
pGridLayout->addWidget(m_pSpinBox, 0, 1);
pGridLayout->addWidget(m_pCheckBox, 1, 0, 1, 2);
pLayout->addWidget(pGroupBox);
m_pSpinBox->setValue(5);
}
}
QHBoxLayout *pBtnLayout = new QHBoxLayout(this);
if (pLayout != nullptr)
{
m_pNewScreenShotBtn = new QPushButton(tr("New Screen Shot"), this);
connect(m_pNewScreenShotBtn, &QPushButton::clicked, this, &CScreenShotView::newScreenShot);
pBtnLayout->addWidget(m_pNewScreenShotBtn);
m_pSaveScreenShotBtn = new QPushButton(tr("Save Screen Shot"), this);
connect(m_pSaveScreenShotBtn, &QPushButton::clicked, this, &CScreenShotView::saveScreenShot);
pBtnLayout->addWidget(m_pSaveScreenShotBtn);
QPushButton *pQuitScreenShotBtn = new QPushButton(tr("Quit"), this);
connect(pQuitScreenShotBtn, &QPushButton::clicked, this, &QWidget::close);
pBtnLayout->addWidget(pQuitScreenShotBtn);
pBtnLayout->addStretch();
pLayout->addLayout(pBtnLayout);
}
screenShot();
show();
}
void CScreenShotView::resizeEvent(QResizeEvent *event)
{
setWndLayout();
}
void CScreenShotView::setWndLayout()
{
if (m_pScreenImageLabel == nullptr)
return;
QSize size = m_pixmap.size();
size.scale(m_pScreenImageLabel->size(), Qt::KeepAspectRatio);
if (!m_pScreenImageLabel->pixmap() || size != m_pScreenImageLabel->pixmap()->size())
showImageLabel(m_pixmap);
}
void CScreenShotView::setWidgetCtrl(bool bFlag)
{
if (bFlag)
{
if (m_pCheckBox->isChecked())
hide();
m_pNewScreenShotBtn->setDisabled(true);
m_pSaveScreenShotBtn->setDisabled(true);
}
else
{
if (m_pCheckBox->isChecked())
show();
m_pNewScreenShotBtn->setDisabled(false);
m_pSaveScreenShotBtn->setDisabled(false);
}
}
void CScreenShotView::showImageLabel(QPixmap &pixmap)
{
if (m_pScreenImageLabel == nullptr)
return;
if (pixmap.isNull())
return;
m_pScreenImageLabel->setPixmap(pixmap.scaled(m_pScreenImageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
void CScreenShotView::newScreenShot()
{
int value = 0;
if (m_pSpinBox != nullptr)
value = m_pSpinBox->value();
setWidgetCtrl(true);
QTimer::singleShot(value*1000, this, &CScreenShotView::screenShot);
}
void CScreenShotView::saveScreenShot()
{
const QString format = "png";
QString strImagePath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
if (strImagePath.isEmpty())
strImagePath = QDir::currentPath();
strImagePath += tr("\\*.") + format;
QFileDialog fileDialog(this, tr("Save As"), strImagePath);
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setFileMode(QFileDialog::AnyFile);
fileDialog.setDirectory(strImagePath);
QStringList mimeTypes;
const QList<QByteArray> baMimeTypes = QImageWriter::supportedMimeTypes();
for (const QByteArray &bf : baMimeTypes)
mimeTypes.append(QLatin1String(bf));
fileDialog.setMimeTypeFilters(mimeTypes);
fileDialog.selectMimeTypeFilter("image/" + format);
fileDialog.setDefaultSuffix(format);
if (fileDialog.exec() != QDialog::Accepted)
return;
const QString fileName = fileDialog.selectedFiles().first();
if (m_pixmap.isNull())
return;
m_pixmap.save(fileName);
}
void CScreenShotView::screenShot()
{
QScreen *pScreen = QGuiApplication::primaryScreen();
if (const QWindow *pWindow = windowHandle())
pScreen = pWindow->screen();
if (pScreen == nullptr)
return;
m_pixmap = pScreen->grabWindow(0);
if (!m_pixmap.isNull())
{
showImageLabel(m_pixmap);
}
setWidgetCtrl(false);
}
| true |
6d16e5cec61f51e427078b2997b00b8df402b73b | C++ | mclaughlinpeter/c_primer_plus | /playground/cppstrings.cpp | UTF-8 | 736 | 3.609375 | 4 | [] | no_license | #include<iostream>
#include<sstream>
#include<string>
int main()
{
std::string a = "hello ";
char temp[] = {'w', 'o', 'r', 'l', 'd', '!', '\0'};
std::string b(temp);
a[0] = 'H';
std::string c = a + b;
std::cout << "The string c is: " << c << std::endl;
std::cout << "The length of c is: " << c.length() << std::endl;
int loc = c.find_first_of('w');
c.replace(loc, 1, 1, 'W');
std::cout << "The string c is now: " << c << std::endl;
c.insert(5, " to the");
std::cout << "The string c is now: " << c << std::endl;
std::stringstream ss;
ss << c;
std::string token;
while(std::getline(ss, token, ' '))
std::cout << "Token: " << token << std::endl;
return 0;
} | true |
6b25f1305902e1c2492539c07e0de6637de1cacd | C++ | LYHyoung/BaekJoon | /BOJ solve/1000~9999/1000~1999/1719/main.cpp | WINDOWS-1252 | 2,714 | 2.578125 | 3 | [] | no_license | /*
#include <iostream>
#include <queue>
#define MAX 200
#define INF 10000
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
int MAP[MAX][MAX];
int ans[MAX];
int dist[MAX];
for (int i = 1; i < MAX; i++) {
for (int j = 1; j < MAX; j++) {
MAP[i][j] = INF;
}
dist[i] = INF;
ans[i] = INF;
}
for (int i = 0; i < m; i++) {
int a, b, length;
cin >> a >> b >> length;
MAP[a][b] = length;
MAP[b][a] = length;
}
for (int i = 1; i <= n; i++) {
priority_queue<pair<int, int>> PQ;
dist[i] = 0; // ڱڽ
PQ.push({ dist[i],i });
while (PQ.empty() == 0) {
int d = -PQ.top().first;
int e = PQ.top().second;
PQ.pop();
for (int j = 1; j <= n; j++) {
if (MAP[e][j] == INF) continue;
if (dist[j] > dist[e] + MAP[e][j]) {
dist[j] = dist[e] + MAP[e][j];
ans[j] = e;
PQ.push(make_pair(dist[j], j));
}
}
}
for (int k = 1; k <= n; k++) {
int t = k;
while (ans[t] != i) {
if (ans[t] == INF) {
cout << "- ";
break;
}
t = ans[k];
}
cout << t << " ";
}
cout << '\n';
}
return 0;
}
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <queue>
#include <vector>
#define INF 10000
#define MAX 201
using namespace std;
int dist[MAX];
int p[MAX];
int n, m, a, b, c;
struct store {
int cur;
int cost;
};
vector<store> v[MAX];
struct cmp {
bool operator()(const store &a, const store &b){
return a.cost > b.cost;
}
};
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &a, &b, &c);
v[a].push_back({ b,c });
v[b].push_back({ a,c });
}
priority_queue<store, vector<store>, cmp> PQ;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) dist[j] = INF;
dist[i] = 0;
PQ.push({ i,dist[i] });
while (!PQ.empty()) {
store cur = PQ.top();
int c_node = cur.cur;
PQ.pop();
for (int j = 0; j < v[c_node].size(); j++) {
store next = v[c_node][j]; //
int n_node = next.cur;
int n_cost = next.cost;
if (dist[n_node] > dist[c_node] + n_cost) {
dist[n_node] = dist[c_node] + n_cost;
p[n_node] = c_node;
PQ.push({ n_node, dist[n_node] });
}
}
}
for (int k = 1; k <= n; k++) {
if (k == i) {
printf("- ");
}
else if (p[k] == i) {
printf("%d ", k);
}
else {
int current = k;
while (1) {
if (p[current] == i) {
printf("%d ", current);
break;
}
else {
current = p[current];
}
}
}
}
printf("\n");
}
} | true |
2ea475be94cc4491b539c10481c8eb5364f6ae6f | C++ | admantium-sg/learning-cpp | /ccc/28_variadic_templates.cpp | UTF-8 | 634 | 3.09375 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* ---------------------------------------
* Copyright (c) Sebastian Günther 2021 |
* |
* devcon@admantium.com |
* |
* SPDX-License-Identifier: BSD-3-Clause |
* ---------------------------------------
*/
#include <stdio.h>
#include <stdexcept>
#include <iostream>
#include <cstddef>
using namespace std;
template <typename T>
constexpr T sum(T x) {
return x;
}
template<typename T, typename... Args>
constexpr T sum(T x, Args... args) {
return x + sum(args...);
}
int main() {
std::cout << "Folding of ints " << sum(1,3,5,6,7,14) << "\n";
}
| true |
8d2eef431d4de4a93b3d3b216b4cf5b593c8367d | C++ | mhunicken/icpc-team-notebook-el-vasito | /data_structures/linkcut2_test3.cpp | UTF-8 | 3,940 | 2.640625 | 3 | [] | no_license | /*
* Contest: XVIII Open Cup named after E.V. Pankratiev
* Grand Prix of Korea
* Problem: G
*
* An example of adapting linkcut for queries of max edge in a path.
* Change are mostly (if not all) in how Node_t does update and returns
* value
*/
#include <bits/stdc++.h>
#define fore(x,a,b) for(int x=a,qwe=b; x<qwe; x++)
#define pb push_back
using namespace std;
typedef long long ll;
const int N_VALUE = -1;
struct Node_t{
int sz; ll val; int u, v;
bool rev;
Node_t *ch[2], *p, *mxedge;
Node_t(int u):sz(1),val(-1),u(u),v(u),rev(0),p(0){
ch[0]=ch[1]=0;mxedge=this;
}
Node_t(int u, int v, ll c):sz(1),val(c),u(u),v(v),rev(0),p(0){
ch[0]=ch[1]=0;mxedge=this;
}
bool isRoot(){return !p || (p->ch[0] != this && p->ch[1] != this);}
void push(){
if(rev){
rev=0; swap(ch[0], ch[1]);
fore(x,0,2)if(ch[x])ch[x]->rev^=1;
}
}
void upd();
};
typedef Node_t* Node;
inline Node queryOp(Node lval, Node rval){
if(!lval||!rval)return lval?lval:rval;
return (lval->val>rval->val) ? lval : rval;
}
int getSize(Node r){return r ? r->sz : 0;}
Node getstVal(Node r){return r ? r->mxedge : 0;}
void Node_t::upd(){
mxedge = queryOp(queryOp(this,getstVal(ch[0])),getstVal(ch[1]));
sz = 1 + getSize(ch[0]) + getSize(ch[1]);
}
void connect(Node ch, Node p, int isl){if(ch)ch->p=p; if(isl>=0)p->ch[1-isl]=ch;}
void rotate(Node x){
Node p = x->p, g = p->p;
bool gCh=p->isRoot(), isl = x==p->ch[0];
connect(x->ch[isl],p,isl);connect(p,x,!isl);connect(x,g,gCh?-1:(p==g->ch[0]));
p->upd();
}
void splay(Node x){
while(!x->isRoot()){
Node p = x->p, g = p->p;
if(!p->isRoot())g->push();
p->push(); x->push();
if(!p->isRoot())rotate((x==p->ch[0])==(p==g->ch[0])? p : x);
rotate(x);
}
x->push(); x->upd();
}
Node expose(Node x){
Node last=0;
for(Node y=x; y; y=y->p){
splay(y);
y->ch[1]=last;y->upd();last=y;
}
splay(x);
return last;
}
Node findRoot(Node x){expose(x); while(x->ch[0])x=x->ch[0]; splay(x); return x;}
Node lca(Node x, Node y){expose(x);return expose(y);}//not tested
void makeRoot(Node x){expose(x);x->rev^=1;}
bool connected(Node x, Node y){if(x==y)return 1;expose(x);expose(y);return x->p;}
void link(Node x, Node y){makeRoot(x); x->p=y;}
void cut(Node x, Node y){makeRoot(x);expose(y);y->ch[0]->p = 0; y->ch[0]=0;}
Node query(Node x, Node y){makeRoot(x); expose(y); return getstVal(y);}
const int N=3e5+5;
int n, m, P[N];
vector<pair<int,ll> > g[N];
Node vs[N], es[N];
ll calc(int u){
vector<tuple<Node,Node,int> > log;
ll ans = 0;
for(auto p : g[u]){
int v=p.first;
Node e=query(vs[u],vs[v]);
cut(e,vs[e->v]);cut(vs[e->u],e);
Node tmp=new Node_t(-1);
link(tmp,vs[u]);link(vs[v],tmp);
ans -= e->val;
ans += p.second;
log.push_back(make_tuple(tmp,e,v));
}
//restore
for(auto t : log){
Node erem=get<0>(t);
cut(erem,vs[get<2>(t)]);cut(erem,vs[u]);
delete erem;
}
for(auto t : log){
Node eold=get<1>(t);
link(eold,vs[eold->u]);link(eold,vs[eold->v]);
}
return ans;
}
struct Edge {
int u, v; ll c;
bool operator<(const Edge& o)const{
return c<o.c;
}
};
vector<Edge> edges;
int find(int i){return i==P[i]?i:P[i]=find(P[i]);}
int main(){ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin >> n >> m;
fore(x,0,n)P[x]=x,vs[x]=new Node_t(x);
fore(x,0,m){
int u,v;ll c; cin >> u >> v >> c; u--; v--;
g[u].pb({v,c});g[v].pb({u,c});
edges.pb(Edge{u,v,c});
}
sort(edges.begin(),edges.end());
ll total = 0;
fore(x,0,m){
int u=edges[x].u,v=edges[x].v;
es[x]=new Node_t(u,v,edges[x].c);
int i=find(u), j=find(v);
if(i!=j){
total += edges[x].c;
P[i]=j;
link(es[x],vs[u]); link(vs[v],es[x]);
}
}
fore(x,0,n)cout<<total+calc(x)<<"\n";
}
| true |
8372d8cda3aefe81dba2a3e38facc077db5eedc4 | C++ | SamChien/Competitive-Programming | /uva_online_judge/11727-Cost_Cutting.cpp | UTF-8 | 490 | 3.046875 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
int main() {
int caseNum;
scanf("%d", &caseNum);
for (int caseCount=1; caseCount<=caseNum; caseCount++) {
int empNum = 3;
int salArr[empNum];
for (int i=0; i<empNum; i++) {
int salary;
scanf("%d", &salary);
salArr[i] = salary;
}
sort(salArr, salArr + empNum);
printf("Case %d: %d\n", caseCount, salArr[1]);
}
return 0;
}
| true |
9fef4f9aa3af1051b07d8f8ac0a60658723328f8 | C++ | JunHaoSu/Algorithm | /For_course/rent.cpp | UTF-8 | 1,589 | 3.125 | 3 | [] | no_license | /*************************************************************************
> File Name: rent.cpp
> Author: sujunhao
> Mail: sujunhao0504@gmail.com
> Created Time: 2017年11月14日 星期二 19时15分51秒
************************************************************************/
/* 该算法的思想是,如果单步租用小于连续租用的钱,就用单步租用的钱替换掉连续租用的钱。即本例的1站->2站->3站的租金替换掉1站->3站的租金。依次循环,最后右上角的那个值就是最小的租金。
*/
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
const int MAX = 200;
vector<vector<int> >list;//用于存放租金
vector<int>line;
int R(int n){
int i, j, k;//定义三个索引
for (k=2;k<n;k++){
for (i=0;i<n-k;i++){
int mark=i+k;
for(j=i+1;j<mark;j++){
if(list[i][j]+list[j][mark]<list[i][mark]){//核心代码
list[i][mark]=list[i][j]+list[j][mark];
}
}
}
return list[0][n-1];
}
}
int main(){
ifstream fin;
ofstream fout;
fin.open("rent_input.txt");
fout.open("rent_output.txt");
int n;//站点数
int rent;//租金
fin>>n;
for (int i=0;i<n-1;i++){ //二维向量,不满的值用0填满。
list.push_back(line);
for(int j=0;j<=i;j++){
list[i].push_back(0);
}
for (int j=i+1;j<n;j++){
fin>>rent;
list[i].push_back(rent);
}
}
fin.close();
fout<<R(n)<<endl;
return 0;
}
| true |
ad4fe8205935b5c4f89bc9878c61492cc3867dde | C++ | Sashkoiv/yandex-cpp-belts | /white/Task_7/accessory.cpp | UTF-8 | 552 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "accessory.hpp"
using namespace std;
vector<string> PalindromFilter(vector<string> words, int minLength) {
vector<string> result;
for (string word : words) {
if (word.length() >= minLength) {
if (word == string(word.rbegin(), word.rend())) {
result.push_back(word);
}
}
}
return result;
}
int VectorPrint(const vector<string>& input){
for (auto i : input){
cout << i << ", ";
}
cout << endl;
return 0;
}
| true |
5e6f3065c5a94f032fad3fc9760369e67be88f3d | C++ | zjingcong/pba | /pba/include/Triangle.h | UTF-8 | 1,290 | 2.90625 | 3 | [] | no_license | //
// Created by jingcoz on 9/18/17.
//
#ifndef PBA_TRIANGLE_H
#define PBA_TRIANGLE_H
# include "Vector.h"
# include "Color.h"
namespace pba
{
class Triangle
{
public:
Triangle(const pba::Vector& P0, const pba::Vector& P1, const pba::Vector& P2);
~Triangle() {}
void setColor(pba::Color c) {color = c;}
void setVisible(bool flag) {isVisible = flag;}
void setCollisionStatus(bool flag) {isCollision = flag;}
const pba::Vector& getP0() const { return P0;}
const pba::Vector& getP1() const { return P1;}
const pba::Vector& getP2() const { return P2;}
const pba::Vector& getE1() const { return e1;}
const pba::Vector& getE2() const { return e2;}
const pba::Vector& getNorm() const { return norm;}
const pba::Color& getColor() const { return color;}
bool getCollisionStatus() const { return isCollision;}
bool getVisibility() const { return isVisible;}
private:
pba::Vector P0;
pba::Vector P1;
pba::Vector P2;
pba::Vector e1;
pba::Vector e2;
pba::Vector norm;
pba::Color color;
bool isCollision;
bool isVisible;
};
typedef Triangle* TrianglePtr;
}
#endif //PBA_TRIANGLE_H
| true |
81549d24201e5cdf9c6a4fa8ece9489bd2a4927c | C++ | tofergregg/CodeReview | /course/cs106b/1176/midterm/p2/cgregg.cpp | UTF-8 | 610 | 3.15625 | 3 | [] | no_license | string decode(string seq) {
// create a stack to hold the values
Stack<int> s;
// create a string for the result
string result;
// we need to iterate n+1 times
for (int i=0; i <= (int)seq.length(); i++) {
s.push(i+1);
// if we have processed all characters or the character
// is an 'I'
if (i == (int)seq.length() || seq[i] == 'I') {
// process the entire stack
while (!s.isEmpty()) {
// pop and add it to the solution
result += integerToString(s.pop());
}
}
}
return result;
}
| true |
98a0db9a560ce73ff45a2f3907c271a23b7c4b9f | C++ | JackyHan/Human-Body-Temperature-Simulation | /Time-dependent simulation/main.cpp | UTF-8 | 5,584 | 2.546875 | 3 | [
"MIT"
] | permissive | /*
MIT License
Copyright (c) 2016 - Jacky Han
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
#include "processes.h"
/*
** This program was designed to run in a linux terminal window that
** is 143 characters wide, and as such might not display nicely on
** other widths unless properly modified. However, the output file
** should have nice formating regardless of the running environment.
**
** Most of the computation and ugly details are in the header file
** called "processes.h", included above.
**
** The paramters for each run must be specified in a text file called
** "config.txt". The order in which the paramters must be listed can
** be found below in the code (the several "infile >>" lines).
** @Author: Jacky Han
** @Date: July 15 2016
*/
int main(int argc, char** argv)
{
//Create output file stream and open file for output
std::ofstream outfile;
outfile.open("run.txt");
//data output file
// std::ofstream outfile2;
//outfile2.open("data.txt");
//Create input file stream and open the configuration file
std::ifstream infile;
infile.open("config.txt");
//The following lines set the default values for various parameters
//before the config values are read in
const bool MALE = true;
const bool FEMALE = false; //for use in REE function argument
double m = 80; //mass in kg
double h = 185; //height in cm
double a = 25; //age in years
double refl = 0.50; //skin reflectivity
double T = 30; //dry temp (C)
double Tw = 35; //wet bulb temp (C) - high
double v = 5.0; //wind speed (m/s)
char gend; //gender ('m' or 'f')
double met = 0; //metabolic heat (0 means REE) (in watts)
double L; //evaporation
//The next several lines read in the desired parameter values from
//the file "config.txt". Refer to comments above for their meaning.
infile >> m;
infile >> h;
infile >> a;
infile >> refl;
infile >> T;
infile >> Tw;
infile >> v;
infile >> met;
infile >> gend;
infile.close(); //close the config file after reading it
double A = BSA(m, h); //body surface area (Mosteller)
if(met == 0)
{
if(gend == 'm')
{
met = REE(m, h, a, MALE);
}
else
{
met = REE(m, h, a, FEMALE);
}
}
//Set up initial values and create vars for later use
double Tc = 36.5; //core temp (initial)
double Ts = 31.3; //skin temp (initial)
double W = 0; //necessary water intake (initial)
double S, M, Rs, Rb, Fs, Fc, coreFlow, temp1,temp2;
int i2 = 0;
Fs = 1; //so that the loop initiates
Fc = 1; //ditto
outfile << std::left << std::setw(COL_W) << "time(min)" << std::setw(COL_W) << "Tc"
<< std::setw(COL_W) << "Ts" << std::endl;
//Run the sim for as long as core temp is below 42 or until the core or skin flux is tiny
for(int i = 0; (Tc < 42)&&((std::abs(Fs) > 1e-4)||(std::abs(Fc) > 1e-4)); i++)
{
S = conv(v, T, Ts); //sensible heat (convection)
L = evap(v, T, Ts, Tw); //Latent heat (evaporation)
M = met; //metabolic heat
Rs = solarRad(A, refl); //Solar radiation
Rb = bbRad(A, T, Ts); //Blackbody radiation
coreFlow = fc(Tc, Ts, A); //Core heat flow
Fs = (S + L + Rs + Rb + coreFlow); //heat flow at skin interface
Fc = (M - coreFlow); //heat flow at core/shell interface
Ts += 0.1 * Fs / (0.1 * m * 3874); //skin(shell) temp
Tc += 0.1 * Fc / (0.9 * m * 3874); //core temp
i2 = i;
if(i % 600 == 0) {
outfile << std::left << std::setw(COL_W) << i/600 << std::setw(COL_W) << Tc
<< std::setw(COL_W) << Ts << std::endl;
}
}
outfile.close(); //close the output file
//outfile2.close();
return 0;
}
| true |
f06405f77c8b093b0b6ae76e55a662cd3316d50e | C++ | niloufar60/cpp-codes | /p432-varaddr.cpp | UTF-8 | 282 | 2.578125 | 3 | [] | no_license | //
// p432-varaddr.cpp
//
//
// Created by Niloufar on 2018-08-17.
//
#include <iostream>
using namespace std;
int main ()
{
int var1=11;
int var2=22;
int var3=33;
cout << &var1 << endl
<< &var2 << endl
<< &var3 << endl;
return 0;
}
| true |
6146912a7080067cc850bde6f3885a3dbe371b12 | C++ | sawarn/Captcha_Generator | /main.cpp | UTF-8 | 890 | 3.140625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool checkCAPTCHA(string &captcha,string &user_CAPTCHA)
{
if(captcha==user_CAPTCHA)
return true;
else
return false;
}
string generateCAPTCHA(int n){
char *ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
string captcha="";
while(n--){
captcha=captcha+ch[rand()%62];
}
return captcha;
}
int main()
{
srand(time(NULL));
int x;
cout<<"Enter the length of CAPTCHA="<<endl;
cin>>x;
string captcha=generateCAPTCHA(x);
cout<<captcha;
string user_CAPTCHA;
cout<<endl<<"Enter the above CAPTCHA"<<endl;
cin>>user_CAPTCHA;
if(checkCAPTCHA(captcha,user_CAPTCHA))
{
cout<<"CAPTCHA MATCHED";
}
else
{
cout<<"CAPTCHA not matched";
}
return 0;
}
| true |
5b8092e122aaa40424e0ca25874a2f9779991597 | C++ | HaythemBenMechichi/test | /congee.cpp | UTF-8 | 2,298 | 2.53125 | 3 | [] | no_license | #include "congee.h"
congee::congee()
{
cin=0;
}
congee::congee(int a,QDate d,QDate e)
{
cin=a;
date_d=d;
date_e=e;
}
int congee::getcin(){
return cin;
}
QDate congee::getdate_d(){
return date_d;
}
QDate congee::getdate_e(){
return date_e;
}
bool congee::ajouter(){
QSqlQuery query;
query.prepare("insert into conges values(?,?,?,id.nextval);");
query.addBindValue(cin);
query.addBindValue(date_d);
query.addBindValue(date_e);
return query.exec();
}
QStandardItemModel * congee::afficher(QObject* parent){
QSqlQuery q;
q.prepare("select * from conges;");
int i=0;
if(q.exec()){
while(q.next()){
for(int col=0; col<4 ; col++){
QString a=q.value(col).toString();
}
i++;
}
}
QStandardItemModel* model =new QStandardItemModel(i,4,parent);
// QSqlQueryModel *model1=new QSqlQueryModel();
//QStandardItemModel* model =new QStandardItemModel(4,2,this);
q.prepare("select * from conges");
i=0;
if(q.exec()){
while(q.next()){
for(int col=0; col<4 ; col++){
if(col==2 or col==1){
QDate a=q.value(col).toDate();
QModelIndex index=model->index(i,col,QModelIndex());
model->setData(index,a);
}
else
{
QString a=q.value(col).toString();
QModelIndex index=model->index(i,col,QModelIndex());
model->setData(index,a);
}
}
i++;
}
}
return model;
}
bool congee::supprimer(int a){
QSqlQuery query;
query.prepare("delete from conges where id = ?");
query.addBindValue(a);
return query.exec();
}
bool congee::modifier(int a){
QSqlQuery query;
query.prepare("update conges set cin = ? , date_d = ? , date_e = ? where id = ?");
query.addBindValue(cin);
query.addBindValue(date_d);
query.addBindValue(date_e);
query.addBindValue(a);
return query.exec();
}
QSqlQueryModel * congee::afficher_cin(){
QSqlQueryModel * model= new QSqlQueryModel();
model->setQuery("select id from conges;" );
return model;
}
| true |
6e523d91f4029b0139a57df2ca9087c63eea6af5 | C++ | rohitbhatghare/c-c- | /Sept-25-20/assignment158.cpp | UTF-8 | 295 | 3.015625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i,j;
int sum=1,avg;
cout<<"Enter the Number ";
cin>>j;
for(i=1;i<=j;i++)
{
sum=sum*i;
}
cout<<"Odd natural numbers and their sums are"<<j<<" "<<sum<<endl;
return 0;
}
| true |
a9ccb17dcc30fdc8e1f7042b2bafd5182903bfc1 | C++ | dragonir/Sicily | /1199. GCD(欧拉函数).cpp | UTF-8 | 731 | 3.125 | 3 | [] | no_license | #include<algorithm>
#include <iostream>
#include <cmath>
using namespace std;
int data[40000];
int Euler(int n){
int temp=n;
for(int i=2;i*i<=n;i++)if(n%i==0){
temp=(temp/i)*(i-1);
for(;n%i==0;n/=i);
}
if(n>1)temp=(temp/n)*(n-1);
return temp;
}
int main(){
int t;cin>>t;
while(t--){
int n,m;cin>>n>>m;
if(m>n){
cout<<0<<endl;
continue;
}
if(m==n){
cout<<1<<endl;
continue;
}
if(m==1||m==0){
cout<<n<<endl;
continue;
}
int index=0;
for(int i=2;i*i<=n;i++){
if(n%i==0){
data[index++]=i;
if(i*i<n) data[index++]=n/i;
}
}
int sum=0;
for(int i=0;i<index;i++)
if(data[i]>=m)
sum+=Euler(n/data[i]);
cout<<sum+1<<endl;
}
return 0;
}
| true |
4d729964de4335a6243e225659cea03a29177901 | C++ | ChickYQ/Leetcode | /121.cc | UTF-8 | 1,544 | 3.953125 | 4 | [] | no_license | /*
121. 买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
注意:你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, //因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
解法:移动左指针进行扫描,用min记录当前扫描过的元素的最小值,
每次prices[left]为没有扫描的元素,若该元素小于min,则将其置为min
否则,用该值减去min,若差值大于res,更新res.
*/
#include<vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1)
return 0;
int left = 0;
int min = prices[left], res = 0;
while(left < prices.size())
{
if(prices[left] < min)
{
min = prices[left];
}
else if(prices[left] - min > res)
{
res = prices[left] - min;
}
++left;
}
return res;
}
}; | true |
996834d6d48ccc54ef17ee1e01fb672df4a0a404 | C++ | Kaldie/GeRoBot | /math/Line2D.h | UTF-8 | 766 | 2.796875 | 3 | [] | no_license | // Copyright [2015] Ruud Cools
#ifndef MATH_LINE2D_H_
#define MATH_LINE2D_H_
#include <Point2D.h>
class Line2D {
private:
GETSET(Point2D, m_startPoint, StartPoint);
GETSET(Point2D, m_endPoint, EndPoint);
public:
bool operator==(const Line2D& i_rhs) const;
Line2D();
Line2D(Point2D i_startPoint,
Point2D i_endPoint);
/// Get the intersection of the two lines
bool intersects(const Line2D& i_line) const;
/// get the intersection of the line and the point
/// Where the point defines a line through origin
Point2D getIntersectingPoint(const Point2D&) const;
Point2D getIntersectingPoint(const Line2D &i_line2D) const;
/// Get the length of the line defined by the two points
traceType getLength();
};
#endif // MATH_LINE2D_H_
| true |
ecb0bb1577c00c4f4469653aa360fe741dfdc723 | C++ | lizizatt/TicTacToe | /source/Cube.h | UTF-8 | 1,662 | 2.546875 | 3 | [] | no_license | #pragma once
#include <glad/glad.h>
#include <gl/GL.h>
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <string>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <vector>
#include <unordered_map>
#include <chrono>
using Clock = std::chrono::steady_clock;
using std::chrono::time_point;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using namespace std::literals::chrono_literals;
using namespace std;
class Cube
{
public:
enum Face
{
logo,
startGame,
X,
lose,
win,
O
};
public:
class Listener
{
public:
virtual void OnClick(Cube *c) = 0;
};
public:
Cube();
Cube(Cube &c);
Cube(glm::vec3 pos, glm::vec3 scale, glm::vec3 scenePos = glm::vec3(), glm::vec3 sceneScale = glm::vec3());
~Cube();
void draw(glm::mat4 mvp);
void setup();
static void SetUpCube();
static void TearDownCube();
Face getFace() { return face; }
void setFace(Face face);
void raycastClick(glm::vec3 rayPos, glm::vec3 ray);
inline void addListener(Listener *l) { listeners.push_back(l); }
inline void removeListener(Listener *l) { listeners.remove(l); }
private:
glm::vec3 pos;
glm::vec3 scale;
Face face;
glm::mat4 mvp;
glm::mat4 targetMVP;
static string textureFileName;
static unsigned int texWidth;
static unsigned int texHeight;
static std::vector<unsigned char> texBuffer;
static GLuint textureID;
static GLuint VertexArrayID;
static GLuint vertexbuffer;
static GLuint uvbuffer;
static GLuint texSampler;
bool once = false;
glm::vec3 scenePos;
glm::vec3 sceneScale;
list<Listener*> listeners;
time_point<Clock> start;
long rockPeriodMS = 6000;
float rockMagnitude = .05;
};
| true |
1a9e64017aba7c65581df84920a8cb2a06761e11 | C++ | davidjacobo/Competencias | /HackerRank/find_digits.cpp | UTF-8 | 493 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstring>
#define MAX_N 12
using namespace std;
typedef long long ll;
int main(){
ll N;
char line[MAX_N];
int T, len, counter;
cin>>T;
while(T--){
cin>>line;
N = atoi(line);
len = strlen(line);
counter = 0;
for(int i=0;i<len;++i){
if(line[i]=='0') continue;
else if(N%(line[i]-'0')==0) ++counter;
}
cout<<counter<<endl;
}
return 0;
}
| true |
192b440e51c6cbf778bb094baa3a06eba6066f5a | C++ | Meaple-SFKY/Programming | /C_Folder/Data_Structure/Graph_Experiment/createGrpAdjLinkedList.h | GB18030 | 11,036 | 3.15625 | 3 | [] | no_license | #ifndef _CREATGRPADJLINKEDLIST_H_
#define _CREATGRPADJLINKEDLIST_H_
#include<iostream>
#include<cstring>
#include"grpAdjLinkedList.h"
using namespace std;
void strLTrim(char* str); //ɾַ߿ո
//***************************2 ļͼ****************************//
//* ܣıļڽӾʾͼ *//
//* ڲ char fileName[]ļ *//
//* ڲGraph &Gͼ *//
//* ֵbooltrueɹfalseʧ *//
//* CreateGrpFromFile(char fileName[], Graph &G) *//
//* עʹõļڽӾΪ *//
//*******************************************************************//
int CreateGrpFromFile1(char fileName[], Graph &G)
{
FILE* pFile; //˳ļָ
char str[1000]; //Ŷһıַ
char strTemp[10]; //жǷע
char* ss;
int i=0,j=0;
int edgeNum=0; //ߵ
GraphKind graphType; //ͼöٱ
pFile=fopen(fileName,"r");
if(!pFile)
{
printf("ļ%sʧܡ\n",fileName);
return false;
}
ss=fgets(str,1000,pFile);
strncpy(strTemp,str,2);
while((ss!=NULL) && (strstr(strTemp,"//")!=NULL) ) //ע
{
ss=fgets(str,1000,pFile);
strncpy(strTemp,str,2);
//cout<<strTemp<<endl;
}
//ѭstrӦѾļʶжļʽ
//cout<<str<<endl;
if(strstr(str,"Graph")==NULL)
{
printf("ļʽ\n");
fclose(pFile); //رļ
return false;
}
//ȡͼ
if(fgets(str,1000,pFile)==NULL)
{
printf("ȡͼͱʧܣ\n");
fclose(pFile); //رļ
return false;
}
//ͼ
if(strstr(str,"UDG"))
graphType=UDG; //ͼ
else if(strstr(str,"UDN"))
graphType=UDN; //
else if(strstr(str,"DG"))
graphType=DG; //ͼ
else if(strstr(str,"DN"))
graphType=DN; //
else
{
printf("ȡͼͱʧܣ\n");
fclose(pFile); //رļ
return false;
}
//ȡԪأstr
if(fgets(str,1000,pFile)==NULL)
{
printf("ȡͼĶԪʧܣ\n");
fclose(pFile); //رļ
return false;
}
//ݷͼĶ
char* token=strtok(str," ");
int nNum=1;
while(token!=NULL)
{
G.VerList[nNum].data=*token;
G.VerList[nNum].firstEdge=NULL;
//p=NULL;
//eR=G.VerList[i].firstEdge;
token = strtok( NULL, " ");
nNum++;
}
//ѭȡڽӾ
int nRow=1; //±
int nCol=1; //±
EdgeNode* eR; //βָ
EdgeNode* p;
while(fgets(str,1000,pFile)!=NULL)
{
eR=NULL;
p=NULL;
nCol=1; //кΪ0һ¿ʼ
char* token=strtok(str," "); //ԿոΪָָһݣдڽӾ
while(token!=NULL)
{
if(atoi(token)>=1 && atoi(token)<INF) //ǵ
{
p=new EdgeNode; //һ
p->adjVer=nCol; //ıţ1ʼ
p->eInfo=atoi(token); //ȨͼȨֵȨͼΪ1
p->next=NULL;
if(G.VerList[nRow].firstEdge==NULL)
{
G.VerList[nRow].firstEdge=p;
eR=p;
}
else
{
eR->next=p;
eR=p; //µβָ
}
edgeNum++; //1
}
token = strtok( NULL, " "); //ȡһӴ
nCol++;
}
nRow++; //һݴ
}
G.VerNum=nNum; //ͼĶ
if(graphType==UDG || graphType==UDN)
G.ArcNum=edgeNum / 2; //ͼıͳƵֳ2
else
G.ArcNum=edgeNum;
G.gKind=graphType; //ͼ
fclose(pFile); //رļ
return true;
}
//***************************3 ļͼ****************************//
//* ܣıļڽӾʾͼ *//
//* ڲ char fileName[]ļ *//
//* ڲGraph &Gͼ *//
//* ֵbooltrueɹfalseʧ *//
//* CreateGraphUDFromFile(char fileName[], Graph &G) *//
//* עʹõļʽԱߣԣΪ *//
//*******************************************************************//
int CreateGraphFromFile(char fileName[], Graph &G)
{
FILE* pFile; //˳ļָ
char str[1000]; //Ŷһıַ
char strTemp[10]; //жǷע
int i=0,j=0;
int edgeNum=0; //ߵ
eInfoType eWeight; //ߵϢΪߵȨֵ
GraphKind graphType; //ͼöٱ
pFile=fopen(fileName,"r");
if(!pFile)
{
printf("ļ%sʧܡ\n",fileName);
return false;
}
while(fgets(str,1000,pFile)!=NULL) //кע
{
//ɾַ߿ո
strLTrim(str);
if (str[0]=='\n') //Уȡһ
continue;
strncpy(strTemp,str,2);
if(strstr(strTemp,"//")!=NULL) //ע
continue;
else //עСǿУѭ
break;
}
//ѭstrӦѾļʶжļʽ
if(strstr(str,"Graph")==NULL)
{
printf("ļʽ\n");
fclose(pFile); //رļ
return false;
}
//ȡͼͣмע
while(fgets(str,1000,pFile)!=NULL)
{
//ɾַ߿ո
strLTrim(str);
if (str[0]=='\n') //Уȡһ
continue;
strncpy(strTemp,str,2);
if(strstr(strTemp,"//")!=NULL) //עУȡһ
continue;
else //ǿУҲעУͼͱʶ
break;
}
//ͼ
if(strstr(str,"UDG"))
graphType=UDG; //ͼ
else if(strstr(str,"UDN"))
graphType=UDN; //
else if(strstr(str,"DG"))
graphType=DG; //ͼ
else if(strstr(str,"DN"))
graphType=DN; //
else
{
printf("ȡͼͱʧܣ\n");
fclose(pFile); //رļ
return false;
}
//ȡԪأstr
while(fgets(str,1000,pFile)!=NULL)
{
//ɾַ߿ո
strLTrim(str);
if (str[0]=='\n') //Уȡһ
continue;
strncpy(strTemp,str,2);
if(strstr(strTemp,"//")!=NULL) //עУȡһ
continue;
else //ǿУҲעУͼĶԪ
break;
}
//ݷͼĶ
char* token=strtok(str," ");
int nNum=0;
while(token!=NULL)
{
G.VerList[nNum+1].data=*token;
G.VerList[nNum+1].firstEdge=NULL;
//p=NULL;
//eR=G.VerList[i].firstEdge;
token = strtok( NULL, " ");
nNum++;
}
//ѭȡߣԣ
int nRow=1; //±
int nCol=1; //±
EdgeNode* eR; //βָ
EdgeNode* p;
elementType Nf,Ns; //2ڶ
while(fgets(str,1000,pFile)!=NULL)
{
//ɾַ߿ո
strLTrim(str);
if (str[0]=='\n') //Уȡһ
continue;
strncpy(strTemp,str,2);
if(strstr(strTemp,"//")!=NULL) //עУȡһ
continue;
//nCol=0; //кΪ0һ¿ʼ
char* token=strtok(str," "); //ԿոΪָָһݣдڽӾ
if(token==NULL) //ָΪմʧ˳
{
printf("ȡͼıʧܣ\n");
fclose(pFile); //رļ
return false;
}
Nf=*token; //ȡߵĵһ
token = strtok( NULL, " "); //ȡһӴڶ
if(token==NULL) //ָΪմʧ˳
{
printf("ȡͼıʧܣ\n");
fclose(pFile); //رļ
return false;
}
Ns=*token; //ȡߵĵڶ
//ӵһȡк
for(nRow=1;nRow<=nNum;nRow++)
{
if(G.VerList[nRow].data==Nf) //Ӷбҵһı
break;
}
//ӵڶȡк
for(nCol=1;nCol<=nNum;nCol++)
{
if(G.VerList[nCol].data==Ns) //Ӷбҵڶı
break;
}
//ΪȡȨֵ
if(graphType==UDN || graphType==DN)
{
token = strtok( NULL, " "); //ȡһӴߵĸϢΪߵȨ
if(token==NULL) //ָΪմʧ˳
{
printf("ȡͼıʧܣ\n");
fclose(pFile); //رļ
return false;
}
eWeight=atoi(token); //ȡñߵĸϢ
}
eR=G.VerList[nRow].firstEdge;
while(eR!=NULL && eR->next!=NULL)
{
eR=eR->next; //Ʊָ룬ֱβڵ
}
p=new EdgeNode; //һ
p->adjVer=nCol; //ıţ1ʼ
if(graphType==UDN || graphType==DN) //ߵĸϢȨͼȨֵȨͼΪ1
p->eInfo=eWeight;
else
p->eInfo=1;
p->next=NULL;
if(G.VerList[nRow].firstEdge==NULL)
{
G.VerList[nRow].firstEdge=p;
eR=p;
}
else
{
eR->next=p;
eR=p; //µβָ
}
edgeNum++; //1
}
G.VerNum=nNum; //ͼĶ
if(graphType==UDG || graphType==UDN)
G.ArcNum=edgeNum / 2; //ͼıͳƵֳ2
else
G.ArcNum=edgeNum;
G.gKind=graphType; //ͼ
fclose(pFile); //رļ
return true;
}
//ɾַַ߿ո
void strLTrim(char* str)
{
int i,j;
int n=0;
n=strlen(str)+1;
for(i=0;i<n;i++)
{
if(str[i]!=' ') //ҵһǿոλ
break;
}
//ԵһǿոַΪַƶַ
for(j=0;j<n;j++)
{
str[j]=str[i];
i++;
}
}
//ͼ
void DestroyGraph(Graph &G)
{
EdgeNode *p,*u;
int vID;
for(vID=1; vID<=G.VerNum; vID++) //ѭɾÿı
{
p=G.VerList[vID].firstEdge;
G.VerList[vID].firstEdge=NULL;
while(p) //ѭɾǰеĹ
{
u=p->next; //uָһ߽
delete(p); //ɾǰ߽
p=u;
}
}
p=NULL;
u=NULL;
G.VerNum=-1; //༭ͼѾ
}
#endif | true |
cca0b6622e49c3437fd83041c9f07b4b79d71b01 | C++ | dronekit/dronekit-la | /analyzer.h | UTF-8 | 9,417 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /**
* @file
* @author Peter Barker <peter.barker@3drobotics.com>
*
* @section DESCRIPTION
*
* Base class for all analyzers; provides facilities to register results
*/
#ifndef ANALYZER_H
#define ANALYZER_H
#include <jsoncpp/json/json.h> // libjsoncpp0 and libjsoncpp-dev on debian
// #include <jsoncpp/json/writer.h> // libjsoncpp0 and libjsoncpp-dev on debian
#include "analyzervehicle.h"
#include "INIReader.h"
#include "data_sources.h"
#include "analyzer_util.h"
/// Enumeration of possible states for both an Analyzer_Result and Analyzer.
enum analyzer_status {
analyzer_status_warn = 17,
analyzer_status_fail,
analyzer_status_ok,
};
/*!
* Returns a textual interpretation of the supplied status.
*
* @param status Analyzer status to provide text for.
* @return Textual interpretation of status.
*/
const char *_status_as_string(analyzer_status status);
/// @brief Base class for analyzer results; extend this to provide a custom result object.
///
/// You probably do not want to directly extend Analyzer_Result, but one of its immediate subclasses.
class Analyzer_Result {
public:
/// @brief Construct an Analyzer_Result.
virtual ~Analyzer_Result() { }
/// @brief Provides a textual description of the Analyzer Result's status.
/// @return A text string e.g. "OK" or "FAIL".
const char *status_as_string() const {
return _status_as_string(_status);
}
/// @brief Provide the Analyzer_Result's status.
/// @return The Analyzer_Result's status.
analyzer_status status() { return _status; }
/// @brief Set the Analyzer Result's status.
/// @param status The new status for this Result.
void set_status(analyzer_status status) { _status = status; }
/// @brief Set a simple, human-readable explanation of the result.
/// @param reason The reason for the existence of this result.
void set_reason(const std::string reason) {
if (_reason != NULL) {
delete(_reason);
}
_reason = new std::string(reason);
}
/// @brief Provide a simple, human-readable explanation if the result.
const std::string *reason() const { return _reason; }
/// @brief Provide analyzer output in the provided Json::Value.
/// @param[out] Root object to populate with output.
virtual void to_json(Json::Value &root) const;
/// @brief Provide textual free-form evidence for the "reason".
/// @param f Textual free-form evidence.
void add_evidence(const std::string f) {
_evidence.push_back(f);
}
/// @brief Indicate that a particular data source was used to come to the conclusion returned by reason().
/// @param f A Data_Source relevant to the conclusion in reason().
void add_source(const Data_Source *f) {
if (f == NULL) {
abort();
}
_sources.push_back(f);
}
/// @brief Indicate the result is incrementally more significant.
/// @param evilness Degree to which this result is more significant.
void increase_severity_score(uint32_t evilness) {
_evilness += evilness;
}
/// @brief Indicate how significant this result is.
/// @param evilness Degree of significance of this result.
void set_severity_score(uint32_t evilness) {
_evilness = evilness;
}
/// @brief Return a number indicating the relative significance of this result.
/// @return The relative significance of this result.
uint32_t severity_score() const {
return _evilness;
}
void set_pure_output(bool pure) {
_pure = pure;
}
bool pure_output() const {
return _pure;
}
private:
analyzer_status _status = analyzer_status_ok;
std::string *_reason = NULL;
std::vector<std::string> _evidence;
std::vector<const Data_Source*> _sources;
void to_json_add_array(Json::Value &root,
std::string name,
std::vector<std::string> array) const;
uint32_t _evilness = 0;
bool _pure = false;
};
/// @brief Base class for an Analyzer Result which spans a period.
///
/// Examples would include a momentary attitude control loss.
class Analyzer_Result_Period : public Analyzer_Result {
public:
Analyzer_Result_Period() :
Analyzer_Result()
{ }
virtual void to_json(Json::Value &root) const override;
void set_T_start(const uint64_t start) { _T_start = start; }
uint64_t T_start() const { return _T_start; }
void set_T_stop(const uint64_t stop) { _T_stop = stop; }
uint64_t T_stop() const { return _T_stop; }
uint64_t duration() const { return _T_stop - _T_start; }
private:
uint64_t _T_start = 0;
uint64_t _T_stop;
};
/// @brief Base class for an Analyzer Result which provides information derived over the entire period of data input.
///
/// Examples would include "How many bytes of the input were processed".
class Analyzer_Result_Summary : public Analyzer_Result {
public:
Analyzer_Result_Summary() :
Analyzer_Result()
{ }
// virtual void to_json(Json::Value &root) const override;
private:
};
/// @brief Base class for an Analyzer Result which does not span any time.
///
/// Examples would include a "Crash" event present in a log.
class Analyzer_Result_Event : public Analyzer_Result {
public:
Analyzer_Result_Event() :
Analyzer_Result()
{ }
virtual void to_json(Json::Value &root) const;
void set_T(uint64_t timestamp) {
_T = timestamp;
}
uint64_t T() const {
return _T;
}
private:
uint64_t _T;
};
/// @brief Base class for all analyzers.
///
/// @description Extend this class to create a new analyzer.
///
/// An Analyzer tracks changes to a vehicle model over time to
/// determine if anything untoward is happening. "evaluate()" is
/// called repeatedly when the model's state changes, and "end_of_log"
/// is called when no more input will be forthcoming. An Analyzer is
/// expected to output Analyzer_Result objects through the "add_result"
/// object.
class Analyzer {
public:
/// @brief Constructor for Analyzer.
/// @param vehicle The vehicle model to be analyzed.
/// @param data_sources A mapping of abstract data source names to their concrete data sources (e.g. ATTITUDE -> [ ATT.Pitch, ATT.Roll ]).
Analyzer(AnalyzerVehicle::Base *&vehicle, Data_Sources &data_sources) :
_vehicle(vehicle),
_data_sources(data_sources)
{ }
virtual ~Analyzer() { }
/// @brief Configure an analyzer from a .ini config file
/// @param config The configuration source.
/// @return true if configuration succeeded.
virtual bool configure(INIReader *config UNUSED) {
return true;
}
/// @brief a simple name that used to refer to this Analyzer.
virtual const std::string name() const = 0;
/// @brief Outlines the reason this test exists.
virtual const std::string description() const = 0;
/// @brief Provide analyzer output in the provided Json::Value.
/// @param[out] root Object to populate with output
virtual void results_json_results(Json::Value &root) const;
/// @brief Return the analyzer's status represented as a string.
const char *status_as_string() const {
return _status_as_string(status());
}
/// @brief Set whether to produce output compatible with older versions.
/// @param purity True if compatability fields should not be produced
void set_pure_output(bool pure) {
_pure = pure;
}
/// @brief Returns true if compatability fields will not be produced.
/// @return true if compatability fields will not be produced.
bool pure_output() const {
return _pure;
}
/// @brief Return all results this analyzer has produced.
std::vector<Analyzer_Result*> results() const {
return _results;
}
/// @brief Return the number of results this analyzer has produced.
uint16_t result_count() const {
return _results.size();
}
/// @brief Returns a number "score" indicating how significant this result may be.
virtual uint32_t severity_score() const;
/// @brief Called whenever the vehicle's state changes.
virtual void evaluate() = 0;
/// @brief Called when no more input will be forthcoming.
/// @param packet_count The number of packets processed to update the model.
virtual void end_of_log(uint32_t packet_count UNUSED) { }
/// @brief Provide the Analyzer's overall status.
/// @return The Analyzer overall status.
analyzer_status status() const;
protected:
// @brief Add a result for this Analyzer.
// @param result The result to add.
virtual void add_result(Analyzer_Result* result) {
result->set_pure_output(pure_output());
_results.push_back(result);
}
/// @brief Provide the Analyzer Result's status.
/// @return The Analyzer_Result's status.
std::string to_string(double x);
/// @brief Vehicle model.
/// @details Updated by LA_MsgHandler* and analyzing_mavlink_message_handler, analyzed by analyzer_*.
AnalyzerVehicle::Base *&_vehicle;
/// @brief Map from abstract data source to concrete data source.
/// @details e.g. BATTERY_REMAINING -> SYS_STATUS.battery_remaining.
Data_Sources &_data_sources;
bool _pure = false;
private:
std::vector<Analyzer_Result*> _results;
};
#endif
| true |
72705f89fe9b5bf57182e61304728d8864bed169 | C++ | AlexUnderMoscow/DSP | /_DSP150217/arrow.cpp | UTF-8 | 3,802 | 2.53125 | 3 | [] | no_license |
#include <QtGui>
#include "arrow.h"
#include <math.h>
const qreal Pi = 3.1428;
Arrow::Arrow(QWidget *startItem, QWidget *endItem, unsigned short _startID, unsigned short _stopID,
QGraphicsItem *parent, QGraphicsScene *scene)
: QGraphicsLineItem(parent)
{
myStartItem = startItem;
myEndItem = endItem;
startID = _startID;
stopID = _stopID;
setFlag(QGraphicsItem::ItemIsSelectable, true);
myColor = Qt::black;
setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
queue = std::shared_ptr<fifo>(new fifo(tmpBufSize));
sc = scene;
}
Arrow::~Arrow()
{
}
void Arrow::clear()
{
sc->removeItem(this); //!!!!
}
QRectF Arrow::boundingRect() const
{
qreal extra = (pen().width() + 20) / 2.0;
return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),
line().p2().y() - line().p1().y()))
.normalized()
.adjusted(-extra, -extra, extra, extra);
}
QPainterPath Arrow::shape() const
{
QPainterPath path = QGraphicsLineItem::shape();
return path;
}
void Arrow::updatePosition()
{
QPointF s(myStartItem->x()+myStartItem->width()/2,
myStartItem->y()+myStartItem->height()/2);
QPointF f(myEndItem->x()+myEndItem->width()/2,
myEndItem->y()+myEndItem->height()/2);
QLineF thisline(s, f);
setLine(thisline);
}
bool Arrow::inWidget(QWidget *w, float mx, float my)
{
int up,down,left,right;
bool inX,inY;
inX = false;
inY = false;
left = w->x();
right = w->x()+w->width();
up = w->y();
down = w->y()+w->height();
if ((mx > left) && (mx < right))
{
inX = true;
}
if ((my > up) && (my < down))
{
inY = true;
}
if (inX && inY)
{
return true;
}
else
{
return false;
}
}
void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
QPen myPen = pen();
myPen.setColor(myColor);
// qreal arrowSize = 20;
painter->setPen(myPen);
painter->setBrush(myColor);
QPointF str(myStartItem->x()+myStartItem->width()/2,
myStartItem->y()+myStartItem->height()/2);
QPointF stp(myEndItem->x()+myEndItem->width()/2,
myEndItem->y()+myEndItem->height()/2);
QLineF centerLine(str, stp);
float dx = centerLine.dx();
float dy = centerLine.dy();
float rel = dy/dx;
float angle = atan(rel);
int i = 0;
QPointF newpoint;
newpoint = stp;
while (inWidget(myEndItem,newpoint.x(),newpoint.y()))
{
if ((dx>=0) && (dy>=0))
{
newpoint.setX(stp.x()-i*cos(angle));
newpoint.setY(stp.y()-i*sin(angle));
}
if (((dx<0) && (dy<0)))
{
newpoint.setX(stp.x()+i*cos(angle));
newpoint.setY(stp.y()+i*sin(angle));
}
if ((dx>=0) && (dy<0))
{
newpoint.setX(stp.x()-i*cos(angle));
newpoint.setY(stp.y()-i*sin(angle));
}
if ((dx<0) && (dy>=0))
{
newpoint.setX(stp.x()+i*cos(angle));
newpoint.setY(stp.y()+i*sin(angle));
}
i++;
}
centerLine.setPoints(str, newpoint);
painter->drawLine(centerLine);
QPointF tmp1, tmp2;
int a =10; //длина концов стрелок
if (dx>=0)
{
tmp1.setX(newpoint.x()-a*cos(angle+0.2));
tmp2.setX(newpoint.x()-a*cos(angle-0.2));
}
else
{
tmp1.setX(newpoint.x()+a*cos(angle+0.2));
tmp2.setX(newpoint.x()+a*cos(angle-0.2));
}
if (dy>=0)
{
tmp1.setY(newpoint.y()-a*sin(angle+0.2));
tmp2.setY(newpoint.y()-a*sin(angle-0.2));
}
else
{
tmp1.setY(newpoint.y()+a*sin(angle+0.2));
tmp2.setY(newpoint.y()+a*sin(angle-0.2));
}
if ((dx>=0) && (dy<0))
{
tmp1.setY(newpoint.y()+a*sin(angle+0.2+Pi));
tmp2.setY(newpoint.y()+a*sin(angle-0.2+Pi));
}
if ((dx<0) && (dy>=0))
{
tmp1.setY(newpoint.y()+a*sin(angle+0.2));
tmp2.setY(newpoint.y()+a*sin(angle-0.2));
}
QLineF ar1(newpoint,tmp1);
painter->drawLine(ar1);
QLineF ar2(newpoint,tmp2);
painter->drawLine(ar2);
}
| true |
0f3bef35db94f0245d9cd82b66b5ebcb94a201ed | C++ | dlotko/SComplex | /inc/redHom/complex/BasicCellProxy.hpp | UTF-8 | 2,397 | 3.046875 | 3 | [] | no_license | #ifndef CELL_PROXY_HPP
#define CELL_PROXY_HPP
#include <boost/ref.hpp>
template<typename CellImplT>
class BasicCellProxy {
protected:
// boost::reference_wrapper<CellImplT> nonConstImpl;
mutable CellImplT impl;
public:
typedef typename CellImplT::Color Color;
typedef typename CellImplT::Dim Dim;
typedef typename CellImplT::Id Id;
typedef CellImplT Impl;
BasicCellProxy(): impl() {} //, nonConstImpl(impl) {}
BasicCellProxy(const CellImplT& _impl): impl(_impl) {} //, nonConstImpl(impl) {}
template<typename ImplT2>
BasicCellProxy(const ImplT2& _impl): impl(_impl) {}
Color getColor() const{
return impl.getColor();
}
template<Color color>
void setColor() const {
impl.template setColor<color>();
}
void setColor(const Color& color) const {
impl.setColor(color);
}
Dim getDim() const {
return impl.getDim();
}
Id getId() const {
return impl.getId();
}
bool operator<(const BasicCellProxy& b) const {
return impl < b.impl;
}
CellImplT* getImpl() const {
//return nonConstImpl.get_pointer();
return &(const_cast<BasicCellProxy*>(this)->impl);
}
};
template<typename CellImplT>
class BasicCellProxy<CellImplT*> {
protected:
mutable CellImplT* impl;
// boost::reference_wrapper<CellImplT> nonConstImpl;
public:
typedef typename CellImplT::Color Color;
typedef typename CellImplT::Dim Dim;
typedef typename CellImplT::Id Id;
typedef CellImplT Impl;
BasicCellProxy(): impl(NULL) {} //, nonConstImpl(*impl) {}
BasicCellProxy(CellImplT* _impl): impl(_impl) {} //, nonConstImpl(*impl) {}
BasicCellProxy(const BasicCellProxy<CellImplT>& other): impl(other.getImpl()) {}
//nonConstImpl(*impl) {}
Id getId() const
{
return impl->getId();
}
Color getColor() const{
return impl->getColor();
}
template<Color color>
void setColor() const {
impl->template setColor<color>();
}
void setColor(const Color& color) const {
impl->setColor(color);
}
Dim getDim() const {
return impl->getDim();
}
bool operator<(const BasicCellProxy& b) const {
return *impl < *b.impl;
}
CellImplT* getImpl() const {
return const_cast<BasicCellProxy*>(this)->impl;
}
};
template<typename CellImplT>
class BasicCellProxy<BasicCellProxy<CellImplT> >: public BasicCellProxy<CellImplT> {
BasicCellProxy();
BasicCellProxy(const BasicCellProxy&);
};
#endif
| true |
fd862c0279ea3a6644a308dcc21d634b8b33d78a | C++ | PierreLeBlond/Orangutan | /src/object/mesh.cpp | UTF-8 | 17,689 | 3.203125 | 3 | [] | no_license | #include "object/mesh.h"
Mesh::Mesh(std::string name) : Asset(name)
{
_indexes = new unsigned int ;
_positions = new float;
_normals = new float;
_texCoords = new float;
}
Mesh::Mesh(const Mesh & mesh) : Asset(mesh.getName()){
const float* texCoords = mesh.getTexCoords();
const float* normals = mesh.getNormals();
const float* positions = mesh.getPositions();
const unsigned int * indexes = mesh.getIndexes();
_numberOfVertices = mesh.getNumberOfVertices();
_numberOfNormals = mesh.getNumberOfNormals();
_numberOfTexCoords = mesh.getNumberOfTexCoords();
_numberOfTriangles = mesh.getNumberOfTriangles();
_indexes = new unsigned int [3 * _numberOfTriangles];
_positions = new float[3 * _numberOfVertices];
_normals = new float[3 * _numberOfNormals];
_texCoords = new float[2 * _numberOfTexCoords];
copyIndexes(indexes);
copyNormals(normals);
copyPositions(positions);
copyTexCoords(texCoords);
}
Mesh::~Mesh()
{
delete[] _texCoords;
delete[] _normals;
delete[] _positions;
delete[] _indexes;
}
Mesh& Mesh::operator=(const Mesh& mesh){
delete[] _texCoords;
delete[] _normals;
delete[] _positions;
delete[] _indexes;
setName(mesh.getName());
const float* texCoords = mesh.getTexCoords();
const float* normals = mesh.getNormals();
const float* positions = mesh.getPositions();
const unsigned int * indexes = mesh.getIndexes();
_numberOfVertices = mesh.getNumberOfVertices();
_numberOfNormals = mesh.getNumberOfNormals();
_numberOfTexCoords = mesh.getNumberOfTexCoords();
_numberOfTriangles = mesh.getNumberOfTriangles();
_indexes = new unsigned int [3 * _numberOfTriangles];
_positions = new float[3 * _numberOfVertices];
_normals = new float[3 * _numberOfNormals];
_texCoords = new float[2 * _numberOfTexCoords];
copyIndexes(indexes);
copyNormals(normals);
copyPositions(positions);
copyTexCoords(texCoords);
return *this;
}
void Mesh::setObj(std::vector<glm::core::type::vec3> vertexList, std::vector<glm::core::type::vec3> normalList, std::vector<glm::core::type::vec2> texCoordList, std::vector<unsigned int > faceIndexes)
{
//ensure that memory is freed before any allocation
delete[] _texCoords;
delete[] _normals;
delete[] _positions;
delete[] _indexes;
_numberOfTriangles = faceIndexes.size() / 3.0;
_indexes = new unsigned int [3 * _numberOfTriangles];
for (unsigned int i = 0; i < _numberOfTriangles; i++)
{
for (unsigned int j = 0; j < 3; j++)
{
_indexes[3 * i + j] = faceIndexes[3 * i + j];
}
}
_numberOfVertices = (unsigned int ) vertexList.size();
_positions = new float[3 * _numberOfVertices];
for (unsigned int i = 0; i < _numberOfVertices; ++i)
{
_positions[3 * i + 0] = vertexList[i].x;
_positions[3 * i + 1] = vertexList[i].y;
_positions[3 * i + 2] = vertexList[i].z;
}
_numberOfNormals = (unsigned int ) normalList.size();
_normals = new float[3 * _numberOfNormals];
for (unsigned int i = 0; i < _numberOfNormals; ++i)
{
_normals[3 * i + 0] = normalList[i].x;
_normals[3 * i + 1] = normalList[i].y;
_normals[3 * i + 2] = normalList[i].z;
}
_numberOfTexCoords = (unsigned int ) texCoordList.size();
_texCoords = new float[2 * _numberOfTexCoords];
for (unsigned int i = 0; i < _numberOfTexCoords; ++i)
{
_texCoords[2 * i + 0] = texCoordList[i].s;
_texCoords[2 * i + 1] = texCoordList[i].t;
}
}
void Mesh::copyPositions(const float *positions){
for(unsigned int i = 0; i < 3 * _numberOfVertices; i++){
if(&positions[i] != 0){
_positions[i] = positions[i];
}
}
}
void Mesh::copyNormals(const float *normals){
for(unsigned int i = 0; i < 3 * _numberOfNormals; i++){
if(&normals[i] != 0){
_normals[i] = normals[i];
}
}
}
void Mesh::copyTexCoords(const float *texCoord){
for(unsigned int i = 0; i < 2 * _numberOfTexCoords; i++){
if(&texCoord[i] != 0){
_texCoords[i] = texCoord[i];
}
}
}
void Mesh::copyIndexes(const unsigned int *indexes){
for(unsigned int i = 0; i < 3 * _numberOfTriangles; i++){
if(&indexes[i] != 0){
_indexes[i] = indexes[i];
}
}
}
std::shared_ptr<Mesh> Mesh::createSquare(const std::string& name){
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>(name);
std::vector<glm::vec3> vertexList;
std::vector<glm::vec3> normalList;
std::vector<glm::vec2> texCoordList;
vertexList.push_back(glm::vec3(-1.0f, -1.0f, 0.0f));
vertexList.push_back(glm::vec3(1.0f, -1.0f, 0.0f));
vertexList.push_back(glm::vec3(-1.0f, 1.0f, 0.0f));
vertexList.push_back(glm::vec3(1.0f, 1.0f, 0.0f));
normalList.push_back(glm::vec3(0.0f, 0.0f, -1.0f));
normalList.push_back(glm::vec3(0.0f, 0.0f, -1.0f));
normalList.push_back(glm::vec3(0.0f, 0.0f, -1.0f));
normalList.push_back(glm::vec3(0.0f, 0.0f, -1.0f));
texCoordList.push_back(glm::vec2(0.0f, 0.0f));
texCoordList.push_back(glm::vec2(1.0f, 0.0f));
texCoordList.push_back(glm::vec2(0.0f, 1.0f));
texCoordList.push_back(glm::vec2(1.0f, 1.0f));
std::vector<unsigned int > faceIndexes;
faceIndexes.push_back(0);
faceIndexes.push_back(1);
faceIndexes.push_back(2);
faceIndexes.push_back(1);
faceIndexes.push_back(2);
faceIndexes.push_back(3);
mesh->setObj(vertexList, normalList, texCoordList, faceIndexes);
return mesh;
}
std::shared_ptr<Mesh> Mesh::createCube(int resolution, const std::string& name){
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>(name);
std::vector<glm::vec3> vertexList;
std::vector<glm::vec3> normalList;
std::vector<glm::vec2> texCoordList;
std::vector<unsigned int > faceIndexes;
//front
//0
vertexList.push_back(glm::vec3(1.0, 1.0, 1.0));
normalList.push_back(glm::vec3(0.0, 0.0, 1.0));
texCoordList.push_back(glm::vec2(0.5, 0.3334));
//1
vertexList.push_back(glm::vec3(-1.0, 1.0, 1.0));
normalList.push_back(glm::vec3(0.0, 0.0, 1.0));
texCoordList.push_back(glm::vec2(0.25, 0.3334));
//2
vertexList.push_back(glm::vec3(-1.0, -1.0, 1.0));
normalList.push_back(glm::vec3(0.0, 0.0, 1.0));
texCoordList.push_back(glm::vec2(0.25, 0.0));
//3
vertexList.push_back(glm::vec3(1.0, -1.0, 1.0));
normalList.push_back(glm::vec3(0.0, 0.0, 1.0));
texCoordList.push_back(glm::vec2(0.5, 0.0));
faceIndexes.push_back(0);
faceIndexes.push_back(1);
faceIndexes.push_back(2);
faceIndexes.push_back(0);
faceIndexes.push_back(2);
faceIndexes.push_back(3);
//back
//4
vertexList.push_back(glm::vec3(1.0, 1.0, -1.0));
normalList.push_back(glm::vec3(0.0, 0.0, -1.0));
texCoordList.push_back(glm::vec2(0.5, 0.6665));
//5
vertexList.push_back(glm::vec3(-1.0, 1.0, -1.0));
normalList.push_back(glm::vec3(0.0, 0.0, -1.0));
texCoordList.push_back(glm::vec2(0.25, 0.6665));
//6
vertexList.push_back(glm::vec3(-1.0, -1.0, -1.0));
normalList.push_back(glm::vec3(0.0, 0.0, -1.0));
texCoordList.push_back(glm::vec2(0.25, 1.0));
//7
vertexList.push_back(glm::vec3(1.0, -1.0, -1.0));
normalList.push_back(glm::vec3(0.0, 0.0, -1.0));
texCoordList.push_back(glm::vec2(0.5, 1.0));
faceIndexes.push_back(4);
faceIndexes.push_back(5);
faceIndexes.push_back(6);
faceIndexes.push_back(4);
faceIndexes.push_back(6);
faceIndexes.push_back(7);
//top
//8
vertexList.push_back(glm::vec3(1.0, 1.0, -1.0));
normalList.push_back(glm::vec3(0.0, 1.0, 0.0));
texCoordList.push_back(glm::vec2(0.5, 0.6665));
//9
vertexList.push_back(glm::vec3(-1.0, 1.0, -1.0));
normalList.push_back(glm::vec3(0.0, 1.0, 0.0));
texCoordList.push_back(glm::vec2(0.25, 0.6665));
//10
vertexList.push_back(glm::vec3(-1.0, 1.0, 1.0));
normalList.push_back(glm::vec3(0.0, 1.0, 0.0));
texCoordList.push_back(glm::vec2(0.25, 0.3334));
//11
vertexList.push_back(glm::vec3(1.0, 1.0, 1.0));
normalList.push_back(glm::vec3(0.0, 1.0, 0.0));
texCoordList.push_back(glm::vec2(0.5, 0.3334));
faceIndexes.push_back(8);
faceIndexes.push_back(9);
faceIndexes.push_back(10);
faceIndexes.push_back(8);
faceIndexes.push_back(10);
faceIndexes.push_back(11);
//bottom
//12
vertexList.push_back(glm::vec3(1.0, -1.0, -1.0));
normalList.push_back(glm::vec3(0.0, -1.0, 0.0));
texCoordList.push_back(glm::vec2(0.75, 0.6665));
//13
vertexList.push_back(glm::vec3(-1.0, -1.0, -1.0));
normalList.push_back(glm::vec3(0.0, -1.0, 0.0));
texCoordList.push_back(glm::vec2(1.0, 0.6665));
//14
vertexList.push_back(glm::vec3(-1.0, -1.0, 1.0));
normalList.push_back(glm::vec3(0.0, -1.0, 0.0));
texCoordList.push_back(glm::vec2(1.0, 0.3334));
//15
vertexList.push_back(glm::vec3(1.0, -1.0, 1.0));
normalList.push_back(glm::vec3(0.0, -1.0, 0.0));
texCoordList.push_back(glm::vec2(0.75, 0.3334));
faceIndexes.push_back(12);
faceIndexes.push_back(13);
faceIndexes.push_back(14);
faceIndexes.push_back(12);
faceIndexes.push_back(14);
faceIndexes.push_back(15);
//right
//16
vertexList.push_back(glm::vec3(1.0, 1.0, -1.0));
normalList.push_back(glm::vec3(1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.5, 0.6665));
//17
vertexList.push_back(glm::vec3(1.0, 1.0, 1.0));
normalList.push_back(glm::vec3(1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.5, 0.3334));
//18
vertexList.push_back(glm::vec3(1.0, -1.0, 1.0));
normalList.push_back(glm::vec3(1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.75, 0.3334));
//19
vertexList.push_back(glm::vec3(1.0, -1.0, -1.0));
normalList.push_back(glm::vec3(1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.75, 0.6665));
faceIndexes.push_back(16);
faceIndexes.push_back(17);
faceIndexes.push_back(18);
faceIndexes.push_back(16);
faceIndexes.push_back(18);
faceIndexes.push_back(19);
//left
//20
vertexList.push_back(glm::vec3(-1.0, 1.0, -1.0));
normalList.push_back(glm::vec3(-1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.25, 0.6665));
//21
vertexList.push_back(glm::vec3(-1.0, 1.0, 1.0));
normalList.push_back(glm::vec3(-1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.25, 0.3334));
//22
vertexList.push_back(glm::vec3(-1.0, -1.0, 1.0));
normalList.push_back(glm::vec3(-1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.0, 0.3334));
//23
vertexList.push_back(glm::vec3(-1.0, -1.0, -1.0));
normalList.push_back(glm::vec3(-1.0, 0.0, 0.0));
texCoordList.push_back(glm::vec2(0.0, 0.6665));
faceIndexes.push_back(20);
faceIndexes.push_back(21);
faceIndexes.push_back(22);
faceIndexes.push_back(20);
faceIndexes.push_back(22);
faceIndexes.push_back(23);
for(int subdivide = 0;subdivide < resolution; subdivide++){
size_t nbVertex = vertexList.size();
int **mat = new int *[nbVertex];
for(size_t i=0;i<nbVertex;i++){
mat[i] = new int [nbVertex];
}
for(size_t i = 0; i < nbVertex;i++)
for(size_t j = 0;j < nbVertex;j++)
mat[i][j] = -1;
unsigned int stIndex;
unsigned int sndIndex;
unsigned int thIndex;
unsigned int stNewIndex;
unsigned int sndNewIndex;
unsigned int thNewIndex;
size_t numberOfIndexes = nbVertex - 1;
size_t nbFace = faceIndexes.size()/3;
for(size_t i = 0; i < nbFace;i++){
stIndex = faceIndexes[3*i];
sndIndex = faceIndexes[3*i + 1];
thIndex = faceIndexes[3*i + 2];
if(mat[stIndex][sndIndex] != -1){
stNewIndex = mat[stIndex][sndIndex];
} else if(mat[sndIndex][stIndex] != -1){
stNewIndex = mat[sndIndex][stIndex];
} else {
stNewIndex = (unsigned int ) ++numberOfIndexes;
mat[stIndex][sndIndex] = stNewIndex;
glm::vec3 stPosition = vertexList[stIndex];
glm::vec3 sndPosition = vertexList[sndIndex];
vertexList.push_back(0.5f*(stPosition + sndPosition));
glm::vec2 stTex = texCoordList[stIndex];
glm::vec2 sndTex = texCoordList[sndIndex];
texCoordList.push_back(0.5f*(stTex + sndTex));
normalList.push_back(normalList[stIndex]);
}
if(mat[thIndex][sndIndex] != -1){
sndNewIndex = mat[thIndex][sndIndex];
} else if(mat[sndIndex][thIndex] != -1){
sndNewIndex = mat[sndIndex][thIndex];
} else {
sndNewIndex = (unsigned int ) ++numberOfIndexes;
mat[thIndex][sndIndex] = sndNewIndex;
glm::vec3 thPosition = vertexList[thIndex];
glm::vec3 sndPosition = vertexList[sndIndex];
vertexList.push_back(0.5f*(thPosition + sndPosition));
glm::vec2 thTex = texCoordList[thIndex];
glm::vec2 sndTex = texCoordList[sndIndex];
texCoordList.push_back(0.5f*(thTex + sndTex));
normalList.push_back(normalList[sndIndex]);
}
if(mat[stIndex][thIndex] != -1){
thNewIndex = mat[stIndex][thIndex];
} else if(mat[thIndex][stIndex] != -1){
thNewIndex = mat[thIndex][stIndex];
} else {
thNewIndex = (unsigned int ) ++numberOfIndexes;
mat[stIndex][thIndex] = thNewIndex;
glm::vec3 stPosition = vertexList[stIndex];
glm::vec3 thPosition = vertexList[thIndex];
vertexList.push_back(0.5f*(stPosition + thPosition));
glm::vec2 stTex = texCoordList[stIndex];
glm::vec2 thTex = texCoordList[thIndex];
texCoordList.push_back(0.5f*(stTex + thTex));
normalList.push_back(normalList[thIndex]);
}
faceIndexes[3*i] = stNewIndex;
faceIndexes[3*i + 1] = sndNewIndex;
faceIndexes[3*i + 2] = thNewIndex;
faceIndexes.push_back(stIndex);
faceIndexes.push_back(stNewIndex);
faceIndexes.push_back(thNewIndex);
faceIndexes.push_back(sndIndex);
faceIndexes.push_back(stNewIndex);
faceIndexes.push_back(sndNewIndex);
faceIndexes.push_back(thIndex);
faceIndexes.push_back(sndNewIndex);
faceIndexes.push_back(thNewIndex);
}
for (unsigned int i=0; i < nbVertex; i++)
delete[] mat[i];
delete[] mat;
}
mesh->setObj(vertexList, normalList, texCoordList, faceIndexes);
return mesh;
}
std::shared_ptr<Mesh> Mesh::createSphere(int resolution, const std::string& name){
std::shared_ptr<Mesh> mesh = createCube(resolution, name);
float* newNormals = new float[3 * mesh->getNumberOfNormals()];
float* newPositions = new float[3 * mesh->getNumberOfVertices()];
const float* oldPositions = mesh->getPositions();
for(unsigned int i = 0; i < mesh->getNumberOfVertices();i++){
float l = sqrt(oldPositions[3*i]*oldPositions[3*i] + oldPositions[3*i+1]*oldPositions[3*i+1] + oldPositions[3*i+2]*oldPositions[3*i+2]);
newPositions[3*i] = oldPositions[3*i]/l;
newNormals[3*i] = oldPositions[3*i];
newPositions[3*i + 1] = oldPositions[3*i + 1]/l;
newNormals[3*i + 1] = oldPositions[3*i + 1];
newPositions[3*i + 2] = oldPositions[3*i + 2]/l;
newNormals[3*i + 2] = oldPositions[3*i + 2];
}
mesh->copyNormals(newNormals);
mesh->copyPositions(newPositions);
return mesh;
}
std::shared_ptr<Mesh> Mesh::createCylinder(int resolution, const std::string& name){
std::shared_ptr<Mesh> mesh = createCube(resolution, name);
float* newNormals = new float[3 * mesh->getNumberOfNormals()];
float* newPositions = new float[3 * mesh->getNumberOfVertices()];
const float* oldPositions = mesh->getPositions();
for(unsigned int i = 0; i < mesh->getNumberOfVertices();i++){
if(oldPositions[3*i + 1] == 1.0 || oldPositions[3*i + 1] == -1.0){
float l = sqrt(oldPositions[3*i]*oldPositions[3*i] + oldPositions[3*i+2]*oldPositions[3*i+2]);
if(l > 1.0){
newPositions[3*i] = oldPositions[3*i]/l;
newPositions[3*i + 2] = oldPositions[3*i + 2]/l;
}
/*if(abs(positions[3*i]) >= abs(positions[3*i + 2])){
positions[3*i] = abs(positions[3*i + 2])*positions[3*i];
positions[3*i + 2] = abs(positions[3*i + 2])*positions[3*i + 2];
}else if(abs(positions[3*i]) < abs(positions[3*i + 2])){
positions[3*i] *= abs(positions[3*i]);
positions[3*i + 2] *= abs(positions[3*i]);
}*/
}else{
float l = sqrt(oldPositions[3*i]*oldPositions[3*i] + oldPositions[3*i+2]*oldPositions[3*i+2]);
newPositions[3*i] = oldPositions[3*i]/l;
newNormals[3*i] = oldPositions[3*i];
newPositions[3*i + 2] = oldPositions[3*i + 2]/l;
newNormals[3*i + 2] = oldPositions[3*i + 2];
}
}
mesh->copyNormals(newNormals);
mesh->copyPositions(newPositions);
return mesh;
}
| true |
fc41f6b63d9dbf01fba8d62f57840a0f38059ca0 | C++ | AniruddhaSadhukhan/C-Plus-Plus-Programs | /File Handling/eofFile.cpp | UTF-8 | 339 | 2.96875 | 3 | [] | no_license | #include<iostream>
#include<fstream>
using namespace std;
/*Write a C++ program to read and display contents of file. Use eof( ) function.*/
// by Aniruddha
int main()
{
string name;
int age;
char c;
ifstream in ("text.txt");
while(in.eof()==0)
{
in>>c;
cout<<c;
}
in.close();
return 0;
}
/*Sample Output
Aniruddhaa
*/
| true |
476cc807f66b1adeb1e81a8d30936b58e5f3e1ce | C++ | jordanlee008/Code | /USACO/Oct2015Bronze/speeding/speeding.cpp | UTF-8 | 1,054 | 2.671875 | 3 | [] | no_license | /*
ID: jorlee
PROG: speeding
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main () {
ifstream fin ("speeding.in");
ofstream fout ("speeding.out");
int N, M;
fin >> N >> M;
vector< vector<int> > n (N), m (M);
for (int i = 0; i < N; i++) {
vector<int> a (2);
fin >> a[0] >> a[1];
n[i] = a;
}
for (int i = 0; i < M; i++) {
vector<int> a (2);
fin >> a[0] >> a[1];
m[i] = a;
}
vector< vector<int> > len (100);
for (int i = 0; i < N; i++) {
int a = 0;
for (int j = 0; j < i; j++) {
a += n[j][0];
}
for (int k = 0; k < n[i][0]; k++)
len[a + k].push_back(n[i][1]);
}
for (int i = 0; i < M; i++) {
int a = 0;
for (int j = 0; j < i; j++) {
a += m[j][0];
}
for (int k = 0; k < m[i][0]; k++)
len[a + k].push_back(m[i][1]);
}
int out = 0;
for (int i = 0; i < 100; i++) {
if (len[i][0] < len[i][1])
out = max(len[i][1] - len[i][0], out);
}
fout << out << endl;
return 0;
}
| true |
1af70b09a8bae1f0b7957381930d2edc0f983384 | C++ | Solomia-Ratushna/oop2.4.1 | /Source.cpp | WINDOWS-1251 | 1,050 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include "Matrix.h"
#include <Windows.h>
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
Matrix A(3), B(3), z;
int x;
cout << " 1" << endl;
cin >> A;
cout << " 1:" << endl;
cout << A;
cout << " 1:" << A.MatrixNorm() << endl;
cout << " 2" << endl;
cin >> B;
cout << " 2:" << endl;
cout << B;
cout << " 2:" << B.MatrixNorm() << endl;
cout << "_____________________________" << endl;
cout << " 1 2:" << endl;
A.ComparisonMatrix(A, B);
cout << "_____________________________" << endl;
cout << "M " << endl;
cout << "x = ? "; cin >> x;
cout << " A :" << endl;
A* x;
cout << " :" << endl;
B* x; cout << endl;
return 0;
}
| true |
005e65250845a6c65488ad9d0fa41b1d91565e4d | C++ | THLEE-KR/Baekjoon-Online-Judge_THLEE | /20200731_1149/main.cpp | UTF-8 | 707 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int v[1010][10];
int ans[1010][10];
int main() {
int n;
cin >> n;
for(int i=0; i<n; i++){
cin >> v[i][0] >> v[i][1] >> v[i][2];
}
for(int i=0; i<3; i++)
ans[0][i] = v[0][i];
for(int i=1; i<n; i++){
for(int j=0; j<3; j++)
ans[i][j] = min(ans[i-1][(j+1)%3] + v[i][j],
ans[i-1][(j+2)%3] + v[i][j]);
}
// for(int i=0; i<3; i++){
// int result = min(ans[i][0], ans[i][1]);
// cout << min(result, ans[i][2]) << '\n';
// }
int result = min(ans[n-1][0], ans[n-1][1]);
cout << min(result, ans[n-1][2]) << '\n';
return 0;
}
| true |
c10688eac1d18230515c8431149dbef62840b261 | C++ | Gobukgol/Algorithm | /DP/B1463.cpp | UTF-8 | 1,448 | 2.859375 | 3 | [] | no_license | //
// B1463.cpp
// 23rdSoptAlgo
//
// Created by Minhyoung on 2019. 2. 4..
// Copyright © 2019년 Minhyoung. All rights reserved.
//
#include <cstdio>
#include <algorithm>
using namespace std;
int result[1000001] = {-1,};
void setMinValue(int n){
int minValue = -1;
if(n%2 == 0 && n%3 == 0){
if(result[n/2] == -1){
setMinValue(n/2);
}
if(result[n/3] == -1){
setMinValue(n/3);
}
if(result[n-1] == -1){
setMinValue(n-1);
}
minValue = min(min(result[n/2], result[n/3]),result[n-1]);
} else if(n%2==0){
if(result[n/2] == -1){
setMinValue(n/2);
}
if(result[n-1] == -1){
setMinValue(n-1);
}
minValue = min(result[n/2],result[n-1]);
} else if(n%3==0){
if(result[n/3] == -1){
setMinValue(n/3);
}
if(result[n-1] == -1){
setMinValue(n-1);
}
minValue = min(result[n/3],result[n-1]);
} else {
if(result[n-1] == -1){
setMinValue(n-1);
}
minValue = result[n-1];
}
result[n] = minValue+1;
}
int main(int argc,const char* argv[]){
int n;
scanf("%d",&n);
for(int i=0;i<=n;i++){
result[i] = -1;
}
result[1] = 0; result[2] = 1; result[3] = 1;
if(result[n] == -1){
setMinValue(n);
}
printf("%d",result[n]);
return 0;
}
| true |
7cebe11f806143674fe484742b89bef82d263ad2 | C++ | sparkfiresprairie/cpc | /dfs_bfs/word_search.cpp | UTF-8 | 1,440 | 3.46875 | 3 | [] | no_license | //
// Created by Xingyuan Wang on 4/13/17.
//
/*
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where
"adjacent" cells are those horizontally or vertically neighboring. The same
letter cell may not be used more than once.
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
*/
#include "DFSBFS.h"
bool dfs(vector<vector<char>>& board, string const& word, int i, int j, int b) {
int m = board.size(), n = board[0].size();
if (b >= word.size()) return true;
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[b]) return false;
vector<int> dir{0, 1, 0, -1, 0};
char c = board[i][j];
board[i][j] = 0;
for (int k = 0; k < 4; ++k) {
if (dfs(board, word, i + dir[k], j + dir[k + 1], b + 1)) return true;
}
board[i][j] = c;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[0].empty()) return false;
if (word.empty()) return false;
int m = board.size(), n = board[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (dfs(board, word, i, j, 0)) return true;
}
}
return false;
}
| true |
4370c5a6b15016f7b5c36e5db59e57315adf794e | C++ | yashart/neva_offline_gps_check_module | /drone_angle_header.cpp | UTF-8 | 1,315 | 2.71875 | 3 | [] | no_license | #include "drone_angle_header.h"
#include "drone_angles.h"
#include "stdio.h"
#include <stdlib.h>
DroneAngleHeader read_angles() {
DroneAngleHeader droneAngleHeader;
droneAngleHeader.angles = (DroneAngle*) calloc (10000, sizeof(*(droneAngleHeader.angles)));
FILE* textAngles = fopen("angles.txt", "r");
int minutes;
int seconds;
int mseconds;
int mtime;
double roll;
double pitch;
double yaw;
int i;
double height;
char lat[50];
char lon[50];
fscanf (textAngles, ";sau\n");
for (i = 0; fscanf(textAngles, "00:%d:%d.%d\t%s %s %lf %lf\t%lf\t%lf\n",
&minutes, &seconds, &mseconds, lat, lon, &height, &roll, &pitch, &yaw) != EOF ;i++) {
mtime = mseconds * 10 + seconds * 1000 + minutes * 1000 * 60;
droneAngleHeader.angles[i] = drone_angle_ctor(mtime, roll, pitch, yaw);
}
droneAngleHeader.count = i;
droneAngleHeader.angles = (DroneAngle*) realloc(droneAngleHeader.angles,
droneAngleHeader.count * sizeof(*(droneAngleHeader.angles)));
return droneAngleHeader;
}
DroneAngle get_angels_by_time(int timeMs, DroneAngleHeader droneAngleHeader) {
int i;
for (i = 0; droneAngleHeader.angles[i].time_ms < timeMs; i++);
return droneAngleHeader.angles[i];
}
| true |
6cd5c3d6dc40e3a4fd1e494f1739dfcaef0962f8 | C++ | Madness-D/CodeUp | /3 入门模拟/3.2 查找元素/E 学生查询.cpp | UTF-8 | 699 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
struct Student {
char xuehao[100];
char name[100];
char sex[100];
int age;
}stu[20];
int main() {
int m;
cin >> m;
while(m--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> stu[i].xuehao >> stu[i].name >> stu[i].sex >> stu[i].age;
}
char obj[100];
cin >> obj;
for (int i = 0; i < n; i++) {
if (!strcmp(obj, stu[i].xuehao)) {
cout << stu[i].xuehao << " " << stu[i].name << " " << stu[i].sex << " " << stu[i].age << endl;
}
}
}
return 0;
} | true |
2299bd69bd4b0716fc0c6241083ef9ca3882f292 | C++ | Pallesnik/Portfolio | /Game_Library/Developer.h | UTF-8 | 521 | 2.828125 | 3 | [] | no_license |
#include <string>
#include <iostream>
#include <vector>
#ifndef DEVELOPER_H_
#define DEVELOPER_H_
using namespace std;
class Developer{
protected:
string DevName;
int games;
float salary;
public:
Developer();
Developer(string a);
void setDeveloperName(string n);
void setnofGamesReleased(int nog);
void setSalaryEarned(float se);
string getDeveloperName();
int getnofGamesReleased();
float getSalaryEarned();
void DeveloperDisplay();
virtual int calcSalary();
};
#endif
| true |
f86180aab2c22be16f82ab159e56228b8ed52cbd | C++ | Shaykat/Data-Structure | /link list delete(complete).cpp | UTF-8 | 2,658 | 3.8125 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
class node{
int data;
node *next;
public:
node *start,*np,*p,*ptr,*delt,*prev;
void Add()
{
int v;
cin >> v;
np = new node;
np->data = v;
np->next=NULL;
if(start == NULL)
{
start = np;
}
else
p->next=np;
p=np;
}
void display()
{
ptr = start;
cout << "The created list is given bellow: " << endl;
while(ptr != NULL)
{
cout << ptr->data << " --> ";
ptr = ptr->next;
}
cout << endl;
cout << "\n\n";
}
void deletion()
{
int v;
cout << "Enter which node u want to delete: ";
cin >> v;
delt = start;
if(start->data == v)
{
start = delt->next;
delete(delt);
}
else
{
while(delt->data != v && delt->next !=NULL)
{
prev = delt;
delt = delt->next;
}
if(delt->data == v)
{
prev->next = delt->next;
delete(delt);
}
}
}
void delete_before()
{
int v;
cout << "Enter a value before which you want to delete: ";
cin >> v;
delt = start;
while(delt->next->data != v && delt->next->next != NULL)
{
prev = delt;
delt = delt->next;
}
if(delt->data == v)
{
cout << "No other node is exist before this node, so nothing to delete here \n\n";
}
if(delt == start)
{
start = delt->next;
delete(delt);
}
else if(delt->next->data == v)
{
prev->next = delt->next;
delete(delt);
}
}
void delete_after()
{
int v;
cout << "Enter a value after which value you want to delete: ";
cin >> v;
delt = start;
while(delt->data !=v && delt->next != NULL)
{
prev = delt;
delt = delt->next;
}
if(delt->next == NULL)
{
cout << "This is the last node,so there is no node to delete" << endl << endl;
}
else if(delt->data == v)
{
delt = delt->next;
prev = prev->next;
prev->next = delt->next;
delete(delt);
}
}
};
int main()
{
node list;
list.start = NULL;
int i,n;
cout << "Enter the number of value you want to add: ";
cin >> n;
cout << "Enter values to add: " << endl;
for(i=0;i<n;i++)
{
list.Add();
}
list.display();
list.deletion();
list.display();
list.delete_before();
list.display();
list.delete_after();
list.display();
}
| true |
054c83ed55a14de198986c01e68026562a9aeabf | C++ | dipendughosh/programs | /MSc_CompSc/3rd_sem/multimedia/quesn_3.c | UTF-8 | 4,129 | 2.859375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#define ALL -1
#define MAXCITIES 10
enum BOOL{FALSE,TRUE};
long *visited;//visited nodes set here
long *min_circuit;//min inner circuit for given node as start node at position indexed 0
long *ham_circuit;//optimal circuit with length stored at position indexed 0
long min_circuit_length;//min circuit lenth for given start node
int n;//city count
long matrix[MAXCITIES][MAXCITIES];//nondirectional nXn symmetric matrix
//to store path distances as sourceXdestination
long INFI;// INFINITY value to be defined by user
// function resets minimum circuit for a given start node
//with setting its id at index 0 and setting furthr node ids to -1
void reset_min_circuit(int s_v_id)
{
int i;
min_circuit[0]=s_v_id;
for(i=1;i<n;i++)
{
min_circuit[i]=-1;
}
}
// marks given node id with given flag
// if id==ALL it marks all nodes with given flag
void set_visited(int v_id,BOOL flag)
{
int i;
if(v_id==ALL)
{
for(i=0;i<n;i++)
{
visited[i]=flag;
}
}
else
{
visited[v_id]=flag;
}
}
// function sets hamiltonion circuit for a given path length
//with setting it at index 0 and setting furthr nodes from current min_circuit
void SET_HAM_CKT(long pl)
{
ham_circuit[0]=pl;
for(int i=0;i<n;i++)
{
ham_circuit[i+1]=min_circuit[i];
}
ham_circuit[n+1]=min_circuit[0];
}
//function sets a valid circuit by finiding min inner path for a given
//combination start vertex and next vertex to start vertex such that
// the 2nd vertex of circuits is always s_n_v and start and dest node is
//always s_v for all possible values of s_n_v, and then returns the
// valid circuit length for this combination
long get_valid_circuit(int s_v,int s_n_v)
{
int next_v,min,v_count=1;
long path_length=0;
min_circuit[0]=s_v;
min_circuit[1]=s_n_v;
set_visited(s_n_v,TRUE);
path_length+=matrix[s_v][s_n_v];
for(int V=s_n_v;v_count<n-1;v_count++)
{
min=INFI;
for(int i=0;i<n;i++)
{
if( matrix[V][i]<INFI && !visited[i] && matrix[V][i]<=min )
{
min=matrix[V][next_v=i];
}
}
set_visited(next_v,TRUE);
V=min_circuit[v_count+1]=next_v;
path_length+=min;
}
path_length+=matrix[min_circuit[n-1]][s_v];
return(path_length);
}
void main()
{
int pathcount,i,j,source,dest;
long dist=0;
long new_circuit_length=INFI;
clrscr();
printf("Make sure that infinity value < sum of all path distances\nSet Infinity at (signed long):");
scanf("%ld",&INFI);
printf("Enter no. of cities(MAX:%d):",MAXCITIES);
scanf("%d",&n);
printf("Enter path count:");
scanf("%d",&pathcount);
printf("Enter paths:< source_id destination_id distance >\n ids varying from 0 to %d\n",n-1);
//init all matrix distances to infinity
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
matrix[i][j]=INFI;
}
}
//populate the matrix
for(i=0;i<pathcount;i++)
{
printf("[path %d]:",i);
scanf("%d %d %ld",&source,&dest,&dist);
if(source!=dest)
{
matrix[source][dest]=matrix[dest][source]=dist;
}
}
visited=new long[n];
min_circuit=new long[n];
ham_circuit=new long[n+2];
min_circuit_length=INFI;
// algorithm
//for each vertex, S_V as a staring node
for(int S_V_id=0;S_V_id<n;S_V_id++)
{
//for each and non start vertex as i
for(i=0;i<n;i++)
{
//set all to unvisited
set_visited(ALL,FALSE);
// set staring vertex as visited
set_visited(S_V_id,TRUE);
//reset/init minimum circuit
reset_min_circuit(S_V_id);
// obtain circuit for combination of S_V and i
new_circuit_length=get_valid_circuit(S_V_id,i);
// if newer length is less than the previously
//calculated min then set it as min and set the
//current circuit in hamiltonion circuit
if(new_circuit_length<=min_circuit_length)
{
SET_HAM_CKT(min_circuit_length=new_circuit_length);
}
}
}
// if any circuit found
if(min_circuit_length<INFI)
{
printf("\n\nMinimum circuit length is: %ld\nCircuit is:\n",min_circuit_length);
for(i=1;i<n+2;i++)
{
printf("<%ld> ",ham_circuit[i]);
}
}
else
{
printf("\n\nNo hamiltonian circuit !");
}
getch();
delete []visited;
delete []min_circuit;
delete []ham_circuit;
} | true |