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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a8cb5237e76f586eb01583237d46a66821c83609 | C++ | drop-stones/Scheduling-Algorithms-Simulation | /schedule_sjf.hpp | UTF-8 | 1,316 | 3.28125 | 3 | [] | no_license | /**
* Implementation of Shortest-Job-First Scheduling.
*/
#include "CPU.hpp"
#include <deque>
#include <algorithm>
namespace cpu {
// burst-time order
bool operator< (const class task &t1, const class task &t2) {
return t1.get_burst () < t2.get_burst ();
}
bool operator> (const class task &t1, const class task &t2) {
return t1.get_burst () > t2.get_burst ();
}
class sjf_cpu : public CPU {
public:
sjf_cpu (std::initializer_list<class task> l, int q) : task_list {l}, CPU {q, 0, 0} {}
sjf_cpu (class task& t, int q) : task_list {t}, CPU {q, 0, 0} {}
sjf_cpu (int q) : task_list {}, CPU {q, 0, 0} {}
~sjf_cpu () {}
void insert (class task& t) override
{
task_list.push_back (t);
std::sort (task_list.begin (), task_list.end ());
}
class task* fetch_task () override
{
if (task_list.empty ())
return nullptr;
auto t = &task_list.front ();
task_list.pop_front ();
return t;
}
class task* process_one_task (class task* t) override
{
if (t == nullptr)
return nullptr;
t->set_wait (duration);
t->print (1);
duration += t->get_burst ();
return t;
}
private:
std::deque<class task> task_list;
};
} // namespace cpu | true |
5c2a0fa3da60e54357c70f99a97c3aba330afb48 | C++ | lostsquirrel/cpp_learning | /src/03_function/gcd_lcm.ex.cpp | UTF-8 | 1,046 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*
*编写函数gcd与lcm,分别求两个正整数的最大公约数与最小公倍数。
*/
int gcd(int a, int b);
int lcm(int a, int b);
int min(int a, int b);
bool is_divisible(int a, int b);
int main() {
cout << gcd(6, 12) <<endl;
cout << lcm(6, 12) <<endl;
cout << gcd(5, 7) <<endl;
cout << lcm(5, 7) <<endl;
return 0;
}
int min(int a, int b) {
int smaller = a;
if (b < a) {
smaller = b;
}
return smaller;
}
int gcd(int a, int b) {
int gcd = 1;
int x = 2;
int limit = min(a, b);
while (x <= limit) {
if (is_divisible(a, x) && is_divisible(b, x)) {
a /= x;
b /= x;
gcd *= x;
}
x++;
}
return gcd;
}
int lcm(int a, int b) {
int lcm = 1;
int x = 2;
int limit = min(a, b);
while (x <= limit) {
if (is_divisible(a, x) && is_divisible(b, x)) {
a /= x;
b /= x;
lcm *= x;
}
x++;
}
return lcm * a * b;
}
bool is_divisible(int a, int b) {
return !(a % b);
}
/*
测试用例:
*/
| true |
e019e7ecda1bb10452076decaaef4d2ffcfd69bd | C++ | AhoiJ/olio-ohjelmointi-kurssi | /Vko46_2017/T1-2/main.cpp | UTF-8 | 527 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <exception>
#include <stdexcept>
#include "Header.h"
using std::cout; using std::cin; using std::endl; using std::cout; using std::exception;
int main()
{
/*
std::vector<int> myvector(10);
try {
myvector.at(20) = 100; // vector::at throws an out-of-range
}
catch (const std::out_of_range& oor) {
cout << "Out of Range error: " << oor.what() << '\n';
}
try {
}
system("pause");
return 0;
*/
heady ajo;
ajo.laitaVektoriin();
system("pause");
return 0;
} | true |
a4707eb5bc7057641b662b2f1ccdd26cf6ac7b9a | C++ | mascure/PAT | /pat1022_me.cpp | UTF-8 | 3,474 | 2.8125 | 3 | [] | no_license | //pat 1022. Digital Library (30)
//看别人的代码,找处理输入,字符串的简便方法
#include<iostream>
#include<iomanip>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#include<stack>
//#include<map>
#include<algorithm>
#define MAXN 505
#define inf 0x7fffffff
#define LL long long
using namespace std;
struct Book
{
int ID;
char title[85];
char author[85];
int keyNum;
char key[5][15];
char publisher[85];
char year[5];
};
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int main()
{
//freopen("in.txt","r",stdin);
int i,j,k,N,M;
//char s[80];
//Book a;
//gets(s);
//scanf("%s %s %s %s %s",a.key[0],a.key[1],a.key[2],a.key[3],a.key[4]);
//printf("%s %s %s %s %s\n",a.key[0],a.key[1],a.key[2],a.key[3],a.key[4]);
while(scanf("%d",&N)!=EOF)
{
Book* book=new Book[N];
int* res=new int[N],resN=0;
for(i=0;i<N;i++)
{
scanf("%d",&book[i].ID);
getchar();
gets(book[i].title);
gets(book[i].author);
char tmp[85];
gets(tmp);
j=0,k=0;
book[i].keyNum=0;
while(tmp[j]!='\0')
{
int t=0;
//若为空格,跳到下一个字符
if(tmp[j]==' ')j++;
while(tmp[j]!=' '&&tmp[j]!='\0')
{
book[i].key[k][t]=tmp[j];
t++;
j++;
}
book[i].key[k][t]='\0';
k++;
}
book[i].keyNum=k;
gets(book[i].publisher);
scanf("%s",book[i].year);
//printf("%s\n",book[i].title);
//printf("%s\n",book[i].author);
//for(j=0;j<book[i].keyNum;j++)
//printf("%s\n",book[i].key[j]);
}
scanf("%d",&M);
int id;
char query[85];
for(i=0;i<M;i++)
{
resN=0;
scanf("%d:",&id);
getchar();
gets(query);
printf("%d: %s\n",id,query);
if(id==1)
{
for(j=0;j<N;j++)
if(strcmp(book[j].title,query)==0)
res[resN++]=book[j].ID;
}
else if(id==2)
{
for(j=0;j<N;j++)
if(strcmp(book[j].author,query)==0)
res[resN++]=book[j].ID;
}
else if(id==3)
{
for(j=0;j<N;j++)
{
for(k=0;k<book[j].keyNum;k++)
if(strcmp(book[j].key[k],query)==0)
{
res[resN++]=book[j].ID;
break;
}
}
}
else if(id==4)
{
for(j=0;j<N;j++)
if(strcmp(book[j].publisher,query)==0)
res[resN++]=book[j].ID;
}
else if(id==5)
{
for(j=0;j<N;j++)
if(strcmp(book[j].year,query)==0)
res[resN++]=book[j].ID;
}
if(resN==0)
printf("Not Found\n");
else
{
qsort(res,resN,sizeof(res[0]),cmp);
for(j=0;j<resN;j++)
printf("%d\n",res[j]);
}
}
}
return 0;
}
| true |
11adf9ad6c66ff5745acffb1d54bb977a12db491 | C++ | TensorCodeGen/tensor-codegen | /libcxx/test/std/iterators/iterator.primitives/range.iter.ops/range.iter.ops.prev/iterator.pass.cpp | UTF-8 | 1,125 | 2.515625 | 3 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17
// UNSUPPORTED: libcpp-no-concepts
// UNSUPPORTED: gcc-10
// ranges::prev(iterator)
#include <iterator>
#include <array>
#include <cassert>
#include "check_round_trip.h"
#include "test_iterators.h"
constexpr bool check_iterator() {
constexpr auto range = std::array{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assert(std::ranges::prev(bidirectional_iterator(&range[4])) == bidirectional_iterator(&range[3]));
assert(std::ranges::prev(random_access_iterator(&range[5])) == random_access_iterator(&range[4]));
assert(std::ranges::prev(contiguous_iterator(&range[6])) == contiguous_iterator(&range[5]));
return true;
}
int main(int, char**) {
static_assert(check_iterator());
check_iterator();
return 0;
}
| true |
3b014a6b6ec2ac4a9064d9eabbe468104b628cf7 | C++ | liadab/TransactionalDataStructures | /test/test_linked_list_mt.cpp | UTF-8 | 4,325 | 3.125 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <thread>
#include "../datatypes/LinkedList.h"
class ThreadRunner {
public:
template <typename func1_t, typename func2_t>
void run_thread_set_1(func1_t func1, func2_t func2) {
stop_main = true;
stop_thread = true;
m_t = std::make_unique<std::thread>([this, func1, func2]() {
func1();
stop_main = false;
while(stop_thread);
func2();
});
while(stop_main);
}
void run_thread_set_2() {
stop_thread = false;
m_t->join();
}
private:
std::atomic<bool> stop_main;
std::atomic<bool> stop_thread;
std::unique_ptr<std::thread> m_t;
};
TEST(LinkedListTransctionMT, putOne) {
std::shared_ptr<TX> tx = std::make_shared<TX>();
tx->TXbegin();
auto global_record_mgr = RecordMgr<size_t, size_t>::make_record_mgr(2);
RecordMgr<size_t, size_t> record_mgr(global_record_mgr, 0);
RecordMgr<size_t, size_t> record_mgr2(global_record_mgr, 1);
LinkedList<size_t, size_t> l(tx, record_mgr);
ThreadRunner t1;
t1.run_thread_set_1([&l, tx, &record_mgr2] {
tx->TXbegin();
auto r1 = l.put(5, 3, record_mgr2);
},
[&l, tx, &record_mgr2] {
tx->TXend<size_t, size_t>(record_mgr2);
});
auto r2 = l.get(5, record_mgr);
EXPECT_EQ(r2, NULLOPT);
//now there will be a commit
t1.run_thread_set_2();
ASSERT_THROW(l.get(5, record_mgr), TxAbortException);
}
TEST(LinkedListTransctionMT, putOneWithSingelton) {
std::shared_ptr<TX> tx = std::make_shared<TX>();
auto global_record_mgr = RecordMgr<size_t, size_t>::make_record_mgr(2);
RecordMgr<size_t, size_t> record_mgr(global_record_mgr, 0);
RecordMgr<size_t, size_t> record_mgr2(global_record_mgr, 1);
LinkedList<size_t, size_t> l(tx, record_mgr);
ThreadRunner t1;
t1.run_thread_set_1([&l, tx, &record_mgr2] {
tx->TXbegin();
auto r1 = l.put(5, 3, record_mgr2);
},
[&l, tx, &record_mgr2] {
tx->TXend<size_t, size_t>(record_mgr2);
});
auto r2 = l.get(5, record_mgr);
EXPECT_EQ(r2, NULLOPT);
//now there will be a commit
t1.run_thread_set_2();
auto r3 = l.get(5, record_mgr);
EXPECT_EQ(r3, 3);
}
//this is bug there should be an abort
TEST(LinkedListTransctionMT, SingeltonPutTxAbort) {
std::shared_ptr<TX> tx = std::make_shared<TX>();
auto global_record_mgr = RecordMgr<size_t, size_t>::make_record_mgr(2);
RecordMgr<size_t, size_t> record_mgr(global_record_mgr, 0);
RecordMgr<size_t, size_t> record_mgr2(global_record_mgr, 1);
LinkedList<size_t, size_t> l(tx, record_mgr);
ThreadRunner t1;
t1.run_thread_set_1([&l, tx, &record_mgr2] {
tx->TXbegin();
auto r1 = l.get(5, record_mgr2);
EXPECT_EQ(r1, NULLOPT);
},
[&l, tx, &record_mgr2] {
ASSERT_THROW(l.get(5, record_mgr2), TxAbortException);
});
auto r1 = l.put(5, 3, record_mgr);
EXPECT_EQ(r1, NULLOPT);
//now there will be a commit
t1.run_thread_set_2();
}
//this is bug there should be an abort
TEST(LinkedListTransctionMT, SingeltonPutBeforeTx) {
std::shared_ptr<TX> tx = std::make_shared<TX>();
auto global_record_mgr = RecordMgr<size_t, size_t>::make_record_mgr(2);
RecordMgr<size_t, size_t> record_mgr(global_record_mgr, 0);
RecordMgr<size_t, size_t> record_mgr2(global_record_mgr, 1);
LinkedList<size_t, size_t> l(tx, record_mgr);
auto r1 = l.put(5, 3, record_mgr);
EXPECT_EQ(r1, NULLOPT);
ThreadRunner t1;
t1.run_thread_set_1([&l, tx, &record_mgr2] {
//since there were a singleton put we must abort once in this implmention
tx->TXbegin();
ASSERT_THROW(l.get(5, record_mgr2), TxAbortException);
tx->TXbegin();
EXPECT_EQ(l.get(5, record_mgr2), 3);
},
[&l, tx] {
});
//now there will be a commit
t1.run_thread_set_2();
} | true |
cd378fa73a1bed2d6413817b75fc46ffb9309f9b | C++ | MMajeed/Poker-Hand-Frequencies | /Poker Hand Frequencies/deck.hpp | UTF-8 | 783 | 3.375 | 3 | [] | no_license | /** @file: Deck.hpp
@author Mohammed Majeed
@author m_majeed@fanshaweonline.ca
@date 2011/10/15
@version 1.0
@note Developed for Visual Studio C++ 2010
@brief - A deck class that uses the card class to develop a deck of playing cards
*/
#ifndef __Deck_HPP__
#define __Deck_HPP__
#include "card.hpp"
#include <vector>
class Deck
{
public:
std::vector<Card> deck_;
std::vector<Card> hand_;
/** Default constructor */
Deck();
/** Shuffles the cards */
void shuffe();
/** Takes the top 5 hands from the deck and puts them in the hand */
void draw();
};
enum {NoPair = 0, OnePair, TwoPair, ThreeOfaKind, Straight,
Flush, FullHouse, FourOfAKind, StraightFlush, RoyalFlush};
/** Take a vector of 5 cards and figures out what type of hand it is */
int checkHand(std::vector<Card> hand);
#endif | true |
cd43afb545cd349c2cbcfc7b2cb00ce3d0b35c5e | C++ | shashankcic/June-Leetcoding-Challenge | /validIPAddress.cpp | UTF-8 | 2,463 | 2.90625 | 3 | [] | no_license | class Solution {
public:
string validIPAddress(string IP) {
int deli;
deli=IP.find('.');
if(deli!=string::npos){
deli=0;
for(int i=0;i<4;++i){
if(deli>=IP.size()){
return "Neither";
}
int j;
for (j =deli;j<IP.size();++j){
if(IP[j]=='.'){
break;
}
else if(IP[j]<'0' || IP[j]>'9'){
return "Neither";
}
}
if(j-deli<=0){
return "Neither";
}
string sub=IP.substr(deli,j-deli);
if(sub[0]=='0' && sub.size()>1){
return "Neither";
}
int s=atoi(sub.c_str());
if (s<0 || s>255){
return "Neither";
}
deli=j+1;
}
if(deli-1<IP.size()){
return "Neither";
}
else{
return "IPv4";
}
}
else{
deli=0;
for(int i=0;i<8;++i) {
if(deli>=IP.size()){
return "Neither";
}
int j;
for(j=deli;j<IP.size();++j){
if(IP[j]==':'){
break;
}
else if(!(IP[j]>='0' && IP[j]<='9' || IP[j]>='a' && IP[j]<='f' || IP[j]>='A' && IP[j]<='F')){
return "Neither";
}
}
if(j-deli<=0 || j-deli>4){
return "Neither";
}
deli=j+1;
}
if(deli-1<IP.size()){
return "Neither";
}
else{
return "IPv6";
}
}
}
};
// class Solution {
// public:
// string validIPAddress(string IP) {
// regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"), ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}");
// if(regex_match(IP,ipv4)){
// return "IPv4";
// }
// else if(regex_match(IP,ipv6)){
// return "IPv6";
// }
// return "Neither";
// }
// };
| true |
6f9807f8540a37c6a7848e15ce11ed5098a151b8 | C++ | aclark206/Binary-Search-Tree | /BST.cpp | UTF-8 | 12,690 | 3.921875 | 4 | [] | no_license | #include <iostream>
using namespace std;
// constructor
bst::bst(int key){
root = new Node;
root->data = key;
root->right = NULL;
root->left = NULL;
}
// copy constructor
//uses a preorder traversal so that the tree will be ordered the same
bst::bst(const bst& copyTree){
recursiveCopy(copyTree.root);
}
// insert a new node into the bst
// if the data is larger than the node data, go to the right, if it is smaller, go to the right.
//if the data already exists in the tree, it will not be inserted
void bst::insert(int& item){
if (root == NULL){
root = new Node;
root->data = item;
root->right = NULL;
root->left = NULL;
}
else{
Node* current = find(root, item);
if (item > current->data){
current->right = new Node;
current->right->data = item;
current->right->right = NULL;
current->right->left = NULL;
}
else if (item < current->data){
current->left = new Node;
current->left->data = item;
current->left->right = NULL;
current->left->left = NULL;
}
// else (item == current->data) and item already exists in the tree and does not need to be inserted
}
} // end insert
// find
// recurses through the tree to find the node with the same key as item
// returns a pointer the node with the same key as item
// if there is no identical item, it returns a pointer to the node onto which the
// node should be added
Node* bst::find(Node* current, int& item){
//if the item to be inserted is larger than the data in the current node, look right
// if the right branch is empty return
// otherwise recurse further
if (item > current->data){
if (current->right == NULL)
return current;
else
find(current->right, item);
}
//if the item to be inserted is smaller than the data in the current node, look right
// if the right branch is empty return
// otherwise recurse further
else if (item < current->data){
if (current->left == NULL)
return current;
else
find(current->left, item);
}
else // (item == current->data)
return current;
}// end bst::find
//print
//prints a the data in the tree nodes by order of root, left sub tree, right sub tree
void bst::preOrderPrint(){
if (root == NULL){
cout << "Tree is empty" << endl;
}
else
recursivePreOrderPrint(root);
cout << endl;
}// end bst::preOrderPrint()
//prints a the data in the tree nodes by order of root, left sub tree, right sub tree
void bst::inOrderPrint(){
if (root == NULL){
cout << "Tree is empty" << endl;
}
else
recursiveInOrderPrint(root);
cout << endl;
}// end bst::inOrderprint()
//PostOrderPrint
//prints a the data in the tree nodes by PostOrder-- left sub tree, right sub tree, root
void bst::postOrderPrint(){
if (root == NULL){
cout << "Tree is empty" << endl;
}
else
recursivePostOrderPrint(root);
cout << endl;
}// end bst::postOrderprint()
//clear
// deletes all the nodes in the tree.
// sets root to NULL
// uses postOrder Traversal
void bst::clear(){
if (root == NULL){
return;
}
else{
recursiveClear(root);
root = NULL;
}
}// end bst::clear()
// remove
// deletes the node that matches item,
// nothing if no nodes match
void bst::remove(int& item){
// first find the node to be removed
Node* removedParent= NULL; //will point to the parent of the node to be deleted
if (root == NULL){
cout << "[remove]Error: Tree is empty. No nodes to remove.\n";
}
else {
// find the Parent node to the node we wish to remove
if (root->data == item){
removedParent = root;
}
else {
removedParent = removeFind(root, item);
};
if (removedParent != NULL){ // if the node exists in the tree
// We have a pointer to the Parent to the Node to be removed,
// Now find a pointer to the Node to be removed
Node* tobeRemoved = NULL;
if (removedParent->data == item){ //item to be removed is the root
tobeRemoved = removedParent;
}
else if (removedParent->data > item)
tobeRemoved = removedParent->left;
else
tobeRemoved = removedParent->right;
// remove the node
// 3 cases exist to remove the node
// Case 1: The node is a leaf
// Case 2: The node has one child
// Case 3: The node has 2 children
// Case 1: remove a leaf node
if (tobeRemoved->left == NULL && tobeRemoved->right == NULL){
if (removedParent->data > item)
removedParent->left = NULL;
else
removedParent->right = NULL;
delete tobeRemoved;
} // end Case 1
//Case 3: remove a node with 2 children
else if (!(tobeRemoved->left == NULL || tobeRemoved->right == NULL)){
// cout << " Case 3." << endl;
// find the inorder predessessor, or rightmost node on the left
int replaceData = recursiveRightmost(tobeRemoved->left);
// cout << "rightmostNode data = " << rightmostNode->data << endl;
//remove the rightmostNode
remove(replaceData);
// replace it with the node to delete
tobeRemoved->data = replaceData;
//clean up pointers
tobeRemoved = NULL;
} // end Case 3
// Case 2: remove a node with 1 child
else {
//cout << " Case 2." << endl;
// set Parent node pointing to the child of the node to be removed
if (removedParent->data > item){
if (tobeRemoved-> left == NULL)
removedParent->left = tobeRemoved->right;
else
removedParent->left = tobeRemoved->left;
}
else{
if (tobeRemoved-> left == NULL)
removedParent->right = tobeRemoved->right;
else
removedParent->right = tobeRemoved->left;
}
// delete node
delete tobeRemoved;
} // end Case 2
} // end if (removedParent != NULL)
else { // the node didn't exist
cout << "[remove] The node didn't exist. No nodes were removed. \n";
}
} // end else root != NULL
}// end remove()
// removeFind
//recurses through the tree to find the Node with the data that matches item
//returns a pointer to the parent Node of the Node to be removed
// returns NULL if the item doesn't exist in the tree
// assumes that the item to be found isn't it
// assumes that the root isn't NULL
Node* bst::removeFind(Node* currentRoot, int item){
//if the item to be inserted is larger than the data in the current node, look right
// if the right branch is empty return
// otherwise recurse further
if (item > currentRoot->data){
if (currentRoot->right == NULL) //item doesn't exist
return NULL;
else if (currentRoot->right->data == item){ //item found
return currentRoot;
}
else //keep recursing
removeFind(currentRoot->right, item);
}
//if the item to be inserted is smaller than the data in the current node, look right
// if the right branch is empty return
// otherwise recurse further
else if (item < currentRoot->data){
if (currentRoot->left == NULL)
return NULL;
else if (currentRoot->left->data == item){ //item found
return currentRoot;
}
else
removeFind(currentRoot->left, item);
}
else // (item == current->data)
return currentRoot;
} // end removeFind
// called by remove function
// recursively finds the largest item in the tree with root currentRoot
// returns a pointer to the rightmost node
//assumes currentRoot is not NULL
int bst:: recursiveRightmost(Node* currentRoot){
if (currentRoot->right == NULL ){ // rightmost node found
return currentRoot->data;
}
else //keep digging down to the right
recursiveRightmost(currentRoot->right);
}
// is called by the public copy constructor
// It uses a preorder traverse to recurse through the tree being copied and inserts the nodes into the constructed tree
void bst::recursiveCopy(Node* currentRoot){
if (currentRoot ==NULL)
return;
else {
this->insert(currentRoot->data);
recursiveCopy(currentRoot->left);
recursiveCopy(currentRoot->right);
}
} // end bst::recursivePreOrderPrint
// is called by the public print function to recurse through the tree
// prints the root, then prints the left sub tree and then the right sub tree
void bst::recursivePreOrderPrint(Node* currentRoot){
if (currentRoot ==NULL)
return;
else {
cout << currentRoot->data << " ";
recursivePreOrderPrint(currentRoot->left);
recursivePreOrderPrint(currentRoot->right);
}
} // end bst::recursivePreOrderPrint
// is called by the public preOrderprint function to recurse through the tree
// uses the InOrder Traversal
void bst::recursiveInOrderPrint(Node* currentRoot){
if (currentRoot ==NULL)
return;
else {
recursiveInOrderPrint(currentRoot->left);
cout << currentRoot->data << " ";
recursiveInOrderPrint(currentRoot->right);
}
} // end bst::recursiveInOrderPrint
// is called by the public preOrderprint function to recurse through the tree
// uses the PostOrder Traversal
void bst::recursivePostOrderPrint(Node* currentRoot){
if (currentRoot ==NULL)
return;
else {
recursivePostOrderPrint(currentRoot->left);
recursivePostOrderPrint(currentRoot->right);
cout << currentRoot->data << " ";
}
} // end bst::recursiveInOrderPrint
// recursiveClear
// Called by the public clear() function
//recurses through the tree using the PostOrder Traversal to delete all nodes from the tree
void bst::recursiveClear(Node* currentRoot){
if (currentRoot ==NULL)
return;
else {
recursiveClear(currentRoot->left);
recursiveClear(currentRoot->right);
// delete node
currentRoot->left = NULL;
currentRoot->right = NULL;
delete currentRoot;
}
}// end std::recursiveClear() | true |
9e73270a4085ee69b088e52c7b86d61985d85152 | C++ | Cheshulko/Algorithms | /Leetcode/PermutationSequence.cpp | UTF-8 | 380 | 2.6875 | 3 | [] | no_license | class Solution {
public:
string getPermutation(int n, int k) {
int f[10] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
vector<int> arr;
string ans;
for (int i = 1; i <= n; ++i) arr.push_back(i);
for (int i = n; i >= 1; --i){
int x = ((k - 1) / f[i - 1]);
k -= x * f[i - 1];
ans.push_back(arr[x] + '0');
arr.erase(arr.begin() + x);
}
return ans;
}
};
| true |
b80dd0b96f8c1bb387226dcc0afee716ec75d354 | C++ | Egor201/Programming | /Practice/08/c++/Project1/Project1/Source.cpp | MacCyrillic | 525 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
int main() {
setlocale(LC_ALL, "Russian");
double x, y;
char q = ' ', w = ' ';
std::cout << " \n";
std::cin >> x >> q >> y;
q = (int)(q);
w = (int)('+');
if (q == '+') {
std::cout << x + y;
}
else {
if (q == '-') {
std::cout << x - y;
}
else {
if (q == '*') {
std::cout << x * y;
}
else {
if (q == '/') {
std::cout << setprecision(5) << fixed;
std::cout << x / y;
}
}
}
}
} | true |
83783145cc3b59d955def374af14e17ddc11b2a1 | C++ | yelanzhou/learnVulkan | /LearnVulkan/VulkanEncapsulation/Private/VulkanImageView.cpp | UTF-8 | 1,272 | 2.609375 | 3 | [] | no_license | #include "VulkanImageView.h"
#include "VulkanDevice.h"
#include <assert.h>
VulkanImageView::VulkanImageView(std::shared_ptr<VulkanDevice> vulkanDevicePtr, VkImage imageHanle, VkFormat format)
:m_vulkanDevicePtr(vulkanDevicePtr)
{
VkImageViewCreateInfo viewInfo;
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.pNext = nullptr;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.image = imageHanle;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = 1;
viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
auto ret = vkCreateImageView(m_vulkanDevicePtr->getHandle(), &viewInfo, nullptr, &m_vulkanImageViewHandle);
assert(ret == VK_SUCCESS);
}
VulkanImageView::~VulkanImageView()
{
vkDestroyImageView(m_vulkanDevicePtr->getHandle(), m_vulkanImageViewHandle, nullptr);
}
VkImageView VulkanImageView::getHandle()
{
return m_vulkanImageViewHandle;
}
| true |
ece58e8ecd148a7edcd47949323d1a956c59eb20 | C++ | ashnachadha/cs100-lab-05-strategy-pattern | /bubbleSort.hpp | UTF-8 | 658 | 3.140625 | 3 | [] | no_license | #ifndef __BUBBLESORT_HPP__
#define __BUBBLESORT_HPP__
#include "container.hpp"
#include "sort.hpp"
class BubbleSort : public Sort {
public:
/* Constructors */
BubbleSort() : Sort() {}
/* Pure Virtual Functions */
virtual void sort(Container* container) {
for (unsigned i = 0; i + 1 < container->size(); ++i) {
for (unsigned j = 0; j + i + 1 < container->size(); ++j) {
if (container->at(j)->evaluate() > container->at(j+1)->evaluate()) {
container->swap(j, j+1);
}
}
}
}
};
#endif //__BUBBLESORT_HPP__
| true |
9583c93b3f07713e3c2172087e3215e5bfadad9a | C++ | int-i/ICE2004 | /psj/week07/hw01/main.cpp | UTF-8 | 2,818 | 3.9375 | 4 | [] | no_license | // 사용할 헤더 정의
#include <iostream>
#include "media.h"
// 프로그램 시작점
int main() {
// 미디어 클래스 인스턴스 포인터를 저장하는 배열
Media* media_ptrs[] = {
// 각 클래스를 동적할당하여 생성
// 사용 후에는 `delete` 해야 함
new VTR("Hello", 15, "avi"),
new DVD("Superman", 3, "123-9899"),
new LegalDVD("Marvel", 10, "456-9899", "GG entertainment"),
new VTR("Disney", 23, "mkv"),
};
// 추상 메소드 실습
std::cout << "<Virtual Method Practice>" << std::endl;
// 배열의 모든 원소를 순회하는 반복문
for (int i = 0; i < Media::count; i += 1) {
// 각 미디어를 실행함
// 원소의 타입은 포인터이기 때문에 화살표 연산자로 접근
media_ptrs[i]->play();
}
std::cout << std::endl;
// 연산자 오버로딩 실습
std::cout << "<Operator Overloading Practice>" << std::endl;
// media_ptrs 원소의 타입은 포인터이기 때문에 `std::ostream& operator<<(std::ostream& out, Media* media_ptr)`을 구현해야 함
std::cout << "media_ptrs[0]: " << media_ptrs[0] << std::endl;
// 아래에서 `media_ptrs[3]`를 새로 만들기 때문에 기존에 사용하던 `media_ptrs[3]`는 삭제해야 함
delete media_ptrs[3];
// 미디어 길이를 합친 새로운 미디어를 반환하는 `Media* operator+(Media* media_ptr)`을 구현
// `Media*`를 반환하기 때문에 배열 원소에 바로 할당
// 오버로딩 함수를 nodiscard 애트리뷰트(attribute)으로 정의했기 때문에 값이 사용되지 않으면 warning 출력
media_ptrs[3] = *media_ptrs[1] + media_ptrs[2];
// `get_length()`은 반환타입은 `int`이기 때문에 별도의 연산자 오버로딩이 필요 없음
std::cout << "media_ptrs[3]->get_length(): " << media_ptrs[3]->get_length() << std::endl; // 3+10=13
std::cout << std::endl;
// 소멸자 호출 실습
std::cout << "<Destructor Call Practice>" << std::endl;
// 현재 미디어 클래스 객체는 총 4개 있음
std::cout << "Media::count: " << Media::count << std::endl; // 4
// 배열의 모든 원소를 순회하는 반복문
// `delete`의 호출이 `Media::count`을 수정하기 떄문에 `count`로 초기값을 복사해야 함
for (int i = 0, count = Media::count; i < count; i += 1) {
// 동적할당된 객체를 해지함
// 소멸자 호출 순서를 따라가면 `~Media`가 호출되기 때문에 `Media::count -= 1`이 실행됨
delete media_ptrs[i];
}
// 모든 객체가 소멸되며 소멸자를 호출했기 때문에 `Media::count`는 0
std::cout << "Media::count: " << Media::count << std::endl; // 0
return 0;
}
| true |
bfcb613d28b5eaa4c4464547fb64f2430475be09 | C++ | tomerwei/Robot-Motion-Planning | /4.2/Prm.h | UTF-8 | 1,982 | 2.828125 | 3 | [] | no_license | #ifndef PRM_H
#define PRM_H
#include "basic_typedef.h"
#include "Graph.h"
#include "CollisionDetector.h"
#include "Sampler.h"
#include "Kd_tree_d.h"
#include "SRPrm.h"
#include <map>
#include <utility>
// Should be used with the Graph wrapper
class Prm {
typedef map< Point_d, int, point_d_less > point_to_node_map_t;
public:
/* IMPORTANT: The main code of the PRM algorithm should be placed in this
* file.
* You may change its structure, but make sure you that it remains consistent
* with the run() operation in Planner.h
*/
Prm(int number_vertices,
int k_nearest,
const CollisionDetector& col,
const Sampler& sampler,
Point_d start, Point_d target);
~Prm()
{
delete m_graph;
}
double configuration_distance(const Point_d& lhs, const Point_d& rhs);
void add_edges( const Point_d &p, int K );
// This operation is supposed to generate the roadmap (sample configurations
// and connect them.
void generate_roadmap();
// Returns a point path from start to target.
// If a path doesn't exist, returns empty vector.
const vector<Point_d>& retrieve_path() const
{
return m_path;
}
private:
int m_number_vertices; // number of sampled vertices
int m_k_nearest; // maximal degree of vertex in roadmap
const CollisionDetector &m_col;
const Sampler &m_sampler;
LocalPlanner m_loc_planner;
Graph<int, Less_than_int>* m_graph; // Graph structure
Kd_tree_d<Kernel_d> m_kd_tree; // Kd-tree for nearest neighbor search
Point_d m_start,m_target; // Start and target configurations
point_to_node_map_t vertexID; // mapping point to node id
map< int, Point_d > vertexIDToPoint; // mapping node id to point
bool is_path; // is there a path from m_start to m_target
vector<Point_d> m_path; // the result path
};
#endif
| true |
82eca371668cfe5b19108323176aab329b1fe243 | C++ | Ilisio-Lungavi/Laboratorios-de-TIC | /Lab1/1/Exercício Nº1.cpp | ISO-8859-1 | 252 | 2.953125 | 3 | [] | no_license | //Exerccio N1
#include <stdio.h>
int main(){
int A, lado1, lado2;
printf("Digite os lados do quadrado...:");
scanf("%i%i", &lado1, &lado2);
A = lado1 * lado2;
printf("A area do quadrado igual a %i", A);
return 0;
} | true |
e64b2eceef7954b51bf678ec29e3d7be204b86f4 | C++ | CMS-TMTT/cmssw | /TrackingTools/DetLayers/interface/PeriodicBinFinderInZ.h | UTF-8 | 1,334 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef DetLayers_PeriodicBinFinderInZ_H
#define DetLayers_PeriodicBinFinderInZ_H
#include "Utilities/BinningTools/interface/BaseBinFinder.h"
#include "Geometry/CommonDetUnit/interface/GeomDet.h"
#include <cmath>
/** Bin finder along the global Z for (almost) equidistant bins.
* The bins are computed from GeomDet positions.
*/
template <class T>
class PeriodicBinFinderInZ : public BaseBinFinder<T> {
public:
PeriodicBinFinderInZ() : theNbins(0), theZStep(0), theZOffset(0) {}
PeriodicBinFinderInZ(std::vector<const GeomDet*>::const_iterator first,
std::vector<const GeomDet*>::const_iterator last) :
theNbins( last-first)
{
float zFirst = (**first).surface().position().z();
theZStep = ((**(last-1)).surface().position().z() - zFirst) / (theNbins-1);
theZOffset = zFirst - 0.5*theZStep;
}
/// returns an index in the valid range for the bin that contains Z
int binIndex( T z) const override {
return binIndex( int((z-theZOffset)/theZStep));
}
/// returns an index in the valid range
int binIndex( int i) const override {
return std::min( std::max( i, 0), theNbins-1);
}
/// the middle of the bin
T binPosition( int ind) const override {
return theZOffset + theZStep * ( ind + 0.5);
}
private:
int theNbins;
T theZStep;
T theZOffset;
};
#endif
| true |
5ea12e6e31c72529a9112feda15fececa94855dc | C++ | Hyoe/CST370 | /Week1_LinkedLists/HelpExamples/maxIsAscending/LinkedList.cpp | UTF-8 | 3,020 | 3.890625 | 4 | [] | no_license | #include <iostream>
using namespace std;
#include "LinkedList.h"
//-- Default constructor
LinkedList::LinkedList()
{
mySize = 0;
first = NULL;
}
//-- Definition of the copy constructor
LinkedList::LinkedList(const LinkedList & origList)
{
mySize = origList.mySize;
first = NULL;
if (mySize == 0)
return;
Node * origPtr, *lastPtr;
first = new Node(origList.first->data); // copy first node
lastPtr = first;
origPtr = origList.first->next;
while (origPtr != NULL)
{
lastPtr->next = new Node(origPtr->data);
origPtr = origPtr->next;
lastPtr = lastPtr->next;
}
}
//-- Definition of the destructor
LinkedList::~LinkedList()
{
Node * prev = first;
Node * ptr;
while (prev != NULL)
{
ptr = prev->next;
delete prev;
prev = ptr;
}
}
//-- Definition of insert()
void LinkedList::insert(ElementType dataVal, int index)
{
if (index < 0 || index > mySize)
{
cerr << "Illegal location to insert -- " << index << endl;
return;
}
mySize++;
Node * newPtr = new Node(dataVal);
Node * predPtr = first;
if (index == 0)
{
newPtr->next = first;
first = newPtr;
}
else
{
for (int i = 1; i < index; i++)
predPtr = predPtr->next;
newPtr->next = predPtr->next;
predPtr->next = newPtr;
}
}
//-- Definition of erase()
void LinkedList::erase(ElementType index)
{
if (index < 0 || index >= mySize)
{
cerr << "Illegal location to delete -- " << index << endl;
return;
}
mySize--;
Node * ptr;
Node * predPtr = first;
if (index == 0)
{
ptr = first;
first = ptr->next;
delete ptr;
}
else
{
for (int i = 1; i < index; i++)
predPtr = predPtr->next;
ptr = predPtr->next;
predPtr->next = ptr->next;
delete ptr;
}
}
//-- Definition of display()
void LinkedList::display(ostream & out) const
{
Node * ptr = first;
while (ptr != 0)
{
out << ptr->data << " ";
ptr = ptr->next;
}
}
//-Definition of Add()
int LinkedList::sumList()
{
int sum = 0;
Node * next = first;
while (next != NULL)
{
sum = sum + next->data;
next = next->next;
}
return sum;
}
ElementType LinkedList::maxItem()
{
ElementType max;
Node * next = first;
if (first == NULL)
cout << "The list is empty." << endl;
else
{
max = first->data;
while (next != NULL)
{
if (max < next->data)
max = next->data;
next = next->next;
}
}
return max;
}
bool LinkedList::isAscendingOrder()
{
ElementType prev;
bool ascending = true;
Node * next = first;
if (first == NULL)
cout << "The list is empty." << endl;
else
{
prev = first->data;
while (next != NULL && ascending)
{
if (next->data < prev)
ascending = false;
prev = next->data;
next = next->next;
}
}
return ascending;
}
| true |
24ad9a159fa07b14e302f7b032c8eb5ea4c3c347 | C++ | MarkInsom/Assignment-3 | /Linked List/ConsoleApplication1/LinkedList.h | UTF-8 | 509 | 3.359375 | 3 | [] | no_license | #pragma once
#include <iostream>
class LinkedList
{
public:
struct Node
{
int value;
Node* next;
Node* previous;
};
//Head
Node* m_first;
Node* m_last;
void pushFront(int value);
void pushBack(int value);
void popFront();
void popBack();
void printDetails();
void remove(int value);
void clear();
bool empty();
int count();
int printFirst() { return m_first->value; }
int printLast() { return m_last->value; }
LinkedList();
~LinkedList();
};
| true |
de89b4a3ca5bf449683074a1c2e76079057eb55b | C++ | seabass04/CS100 | /Labs/Lab05/Rand.hpp | UTF-8 | 343 | 2.53125 | 3 | [] | no_license | #ifndef __RAND_HPP__
#define __RAND_HPP__
#include "base.hpp"
#include <stdlib.h>
using namespace std;
class Rand : public Base {
private:
double n = rand() % 100;
public:
Rand() { };
double evaluate() { return n; };
string stringify(){
string s;
s = to_string(n);
return s;
}
};
#endif
| true |
53b62860b9f54dad86527930a03d9a81dedb52fb | C++ | ztangaj/RM_sentry | /src/peripherals/flash.cpp | UTF-8 | 7,928 | 3.125 | 3 | [] | no_license | /**
* @file flash.cpp
* @author Someone on GitHub, Modified by Alex Au
* @brief flash memory manipulator for stm32f4 devices
* @date 2018-10-27
*
* @copyright Copyright (c) 2018
*
*/
#include "string.h"
#include "flash.hpp"
size_t flashSectorSize(flashsector_t sector)
{
if (sector > 11 && sector < 24)
sector -= 12;
if (sector <= 3)
return 16 * 1024;
else if (sector == 4)
return 64 * 1024;
else if (sector >= 5 && sector <= 11)
return 128 * 1024;
return 0;
}
char *flashSectorBegin(flashsector_t sector)
{
char *address = (char *)FLASH_BASE;
while (sector > 0)
{
--sector;
address += flashSectorSize(sector);
}
return address;
}
char *flashSectorEnd(flashsector_t sector)
{
return flashSectorBegin(sector + 1);
}
flashsector_t flashSectorAt(char *address)
{
flashsector_t sector = 0;
while (address >= flashSectorEnd(sector))
++sector;
return sector;
}
/**
* @brief Wait for the flash operation to finish.
*/
inline void flashWaitWhileBusy()
{
while (FLASH->SR & FLASH_SR_BSY)
;
}
/**
* @brief Unlock the flash memory for write access.
* @return true Unlock was successful.
*/
bool flashUnlock()
{
/* Check if unlock is really needed */
if (!(FLASH->CR & FLASH_CR_LOCK))
return true;
/* Write magic unlock sequence */
FLASH->KEYR = 0x45670123;
FLASH->KEYR = 0xCDEF89AB;
/* Check if unlock was successful */
if (FLASH->CR & FLASH_CR_LOCK)
return false;
return true;
}
/**
* @brief Lock the flash memory for write access.
*/
#define flashLock() \
{ \
FLASH->CR |= FLASH_CR_LOCK; \
}
int flashSectorErase(flashsector_t sector)
{
/* Unlock flash for write access */
if (!flashUnlock())
return FLASH_RETURN_NO_PERMISSION;
/* Wait for any busy flags. */
flashWaitWhileBusy();
/* Setup parallelism before any program/erase */
FLASH->CR &= ~FLASH_CR_PSIZE_MASK;
FLASH->CR |= FLASH_CR_PSIZE_VALUE;
/* Start deletion of sector.
* SNB(3:1) is defined as:
* 00000 to 01011 sector 0 to sector 11
* 10000 to 11011 sector 12 to sector 23
* others not allowed */
if (sector > 11)
{
FLASH->CR |= FLASH_CR_SNB_4;
sector -= 12;
}
FLASH->CR &= ~(FLASH_CR_SNB_0 | FLASH_CR_SNB_1 | FLASH_CR_SNB_2 | FLASH_CR_SNB_3);
if (sector & 0x1)
FLASH->CR |= FLASH_CR_SNB_0;
if (sector & 0x2)
FLASH->CR |= FLASH_CR_SNB_1;
if (sector & 0x4)
FLASH->CR |= FLASH_CR_SNB_2;
if (sector & 0x8)
FLASH->CR |= FLASH_CR_SNB_3;
FLASH->CR |= FLASH_CR_SER;
FLASH->CR |= FLASH_CR_STRT;
/* Wait until it's finished. */
flashWaitWhileBusy();
/* Sector erase flag does not clear automatically. */
FLASH->CR &= ~FLASH_CR_SER;
/* Lock flash again */
flashLock();
/* Check deleted sector for errors */
if (flashIsErased(flashSectorBegin(sector), flashSectorSize(sector)) == FALSE)
return FLASH_RETURN_BAD_FLASH; /* Sector is not empty despite the erase cycle! */
/* Successfully deleted sector */
return FLASH_RETURN_SUCCESS;
}
int flashErase(char *address, size_t size)
{
while (size > 0)
{
flashsector_t sector = flashSectorAt(address);
int err = flashSectorErase(sector);
if (err != FLASH_RETURN_SUCCESS)
return err;
address = flashSectorEnd(sector);
size_t sector_size = flashSectorSize(sector);
if (sector_size >= size)
break;
else
size -= sector_size;
}
return FLASH_RETURN_SUCCESS;
}
bool flashIsErased(char *address, size_t size)
{
/* Check for default set bits in the flash memory
* For efficiency, compare flashdata_t values as much as possible,
* then, fallback to byte per byte comparison. */
while (size >= sizeof(flashdata_t))
{
if (*(volatile flashdata_t *)address != (flashdata_t)(-1)) // flashdata_t being unsigned, -1 is 0xFF..FF
return FALSE;
address += sizeof(flashdata_t);
size -= sizeof(flashdata_t);
}
while (size > 0)
{
if (*(char *)address != 0xff)
return FALSE;
++address;
--size;
}
return TRUE;
}
bool flashCompare(char *address, const char *buffer, size_t size)
{
/* For efficiency, compare flashdata_t values as much as possible,
* then, fallback to byte per byte comparison. */
while (size >= sizeof(flashdata_t))
{
if (*(volatile flashdata_t *)address != *(flashdata_t *)buffer)
return FALSE;
address += sizeof(flashdata_t);
buffer += sizeof(flashdata_t);
size -= sizeof(flashdata_t);
}
while (size > 0)
{
if (*(volatile char *)address != *buffer)
return FALSE;
++address;
++buffer;
--size;
}
return TRUE;
}
int flashRead(char *address, char *buffer, size_t size)
{
memcpy(buffer, (char *)address, size);
return FLASH_RETURN_SUCCESS;
}
static void flashWriteData(char *address, const flashdata_t data)
{
/* Enter flash programming mode */
FLASH->CR |= FLASH_CR_PG;
/* Write the data */
*(flashdata_t *)address = data;
/* Wait for completion */
flashWaitWhileBusy();
/* Exit flash programming mode */
FLASH->CR &= ~FLASH_CR_PG;
}
int flashWrite(char *address, const uint8_t *buffer, size_t size)
{
/* Unlock flash for write access */
if (!flashUnlock())
return FLASH_RETURN_NO_PERMISSION;
/* Wait for any busy flags */
flashWaitWhileBusy();
/* Setup parallelism before any program/erase */
FLASH->CR &= ~FLASH_CR_PSIZE_MASK;
FLASH->CR |= FLASH_CR_PSIZE_VALUE;
/* Check if the flash address is correctly aligned */
size_t alignOffset = (size_t)address % sizeof(flashdata_t);
if (alignOffset != 0)
{
/* Not aligned, thus we have to read the data in flash already present
* and update them with buffer's data */
/* Align the flash address correctly */
char *alignedFlashAddress = address - alignOffset;
/* Read already present data */
flashdata_t tmp = *(volatile flashdata_t *)alignedFlashAddress;
/* Compute how much bytes one must update in the data read */
size_t chunkSize = sizeof(flashdata_t) - alignOffset;
if (chunkSize > size)
chunkSize = size; // this happens when both address and address + size are not aligned
/* Update the read data with buffer's data */
memcpy((char *)&tmp + alignOffset, buffer, chunkSize);
/* Write the new data in flash */
flashWriteData(alignedFlashAddress, tmp);
/* Advance */
address += chunkSize;
buffer += chunkSize;
size -= chunkSize;
}
/* Now, address is correctly aligned. One can copy data directly from
* buffer's data to flash memory until the size of the data remaining to be
* copied requires special treatment. */
while (size >= sizeof(flashdata_t))
{
flashWriteData(address, *(const flashdata_t *)buffer);
address += sizeof(flashdata_t);
buffer += sizeof(flashdata_t);
size -= sizeof(flashdata_t);
}
/* Now, address is correctly aligned, but the remaining data are to
* small to fill a entier flashdata_t. Thus, one must read data already
* in flash and update them with buffer's data before writing an entire
* flashdata_t to flash memory. */
if (size > 0)
{
flashdata_t tmp = *(volatile flashdata_t *)address;
memcpy(&tmp, buffer, size);
flashWriteData(address, tmp);
}
/* Lock flash again */
flashLock();
return FLASH_RETURN_SUCCESS;
}
/*
Additional commands for storing more dynamic data
*/
| true |
c08e5484b07bf5769d97af54c5b2479652059ece | C++ | Scoobadood/Animesh | /src/libArgs/src/Args.cpp | UTF-8 | 8,697 | 3.0625 | 3 | [] | no_license | #include "Args.h"
#include <tclap/CmdLine.h>
#include <tclap/ArgException.h>
const int DEFAULT_SMOOTH_ITERATIONS = 50;
const int UNUSED = -1;
std::vector<std::string> split( const std::string& str, char token ) {
std::vector<std::string> strings;
std::istringstream f(str);
std::string s;
while (getline(f, s, token)) {
strings.push_back(s);
}
return strings;
}
class Prefab {
private:
std::string m_name;
float m_grid_spacing;
int m_dim1;
int m_dim2;
int m_dim3;
protected:
Prefab( const std::string& name, float grid_spacing, int dim1, int dim2, int dim3) : m_name{ name } {
m_grid_spacing = grid_spacing;
m_dim1 = dim1;
m_dim2 = dim2;
m_dim3 = dim3;
}
Prefab( const std::string& name, float grid_spacing, int dim1, int dim2) : m_name{ name } {
m_grid_spacing = grid_spacing;
m_dim1 = dim1;
m_dim2 = dim2;
m_dim3 = UNUSED;
}
Prefab( const std::string& name, float grid_spacing, int dim1) : m_name{ name } {
m_grid_spacing = grid_spacing;
m_dim1 = dim1;
m_dim2 = UNUSED;
m_dim3 = UNUSED;
}
public:
std::string name() const {
return m_name;
}
float radius( ) const {
if( m_name == "sphere" || m_name == "circle" ) {
return m_grid_spacing;
}
throw std::domain_error( "Radius is only valid for circle or sphere");
}
float grid_spacing( ) const {
if( m_name != "sphere" || m_name != "circle" ) {
return m_grid_spacing;
}
throw std::domain_error( "Grid spacing is not valid for circle or sphere");
}
int theta_steps( ) const {
if( m_name == "sphere" || m_name == "circle" ) {
return m_dim1;
}
throw std::domain_error( "Theta steps is only valid for circle or sphere");
}
int phi_steps( ) const {
if( m_name == "sphere" ) {
return m_dim2;
}
throw std::domain_error( "Phi steps is only valid for sphere");
}
int size_x( ) const {
if( m_name == "plane" || m_name == "poly" || m_name == "cube" ) {
return m_dim1;
}
throw std::domain_error( "size_x is only valid for poly, plane or cube");
}
int size_y( ) const {
if( m_name == "plane" || m_name == "poly" || m_name == "cube" ) {
return m_dim2;
}
throw std::domain_error( "size_y is only valid for poly, plane or cube");
}
int size_z( ) const {
if( m_name == "cube" ) {
return m_dim3;
}
throw std::domain_error( "size_z is only valid for cube");
}
static Prefab from_string( const std::string& value ) {
using namespace TCLAP;
// Break the string into chunks at commas
std::vector<std::string> chunks = split( value, ',');
if( chunks[0] == "cube") {
if( chunks.size() != 5 )
throw ArgException( "Cube args should be grid_size, dim_x, dim_y, dim_z" );
return cube_prefab( chunks );
}
else if( chunks[0] == "sphere") {
if( chunks.size() != 4 )
throw ArgException( "Sphere args should be radius, theta steps, phi steps" );
return sphere_prefab( chunks );
}
else if( chunks[0] == "poly") {
if( chunks.size() != 4 )
throw ArgException( "Poly args should be grid spacing, x dim, y dim" );
return poly_prefab( chunks );
}
else if( chunks[0] == "plane") {
if( chunks.size() != 4 )
throw ArgException( "Plane args should be grid spacing, x dim, y dim" );
return plane_prefab( chunks );
}
else if( chunks[0] == "circle") {
if( chunks.size() != 3 )
throw ArgException( "Circle args should be radius, num_steps" );
return circle_prefab( chunks );
}
else
throw std::invalid_argument("Unknown prefab type " + chunks[0]);
}
static Prefab sphere_prefab( const std::vector<std::string>& chunks ) {
// Expect radius, theta_step, phi_step and K
float radius = std::stof(chunks[1]);
int theta_steps = std::stoi(chunks[2]);
int phi_steps = std::stoi(chunks[3]);
return Prefab{ "sphere", radius, theta_steps, phi_steps};
}
static Prefab cube_prefab( const std::vector<std::string>& chunks ) {
// Expect grid_spacing, x dim, y dim, z dim
float grid_spacing = std::stof(chunks[1]);
int x_dim = std::stoi(chunks[2]);
int y_dim = std::stoi(chunks[3]);
int z_dim = std::stoi(chunks[4]);
return Prefab{ "cube", grid_spacing, x_dim, y_dim, z_dim};
}
static Prefab plane_prefab( const std::vector<std::string>& chunks ) {
// Expect grid_spacing, x dim, y dim, z dim
float grid_spacing = std::stof(chunks[1]);
int x_dim = std::stoi(chunks[2]);
int y_dim = std::stoi(chunks[3]);
return Prefab{ "plane", grid_spacing, x_dim, y_dim};
}
static Prefab poly_prefab( const std::vector<std::string>& chunks ) {
// Expect grid_spacing, x dim, y dim, z dim
float grid_spacing = std::stof(chunks[1]);
int x_dim = std::stoi(chunks[2]);
int y_dim = std::stoi(chunks[3]);
return Prefab{ "poly", grid_spacing, x_dim, y_dim};
}
static Prefab circle_prefab( const std::vector<std::string>& chunks ) {
// Expect grid_spacing, x dim, y dim, z dim
float radius = std::stof(chunks[1]);
int num_steps = std::stoi(chunks[2]);
return Prefab{ "circle", radius, num_steps};
}
};
std::istream& operator>> (std::istream& is, Prefab& p) {
std::string s;
is>> s;
p = Prefab::from_string(s);
return is;
}
Args::Args( int &argc, char **argv) {
using namespace TCLAP;
try {
// Define the command line object, and insert a message
// that describes the program. The "Command description message"
// is printed last in the help text. The second argument is the
// delimiter (usually space) and the last one is the version number.
// The CmdLine object parses the argv array based on the Arg objects
// that it contains.
CmdLine cmd("Command description message", ' ', "0.9");
// Define a value argument and add it to the command line.
// A value arg defines a flag and a type of value that it expects,
// such as "-n Bishop".
ValueArg<int> iterations("i","iter","Number of smoothing iterations to run per click",false, DEFAULT_SMOOTH_ITERATIONS, "num_iters", cmd);
// Shapes are all strings and must be one of
// Cube,dimx,dimy,dimz,spacing
// Plane,dimx,dimy,spacing
// Polynomial,dimx,dimy,spacing
// Sphere,radius,theta_steps,phi_steps
// Circle,radius,theta_steps
std::vector<std::string> plane = {"poly", "1.0", "10", "10"};
Prefab simple_plane = Prefab::plane_prefab( plane );
ValueArg<Prefab> prefab("p","prefab","Use a prefab field shape. plane, cube,polynomial, circle or sphere", true, simple_plane, "prefab");
ValueArg<std::string> file_name("n","file","OBJ File name.",true, "", "filename");
cmd.xorAdd( prefab, file_name );
ValueArg<int> k("k","knear","Specify k nearest neighbours to use when building graph", true, 5, "num", cmd);
SwitchArg make_fixed("f","fix","Make initial field tangents fixed", cmd, false);
SwitchArg dump_field("d","dump","Dump the field in it's initial state", cmd, false);
SwitchArg tracing_enabled("v","verbose","Output lots of diagnostics", cmd, false);
// Parse the argv array.
cmd.parse( argc, argv );
m_num_smoothing_iterations = iterations.getValue();
m_should_fix_tangents = make_fixed.getValue();
m_should_dump_field = dump_field.getValue();
m_tracing_enabled = tracing_enabled.getValue();
m_k = k.getValue();
if( file_name.isSet() ) {
m_file_name = file_name.getValue();
m_load_from_pointcloud = true;
} else if ( prefab.isSet() ) {
if( prefab.getValue().name() == "plane" || prefab.getValue().name() == "poly" ){
m_default_shape = PLANE;
m_plane_x = prefab.getValue().size_x();
m_plane_y = prefab.getValue().size_y();
m_grid_spacing = prefab.getValue().grid_spacing();
if( prefab.getValue().name() == "poly" ) {
m_default_shape = POLYNOMIAL;
}
} else if( prefab.getValue().name() == "sphere") {
m_default_shape = SPHERE;
m_radius = prefab.getValue().radius();
m_theta_steps = prefab.getValue().theta_steps();
m_phi_steps = prefab.getValue().phi_steps( );
} else if( prefab.getValue().name() == "cube") {
m_default_shape = CUBE;
m_cube_x = prefab.getValue().size_x();
m_cube_y = prefab.getValue().size_y();
m_cube_z = prefab.getValue().size_z();
} else if( prefab.getValue().name() == "circle") {
m_default_shape = CIRCLE;
m_radius = prefab.getValue().radius( );
m_theta_steps = prefab.getValue().theta_steps( );
} else {
throw("Very bad things...");
}
} else {
// No prefab or file: Shold never get here because TCLAP should have handled it
throw("Very bad things...");
}
} catch (TCLAP::ArgException &e) { // catch any exceptions
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
}
| true |
d214e34457baf2a0e130c9ab0989b78904637b66 | C++ | yr4528/algo | /lost_clothes/lost_clothes/소스.cpp | UTF-8 | 679 | 3 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int n = 3;
vector<int> lost = { 3 };
vector<int> reserve = { 1 };
int solution() {
int answer = 0;
vector<int> stu(n,1);
for (int i = 0; i < reserve.size(); i++) {
stu[reserve[i] - 1]++;
}
for (int i = 0; i < lost.size(); i++) {
stu[lost[i] - 1]--;
}
for (int i = 0; i < n; i++) {
if (stu[i] > 1) {
if (i >= 1 && stu[i - 1] == 0) {
stu[i]--;
stu[i - 1]++;
}
if (i < n - 1 && stu[i + 1] == 0) {
stu[i]--;
stu[i + 1]++;
}
}
}
for (int i = 0; i < n; i++) {
if (stu[i] != 0) answer++;
}
return answer;
}
int main() {
int sol = solution();
cout << sol;
return 0;
} | true |
abddc20680a9dc86d126af0778544b230de51d97 | C++ | cpe102/lab18-2562-2-poncmu | /lab18_1.cpp | UTF-8 | 656 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct Rect{
double x,y,w,h;
};
double overlap(Rect A,Rect B)
{
double xmin,xmax,ymin,ymax;
if(A.x>B.x) xmin=A.x;
else xmin=B.x;
if(A.x+A.w>B.x+B.w) xmax=B.x+B.w;
else xmax=A.x+A.w;
if(A.y>B.y) ymax=B.y;
else ymax=A.y;
if(A.y-A.w>B.y-B.w) ymin=A.y-A.w;
else ymin=B.y-B.w;
if(xmax-xmin<0 || ymax-ymin<0)
return 0;
else
{
return (xmax-xmin)*(ymax-ymin);
}
}
int main(){
Rect A;
Rect B;
cout << "Please input Rect 1 (x y w h): ";
cin>>A.x>>A.y>>A.w>>A.h;
cout << "Please input Rect 2 (x y w h): ";
cin>>B.x>>B.y>>B.w>>B.h;
cout << "Overlap area = "<<overlap(A,B);
return 0;
}
| true |
5e458e9387cfb2369add2e2d19eb6c3f80079ae0 | C++ | tiwanari/pmi-box | /reducer/main.cc | UTF-8 | 2,122 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | #include <cstdlib>
#include <sstream>
#include <future>
#include <fstream>
#include <iostream>
#include <string>
#include <unistd.h>
#include "reducer.h"
#include "util/trim.h"
#include "util/cmdline.h"
void readLinesFromAFile(
const std::string& input_filename,
std::vector<std::string>* lines)
{
std::ifstream input_file;
input_file.open(input_filename);
if (!input_file) {
std::cerr << "Can't open file: " << input_filename << std::endl;
input_file.close();
exit(1);
}
std::string line;
while (std::getline(input_file, line)) {
if (line.empty()) continue;
lines->emplace_back(util::trim(line));
}
input_file.close();
}
void reduce(
const std::string& input_file_list,
const std::string& output_file)
{
// input file is a list of counted result files
std::vector<std::string> counted_result_files;
readLinesFromAFile(input_file_list, &counted_result_files);
// show target files
std::cerr << "=== reduce target file(s) ===" << std::endl;
for (const auto& file : counted_result_files)
std::cerr << file << std::endl;
std::cerr << "-> " << output_file << std::endl;
// reducing hints
pmi_toolkit::Reducer reducer(counted_result_files);
std::cout << "reducing..." << std::endl;
reducer.reduce(output_file);
std::cout << "reduced!" << std::endl;
}
const std::string ARG_IN = "input_list_file";
const std::string ARG_OUT = "output_file";
void parseArguments(cmdline::parser& p, int argc, char** argv)
{
p.add<std::string>(ARG_IN, 'i', "a file shows a list of inputs", true);
p.add<std::string>(ARG_OUT, 'o', "a file for output", true);
p.parse_check(argc, argv);
}
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "ja_JP.UTF-8");
cmdline::parser p;
parseArguments(p, argc, argv);
// === read arguments ===
const std::string input_list_file = p.get<std::string>(ARG_IN);
const std::string output_file = p.get<std::string>(ARG_OUT);
// === /read arguments ===
reduce(input_list_file, output_file);
return 0;
}
| true |
54761dfce58bd16175865469c3de0fb8b92e0471 | C++ | zhang416/rpyfmm | /include/rpy.h | UTF-8 | 14,988 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef __RPY_EXPANSION_H__
#define __RPY_EXPANSION_H__
#include <cmath>
#include <complex>
#include <map>
#include <memory>
#include <vector>
#include "dashmm/index.h"
#include "builtins/laplace.h"
#include "dashmm/point.h"
#include "dashmm/types.h"
#include "dashmm/viewset.h"
namespace dashmm {
class RPYTable {
public:
RPYTable(double a, double kb, double T, double eta)
: a_{a}, kb_{kb}, T_{T}, eta_{eta} {
c0_ = kb * T / 6 / M_PI / a / eta;
c1_ = kb * T / 8 / M_PI / eta;
c2_ = kb * T * a * a / 12 / M_PI;
}
double a() const {return a_;}
double c0() const {return c0_;}
double c1() const {return c1_;}
double c2() const {return c2_;}
bool update(double a, double kb, double T, double eta) const {
return (a != a_) || (kb * T / eta != kb_ * T_ / eta_);
}
private:
double a_; // Radius of the bead
double kb_; // Boltzmann constant
double T_; // Absolute temperature
double eta_; // Solvent viscosity
double c0_;
double c1_;
double c2_;
};
extern std::unique_ptr<RPYTable> rpy_table_;
void update_rpy_table(double a, double kb = 1.0,
double T = 1.0, double eta = 1.0);
struct Bead {
Bead() { }
int index; // Index of the bead
dashmm::Point position; // Position of the bead
double q[3] = {0.0}; // "charges" carried by the bead
double value[3] = {0.0};
};
std::vector<double> rpy_m_to_t(const Point &t, const Point &c, double scale,
const dcomplex_t *M1, const dcomplex_t *M2,
const dcomplex_t *M3, const dcomplex_t *M4);
std::vector<double> rpy_l_to_t(const Point &t, const Point &c, double scale,
const dcomplex_t *L1, const dcomplex_t *L2,
const dcomplex_t *L3, const dcomplex_t *L4);
template <typename Source, typename Target>
class RPY {
public:
using source_t = Source;
using target_t = Target;
using expansion_t = RPY<Source, Target>;
RPY(ExpansionRole role, double scale = 1.0, Point center = Point{})
: views_{ViewSet{role, center, scale}} {
// The RPY class applies the Laplace kernel to create four views
// Views 0, 1, 2 are generated using q[0], q[1], and q[2] as the "charge"
// Views 3 is generated using -c1 * (q[0] * x + q[1] * y + q[2] * z)
// View size for each spherical harmonic expansion
int p = builtin_laplace_table_->p();
int nsh = (p + 1) * (p + 2) / 2;
// View size for each exponential expansion
int nexp = builtin_laplace_table_->nexp();
if (role == kSourcePrimary || role == kTargetPrimary) {
size_t bytes = sizeof(dcomplex_t) * nsh;
for (int i = 0; i < 4; ++i) {
char *data = new char[bytes]();
views_.add_view(i, bytes, data);
}
} else if (role == kSourceIntermediate) {
size_t bytes = sizeof(dcomplex_t) * nexp;
for (int i = 0; i < 24; ++i) {
char *data = new char[bytes]();
views_.add_view(i, bytes, data);
}
} else if (role == kTargetIntermediate) {
size_t bytes = sizeof(dcomplex_t) * nexp;
for (int i = 0; i < 112; ++i) {
char *data = new char[bytes]();
views_.add_view(i, bytes, data);
}
}
}
RPY(const ViewSet &views) : views_{views} { }
~RPY() {
int count = views_.count();
if (count) {
for (int i = 0; i < count; ++i) {
delete [] views_.view_data(i);
}
}
}
void release() {views_.clear();}
bool valid(const ViewSet &view) const {
// \p view is assumed to be a subset of \p views_ (no range checking
// performed). The function returns true if and only if each entry in the
// required subset is associated with some data.
bool is_valid = true;
int count = view.count();
for (int i = 0; i < count; ++i) {
int idx = view.view_index(i);
if (views_.view_data(idx) == nullptr) {
is_valid = false;
break;
}
}
return is_valid;
}
int view_count() const { return views_.count(); }
ViewSet get_all_views() const {return views_;}
ExpansionRole role() const {return views_.role();}
Point center() const {return views_.center();}
size_t view_size(int view) const {
return views_.view_bytes(view) / sizeof(dcomplex_t);
}
dcomplex_t view_term(int view, size_t i) const {
dcomplex_t *data = reinterpret_cast<dcomplex_t *>(views_.view_data(view));
return data[i];
}
std::unique_ptr<expansion_t> S_to_M(const Source *first,
const Source *last) const {
Point center = views_.center();
double scale = views_.scale();
expansion_t *ret{new expansion_t{kSourcePrimary, scale, center}};
dcomplex_t *M1 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(0));
dcomplex_t *M2 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(1));
dcomplex_t *M3 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(2));
dcomplex_t *M4 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(3));
for (auto i = first; i != last; ++i) {
Point dist = point_sub(i->position, center);
lap_s_to_m(dist, i->q[0], scale, M1);
lap_s_to_m(dist, i->q[1], scale, M2);
lap_s_to_m(dist, i->q[2], scale, M3);
double q4 = i->q[0] * i->position.x() +
i->q[1] * i->position.y() + i->q[2] * i->position.z();
lap_s_to_m(dist, q4, scale, M4);
}
return std::unique_ptr<expansion_t>{ret};
}
std::unique_ptr<expansion_t> S_to_L(const Source *first,
const Source *last) const {
Point center = views_.center();
double scale = views_.scale();
expansion_t *ret{new expansion_t{kTargetPrimary}};
dcomplex_t *L1 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(0));
dcomplex_t *L2 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(1));
dcomplex_t *L3 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(2));
dcomplex_t *L4 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(3));
for (auto i = first; i != last; ++i) {
Point dist = point_sub(i->position, center);
lap_s_to_l(dist, i->q[0], scale, L1);
lap_s_to_l(dist, i->q[1], scale, L2);
lap_s_to_l(dist, i->q[2], scale, L3);
double q4 = i->q[0] * i->position.x() +
i->q[1] * i->position.y() + i->q[2] * i->position.z();
lap_s_to_l(dist, q4, scale, L4);
}
return std::unique_ptr<expansion_t>{ret};
}
std::unique_ptr<expansion_t> M_to_M(int from_child) const {
dcomplex_t *M1 = reinterpret_cast<dcomplex_t *>(views_.view_data(0));
dcomplex_t *M2 = reinterpret_cast<dcomplex_t *>(views_.view_data(1));
dcomplex_t *M3 = reinterpret_cast<dcomplex_t *>(views_.view_data(2));
dcomplex_t *M4 = reinterpret_cast<dcomplex_t *>(views_.view_data(3));
expansion_t *ret{new expansion_t{kSourcePrimary}};
dcomplex_t *W1 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(0));
dcomplex_t *W2 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(1));
dcomplex_t *W3 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(2));
dcomplex_t *W4 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(3));
lap_m_to_m(from_child, M1, W1);
lap_m_to_m(from_child, M2, W2);
lap_m_to_m(from_child, M3, W3);
lap_m_to_m(from_child, M4, W4);
return std::unique_ptr<expansion_t>{ret};
}
std::unique_ptr<expansion_t> M_to_L(Index s_index, Index t_index) const {
return std::unique_ptr<expansion_t>{nullptr};
}
std::unique_ptr<expansion_t> L_to_L(int to_child) const {
dcomplex_t *L1 = reinterpret_cast<dcomplex_t *>(views_.view_data(0));
dcomplex_t *L2 = reinterpret_cast<dcomplex_t *>(views_.view_data(1));
dcomplex_t *L3 = reinterpret_cast<dcomplex_t *>(views_.view_data(2));
dcomplex_t *L4 = reinterpret_cast<dcomplex_t *>(views_.view_data(3));
expansion_t *ret{new expansion_t{kTargetPrimary}};
dcomplex_t *W1 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(0));
dcomplex_t *W2 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(1));
dcomplex_t *W3 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(2));
dcomplex_t *W4 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(3));
lap_l_to_l(to_child, L1, W1);
lap_l_to_l(to_child, L2, W2);
lap_l_to_l(to_child, L3, W3);
lap_l_to_l(to_child, L4, W4);
return std::unique_ptr<expansion_t>{ret};
}
void M_to_T(Target *first, Target *last) const {
double scale = views_.scale();
dcomplex_t *M1 = reinterpret_cast<dcomplex_t *>(views_.view_data(0));
dcomplex_t *M2 = reinterpret_cast<dcomplex_t *>(views_.view_data(1));
dcomplex_t *M3 = reinterpret_cast<dcomplex_t *>(views_.view_data(2));
dcomplex_t *M4 = reinterpret_cast<dcomplex_t *>(views_.view_data(3));
for (auto i = first; i != last; ++i) {
auto result = rpy_m_to_t(i->position, views_.center(), scale,
M1, M2, M3, M4);
i->value[0] += result[0];
i->value[1] += result[1];
i->value[2] += result[2];
}
}
void L_to_T(Target *first, Target *last) const {
double scale = views_.scale();
dcomplex_t *L1 = reinterpret_cast<dcomplex_t *>(views_.view_data(0));
dcomplex_t *L2 = reinterpret_cast<dcomplex_t *>(views_.view_data(1));
dcomplex_t *L3 = reinterpret_cast<dcomplex_t *>(views_.view_data(2));
dcomplex_t *L4 = reinterpret_cast<dcomplex_t *>(views_.view_data(3));
for (auto i = first; i != last; ++i) {
auto result = rpy_l_to_t(i->position, views_.center(), scale,
L1, L2, L3, L4);
i->value[0] += result[0];
i->value[1] += result[1];
i->value[2] += result[2];
}
}
void S_to_T(const Source *s_first, const Source *s_last,
Target *t_first, Target *t_last) const {
double a = rpy_table_->a();
double c0 = rpy_table_->c0();
double c1 = rpy_table_->c1();
double c2 = rpy_table_->c2();
for (auto i = t_first; i != t_last; ++i) {
double v0 = 0.0, v1 = 0.0, v2 = 0.0;
for (auto j = s_first; j != s_last; ++j) {
double x = i->position.x() - j->position.x();
double y = i->position.y() - j->position.y();
double z = i->position.z() - j->position.z();
double q0 = j->q[0];
double q1 = j->q[1];
double q2 = j->q[2];
double r = sqrt(x * x + y * y + z * z);
if (r >= 2 * a) {
double A = (q0 * x + q1 * y + q2 * z) *
(c1 / pow(r, 3) - 3 * c2 / pow(r, 5));
double B = c1 / r + c2 / pow(r, 3);
v0 += q0 * B + A * x;
v1 += q1 * B + A * y;
v2 += q2 * B + A * z;
} else if (r > 0) {
double c3 = 9.0 / 32.0 / a;
double c4 = 3.0 / 32.0 / a;
double A1 = c0 * (1 - c3 * r);
double A2 = c4 * (q0 * x + q1 * y + q2 * z) / r;
v0 += A1 * q0 + A2 * x;
v1 += A1 * q1 + A2 * y;
v2 += A1 * q2 + A2 * z;
}
}
i->value[0] += v0;
i->value[1] += v1;
i->value[2] += v2;
}
}
std::unique_ptr<expansion_t> M_to_I() const {
dcomplex_t *M1 = reinterpret_cast<dcomplex_t *>(views_.view_data(0));
dcomplex_t *M2 = reinterpret_cast<dcomplex_t *>(views_.view_data(1));
dcomplex_t *M3 = reinterpret_cast<dcomplex_t *>(views_.view_data(2));
dcomplex_t *M4 = reinterpret_cast<dcomplex_t *>(views_.view_data(3));
expansion_t *ret{new expansion_t{kSourceIntermediate}};
lap_m_to_i(M1, ret->views_, 0);
lap_m_to_i(M2, ret->views_, 6);
lap_m_to_i(M3, ret->views_, 12);
lap_m_to_i(M4, ret->views_, 18);
return std::unique_ptr<expansion_t>(ret);
}
std::unique_ptr<expansion_t> I_to_I(Index s_index, Index t_index) const {
ViewSet views{kTargetIntermediate};
lap_i_to_i(s_index, t_index, views_, 0, 0, views);
lap_i_to_i(s_index, t_index, views_, 6, 28, views);
lap_i_to_i(s_index, t_index, views_, 12, 56, views);
lap_i_to_i(s_index, t_index, views_, 18, 84, views);
expansion_t *ret = new expansion_t{views};
return std::unique_ptr<expansion_t>{ret};
}
std::unique_ptr<expansion_t> I_to_L(Index t_index) const {
// t_index is the index of the child
expansion_t *ret{new expansion_t{kTargetPrimary}};
dcomplex_t *L1 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(0));
dcomplex_t *L2 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(1));
dcomplex_t *L3 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(2));
dcomplex_t *L4 = reinterpret_cast<dcomplex_t *>(ret->views_.view_data(3));
double scale = views_.scale() * 2;
lap_i_to_l(views_, 0, t_index, scale, L1);
lap_i_to_l(views_, 28, t_index, scale, L2);
lap_i_to_l(views_, 56, t_index, scale, L3);
lap_i_to_l(views_, 84, t_index, scale, L4);
return std::unique_ptr<expansion_t>(ret);
}
void add_expansion(const expansion_t *temp1) {
// This operation assumes that the views included in \p temp1 is a subset of
// \p views_. No range checking performed.
int count = temp1->views_.count();
for (int i = 0; i < count; ++i) {
int idx = temp1->views_.view_index(i);
int size = temp1->views_.view_bytes(i) / sizeof(dcomplex_t);
dcomplex_t *lhs = reinterpret_cast<dcomplex_t *>(views_.view_data(idx));
dcomplex_t *rhs =
reinterpret_cast<dcomplex_t *>(temp1->views_.view_data(i));
for (int j = 0; j < size; ++j) {
lhs[j] += rhs[j];
}
}
}
static void update_table(int n_digits, double domain_size,
const std::vector<double> &kernel_params) {
update_laplace_table(n_digits, domain_size);
if (kernel_params.size() == 1) {
update_rpy_table(kernel_params[0]);
} else {
assert(kernel_params.size() == 4);
update_rpy_table(kernel_params[0], kernel_params[1],
kernel_params[2], kernel_params[3]);
}
}
static void delete_table() { }
static double compute_scale(Index index) {
return builtin_laplace_table_->scale(index.level());
}
static int weight_estimate(Operation op,
Index s = Index{}, Index t = Index{}) {
int weight = 0;
if (op == Operation::MtoI) {
weight = 6;
} else if (op == Operation::ItoI) {
int dx = s.x() - 2 * t.x();
int dy = s.y() - 2 * t.y();
int dz = s.z() - 2 * t.z();
for (int i = 0; i < 3; ++i) {
int tag = merge_and_shift_table[dx + 2][dy + 2][dz + 2][i];
if (tag == -1) {
break;
}
weight++;
}
} else {
weight = 1;
}
return weight;
}
private:
ViewSet views_;
};
} // namespace dashmm
#endif // __RPY_EXPANSION_H__
| true |
80ab221ab8ac63aa373007e0213844dcadefbc3c | C++ | ROtrebski/ros-indigo-robotino | /invert_laser/src/invert_laser.cpp | UTF-8 | 1,186 | 2.640625 | 3 | [] | no_license | #include "invert_laser.h"
Invert_Laser::Invert_Laser(ros::NodeHandle n)
{
n_ = n;
scan_sub_ = n.subscribe("scan_uninverted", 10, &Invert_Laser::laserCallback, this);
scan_pub_ = n.advertise<sensor_msgs::LaserScan>("scan", 50, true);
}
Invert_Laser::~Invert_Laser()
{
scan_sub_.shutdown();
scan_pub_.shutdown();
}
void Invert_Laser::laserCallback(const sensor_msgs::LaserScanConstPtr& scan)
{
laser_data_.header.stamp = scan->header.stamp;
laser_data_.header.frame_id = scan->header.frame_id;
laser_data_.angle_min = scan->angle_min;
laser_data_.angle_max = scan->angle_max;
laser_data_.angle_increment = scan->angle_increment;
laser_data_.time_increment = scan->time_increment;
laser_data_.scan_time = scan->scan_time;
laser_data_.range_min = scan->range_min;
laser_data_.range_max = scan->range_max;
laser_data_.ranges = scan->ranges;
for (int laser_index = 0 ; laser_index < scan->ranges.size() ; laser_index++ )
{
laser_data_.ranges[scan->ranges.size() - laser_index - 1] = scan->ranges[laser_index];
}
scan_pub_.publish(laser_data_);
//std::cout<<"scan_size: "<<scan->ranges.size()<<" | laser_data_size: "<<laser_data_.ranges.size()<<std::endl;
}
| true |
351e56d7f643eca189933a878949fd79545c8298 | C++ | HexaTeam4212/TPCompiloLouisLucie | /States.h | UTF-8 | 2,016 | 2.71875 | 3 | [] | no_license | //
// Created by Louis on 18/02/2020.
//
#ifndef TP_STATES_H
#define TP_STATES_H
#include <string>
#include <iostream>
#include "Symbol.h"
#include "Automata.h"
using namespace std;
class Automata;
class Symbol;
class State;
class E0;
class E1;
class E2;
class E3;
class E4;
class E5;
class E6;
class E7;
class E8;
class E9;
class State {
public:
State();
explicit State(const string& name);
virtual ~State();
virtual void print() const;
virtual bool transition(Automata & automate,
Symbol * s) = 0;
};
class E0: public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override ;
};
class E1 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override;
};
class E2 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override ;
};
class E3 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override;
};
class E4 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override;
};
class E5 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override ;
};
class E6 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override ;
};
class E7 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override ;
};
class E8 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override ;
};
class E9 : public State {
public:
void print() const override;
bool transition(Automata &automate, Symbol *s) override;
};
#endif //TP_STATES_H
| true |
5aa80f31da1a2f4fdec721f590802681b82b78c3 | C++ | antbenar/AlgebraAbstracta_2_1-2017-1- | /rutas_encriptar/main.cpp | UTF-8 | 356 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include "rutas.h"
#include <string>
using namespace std;
int main()
{
Rutas ruta(4);//3,7,6,11,12,13,...
string b,a;
cout<< "escriba su frase a cifrar: ";
getline(cin,b);
a=ruta.cifrar(b);
cout<< "su clave cifrada es: "<<a<<endl;
cout<< "su clave descifrada es: "<<ruta.descifrar(a)<<endl;
return 0;
}
| true |
87eaa1c28c1356dbb87a7b9d85c2a2db023feea1 | C++ | BenjaminRubio/CompetitiveProgramming | /Problems/Otros/MemoryAndTrident.cpp | UTF-8 | 424 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
string s;
map<char, int> m = {{'L', 0}, {'R', 0}, {'U', 0}, {'D', 0}};
int main()
{
cin >> s;
if (s.size() % 2)
{
cout << -1 << '\n';
return 0;
}
for (char c : s) m[c]++;
int ans = 0;
ans += abs(m['L'] - m['R']) / 2;
ans += abs(m['U'] - m['D']) / 2;
if ((m['L'] + m['R']) % 2)
ans++;
cout << ans << '\n';
} | true |
91a101b4baa1378a2821f80f51ffc954e26b68e4 | C++ | abrahanrm/ComputerScience_UNI | /CC232-Algoritmos_y_estructura_de_datos/Coding/C08-listaDoblementeEnlazada.cpp | UTF-8 | 4,043 | 3.421875 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
class NodoDoble
{
private:
int dato;
NodoDoble* adelante;
NodoDoble* atras;
public:
NodoDoble(int t)
{
dato=t;
adelante=atras=NULL;
}
int datoNodo(){return dato;}
void fijarDato(int a){dato=a;}
NodoDoble* adelanteNodo(){return adelante;}
NodoDoble* atrasNodo(){return atras;}
void ponerAdelante(NodoDoble* a){adelante=a;}
void ponerAtras(NodoDoble* a){atras=a;}
};
class ListaDoble
{
private:
NodoDoble* cabeza;
NodoDoble* cola;
public:
ListaDoble()
{
cabeza=cola=NULL;
}
void crearLista();
void visualizar();
void insertarCabezaLista(int);
void insertarDespues(int, int);
void eliminar(int);
void insertarFinLista(int);
void insertarAntes(int, int);
void modificar(int,int);
};
void ListaDoble::crearLista(){
int x;
cout<<"Termina con -1"<<endl;
do
{
cin>>x;
if(x!=-1)
insertarCabezaLista(x);
} while(x!=-1);
};
void ListaDoble::insertarCabezaLista(int dato)
{
NodoDoble* nuevo;
nuevo=new NodoDoble(dato);
nuevo->ponerAdelante(cabeza);
if(cabeza!=NULL)
cabeza->ponerAtras(nuevo);
cabeza=nuevo;
};
void ListaDoble::visualizar()
{
NodoDoble* indice;
indice=cabeza;
cout<<"Atras"<<"\t"<<"DirDelDato"<<"\t"<<"Dato"<<"\t"<<"Adelante"<<endl;
while (indice!=NULL)
{
cout<<indice->atrasNodo()<<"\t"<<indice<<"\t"<<indice->datoNodo()<<"\t"<<indice->adelanteNodo()<<endl;
indice=indice->adelanteNodo();
}
};
void ListaDoble::insertarDespues(int datoAnterior, int dato)
{
NodoDoble* nuevo;
NodoDoble* anterior;
nuevo=new NodoDoble(dato);
//buscando el dato anterior
NodoDoble *indice;
indice=cabeza;
while (indice!=NULL)
{
if(indice->datoNodo()==datoAnterior)
break;
else
indice=indice->adelanteNodo();
}
//insertando el dato
if(indice!=NULL)
{
anterior=indice;
nuevo->ponerAdelante(anterior->adelanteNodo());
if(anterior->adelanteNodo()!=NULL)
anterior->adelanteNodo()->ponerAtras(nuevo);
else
cola=nuevo;
anterior->ponerAdelante(nuevo);
nuevo->ponerAtras(anterior);
}
};
void ListaDoble::insertarFinLista(int dato)
{
NodoDoble* nuevo;
nuevo = new NodoDoble (dato);
nuevo -> ponerAtras(cola);
if (cola != NULL )
cola->ponerAdelante(nuevo);
else
cabeza=cola=nuevo;
cola=nuevo;
};
void ListaDoble::insertarAntes(int datoPosterior, int dato)
{
NodoDoble* nuevo;
NodoDoble* posterior;
nuevo=new NodoDoble(dato);
//busqueda del nodo
NodoDoble* indice;
indice = cabeza;
while (indice != NULL)
{
if(indice -> datoNodo() == datoPosterior)
break;
else
indice = indice -> adelanteNodo();
}
//Inserta antes
if(indice != NULL)
{
posterior=indice;
nuevo->ponerAdelante(posterior);
if(posterior->atrasNodo()!=NULL)
posterior->atrasNodo()->ponerAdelante(nuevo);
else
cabeza=nuevo;
nuevo->ponerAtras(posterior->atrasNodo());
posterior->ponerAtras(nuevo);
}
};
void ListaDoble::modificar(int datoAntiguo, int dato)
{
// Bucle de búsqueda del antiguo
NodoDoble* indice;
indice = cabeza;
while (indice != NULL)
{
if (indice -> datoNodo() == datoAntiguo)
break;
else
indice=indice->adelanteNodo();
}
//Reemplaza el dato
if(indice != NULL)
{
indice->fijarDato(dato);
}
}
int main()
{
ListaDoble miLista;
miLista.crearLista();
miLista.visualizar();
miLista.insertarDespues(7, 99);
//miLista.modificar(7,555);
//cout<<"--------------\n";
miLista.visualizar();
return 0;
}
| true |
3aea094c3343947d523ece794a8309b07ab572f5 | C++ | thecherry94/BuzzerMusicESP | /buzzer_music_importer.cpp | UTF-8 | 1,354 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
using namespace std;
#define A 27.50
#define B 30.87
#define C 32.70
#define D 36.70
#define E 41.20
#define F 43.65
#define G 49.00
#define __DEBUG__
struct MusicTone
{
uint32_t frequency;
double duration;
};
int main(int argc, char** argv)
{
if (argc != 2)
{
cout << "Invalid parameters!\n";
cout << "Syntax: program import_file_name\n";
}
const char* filename = argv[1];
int fd = open(filename, O_RDONLY, 0644);
size_t num_elem = 0;
read(fd, &num_elem, sizeof(size_t));
MusicTone buf;
std::vector<MusicTone> music;
music.reserve(num_elem);
while(read(fd, &buf, sizeof(MusicTone)))
music.push_back(buf);
char* info = "";
if(num_elem < music.size())
info = "more";
else if (num_elem > music.size())
info = "less";
if (strcmp(info, "") != 0)
cout << "[WARNING] File contains " << info << " elements than specified\n";
cout << "Number of tones: " << music.size() << endl;
for(int i = 0; i < music.size(); i++)
{
cout << "Tone: " << music[i].frequency << "Hz | " << music[i].duration << "sec\n";
}
return 0;
} | true |
86088cc5f3dfa2663184bdef8a86a1ba902ba6b6 | C++ | abhinavtripathi95/fancy-keypoints | /sfop/src/main.cpp | UTF-8 | 2,461 | 2.90625 | 3 | [] | no_license | /*
This is a modification of the main.cpp file which comes with the
original SFOP-0.9 code. We use this modified version to interface Python
with C using ctypes to get the SFOP keypoints.
The original code can be downloaded from
http://www.ipb.uni-bonn.de/data-software/sfop-keypoint-detector/
Apart from this, the other files which have been modified are: CSfop.cpp
and CSfop.h because we have added the function return_kp()
*/
#include "CSfop.h"
#include "CImg.h"
#include "CImageFactory.h"
#include "CImageCpu.h"
#ifdef GPU
#include "CImageCl.h"
#endif
using namespace SFOP;
extern "C" float* mymain(const char* inFile);
extern "C" void free_mem(float* a);
/**
* @brief This program demonstrates the use of the SFOP detector class CSfop.
*
* Run \code ./main --help \endcode to see a list of possible arguments, while
* SFOP detection is performed on a standard test image with default parameters.
*
* @param[in] argc
* @param[in] argv[]
*
* @return 0 if succeeded
*/
float* mymain(const char* inFile)
{
// parse options
const char* outFile = "sfop.dat";
const bool display = false; // Display result
const float imageNoise = 0.02; // Image noise [0.02]
const float precisionThreshold = 0; // Threshold on precision [0]
const float lambdaWeight = 2; // Weighting for lambda [2]
const unsigned int numOctaves = 3; // Number of octaves [3]
const unsigned int numLayers = 4; // Number of layers per octave [4]
#ifdef GPU
const int device = 0; //cimg_option("--device", 0, "Device, 0 for CPU, 1 for OpenCL on GPU [0]");
#endif
const int type = -1; //cimg_option("--type", -1, "Angle in degrees, or -1 for optimal features [-1]");
// create image factory depending on device
CImageFactoryAbstract* l_factory_p;
#ifdef GPU
if (device == 0) {
l_factory_p = new CImageFactory<CImageCpu>();
}
else {
l_factory_p = new CImageFactory<CImageCl>();
}
#else
l_factory_p = new CImageFactory<CImageCpu>();
#endif
// process input image
CSfop detector(l_factory_p, inFile);
detector.detect(numOctaves, numLayers, imageNoise, lambdaWeight, precisionThreshold, type);
detector.writeFile(outFile);
if (display) {
CImageCpu image;
image.load(inFile);
image.displayFeatures(detector.features_p());
}
float* kp = detector.return_kp();
return kp;
}
void free_mem(float* a)
{
delete[] a;
}
int main(){
return 0;
}
| true |
f6c4937905b4dd7487c2c46540c3d324540112de | C++ | SouthernStatesASD/tfdirDSPonPC | /configuration/src/configuration/Utility/Substation/Oneline/Oneline.cpp | UTF-8 | 1,060 | 3.125 | 3 | [] | no_license | //
// Created by Andre Henriques on 2019-08-14.
//
#include <utility>
#include <vector>
#include "Oneline.hpp"
Oneline::Oneline(string _x, string _y, string _z) {
x = move(_x);
y = move(_y);
z = move(_z);
}
Oneline::Oneline() {
this -> x = "";
this -> y = "";
this -> z = "";
}
vector<Oneline> Oneline::getVector(const Value &oneline) {
vector<Oneline> onelineVector;
for (auto& thisOneline : oneline.GetArray()) {
Oneline point;
if(thisOneline.HasMember("x")) point.setX(thisOneline["x"].GetString());
if(thisOneline.HasMember("y")) point.setY(thisOneline["y"].GetString());
if(thisOneline.HasMember("z")) point.setZ(thisOneline["z"].GetString());
onelineVector.push_back(point);
}
return onelineVector;
}
string Oneline::getX() {
return x;
}
void Oneline::setX(string x) {
this->x = x;
}
string Oneline::getY() {
return y;
}
void Oneline::setY(string y) {
this->y = y;
}
string Oneline::getZ() {
return z;
}
void Oneline::setZ(string z) {
this->z = z;
} | true |
590ee27ff19d041cb37a53f22e0651e5cca0d019 | C++ | nkcr7/Beginning-Algorithm-Contests | /exercise-3-8-repeating-decimals.cpp | UTF-8 | 615 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
int main()
{
double num, den;
double value;
std::string s;
int pointer;
int period;
while (std::cin>>num && std::cin>>den)
{
// 抓住小数计算的特征,一上来容易走错方向,例如先计算,然后转化为字符串,然后暴力求解循环长度
// 记录每次除法的余数,如果出现重复的余数,则循环了
// 数组记录是否出现该余数,例如余数3,则a[3]来记录,有记录的位置每次更新一位后加1,没有记录的保持为0,累加后的数可以作为循环长度
}
return 0;
} | true |
2411e65118aa29f877b583c395fd205edf55d3f5 | C++ | hsab/ofMoldApp | /src/conidium/ConidiumDance.cpp | UTF-8 | 531 | 2.546875 | 3 | [] | no_license | //
// ConidiumDance.cpp
// moldApp
//
// Created by Nuno on 24/01/2019.
//
#include "ConidiumDance.h"
ConidiumDance::ConidiumDance(Ink *ink, float recenterRatio) {
this->ink = ink;
this->recenterRatio = recenterRatio;
}
void ConidiumDance::update() {
ofVec2f cursorDir = ofVec2f(ofRandom(-1,1),
ofRandom(-1,1));
cursor = (cursor + cursorDir) * recenterRatio;
}
void ConidiumDance::draw() {
ofSetColor(ink->getColor(cursor));
ofFill();
ofDrawRectangle(cursor.x, cursor.y, 1, 1);
}
| true |
d17cfa6de14037b0cbfbda9e2edcbe7486c8ad27 | C++ | DawidCieslik/Warcaby | /Error.cpp | WINDOWS-1250 | 605 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "Error.h"
void Blad(unsigned int RodzajBledu)
{
switch (RodzajBledu)
{
case 1:
{
std::string error = "Nie ma takiego pola lub pionka!";
throw error;
break;
}
case 2:
{
std::string error = "Wczytywanie pliku nie powiodo si!";
throw error;
break;
}
case 3:
{
std::string error = "Gracz nie moze przyjmowac nazwy Komputer!";
throw error;
break;
}
case 4:
{
std::string error = "Nazwy graczy nie moga byc puste!";
throw error;
break;
}
}
} | true |
ce2f619cfd77a6c6c580eee8cb9f58311417610e | C++ | mark-tasaka/C-SFML-Ratcatchers-Revenge-Game | /code/Player.h | UTF-8 | 1,925 | 2.96875 | 3 | [] | no_license | #pragma once
#include <SFML/Graphics.hpp>
using namespace sf;
class Player
{
private:
const float START_SPEED = 200;
const float START_HEALTH = 200;
//where is the player
Vector2f m_Position;
//Player Sprite
Sprite m_Sprite;
//add a texture
Texture m_Texture;
//screen resolution
Vector2f m_Resolution;
//size of the current arena
IntRect m_Arena;
//how big is each tile in the arena
int m_TileSize;
//direction player is currently moving in
bool m_UpPressed;
bool m_DownPressed;
bool m_leftPressed;
bool m_RightPressed;
//player's current health
int m_Health;
//player's max health
int m_MaxHealth;
//when was the player hit last
Time m_LastHit;
//speed in pixels per second
float m_Speed;
/*Public Functions*/
public:
//C'tor
Player();
void spawn(IntRect arena, Vector2f resolution, int tielSize);
//call this at the end of every game
void resetPlayerStats();
//handle the player getting hit by rat
bool hit(Time timeHit);
//how long ago was the Player last hit
Time getLastHitTime();
//where is the player
FloatRect getPosition();
//where is the centre of the player
Vector2f getCenter();
//which angle is the player facing
float getRotation();
//send a copy of the sprite to main()
Sprite getSprite();
//move the player
void moveLeft();
void moveRight();
void moveUp();
void moveDown();
//stop player from moving in specific direction
void stopLeft();
void stopRight();
void stopUp();
void stopDown();
//called once every frame
void update(float elaspedTime, Vector2i mousePosition);
//gives player speed boost
void upgradeSpeed();
//gives player some health
void upgradeHealth();
//increase max amount of health for Player
void increaseHealthLevel(int amount);
//how much health the player has
int getHealth();
}; | true |
99c8d08671e54c320d36fe89a678cb37b2b9e4cc | C++ | pauladams12345/octopus_simulator | /Space.hpp | UTF-8 | 1,557 | 3.1875 | 3 | [] | no_license | /*********************************************************************
* Program name: Octopus Simulator 3000
* Author: Paul Adams
* Date: 03 19 2018
* Description: Header file for Space class. This class represents
* the physical space in which the octopus moves around in the game
*********************************************************************/
#ifndef FINAL_PROJECT_SPACE_HPP
#define FINAL_PROJECT_SPACE_HPP
#include <string>
#include "Octopus.hpp"
class Space {
public:
Space() {};
virtual ~Space();
Space(const std::string &name);
/* Sets the N, S, E, and W pointers to point to the appropriate locations
* in the world grid from Game */
void setSurroundings(Space *N, Space *E, Space *S, Space *W);
const std::string &getName() const;
void setName(const std::string &name);
Space *getN() const;
void setN(Space *N);
Space *getE() const;
void setE(Space *E);
Space *getW() const;
void setW(Space *W);
Space *getS() const;
void setS(Space *S);
/* Display all possible moves. Get choice from user. Check if move is valid.
* If yes return choice, else get new choice */
int move();
/* */
virtual void interact(Octopus *player) = 0;
/* Prints a description of the space to the console */
virtual void description() = 0;
private:
std::string name;
//Pointers to the spaces to the north, south, east, and west of the current space
Space *N;
Space *E;
Space *W;
Space *S;
};
#endif //FINAL_PROJECT_SPACE_HPP
| true |
dfbf2ba27e77d5987e9428a71a26eafaaf79c9cf | C++ | robotustra/cncmill | /powerfeed/powerfeed.ino | UTF-8 | 2,227 | 2.78125 | 3 | [] | no_license | /*
Power drive test.
Pin 2 - input encoder channel A,
Pin 3 - input encoder channel B
Pin 5 - Mode of operation HIGH = continuous mode LOW = step mode
Pin 13 - Step
Pin 12 - Direction
Encoder interrupt pin = 2;
*/
int PIN_ENC_A = 2;
int PIN_INT = 1; // interrupt pin for arduino Leonardo 32u4
int PIN_ENC_B = 3;
int PIN_MODE = 5; // input mode, direction
int PIN_PULS = 13;
int PIN_DIR = 12;
volatile unsigned long debounceThreshold = 700; // microseconds
volatile unsigned long debounceLast = 0;
volatile int pos = 0;
int lastPos = 0;
int pos_diff = 0;
int i;
volatile int mode = 0;
int speed = 0; // speed of turning ()
void setup() {
//Initialize serial and wait for port to open:
/*Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}*/
pinMode(PIN_ENC_A, INPUT_PULLUP);
pinMode(PIN_ENC_B, INPUT_PULLUP);
pinMode(PIN_MODE, INPUT_PULLUP);
attachInterrupt(PIN_INT, doEncoder, CHANGE);
pinMode(PIN_PULS, OUTPUT);
pinMode(PIN_DIR, OUTPUT);
digitalWrite(PIN_DIR, HIGH);
digitalWrite(PIN_PULS, HIGH);
speed = 0;
}
void loop ()
{
mode = digitalRead(PIN_MODE);
if (mode)
{
//continuous mode on the base of speed value
if (pos != lastPos)
{
pos_diff = lastPos - pos;
speed += pos_diff;
lastPos = pos;
}
if (speed > 0 )
{
digitalWrite (PIN_DIR, HIGH);
}
else
{
digitalWrite (PIN_DIR, LOW);
}
if (speed !=0){
for (i=0; i<1; i++){
delayMicroseconds(1000-3*abs(speed));
doStep();
}
}
}
else
{
//step mode;
if (pos != lastPos)
{
if (pos < lastPos)
{
digitalWrite (PIN_DIR, HIGH);
}
else
{
digitalWrite (PIN_DIR, LOW);
}
doStep();
lastPos = pos;
}
// reset speed all the time in step mode
speed = 0;
}
}
void doStep()
{
digitalWrite (PIN_PULS,LOW);
digitalWrite (PIN_PULS,HIGH);
}
void doEncoder() {
if (micros() - debounceLast > debounceThreshold)
{
debounceLast = micros();
if (PIND & B00000010) {
if (PIND & B00000001) {
pos--; // counter-clock-wise
}
else {
pos++; // clock-wise
}
}
}
}
| true |
eba3529aa096cdc6b9e94a06f87d33262ad29e5f | C++ | Anshulguptag/Data-Structures | /Graph/FindingShortestPath.cpp | UTF-8 | 2,653 | 3.34375 | 3 | [] | no_license | /*DFS is used*/
#include<iostream>
#include<list>
#include<queue>
using namespace std;
queue<int> temppath;
queue<int> path;
list<int> *adj = new list<int>[8];
void findShortPath(int x,int y,char ch[],int *count,bool visited[])
{
visited[x]=true;
temppath.push(x);
*count = *count+1;
if(x!=y)
{
list<int>::iterator i;
for(i=adj[x].begin();i!=adj[x].end();i++)
{
if(!visited[*i])
return findShortPath(*i,y,ch,count,visited);
}
}
}
void findPath(int x,int y,char ch[])
{
list<int>::iterator i;
int count,k=10;
bool *visited = new bool[8];
for(i=adj[x].begin();i!=adj[x].end();i++)
{
count = 0;
for (int j = 0; j < 8; j++)
visited[j] = false;
visited[x]=true;
findShortPath(*i,y,ch,&count,visited);
if(k>count)
{
while(!path.empty())
{
path.pop();
}
}
while(!temppath.empty())
{
if(k>count)
path.push(temppath.front());
temppath.pop();
}
k=count;
}
}
void addEdge(char a,char b,char ch[],int size)
{
int i,j;
for(i=0;i<size;i++)
{
if(ch[i]==a)
break;
}
for(j=0;j<size;j++)
{
if(ch[j]==b)
break;
}
adj[i].push_front(j);
adj[j].push_front(i);
}
int findIndex(char a,char ch[],int size)
{
int i;
for(i=0;i<size;i++)
{
if(a==ch[i])
break;
}
return i;
}
int main()
{
char ch[] = {'A','B','C','D','E','F','G','H'};
int size = *(&ch+1)-ch;
addEdge('A','B',ch,size);
addEdge('A','C',ch,size);
addEdge('A','F',ch,size);
addEdge('B','D',ch,size);
addEdge('C','E',ch,size);
addEdge('D','E',ch,size);
addEdge('F','G',ch,size);
addEdge('G','H',ch,size);
addEdge('H','E',ch,size);
list<int>::iterator i;
for(int j=0;j<size;j++)
{
cout<<"From "<<ch[j]<<"-->";
for(i=adj[j].begin();i!=adj[j].end();i++)
cout<<ch[*i]<<" ";
cout<<"\n";
}
/*
My Graph
B---D
/ \
A---C---E
\ /
F-G-H
*/
cout<<"\nEnter the Source Node: ";
char x;
cin>>x;
cout<<"\nEnter the Destination Node: ";
char y;
cin>>y;
findPath(findIndex(x,ch,size),findIndex(y,ch,size),ch);
cout<<"\nshortest path from "<<ch[findIndex(x,ch,size)]<<" to "<<ch[findIndex(y,ch,size)]<<": "<<ch[findIndex(x,ch,size)];
while(!path.empty())
{
cout<<ch[path.front()];
path.pop();
}
}
| true |
78c0143e4e0904fbfbd1bebfbb2bc721aa420399 | C++ | ashmi19/interviewbit | /Graph/cycle in a undirected graph/main.cpp | UTF-8 | 803 | 3.25 | 3 | [] | no_license |
bool isCyclic(int curr , const vector<vector<int>> &adj, vector<bool> &vis , int parent)
{
vis[curr] = true;
for(auto it : adj[curr])
{
if(vis[it] && it!=parent)
{
return true;
}
if(!vis[it] && isCyclic(it,adj,vis,curr))
{
return true;
}
}
return false;
}
int Solution::solve(int A, vector<vector<int> > &B)
{
vector<vector<int>> adj(A+1,vector<int>());
for(unsigned int i = 0 ; i < B.size() ; i++)
{
adj[B[i][0]].push_back(B[i][1]);
adj[B[i][1]].push_back(B[i][0]);
}
vector<bool> vis(A+1,0);
for(int i = 1 ; i <= A ;i++)
{
if(vis[i] == false)
{
if(isCyclic(i,adj,vis,-1))
return 1;
}
}
return 0;
}
| true |
772e92cb269b6c14e8973d92aa0be6e843b33f8f | C++ | Kiritow/OJ-Problems-Source | /HDOJ/4486_autoAC.cpp | UTF-8 | 551 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
int id,n,tot=0;
scanf("%d %d",&id,&n);
if(n%3==0) tot++;
int top=(int)ceil(n*1.0/3);
for(int i=n/2;i>=top;i--)
{
if(n-i==i) continue;
if((n-i)&1) {tot+=(i-(n-i+1)/2+1)*2;tot--;}
else {tot+=(i-(n-i)/2+1)*2;tot-=2;}
}
printf("%d %d\n",id,tot);
}
return 0;
}
| true |
b4cd627f280696b3823381a306c21c596b33783c | C++ | CSHwang4869/Online-Judge-Solutions | /Luogu/Luogu2397_N_logN.cpp | UTF-8 | 533 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#define DEBUG printf("Passing [%s] in Line %d\n" , __FUNCTION__ , __LINE__) ;
const int MAX_L = 30 + 5 , L = 30 ;
int n , cnt[2][MAX_L] ;
void add(int x) {
for (int i = 0 ; i <= L ; ++i)
if (x & (1 << i)) ++cnt[1][i] ;
else ++cnt[0][i] ;
}
int main() {
scanf("%d" , &n) ;
for (int i = 0 ; i < n ; ++i) {
int a ; scanf("%d" , &a) ;
add(a) ;
}
int ans = 0 ;
for (int i = 0 ; i <= L ; ++i)
if (cnt[1][i] > cnt[0][i]) ans |= (1 << i) ;
printf("%d\n" , ans) ;
return 0 ;
} | true |
eb576b882e5371ec50cbae61bbffcc3a8cfb3417 | C++ | Degiv/spbsu_homework | /sem1/Test_3/test3.1/main.cpp | UTF-8 | 1,612 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
void quickSort(int *myArray, int first, int last)
{
int i = first;
int j = last;
int pivot = myArray[(first + last) / 2];
while (i <= j)
{
while (myArray[i] < pivot)
++i;
while (myArray[j] > pivot)
--j;
if (i <= j)
{
swap(myArray[i], myArray[j]);
++i;
--j;
}
}
if (j > first)
quickSort(myArray, first, j);
if (i < last)
quickSort(myArray, i, last);
}
int* getNumbers(int &size)
{
const int maxSize = 1000;
int tmp[maxSize];
int i = -1;
bool isFirst = true;
while (tmp[i] != 0 || isFirst)
{
isFirst = false;
++i;
cin >> tmp[i];
}
size = i + 1;
int* result = new int[size];
for (int j = 0; j < size; ++j)
result[j] = tmp[j];
return result;
}
void showNumbers(int* numbers, int size)
{
bool isFirst = true;
int counter = 1;
int prev = 0;
if (size != 0)
prev = numbers[0];
for (int i = 1; i < size; ++i)
{
if (numbers[i] == prev)
{
counter++;
}
else
{
cout << prev << " contains " << counter << " times" << endl;
counter = 1;
}
prev = numbers[i];
}
cout << prev << " contains " << counter << " times";
}
int main()
{
int size = 0;
cout << "Enter your array of numbers: ";
int* numbers = getNumbers(size);
quickSort(numbers, 0, size);
showNumbers(numbers, size);
delete[] numbers;
}
| true |
40d3c46202ee35cdd574033c3c86435bb6841094 | C++ | Ninad99/data-structures-and-algorithms | /Algorithms/Graph/dungeongridBFS.cpp | UTF-8 | 2,367 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Grid {
private:
int R, C, startRow, startCol;
vector<vector<char> > matrix;
queue<int> rq; // row queue
queue<int> cq; // column queue
int move_count, nodes_left_in_layer, nodes_in_next_layer;
bool reached_end;
vector<vector<bool> > visited;
vector<int> dr;
vector<int> dc;
public:
Grid(vector<vector<char> >& grid, int rows, int cols, int sRow, int sCol) {
R = rows;
C = cols;
startRow = sRow;
startCol = sCol;
matrix = vector<vector<char> >(R, vector<char>(C));
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
matrix[i][j] = grid[i][j];
}
}
move_count = 0;
nodes_left_in_layer = 1;
nodes_in_next_layer = 0;
reached_end = false;
visited = vector<vector<bool> >(R, vector<bool>(C, false));
dr = { -1, 1, 0, 0 };
dc = { 0, 0, 1, -1 };
}
void explore_neighbours(int r, int c) {
for (int i = 0; i < 4; i++) {
int rr = r + dr[i];
int cc = c + dc[i];
if (rr < 0 || cc < 0) continue;
if (rr >= R || cc >= C) continue;
if (visited[rr][cc]) continue;
if (matrix[rr][cc] == '#') continue;
rq.push(rr);
cq.push(cc);
visited[rr][cc] = true;
nodes_in_next_layer++;
}
}
int solve() {
rq.push(startRow);
cq.push(startCol);
visited[startRow][startCol] = true;
while (!rq.empty()) {
int r = rq.front();
int c = cq.front();
if (matrix[r][c] == 'E') {
reached_end = true;
break;
}
explore_neighbours(r, c);
nodes_left_in_layer--;
if (nodes_left_in_layer == 0) {
nodes_left_in_layer = nodes_in_next_layer;
nodes_in_next_layer = 0;
move_count++;
}
rq.pop();
cq.pop();
}
if (reached_end)
return move_count;
return -1;
}
};
int main() {
vector<vector<char> > grid = {
{ 'S', '.', '.', '#', '.', '.', '.' },
{ '.', '#', '.', '.', '.', '#', '.' },
{ '.', '#', '.', '.', '.', '.', '.' },
{ '.', '.', '#', '#', '.', '.', '.' },
{ '#', '.', '#', 'E', '.', '#', '.' }
};
Grid g(grid, 5, 7, 0, 0);
int minMoves = g.solve();
if (minMoves != -1)
cout << "Minimum moves required to reach end: " << minMoves << endl;
else
cout << "Can't reach end" << endl;
return 0;
}
| true |
8bf4243403dce82142a9baa2f12f3ff019159b0f | C++ | saini-gitanjali/DSA | /sorting and searching/SquareRoot.cpp | UTF-8 | 551 | 3.40625 | 3 | [] | no_license | // { Driver Code Starts
#include <iostream>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int countSquares(int N) {
int count = 0;
for(int i = 1; i < sqrt(N); i++)
{
if(i*i < N)
count++;
}
return count;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin>>N;
Solution ob;
cout << ob.countSquares(N) << endl;
}
return 0;
} // } Driver Code Ends | true |
9002731c6b0934757f0f3caa1d9a4090f6f9730b | C++ | Abhijit-Dixit/Sports-Programming | /DisjointSetUnion.cpp | UTF-8 | 1,327 | 3.15625 | 3 | [] | no_license | vector<int> dsu; // the i'th index stores the parent of i if v[i] is positive, if v[i] is negative then i is its own parent...
int fin(int a){
vector<int> store;
while(dsu[a]>0){
store.push_back(a);
a=dsu[a];
}
for(int i=0;i<store.size();i++){
dsu[store[i]]=a;
}
return a;
}
void unio(int a,int b){
a=fin(a);
b=fin(b);
if(a!=b){
dsu[a]+=dsu[b];
dsu[b]=a;
}
}
int main(){
dsu.resize(n+1,-1);
dsu[0]=0;
for(int i=0;i<m;i++){
cin>>a>>b;
unio(a,b);
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class DSU{
private:
vector<int> parent;
public:
DSU(int n){
parent.resize(n);
}
void setParent(int ind,int val){
parent[ind]=val;
}
int findFunc(int ind){
if(ind!=parent[ind]){
parent[ind]=findFunc(parent[ind]);
}
return parent[ind];
}
bool unionFunc(int ind1, int ind2){
int parentInd1=findFunc(ind1);
int parentInd2=findFunc(ind2);
if(parentInd1==parentInd2){
return false;
}
parent[parentInd1]=parentInd2;
return true;
}
};
| true |
e0141d8f8d906e33a0412c975323e11dec2ec786 | C++ | whal0071/GameDevFrameWorkWhalen | /Resources/Images/Game/GameLayer.h | UTF-8 | 990 | 2.5625 | 3 | [] | no_license | //
// GameLayer.h
// GameDevFramework
//
// Created by Walter Whalen on 12-11-01.
// Copyright (c) 2012 Algonquin College. All rights reserved.
//
#ifndef __GameDevFramework__GameLayer__
#define __GameDevFramework__GameLayer__
#include <iostream>
#include "GameObject.h"
class GameLayer: public GameObject
{
//verbs -what i want my class to do
//draw
//update
public:
GameLayer();
~GameLayer();
//creating our overriding methods
//virtual so that our subclasses can overrride them
virtual void update(float delta);
virtual void paint();
virtual const char* getType();
//nouns - what i want my class to have
//have a location
//have a texture
protected:
OpenGLTexture *m_FollowingParallaxTexture;
OpenGLTexture *m_ParallaxTextures[2];
//vector<OpenGLTexture *>m_ParallaxTextures;
//OpenGLTexture **m_ParallaxTextures;
// TODO: include extra location variables if necessary
};
#endif
| true |
4cb8c728f2fdcb5dec3aa7a332dcf40e237f7bbd | C++ | galeirb/Seletor_Automatizado_de_Resistores | /InterfacePC/ArdSlave/ArdSlave.ino | UTF-8 | 1,925 | 2.625 | 3 | [
"MIT"
] | permissive | #include <Wire.h>
const int analogPin = A7;
const int pin_qtd = 6;
const int qtd_amostra = 10;
String instrucao_rx;
const int pin[pin_qtd] = { 2, 3, 4, 5, 6, 7 };
const float r1[pin_qtd] = { 62.0, 221.0, 9780.0, 4620.0, 327.0 };
float ref;
char c;
int x;
void setup() {
Serial.begin(9600);
Wire.begin(15); // MEGA - 15
Wire.onReceive(receiveEvent); //Recep��o dos dados (chama fun��o auxiliar)
for (int i = 0; i<pin_qtd; i++) {
pinMode(pin[i], OUTPUT);
digitalWrite(pin[i], LOW);
pinMode(pin[i], INPUT);
}
}
float tensaoMedia() {
float total = 0.0;
for (int i = 0; i<qtd_amostra; i++) {
delay(0);
total += float(analogRead(analogPin));
}
return 5.0*total / (qtd_amostra*1023.0);
}
float calcularResistencia(float r, float v) {
return r / (5.0 / v - 1.0);
}
void receiveEvent(int howMany)
{
while (1 < Wire.available()) //Loop para receber toda String de dados
{
if (Wire.read() == "1"); {
Serial.print("Deu certo"); //Imprime na Serial
}
if (Wire.read() == "1")
{
Serial.print("Fechado");
}
}
}
void loop() {
if (Serial.available()) {
char inst = Serial.read();
if (inst == ',') {
if (instrucao_rx == "leitura") {
float minimo = 2.5;
float resistencia = 100000000.0;
for (int i = 0; i<pin_qtd; i++) {
pinMode(pin[i], OUTPUT);
digitalWrite(pin[i], HIGH);
float v = tensaoMedia();
digitalWrite(pin[i], LOW);
pinMode(pin[i], INPUT);
float diferenca = abs(v - 2.5);
if (5.0 > v && diferenca < minimo) {
minimo = diferenca;
resistencia = calcularResistencia(r1[i], v);
ref = r1[i];
}
}
Serial.print("Resistencia = ");
Serial.println(resistencia);
Serial.print("Referencia utilizada: ");
Serial.println(ref);
Serial.println();
}
/////////
instrucao_rx = "";
/////////
}
else {
instrucao_rx += inst;
}
}
}
| true |
893132c2c9695d85b54372aa7fde70606cd05dfe | C++ | chihyang/CPP_Primer | /chap07/Exer07_57.cpp | UTF-8 | 617 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | #include <string>
class Account {
public:
Account() = default;
Account(const std::string& s, double d) : owner(s), amount(d) {}
void calculate() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double);
private:
static constexpr int period = 30; // period is a const expression
double daily_tbl[period] = {0};
std::string owner;
double amount;
static double interestRate;
};
void Account::rate(double d)
{
interestRate = d;
}
constexpr int Account::period;
double Account::interestRate = 0.0;
int main()
{
return 0;
}
| true |
0599520dc29f7dc561d083fd534e28a10c3e61ca | C++ | suaebahmed/data-structure-in-C-and-Cpp | /cpp strings-stream/stringstream.cpp | UTF-8 | 1,073 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<sstream>
using namespace std;
int main()
{
int k_size,k_item;
string line;
//getline(cin,line);
//istringstream ss(line);
//ss >>k_size;
//for(int j=0; j<k_size; j++){
// ss >> k_item;
// cout<<" | "<<k_item;
//}
//istream& getline (char* s, streamsize n );
//istream& getline (char* s, streamsize n, char delim );
//stringstream ss;
//ss.str("set the string value"); // setter
//cout<<ss.str()<<endl; // getter
char name[256], title[256];
cout << "Please, enter your name: ";
cin.getline (name,256);
cout << " Please, enter your favourite movie: ";
cin.getline (title,256);
cout<<name<<"'s favourite movie "<<title<<endl;
//char first, last;
//cout << "Please, enter your first name followed by your surname: ";
//first = cin.get(); // get one character
//cin.ignore(256,' '); // ignore until space
//last = cin.get(); // get one character
//cout << "Your initials are " << first << last << '\n';
return 0;
}
| true |
79897809c2aa055436d90fb546ec463a3ce63e9d | C++ | cyendra/ACM_Training_Chapter_One | /D - Game/main.cpp | UTF-8 | 1,079 | 2.515625 | 3 | [] | no_license |
#include <iostream>
#include <cstring>
using namespace std;
const int OO=1e9;
char s[1111];
char b[1111];
int n;
bool a[1111];
int main()
{
cin>>n;
cin>>s;
b[0]='1';
for (int i=1;i<n;i++)
{
if (b[i-1]=='0')
{
b[i]='1';
}
else if (b[i-1]=='1')
{
b[i]='0';
}
}
b[n]='\0';
//for (int i=0;i<n;i++) cout<<b[i];cout<<endl;
int ans=0;
memset(a,0,sizeof(a));
for (int i=0;i<n;i++)
{
if (s[i]!=b[i])
{
a[i]=1;
}
}
//for (int i=0;i<n;i++) cout<<a[i];cout<<endl;
for (int i=0;i<n;i++)
{
if (a[i]==1)
{
ans++;
}
}
int ret=0;
memset(a,0,sizeof(a));
for (int i=0;i<n;i++)
{
if (s[i]==b[i])
{
a[i]=1;
}
}
//for (int i=0;i<n;i++) cout<<a[i];cout<<endl;
for (int i=0;i<n;i++)
{
if (a[i]==1)
{
ret++;
}
}
ans=min(ans,ret);
cout<<ans<<endl;
return 0;
}
| true |
62b10427edc3fb90007c38e62b9b4f8513eefa58 | C++ | joeyleeeeeee97/ministl | /Test/Test_map.h | ISO-8859-1 | 1,426 | 2.96875 | 3 | [] | no_license | #pragma once
#ifndef _TEST_MAP
#define _TEST_MAP
#include<map>
#include"Test_map.h"
#include"map.h"
#include"string.h"
#include<assert.h>
#include<random>
//TestCase cppreference
namespace ministl
{
void TestCase1()
{
ministl::map<char, int> mymap;
std::map<char, int > mymap1;
char c;
mymap['a'] = mymap1['a'] = 101;
mymap['c'] = mymap1['c'] = 202;
mymap['f'] = mymap1['f'] = 303;
for (c = 'a'; c<'h'; c++)
{
assert( mymap1.count(c) == mymap.count(c) );
}
auto i = mymap.begin();
auto j = mymap1.begin();
while (i != mymap.end())
{
std::cout << (*i).first << (*j).first << std::endl;
assert((*i).first == (*j).first);
std::cout << (*i).second << (*j).second << std::endl;
assert((*i).second == (*j).second);
i++, j++;
}
}
void TestCase2()
{
ministl::map<int, string> mymap;
std::map<int, string > mymap1;
std::random_device rd;
for (int i = 0; i < 100; i++)
{
int tmp = rd() % 65536;
mymap1[tmp] = string(tmp,'a' + tmp % 26);
mymap[tmp] = string(tmp,'a' + tmp % 26);
}
auto i = mymap.begin();
auto j = mymap1.begin();
while (i != mymap.end())
{
// std::cout << (*i).first << (*j).first << std::endl;
assert((*i).first == (*j).first);
// std::cout << (*i).second << (*j).second << std::endl;
assert((*i).second == (*j).second);
i++, j++;
}
}
void TestAllcases()
{
TestCase1();
TestCase2();
}
}
#endif | true |
1dd68a6865f9e31ce0641f53bcdd65e822b68ed5 | C++ | mokkorin/sotukenProject | /Gauss.h | UTF-8 | 508 | 2.515625 | 3 | [] | no_license | #include <opencv\cv.h>
#include <opencv\highgui.h>
#define M_PI 3.1415926535897932384626433832795
class Gauss
{
public:
Gauss();
void dataSet(cv::Vec3d color, cv::Point p);
void dataClear(void);
void calcAverage(void);
void calcSigma(void);
void output(void);
double distribution(cv::Vec3d color);
bool isAveCalc;
bool isData;
double ave[3];
cv::Point p_ave;
protected:
std::vector< cv::Vec3d > data;
std::vector< cv::Point > point;
private:
cv::Mat sigma = (cv::Mat_<double>(3, 3));
};
| true |
a63f38789c85a26044bac83d311dec516fbba382 | C++ | black-shadows/Cracking-the-Coding-Interview | /Solutions/Chapter 8 Recursion/8.7.cpp | UTF-8 | 1,369 | 4.125 | 4 | [] | no_license | /*
* Q 8.7 Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent),
* write code to calculate the number of ways of representing n cents.
*/
#include <iostream>
using namespace std;
int cnt = 0;
void sumN(int sum, int c, int n)
{
if (sum >= n)
{
if (sum == n) ++cnt;
return;
}
else
{
if (c >= 25)
sumN(sum + 25, 25, n);
if (c >= 10)
sumN(sum + 10, 10, n);
if (c >= 5)
sumN(sum + 5, 5, n);
if (c >= 1)
sumN(sum + 1, 1, n);
}
}
int sum_n(int sum, int c, int n)
{
int ways = 0;
if (sum <= n)
{
if (sum == n) return 1;
if (c >= 25)
ways += sum_n(sum + 25, 25, n);
if (c >= 10)
ways += sum_n(sum + 10, 10, n);
if (c >= 5)
ways += sum_n(sum + 5, 5, n);
if (c >= 1)
ways += sum_n(sum + 1, 1, n);
}
return ways;
}
int make_change(int n, int denom)
{
int next_denom = 0;
switch (denom)
{
case 25:
next_denom = 10;
break;
case 10:
next_denom = 5;
break;
case 5:
next_denom = 1;
break;
case 1:
return 1;
}
int ways = 0;
for (int i = 0; i*denom <= n; ++i)
ways += make_change(n - i*denom, next_denom);
return ways;
}
int main()
{
int n = 10;
sumN(0, 25, n);
cout << cnt << endl;
cout << make_change(n, 25) << endl;
cout << sum_n(0, 25, n) << endl;
return 0;
}
| true |
03a36cd03b4eece2e78b7d1f98ea2f3df73fa083 | C++ | vtqtuan/mSIGNA | /src/setpassphrasedialog.cpp | UTF-8 | 2,093 | 2.625 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | ///////////////////////////////////////////////////////////////////////////////
//
// mSIGNA
//
// setpassphrasedialog.cpp
//
// Copyright (c) 2014 Eric Lombrozo
// Copyright (c) 2011-2016 Ciphrex Corp.
//
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
//
#include "setpassphrasedialog.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QLabel>
SetPassphraseDialog::SetPassphraseDialog(const QString& objectName, const QString& additionalText, QWidget* parent)
: QDialog(parent)
{
// Buttons
QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
| QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// Prompts
QLabel* promptLabel = new QLabel(tr("Enter passphrase for ") + objectName + ":");
QLabel* repromptLabel = new QLabel(tr("Enter it again:"));
// Text Edits
passphrase1Edit = new QLineEdit();
passphrase1Edit->setEchoMode(QLineEdit::Password);
passphrase2Edit = new QLineEdit();
passphrase2Edit->setEchoMode(QLineEdit::Password);
// Additional Text
QLabel* additionalTextLabel = new QLabel();
additionalTextLabel->setText(additionalText);
QVBoxLayout* mainLayout = new QVBoxLayout();
mainLayout->setSizeConstraint(QLayout::SetNoConstraint);
mainLayout->addWidget(promptLabel);
mainLayout->addWidget(passphrase1Edit);
mainLayout->addWidget(repromptLabel);
mainLayout->addWidget(passphrase2Edit);
mainLayout->addWidget(additionalTextLabel);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
setMinimumWidth(500);
}
QString SetPassphraseDialog::getPassphrase() const
{
if (passphrase1Edit->text() != passphrase2Edit->text())
throw std::runtime_error("Passphrases do not match.");
// TODO: check passphrase strength
return passphrase1Edit->text();
}
| true |
5805578c56cf641e402d37ac4f54bbc13fd26500 | C++ | os3llc/cloudsm | /src/common/xattr.cpp | UTF-8 | 3,791 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2020 nick_couchman.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/xattr.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/xattr.h>
#include <unistd.h>
/**
* Retrieve the HSM flags for a particular file by reading the extended
* attribute containing the flags. If nothing is read the default of 0
* will be returned, indicating no flags are set.
*
* @param fd
* The file descriptor pointing to the file whose extended attribute is
* being queried for HSM-related flags.
*
* @return
* The flags set on a particular file, or 0 if no flags are set.
*/
static uint8_t get_flags(int fd) {
uint8_t flags = 0;
fgetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags));
return flags;
}
/**
* Retrieve the file stat info for a particular stub file as stored in the
* extended attribute. This reads the data out of the extended attribute and
* allocates a character array for it, storing the value in the character array.
*
* @param fd
* The file descriptor pointing to the stub file whose extended attributes
* are being queried.
*
* @return
* A character array with the data from the stat extended attribute, or
* NULL if no data is present.
*/
static char* get_stats(int fd) {
ssize_t xa_size = fgetxattr(fd, HSM_XATTR_STAT_NAME, NULL, 0);
if (xa_size > 0) {
char* stats = malloc(xa_size);
fgetxattr(fd, HSM_XATTR_STAT_NAME, stats, xa_size);
return stats;
}
return NULL;
}
ssize_t hsm_clear_dirty(int fd) {
uint8_t flags = get_flags(fd);
flags ~= HSM_XATTR_FLAG_DIRTY;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
ssize_t hsm_clear_lost(int fd) {
uint8_t flags = get_flags(fd);
flags ~= HSM_XATTR_FLAG_LOST;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
ssize_t hsm_clear_recall(int fd) {
uint8_t flags = get_flags(fd);
flags ~= HSM_XATTR_FLAG_RECALL;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
ssize_t hsm_clear_stub(int fd) {
uint8_t flags = get_flags(fd);
flags ~= HSM_XATTR_FLAG_STUB;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
int hsm_is_dirty(int fd) {
return (get_flags(fd) & HSM_XATTR_FLAG_DIRTY);
}
int hsm_is_lost(int fd) {
return (get_flags(fd) & HSM_XATTR_FLAG_LOST);
}
int hsm_is_recalled(int fd) {
return (get_flags(fd) & HSM_XATTR_FLAG_RECALL);
}
int hsm_is_stub(int fd) {
return (get_flags(fd) & HSM_XATTR_FLAG_STUB);
}
ssize_t hsm_mark_dirty(int fd) {
uint8_t flags = get_flags(fd);
flags |= HSM_XATTR_FLAG_DIRTY;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
ssize_t hsm_mark_lost(int fd) {
uint8_t flags = get_flags(fd);
flags |= HSM_XATTR_FLAG_LOST;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
ssize_t hsm_mark_recall(int fd) {
uint8_t flags = get_flags(fd);
flags |= HSM_XATTR_FLAG_RECALL;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
}
ssize_t hsm_mark_stub(int fd) {
uint8_t flags = get_flags(fd);
flags |= HSM_XATTR_FLAG_STUB;
return fsetxattr(fd, HSM_XATTR_FLAG_NAME, &flags, sizeof(flags), 0);
} | true |
6585ad64cc816915ed8dcfcc1b9285ccc7b20816 | C++ | triffon/sdp-samples | /UnitTests/UnitTestCustomFramework/BoxTest.cpp | UTF-8 | 1,170 | 3.15625 | 3 | [] | no_license | /********************************************************************
*
* This file is part of the Data Structures in C++ Course Examples package.
*
* Author: Atanas Semerdzhiev
* URL: https://github.com/semerdzhiev/sdp-samples
*
*/
#include "UnitTestFramework.h"
#include "..\Box\Box.h"
TEST_FUNCTION(CreateEmptyBox)
{
Box obj;
}
TEST_FUNCTION(CreateBox)
{
Box obj(10);
}
TEST_FUNCTION(CreateBoxArray)
{
Box* p = new Box[1000000];
delete[] p;
}
TEST_FUNCTION(StoreAndRetrieveValue)
{
Box obj;
obj.Add(10.0);
TEST(obj.Peek() == 10.0);
}
TEST_FUNCTION(StoreAndModifyValue)
{
Box obj;
obj.Add(10);
obj.Add(20);
TEST(obj.Peek() == 20);
}
TEST_FUNCTION(IsEmpty)
{
Box obj;
TEST(obj.IsEmpty());
}
TEST_FUNCTION(NotEmpty)
{
Box obj;
obj.Add(10);
TEST(!obj.IsEmpty());
}
TEST_FUNCTION(PeekOnEmptyBox)
{
Box obj;
try
{
obj.Peek();
// The line above should throw, so if we reach this,
// the test has failed.
TEST(false);
}
catch (std::exception &)
{
// OK, std::exception thrown
}
catch (...)
{
// The exception should be of type std::exception,
// so if we reach this clause, the test has failed.
TEST(false);
}
} | true |
475df84f2ac0de1bd24ee9aa8d3013e30621c127 | C++ | shvrd/shvrdengine | /src/library/components/Entity.cpp | UTF-8 | 464 | 2.625 | 3 | [] | permissive | //
// Created by thekatze on 15/12/2018.
//
#include "Entity.h"
Entity::Entity()
: m_components()
, m_finalized(false) {
}
void Entity::update() {
for (auto& component : m_components) {
component->update();
}
}
void Entity::render() {
for (auto& component : m_components) {
component->render();
}
}
void Entity::pushComponent(std::unique_ptr<Component> component) {
m_components.push_back(std::move(component));
}
| true |
3f4551d0fca40f65026925593022e6eef34fe185 | C++ | Ckend/myLeetcode | /12. Integer to Roman/12. Integer to Roman/main.cpp | UTF-8 | 741 | 3.328125 | 3 | [] | no_license | //
// main.cpp
// 12. Integer to Roman
//
// Created by ckend on 2017/1/25.
// Copyright © 2017年 ckend. All rights reserved.
//
#include <iostream>
class Solution{
public:
std::string intToRoman(int num){
std::string M[] = {"", "M", "MM", "MMM"};
std::string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
std::string X[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
std::string I[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
};
int main(int argc, const char * argv[]) {
int nums = 1234;
Solution y;
std::cout<<y.intToRoman(nums)<<std::endl;
return 0;
}
| true |
d2b00564731dc7e88f138223d7cd8dc09f0cde51 | C++ | evanwills/artbot | /libraries/Evan__drawing-Machine-III/Evan_Circle-Manager.cpp | UTF-8 | 7,563 | 3.421875 | 3 | [] | no_license | // ==================================================================
// How it should work:
// 1.
// 2. for each child,
// 2.a. get radiusPointX & radiusPointY
// 2.b. rotate radiusPointX & radiusPointY around current
// orginX & orginY
// 2.c. send new radiusPointX & radiusPointY back to child
// 3. repeat steps 1 - 3 for each child
// ==================================================================
// START: circleManager family
// circleManager class objects manage recursively rotating the
// radiusPointX & Y of each circle in the stack relative to the
// origin of the current circle.
// Not sure how this needs to be coded but... the _radiusPointX,
// _circle->_radiusPointX, _childCircle->_originX and
// _childCircle->_circle->_originX should all share the same pointer.
// The same goes for the _radiusPointY
class circleManager : abstractCircle
{
private:
circleType * _circle;
unsigned int _depth = 0;
public:
/**
* @method depthOK() is used to varify that the stack of
* circles is OK. By OK, I mean that the
* last circle is a singleCircle object and
* that no multiCircle objects were added
* after it.
*
* This method should be called after all the circleManager
* objects have been initialised.
*
* NOTE: Because of the way multiCircle is setup, it should
* be OK to use a stack even if the output of depthOK()
* is FALSE.
*/
virtual bool depthOK( bool fix ) = 0;
virtual void fixDepth( );
/**
* @method setChildCircle() adds another circleManager
* object to the top of the stack
*/
virtual void setChildCircle( circleManager childCircle );
/**
* @method setRadiusPointXY() sets the radius point at a
* given depth after the XY points have been rotated
* by lower circleManager object
*
* @param [double] x the X coordinate of the radius point
* @param [double] y the Y coordinate of the radius point
* @param [unsigned in] depth how far from the top of the
* stack the radius point should be set
*/
virtual void setRadiusPointXY( double x , double y , unsigned int depth );
/**
* @method getCircleShape() returns the circleShape object
* used at a given depth;
*/
virtual circleShape * getCircleShape( unsigned int depth );
/**
* @method getDepth() returns the level in the stack that the
* circle is at
* e.g. if there are 5 circles in the stack
* and this one was added fourth, it's
* depth would be 1
*/
virtual unsigned int getDepth() = 0;
/**
* @method getRadiusPointX() returns the _radiusPointX
* coordinate at a given depth
*/
virtual double getRadiusPointX( unsigned int depth ) = 0;
/**
* @method getRadiusPointY() like getRadiusPointX() but for
* the Y value
*/
virtual double getRadiusPointY( unsigned int depth ) = 0;
}
class singleCircle : circleManager
{
public:
singleCircleManager( circleType circle ) {
_circle = circle;
}
double getDepth() {
return depth;
}
bool depthOK() {
return true;
}
bool fixDepth() {
}
void setChildCircle( circleManager * childCircle ) {
// do nothing singleCirclePoint objects have no child
}
void setRadiusPointXY( double x , double y , unsigned int depth ) {
_radiusPointX = x;
_radiusPointY = y;
}
void setOriginXY( double x , double y ) {
_OriginX = x;
_OriginY = y;
_circle->setOriginXY(x,y);
}
void initXY( double x , double y ) {
double pointX = 0;
double pointY = 0;
setOriginXY( x , y );
_circle->initXY( x , y );
_radiusPointX = _circle->getX();
_radiusPointY = _circle->getY();
}
/**
* @method rotate() rotates its own radius points
*/
void rotate() {
_circle->setOriginXY( _originX , _originY );
_circle->rotateXY( _radiusPointX , _radiusPointY );
_radiusPointX = _circle->getX();
_radiusPointY = _circle->getY();
}
double getAngleStep( unsigned int depth ) {
return _circle->getAngleStep(depth);
}
double getRadiusPointX( unsigned int depth ) {
return _radiusPointX;
}
double getRadiusPointY( unsigned int depth ) {
return _radiusPointY;
}
unsigned int getDepth() {
return _depth;
}
};
class multiCircle : singleCircle
{
private:
circleManager * _childCircle;
public:
void setChildCircle( circleManager * childCircle ) {
_depth += 1;
if( _childCircle === null ) {
_childCircle = childCircle;
_childCircle->initXY( _radiusPointX , _radiusPointY );
} else {
_childCircle->setChildCircle(childCircle);
}
}
/**
* @method rotate() rotates its own radius points as
* well as those of all its children. It also sets
* the _originX & _originY of its direct child
* manager
*/
void rotate() {
unsigned int tmpDepth = _depth;
double radiusPointX = 0;
double radiusPointY = 0;
_circle->setOriginXY( _originX , _originY );
for( tmpDepth ; tmpDepth >= 0 ; tmpDepth -= 1 ) {
radiusPointX = childCircle->getRadiusPointX( tmpDepth );
radiusPointY = childCircle->getRadiusPointY( tmpDepth );
_circle->rotateXY( radiusPointX , radiusPointY );
childCircle->setRadiusPointXY( _circle->getX() , _circle->getY() , tmpDepth );
}
_circle->rotate();
_radiusPointX = _circle->getX();
_radiusPointY = _circle->getY();
childCircle->setOriginXY( _radiusPointX , _radiusPointY );
childCircle->rotate();
}
/**
* @method depthOK() checks whether the hierarchy of nested
* circles is correct
*/
bool depthOK( ) {
bool output = false;
if( _childCircle == null ) {
if( _depth == 0 ) {
output true;
}
} else if( _childCircle->getDepth() + 1 == _depth ) {
output = true;
}
// this looks OK lets see whether the child is OK
return output;
}
/**
* @method fixDepth() makes sure the hierarchy of nested
* circles is correct
*/
void fixDepth( bool fix) {
if( _childCircle == null ){
if( _depth != 0 ) {
_depth = 0;
}
} else {
_childCircle->fixDepth();
int tmpDepth = _childCircle->getDepth();
if( tmpDepth + 1 != _depth ) {
if( fix == true ){
_depth = tmpDepth + 1;
}
}
}
}
void setRadiusPointXY( double x , double y , unsigned int depth ) {
depth -= 1;
if( depth == _depth ) {
_radiusPointX = x;
_radiusPointY = y;
// the radius point of this circle is the origin of the child
_childCircle->setOriginXY( x , y );
} else {
_childCircle->setRadiusPointXY( x , y , depth );
}
}
double getAngleStep( unsigned int depth ) {
depth -= 1;
if( depth == _depth ) {
return _circle->getAngleStep();
} else {
return _childCircle->getAngleStep(depth);
}
}
double getRadiusPointX( unsigned int depth ) {
depth -= 1;
if( depth == _depth || _childCircle == null ) {
return _radiusPointX;
} else {
return _childCircle->getRadiusPointX( depth );
}
}
double getRadiusPointY( unsigned int depth ) {
depth -= 1;
if( depth == _depth || _childCircle == null ) {
return _radiusPointY;
} else {
return _childCircle->getRadiusPointY( depth );
}
}
double getX() {
if( _childCircle == null ) {
return _radiusPointX;
} else {
return _childCircle->getX();
}
}
double getY() {
if( _childCircle == null ) {
return _radiusPointY;
} else {
return _childCircle->getY();
}
}
}
// END: circleManager
// ==================================================================
| true |
d1e906bce84fb09a68e6bcaf99588e52659f0cbf | C++ | westongaylord/okyesno | /Lexicon.cpp | UTF-8 | 2,609 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
typedef struct node {
bool isWord;
node *children[26];
} node;
private:
node *root;
bool recContainsPrefix(string prefix, node *curr);
bool recContains(string word, node *curr);
Lexicon::Lexicon() {
node *root = new node();
root->isWord = false;
for(int i = 0; i < node->children.length(); i++) {
node->children[i] = NULL;
}
}
bool recContainsPrefix(string prefix, node *curr) {
bool temp = false;
if(prefix == "") {
return true;
}
if(curr == NULL) {
return false;
}
char ch = prefix[0] - 'a';
if(ch >= 0 && ch < 26) {
temp = recContainsPrefix(prefix.substr(1, prefix.length()), curr->children[ch]);
}
return temp;
}
bool recContains(string word, node *curr) {
bool temp = false;
if(curr == NULL) {
return false;
}
if(word == "") {
return curr->isWord;
}
char ch = word[0] - 'a';
if(ch >= 0 && ch < 26) {
temp = recContainsPrefix(word.substr(1, word.length()), curr->children[ch]);
}
return temp;
}
//NO ARMS LENGTH RECURSION, NEED TO PASS IN A START STAR
void addHelper(node* &root, string word) {
if (root == NULL) {
// create new child
node *child = new node();
child->isWord = false;
for (char i = 'a'; i <= 'z'; i++) {
child->children[i - 'a'] = NULL;
}
root = child;
}
if (word == "") {
root->isWord = true;
return;
}
if (word[0] - 'a' < 0 || word[0] - 'a' >= 26) {
return;
}
char ch = word[0] - 'a';
addHelper(root->children[ch], word.substr(1));
}
void recAdd(string word, node *curr) {
if (word == "") {
curr->isWord = true;
return;
}
char ch = word[0] - 'a';
if(ch >= 0 && ch < 26) {
if(curr->children[ch] != NULL) {
recAdd(word.substr(1, word.length()), curr->children[ch]);
} else {
node *next = new node();
next->isWord = false;
for(int i = 0; i < node->children.length(); i++) {
next->children[i] = NULL;
}
curr->children[ch] = next;
recAdd(word.substr(1, word.length()), curr->children[ch]);
}
}
}
bool containsPrefix(string prefix) {
return recContainsPrefix(prefix, root);
}
bool contains(string word) {
return recContains(word, root);
}
void add(string word) {
if(curr == NULL) return;
recAdd(word, node *curr);
}
void recPrint(string curr, node * root) {
if(root == NULL) return;
if(root->isWord) cout << curr;
for(int i = 0; i < 26; i++) {
curr = 'a'+i;
recPrint(curr, root->children[i]);
}
}
void printAll() {
recPrint("", root);
}
void unionWith(Lexicon& other) {
foreach (string word in other) {
if(!contains(word)) {
add(word);
}
}
}
int main {
return 0;
} | true |
4e029138c4413270b104353f92f98dcb0ed6fc02 | C++ | Joeycama/CamachoJoseph_2524304 | /Project/Project%201/Project 1/main.cpp | UTF-8 | 7,390 | 3.703125 | 4 | [] | no_license | /*
File: main
Author: Joseph Camacho
Created on October 25th, 2016, 12:00 PM
Purpose: Project 1
*/
//System Libraries
#include <iostream> //Input/Output objects
#include <cstdlib> //Random number generator
#include <ctime> //Time
using namespace std; //Name-space used in the System Library
//User Libraries
//Global Constants
char TTT[3][3]={'1','2','3','4','5','6','7','8','9'};
char player = 'x';
short computr;
char comp = 'o';
//Function prototypes
void draw();
void Input();
void Input2();
void Player();
void Player2();
char win();
//Execution Begins Here!
int main(int argc, char** argv) {
//Declaration of Variables
int Choos;
//Input Variable
cout<<"Tic Tac Toe"<<endl;
cout<<"How many wish to Play"<<endl;
cin>>Choos;
cout<<" "<<endl;
//Display Output
if(Choos==2){
draw();
while(1){
Input();
draw();
if(win()=='x'){
cout<<"Player 1 wins"<<endl;
break;
}
else if (win()=='o'){
cout<<"Player 2 wins"<<endl;
break;
}
Player();
}
}
else if(Choos==1){
draw();
while(1){
Input();
Input2();
draw();
if(win()=='x'){
cout<<"You win"<<endl;
break;
}
else if (win()=='o'){
cout<<"You lose"<<endl;
break;
}
Player2();
}
}
else{
cout<<Choos<<" people, really?...your choice buddy!"<<endl;
draw();
while(1){
Input();
draw();
if(win()=='x'){
cout<<"Who ever was x won"<<endl;
break;
}
else if (win()=='o'){
cout<<"Who ever was o won"<<endl;
break;
}
Player();
}
}
return 0;
}
void draw()
{
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<TTT[i][j]<<" ";
}
cout<<endl;
}
}
void Input(){
int a;
cout<<"Press the number of the field: ";
cin>>a;
if (a==1)
{
if (TTT[0][0]=='1')
TTT[0][0]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==2)
{
if (TTT[0][1]=='2')
TTT[0][1]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==3)
{
if (TTT[0][2]=='3')
TTT[0][2]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==4)
{
if (TTT[1][0]=='4')
TTT[1][0]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==5)
{
if (TTT[1][1]=='5')
TTT[1][1]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==6)
{
if (TTT[1][2]=='6')
TTT[1][2]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==7)
{
if (TTT[2][0]=='7')
TTT[2][0]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==8)
{
if (TTT[2][1]=='8')
TTT[2][1]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==9)
{
if (TTT[2][2]=='9')
TTT[2][2]=player;
else
{
cout<<"Field is already in use"<<endl;
}
}
}
void Input2(){
int a;
srand(static_cast<unsigned int>(time(0)));
a=(rand()%9)+1;
cout<<"the computer chose: "<<a<<endl;
if (a==1)
{
if (TTT[0][0]=='1')
TTT[0][0]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==2)
{
if (TTT[0][1]=='2')
TTT[0][1]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==3)
{
if (TTT[0][2]=='3')
TTT[0][2]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==4)
{
if (TTT[1][0]=='4')
TTT[1][0]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==5)
{
if (TTT[1][1]=='5')
TTT[1][1]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==6)
{
if (TTT[1][2]=='6')
TTT[1][2]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==7)
{
if (TTT[2][0]=='7')
TTT[2][0]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==8)
{
if (TTT[2][1]=='8')
TTT[2][1]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
else if (a==9)
{
if (TTT[2][2]=='9')
TTT[2][2]=comp;
else
{
cout<<"Field is already in use"<<endl;
}
}
}
void Player(){
if(player=='x')
player='o';
else
player ='x';
}
void Player2(){
player='x';
comp='o';
}
char win(){
//first player
//Horizontal
if (TTT[0][0] =='x' && TTT[0][1] =='x' && TTT[0][2] =='x')
return 'x';
if (TTT[1][0] =='x' && TTT[1][1] =='x' && TTT[1][2] =='x')
return 'x';
if (TTT[2][0] =='x' && TTT[2][1] =='x' && TTT[2][2] =='x')
return 'x';
//Vertical
if (TTT[0][0] =='x' && TTT[1][0] =='x' && TTT[2][0] =='x')
return 'x';
if (TTT[0][1] =='x' && TTT[1][1] =='x' && TTT[2][1] =='x')
return 'x';
if (TTT[0][2] =='x' && TTT[1][2] =='x' && TTT[2][2] =='x')
return 'x';
//diagonal
if (TTT[0][0] =='x' && TTT[1][1] =='x' && TTT[2][2] =='x')
return 'x';
if (TTT[0][2] =='x' && TTT[1][1] =='x' && TTT[2][0] =='x')
return 'x';
//second player
//Horizontal
if (TTT[0][0] =='o' && TTT[0][1] =='o' && TTT[0][2] =='o')
return 'o';
if (TTT[1][0] =='o' && TTT[1][1] =='o' && TTT[1][2] =='o')
return 'o';
if (TTT[2][0] =='o' && TTT[2][1] =='o' && TTT[2][2] =='o')
return 'o';
//vertical
if (TTT[0][0] =='o' && TTT[1][0] =='o' && TTT[2][0] =='o')
return 'o';
if (TTT[0][1] =='o' && TTT[1][1] =='o' && TTT[2][1] =='o')
return 'o';
if (TTT[0][2] =='o' && TTT[1][2] =='o' && TTT[2][2] =='o')
return 'o';
//diagonal
if (TTT[0][0] =='o' && TTT[1][1] =='o' && TTT[2][2] =='o')
return 'o';
if (TTT[0][2] =='o' && TTT[1][1] =='o' && TTT[2][0] =='o')
return 'o';
return '/';
} | true |
ef49be27c899d5645db63df14f2a9cb3fe6d35e4 | C++ | chrystallagh/HavadjiaChrystalla_CSC17a_42824 | /Homework/Assignment 1 /Gaddis_Probl3.13/main.cpp | UTF-8 | 767 | 3.625 | 4 | [] | no_license | /*
* File: newmain.cpp
* Author: chrystallahavadjia
* Created on February 22, 2016, 8:42 PM
* Purpose: Convert U.S. dollars to Yen and Euro
* 3.13
*/
//System Libraries
#include <iostream>
using namespace std;
//User Libraries
//Global Constants
//Function Prototypes
//Execution Begins Here
int main()
{
const float YEN_PER_DOLLAR = 114.02, EUROS_PER_DOLLAR = 0.92;
float dollars = 0, yen = 0, euro = 0;
cout << "What is the amount of U.S dollars you wish to convert?\n";
cin >> dollars;
yen = YEN_PER_DOLLAR * dollars;
euro = EUROS_PER_DOLLAR * dollars;
cout << "The amount of money you will receive in yen and in euros is:" << endl;
cout << "\tYen: " << yen << "\n\tEuros: " << euro;
return 0;
} | true |
923f062cba4da342feb518150426bfeb3a6e56ea | C++ | danymtz/C-Course-for-begginers | /02.- Imprimir en pantalla.cpp | ISO-8859-1 | 647 | 3.109375 | 3 | [] | no_license | //Directivas de preprocesador
#include <stdio.h> //Librera stdio: incluye la funcin "printf()"
#include <conio.h> //Librera conio: incluye la funcin "getch()"
//Funcin: programa principal
void main()
{ //Inicia programa
printf("Hola, mundo."); //Imprime en pantalla la cadena "Hola, mundo."
getch(); //Espera respuesta por teclado
} //Fin del programa
/*
Estructura general de un programa econmico en C.
main()
{
//Sentencia 1;
//Sentencia 2;
//Sentencia n;
}
*/ | true |
a27ae6c63c52122ab9614355f414fa58b127e153 | C++ | armmah/LeetcodeProblems | /p441.cpp | UTF-8 | 1,345 | 3.296875 | 3 | [] | no_license | #include "LeetCodeProblem.h"
class p441 : public LeetCodeProblem {
int arrangeCoins(int n) {
// Sk = k / 2 (2 * a + (k - 1)d), where d = 1 and a = 1
// k (k + 1) = 2 n
// k ^ 2 + k - 2n = 0
// D = b ^ 2 - 4ac = 1 - 4 * (-2n) = 1 + 8n
// 2k = -1 + sqrt(1 + 8n) negative D is of no consequence to us because the b^2 = 1 and x can't be negative.
return (sqrt(8 * (long long)n + 1) - 1.0) / 2.0;
}
int bruteForce(int n) {
int c = 0;
for (int i = 1; ; i += 1) {
for(int k = 0; k < i; k++) {
//std::cout<<"[]";
c ++;
if(c == n) {
//std::cout<<" "<<(i - 1 + (k == i - 1))<<std::endl<<std::endl;
return (i - 1 + (k == i - 1));
}
}
//std::cout<<std::endl;
}
}
public:
void testCase() {
assert(arrangeCoins(2) == bruteForce(2));
assert(arrangeCoins(4) == bruteForce(4));
assert(arrangeCoins(10) == bruteForce(10));
assert(arrangeCoins(13) == bruteForce(13));
assert(arrangeCoins(15) == bruteForce(15));
assert(arrangeCoins(16) == bruteForce(16));
assert(arrangeCoins(18) == bruteForce(18));
assert(arrangeCoins(21) == bruteForce(21));
}
}; | true |
4fc4d181ec220ecc7ce8c421ad580d24e90cb1cb | C++ | yiboyang/quantize1d | /quantize1d.h | UTF-8 | 14,946 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <parallel/algorithm>
#include <unordered_set>
/* Fast 1d quantization methods
* Currently supports k-means. dp-means would require std::vector for cluster_centers (see original C++ implementation)
* k-means uses multithreaded (openMP) sort, as it tends to dominate the runtime.
* https://arxiv.org/abs/1806.05355
* Yibo Yang, Vibhav Gogate
*/
typedef double prec_type; // high precision type e.g., for std::accumulate; may need long double if input is huge (1e8)
// utility methods
// return a vector of indices in sorted order, based on an array of values
template<typename T>
std::vector<size_t> sort_index(const T *v, size_t v_size) {
// initialize index vector
std::vector<size_t> idx(v_size);
std::iota(idx.begin(), idx.end(), 0);
// sort indexes based on comparing values in v
__gnu_parallel::sort(idx.begin(), idx.end(),
[&v](size_t i, size_t j) -> bool { return v[i] < v[j]; });
// uncomment below for single-threaded sort
// std::sort(idx.begin(), idx.end(),
// [&v](size_t i, size_t j) -> bool { return v[i] < v[j]; });
//
return idx;
}
// overloaded version of the above accepting vectors
template<typename T>
std::vector<size_t> sort_index(const std::vector<T> &v) {
return sort_index(v.data(), v.size());
}
template<typename T>
void print_arr(T *a, const unsigned size) {
for (unsigned i = 0; i < size; ++i)
std::cout << *(a + i) << ' ';
std::cout << '\n';
}
template<typename T>
void print_vec(const std::vector<T> &v) {
for (auto &i: v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
// Fast iterative 1d kmeans:
// Strictly executes the E and M steps of kmeans, but operates on entire partitions of data points in 1D
// for O(K logN) E steps and O(N) M-steps; may end up with some empty clusters and have NaN as cluster centers;
// return the number of iterations that were actually run.
// The clusters are heuristically initialized to have equal cluster sizes.
// Always outputs cluster centers that are in sorted order.
template<typename asm_type, typename value_type>
size_t kmeans_cluster(value_type *data, asm_type *cluster_assignments, size_t num_data_points,
value_type *cluster_centers, size_t num_clusters, size_t max_iterations) {
if (num_clusters == 1) {
std::fill(cluster_assignments, cluster_assignments + num_data_points, 0);
prec_type data_sum = std::accumulate(data, data + num_data_points, 0.0);
value_type mean = static_cast<value_type>(data_sum / num_data_points);
cluster_centers[0] = mean;
return 0;
}
// need high precision for cluster_centers; will copy back later
auto cluster_centers_v = std::vector<prec_type>(num_clusters, 0.0);
// setup sorted data
std::vector<size_t> idx = sort_index(data, num_data_points); // idx addresses the original data in sorted order
std::vector<value_type> sorted_data(num_data_points); // copy of data that is sorted
for (unsigned i = 0; i < num_data_points; ++i)
sorted_data[i] = data[idx[i]];
// initialize by partitioning sorted data into K roughly equally-sized partitions; cluster_sizes
// implicitly determines cluster_assignments; each cluster roughly the same size
auto cluster_sizes = std::vector<size_t>(num_clusters, num_data_points / num_clusters);
for (size_t i = 0; i < (num_data_points % num_clusters); i++) // divvy up the remainder
++cluster_sizes[i];
// initialize the boundaries based on partition sizes;
// the kth boundary element marks the beginning of the kth partition (cluster); e.g. the 0th sorted data point
// trivially marks the beginning of the 0th cluster/partition;
// for convenience, I use an extra boundary at the end (whose position is equal to num_data_point) to mark
// the end of the last cluster
std::vector<size_t> boundaries(num_clusters + 1);
size_t position = 0;
for (size_t k = 0; k < num_clusters + 1; ++k) { // boundaries[num_clusters] == num_data_points
boundaries[k] = position;
position += cluster_sizes[k];
}
// update centers/sums based on assignment boundaries
auto cluster_sums = std::vector<prec_type>(num_clusters, 0.0);
for (size_t k = 0; k < num_clusters; ++k) {
size_t beg = boundaries[k], end = boundaries[k + 1];
for (size_t j = beg; j < end; ++j)
cluster_sums[k] += sorted_data[j];
cluster_centers_v[k] = cluster_sums[k] / (end - beg);
}
// assume Euclidean (geometric) distance is used
unsigned t;
const auto sorted_data_iter = sorted_data.begin(); // base iterator
auto new_boundaries = boundaries;
for (t = 0; t < max_iterations; t++) {
bool assignments_changed = false;
// reassign clusters (by redrawing boundaries); E-step
// in the kth iter, redraw the boundary (beginning) of the (k+1)th partition
for (size_t k = 0; k < (num_clusters - 1); k++) {
auto left_center = cluster_centers_v[k];
auto right_center = cluster_centers_v[k + 1];
size_t left_bound = boundaries[k]; // beginning of the kth cluster
size_t right_bound = boundaries[k + 2]; // beginning of the (k+2)th cluster (one past the end of (k+1)th)
// points lying in between left_center and right_center belongs to whichever is closer;
// simply find the mid-point, and assign points in [left_center, mid) to cluster k, and
// points in [mid, right_center) cluster k+1, i.e. the mid point marks the beginning of the (k+1)th
// cluster; note there's no need to adjust points either to the left of the smallest center or to the
// right of the largest center
auto mid = (left_center + right_center) / 2.0;
// binary-search between left_bound and right_bound for efficiency
auto mid_iter = lower_bound(sorted_data_iter + left_bound, sorted_data_iter + right_bound, mid);
auto mid_idx = static_cast<unsigned long>(mid_iter - sorted_data_iter); // guaranteed to be non-negative
if (boundaries[k + 1] != mid_idx) {
new_boundaries[k + 1] = mid_idx;
assignments_changed = true;
}
}
if (!assignments_changed) // converged; more iterations won't help
break;
// M-step
// update cluster sums based on changes in partitioning
for (size_t k = 0; k < num_clusters - 1; ++k) {
size_t prev_end = boundaries[k + 1], new_end = new_boundaries[k + 1];
value_type inc_sum; // how much the kth cluster expanded (and how much the (k+1)th shrunk)
if (new_end > prev_end) {
inc_sum = std::accumulate(sorted_data_iter + prev_end, sorted_data_iter + new_end, 0.0);
} else { // note the negative sign
inc_sum = -std::accumulate(sorted_data_iter + new_end, sorted_data_iter + prev_end, 0.0);
}
cluster_sums[k] += inc_sum;
cluster_sums[k + 1] -= inc_sum;
}
// update cluster centers
for (size_t k = 0; k < num_clusters; ++k) {
size_t cluster_size = new_boundaries[k + 1] - new_boundaries[k];
cluster_centers_v[k] = cluster_sums[k] / cluster_size;
}
boundaries = new_boundaries;
}
// map the partitioning scheme back to cluster_assignments
for (size_t k = 0; k < num_clusters; ++k) {
size_t beg = boundaries[k], end = boundaries[k + 1];
for (size_t j = beg; j < end; ++j)
cluster_assignments[idx[j]] = static_cast<asm_type>(k);
}
// copy to original cluster_centers
std::copy(cluster_centers_v.begin(), cluster_centers_v.end(), cluster_centers);
return t;
}
// Fast iterative 1d kmeans with warm start:
// Strictly executes the E and M steps of kmeans, but operates on entire partitions of data points in 1D
// for O(K logN) E steps and O(N) M-steps; may end up with some empty clusters and have NaN as cluster centers;
// return the number of iterations that were actually run.
// The clusters are initialized based on given values of cluster centers and are assumed valid (hence "lazy").
// Always outputs cluster centers that are in sorted order.
template<typename asm_type, typename value_type>
size_t kmeans_cluster_lazy(value_type *data, asm_type *cluster_assignments, size_t num_data_points,
value_type *cluster_centers, size_t num_clusters, size_t max_iterations) {
if (num_clusters == 1) {
std::fill(cluster_assignments, cluster_assignments + num_data_points, 0);
double data_sum = std::accumulate(data, data + num_data_points, 0.0);
value_type mean = static_cast<value_type>(data_sum / num_data_points);
cluster_centers[0] = mean;
return 0;
}
// need high precision for cluster_centers; will copy back later
std::vector<prec_type> cluster_centers_v;
cluster_centers_v.insert(cluster_centers_v.end(), cluster_centers,
cluster_centers + num_clusters); // copy over to vec
// keep the current values of cluster centers, but ensure cluster_centers is sorted (this may cause some data points
// to switch cluster/assignment labels if the cluster centers have evolved to no longer being sorted
std::sort(cluster_centers_v.begin(), cluster_centers_v.end()); // recall that raw pointers are also iterators
// set up sorted data
std::vector<size_t> idx = sort_index(data, num_data_points); // idx addresses the original data in sorted order
std::vector<value_type> sorted_data(num_data_points); // copy of data that is sorted
for (unsigned i = 0; i < num_data_points; ++i)
sorted_data[i] = data[idx[i]];
// initialize the cluster boundaries (therefore, assignments) with a E-step, based on existing cluster center values
// the kth boundary element marks the beginning of the kth partition (cluster); e.g. the 0th sorted data point
// trivially marks the beginning of the 0th cluster/partition;
// for convenience, I use an extra boundary at the end (whose position is equal to num_data_point) to mark
// the end of the last cluster
std::vector<size_t> boundaries(num_clusters + 1);
// in kth iter, determine boundary (beginning idx) of k+1th cluster
for (size_t k = 0; k < (num_clusters - 1); k++) {
auto left_center = cluster_centers_v[k];
auto right_center = cluster_centers_v[k + 1];
auto mid = (left_center + right_center) / 2.0;
// search entire data array for correctness
auto mid_iter = lower_bound(sorted_data.begin(), sorted_data.end(), mid);
auto mid_idx = static_cast<unsigned long>(mid_iter - sorted_data.begin()); // guaranteed to be non-negative
boundaries[k + 1] = mid_idx;
}
boundaries[num_clusters] = num_data_points; // important
// update centers/sums based on assignment boundaries
auto cluster_sums = std::vector<prec_type>(num_clusters, 0.0);
std::fill(cluster_centers_v.begin(), cluster_centers_v.end(), 0.0);
for (size_t k = 0; k < num_clusters; ++k) {
size_t beg = boundaries[k], end = boundaries[k + 1];
for (size_t j = beg; j < end; ++j)
cluster_sums[k] += sorted_data[j];
cluster_centers_v[k] = cluster_sums[k] / (end - beg);
}
// assume Euclidean (geometric) distance is used
unsigned t;
const auto sorted_data_iter = sorted_data.begin(); // base iterator
auto new_boundaries = boundaries;
for (t = 0; t < max_iterations; t++) {
bool assignments_changed = false;
// reassign clusters (by redrawing boundaries); E-step
// in the kth iter, redraw the boundary (beginning) of the (k+1)th partition
for (size_t k = 0; k < (num_clusters - 1); k++) {
auto left_center = cluster_centers_v[k];
auto right_center = cluster_centers_v[k + 1];
size_t left_bound = boundaries[k]; // beginning of the kth cluster
size_t right_bound = boundaries[k + 2]; // beginning of the (k+2)th cluster (one past the end of (k+1)th)
// points lying in between left_center and right_center belongs to whichever is closer;
// simply find the mid-point, and assign points in [left_center, mid) to cluster k, and
// points in [mid, right_center) cluster k+1, i.e. the mid point marks the beginning of the (k+1)th
// cluster; note there's no need to adjust points either to the left of the smallest center or to the
// right of the largest center
auto mid = (left_center + right_center) / 2.0;
// binary-search between left_bound and right_bound for efficiency
auto mid_iter = lower_bound(sorted_data_iter + left_bound, sorted_data_iter + right_bound, mid);
auto mid_idx = static_cast<unsigned long>(mid_iter - sorted_data_iter); // guaranteed to be non-negative
if (boundaries[k + 1] != mid_idx) {
new_boundaries[k + 1] = mid_idx;
assignments_changed = true;
}
}
if (!assignments_changed) // converged; more iterations won't help
break;
// M-step
// update cluster sums based on changes in partitioning
for (size_t k = 0; k < num_clusters - 1; ++k) {
size_t prev_end = boundaries[k + 1], new_end = new_boundaries[k + 1];
value_type inc_sum; // how much the kth cluster expanded (and how much the (k+1)th shrunk)
if (new_end > prev_end) {
inc_sum = std::accumulate(sorted_data_iter + prev_end, sorted_data_iter + new_end, 0.0);
} else { // note the negative sign
inc_sum = -std::accumulate(sorted_data_iter + new_end, sorted_data_iter + prev_end, 0.0);
}
cluster_sums[k] += inc_sum;
cluster_sums[k + 1] -= inc_sum;
}
// update cluster centers
for (size_t k = 0; k < num_clusters; ++k) {
size_t cluster_size = new_boundaries[k + 1] - new_boundaries[k];
cluster_centers_v[k] = cluster_sums[k] / cluster_size;
}
boundaries = new_boundaries;
}
// map the partitioning scheme back to cluster_assignments
for (size_t k = 0; k < num_clusters; ++k) {
size_t beg = boundaries[k], end = boundaries[k + 1];
for (size_t j = beg; j < end; ++j)
cluster_assignments[idx[j]] = static_cast<asm_type>(k);
}
// copy to original cluster_centers
std::copy(cluster_centers_v.begin(), cluster_centers_v.end(), cluster_centers);
return t;
}
| true |
584013bc1ccfee6c9c3154125ca6de6a9800f6ff | C++ | lilinhan/code | /c++11/for_each5.cpp | UTF-8 | 603 | 2.875 | 3 | [] | no_license | /*************************************************************************
> File Name: for_each5.cpp
> Author: lewin
> Mail: lilinhan1303@gmail.com
> Company: Xiyou Linux Group
> Created Time: Mon 16 Nov 2015 13:33:16 CST
************************************************************************/
#include<iostream>
#include<string>
#include<cstdlib>
#include<cerrno>
#include<vector>
int main( int argc , char * argv[] ) {
std::vector<int> arr = {1, 2, 3, 4, 5};
for(auto val : arr) {
std::cout << val << std::endl;
arr.push_back(0);
}
return EXIT_SUCCESS;
}
| true |
9f242016152a210fcb26c430041185a402dbfa46 | C++ | vshcryabets/AndroidFTDI | /arduino/DigitalVoltmeter/DigitalVoltmeter.ino | UTF-8 | 940 | 2.828125 | 3 | [] | no_license | //electronicsblog.net
//http://www.electronicsblog.net/digital-voltmeter-arduino-ant-pc-visual-c-comunication-via-serial-port/
//Arduino communication with PC via serial port.
int voltage=0;
int channel =0;
unsigned char incomingByte = 0;
boolean measure=false;
void setup() {
Serial.begin(9600);
}
void loop() {
if (measure) {
voltage=analogRead(channel);
Serial.write(0xAB);
Serial.write(voltage>>8);
Serial.write(voltage & 0xFF);
delay(50);
}
if (Serial.available() > 0) {
delay(10);
if(Serial.read()=='a') {
incomingByte =Serial.read();
switch (incomingByte) {
case 'a':
measure=true;
channel=0;
break;
case 'b':
measure=true;
channel=1;
break;
case 'c':
measure=true;
channel=2;
break;
case 'd':
measure=false;
break;
}
}
}
};
| true |
9737efdd40c541d6028aaf5023d3f1c32b74bb2b | C++ | MIPT-ILab-Compilers/mipt-scheme-compiler | /sources/Frontend/interpreter/activation.hpp | UTF-8 | 683 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | /**
* @file:activation.hpp
* Activation class.
*/
/**
* Copyright 2012 MIPT-COMPILER team
*/
#pragma once
#include "../parser/ast.hpp"
#include <map>
#include <boost/shared_ptr.hpp>
namespace interpreter
{
using parser::ast::Nodep;
using parser::ast::Ident;
using parser::ast::IdentIdType;
class Activation;
typedef boost::shared_ptr<Activation> ActPtr;
class Activation : public std::map<IdentIdType, Nodep>
{
public:
Activation( ActPtr parent);
Activation();
Nodep get( IdentIdType _id);
void add( Ident& ident, Nodep& ptr);
ActPtr getParentPtr();
bool hasParent();
~Activation();
private:
ActPtr parent_activation_ptr;
};
}
| true |
8aaa4169f73492a2e0c3a16ff7d9810e97cdedb0 | C++ | SpintroniK/eXaDrums | /Source/Widgets/TriggerIdAndLocation.h | UTF-8 | 1,147 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* TriggerIdAndLocation.h
*
* Created on: 4 Dec 2016
* Author: jeremy
*/
#ifndef SOURCE_WIDGETS_TRIGGERIDANDLOCATION_H_
#define SOURCE_WIDGETS_TRIGGERIDANDLOCATION_H_
#include <gtkmm/grid.h>
#include <gtkmm/label.h>
#include <gtkmm/comboboxtext.h>
#include <memory>
#include <vector>
#include <string>
namespace Widgets
{
class TriggerIdAndLocation : public Gtk::Grid
{
public:
TriggerIdAndLocation(const std::vector<std::string>& locations, const std::vector<int>& ids);
virtual ~TriggerIdAndLocation() = default;
void SetTriggerLoc(const std::string& t) { location.set_active_text(t); };
void SetTriggerId(const int id) { triggerId.set_active_text(std::to_string(id)); }
std::string GetTriggerLoc() const { return location.get_entry_text(); }
int GetTriggerId() const { return std::stoi(triggerId.get_entry_text()); }
private:
Gtk::Label locationLabel;
Gtk::Label triggerIdLabel;
Gtk::ComboBoxText location;
Gtk::ComboBoxText triggerId;
};
typedef std::shared_ptr<TriggerIdAndLocation> TriggerIdAndLocationPtr;
} /* namespace Widgets */
#endif /* SOURCE_WIDGETS_TRIGGERIDANDLOCATION_H_ */
| true |
c30b88c2076f2b150856de3680064f73c6b03c32 | C++ | RKMVCC-BSc-Comp-Sci-2020-21/Programming-C-Cpp-Sem1 | /March/Swapping of two number using third variable.cpp | UTF-8 | 220 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a=10,b=20,c;
cout<<"Before swapping a="<<a<<" and b="<<b<<"\n";
c=a;
a=b;
b=c;
cout<<"After swapping a="<<a<<" and b="<<b<<"\n";
}
| true |
bd456ee80f132774e57f55e70fb5a1068e895c09 | C++ | thinkrobotics/TUTORIALS | /Four Degrees of Freedom Robotic Arm/4dof_arm.ino | UTF-8 | 1,679 | 2.9375 | 3 | [] | no_license | #include<Servo.h>
Servo s1;
Servo s2;
Servo s3;
Servo s4;
int s1angle = 95;
int s2angle = 80;
int s3angle = 30;
int s4angle = 90;
void ServoControl(Servo k, int startangle, int stopangle, int speedangle)
{
if (startangle < stopangle)
for (int i = startangle; i <= stopangle; i++)
{
k.write(i);
delay(1000 / speedangle);
}
else
for (int i = startangle; i >= stopangle; i--)
{
k.write(i);
delay(1000 / speedangle);
}
k.write(stopangle);
}
void Left()
{
ServoControl(s1, s1angle, 180, 80);
s1angle = 180;
}
void Center()
{
ServoControl(s1, s1angle, 95, 80);
s1angle = 95;
}
void Right()
{
ServoControl(s1, s1angle, 10, 80);
s1angle = 10;
}
void Up()
{
ServoControl(s2, s2angle, 140, 80);
s2angle = 140;
}
void Down()
{
ServoControl(s2, s2angle, 80, 80);
s2angle = 80;
}
void Forw()
{
ServoControl(s3, s3angle, 70, 80);
s3angle = 70;
}
void Back()
{
ServoControl(s3, s3angle, 40, 80);
s3angle = 30;
}
void Open()
{
ServoControl(s4, s4angle, 90, 80);
s4angle = 90;
}
void Close()
{
ServoControl(s4, s4angle, 52, 80);
s4angle = 52;
}
void Init()
{
Center();
Down();
Back();
Open();
delay(1000);
}
void setup()
{
s1.attach(3);
s2.attach(5);
s3.attach(6);
s4.attach(9);
Init();
}
void loop()
{
Left();
delay(500);
Center();
delay(500);
Right();
delay(500);
Center();
delay(500);
Forw();
delay(500);
Back();
delay(500);
Up();
delay(500);
Down();
delay(500);
Close();
delay(500);
Open();
delay(500);
} | true |
52faf81671214137b6a2aad3585eb0cfa3d0b9bc | C++ | jfcaraujo/viage-poupe | /src/comboios.h | UTF-8 | 779 | 2.65625 | 3 | [] | no_license | /*#ifndef _COMBOIOS_H
#define _COMBOIOS_H
#include <string>
#include <vector>
class Comboio {//outras caracteristicas?
protected:
int lotacao;
bool ocupado;//se ja tem uma viagem atribuida
public:
int getlotacao();
virtual string getInformacao();
bool getOcupado();
virtual ~Comboio(){};
};
class AlfaPendular: public Comboio {
public:
AlfaPendular(int lotacao);
string getInformacao();
};
class Intercidades: public Comboio {
public:
Intercidade(int lotacao);
string getInformacao();
};
class Frota{ //Esta classe vai ser usada para mostrar todos os comboios que existem
vector <AlfaPendular *> alfas;
vector <Intercidades *> inters;
public:
void adicionaAlfa(AlfaPendular *a1);
void adicionaInter(Intercidades *I1);
string getInformacao();
};
#endif
*/
| true |
af885d66e11c65cb723e56f61bbafa92196b0430 | C++ | wangli-cn/online-judge-libs | /string/palindrome_partition_II.cc | UTF-8 | 1,423 | 3.421875 | 3 | [] | no_license | //============================================================================
// Palindrome Partitioning II
// Given a string s, partition s such that every substring of the partition¿
// is a palindrome.
//
// Return the minimum cuts needed for a palindrome partitioning of s.
//
// For example, given s = "aab",
// Return 1 since the palindrome partitioning ["aa","b"] could be produced¿
// using 1 cut.
//
//============================================================================
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef vector<vector<bool> > VVB;
typedef vector<bool> VB;
typedef vector<int> VI;
bool go(string s, int i, int j, VVB &dp)
{
if (i == j) return dp[i][j] = true;
else if (i+1 == j) return dp[i][j] = (s[i] == s[j]);
else return dp[i][j] = (go(s, i+1, j-1, dp) && s[i] == s[j]);
}
int run(string s, int i, VI &part, VVB &dp)
{
if (i == 0) return part[i] = -1;
part[i] = run(s, i-1, part, dp) + 1;
for (int j = i-2; j >= 0; j--) {
if (go(s, j, i-1, dp)) {
part[i] = min(part[i], 1 + run(s, j, part, dp));
}
}
return part[i];
}
int min_cut(string s)
{
int n = s.length();
VI part(n+1, 0);
VVB dp(n, vector<bool>(n, false));
int res = run(s, n, part, dp);
return res;
}
int main(void)
{
auto res = min_cut(string("aab"));
cout << res << endl;
return 0;
}
| true |
4161e6fedbef7b278ce2cca8a562ceca9e638d86 | C++ | echoht/leetcodes | /50_myPow.cpp | UTF-8 | 627 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<sstream>
#include<math.h>
using namespace std;
// -100.0 < x < 100.0
//n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
double powImp(double x, long n){
if(n == 0){
return 1;
}
if(n == 1){
return x;
}
double tmp = powImp(x, n/2);
if(n & 1 == 1){
return tmp*tmp*x;
}
return tmp*tmp;
}
double myPow(double x, int n) {
if(n<0){
long l = (long)n*(-1); //这里需要注意有最小负数int*(-1)后大于最大正数int
double tmp = powImp(x,l);
return 1/tmp;
}
return powImp(x, n);
}
| true |
828799937e3bda5969d22a1cae2e6d1c0930a2ec | C++ | JanSpiesZA/SRF02 | /SRF02.ino | UTF-8 | 2,454 | 2.984375 | 3 | [] | no_license | //First experiments in using the SRF02 with SERIAL comms
//Allows distance measurements to be sent via Serial to PC
#define CMD_REAL_RANGE_TX_cm 84
#define CMD_REAL_RANGE_NO_TX_cm 81
#define CMD_GET_RANGE 94
int sendflag = 1;
String readString;
int oldTime = 0;
String serialData = "";
boolean done = false;
int index = 0;
int sensorAddr[] = {3,0,4,1,5,2,6}; //Array used to store the addresses of the SRF02 sensors in the order in which they must be read
//sizeof give the amount of bytes used in the array and not the actual elements. When using int every element is 2 bytes long
// therefore the value must be divided by the siezeof(int) to get the total amount of elements in the array
const int numSensors = sizeof(sensorAddr)/ sizeof(int);
int sensorDist[numSensors];
void setup()
{
Serial.begin(115200);
Serial3.begin(9600); //Comms port for SRF modules
Serial.println("US Interface Started");
delay(1000);
}
void loop()
{
//Lees seriedata tot 'n EOL karakter gekry word
if (Serial.available() >0)
{
char c = Serial.read();
switch(c)
{
case '<': //new command line starts
index = 0;
break;
case '\r':
done = true;
break;
default:
serialData += c; //Add serial data input char to string
break;
}
}
if (done)
{
done = false;
char testChar = serialData.charAt(0);
switch(testChar)
{
case 's':
{
for (int n = 0; n <= numSensors-1; n++)
{
sensorDist[n] = getRange(sensorAddr[n]);
Serial.print(sensorAddr[n]);
Serial.print(':');
Serial.print(sensorDist[n]);
Serial.print('\t');
delay(5);
}
Serial.println();
break;
}
}
serialData = "";
}
//Ping distance to nearest object for each of the sensors
for (int n = 0; n <= numSensors-1; n++)
{
ping(sensorAddr[n]);
delay(10);
}
}
//Ping a sensors without sending the distance data back
void ping(int _sensorAddr)
{
Serial3.write(_sensorAddr);
Serial3.write(CMD_REAL_RANGE_NO_TX_cm);
}
int getRange(int _sensorAddr)
{
Serial3.write(_sensorAddr);
Serial3.write(CMD_GET_RANGE);
while(Serial3.available() < 2); //Wait until 2 bytes received
int rxData = Serial3.read()<<8;
rxData |= Serial3.read();
return rxData;
}
| true |
517ba6d8f1be55b4fd70344f0b5968f27a6769c0 | C++ | darwin/inferno | /src/cgcw/inilib/int_attribute.cc | UTF-8 | 6,380 | 2.796875 | 3 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //
// This software may only be used by you under license from the
// University of Notre Dame. A copy of the University of Notre Dame's
// Source Code Agreement is available at the inilib Internet website
// having the URL: <http://inilib.sourceforge.net/license/> If you
// received this software without first entering into a license with the
// University of Notre Dame, you have an infringing copy of this software
// and cannot use it without violating the University of Notre Dame's
// intellectual property rights.
//
// $Id: int_attribute.cc,v 1.6 2000/09/03 19:47:13 bwbarrett Exp $
//
// FUNCTION: Parse initialization files,
// maintain state of program
// save state of program
#include <string>
#include "int_attribute.h"
#include "ini_functions.h"
// Note: we could have used "using namespace std; using namespace
// INI;" in here, but this file used to be part of a .h file, where
// such things would be a distinct no-no. Hence, just for consistency
// (and because we're lazy and have 6 billion other details to attend
// to), we kept the std:: and INI:: everywhere.
INI::int_attribute::int_attribute(int _value) : value(_value)
{
// Don't need nuttin' here, but the default constructor is necessary
}
// assignment operators for a value that should be stored
// internally as an integer. 4 functions, based on the
// type of the value we are assigning from
INI::attribute&
INI::int_attribute::operator=(int new_value)
{
debug << "*** Entering int_attribute::operator=(int) ***" << std::endl;
value = new_value;
return *this;
}
INI::attribute&
INI::int_attribute::operator=(double new_value)
{
debug << "*** Entering int_attribute::operator=(double) ***"
<< std::endl;
value = (int) new_value;
return *this;
}
INI::attribute&
INI::int_attribute::operator=(const std::string& new_value)
{
debug << "*** Entering int_attribute::operator=(string) ***"
<< std::endl;
value = atoi(new_value.c_str());
return *this;
}
INI::attribute&
INI::int_attribute::operator=(bool new_value)
{
debug << "*** Entering int_attribute::operator=(bool) ***"
<< std::endl;
value = (int) new_value;
return *this;
}
INI::attribute&
INI::int_attribute::operator=(const attribute& new_value)
{
debug << "*** Entering int_attribute::operator=(attribute&) ***"
<< std::endl;
value = (int) new_value;
return *this;
}
// overload the casting operator, so that we can assign the
// int_attribute to an int, float, string, etc. 4 functions,
// based on the type casting to.
INI::int_attribute::operator int() const
{
debug << "*** Entering int_attribute::operator int() ***"
<< std::endl;
return value;
}
INI::int_attribute::operator double() const
{
debug << "*** Entering int_attribute::operator double() ***"
<< std::endl;
return ((double) value);
}
INI::int_attribute::operator std::string() const
{
debug << "*** Entering int_attribute::operator string() ***"
<< std::endl;
return int2str(value);
}
INI::int_attribute::operator bool() const
{
debug << "*** Entering int_attribute::operator bool() ***"
<< std::endl;
return ((bool) (value != 0));
}
INI::attribute&
INI::int_attribute::operator*=(bool a)
{
value = value * (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator*=(double a)
{
value = value * (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator*=(int a)
{
value = value * a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator*=(const std::string& a)
{
value = value * atoi(a.c_str());
return (*this);
}
INI::attribute&
INI::int_attribute::operator*=(const attribute& a)
{
value = value * (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator/=(bool a)
{
value = value * (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator/=(double a)
{
value = value / (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator/=(int a)
{
value = value / a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator/=(const std::string& a)
{
value = value * atoi(a.c_str());
return (*this);
}
INI::attribute&
INI::int_attribute::operator/=(const attribute& a)
{
value = value * (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator%=(bool a)
{
value = value % (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator%=(double a)
{
value = value % (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator%=(int a)
{
value = value % a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator%=(const std::string& a)
{
value = value % atoi(a.c_str());
return (*this);
}
INI::attribute&
INI::int_attribute::operator%=(const attribute& a)
{
value = value % (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator+=(bool a)
{
value = value + (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator+=(double a)
{
value = value + (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator+=(int a)
{
value = value + a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator+=(const std::string& a)
{
value = value + atoi(a.c_str());
return (*this);
}
INI::attribute&
INI::int_attribute::operator+=(const attribute& a)
{
value = value + (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator-=(bool a)
{
value = value - (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator-=(double a)
{
value = value - (int) a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator-=(int a)
{
value = value - a;
return (*this);
}
INI::attribute&
INI::int_attribute::operator-=(const std::string& a)
{
value = value - atoi(a.c_str());
return (*this);
}
INI::attribute&
INI::int_attribute::operator-=(const attribute& a)
{
value = value - (int) a;
return (*this);
}
// ++, -- use (double) 1
// Prefix operators
INI::attribute&
INI::int_attribute::operator++()
{
++value;
return (*this);
}
INI::attribute&
INI::int_attribute::operator--()
{
--value;
return (*this);
}
INI::attr_type
INI::int_attribute::get_type() const
{
return INT;
}
INI::attribute*
INI::int_attribute::make_copy() const
{
return new int_attribute(value);
}
| true |
1a75b6aeb6b0c8ced8edd24b4dd21b08e3fe0c9b | C++ | a930736/c-object-oriented-programming | /ex05.cpp | UTF-8 | 1,249 | 3.5625 | 4 | [] | no_license | //
// main.cpp
// ex04
//
// Created by Peter on 2021/1/5.
// Copyright © 2021 Peter. All rights reserved.
//
//類別與結構實作
#include <iostream>
#include <cstdlib>
using namespace std;
struct Data
{
char name[10];
int height;
};
class Date
{
private:
int year;
int month;
int day;
public:
void setDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
int getYear(){
return year;
}
int getMonth(){
return month;
}
int getDay(){
return day;
}
};
class Person
{
private:
Date birthday;
Data data;
public:
void setAllData(Date d1, Data d2) {
birthday.setDate(d1.getYear(), d1.getMonth(), d1.getDay());
strcpy(data.name,d2.name);
data.height = d2.height;
}
void printAllData(){
cout<<"Name: " <<data.name<<endl;
cout<<"Height: "<<data.height <<endl;
cout<<"Birthday: "<<birthday.getYear()<<","<<birthday.getMonth()<<","<<birthday.getDay()<<endl;
}
};
int main(){
Date d1;
d1.setDate(1999, 3, 6);
Data d2;
d2.height = 175;
strcpy(d2.name,"Eric");
Person p;
p.setAllData(d1,d2);
p.printAllData();
return 0;
}
| true |
fe27f89fbea17d8cff2addc41f7117227a8f5c47 | C++ | nWhitcome/Wireless-MIDI | /Server/final_server.cpp | UTF-8 | 3,816 | 2.703125 | 3 | [] | no_license | #include <io.h>
#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include <mmsystem.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define DEFAULT_BUFLEN 512
void RemoveChars(char *s, char c);
char* concat(const char *s1, const char *s2);
char* swapChars(char * input);
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char *finalMessage;
char *finalMessage2;
int iResult;
char recvbuf[DEFAULT_BUFLEN + 1];
int recvbuflen = DEFAULT_BUFLEN + 1;
unsigned long result;
HMIDIOUT outHandle;
MIDIOUTCAPS moc;
//Standard Windows socket startup
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//Check for client connections
while( (new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET )
{
puts("Connection accepted");
//Get the third MIDI output, which happens to be the loopMIDI output on my computer. May need modification on another system.
if (!midiOutGetDevCaps(3, &moc, sizeof(MIDIOUTCAPS)))
{
/* Display its Device ID and name */
printf("%s\r\n", moc.szPname);
result = midiOutOpen(&outHandle, 3, 0, 0, CALLBACK_WINDOW);
if (result)
{
printf("There was an error opening MIDI Mapper!\r\n");
}
do {
//Receive the data from the socket and put it into a buffer
iResult = recv(new_socket, recvbuf, recvbuflen, 0);
if ( iResult > 0 ){
recvbuf[iResult] = '\0';
//Modify the input so that it is in a proper format to be sent to the MIDI output
RemoveChars(recvbuf, ' ');
finalMessage = concat("0x00", swapChars(recvbuf));
int number = (int)strtol(finalMessage, NULL, 0);
if(!result){
midiOutShortMsg(outHandle, number);
}
}
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while( iResult > 0 );
midiOutClose(outHandle);
}
}
//Exit if the socket is invalid
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
//Re-order the MIDI message to the proper format for the Windows MIDI output
char* swapChars(char * input){
char *returned = (char *)malloc(strlen(input) + 1);
size_t len = strlen(input);
memcpy(returned, &input[4], 2);
memcpy(&returned[2], &input[2], 2);
memcpy(&returned[4], &input[0], 2);
return returned;
}
//Remove specific characters from a string
void RemoveChars(char *s, char c)
{
int writer = 0, reader = 0;
while (s[reader])
{
if (s[reader]!=c)
{
s[writer++] = s[reader];
}
reader++;
}
s[writer]=0;
}
//Custom concat function for strings
char* concat(const char *s1, const char *s2)
{
char *result = (char *)malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
strcpy(result, s1);
strcat(result, s2);
return result;
} | true |
029a2e9f0c4979bc2805cd577fde807d470bccc3 | C++ | Farrius/cp | /codeforces/edu_forces/segment_tree/chap2/b.cpp | UTF-8 | 1,448 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
struct segtree {
int sz = 1;
vector<int> seg;
void init (int n) {
while (sz < n) sz *= 2;
seg.assign(sz * 2, 0);
}
void build (vector<int>& ar, int x, int lx, int rx) {
if (rx - lx == 1) {
if (lx < (int) ar.size()) {
seg[x] = ar[lx];
}
return;
}
int m = (lx + rx)/2;
build(ar, 2 * x + 1, lx, m);
build(ar, 2 * x + 2, m, rx);
seg[x] = seg[2 * x + 1] + seg[2 * x + 2];
}
void set (int i, int x, int lx, int rx) {
if (rx - lx == 1) {
seg[x] ^= 1;
return;
}
int m = (lx + rx)/2;
if (i < m) {
set(i, 2 * x + 1, lx, m);
} else {
set(i, 2 * x + 2, m, rx);
}
seg[x] = seg[2 * x + 1] + seg[2 * x + 2];
}
void set (int i) {
set(i, 0, 0, sz);
}
int pos (int k, int x, int lx, int rx) {
if (rx - lx == 1) {
return lx;
}
int m = (lx + rx)/2;
if (k <= seg[2 * x + 1]) {
return pos(k, 2 * x + 1, lx, m);
} else {
return pos(k - seg[2 * x + 1], 2 * x + 2, m, rx);
}
}
int pos (int k) {
return pos(k, 0, 0, sz);
}
void build (vector<int>& ar) {
build(ar, 0, 0, sz);
}
};
int main () {
int n, m;
cin >> n >> m;
vector<int> ar(n);
for (int i = 0; i < n; i++) {
cin >> ar[i];
}
segtree st;
st.init(n);
st.build(ar);
while (m--) {
int type, k;
cin >> type >> k;
if (type == 1) {
st.set(k);
} else {
k++;
cout << st.pos(k) << '\n';
}
}
}
| true |
bcbe098603656795c17419925b94839d9b09ed59 | C++ | Diptendu28/myCprogram | /pattern 34.cpp | UTF-8 | 315 | 2.8125 | 3 | [] | no_license | /* *********
**** ****
*** ***
** **
* * */
#include<stdio.h>
int main()
{
int i,j,k,s,p=1;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf("*");
}
for(k=1;k<=2*p-3;k++)
{
printf(" ");
}
for(s=i;s>=1;s--)
{
if(s<5)
printf("*");
}
printf("\n");
p++;
}
}
| true |
35acb49ce54f60cfbc6f2abb303fd9f165e42507 | C++ | jamillosantos/mote-vision | /src/data/colour.h | UTF-8 | 2,410 | 3.265625 | 3 | [
"MIT"
] | permissive | /**
* @author J. Santos <jamillo@gmail.com>
* @date July 24, 2016
*/
#ifndef MOTE_VISION_COLOUR_H
#define MOTE_VISION_COLOUR_H
#include <cstdint>
#include "serializable.h"
#include "pixel.h"
namespace mote
{
namespace data
{
/**
* Colour abstrction on the system.
*/
class Colour
: public Serializable
{ };
/**
* RGB Colour definition.
*/
struct RGBColour
: public Colour
{
public:
static RGBColour red;
static RGBColour blue;
static RGBColour green;
static RGBColour white;
static RGBColour black;
static RGBColour yellow;
static mote::data::RGBColour cyan;
static mote::data::RGBColour magenta;
private:
mote::data::Pixel* _pixel;
bool _ownsPixel;
public:
RGBColour(uint8_t r, uint8_t g, uint8_t b);
RGBColour(mote::data::Pixel *pixel);
RGBColour(const RGBColour& colour);
RGBColour();
virtual ~RGBColour();
mote::data::Pixel* pixel();
mote::data::Pixel* pixel() const;
RGBColour& pixel(mote::data::Pixel* pixel, bool own=false);
bool ownsPixel() const;
/**
* Intensity of the colour (average).
*
* @return
*/
virtual double intensity();
/**
* Replaces the channel value only if the equivalent channel of the `colour` param passed is greater than the
* current value.
*
* @param colour Colour that will be used for comparision.
* @return This instance of the colour.
*/
virtual RGBColour& minimum(const RGBColour& colour);
/**
* Replaces the channel value only if the equivalent channel of the `colour` param passed is smaller than the
* current value.
*
* @param colour Colour that will be used for comparision.
* @return This instance of the colour.
*/
virtual RGBColour& maximum(const RGBColour& colour);
RGBColour& operator=(const RGBColour& colour);
virtual bool operator==(const RGBColour& colour) const;
virtual bool operator!=(const RGBColour& colour) const;
RGBColour operator+(const RGBColour& colour);
RGBColour operator-(const RGBColour& colour);
RGBColour operator*(const RGBColour& colour);
RGBColour operator/(const RGBColour& colour);
virtual RGBColour &operator+=(const RGBColour& colour);
virtual RGBColour &operator-=(const RGBColour& colour);
virtual RGBColour &operator*=(const RGBColour& colour);
virtual RGBColour &operator/=(const RGBColour& colour);
virtual void fromJson(const Json::Value &json) override;
virtual void toJson(Json::Value &json) const override;
};
}
}
#endif //MOTE_VISION_COLOUR_H
| true |
ed00eb11af1f702362ac74e858a3a81d63a6c7bd | C++ | svalenciasan/IdealGasSimulator | /include/visualizer/histogram.h | UTF-8 | 1,462 | 2.578125 | 3 | [] | no_license | #pragma once
#include "cinder/gl/gl.h"
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "core/particle.h"
#include "core/particle_manager.h"
#include <vector>
#include <map>
using std::string;
using std::vector;
using std::map;
using glm::vec2;
using idealgas::particle::Particle;
using idealgas::particlemanager::ParticleManager;
namespace idealgas {
namespace visualizer {
class Histogram {
public:
Histogram() = default;
Histogram(const vec2& top_left_corner, const vec2& bottom_right_corner, size_t num_of_rectangles);
void Update(const ParticleManager& particleManager, string color);
void Draw();
void DrawAxisLabels();
void AddParticle(Particle& particle);
size_t GetNumberInRange(float greater_than, float less_than);
private:
vector<Particle> particles_;
string color_ = "black";
/**
* Position of Histogram.
*/
const vec2 kTopLeftCorner;
const vec2 kBottomRightCorner;
/**
* Margin from the bounds of the histogram and the actual graph
*/
const float kMargin = 20;
/**
* How many rectangles are used to display the data.
*/
size_t num_of_rectangles_;
/**
* Width of each rectangle used to display the data.
*/
float rectangle_width_;
/**
* The range of every rectangle partition.
* The highest value/number of rectangles.
*/
float partitions_ = 0;
float highest_vel_ = 0;
float lowest_vel_ = 0;
};
}//namespace particle
}//namespace idealgas | true |
e955b66a5eec37b5d65a9f79d7290f18ec22e407 | C++ | NamKim-il/BOJ-list | /Solved/11438.cpp | UTF-8 | 1,315 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef struct nod{
int parent;
int height;
}node;
bool check[200005];
vector< pair<vector<int>,node>> n(200005);
int bfs()
{
queue<int> qu;
int ind;
qu.push(1);
check[1]=true;
while(!qu.empty())
{
ind=qu.front();
qu.pop();
auto iter=n[ind].first.begin();
while(iter<n[ind].first.end()) {
if(!check[*iter]){
qu.push(*iter);
n[*iter].second.parent=ind;
n[*iter].second.height=n[ind].second.height+1;
check[*iter]=true;
}
iter++;
}
}
}
int ans(int a,int b)
{
while(n[a].second.height>n[b].second.height) a=n[a].second.parent;
while(n[a].second.height<n[b].second.height) b=n[b].second.parent;
while(a!=b)
{
if(a>1) a=n[a].second.parent;
if(b>1) b=n[b].second.parent;
}
return a;
}
int main()
{
cin.tie(NULL);
ios::sync_with_stdio(false);
int N,M,i,a,b;
cin>>N;
n[1].second.parent=1;
n[1].second.height=1;
for(i=0;i<N-1;i++)
{
cin>>a>>b;
n[a].first.push_back(b);
n[b].first.push_back(a);
}
bfs();
cin>>M;
for(i=0;i<M;i++)
{
cin>>a>>b;
cout<<ans(a,b)<<"\n";
}
}
| true |
9e684a6760ca785d20e00d074aaf11a1892c6984 | C++ | adamk33n3r/Icarus | /Engine-Core/src/maths/Vector3.cpp | UTF-8 | 2,640 | 3.375 | 3 | [] | no_license | #include "Vector3.h"
namespace icarus {
namespace maths {
const Vector3 Vector3::up = Vector3(0, 1, 0);
const Vector3 Vector3::down = Vector3(0, -1, 0);
const Vector3 Vector3::left = Vector3(-1, 0, 0);
const Vector3 Vector3::right = Vector3(1, 0, 0);
const Vector3 Vector3::forward = Vector3(0, 0, 1);
const Vector3 Vector3::back = Vector3(0, 0, -1);
const Vector3 Vector3::zero = Vector3(0, 0, 0);
const Vector3 Vector3::one = Vector3(1, 1, 1);
Vector3::Vector3()
: x(0.0f), y(0.0f), z(0.0f)
{
}
Vector3::Vector3(const float& x, const float& y, const float& z)
: x(x), y(y), z(z)
{
}
Vector3 Vector3::Add(const Vector3& other) const
{
return Vector3(x + other.x, y + other.y, z + other.z);
}
Vector3 Vector3::Subtract(const Vector3& other) const
{
return Vector3(x - other.x, y - other.y, z - other.z);
}
Vector3 Vector3::Multiply(const Vector3& other) const
{
return Vector3(x * other.x, y * other.y, z * other.z);
}
Vector3 Vector3::Multiply(const float& scalar) const
{
return Vector3(x * scalar, y * scalar, z * scalar);
}
Vector3 Vector3::Divide(const Vector3& other) const
{
return Vector3(x / other.x, y / other.y, z / other.z);
}
Vector3 Vector3::Divide(const float& scalar) const
{
return Vector3(x / scalar, y / scalar, z / scalar);
}
Vector3 operator+(const Vector3& left, const Vector3& right)
{
return left.Add(right);
}
Vector3 operator-(const Vector3& left, const Vector3& right)
{
return left.Subtract(right);
}
Vector3 operator*(const Vector3& left, const Vector3& right)
{
return left.Multiply(right);
}
Vector3 operator*(const Vector3& vec, const float& scalar)
{
return vec.Multiply(scalar);
}
Vector3 operator/(const Vector3& left, const Vector3& right)
{
return left.Divide(right);
}
Vector3 operator/(const Vector3& vec, const float& scalar)
{
return vec.Divide(scalar);
}
Vector3 operator*=(Vector3& vec, const float& scalar)
{
vec.x *= scalar;
vec.y *= scalar;
vec.z *= scalar;
return vec;
}
Vector3 operator/=(Vector3& vec, const float& scalar)
{
vec.x /= scalar;
vec.y /= scalar;
vec.z /= scalar;
return vec;
}
bool operator==(const Vector3& left, const Vector3& right)
{
return left.x == right.x && left.y == right.y && left.z == right.z;
}
bool operator!=(const Vector3& left, const Vector3& right)
{
return !(left == right);
}
std::ostream& operator<<(std::ostream& os, const Vector3& vec)
{
os << "Vector3(" << vec.x << ", " << vec.y << ", " << vec.z << ")";
return os;
}
}
}
| true |
aabf9f908664e925dbcb2d7932b6441e815522ca | C++ | OZoneSQT/Data-Structures-and-Algorithms | /BuildTree/BuildTree.cpp | UTF-8 | 3,294 | 4.0625 | 4 | [] | no_license | // BuildTree.cpp : Defines the entry point for the console application.
//
/* program to construct tree using inorder and preorder traversals */
#include <ostream>
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
char data;
struct node* left;
struct node* right;
};
// Prototypes for utility functions
int search(char arr[], int strt, int end, char value);
struct node* newNode(char data);
char getData(node* node)
{
if (node == NULL) return ' ';
else return node->data;
}
/* Recursive function to construct binary of size len from
Inorder traversal in[] and Preorder traversal pre[]. Initial values
of inStrt and inEnd should be 0 and len -1. The function doesn't
do any error checking for cases where inorder and preorder
do not form a tree */
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
static int preIndex = 0;
if (inStrt > inEnd)
{
return NULL;
}
/* Pick current node from Preorder traversal using preIndex
and increment preIndex */
node *tNode = newNode(pre[preIndex++]);
// If this node has no children then return
if (inStrt == inEnd)
{
return tNode;
}
/* Else find the index of this node in Inorder traversal */
int inIndex = search(in, inStrt, inEnd, tNode->data);
/* Using index in Inorder traversal, construct left and
right subtress */
tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
printf(" - %c - \n%c %c\n", tNode->data, getData(tNode->left), getData(tNode->right) );
return tNode;
}
// UTILITY FUNCTIONS
/* Function to find index of value in arr[start...end]
The function assumes that value is present in in[] */
int search(char arr[], int strt, int end, char value)
{
for (int i = strt; i <= end; i++)
{
if (arr[i] == value)
return i;
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(char data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* This funtcion is here just to test buildTree() */
void printInorder(node* node)
{
if (node == NULL)
return;
// first recur on left child
printInorder(node->left);
// then print the data of node
printf("%c ", node->data);
// now recur on right child
printInorder(node->right);
}
// Driver program to test above functions
int main()
{
printf("Hello World!\n");
/* Inorder: E O N F K L J C A I N H D G B
Preorder: H O E C L F N K J I A N G D B */
char in[15] = { 'E', 'O', 'M', 'F', 'K', 'L', 'J', 'C', 'A', 'I', 'N', 'H', 'D', 'G', 'B' };
char pre[15] = { 'H', 'O', 'E', 'C', 'L', 'F', 'M', 'K', 'J', 'I', 'A', 'N', 'G', 'D', 'B' };
int len = sizeof(in) / sizeof(in[0]);
node *root = buildTree(in, pre, 0, len - 1);
// Let us test the built tree by printing Insorder traversal
printf("\nInorder traversal of the constructed tree is: \n");
printInorder(root);
printf("\n\nHit any key to terminate.");
getchar();
return 0;
}
/*
char in[] = { 'S', 'A', 'E', 'U', 'Y', 'Q', 'R', 'P', 'D', 'F', 'K', 'L', 'M' };
char pre[] = { 'F', 'A', 'S', 'Q', 'Y', 'E', 'U', 'P', 'R', 'D', 'K', 'L', 'M' };
*/ | true |
6449ae8802a2fc396f345c1973836e3f8148b42f | C++ | EndoYuuki/GraphNN | /test/graphnn_classifier_test.cpp | UTF-8 | 2,669 | 2.640625 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <Eigen/Core>
#include "GraphNNClassifier.hpp"
#include "DatasetManager.hpp"
#include "GraphNNLearnableParameter.hpp"
#include "FileGraphGenerator.hpp"
class GraphNNClassifierTest : public ::testing::Test {
protected:
GraphNNClassifierTest() :
classifier(2)
{}
GraphNNClassifier classifier;
};
TEST_F(GraphNNClassifierTest, NormalTest) {
GraphNNLearnableParameter parameter(Eigen::MatrixXd::Constant(4,4,1.0), 1.0, Eigen::VectorXd::Constant(4, 0.01));
Data data1(FileGraphGenerator("../../test_data.dat", 4), false);
// graphNN readout result is [68,68,68,68]^T
// 68*4*0.01 + 1 = 3.72
// log(1.0 + exp(3.72)) ≒ 3.74394498474
EXPECT_NEAR(3.74394498474, classifier.Loss(data1, parameter), 10e-10);
EXPECT_NEAR(3.74394498474, classifier.Loss(data1, parameter), 10e-10);
EXPECT_NEAR(3.74394498474, classifier.Loss(data1, parameter), 10e-10);
Data data2(FileGraphGenerator("../../test_data.dat", 4), true);
// graphNN readout result is [68,68,68,68]^T
// 68*4*0.01 + 1 = 3.72
// log(1.0 + exp(-3.72)) ≒ 0.02394498474
EXPECT_NEAR(0.02394498474, classifier.Loss(data2, parameter), 10e-10);
EXPECT_NEAR(0.02394498474, classifier.Loss(data2, parameter), 10e-10);
EXPECT_NEAR(0.02394498474, classifier.Loss(data2, parameter), 10e-10);
}
TEST_F(GraphNNClassifierTest, OverflowTest) {
GraphNNLearnableParameter parameter1(Eigen::MatrixXd::Constant(4,4,1.0), 1.0, Eigen::VectorXd::Constant(4, 2.0));
Data data1(FileGraphGenerator("../../test_data.dat", 4), false);
// graphNN readout result is [68,68,68,68]^T
// 68*2*4 + 1 = 545
// log(1.0 + exp(545)) ≒ 545
double loss1 = classifier.Loss(data1, parameter1);
EXPECT_FALSE(loss1 != loss1);
EXPECT_NEAR(545, classifier.Loss(data1, parameter1), 10e-20);
Data data2(FileGraphGenerator("../../test_data.dat", 4), true);
// graphNN readout result is [68,68,68,68]^T
// 68*2*4 + 1 = 545
// log(1.0 + exp(-545)) ≒ 0
EXPECT_NEAR(0, classifier.Loss(data2, parameter1), 10e-20);
GraphNNLearnableParameter parameter2(Eigen::MatrixXd::Constant(4,4,1.0), 1.0, Eigen::VectorXd::Constant(4, -2.0));
// graphNN readout result is [68,68,68,68]^T
// -68*2*4 + 1 = -543
// log(1.0 + exp(-543)) ≒ 0
EXPECT_NEAR(0, classifier.Loss(data1, parameter2), 10e-20);
// graphNN readout result is [68,68,68,68]^T
// -68*2*4 + 1 = -543
// log(1.0 + exp(543)) ≒ 543
double loss2 = classifier.Loss(data2, parameter2);
EXPECT_FALSE(loss2 != loss2);
EXPECT_NEAR(543, classifier.Loss(data2, parameter2), 10e-20);
} | true |
e2700e26fadc810e99d43f61e8ff2aa33ead5b52 | C++ | oriariel/binarytree-a | /Test.cpp | UTF-8 | 1,024 | 2.921875 | 3 | [] | no_license | #include "doctest.h"
#include "BinaryTree.hpp"
TEST_CASE("FIRST TEST"){
ariel::BinaryTree<int> tree;
CHECK_NOTHROW(tree.add_root(0));
CHECK_NOTHROW(tree.add_root(1));
CHECK_NOTHROW(tree.add_root(2));
CHECK_NOTHROW(tree.add_root(-3));
CHECK_NOTHROW(tree.add_root(10000));
CHECK_NOTHROW(tree.add_root(-5));
CHECK_THROWS(tree.add_right(102,30));
CHECK_THROWS(tree.add_right(14,50));
CHECK_THROWS(tree.add_left(10,4));
CHECK_THROWS(tree.add_left(12,13));
}
TEST_CASE("SECOND TEST"){
ariel::BinaryTree<int> second_tree;
CHECK_NOTHROW(second_tree.add_root(0));
CHECK_NOTHROW(second_tree.add_root(1));
CHECK_NOTHROW(second_tree.add_root(2));
CHECK_NOTHROW(second_tree.add_root(-3));
CHECK_NOTHROW(second_tree.add_root(10000));
CHECK_NOTHROW(second_tree.add_root(-5));
CHECK_THROWS(second_tree.add_right(7,8));
CHECK_THROWS(second_tree.add_right(9,55));
CHECK_NOTHROW(second_tree.add_right(2,30));
CHECK_THROWS(second_tree.add_left(10,4));
CHECK_THROWS(second_tree.add_left(12,13));
CHECK_NOTHROW(second_tree.add_left(0,13));
}
| true |
5787dfd0c0304a88c40d591e4454d2bc2e73f378 | C++ | Mat-Arnold/Flight-Computer-v01 | /Teensy_KalmanFilter/src/quatFunctions.cpp | UTF-8 | 3,490 | 2.984375 | 3 | [] | no_license | // Functions to be used to manipulate or convert quaternions for Kalman filter
#include <Eigen.h>
#include <Eigen/Dense>
#include "quatFunctions.h"
#include <cmath>
Matrix3d rotFromQuat(const Vector4d& lam)
{
//build output matrix
Matrix3d output;
output << (pow(lam(0),2) + pow(lam(1),2) - 0.5), (lam(1) * lam(2) - lam(0) * lam(3)), (lam(1) * lam(3) + lam(0) * lam(2)),
(lam(1) * lam(2) + lam(0) * lam(3)), (pow(lam(0),2) + pow(lam(2),2) - 0.5), (lam(2) * lam(3) - lam(0) * lam(1)),
(lam(1) * lam(3) - lam(0) * lam(2)), (lam(2) * lam(3) + lam(0) * lam(1)), (pow(lam(0),2) + pow(lam(3),2) - 0.5);
return output * 2;
}
Vector4d Euler2Quat(const Vector3d& EulerVector)
{
// its convenient to split out the components
double phi{EulerVector(0)};
double theta{EulerVector(1)};
double psi{EulerVector(2)};
// initialize the output quaternion
Vector4d lam = Vector4d::Zero();
// Build the Euler rotation matrix
Matrix3d T;
T << (cos(theta)*cos(psi)), (-cos(phi)*sin(psi)+sin(phi)*sin(theta)*cos(psi)), (sin(phi)*sin(psi)+cos(phi)*sin(theta)*cos(psi)),
(cos(theta)*sin(psi)), (cos(phi)*cos(psi)+sin(phi)*sin(theta)*sin(psi)), (-sin(phi)*cos(psi)+cos(phi)*sin(theta)*sin(psi)),
(-sin(theta)), (sin(phi)*cos(theta)), (cos(phi)*cos(theta));
// Get the max diagonal value and it's location
int maxIndex{};
double maxValue{};
maxValue = T.diagonal().maxCoeff(&maxIndex); // a weird eigen function but it puts the index into maxIndex
int set{};
if (T.trace() >= maxValue)
{
set = 0;
}
else
{
set = maxIndex + 1;
}
// thus 0 for lam0 dominant, 1 for lam1 dominant etc.
switch (set)
{
case 0:
lam(0) = 0.5 * sqrt((1 + T.trace()));
lam(1) = (1/(4*lam(0)))*(T(2,1) - T(1,2));
lam(2) = (1/(4*lam(0)))*(T(0,2) - T(2,0));
lam(3) = (1/(4*lam(0)))*(T(1,0) - T(0,1));
break;
case 1:
lam(1) = 0.5 * sqrt((1 + 2*T(0,0) - T.trace()));
lam(0) = (1/(4*lam(1)))*(T(2,1) - T(1,2));
lam(2) = (1/(4*lam(1)))*(T(0,1) - T(1,0));
lam(3) = (1/(4*lam(1)))*(T(0,2) - T(2,0));
break;
case 2:
lam(2) = 0.5 * sqrt((1 + 2*T(1,1) - T.trace()));
lam(0) = (1/(4*lam(2)))*(T(0,2) - T(2,0));
lam(1) = (1/(4*lam(2)))*(T(0,1) - T(1,0));
lam(3) = (1/(4*lam(2)))*(T(1,2) - T(2,1));
break;
case 3:
lam(3) = 0.5 * sqrt((1 + 2*T(2,2) - T.trace()));
lam(0) = (1/(4*lam(3)))*(T(1,0) - T(0,1));
lam(1) = (1/(4*lam(3)))*(T(0,2) - T(2,0));
lam(2) = (1/(4*lam(3)))*(T(1,2) - T(2,1));
break;
default:
lam(0) = 0.5 * sqrt((1 + T.trace()));
lam(1) = (1/(4*lam(0)))*(T(2,1) - T(1,2));
lam(2) = (1/(4*lam(0)))*(T(0,2) - T(2,0));
lam(3) = (1/(4*lam(0)))*(T(1,0) - T(0,1));
break;
}
if (lam(0) < 0)
{
lam = -1 * lam;
}
return lam;
}
Vector3d Quat2Euler(const Vector4d& lam)
{
Vector3d EulerVector = Vector3d::Zero();
EulerVector(0) = atan2((2*(lam(2)*lam(3) + lam(0) * lam(1))),pow(lam(0),2) - pow(lam(1),2) - pow(lam(2),2) + pow(lam(3),2));
EulerVector(1)= asin(2*(lam(0)*lam(2) - lam(1)*lam(3)));
EulerVector(2) = atan2(2*(lam(1)*lam(2) + lam(0)*lam(3)), pow(lam(0),2) + pow(lam(1),2) - pow(lam(2),2) - pow(lam(3),2));
return EulerVector;
} | true |
e55d64129af1fd4565058f3347b3f016f11265f5 | C++ | andyspb/cpp-test | /src/algoritms/find_sum_overlapping_intervals.h | UTF-8 | 1,828 | 3.234375 | 3 | [] | no_license | /*
* find_sum_overlapping_intervals.h
*
* Created on: 30 ���. 2015 �.
* Author: andy
*/
#ifndef FIND_SUM_OVERLAPPING_INTERVALS_H_
#define FIND_SUM_OVERLAPPING_INTERVALS_H_
#include <algorithm>
#include <iostream>
#include <stack>
namespace find_sum_overlapping_intervals {
struct Interval {
Interval(int s, int e)
: start(s),
end(e) {
}
;
int start;
int end;
int getLength() {
if (end <= start) {
return 0;
}
return (end - start - 1);
}
};
struct {
bool operator()(Interval a, Interval b) {
return a.start < b.start;
}
} IntervalLess;
void printIntervals(std::vector<Interval>& v) {
std::for_each(v.begin(), v.end(), [](Interval &i) {std::cout<< "["
<< i.start << "," << i.end << "] ";});
std::cout << std::endl;
}
int find_sum_of_intervals_with_stack(std::vector<Interval>& vector_intervals) {
if (vector_intervals.empty()) {
return 0;
}
std::sort(vector_intervals.begin(), vector_intervals.end(), IntervalLess);
printIntervals(vector_intervals);
// int start(0), end(0);
int l = 0;
std::stack<Interval> stack;
stack.push(vector_intervals[0]);
for (size_t i = 0; i < vector_intervals.size(); ++i) {
Interval top = stack.top();
if (top.end < vector_intervals[i].start) {
stack.push(vector_intervals[i]);
} else if (top.end < vector_intervals[i].end) {
top.end = vector_intervals[i].end;
stack.pop();
stack.push(top);
}
}
// Print contents of stack
std::cout << "\n The Merged Intervals are: ";
while (!stack.empty()) {
Interval t = stack.top();
std::cout << "[" << t.start << "," << t.end << "]" << " ";
stack.pop();
l += t.end - t.start;
}
return l;
}
} // namespace find_sum_overlapping_intervals
#endif /* FIND_SUM_OVERLAPPING_INTERVALS_H_ */
| true |
8733cfe9df8b57e859e2d8731aa57e839223dad1 | C++ | SMiles02/CompetitiveProgramming | /Codeforces/CF 500 - 599/CF0527/CF527/CF527A.cpp | UTF-8 | 498 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int index(int numToFind, std::vector<int> vectorToFindIn) {int len = vectorToFindIn.size();for (int i = 0; i < len; i++){if (vectorToFindIn[i] == numToFind){return i;}}return -1;}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
ll a,b,ans;
cin>>a>>b;
ans=0;
while (a>0&&b>0)
{
if (a>=b)
{
ans+=floor(a/b);
a%=b;
}
else
{
ans+=floor(b/a);
b%=a;
}
}
cout<<ans;
return 0;
} | true |
38427d478615b7a10c8594e39b8eef1f89ff86cc | C++ | TomWang10/LeetCode | /22_Generate_Parenttheses.cc | UTF-8 | 712 | 3.75 | 4 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
Helper(result, "", 0, 0, n);
return result;
}
void Helper(vector<string>& result, string curr, int open, int close, int max) {
if (curr.size() == max * 2) {
result.emplace_back(curr);
return;
}
if (open < max) {
Helper(result, curr + "(", open+1, close, max);
}
if (close < open) {
Helper(result, curr + ")", open, close+1, max);
}
}
};
int main()
{
Solution s;
auto result = s.generateParenthesis(3);
for (auto val : result) {
std::cout << val << std::endl;
}
return 0;
}
| true |
9eaf971b74f668a99e0e32fb386f5eb2645486a6 | C++ | hanyuelaoda/leetcode | /file/动态规划/零钱兑换.cpp | UTF-8 | 1,013 | 3.15625 | 3 | [] | no_license | /*
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。
如果没有任何一种硬币组合能组成总金额,返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-change
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
//动态规划,自顶向下
class Solution
{
public:
vector<int> table;
int coinChange(vector<int>& coins, int amount)
{
if (amount < 1) return 0;
table.resize(amount, 0);
return dp(coins, amount);
}
int dp(vector<int>& coins, int rem)
{
if (rem == 0) return 0;
if (rem < 0) return -1;
if (table[rem - 1] != 0) return table[rem - 1];
int min = INT_MAX;
for (int coin : coins)
{
//记录最小值
int ret = dp(coins, rem - coin);
if (ret >= 0 && ret < min)
{
min = ret + 1;
}
}
table[rem - 1] = (min == INT_MAX) ? -1 : min;
return table[rem - 1];
}
};
| true |
caf1899407ccd86eb2af963fbd4e2a968f0874cc | C++ | cos65535/ICPCLibrary | /Geometry/Intersect.cpp | UTF-8 | 1,405 | 3.015625 | 3 | [] | no_license | bool intersectLL(const Line &l, const Line &m) {
return abs(cross(l[1] - l[0], m[1] - m[0])) > EPS ||
abs(cross(l[1] - l[0], m[0] - l[0])) < EPS;
}
bool intersectLS(const Line &l, const Line &s) {
return cross(l[1] - l[0], s[0] - l[0]) *
cross(l[1] - l[0], s[1] - l[0]) < EPS;
}
bool intersectLP(const Line &l, const Point &p) {
return abs(cross(l[1] - p, l[0] - p)) < EPS;
}
bool intersectSS(const Line &s, const Line &t) {
return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&
ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;
}
bool intersectSP(const Line &s, const Point &p) {
return abs(s[0] - p) + abs(s[1] - p) - abs(s[1] - s[0]) < EPS;
}
bool intersectSPolygon(const Line &l, const Polygon &P) {
for (int i = 0; i < (int)P.size(); i++) {
Point A = CURR(P, i), B = NEXT(P, i);
if (intersectSS(l, Line(A, B))) { return true; }
}
return false;
}
//include inside
//bool intersectSC(const Line &s, const Circle &c) {
// return distanceSP(s, c.p) <= c.r;
//}
enum { OUT, ON, IN };
int Contains(const Polygon& P, const Point& p) {
bool in = false;
for (int i = 0; i < (int)P.size(); ++i) {
Point a = CURR(P,i) - p, b = NEXT(P,i) - p;
if (imag(a) > imag(b)) swap(a, b);
if (imag(a) <= 0 && 0 < imag(b))
if (cross(a, b) < 0) in = !in;
if (cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
| true |
4cd8a3873c32519285d2da72d26444d5fef54de7 | C++ | PratikChakraborty10/Data-Structures-and-Algorithms | /Linked List/arrangeLL.cpp | UTF-8 | 2,035 | 4.375 | 4 | [] | no_license | // Even after Odd LinkedList
// For a given singly linked list of integers, arrange the elements such that all the even numbers are placed after the odd numbers. The relative order of the odd and even terms should remain unchanged.
// Note :
// No need to print the list, it has already been taken care. Only return the new head to the list.
#include<iostream>
using namespace std;
class node {
public:
int data;
node *next;
node(int data) {
this->data=data;
this->next=NULL;
}
};
node *takeInput() {
int data;
cin >> data;
node *head=NULL;
node *tail=NULL;
while(data != -1) {
node *newNode = new node(data);
if(head==NULL) {
head=newNode;
tail=newNode;
} else {
tail->next=newNode;
tail=newNode;
}
cin >> data;
}
return head;
}
node* arrange_LinkedList(node* head){
node* oddHead = NULL;
node* oddTail = NULL;
node* evenHead = NULL;
node* evenTail = NULL;
while(head!=NULL){
if(head->data%2!=0){
if(oddHead == NULL){
oddHead=head;
oddTail=head;
}
else{
oddTail->next=head;
oddTail=oddTail->next;
}
}
else{
if(evenHead == NULL){
evenHead=head;
evenTail=head;
}
else{
evenTail->next=head;
evenTail=evenTail->next;
}
}
head = head->next;
}
if(oddTail==NULL){
return evenHead;
}
if(evenHead==NULL){
return oddHead;
}
oddTail->next = evenHead;
return oddHead;
}
void print(node *head) {
node *temp=head;
while(temp != NULL) {
cout << temp->data << " ";
temp=temp->next;
}
cout << endl;
}
int main() {
node *head = takeInput();
head = arrange_LinkedList(head);
print(head);
} | true |
b70be64d8e84622d3d5bec74bb59774d51cddfad | C++ | jeroennelis/VR_engine | /VR Engine/src/ModelTexture.h | UTF-8 | 968 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "Texture.h"
class ModelTexture :
public Texture
{
private:
float m_ShineDamper = 1;
float m_Reflectivity = 0;
bool m_Transparancy = false;
bool m_FakeLighting = false;
int m_NrOfRows = 1;
public:
ModelTexture(const std::string& path);
~ModelTexture();
inline float GetShineDamper() const { return m_ShineDamper; }
inline float GetReflectivity() const { return m_Reflectivity; }
inline bool IsTransparant() const { return m_Transparancy; }
inline bool UsingFakeLighting() const { return m_FakeLighting; }
inline int GetNrOfRows()const { return m_NrOfRows; }
inline void SetShineDamper(const float value) { m_ShineDamper = value; }
inline void SetReflectivity(const float value) { m_Reflectivity = value; }
inline void SetTransparancy(const bool value) { m_Transparancy = value; }
inline void SetFakeLighting(const bool value) { m_FakeLighting = value; }
inline void SetNrOFRows(const int value) { m_NrOfRows = value; }
};
| true |
14d37b1cf2866b43b68a1807b138b64358f4247f | C++ | Arsenic25/Primitive-Extended-Kalman-filter | /example/estimate attitude with IMU/EKF.hpp | UTF-8 | 2,916 | 2.875 | 3 | [] | no_license | /*
* EKF.h
*
* Created on: 2018/12/18
* Author: Arsenic
*/
#ifndef EKF_HPP_
#define EKF_HPP_
#define PI 3.1415926535
#include "Eigen/Core.h"
#include "Eigen/LU.h"
#include "math.h"
using namespace Eigen;
class EKF {
private:
public:
//constructor
EKF() {
initialX();
initialPreP();
initialQ();
initialR();
}
/*---define rotation matrix---*/
MatrixXf Rx(float dig) {
float rad = dig*(PI/180.0f);
MatrixXf m(3, 3);
m <<
1.0f, 0.0f, 0.0f,
0.0f, cos(rad), -sin(rad),
0.0f, sin(rad), cos(rad);
return m;
}
MatrixXf Ry(float dig) {
float rad = dig*(PI/180.0f);
MatrixXf m(3, 3);
m <<
cos(rad), 0.0f, sin(rad),
0.0f, 1.0f, 0.0f,
-sin(rad), 0.0f, cos(rad);
return m;
}
/*---define rotation matrix---*/
/**
* Calculation newest estimation state Xt
* Matrix z : measurement vector
* Matrix u : control vector
* return : estimation state vector
*/
VectorXf update(VectorXf z, VectorXf u);
/* USER DEFINITION */
//Cycle[s]
float dt;
//state X
VectorXf X;
void initialX() { //Define initial state here
VectorXf m(3);
m <<
0.0f,
0.0f,
0.0f;
X = m;
}
//state covariance
MatrixXf P;
void initialPreP() { //Define initial state covariance
MatrixXf m(3, 3);
m <<
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f;
P = m;
}
//Control covariance
MatrixXf Q;
void initialQ() { //Define Control covariance here
MatrixXf m(3, 3);
m <<
0.001f, 0.0f, 0.0f,
0.0f, 0.001f, 0.0f,
0.0f, 0.0f, 0.001f;
Q = m;
}
//Measurement covariance
MatrixXf R;
void initialR() { //Define Measurement covariance here
MatrixXf m(3, 3);
m <<
0.005071526f, 0.0f, 0.0f,
0.0f, 0.007402357f, 0.0f,
0.0f, 0.0f, 0.014450039f;
R = m;
}
//Equation of state f
VectorXf f(VectorXf preX, VectorXf u) {
VectorXf x;
x = preX + dt*Ry(preX(1))*Rx(preX(0))*u;
return x;
}
//Jacobian matrix F
MatrixXf jacF(VectorXf x, VectorXf u) {
VectorXf rad = (PI/180.0f)*x;
MatrixXf jF(3, 3);
jF <<
1.0f+dt*(cos(rad(0))*sin(rad(1))*u(1)-sin(rad(0))*sin(rad(1))*u(2)), dt*(-sin(rad(1))*u(0)+sin(rad(0))*cos(rad(1))*u(1)+cos(rad(0))*cos(rad(1))*u(2)), 0.0f,
dt*(-sin(rad(0))*u(1)), 1+dt*(-cos(rad(1))*u(2)), 0.0f,
dt*(cos(rad(0))*cos(rad(1))*u(1)-sin(rad(0))*cos(rad(1))*u(2)), dt*(-cos(rad(1))*u(0)-sin(rad(0))*sin(rad(1))*u(1)-cos(rad(0))*sin(rad(1))*u(2)), 1.0f;
return jF;
}
//Equation of output h
VectorXf h(VectorXf x) {
VectorXf z;
VectorXf gVec(3);
gVec <<
0,
0,
1;
z = (Rx(x(0)).transpose())*(Ry(x(1)).transpose())*gVec;
return z;
}
//Jacobian matrix H
MatrixXf jacH(VectorXf x) {
VectorXf rad = (PI/180.0f)*x;
MatrixXf jH(3, 3);
jH <<
0.0f, -cos(rad(1)), 0.0f,
cos(rad(0))*cos(rad(1)), -sin(rad(0))*sin(rad(1)), 0.0f,
-sin(rad(0))*cos(rad(1)), -cos(rad(0))*sin(rad(1)), 0.0f;
return jH;
}
/* USER DEFINITION */
};
#endif /* EKF_HPP_ */
| true |
047e506c34734bb010b5c06abfebee4a5e0da004 | C++ | tov/ge211 | /include/ge211/util/to_string.hxx | UTF-8 | 690 | 3.515625 | 4 | [] | no_license | #pragma once
#include <ostream>
#include <sstream>
#include <string>
namespace util {
namespace format {
namespace detail {
inline void
concat_to(std::ostream&) { }
template <typename FIRST, typename... REST>
void
concat_to(std::ostream& buf, FIRST const& first, REST const& ... rest)
{
buf << first;
concat_to(buf, rest...);
}
} // end namespace detail
/// Converts any printable type to a `std::string`. Multiple arguments
/// are concatenated.
template <typename... PRINTABLE>
std::string
to_string(PRINTABLE const& ... value)
{
std::ostringstream buf;
detail::concat_to(buf, value...);
return buf.str();
}
} // end namespace format
} // end namespace util
| true |