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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2101cac27376828737ecc61cc306e05424810cd7 | C++ | minecraburn/cs144- | /cs144/libsponge/network_interface.cc | UTF-8 | 6,303 | 2.59375 | 3 | [] | no_license | #include "network_interface.hh"
#include "arp_message.hh"
#include "ethernet_frame.hh"
#include <iostream>
// Dummy implementation of a network interface
// Translates from {IP datagram, next hop address} to link-layer frame, and from link-layer frame to IP datagram
// For Lab 5, please replace with a real implementation that passes the
// automated checks run by `make check_lab5`.
// You will need to add private members to the class declaration in `network_interface.hh`
template <typename... Targs>
void DUMMY_CODE(Targs &&... /* unused */) {}
using namespace std;
//! \param[in] ethernet_address Ethernet (what ARP calls "hardware") address of the interface
//! \param[in] ip_address IP (what ARP calls "protocol") address of the interface
NetworkInterface::NetworkInterface(const EthernetAddress ðernet_address, const Address &ip_address)
: _ethernet_address(ethernet_address), _ip_address(ip_address) {
cerr << "DEBUG: Network interface has Ethernet address " << to_string(_ethernet_address) << " and IP address "
<< ip_address.ip() << "\n";
_mapae[_ip_address.ipv4_numeric()]=_ethernet_address;
}
//! \param[in] dgram the IPv4 datagram to be sent
//! \param[in] next_hop the IP address of the interface to send it to (typically a router or default gateway, but may also be another host if directly connected to the same network as the destination)
//! (Note: the Address type can be converted to a uint32_t (raw 32-bit IP address) with the Address::ipv4_numeric() method.)
void NetworkInterface::send_datagram(const InternetDatagram &dgram, const Address &next_hop) {
// convert IP address of next hop to raw 32-bit representation (used in ARP header)
const uint32_t next_hop_ip = next_hop.ipv4_numeric();
if(_mapae.count(next_hop_ip)){
BufferList ss=dgram.serialize();
EthernetFrame sende;
sende.payload()=ss;
EthernetHeader eh;
eh.dst=_mapae[next_hop_ip];
eh.src=_ethernet_address;
eh.type=EthernetHeader::TYPE_IPv4;
sende.header()=eh;
_frames_out.push(sende);return;
}
_queind.push(dgram);
_queip.push(next_hop_ip);
if(_reqat.count(next_hop_ip))return;
ARPMessage arpme;
arpme.opcode=ARPMessage::OPCODE_REQUEST;
arpme.sender_ip_address=_ip_address.ipv4_numeric();
arpme.target_ip_address=next_hop_ip;
arpme.sender_ethernet_address=_ethernet_address;
string ss=arpme.serialize();
EthernetFrame sende;
sende.payload()=Buffer(std::move(ss));
EthernetHeader eh;
eh.dst=ETHERNET_BROADCAST;
eh.src=_ethernet_address;
eh.type=EthernetHeader::TYPE_ARP;
sende.header()=eh;
_frames_out.push(sende);
_reqat[next_hop_ip]=_time;
}
//! \param[in] frame the incoming Ethernet frame
optional<InternetDatagram> NetworkInterface::recv_frame(const EthernetFrame &frame) {
if(frame.header().dst!=_ethernet_address&&frame.header().dst!=ETHERNET_BROADCAST) return {};
if(frame.header().type==EthernetHeader::TYPE_IPv4){
InternetDatagram rec;
if(rec.parse(frame.payload())==ParseResult::NoError){
uint32_t myaddr;
EthernetAddress myead;
myaddr=rec.header().src;
myead=frame.header().src;
_mapae[myaddr]=myead;
if(myaddr!=_ip_address.ipv4_numeric()) _mapat[myaddr]=_time;
return rec;
}
}
if(frame.header().type==EthernetHeader::TYPE_ARP){
ARPMessage recarp;
if(recarp.parse(frame.payload())==ParseResult::NoError){
uint32_t myaddr;
EthernetAddress myead;
myaddr=recarp.sender_ip_address;
myead=recarp.sender_ethernet_address;
_mapae[myaddr]=myead;
if(myaddr!=_ip_address.ipv4_numeric()) _mapat[myaddr]=_time;
if(recarp.opcode==ARPMessage::OPCODE_REQUEST&&_mapae.count(recarp.target_ip_address)){
ARPMessage arpme;
arpme.opcode=ARPMessage::OPCODE_REPLY;
arpme.sender_ip_address=recarp.target_ip_address;
arpme.sender_ethernet_address=_mapae[recarp.target_ip_address];
arpme.target_ethernet_address=myead;
arpme.target_ip_address=myaddr;
string ss=arpme.serialize();
EthernetFrame sende;
sende.payload()=Buffer(std::move(ss));
EthernetHeader eh;
eh.dst=myead;
eh.src=_ethernet_address;
eh.type=EthernetHeader::TYPE_ARP;
sende.header()=eh;
_frames_out.push(sende);
}else{
myaddr=recarp.target_ip_address;
myead=recarp.target_ethernet_address;
_mapae[myaddr]=myead;
if(myaddr!=_ip_address.ipv4_numeric()) _mapat[myaddr]=_time;
}
std::queue<InternetDatagram> qid;
std::queue<uint32_t> qip;
while(!_queip.empty()){
InternetDatagram dgra;
uint32_t dip;
dip=_queip.front();
_queip.pop();
dgra=_queind.front();
_queind.pop();
if(_mapae.count(dip)){
BufferList ss=dgra.serialize();
EthernetFrame sende;
sende.payload()=ss;
EthernetHeader eh;
eh.dst=_mapae[dip];
eh.src=_ethernet_address;
eh.type=EthernetHeader::TYPE_IPv4;
sende.header()=eh;
_frames_out.push(sende);
}else{
qid.push(dgra);
qip.push(dip);
}
}
_queind=qid;
_queip=qip;
}
}
return {};
}
void NetworkInterface::tick(const size_t ms_since_last_tick) {
_time+=ms_since_last_tick;
for(auto it=_mapat.begin();it!=_mapat.end();){
if(it->second+30000<=_time){
_mapae.erase(it->first);
_mapat.erase(it++);
}else
it++;
}
for(auto it=_reqat.begin();it!=_reqat.end();){
if(it->second+5000<=_time){
_reqat.erase(it++);
}else
it++;
}
}
| true |
fd09c0d0f2f1cd2254c5d38a53b1c4e9e9553586 | C++ | Lincoln12w/OJs | /PAT/C_C++_Java/Loop-06.cpp | UTF-8 | 294 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
using std::string;
using std::istringstream;
int main()
{
string s;
string word;
int cnt = 0;
getline(std::cin, s);
istringstream iss(s);
while(iss >> word)
cnt++;
std::cout << cnt;
return 0;
}
| true |
2a5377b8f157f761d6bed241df3cf6b4b9e443eb | C++ | thuleqaid/boost_study | /filesystem/src/fs-utility.cpp | UTF-8 | 1,775 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "fs-utility.hpp"
#include <cstdlib>
void makedirs(const bfs::path& inpath)
{
/* path must exist for bfs::canonical(path) */
bfs::path fpath=bfs::absolute(inpath);
if (!bfs::is_directory(inpath))
{
bfs::path cur;
for(auto item=fpath.begin();item!=fpath.end();++item)
{
/* concatenation */
cur/=*item;
if(bfs::is_directory(cur))
{
/* in case of '..' and '.' */
cur=bfs::canonical(cur);
}
else
{
/* create directory */
bfs::create_directory(cur);
}
}
}
}
/* find executable file in the environment */
static void _saveToList(const bfs::path& file,std::vector<bfs::path>& vec,const std::string& filename)
{
if (file.filename().generic_string()==filename)
{
vec.push_back(file);
}
}
void findInPath(const std::string& filename, std::initializer_list<std::string> additions, std::vector<bfs::path>& result, int count)
{
std::string env(std::getenv("PATH"));
#ifdef WIN32
const std::string sep(";");
#else
const std::string sep(":");
#endif
std::string::size_type pos1(0),pos2;
std::vector<std::string> pathlist;
pathlist.reserve(additions.size());
std::copy(additions.begin(),additions.end(),std::back_inserter(pathlist));
while(true)
{
pos2=env.find(sep,pos1);
if (std::string::npos==pos2)
{
if (env.size()-pos1>0)
{
pathlist.push_back(env.substr(pos1));
}
break;
}
else
{
if (pos2-pos1>0)
{
pathlist.push_back(env.substr(pos1,pos2-pos1));
}
pos1=pos2+1;
}
}
std::copy(pathlist.cbegin(),pathlist.cend(),std::ostream_iterator<std::string>(std::cout,"\n"));
for (auto &item:pathlist)
{
walk(bfs::path(item),std::bind(_saveToList,std::placeholders::_1,std::ref(result),filename),false);
if ((count>0) && (result.size()-count>=0))
{
break;
}
}
}
| true |
a253c48674cb04b66a81e7b2cc94a0ef3ea28859 | C++ | dipta007/Competitive-Programming | /@DOC by DIPTA/dipta007_final/String/tokenizer.cpp | UTF-8 | 421 | 2.859375 | 3 | [
"MIT"
] | permissive | int main ()
{
char str[] ="- This, a sample string.";
char * pch;
// by which charcters string is tokenized that should be given into "(here)"
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
// by which charcters string is tokenized that should be given into "(here)"
pch = strtok (NULL, " ,.-");
}
return 0;
}
/// OUTPUT
This
a
sample
string
| true |
bdc67e6a2ac41c483b8a40cabc7664b782378a4f | C++ | virenvarma007/Data-Structures-and-Algorithms | /Sherlock and Numbers.cpp | UTF-8 | 738 | 2.5625 | 3 | [] | no_license | #include <iostream>
using namespace std;
long long int binarySearch(long long int low, long long int high, long long int key, long long int a[]){
int mid;
while(low<=high){
mid=(low+high)/2;
if(a[mid]<key){
high=mid-1;
}
else if(a[mid]>key){
low=mid+1;
}
else{
return mid;
}
}
return -1;
}
int main(){
int t;
cin>>t;
for(int T=0; T<t; T++){
long long int n,k,p,val,num=0;
long long int ans=-1;
cin>>n>>k>>p;
long long int a[n+1];
for(long long int i=1; i<=n; i++){
a[i]=i;
}
for(long long int i=0; i<k; i++){
cin>>val;
a[val]=0;
}
for(long long int i=1; i<=n; i++){
if(a[i]!=0){
num=num+1;
if(num==p){
ans=a[i];
break;
}
}
}
cout<<ans<<endl;
}
}
| true |
d8c5618dd47a2d2635bab48da7d26e1779615e12 | C++ | kimdy003/AlgorithmStudy | /Study/8_week/6_11437.cpp | UTF-8 | 1,392 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <vector>
const int Level = 18;
const int MAX = 50001;
using namespace std;
int n;
int depth[MAX];
int ac[MAX][20];
vector<int> graph[MAX];
void Make_Tree(int cur, int parent){
depth[cur] = depth[parent]+1;
ac[cur][0] = parent;
for(int i=1; i<=Level; i++){
int pp = ac[cur][i-1];
ac[cur][i] = ac[pp][i-1];
}
for(int i=0; i<graph[cur].size(); i++){
int child = graph[cur][i];
if(child != parent){
Make_Tree(child, cur);
}
}
}
int main(){
cin >> n;
for(int i=0; i<n-1; i++){
int u, v; cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
depth[0] = -1;
Make_Tree(1, 0);
int q; cin >> q;
while(q--){
int x, y; cin >> x >> y;
if(depth[x] != depth[y]){
if(depth[x] > depth[y]){
swap(x, y);
}
for(int i = Level; i>=0; i--){
if(depth[x] <= depth[ac[y][i]]){
y = ac[y][i];
}
}
}
int lca = x;
if(x != y){
for(int i=Level; i>=0; i--){
if(ac[x][i] != ac[y][i]){
x = ac[x][i];
y = ac[y][i];
}
lca = ac[x][i];
}
}
cout << lca << "\n";
}
} | true |
a4e3f7b6f4e76bf5ef2d1f75d52991910f56deac | C++ | alexandraback/datacollection | /solutions_5744014401732608_1/C++/gridnevvvit/main.cpp | UTF-8 | 1,059 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <vector>
typedef long long li;
using namespace std;
inline void solve(int test) {
int n;
li m;
cin >> n >> m;
vector < li > d(n);
vector < vector < int > > ans(n, vector < int > (n, 0));
d[n - 1] = 1;
for(int i = n - 2; i >= 0; i--) {
d[i] = 0;
for(int j = i + 1; j < n; j++) {
d[i] += d[j];
if (i != 0)
ans[i][j] = 1;
}
}
cerr << d[0] << endl;
printf("Case #%d: ", test);
if (m <= d[0]) {
puts("POSSIBLE");
m--;
for(int i = 1; i < n - 1; i++)
if ((m & d[i]) > 0)
ans[0][i] = 1;
ans[0][n - 1] = 1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
printf("%d", ans[i][j]);
puts("");
}
} else {
puts("IMPOSSIBLE");
}
}
int main() {
int testcount;
cin >> testcount;
for(int test = 0; test < testcount; test++) {
solve(test + 1);
}
}
| true |
716eb6574112f9c8339d6aa53747a3f97083a522 | C++ | asucato2/datastructures | /include/DataStructures/RBTree.hpp | UTF-8 | 16,007 | 3.390625 | 3 | [
"MIT"
] | permissive | //
// Created by ansucato on 11/11/19.
//
#ifndef DATASTRUCTURES_RBTREE_HPP
#define DATASTRUCTURES_RBTREE_HPP
#include <iostream>
#include <list>
#include <vector>
namespace DataStructures
{
template<typename keyType, typename valueType>
class RBTree
{
public:
RBTree();
RBTree(const keyType *t_key, const valueType *t_value, const int t_size);
~RBTree();
void insert(const keyType t_key, const valueType t_value);
int remove(const keyType t_key);
valueType *search(const keyType t_key) const;
int rank(const keyType t_key) const;
int size() const;
keyType select(const int t_pos) const;
void split(const keyType t_key, RBTree<keyType, valueType> &T1, RBTree<keyType, valueType> &T2);
void preorder() const;
void inorder() const;
void postorder() const;
private:
struct Node
{
keyType key;
valueType value;
int weight;
enum class Color
{
black = 0, red
} color; // color of link above node
Node *leftChild;
Node *rightChild;
};
Node *_root;
inline void initializeNode(Node *t_node, const keyType t_key, const valueType t_value, const typename Node::Color t_color);
inline bool isRed(Node *t_node) const;
Node *rotateLeft(Node *t_head);
Node *rotateRight(Node *t_head);
Node *colorFlip(Node *t_head);
Node *insertHelper(Node *t_head, const keyType t_key, const valueType t_value);
Node *fixup(Node* t_head);
Node *moveRedRight(Node* t_head);
Node *moveRedLeft(Node* t_head);
Node *deleteMin(Node* t_head);
Node *deleteNode(Node* t_head, const keyType t_key);
Node *leanRight(Node* t_head);
void preorderTreeWalk(const Node *t_head) const;
void inorderTreeWalk(const Node *t_head) const;
void postorderTreeWalk(const Node *t_head) const;
int treeSize(const Node *t_target) const;
void treeDelete(Node *t_root);
Node* treeMin(Node *t_root) const;
Node* treeMax(const Node *t_root) const;
void inorderTreeWalkList(const Node *t_head, std::vector<Node> &nodes);
};
template<typename keyType, typename valueType>
RBTree<keyType, valueType>::RBTree()
: _root(nullptr)
{
}
template<typename keyType, typename valueType>
RBTree<keyType, valueType>::RBTree(const keyType *t_key, const valueType *t_value, const int t_size)
: _root(nullptr)
{
for (int i = 0; i < t_size; i++)
{
insert(t_key[i], t_value[i]);
}
}
template<typename keyType, typename valueType>
RBTree<keyType, valueType>::~RBTree()
{
treeDelete(_root);
}
template<typename keyType, typename valueType>
bool RBTree<keyType, valueType>::isRed(RBTree::Node *t_node) const
{
if (t_node == nullptr)
{
return false;
}
return t_node->color == Node::Color::red;
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::insert(const keyType t_key, const valueType t_value)
{
_root = insertHelper(_root, t_key, t_value);
_root->color = Node::Color::black;
}
template<typename keyType, typename valueType>
valueType *RBTree<keyType, valueType>::search(const keyType t_key) const
{
Node *curNode = _root;
while (curNode != nullptr)
{
if (t_key == curNode->key)
{
return &curNode->value;
}
else if (t_key < curNode->key)
{
curNode = curNode->leftChild;
}
else
{
curNode = curNode->rightChild;
}
}
return nullptr;
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::initializeNode(RBTree::Node *t_node,
const keyType t_key,
const valueType t_value,
const typename RBTree::Node::Color t_color)
{
t_node->key = t_key;
t_node->value = t_value;
t_node->color = t_color;
t_node->weight = 1;
t_node->leftChild = nullptr;
t_node->rightChild = nullptr;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::rotateLeft(RBTree::Node *t_head)
{
Node *x = t_head->rightChild;
t_head->rightChild = x->leftChild;
x->leftChild = t_head;
x->color = x->leftChild->color;
x->leftChild->color = Node::Color::red;
t_head->weight = treeSize(t_head->leftChild) + treeSize(t_head->rightChild) + 1;
x->weight = treeSize(x->leftChild) + treeSize(x->rightChild) + 1;
return x;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::rotateRight(RBTree::Node *t_head)
{
Node *x = t_head->leftChild;
t_head->leftChild = x->rightChild;
x->rightChild = t_head;
x->color = x->rightChild->color;
x->rightChild->color = Node::Color::red;
t_head->weight = treeSize(t_head->leftChild) + treeSize(t_head->rightChild) + 1;
x->weight = treeSize(x->leftChild) + treeSize(x->rightChild) + 1;
return x;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::colorFlip(RBTree::Node *t_head)
{
if (isRed(t_head))
{
t_head->color = Node::Color::black;
}
else
{
t_head->color = Node::Color::red;
}
if (isRed(t_head->leftChild))
{
t_head->leftChild->color = Node::Color::black;
}
else
{
t_head->leftChild->color = Node::Color::red;
}
if (isRed(t_head->rightChild))
{
t_head->rightChild->color = Node::Color::black;
}
else
{
t_head->rightChild->color = Node::Color::red;
}
return t_head;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::insertHelper(RBTree::Node *t_head,
const keyType t_key,
const valueType t_value)
{
Node *head = t_head;
// Insert at bottom
if (head == nullptr)
{
Node *newNode = new Node;
initializeNode(newNode, t_key, t_value, Node::Color::red);
return newNode;
}
// BST insert
if (t_key == head->key)
{
head->value = t_value;
}
else if (t_key < head->key)
{
head->weight++;
head->leftChild = insertHelper(head->leftChild, t_key, t_value);
}
else
{
head->rightChild = insertHelper(head->rightChild, t_key, t_value);
head->weight++;
}
// fix right leaning reds on the way up
if (isRed(head->rightChild))
{
head = rotateLeft(head);
}
// fix two reds in a row on the way up
if (isRed(head->leftChild) && isRed(head->leftChild->leftChild))
{
head = rotateRight(head);
}
// Split 4-nodes on the way down
if (isRed(head->leftChild) && isRed(head->rightChild))
{
colorFlip(head);
}
return head;
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::preorder() const
{
preorderTreeWalk(_root);
std::cout << std::endl;
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::inorder() const
{
inorderTreeWalk(_root);
std::cout << std::endl;
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::postorder() const
{
postorderTreeWalk(_root);
std::cout << std::endl;
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::preorderTreeWalk(const Node *t_head) const
{
if (t_head == nullptr)
{
return;
}
std::cout << t_head->key << " ";
preorderTreeWalk(t_head->leftChild);
preorderTreeWalk(t_head->rightChild);
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::inorderTreeWalk(const RBTree::Node *t_head) const
{
if (t_head == nullptr)
{
return;
}
inorderTreeWalk(t_head->leftChild);
std::cout << t_head->key << " ";
inorderTreeWalk(t_head->rightChild);
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::postorderTreeWalk(const RBTree::Node *t_head) const
{
if (t_head == nullptr)
{
return;
}
postorderTreeWalk(t_head->leftChild);
postorderTreeWalk(t_head->rightChild);
std::cout << t_head->key << " ";
}
template<typename keyType, typename valueType>
int RBTree<keyType, valueType>::rank(const keyType t_key) const
{
Node *curNode = _root;
int rank = 1;
while (curNode != nullptr)
{
if (t_key < curNode->key)
{
curNode = curNode->leftChild;
}
else if (t_key > curNode->key)
{
rank += 1 + treeSize(curNode->leftChild);
curNode = curNode->rightChild;
}
else
{
rank += treeSize(curNode->leftChild);
return rank;
}
}
return 0;
}
template<typename keyType, typename valueType>
int RBTree<keyType, valueType>::treeSize(const Node *t_target) const
{
if (t_target == nullptr)
{
return 0;
}
return t_target->weight;
}
template<typename keyType, typename valueType>
int RBTree<keyType, valueType>::size() const
{
return treeSize(_root);
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::treeDelete(RBTree::Node *t_root)
{
if (t_root != nullptr)
{
treeDelete(t_root->leftChild);
treeDelete(t_root->rightChild);
delete t_root;
}
}
template<typename keyType, typename valueType>
keyType RBTree<keyType, valueType>::select(const int t_pos) const
{
Node *curNode = _root;
int rank = 0;
while (curNode != nullptr)
{
int curRank = rank + treeSize(curNode->leftChild) + 1;
if (t_pos < curRank)
{
curNode = curNode->leftChild;
}
else if (t_pos > curRank)
{
rank += treeSize(curNode->leftChild) + 1;
curNode = curNode->rightChild;
}
else
{
return curNode->key;
}
}
return 0;
}
template<typename keyType, typename valueType>
void
RBTree<keyType, valueType>::split(const keyType t_key, RBTree<keyType, valueType> &T1, RBTree<keyType, valueType> &T2)
{
std::vector<Node> nodes;
inorderTreeWalkList(_root, nodes);
int splitIndex = 0;
for (auto it = nodes.begin(); it != nodes.end(); it++, splitIndex++)
{
if (it->key >= t_key)
{
break;
}
}
for (int i = 0; i < splitIndex; i++)
{
T1.insert(nodes[i].key, nodes[i].value);
}
for (int i = splitIndex; i < nodes.size(); i++)
{
T2.insert(nodes[i].key, nodes[i].value);
}
}
template<typename keyType, typename valueType>
int RBTree<keyType, valueType>::remove(const keyType t_key)
{
if (search(t_key) == nullptr)
{
return 0;
}
_root = deleteNode(_root, t_key);
_root->color = Node::Color::black;
return 1;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::treeMin(Node *t_root) const
{
if (t_root == nullptr)
{
return nullptr;
}
Node *curNode = t_root;
while (curNode->leftChild != nullptr)
{
curNode = curNode->leftChild;
}
return curNode;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::treeMax(const RBTree::Node *t_root) const
{
if (t_root == nullptr)
{
return nullptr;
}
Node *curNode = t_root;
while (curNode->rightChild != nullptr)
{
curNode = curNode->rightChild;
}
return curNode;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::fixup(RBTree::Node *t_head)
{
// Rotate-left right-leaning reds
if (isRed(t_head->rightChild))
{
t_head = rotateLeft(t_head);
}
// rotate-right red-red pairs
if (isRed(t_head->leftChild) && isRed(t_head->leftChild->leftChild))
{
t_head = rotateRight(t_head);
}
//split 4-nodes
if (isRed(t_head->leftChild) && isRed(t_head->rightChild))
{
colorFlip(t_head);
}
return t_head;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::moveRedRight(RBTree::Node *t_head)
{
colorFlip(t_head);
if (isRed(t_head->leftChild->leftChild))
{
t_head = rotateRight(t_head);
colorFlip(t_head);
}
return t_head;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::deleteMin(RBTree::Node *t_head)
{
// remove node on bottom level (h must be red)
if (t_head->leftChild == nullptr)
{
return nullptr;
}
// push red link down if necessary
if (!isRed(t_head->leftChild) && !isRed(t_head->leftChild->leftChild))
{
t_head = moveRedRight(t_head);
}
// move down one level
t_head->weight--;
t_head->leftChild = deleteMin(t_head->leftChild);
// fix right leaning red links and eliminate 4-nodes on the way up
return fixup(t_head);
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::moveRedLeft(RBTree::Node *t_head)
{
colorFlip(t_head);
if (isRed(t_head->rightChild->leftChild))
{
t_head->rightChild = rotateRight(t_head->rightChild);
t_head = rotateRight(t_head);
colorFlip(t_head);
}
return t_head;
}
template<typename keyType, typename valueType>
typename RBTree<keyType, valueType>::Node *RBTree<keyType, valueType>::deleteNode(RBTree::Node *t_head, keyType t_key)
{
Node* head = t_head;
// node to be deleted is on left
if (t_key < head->key)
{
// push red right if necessary
if (!isRed(head->leftChild) && !isRed(head->leftChild->leftChild))
{
head = moveRedRight(head);
}
// move down on left child
head->leftChild = deleteNode(head->leftChild, t_key);
}
else // node to be deleted is on right
{
// rotate to push red right
if (isRed(head->leftChild))
{
head = rotateRight(head);
}
// equal (at bottom): delete node
if (t_key == head->key && head->rightChild == nullptr)
{
return nullptr;
}
// push red right if necessary
if (!isRed(head->rightChild) && !isRed(head->rightChild->leftChild))
{
head = moveRedRight(head);
}
// equal (not at bottom)
if (t_key == head->key)
{
// replace current node w successor and delete
Node *successor = treeMin(head->rightChild);
head->key = successor->key;
head->value = successor->value;
successor->weight = head->weight - 1;
head->rightChild = deleteMin(head->rightChild);
}
else
{
// move down on right child
head->rightChild = deleteNode(head->rightChild, t_key);
}
}
// fix right leaning red links and eliminate 4-nodes on the way up
return fixup(head);
}
template<typename keyType, typename valueType>
void RBTree<keyType, valueType>::inorderTreeWalkList(const RBTree::Node *t_head, std::vector<Node> &node)
{
if (t_head == nullptr)
{
return;
}
inorderTreeWalkList(t_head->leftChild, node);
node.push_back(*t_head);
inorderTreeWalkList(t_head->rightChild, node);
}
}
#endif //DATASTRUCTURES_RBTREE_HPP
| true |
a4f2d6bff890a40f3517e9aca8ec5f8aea578823 | C++ | Sparrow-hawks/C-Primer-Plus-Exercises | /Chapter9/golf.cpp | UTF-8 | 755 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include "golf.h"
bool setgolf(Golf& g, const char *name, int hc) {
if (name != nullptr && strlen(name) != 0) {
strncpy(g.fullname, name, Len - 1);
g.handicap = hc;
return true;
} else {
return false;
}
}
bool setgolf(Golf& g) {
std::cout << "Enter Player's name: ";
if (std::cin.getline(g.fullname, Len - 1) && strlen(g.fullname) != 0) {
std::cout << "Enter Player's handicap: ";
std::cin >> g.handicap;
std::cin.get();
return true;
} else {
return false;
}
}
void handicap(Golf& g, int hc) {
g.handicap = hc;
}
void showgolf(const Golf& g) {
std::cout << "Player: " << g.fullname << std::endl;
std::cout << "Handicap: " << g.handicap << std::endl;
}
| true |
992624bef242bc0ba90ee5b6055d26470cd87ef0 | C++ | Anujith123/s2lab4 | /lab4.2.cpp | UTF-8 | 7,608 | 4.09375 | 4 | [] | no_license | //Program to implement queue using 2 stacks
// including library
#include<iostream>
//using namespace
using namespace std;
// class
class Node
{
public:
//storing data
int data;
//pointer to move to next node
Node* next;
//initializing next pointer as NULL
Node(){
next = NULL;
}
};
class LinkedList{
public:
//pointer to store start node of the linked list
Node* head;
//pointer to point to the last node of the linked list
Node *tail;
//initializing head as NULL
LinkedList(){
head = NULL;
tail = NULL;
}
void insert(int value){
Node *temp = new Node;
temp->data = value;
if(head==NULL){
//update head;
head = temp;
}
else{
//linking the last element to new node created
tail->next = temp;
}
//update tail
tail = temp;
cout<<endl;
}
//Deleting
//deleting the end element
void deletion(){
Node *temp = tail;
Node *current = head;
while(current->next != tail){
current = current->next;
}
current->next = NULL;
//updating tail
tail = current;
//deleting temp
delete temp;
cout<<endl;
}
void insertAt(int pos,int value){
//To add node at the position of the header
if(pos == 1){
Node *temp = new Node;
temp->data = value;
//linking the new node to head
temp->next = head;
//updating head
head = temp;
}
else{
//Reaching the place before the position
Node *current = head;
int i = 1;
while(i<pos-1){
i++;
current = current->next;
}
//counter variable to count no. of entries
int count = 0;
//declaring present pointer to initially point to head
Node *present = head;
//increment count upto last element and simultaneously increment present pointer
while(present!=NULL){
count++;
present = present->next;
}
if(pos>count){
cout<<"The linked list doesn't have that many elements\n";
}
else{
//Create the node
Node *temp = new Node;
temp->data = value;
//Moving pointers like magic
temp->next = current->next;
current->next = temp;
}
}
cout<<endl;
}
//Deleting element of linked list from a specific position
void deletionAt(int pos){
if(pos == 1){
if(head != NULL){
Node *temp = head;
head = head->next;
//deleting temp
delete temp;
}
}
else{
//reachs the position just before the node to be deleted
Node *current = head;
int i = 1;
while(i<pos-1){
i++;
current = current->next;
}
Node *temp = new Node;
temp = current->next;
current->next = temp->next;
//deleting temp
delete temp;
}
cout<<endl;
}
//Displaying
void display(){
Node *current = head;
while(current != NULL){
cout<<current->data<<"->";
current = current->next;
}
cout<<"NULL";
}
//Counting
int countItems(){
//set a counter variable
int count = 0;
Node *current = head;
while(current !=NULL){
count++;
current = current->next;
}
return count;
}
};
//stack using linked list
class StackLL{
public:
Node *top;
LinkedList l1;
StackLL(){
top = NULL;
}
//pushes on top
void push(int value){
l1.insertAt(1,value);
top = l1.head;
}
//pops from top
void pop(){
l1.deletionAt(1);
top = l1.head;
}
//checks whether the stack is empty
bool isEmpty(){
if(top == NULL)
return true;
return false;
}
//returns size of the stack
int size(){
return l1.countItems();
}
//displays value stored in top pointer
void topDisplay(){
cout<<"Value in top pointer: "<<top->data<<endl;
}
//display
void display(){
l1.display();
}
};
class Queue{
public:
//creating two stacks
StackLL s1,s2;
//adds elements to the queue
void enqueue(int value){
s1.push(value);
}
//deletes elements from the queue
void dequeue(){
if(s1.size()==0)
return; //Newline
if(s1.size()==1){
s1.pop();
return;
}
else{
//pushes data from main stack to another stack
s2.push(s1.top->data);
//pops element from main stack
s1.pop();
cout << "S1 :"; s1.display(); cout << endl; //Newline
cout << "S2 :"; s2.display(); cout << endl; //Newline
dequeue();
//pushes elements back into the main stack
s1.push(s2.top->data);
s2.pop();
}
}
//displaying the contents of the queue
void display(){
s1.display();
cout<<endl;
}
//returns the size of the queue
int size()
{
return s1.size();
}
};
//including main function
int main(){
Queue q1;
for(int i=1;i<6;i++){
q1.enqueue(i);
}
//dequeueing twice
q1.display();
q1.dequeue();
q1.display();
q1.dequeue();
q1.display();
return 0;
}
| true |
aeaf95353d8a01cf0e0e1409cd62935ef3d57807 | C++ | Ashish-012/Ds-Algo | /Linked-list/linked-list-recursive-printing.cpp | UTF-8 | 877 | 4.03125 | 4 | [] | no_license | // Printing the linked list using recursion
#include<iostream>
#include<conio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
node* head;
void print(node* temp){
if(temp==NULL) return;
printf("%d ",temp->data);
print(temp->next);
}
void printrev(node* temp){
if(temp==NULL) return;
printrev(temp->next);
printf("%d ",temp->data);
}
void insert(int data,int n){
node* temp= new node;
node* temp1= head;
temp-> data= data;
temp-> next= NULL;
if(n==1){
temp->next=head;
head=temp;
return;
}
for(int i=0;i<n-2;i++){
temp1=temp1->next;
}
temp->next=temp1->next;
temp1->next=temp;
}
int main(){
head=NULL;
insert(2,1);
insert(3,2);
insert(4,1);
insert(5,2);
printf("Linked list after insertion is : ");
print(head);
printf("Linked list reversed : ");
printrev();
} | true |
d5617378e9a911d92f97a1953672b163e5e27cf0 | C++ | lmatsuki/LEM-Engine | /LEM Engine/src/Message.h | UTF-8 | 416 | 2.84375 | 3 | [] | no_license | #pragma once
#include <string>
#include <ctime>
#include "MessageType.h"
// The default message struct used by the MessageBus.
struct Message
{
Message() : type(MessageType::Console), consoleMessage("") {}
Message(const MessageType type, const std::string & consoleMessage) : type(type), consoleMessage(consoleMessage)
{
}
virtual ~Message() {}
const MessageType type;
const std::string consoleMessage;
}; | true |
24dd79e326ec6b3298bae7fb2d0f039527ab3285 | C++ | anjali9811/Programming-in-Cpp | /BaseMemberMethodusingObjectAsArg.cpp | UTF-8 | 463 | 3.578125 | 4 | [
"Apache-2.0"
] | permissive | #include<iostream>
using namespace std;
class Person {
public:
void getname() {
cout<<"Hi I am Anish"<<endl;
}
};
//we can access the public members of a class in any other function defined which takes a var of that class type as argument
//or which takes a object of that class as argument
void printName(Person &p) {
//calling Person class member function using the object as argument
p->getname();
}
int main() {
Person p;
printName(p);
}
| true |
696c1bc36a6d33144efe62d5d25a3b11e0eec304 | C++ | kirikiko5/Telesilla | /Telesilla/ColaGondola.cpp | UTF-8 | 1,735 | 3.21875 | 3 | [] | no_license | //
// gondola.cpp
// Telesilla
//
// Created by Enrique on 30/10/15.
// Copyright © 2015 Enrique. All rights reserved.
//
#include "Gondola.h"
#include "ColaGondola.h"
#include <stdio.h>
#include <iostream>
#define MAX 5
using namespace std;
//
/*colaGondola::~colaGondola(){
while (primero) desencolar();
}*/
void colaGondola::encolarTelesilla(Persona p[]) {
pnodoArray nuevo = new Gondola(p); //Se crea un nuevo nodo
if (ultimo) {
ultimo->siguiente2 = nuevo; //Si hay final
}
ultimo = nuevo;
if (!primero) { //Si no hay final ni frente, el frente vale lo mismo que el final
primero = nuevo;
}
}
Persona colaGondola::desencolar() {
pnodoArray nodo = primero;
Persona v[5];
if (!nodo) //Si la cola esta vacia devuelve 0
cout << "Cola vacia";
primero = nodo -> siguiente2; //Se asigna a la primera la direccion del segundo nodo
for(int i = 0; i < MAX ; i++) {
v[i] = nodo->arrayP[i]; //Se guarda el valor de retorno
}
delete nodo; //Se borra el nodo
if(!primero) ultimo = NULL; //Si cola vacia, el ultimo debe ser NULL tambien
return v[4];
}
void colaGondola::mostrar () {
pnodoArray actual = primero;
if (actual == NULL) { //Comprobamos que la lista no esta vacia
cout << "LA LISTA ESTA VACIA \n";
}
else {
while (actual != NULL) { //Si la lista no esta vacia
for (int i =0 ; i < 5; i++) {
cout << actual->arrayP[i].getCondicion() << " | "; //Imprimimos por pantalla el valor
}
cout << "\n";
actual = actual -> siguiente2; //Avazamos a la siguiente posicion
}
}
} | true |
8110d4664f0f3e115df10a9bf791b50c7d0945fb | C++ | jrs023/ProjectEuler | /C++/project07.cpp | UTF-8 | 415 | 3.3125 | 3 | [] | no_license | //ProjectEuler Number 7
//by Josh Smith
#include <iostream>
using namespace std;
bool isPrime(size_t n){
if(n < 0){
cout << "n must be larger than zero" << endl;
return false;
}
for(int i = 2; i < sqrt(n)+1; i++){
if(n%i == 0){
return false;
}
}
return true;
}
int main() {
size_t i = 0;
size_t x = 2;
while(i <= 10001){
if(isPrime(x)){
i++;
}
x++;
}
cout << x-1 << endl;
return 0;
}
| true |
72562135b26a44d0916dbb7d7376f0e77d86e373 | C++ | Petrosz007/uni | /2_félév/objektum_elvű_programozás/előadás/shapes/shapes.h | UTF-8 | 3,709 | 3.265625 | 3 | [] | no_license | //Athor: Gregorics Tibor
//Date: 2017.12.15.
//Title: classes of different shapes
#pragma once
#include "area.h"
// class of abstract shapes
class Shape
{
public:
virtual ~Shape();
virtual double volume() const = 0;
static int piece() { return _piece; }
protected:
Shape(double size);
double _size;
private:
static int _piece;
};
// class of abstract regular shapes
class Regular : public Shape{
public:
~Regular();
double volume() const override;
static int piece() { return _piece; }
protected:
Regular(double size);
virtual double multiplier() const = 0;
private:
static int _piece;
};
// class of cubes
class Cube : public Regular
{
public:
Cube(double size);
~Cube();
static int piece() { return _piece; }
protected:
double multiplier() const override { return 1.0; }
private:
static int _piece;
};
// class of spheres
class Sphere : public Regular
{
public:
Sphere(double size);
~Sphere();
static int piece() { return _piece; }
protected:
double multiplier() const override { return _multiplier; }
private:
constexpr static double _multiplier = (4.0 * 3.14159) / 3.0;
static int _piece;
};
// class of tetrahedrons
class Tetrahedron : public Regular
{
public:
Tetrahedron(double size);
~Tetrahedron();
static int piece() { return _piece; }
protected:
double multiplier() const override { return _multiplier; }
private:
constexpr static double _multiplier = 1.41421 / 12.0;
static int _piece;
};
// class of octahedron
class Octahedron : public Regular
{
public:
Octahedron(double size);
~Octahedron();
static int piece() { return _piece; }
protected:
double multiplier() const override { return _multiplier; }
private:
constexpr static double _multiplier = 1.41421 / 3.0;
static int _piece;
};
// class of abstract prismatic
class Prismatic : public Shape{
public:
~Prismatic ();
double volume() const override;
static int piece() { return _piece; }
protected:
Prismatic(double size, double height);
virtual double basis() const = 0;
double _height;
private:
static int _piece;
};
// class of cylinders
class Cylinder : public Prismatic
{
public:
Cylinder(double size, double height);
~Cylinder();
static int piece() { return _piece; }
protected:
double basis() const override;
private:
static int _piece;
};
// class of squarePrisms
class SquarePrism : public Prismatic
{
public:
SquarePrism (double size, double height);
~SquarePrism ();
static int piece() { return _piece; }
protected:
double basis() const override;
private:
static int _piece;
};
// class of triangularPrisms
class TriangularPrism : public Prismatic
{
public:
TriangularPrism (double size, double height);
~TriangularPrism ();
static int piece() { return _piece; }
protected:
double basis() const override;
private:
static int _piece;
};
// class of abstract conicals
class Conical : public Prismatic
{
public:
~Conical();
double volume() const override;
static int piece() { return _piece; }
protected:
Conical(double size, double height);
private:
static int _piece;
};
// class of cones
class Cone : public Conical
{
public:
Cone(double size, double height);
~Cone();
static int piece() { return _piece; }
protected:
double basis() const override;
private:
static int _piece;
};
// class of squarePyramids
class SquarePyramid : public Conical
{
public:
SquarePyramid(double size, double height);
~SquarePyramid();
static int piece() { return _piece; }
protected:
double basis() const override;
private:
static int _piece;
};
| true |
19bcea45716861d5334a1b8da201356ba1a137b1 | C++ | nievesnu/ED | /DOMJUDGE/Ejercicio 53/ListaIntercambia.h | ISO-8859-2 | 881 | 2.84375 | 3 | [] | no_license | //lvaro Miguel Rodrguez Mateos
//A63
#ifndef ListaIntercambia_h
#define ListaIntercambia_h
#include <iostream>
#include "queue_eda.h"
template <class T>
class ListaIntercambia : public queue<T> {
using Nodo = typename queue<T>::Nodo;
public:
void intercambia() {
Nodo* actual = this->prim, * aux = nullptr;
int elem = 0;
Nodo* sig = actual->sig;
while (actual != nullptr) {
if (actual->sig != nullptr) {
elem = actual->elem;
actual->elem = actual->sig->elem;
actual->sig->elem = elem;
actual = actual->sig->sig;
}
else {
actual = nullptr;
}
}
}
friend std::ostream& operator<<(std::ostream& output, ListaIntercambia<T>& lista) {
for (size_t i = 0; i < lista.size(); i++) {
int temp = lista.front();
output << temp << " ";
lista.push(temp);
lista.pop();
}
return output;
}
};
#endif /* ListaIntercambia_h */ | true |
bfc1ccbbf85b9cd2ecfc9fdd175e9b1412cb3eb0 | C++ | zahidabasher/leapfrog-triejoin | /src/globalFunctions/globalFunctions.h | UTF-8 | 1,774 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | /*******************************************************************
Database Systems Implementation Exam 2013
Copyright 2013 - Candidate Number 152051 - , University of Oxford
*******************************************************************/
#ifndef GLOBAL_FUNCTIONS_H
#define GLOBAL_FUNCTIONS_H
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
typedef enum STATUS {FAIL=0, OK=1} STATUS; // error codes
using namespace std;
struct TwoIntVectors{ // obsolete
vector<string> list1;
vector<int> list2;
};
struct PARTITION { // stores a complete partition
vector<vector<int> > rows;
vector<string> colnames;
};
vector<string> explode(string str, char ch); // various string and number manipulation functions
vector<string> explodeTrim(string str, char ch);
string implode(vector<string> vec, char ch);
string pathStem(string filePath);
int stringToInt(string input, bool &isValid);
vector<int> explodeToInt(string str, char ch, bool &isValid);
string implodeFromInt(vector<int> vec, char ch);
std::string <rim(std::string &s); // get rid of whitespaces at end or beginning of string
std::string &rtrim(std::string &s);
std::string &trim(std::string &s);
std::vector<string> removeFromVectorByIndexVector(vector<string>& data, vector<int>& indicesToDelete/* can't assume copy elision, don't pass-by-value */);
std::vector<int> removeFromVectorByIndexVector(vector<int>& data, vector<int>& indicesToDelete/* can't assume copy elision, don't pass-by-value */);
void printArray(vector<string> *array); // for debug purposes
void printArray(vector<int> *array);
void printArray(vector<string> array);
void printArray(vector<int> array);
int ZeroIfNegative(int arg);
#endif
| true |
ed3180b1f57ee9baf955b3056e2eb29bc78162db | C++ | UltiXstorm/TowerForce | /src/sfml/Message.cpp | UTF-8 | 1,940 | 3.078125 | 3 | [] | no_license | #include "Message.h"
////////////////////////////////////////////////////////////////////////////////////////
// Constructeurs et Destructeur //
////////////////////////////////////////////////////////////////////////////////////////
Message::Message() {
}
Message::~Message() {
}
////////////////////////////////////////////////////////////////////////////////////////
// Autres fonctions //
////////////////////////////////////////////////////////////////////////////////////////
void Message::initialisation(const sf::Font &font, const std::string txt, uint taille, const sf::Color couleur, const sf::Vector2f position, const bool encadre) {
//initialisation des paramètres de base
texte.setFont(font);
texte.setCharacterSize(taille);
texte.setString(txt);
#ifdef __unix__
texte.setColor(couleur);
#else
texte.setFillColor(couleur);
#endif
//Si le texte doit être encadré
if(encadre)
{
// Récupère la taille du texte affiché
sf::FloatRect r = texte.getLocalBounds();
// Positionne le texte au milieu de l'écran de jeu
float x = ((HAUTEUR - r.width) / 2)-28;
float y = ((LARGEUR - r.height) / 2)+32;
texte.setPosition(x, y);
// Définition du rectangle noir composant le fond pour afficher le texte
cadre.setSize(sf::Vector2f(r.width + 18, r.height + 22));
cadre.setPosition(sf::Vector2f(x - 8, y - 22));
cadre.setFillColor(sf::Color(0, 0, 0, 170));
}
else
{
//Cadre hors de la zone affichée à l'écran
cadre.setPosition(sf::Vector2f(-100,-100));
texte.setPosition(position);
}
}
void Message::dessiner(sf::RenderWindow &fenetre) const {
//Affichage des composants d'un message
fenetre.draw(cadre);
fenetre.draw(texte);
}
| true |
94dca5f77348d5e57af8079795ebcf7555b3809e | C++ | SachinMeier/Contacts | /main.cpp | UTF-8 | 8,588 | 2.8125 | 3 | [] | no_license | #include "main.h"
#include <functional>
const int TESTS = 10;
bool runTests(int);
int main(int argc, const char * argv[]){
People ppl;
ppl.read("tests/test.fcc", false);
cout << ppl.size() << endl;
ppl.print();
// int passed = 0, failed = 0, taken = TESTS;
// string fails = "";
// if(argc == 1){
// for(int i = 0; i < TESTS; i++){
// if(runTests(i)){
// fails += " " + to_string(i);
// failed++;
// }
// else{
// passed++;
// }
// }
// }
// else{
// taken = 0;
// // if(!strncmp(argv[1], "-e", 2)){
// // for(int i = stoi(argv[2]); i < TESTS; i++){
// // if(runTests(i)){
// // fails += " " + to_string(i);
// // }
// // }
// // }
// // else{
// for(int i = 1; i < argc; i++){
// if(runTests(stoi(argv[i]))){
// fails += " " + to_string(i);
// failed++;
// }
// else{
// passed++;
// }
// taken++;
// }
// // }
// }
// cout << "======== TEST SUMMARY =========" << endl;
// cout << " Tests: " << taken << endl;
// cout << " Passed: " << passed << endl;
// cout << " Failed: " << failed << endl;
// cout << " Percent: " << (double)passed/(double)taken << endl;
// cout << "\n Fails: " << fails << endl;
// cout << "===============================" << endl;
return 0;
}
bool runTests(int test){
switch(test){
case 0:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // Constructor and Destructor
case 1:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.in", true);
if(ppl.size() != 4){
cout << "FAIL - sz=" << ppl.size() << endl;
fail = true;
}
ppl.print();
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // Read, size and print
case 2:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.in", true);
ppl.write(cout);
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // read and write(cout)
case 3:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.in", true);
ppl.write("tests/test.out", true);
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // read and write(text)
case 4:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.in", true);
ppl.write("tests/test.fcc");
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // read and write(fcc)
case 5:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.in", true);
ppl.write("tests/test.fcc", false);
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
try{
People p2;
p2.read("tests/test.fcc", false);
p2.print();
if(p2.size() != 5){
cout << "FAIL - sz: " << to_string(p2.size()) << endl;
fail = true;
}
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // read, write(fcc), and read(fcc)
case 6:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl, p2;
ppl.read("tests/test.in", true);
ppl.write("tests/test.out", true);
p2.read("tests/test.out", true);
if(ppl.size() != p2.size()){
cout << "FAIL - sz: " << to_string(p2.size()) << " vs. " << to_string(ppl.size()) << endl;
fail = true;
}
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // read, write(text), and read(text)
case 7:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.fcc");
Person* arr = ppl.toArray();
for(int i =0; i < 4; i++){
arr[i].write();
}
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // toArray
case 8:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
Person p;
fstream in("tests/test2.in");
p.read(in);
cout << p << endl;
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // Person read
case 9:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People p;
fstream in("tests/test.in");
p.read(in);
People p2(p);
p.print();
cout << "PASS" << endl;
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // Copy Constructor
case 10:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People p;
p.read("tests/test.in", true);
p.write_index("tests/index.txt");
Person me = *(p.find("Sachin Meier,", "tests/index.txt"));
cout << me << endl;
}
catch(exception &e){
cout << "FAIL - error: " << e.what() << endl;
fail = true;
}
return fail;
break;
} // find
case 100:{
cout << "-----Test " << test << "-----" << endl;
bool fail = false;
try{
People ppl;
ppl.read("tests/test.in", true);
Person p;
fstream in("tests/test2.in");
p.read(in);
p.write(cout);
in.close();
cout << "Adding..." << endl;
//ppl.add(&p);
if(ppl.size() != 4){
cout << "FAIL - sz: " << to_string(ppl.size()) << endl;
fail = true;
}
else{
cout << "PASS - sz" << endl;
}
ppl.print();
}
catch(...){
cout << "FAIL - error" << endl;
fail = true;
}
return fail;
break;
} // add
}
} | true |
0f14fb65b0f08705bdc457267e5f7c7ae2fa1f38 | C++ | tangsancai/algorithm | /PAT-A/1067. Sort with Swap.cpp | UTF-8 | 577 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
using namespace std;
int num[100005];
int main()
{
int N;
int tag=1;
int step=0;
int number=0;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%d",&num[i]);
if(num[i]==i)
number++;
}
while(number!=N)
{
if(num[0]==0)
{
for(int i=tag;i<N;i++)
{
if(num[i]!=i)
{
swap(num[0],num[i]);
tag=i;
break;
}
}
number--;
step++;
}
swap(num[num[0]],num[num[num[0]]]);
step++;
number++;
if(num[0]==0)
number++;
}
printf("%d",step);
} | true |
db276831ad10ecc3320eae6c9e33aaa9db4859d0 | C++ | JPTIZ/fuzzytruck | /tools/socket/test.cpp | UTF-8 | 813 | 2.8125 | 3 | [] | no_license | #include "socket.h"
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std::string_literals;
auto parse_args(int argc, char* _argv[]) {
auto args = std::map{
std::pair
{"host"s, std::string(_argv[1])},
{"port"s, std::string(_argv[2])},
};
return args;
}
void show_usage(const std::string& exec_name) {
std::cout << "Usage: " << exec_name << " <host> <port>\n";
}
int main(int argc, char* argv[]) {
if (argc < 3) {
show_usage(argv[0]);
return -1;
}
auto args = parse_args(argc, argv);
auto socket = net::Socket{
args["host"s],
std::uint16_t(std::stoi(args["port"s]))
};
socket.send("1\r\n");
socket.send("1\r\n");
socket.send("-1\r\n");
socket.send("1\r\n");
}
| true |
00cefe56a32ca56b45d4e8da2c95a0443092c919 | C++ | Phytolizer/vktut | /Include/vktut/vulkan/instance.hpp | UTF-8 | 2,695 | 3 | 3 | [] | no_license | #pragma once
#include <array>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
namespace vktut::vulkan
{
struct instance
{
private:
VkInstance m_handle;
public:
template<std::size_t N>
instance(const std::string& application_name,
bool enable_validation_layers,
const std::array<const char*, N>& validation_layers);
~instance();
instance(const instance&) = delete;
instance& operator=(const instance&) = delete;
instance(instance&&) = default;
instance& operator=(instance&&) = default;
VkInstance get();
private:
static std::vector<const char*> get_required_extensions(
bool enable_validation_layers);
};
template<std::size_t N>
inline instance::instance(const std::string& application_name,
bool enable_validation_layers,
const std::array<const char*, N>& validation_layers)
// initialized by vkCreateInstance()
: m_handle(nullptr)
{
VkApplicationInfo app_info = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pApplicationName = application_name.c_str(),
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "No Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_0,
};
VkInstanceCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pApplicationInfo = &app_info,
};
std::vector<const char*> glfw_extensions =
get_required_extensions(enable_validation_layers);
create_info.enabledExtensionCount = glfw_extensions.size();
create_info.ppEnabledExtensionNames = glfw_extensions.data();
if (enable_validation_layers) {
create_info.enabledLayerCount =
static_cast<std::uint32_t>(validation_layers.size());
create_info.ppEnabledLayerNames = validation_layers.data();
} else {
create_info.enabledLayerCount = 0;
}
std::uint32_t extension_count = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, nullptr);
std::vector<VkExtensionProperties> extensions;
extensions.resize(extension_count);
vkEnumerateInstanceExtensionProperties(
nullptr, &extension_count, extensions.data());
std::cout << "[vktut::vulkan::instance::instance()] available extensions:\n";
for (const auto& extension : extensions) {
std::cout << "\t" << static_cast<const char*>(extension.extensionName)
<< "\n";
}
VkResult result = vkCreateInstance(&create_info, nullptr, &m_handle);
if (result != VK_SUCCESS) {
throw std::runtime_error {"failed to create instance!"};
}
}
} // namespace vktut::vulkan
| true |
69375ad73ba771241da2c8fd28312faafed3448a | C++ | eyhl/issm | /trunk/src/c/classes/Contours.h | UTF-8 | 1,097 | 3.015625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | /*!\brief Declaration of Contours class.
*/
#ifndef _CONTAINER_CONTOURS_H_
#define _CONTAINER_CONTOURS_H_
#include "../datastructures/datastructures.h"
#include "./Contour.h"
class Contours: public DataSet{
public:
/*constructors, destructors*/
Contours();
~Contours();
};
/*Methods that relate to datasets: */
int ExpWrite(Contours* contours,char* domainname);
template <class doubletype> Contours* ExpRead(char* domainname){ /*{{{*/
/*intermediary: */
int nprof;
int *profnvertices = NULL;
doubletype **pprofx = NULL;
doubletype **pprofy = NULL;
/*output: */
Contours *domain = NULL;
/*If domainname is an empty string, return empty dataset*/
if (strcmp(domainname,"")==0){
nprof=0;
}
else{
ExpRead(&nprof,&profnvertices,&pprofx, &pprofy, NULL,domainname);
}
/*now create dataset of contours: */
domain=new Contours();
for(int i=0;i<nprof;i++){
domain->AddObject(new Contour<doubletype>(i,profnvertices[i],pprofx[i],pprofy[i],1));
}
return domain;
} /*}}}*/
#endif //ifndef _CONTOURS_H_
| true |
7022b343b206e81626d1b5037e0ca944eb453849 | C++ | wangshiy/cc | /Generate_Pascal_Triangle.cpp | UTF-8 | 1,096 | 3.9375 | 4 | [] | no_license | /*
Problem:
**********************************************************************************
*
* Given numRows, generate the first numRows of Pascal's triangle.
*
* For example, given numRows = 5,
* Return
*
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
*
*
**********************************************************************************
*/
#include<vector>
#include<iostream>
using namespace std;
vector<vector<int>> Generate(int row)
{
vector<vector<int>> Pascal;
for(int i=0; i<row; i++)
{
vector<int> v;
if(i==0)
{
v.push_back(1);
}
else
{
v.push_back(1);
for(int j=0; j<Pascal[i-1].size()-1; j++)
{
int temp = Pascal[i-1][j] + Pascal[i-1][j+1];
v.push_back(temp);
}
v.push_back(1);
}
Pascal.push_back(v);
}
return Pascal;
}
int main()
{
vector<vector<int>> test;
int n = 3;
test = Generate(n);
cout << test[0][0] << endl;
cout << test[1][0] << endl;
cout << test[1][1] << endl;
cout << test[2][0] << endl;
cout << test[2][1] << endl;
cout << test[2][2] << endl;
return 0;
}
| true |
d12dc95533e6c89d9bb2dc4d6f6e68d55e3d64d1 | C++ | ChenFan1995/C-Programming-1 | /Assignments/week8/q5.cpp | UTF-8 | 257 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <iomanip>
int main(){
int n,i;
cin >> n;
int a,b;
i = 10;
while (i<n){
a = i / 10;
b = i % 10;
if (i % (a+b) == 0) cout << i << endl;
i = i + 1;
}
} | true |
4429b694a79e7b415a6d619c66312cbc07840138 | C++ | Manasvi070902/Problem-Solving | /magicsquare.cpp | UTF-8 | 1,272 | 2.921875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Complete the formingMagicSquare function below.
int formingMagicSquare(vector<vector<int>> s) {
int d[8][3][3]={
{{8,1,6},{3,5,7},{4,9,2}},
{{6,1,8},{7,5,3},{2,9,4}},
{{4,9,2},{3,5,7},{8,1,6}},
{{2,9,4},{7,5,3},{6,1,8}},
{{8,3,4},{1,5,9},{6,7,2}},
{{4,3,8},{9,5,1},{2,7,6}},
{{6,7,2},{1,5,9},{8,3,4}},
{{2,7,6},{9,5,1},{4,3,8}}
};
int c[8],min;
for(int k=0;k<8;k++)
{
c[k] = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(s[i][j]!=d[k][i][j])
{
c[k]+=abs(s[i][j]-d[k][i][j]);
}
}
}
}
min = c[0];
for(int i=1;i<8;i++){
if(c[i]<min)
{
min=c[i];
}
}
return min;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
vector<vector<int>> s(3);
for (int i = 0; i < 3; i++) {
s[i].resize(3);
for (int j = 0; j < 3; j++) {
cin >> s[i][j];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int result = formingMagicSquare(s);
fout << result << "\n";
fout.close();
return 0;
}
| true |
27e738ca13ad9c38de36d19038a5c592b9501bbc | C++ | colinhp/WangdaoCPP | /20170731/work/queue.cc | UTF-8 | 3,109 | 3.5625 | 4 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
template <typename T>
class Queue
{
public:
Queue(int size = 10)
:_front(0)
,_back(0)
,_maxSize(size + 1)
,_qu(new T[size + 1]())
{}
~Queue()
{
if(_qu != NULL)
{
delete [] _qu;
_qu = NULL;
}
}
bool full() const;
bool empty() const;
void push(T member);
void pop();
T & front() const;
T & back() const;
private:
int _front;
int _back;
int _maxSize;
T *_qu;
};
template <typename T>
bool Queue<T>::full() const
{
if(((_back + 1)%_maxSize) == _front)
{
cout << "ERROR!queue is full"<<endl;
return true;
}else
return false;
}
template <typename T>
bool Queue<T>::empty() const
{
if(_front == _back)
{
cout<<"ERROR!queue is empty"<<endl;
return true;
}else
return false;
}
template <typename T>
void Queue<T>::push(T member)
{
if(full())
exit(-1);
else
{
_qu[_back] = member;
_back = (_back + 1) % _maxSize;
}
}
template <typename T>
void Queue<T>::pop()
{
if(empty())
exit(-1);
else
{
_front = (_front + 1) % _maxSize;
}
}
template <typename T>
T & Queue<T>::front() const
{
if(empty())
exit(-1);
else
return _qu[_front];
}
template <typename T>
T & Queue<T>::back() const
{
if(empty())
exit(-1);
else
return _qu[(_back -1 + _maxSize) % _maxSize];
}
void test0()
{
Queue<int> que(4);
que.push(1);
que.push(2);
que.push(3);
que.push(4);
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.pop();
cout<<"pop()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.pop();
cout<<"pop()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push(5);
cout<<"push()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.pop();
cout<<"pop()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push(6);
cout<<"push()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push(7);
cout<<"push()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push(8);
cout<<"push()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
}
void test1()
{
Queue<string> que(4);
que.push("hello");
que.push("world");
que.push("shenzhen");
que.push("wangdao");
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.pop();
cout<<"pop()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.pop();
cout<<"pop()"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push("aaa");
cout<<"push(aaa)"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push("bbb");
cout<<"push(bbb)"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
que.push("ccc");
cout<<"push(ccc)"<<endl;
cout<<"front = "<<que.front()<<endl;
cout<<"back = "<<que.back()<<endl;
}
int main(void)
{
test1();
return 0;
}
| true |
741f2b5140c9a11a6d6a80de0850bb50116d8674 | C++ | PolandBall133/SprotxEngine | /include/game/example_fun/snake/snake.hpp | UTF-8 | 726 | 2.671875 | 3 | [] | no_license | #pragma once
#include <vector>
#include "game_core/helpers/mapping_keyboard_handler.hpp"
#include "limiter.hpp"
enum class Way{
none,
up = 1, down = -1,
left = 2, right = -2
};
class Snake{
public:
using BodySegment = struct{ int x, y; };
using Body = std::vector<BodySegment>;
public:
Snake(const Body &body_segments, Way dir, Limiter limiter);
const BodySegment &head() const;
BodySegment &head();
const Body &get_body() const;
void move();
void grow();
void set_direction(Way);
private:
Way direction;
Body body;
Limiter limit;
};
struct SnakeInputHandler{
Snake &snake;
MappingKeyboardHandler keyboard_handler;
SnakeInputHandler(Snake &s);
}; | true |
f14bf133720ab6baf11c6ee5d8edf33f5f413920 | C++ | hogdahl/udptcp | /udptcp/src/UdpSocket.h | UTF-8 | 1,245 | 2.859375 | 3 | [] | no_license | /*
* UdpSocket.h
*
* Created on: Sep 5, 2013
* Author: johan
*/
#ifndef UDPSOCKET_H_
#define UDPSOCKET_H_
#include <netdb.h>
#include "FdList.h"
#include "Buffer.h"
class UdpSocket: public FdList {
public:
struct sockaddr_in si_from;
struct sockaddr_in si_to;
int _som;
int _eom;
Buffer buffer;
public:
UdpSocket();
virtual ~UdpSocket();
virtual const char * className(){ return "UdpSocket"; }
/**
* do something on timeout
*/
virtual void timeout(){
buffer.flush();
};
/** Callback from poll loop when event is triggered
* @returns false if work is done and should be deleted
*/
virtual bool eventHandler(pollfd * pfd);
/** Send a message
* sender is responsible for trashing message after use ( or reuse )
*/
virtual void msgHandler(Message * msg);
/**
* Set up this socket for receiving
*/
void setup(const char * localAddress, int port);
/**
* Set up a destination
*/
bool setDestination(const char * address, int port);
/**
* Write to socket or fd
* @param data to write
* @param len length of data
*/
virtual int write(char * data, int len);
void setSom(int som){
_som = som;
}
void setEom(int eom){
_eom = eom;
}
};
#endif /* UDPSOCKET_H_ */
| true |
ba51a569d2665cf5c151ff0727c0873d46023492 | C++ | Seanb19/BrainGrid | /DynamicSpikingSynapse.cpp | UTF-8 | 9,549 | 2.734375 | 3 | [] | no_license | /**
** \file DynamicSpikingSynapse.cpp
**
** \authors Allan Ortiz & Cory Mayberry
**
** \brief A dynamic spiking synapse (Makram et al (1998))
**/
#include "DynamicSpikingSynapse.h"
/**
* Create a synapse and initialize all internal state vars according to the synapse type.
* @post The synapse is setup according to parameters.
* @param[in] source_x The location(x) of the synapse.
* @param[in] source_y The location(y) of the synapse.
* @param[in] sumX The coordinates(x) of the summation point.
* @param[in] sumY The coordinates(y) of the summation point.
* @param[in] delay The synaptic transmission delay (sec).
* @param[in] new_deltaT The time step size (sec).
* @param[in] s_type Synapse type.
*/
DynamicSpikingSynapse::DynamicSpikingSynapse(int source_x, int source_y,
int sumX, int sumY,
FLOAT& sum_point,
FLOAT delay, FLOAT new_deltaT,
synapseType s_type) :
summationPoint( sum_point ),
deltaT( new_deltaT ),
W( 10.0e-9 ),
psr( 0.0 ),
decay(0),
total_delay( static_cast<int>( delay / new_deltaT )),
tau( DEFAULT_tau ),
r( 1.0 ),
u(0),
D( 1.0 ),
U( DEFAULT_U ),
F( 0.01 ),
lastSpike( ULONG_MAX )
{
synapseCoord.x = source_x;
synapseCoord.y = source_y;
summationCoord.x = sumX;
summationCoord.y = sumY;
type = s_type;
switch (type) {
case II:
U = 0.32;
D = 0.144;
F = 0.06;
tau = 6e-3;
delay = 0.8e-3;
break;
case IE:
U = 0.25;
D = 0.7;
F = 0.02;
tau = 6e-3;
delay = 0.8e-3;
break;
case EI:
U = 0.05;
D = 0.125;
F = 1.2;
tau = 3e-3;
delay = 0.8e-3;
break;
case EE:
U = 0.5;
D = 1.1;
F = 0.05;
tau = 3e-3;
delay = 1.5e-3;
break;
default:
assert( false );
}
// calculate the discrete delay (time steps)
FLOAT tmpFLOAT = ( delay / new_deltaT); //needed to be done in 2 lines or may cause incorrect results in linux
total_delay = static_cast<int> (tmpFLOAT) + 1;
// initialize spike queue
initSpikeQueue();
reset( );
}
DynamicSpikingSynapse::~DynamicSpikingSynapse() {
}
/**
* Creates a synapse and initialize all internal state vars according to the source synapse.
* @post The synapse is setup according to the state of the source synapse.
* @param[in] other The source synapse.
*/
DynamicSpikingSynapse::DynamicSpikingSynapse(const DynamicSpikingSynapse &other) :
summationPoint( other.summationPoint ), summationCoord( other.summationCoord ), synapseCoord( other.synapseCoord ),
deltaT( other.deltaT ), W( other.W ), psr( other.psr ), decay( other.decay ), total_delay( other.total_delay ),
delayIdx( other.delayIdx ), ldelayQueue( other.ldelayQueue ), type( other.type ),
tau( other.tau ), r( other.r ), u( other.u ), D( other.D ), U( other.U ), F( other.F ), lastSpike(
other.lastSpike ) {
delayQueue[0] = other.delayQueue[0];
}
/**
* Reconstruct self using placement new and copy constructor.
* @param[in] rhs Overloaded = operator.
*/
DynamicSpikingSynapse& DynamicSpikingSynapse::operator=(const DynamicSpikingSynapse & rhs) {
if (this == &rhs) // avoid aliasing
return *this;
this->~DynamicSpikingSynapse( ); // destroy self
new ( this ) DynamicSpikingSynapse( rhs ); //reconstruct self using placement new and copy constructor
return *this;
}
/**
* Reset time varying state vars and recompute decay.
*/
void DynamicSpikingSynapse::reset() {
psr = 0.0;
assert( updateInternal() );
u = DEFAULT_U;
r = 1.0;
lastSpike = ULONG_MAX;
}
/**
* Add an input spike event to the queue.
*/
void DynamicSpikingSynapse::preSpikeHit() {
// add an input spike event to the queue
addSpikeQueue();
}
/**
* If an input spike is in the queue, adjust synapse parameters, calculate psr.
* Decay the post spike response(psr), and apply it to the summation point.
*/
void DynamicSpikingSynapse::advance() {
// is an input in the queue?
if (isSpikeQueue()) {
// adjust synapse paramaters
if (lastSpike != ULONG_MAX) {
FLOAT isi = (g_simulationStep - lastSpike) * deltaT ;
r = 1 + ( r * ( 1 - u ) - 1 ) * exp( -isi / D );
u = U + u * ( 1 - U ) * exp( -isi / F );
}
psr += ( ( W / decay ) * u * r );// calculate psr
lastSpike = g_simulationStep; // record the time of the spike
}
// decay the post spike response
psr *= decay;
// and apply it to the summation point
#ifdef USE_OMP
#pragma omp atomic
#endif
summationPoint += psr;
#ifdef USE_OMP
//PAB: atomic above has implied flush (following statement generates error -- can't be member variable)
//#pragma omp flush (summationPoint)
#endif
}
/**
* Recompute decay.
* @return true if success.
*/
bool DynamicSpikingSynapse::updateInternal() {
if (tau > 0) {
decay = exp( -deltaT / tau );
return true;
}
return false;
}
/**
* Clear events in the queue, and initialize the queue.
*/
void DynamicSpikingSynapse::initSpikeQueue()
{
size_t size = total_delay / ( sizeof(uint8_t) * 8 ) + 1;
assert( size <= BYTES_OF_DELAYQUEUE );
delayQueue[0] = 0;
delayIdx = 0;
ldelayQueue = LENGTH_OF_DELAYQUEUE;
}
/**
* Add an input spike event to the queue according to the current index and delay.
*/
void DynamicSpikingSynapse::addSpikeQueue()
{
// calculate index where to insert the spike into delayQueue
int idx = delayIdx + total_delay;
if ( idx >= ldelayQueue )
idx -= ldelayQueue;
// set a spike
assert( !(delayQueue[0] & (0x1 << idx)) );
delayQueue[0] |= (0x1 << idx);
}
/**
* Check if there is an input spike in the queue.
* @post The queue index is incremented.
* @return true if there is an input spike event.
*/
bool DynamicSpikingSynapse::isSpikeQueue()
{
bool r = delayQueue[0] & (0x1 << delayIdx);
delayQueue[0] &= ~(0x1 << delayIdx);
if ( ++delayIdx >= ldelayQueue )
delayIdx = 0;
return r;
}
/**
* Write the synapse data to the stream
* @param[in] os The filestream to write
*/
void DynamicSpikingSynapse::write( ostream& os ) {
os.write( reinterpret_cast<const char*>(&summationCoord), sizeof(summationCoord) );
os.write( reinterpret_cast<const char*>(&synapseCoord), sizeof(synapseCoord) );
os.write( reinterpret_cast<const char*>(&deltaT), sizeof(deltaT) );
os.write( reinterpret_cast<const char*>(&W), sizeof(W) );
os.write( reinterpret_cast<const char*>(&psr), sizeof(psr) );
os.write( reinterpret_cast<const char*>(&decay), sizeof(decay) );
os.write( reinterpret_cast<const char*>(&total_delay), sizeof(total_delay) );
os.write( reinterpret_cast<const char*>(delayQueue), sizeof(uint32_t) );
os.write( reinterpret_cast<const char*>(&delayIdx), sizeof(delayIdx) );
os.write( reinterpret_cast<const char*>(&ldelayQueue), sizeof(ldelayQueue) );
os.write( reinterpret_cast<const char*>(&type), sizeof(type) );
os.write( reinterpret_cast<const char*>(&tau), sizeof(tau) );
os.write( reinterpret_cast<const char*>(&r), sizeof(r) );
os.write( reinterpret_cast<const char*>(&u), sizeof(u) );
os.write( reinterpret_cast<const char*>(&D), sizeof(D) );
os.write( reinterpret_cast<const char*>(&U), sizeof(U) );
os.write( reinterpret_cast<const char*>(&F), sizeof(F) );
os.write( reinterpret_cast<const char*>(&lastSpike), sizeof(lastSpike) );
}
/**
* Read the synapse data from the stream
* @param[in] os The filestream to read
*/
void DynamicSpikingSynapse::read( istream& is, FLOAT* pSummationMap, int width, vector<DynamicSpikingSynapse>* pSynapseMap ) {
Coordinate t_summationCoord, t_synapseCoord;
FLOAT t_deltaT, t_W, t_psr, t_decay, t_tau, t_r, t_u, t_D, t_U, t_F;
int t_total_delay, t_delayIdx, t_ldelayQueue;
uint32_t t_delayQueue[1];
uint64_t t_lastSpike;
synapseType t_type;
is.read( reinterpret_cast<char*>(&t_summationCoord), sizeof(t_summationCoord) );
is.read( reinterpret_cast<char*>(&t_synapseCoord), sizeof(t_synapseCoord) );
is.read( reinterpret_cast<char*>(&t_deltaT), sizeof(t_deltaT) );
is.read( reinterpret_cast<char*>(&t_W), sizeof(t_W) );
is.read( reinterpret_cast<char*>(&t_psr), sizeof(t_psr) );
is.read( reinterpret_cast<char*>(&t_decay), sizeof(t_decay) );
is.read( reinterpret_cast<char*>(&t_total_delay), sizeof(t_total_delay) );
is.read( reinterpret_cast<char*>(t_delayQueue), sizeof(uint32_t) );
is.read( reinterpret_cast<char*>(&t_delayIdx), sizeof(t_delayIdx) );
is.read( reinterpret_cast<char*>(&t_ldelayQueue), sizeof(t_ldelayQueue) );
is.read( reinterpret_cast<char*>(&t_type), sizeof(t_type) );
is.read( reinterpret_cast<char*>(&t_tau), sizeof(t_tau) );
is.read( reinterpret_cast<char*>(&t_r), sizeof(t_r) );
is.read( reinterpret_cast<char*>(&t_u), sizeof(t_u) );
is.read( reinterpret_cast<char*>(&t_D), sizeof(t_D) );
is.read( reinterpret_cast<char*>(&t_U), sizeof(t_U) );
is.read( reinterpret_cast<char*>(&t_F), sizeof(t_F) );
is.read( reinterpret_cast<char*>(&t_lastSpike), sizeof(t_lastSpike) );
// locate summation point
FLOAT* sp = &(pSummationMap[t_summationCoord.x + t_summationCoord.y * width]);
// create synapse
DynamicSpikingSynapse syn(t_synapseCoord.x, t_synapseCoord.y, t_summationCoord.x, t_summationCoord.y, *sp, DEFAULT_delay_weight, t_deltaT, t_type);
// copy read values
syn.W = t_W;
syn.psr = t_psr;
syn.decay = t_decay;
syn.total_delay = t_total_delay;
syn.delayQueue[0] = t_delayQueue[0];
syn.delayIdx = t_delayIdx;
syn.ldelayQueue = t_ldelayQueue;
syn.tau = t_tau;
syn.r = t_r;
syn.u = t_u;
syn.D = t_D;
syn.U = t_U;
syn.F = t_F;
syn.lastSpike = t_lastSpike;
pSynapseMap[t_synapseCoord.x + t_synapseCoord.y * width].push_back(syn);
}
| true |
81e7a3feece2cfbefb3362f67bfbcb72e815b3ef | C++ | okalitova/RayTracing | /scene/Screen.h | UTF-8 | 1,552 | 2.9375 | 3 | [] | no_license | //
// Created by okalitova on 16.04.16.
//
#ifndef RAYTRACING_SCREEN_H
#define RAYTRACING_SCREEN_H
#include "../geometry/Geometry.h"
class Screen {
public:
int getHeight() const {
return height;
}
void setHeight(int height) {
Screen::height = height;
}
int getWidth() const {
return width;
}
void setWidth(int width) {
Screen::width = width;
}
const Vector &getLeft_down() const {
return left_down;
}
void setLeft_down(const Vector &left_down) {
Screen::left_down = left_down;
}
const Vector &getLeft_up() const {
return left_up;
}
void setLeft_up(const Vector &left_up) {
Screen::left_up = left_up;
}
const Vector &getRight_down() const {
return right_down;
}
void setRight_down(const Vector &right_down) {
Screen::right_down = right_down;
}
const Vector &getRight_up() const {
return right_up;
}
void setRight_up(const Vector &right_up) {
Screen::right_up = right_up;
}
private:
int height;
int width;
Vector left_down, left_up, right_down, right_up;
public:
Screen();
Screen(int init_width, int init_height, Vector init_left_down, Vector init_left_up,
Vector init_right_down, Vector init_right_up);
double getCellWidth() {
return ((right_up - left_up).length() / width);
}
double getCellHeight() {
return ((left_up - left_down).length() / height);
}
};
#endif //RAYTRACING_SCREEN_H
| true |
e194e62d591b4e0936338d57d684f33ce6f4f211 | C++ | ahmedelsaie/AlgorithmsProblems | /UVA/1350 - Pinary.cpp | UTF-8 | 1,227 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
#include <cstring>
#define MAX 38
long long fn(int curr, int before);
void trace(int with_me, int curr, int before);
int get_start();
long long dp[MAX + 5][2];
int x, cases, first;;
int main()
{
memset(dp, -1, sizeof(dp));
fn(MAX, 0);
scanf("%d", &cases);
while(cases--)
{
scanf("%d", &x);
x++;
first = get_start();
trace(0, first, 0);
printf("\n");
}
return 0;
}
int get_start()
{
for(int i = 0; i <= MAX; i++)
if(dp[i][0] >= x)
return i;
return -1;
}
void trace(int with_me, int curr, int before)
{
if(curr == 0)
return;
if(before == 1)
printf("0"), trace(with_me, curr - 1, 0);
else
{
long long zero = dp[curr - 1][0];
if(zero + with_me >= x)
printf("0"), trace(with_me, curr - 1, 0);
else
printf("1"), trace(with_me + zero, curr - 1, 1);
}
}
long long fn(int curr, int before)
{
long long& ret = dp[curr][before];
if(ret != -1)
return ret;
if(curr == 0)
return ret = 1;
ret = 0;
ret += fn(curr - 1, 0);
if(before != 1)
ret += fn(curr - 1, 1);
return ret;
}
| true |
712b7fe41dd3f935975d6eb3c84e7da6a2d53463 | C++ | touyou/CompetitiveProgramming | /aoj/1074.cpp | UTF-8 | 1,004 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef pair<int, string> P;
bool comp(const P& a, const P& b) {
if (a.first!=b.first) return a.first<b.first;
return a.second<b.second;
}
int main() {
int n;
while (scanf("%d",&n)) {
if (!n) break;
vector<string> cnt[31];
map<string, int> mp;
P po[n];
for (int i=0; i<n; i++) {
string name; cin>>name;
po[i]=P(0,name);
mp[name]=i;
int m; scanf("%d",&m);
for (int j=0; j<m; j++) {
int d; scanf("%d",&d);
cnt[d].push_back(name);
}
}
for (int i=0; i<31; i++) {
int sz=cnt[i].size();
int x=n-sz+1;
for (int j=0; j<sz; j++) {
po[mp[cnt[i][j]]].first+=x;
}
}
sort(po, po+n, comp);
cout<<po[0].first<<" "<<po[0].second<<endl;
}
} | true |
9345aad264c11ce941494ef4c52988c638cd9bf8 | C++ | JimmyDdotEXE/jpl | /src/value/Equation.cpp | UTF-8 | 230 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "value/Equation.h"
Equation::Equation(oper o, Num *l, Num *r){
op = o;
lhs = l;
rhs = r;
}
oper Equation::getOp(){
return op;
}
Num *Equation::getLeft(){
return lhs;
}
Num *Equation::getRight(){
return rhs;
}
| true |
a9b4e702de7a310cd81e57338daf3ac3791461d4 | C++ | CabernetSauvignon/OpenGL_3DScene | /main.cpp | WINDOWS-1251 | 4,605 | 2.515625 | 3 | [] | no_license | #pragma comment(lib, "glfw3.lib")
#pragma comment(lib, "opengl32.lib")
#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include <iostream>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "Scene.h"
#include "Camera.h"
#include "Projection.h"
//#include <windows.h>
// Nvidia
/*extern "C" {
_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
}*/
int HEIGHT = 720;
int WIDTH = 1280;
float deltaTime = 0.0f; //
float lastFrame = 0.0f; //
Camera camera;
float lastX = WIDTH / 2.0f;
float lastY = HEIGHT / 2.0f;
bool firstMouse = true;
Projection projection((float)WIDTH / (float)HEIGHT);
float _xpos = -8.5f;
float _zpos = -7.0f;
float _rotate = 45.0f;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void processInput(GLFWwindow* window);
int main()
{
// GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, " OpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return 1;
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
stbi_set_flip_vertically_on_load(true);
Scene scene;
glViewport(0, 0, WIDTH, HEIGHT);
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window))
{
//
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
//
processInput(window);
glClearColor(0.1f , 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
scene.drawScene(projection.getProjection(), camera.GetViewMatrix(), camera.GetPosition(), _xpos, _zpos, _rotate);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
_zpos -= 7.5f * deltaTime;
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
_zpos += 7.5f * deltaTime;
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
_xpos -= 7.5f * deltaTime;
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
_xpos += 7.5f * deltaTime;
if (glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS)
_rotate += 5.0f;
if (glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS)
_rotate -= 5.0f;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
WIDTH = width;
HEIGHT = height;
glViewport(0, 0, width, height);
projection.setProgection((float)WIDTH / (float)HEIGHT);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = (float)xpos;
lastY = (float)ypos;
firstMouse = false;
}
float xoffset = (float) xpos - lastX;
float yoffset = lastY - (float) ypos; // , y-
lastX = (float) xpos;
lastY = (float) ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
} | true |
f1a44682993153a05dfd9daf9a55fa3a090cb82a | C++ | akademi4eg/distri-net | /src/IDataReader.h | UTF-8 | 736 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <memory>
#include <vector>
typedef std::vector<double> DataEntry;
struct SDataKey
{
SDataKey(const std::string& fname = std::string(), uintmax_t idx = 0) : sSource(fname), iIndex(idx) {};
std::string toString() const {
return sSource + "\n" + std::to_string(iIndex);
};
std::string toPrettyString() const {
return sSource + "[index = " + std::to_string(iIndex) + "]";
};
std::string getFilename() const {return sSource + ":" + std::to_string(iIndex);}
std::string sSource;
uintmax_t iIndex;
};
class IDataReader
{
public:
virtual bool saveData(const SDataKey& key, const DataEntry& data) = 0;
virtual std::unique_ptr<DataEntry> loadData(const SDataKey& key) = 0;
virtual ~IDataReader() {};
};
| true |
209926d237b9e4ade7c12723c925f2207a3b29c3 | C++ | DKU-STUDY/Algorithm | /BOJ/2644.촌수계산/6047198844.cpp | UTF-8 | 763 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector <int> vt[101];
bool check[101];
int bfs(int x, int y) {
queue <int> q;
q.push(x);
check[x] = true;
int cnt = 0;
int q_size;
while (!q.empty()) {
q_size = q.size();
while (q_size--) {
int point = q.front();
q.pop();
int point_size = vt[point].size();
if (point == y)
return cnt;
for (int i = 0; i < point_size; i++) {
if (!check[vt[point][i]]) {
q.push(vt[point][i]);
check[vt[point][i]] = true;
}
}
}
cnt++;
}
return -1;
}
int main() {
int n;
cin >> n;
int a; int b;
cin >> a >> b;
int m;
cin >> m;
int x; int y;
while (m--) {
cin >> x >> y;
vt[x].push_back(y);
vt[y].push_back(x);
}
cout << bfs(a, b);
} | true |
3092f744224a3c9eda8ff2023105302bbd303951 | C++ | FannyGallais/Projet_3BiM | /gyllenberg.cpp | UTF-8 | 2,939 | 3.25 | 3 | [] | no_license | /*
-------------------------------------------------------------------------------------------------------------
Gyllenberg-Webb
-------------------------------------------------------------------------------------------------------------
dpc = [b - ro(tc)]*pc + ri(tc)*qc
dqc = ro(tc)*pc - [ri(tc) + mu]*qc
tc = pc + qc;
-------------------------------------------------------------------------------------------------------------
In this model, if mu = 0, quiescent cells and necrosed (dead) cells both fall under the 'quiescent' category
*/
#include <cstdio>
#include <math.h>
double ro_evaluate (double, double, double, double);
// function corresponding to the cell transformation rate from proliferent to quiescent
// params : total number of cells (variable of the function), b (growth factor) ; and alpha and teta from gompertz or verhulst model
double ri_evaluate (double); // function corresponding to the cell transformation rate from quiescent to proliferent
// params : total number of cells (variable of the function)
int main (int argc, char* argv[])
{
FILE* output;
output = fopen("gyllenberg.txt","w");
double ipc = 1; // initial number of proliferating cells
double iqc = 1; // initial number of quiescent cells
double itc = ipc + iqc; // initial total number of cells
double pc = ipc; // number of proliferating cells
double qc = iqc; // number of quiescent cells
double tc = pc + qc; // total number of cells
double dpc; // pc derivative
double dqc; // qc derivative
// implicit parameters if using gompertz or verhuslt as the ro function
double alpha = 0.1; // growth factor
double teta = 1000000; // maximum tumor size
double b; // effective growth factor (births - deaths)
double mu = 0; // death rate of quiescent cells (equals 0 if quiescent cells and necrosed (dead) cells both fall under the 'quiescent' category)
double step = 0.001;
double i;
double length = 80; // simulation length
// specific parameter initialization
// if using a gompertz model as the ro function
b = alpha * (itc/ipc) * log(teta/itc);
for (i=0;i<length;i+=step)
{
dpc = pc * (b - ro_evaluate(tc,b,alpha,teta)) + qc * ri_evaluate(tc);
dqc = pc * ro_evaluate(tc,b,alpha,teta) - qc * (mu + ri_evaluate(tc));
pc += step * dpc;
qc += step * dqc;
tc = pc + qc;
fprintf(output,"%lg %lg %lg %lg\n",i,pc,qc,tc);
}
fclose(output);
}
double ro_evaluate (double value, double b, double alpha, double teta)
{
// if using a gompertz model as the ro function
return (alpha * (1 - log(teta/value)) + b);
}
double ri_evaluate (double value)
{
/* basic case : no quiescent cells turn to proliferating cells ;
it corresponds to the situation where quiescent cells are actually all necrosed (dead)
*/
return 0;
}
| true |
2c614e9ebff314eae94a92f4f98edd85a2ec7dda | C++ | bloodMaster/ProducerConsumer | /ProducersConsumers/consumer.cpp | UTF-8 | 986 | 2.625 | 3 | [
"MIT"
] | permissive | //
//
// user define
#include "consumer.hpp"
#include "utilities.hpp"
//standard
namespace antel
{
// init static members
std::mutex consumer::m_mutex;
void consumer::deploy()
{
while (m_consumers_should_work) {
std::unique_lock<std::mutex> lock(m_mutex);
if ( m_consumers.wait_for(lock, std::chrono::milliseconds(100), [&]() { return !m_shared_container.empty(); }) ) {
value_type v;
if (m_shared_container.get_data(v)) {
write_to_file(v);
}
if (m_shared_container.is_min_range()) {
m_producers.notify_all();
}
utilities::sleep_time(utilities::generate_number());
}
m_clean_consumers.notify_one();
}
}
void consumer::write_to_file(const value_type &v)
{
assert(m_file.is_open());
m_file << v << ", ";
}
}; // end namespace antel
| true |
c5470f5508d7687ff1a8872473202ca1168b8803 | C++ | ntomitov/IOTrainingCamp | /Basics/fibonaci.cpp | UTF-8 | 459 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int MAX_SIZE = 200;
int fib(int);
int fibIterative(int);
int main() {
cout << fibIterative(100) << endl;
system("pause");
}
int fib(int n) {
if (n < 3) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
int fibIterative(int n) {
if (n < 2) {
return 1;
}
int list[MAX_SIZE], i = 2;
list[0] = 1;
list[1] = 1;
while (i < n) {
list[i] = list[i - 1] + list[i - 2];
i++;
}
return list[i - 1];
} | true |
56c89c5c34cd506347eb50f7e3f8652bd1fce193 | C++ | northWindPA/cpp_modules | /Module_04/ex01/AWeapon.cpp | UTF-8 | 607 | 3.296875 | 3 | [] | no_license | #include "AWeapon.hpp"
AWeapon::AWeapon(std::string const & name, int apcost, int damage)
: _name(name), _ap_cost(apcost), _damage(damage)
{}
AWeapon::~AWeapon()
{
std::cout << _name << " weapon destroyed" << std::endl;
}
AWeapon::AWeapon(AWeapon const ©)
{
*this = copy;
}
AWeapon &AWeapon::operator = (const AWeapon ©)
{
_name = copy._name;
_ap_cost = copy._ap_cost;
_damage = copy._damage;
return *this;
}
std::string const &AWeapon::get_name() const
{
return (_name);
}
int AWeapon::get_ap_cost() const
{
return (_ap_cost);
}
int AWeapon::get_damage() const
{
return (_damage);
} | true |
bcc65a41baa1a70c0b3bb94305aa2e41a5c54854 | C++ | Chirag-tech/Learning-sprint | /2.cpp | UTF-8 | 753 | 2.890625 | 3 | [] | no_license | //question:Coins And Triangle
#include <iostream>
#include <vector>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
ll n;
cin >> n;
ll first = 1;
ll last = n;
ll ans = 0;
while (first != last - 1)
{
ll mid = (first + last) / 2;
if (mid * (mid + 1) / 2 == n)
{
ans = mid;
break;
}
else if (mid * (mid + 1) / 2 < n)
{
first = mid;
}
else
last = mid;
}
if (ans != 0)
cout << ans << endl;
else
cout << first << endl;
}
return 0;
}
| true |
fea688328f6a60ff83d07f652b977fc4f5d00c57 | C++ | 15831944/ZaoQiBu | /ZaoQiBu/Course.h | UTF-8 | 1,575 | 3.21875 | 3 | [] | no_license | #pragma once
#include <vector>
#include "Chapter.h"
#include "tstring.h"
class PlayRecord
{
public:
void SetLastPlayChapterIndex(int lastPlayChapterIndex)
{
m_lastPlayChapterIndex = lastPlayChapterIndex;
}
int GetLastPlayChapterIndex() const
{
return m_lastPlayChapterIndex;
}
void SetLastPlayChapterTime(int lastPlayChapterTime)
{
m_lastPlayChapterTime = lastPlayChapterTime;
}
int GetLastPlayChapterTime() const
{
return m_lastPlayChapterTime;
}
private:
int m_lastPlayChapterIndex = 0;
int m_lastPlayChapterTime = 0;
};
class Course
{
public:
void SetTitle(const tstring &title)
{
m_title = title;
}
const tstring& GetTitle() const
{
return m_title;
}
void SetAuthor(const tstring &author)
{
m_author = author;
}
const tstring& GetAuthor() const
{
return m_author;
}
void SetIcon(const tstring &icon)
{
m_icon = icon;
}
const tstring& GetIcon() const
{
return m_icon;
}
void AddChapter(const Chapter &chapter)
{
m_chapters.push_back(chapter);
}
const Chapter& GetChapter(size_t index) const
{
return m_chapters[index];
}
size_t GetChapterCount() const
{
return m_chapters.size();
}
void SetPath(const tstring &path)
{
m_path = path;
}
const tstring& GetPath() const
{
return m_path;
}
void SetPlayRecord(const PlayRecord &playRecord)
{
m_playRecord = playRecord;
}
PlayRecord& GetPlayRecord()
{
return m_playRecord;
}
private:
tstring m_title;
tstring m_author;
tstring m_icon;
std::vector<Chapter> m_chapters;
tstring m_path;
PlayRecord m_playRecord;
};
| true |
a3c23b05c158bf919ae32832beb917ed481232d5 | C++ | elanahelou/ASTE499-HW7 | /Vec.h | UTF-8 | 1,309 | 3.25 | 3 | [] | no_license | //
// Vec.h
// ASTE499 HW7 Part1
//
// Created by Elana Helou on 3/9/21.
//
#ifndef Vec_h
#define Vec_h
#include <ostream>
#include <math.h>
template<typename T>
class _vec3{ // generic 3D vector of type T
public:
_vec3<T>(): d{0,0,0} {}
_vec3<T>(T a, T b, T c): d{a,b,c} {}
T& operator[] (int i) {return d[i];}
T operator[] (int i) const {return d[i];}
friend _vec3<T> operator+(const _vec3<T>&a, const _vec3<T>&b) {
return _vec3<T>(a[0]+b[0],a[1]+b[1],a[2]+b[2]); /**@return a double3 style vector */
}
friend _vec3<T> operator-(const _vec3<T>&a, const _vec3<T>&b) {
return _vec3<T>(a[0]-b[0],a[1]-b[1],a[2]-b[2]); /**@return a double3 style vector */
}
/**
* \f$ \vec{a} \cdot \vec{b} = a_0b_0 + a_1b_1 + a_2b_2] \f$
*/
friend T dot(const _vec3<T>&a, const _vec3<T>&b) {
return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; /** @return an interger */
}
friend double mag(const _vec3<T>&a) {return sqrt(dot(a,a));} /** @return a float */
friend std::ostream& operator<<(std::ostream &out, const _vec3<T>&a) {
out<<a[0]<<" "<<a[1]<<" "<<a[2]; return out;
}
protected:
T d[3];
};
using double3 = _vec3<double>; // assign a nickname
#endif /* Vec_h */
| true |
dc619ce5d5e74b7b356253d2ec3c4bf1c4d3cfc4 | C++ | RobotLocomotion/drake | /common/symbolic/codegen.cc | UTF-8 | 9,675 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | #include "drake/common/symbolic/codegen.h"
#include <sstream>
#include <stdexcept>
#include <fmt/format.h>
namespace drake {
namespace symbolic {
using std::ostream;
using std::ostringstream;
using std::runtime_error;
using std::string;
using std::to_string;
using std::vector;
CodeGenVisitor::CodeGenVisitor(const vector<Variable>& parameters) {
for (vector<Variable>::size_type i = 0; i < parameters.size(); ++i) {
id_to_idx_map_.emplace(parameters[i].get_id(), i);
}
}
string CodeGenVisitor::CodeGen(const Expression& e) const {
return VisitExpression<string>(this, e);
}
string CodeGenVisitor::VisitVariable(const Expression& e) const {
const Variable& v{get_variable(e)};
const auto it{id_to_idx_map_.find(v.get_id())};
if (it == id_to_idx_map_.end()) {
throw runtime_error("Variable index is not found.");
}
return "p[" + to_string(it->second) + "]";
}
string CodeGenVisitor::VisitConstant(const Expression& e) const {
return to_string(get_constant_value(e));
}
string CodeGenVisitor::VisitAddition(const Expression& e) const {
const double c{get_constant_in_addition(e)};
const auto& expr_to_coeff_map{get_expr_to_coeff_map_in_addition(e)};
ostringstream oss;
oss << "(" << c;
for (const auto& item : expr_to_coeff_map) {
const Expression& e_i{item.first};
const double c_i{item.second};
oss << " + ";
if (c_i == 1.0) {
oss << CodeGen(e_i);
} else {
oss << "(" << c_i << " * " << CodeGen(e_i) << ")";
}
}
oss << ")";
return oss.str();
}
string CodeGenVisitor::VisitMultiplication(const Expression& e) const {
const double c{get_constant_in_multiplication(e)};
const auto& base_to_exponent_map{
get_base_to_exponent_map_in_multiplication(e)};
ostringstream oss;
oss << "(" << c;
for (const auto& item : base_to_exponent_map) {
const Expression& e_1{item.first};
const Expression& e_2{item.second};
oss << " * ";
if (is_one(e_2)) {
oss << CodeGen(e_1);
} else {
oss << "pow(" << CodeGen(e_1) << ", " << CodeGen(e_2) << ")";
}
}
oss << ")";
return oss.str();
}
// Helper method to handle unary cases.
string CodeGenVisitor::VisitUnary(const string& f, const Expression& e) const {
return f + "(" + CodeGen(get_argument(e)) + ")";
}
// Helper method to handle binary cases.
string CodeGenVisitor::VisitBinary(const string& f, const Expression& e) const {
return f + "(" + CodeGen(get_first_argument(e)) + ", " +
CodeGen(get_second_argument(e)) + ")";
}
string CodeGenVisitor::VisitPow(const Expression& e) const {
return VisitBinary("pow", e);
}
string CodeGenVisitor::VisitDivision(const Expression& e) const {
return "(" + CodeGen(get_first_argument(e)) + " / " +
CodeGen(get_second_argument(e)) + ")";
}
string CodeGenVisitor::VisitAbs(const Expression& e) const {
return VisitUnary("fabs", e);
}
string CodeGenVisitor::VisitLog(const Expression& e) const {
return VisitUnary("log", e);
}
string CodeGenVisitor::VisitExp(const Expression& e) const {
return VisitUnary("exp", e);
}
string CodeGenVisitor::VisitSqrt(const Expression& e) const {
return VisitUnary("sqrt", e);
}
string CodeGenVisitor::VisitSin(const Expression& e) const {
return VisitUnary("sin", e);
}
string CodeGenVisitor::VisitCos(const Expression& e) const {
return VisitUnary("cos", e);
}
string CodeGenVisitor::VisitTan(const Expression& e) const {
return VisitUnary("tan", e);
}
string CodeGenVisitor::VisitAsin(const Expression& e) const {
return VisitUnary("asin", e);
}
string CodeGenVisitor::VisitAcos(const Expression& e) const {
return VisitUnary("acos", e);
}
string CodeGenVisitor::VisitAtan(const Expression& e) const {
return VisitUnary("atan", e);
}
string CodeGenVisitor::VisitAtan2(const Expression& e) const {
return VisitBinary("atan2", e);
}
string CodeGenVisitor::VisitSinh(const Expression& e) const {
return VisitUnary("sinh", e);
}
string CodeGenVisitor::VisitCosh(const Expression& e) const {
return VisitUnary("cosh", e);
}
string CodeGenVisitor::VisitTanh(const Expression& e) const {
return VisitUnary("tanh", e);
}
string CodeGenVisitor::VisitMin(const Expression& e) const {
return VisitBinary("fmin", e);
}
string CodeGenVisitor::VisitMax(const Expression& e) const {
return VisitBinary("fmax", e);
}
string CodeGenVisitor::VisitCeil(const Expression& e) const {
return VisitUnary("ceil", e);
}
string CodeGenVisitor::VisitFloor(const Expression& e) const {
return VisitUnary("floor", e);
}
string CodeGenVisitor::VisitIfThenElse(const Expression&) const {
throw runtime_error("Codegen does not support if-then-else expressions.");
}
string CodeGenVisitor::VisitUninterpretedFunction(const Expression&) const {
throw runtime_error("Codegen does not support uninterpreted functions.");
}
string CodeGen(const string& function_name, const vector<Variable>& parameters,
const Expression& e) {
ostringstream oss;
// Add header for the main function.
oss << "double " << function_name << "(const double* p) {\n";
// Codegen the expression.
oss << " return " << CodeGenVisitor{parameters}.CodeGen(e) << ";\n";
// Add footer for the main function.
oss << "}\n";
// <function_name>_meta_t type.
oss << "typedef struct {\n"
" /* p: input, vector */\n"
" struct { int size; } p;\n"
"} "
<< function_name << "_meta_t;\n";
// <function_name>_meta().
oss << function_name << "_meta_t " << function_name << "_meta() { return {{"
<< parameters.size() << "}}; }\n";
return oss.str();
}
namespace internal {
void CodeGenDenseData(const string& function_name,
const vector<Variable>& parameters,
const Expression* const data, const int size,
ostream* const os) {
// Add header for the main function.
(*os) << "void " << function_name << "(const double* p, double* m) {\n";
const CodeGenVisitor visitor{parameters};
for (int i = 0; i < size; ++i) {
(*os) << " "
<< "m[" << i << "] = " << visitor.CodeGen(data[i]) << ";\n";
}
// Add footer for the main function.
(*os) << "}\n";
}
void CodeGenDenseMeta(const string& function_name, const int parameter_size,
const int rows, const int cols, ostream* const os) {
// <function_name>_meta_t type.
(*os) << "typedef struct {\n"
" /* p: input, vector */\n"
" struct { int size; } p;\n"
" /* m: output, matrix */\n"
" struct { int rows; int cols; } m;\n"
"} "
<< function_name << "_meta_t;\n";
// <function_name>_meta().
(*os) << function_name << "_meta_t " << function_name << "_meta() { return {{"
<< parameter_size << "}, {" << rows << ", " << cols << "}}; }\n";
}
void CodeGenSparseData(const string& function_name,
const vector<Variable>& parameters,
const int outer_index_size, const int non_zeros,
const int* const outer_index_ptr,
const int* const inner_index_ptr,
const Expression* const value_ptr, ostream* const os) {
// Print header.
(*os) << fmt::format(
"void {}(const double* p, int* outer_indices, int* "
"inner_indices, double* values) {{\n",
function_name);
for (int i = 0; i < outer_index_size; ++i) {
(*os) << fmt::format(" outer_indices[{0}] = {1};\n", i,
outer_index_ptr[i]);
}
for (int i = 0; i < non_zeros; ++i) {
(*os) << fmt::format(" inner_indices[{0}] = {1};\n", i,
inner_index_ptr[i]);
}
const CodeGenVisitor visitor{parameters};
for (int i = 0; i < non_zeros; ++i) {
(*os) << fmt::format(" values[{0}] = {1};\n", i,
visitor.CodeGen(value_ptr[i]));
}
// Print footer.
(*os) << "}\n";
}
void CodeGenSparseMeta(const string& function_name, const int parameter_size,
const int rows, const int cols, const int non_zeros,
const int outer_indices, const int inner_indices,
ostream* const os) {
// <function_name>_meta_t type.
(*os) << "typedef struct {\n"
" /* p: input, vector */\n"
" struct { int size; } p;\n"
" /* m: output, matrix */\n"
" struct {\n"
" int rows;\n"
" int cols;\n"
" int non_zeros;\n"
" int outer_indices;\n"
" int inner_indices;\n"
" } m;\n"
"} "
<< function_name << "_meta_t;\n";
// <function_name>_meta().
(*os) << fmt::format(
"{0}_meta_t {1}_meta() {{ return {{{{{2}}}, {{{3}, {4}, {5}, {6}, "
"{7}}}}}; }}\n",
function_name, function_name, parameter_size, rows, cols, non_zeros,
outer_indices, inner_indices);
}
} // namespace internal
std::string CodeGen(
const std::string& function_name, const std::vector<Variable>& parameters,
const Eigen::Ref<const Eigen::SparseMatrix<Expression>>& M) {
DRAKE_ASSERT(M.isCompressed());
ostringstream oss;
internal::CodeGenSparseData(function_name, parameters, M.cols() + 1,
M.nonZeros(), M.outerIndexPtr(),
M.innerIndexPtr(), M.valuePtr(), &oss);
internal::CodeGenSparseMeta(function_name, parameters.size(), M.rows(),
M.cols(), M.nonZeros(), M.cols() + 1,
M.nonZeros(), &oss);
return oss.str();
}
} // namespace symbolic
} // namespace drake
| true |
88cf9d4e67db73ea298a456e789921bedf0977dd | C++ | elrinor/cmc-cg | /2006 - Task4 {19 of 24} [m]/src/Vector.cpp | UTF-8 | 1,808 | 3.28125 | 3 | [
"MIT"
] | permissive | #include "vector.h"
CVector::CVector()
{
v[0] = 0;
v[1] = 0;
v[2] = 0;
}
CVector::CVector(CVector &vec)
{
v[0] = vec.v[0];
v[1] = vec.v[1];
v[2] = vec.v[2];
}
CVector::CVector(float x, float y, float z)
{
v[0] = x;
v[1] = y;
v[2] = z;
}
CVector& CVector::operator=(CVector &vec)
{
v[0] = vec.v[0];
v[1] = vec.v[1];
v[2] = vec.v[2];
return *this;
}
CVector CVector::operator*(float s)
{
return CVector(v[0]*s, v[1]*s, v[2]*s);
}
CVector& CVector::operator*=(float s)
{
v[0] *= s;
v[1] *= s;
v[2] *= s;
return *this;
}
float CVector::operator*(CVector &vec)
{
return v[0]*vec.v[0]+v[1]*vec.v[1]+v[2]*vec.v[2];
}
CVector CVector::operator|(CVector &vec)
{
return CVector(v[1]*vec.v[2]-v[2]*vec.v[1], -(v[0]*vec.v[2]-v[2]*vec.v[0]), v[0]*vec.v[1]-v[1]*vec.v[0]);
}
CVector CVector::operator+(CVector &vec)
{
return CVector(v[0]+vec.v[0], v[1]+vec.v[1], v[2]+vec.v[2]);
}
CVector& CVector::operator+=(CVector &vec)
{
v[0] += vec.v[0];
v[1] += vec.v[1];
v[2] += vec.v[2];
return *this;
}
CVector CVector::operator-(CVector &vec)
{
return CVector(v[0]-vec.v[0], v[1]-vec.v[1], v[2]-vec.v[2]);
}
CVector CVector::operator-()
{
return CVector(-v[0],-v[1],-v[2]);
}
CVector& CVector::operator-=(CVector &vec)
{
v[0] -= vec.v[0];
v[1] -= vec.v[1];
v[2] -= vec.v[2];
return *this;
}
bool CVector::operator==(CVector &vec)
{
return (v[0]==vec.v[0] && v[1]==vec.v[1] && v[2]==vec.v[2]);
}
CVector& CVector::Normalize(float n)
{
float d = sqrtf(v[0]*v[0]+v[1]*v[1]+v[2]*v[2])/n;
v[0]/= d;
v[1]/= d;
v[2]/= d;
return *this;
}
void CVector::Set(float x, float y, float z)
{
v[0] = x;
v[1] = y;
v[2] = z;
}
float CVector::Abs2()
{
return x*x+y*y+z*z;
}
| true |
c7013cbea297b15a88047947fc3e89975d56ee10 | C++ | somewhatlurker/SlidA | /src/SlidA/debugTimer.cpp | UTF-8 | 476 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "debugTimer.h"
void debugTimer::reset() {
lastMicros = 0;
minMicros = (unsigned long)-1; // equal to max value
maxMicros = 0;
totalMicros = 0;
nSamples = 0;
}
void debugTimer::log() {
if (lastMicros == 0) {
lastMicros = micros();
}
else {
unsigned long t = micros() - lastMicros;
lastMicros += t;
if (minMicros > t)
minMicros = t;
if (maxMicros < t)
maxMicros = t;
totalMicros += t;
nSamples++;
}
}
| true |
b488feec96d3b38c0571fc95cdf2e414a0fd2dad | C++ | minhdatplus/amibroker-plugin | /CB180080-SOICT-BKHN/Utils.cpp | UTF-8 | 2,037 | 2.546875 | 3 | [] | no_license | #include "pch.h"
#include "Utils.h"
#include <string>
#include <codecvt>
HRESULT Utils::OLEMethod(int nType, VARIANT* pvResult, IDispatch* pDisp, LPOLESTR ptName, int cArgs ...)
{
if (!pDisp) return E_FAIL;
va_list marker;
va_start(marker, cArgs);
DISPPARAMS dp = { NULL, NULL, 0, 0 };
DISPID dispidNamed = DISPID_PROPERTYPUT;
DISPID dispID;
char szName[200];
// Convert down to ANSI
WideCharToMultiByte(CP_ACP, 0, ptName, -1, szName, 256, NULL, NULL);
// Get DISPID for name passed...
HRESULT hr = pDisp->GetIDsOfNames(IID_NULL, &ptName, 1,
LOCALE_USER_DEFAULT, &dispID);
if (FAILED(hr)) {
return hr;
}
// Allocate memory for arguments...
VARIANT* pArgs = new VARIANT[cArgs + 1];
// Extract arguments...
for (int i = 0; i < cArgs; i++) {
pArgs[i] = va_arg(marker, VARIANT);
}
// Build DISPPARAMS
dp.cArgs = cArgs;
dp.rgvarg = pArgs;
// Handle special-case for property-puts!
if (nType & DISPATCH_PROPERTYPUT) {
dp.cNamedArgs = 1;
dp.rgdispidNamedArgs = &dispidNamed;
}
// Make the call!
hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT,
nType, &dp, pvResult, NULL, NULL);
if (FAILED(hr)) {
return hr;
}
// End variable-argument section...
va_end(marker);
delete[] pArgs;
return hr;
}
std::wstring Utils::S2WS(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
std::string Utils::WS2S(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
} | true |
ed6b3cf89f2d9fc6f60bb583578c0112a4f2f373 | C++ | SatyamJindal/Competitive-Programming | /CodeChef/TRIMETER.cpp | UTF-8 | 1,071 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int dfs(int node,vector<int> g[],int level[],int vis[])
{
vis[node]=1;
for(auto i:g[node])
{
if(!vis[i])
{
level[i] = level[node]+1;
dfs(i,g,level,vis);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
int n;
cin>>n;
vector<int> g[n+5];
int level[n+5],vis[n+5];
memset(level,0,sizeof(level));
memset(vis,0,sizeof(vis));
for(int i=0;i<n-1;i++)
{
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
level[1]=0;
dfs(1,g,level,vis);
int a=1;
for(int i=1;i<=n;i++)
{
if(level[i]>level[a])
a=i;
}
memset(level,0,sizeof(level));
memset(vis,0,sizeof(vis));
level[a]=0;
dfs(a,g,level,vis);
int dia = *max_element(level,level+n+5);
int b=a;
for(int i=1;i<=n;i++)
{
if(level[i]>level[b])
b=i;
}
int levelb[n+5];
memset(levelb,0,sizeof(levelb));
memset(vis,0,sizeof(vis));
levelb[b]=0;
dfs(b,g,levelb,vis);
int ans=0;
for(int i=1;i<=n;i++)
{
if(i!=a && i!=b)
{
int f = level[i] + levelb[i];
ans = max(ans,(f+dia)/2);
}
}
cout<<ans<<"\n";
}
| true |
217d2cb2852d233590cdeac9aa5c5fc7ec134e05 | C++ | Lecureur-Arthur/Apprendre_Cpp | /15--Fonction_virtuelle_polymorphisme/catalogue.cpp | UTF-8 | 767 | 3.375 | 3 | [] | no_license | #include "catalogue.h"
#include <iostream>
using namespace std;
//Constructeur catalogue
catalogue::catalogue(const int _nbBarres):nbBarres(_nbBarres)
{
lesBarres = new Barre *[nbBarres];
index = 0;
}
//Destructeur catalogue
catalogue::~catalogue()
{
delete[] lesBarres;
}
//Peremet d'ajouter un barre grace a un pointeur
bool catalogue::AjouterBarre(Barre *ptrBarre)
{
bool retour = true;
if (index < nbBarres)
lesBarres[index++]=ptrBarre;
else
retour = false;
return retour;
}
//Affichage de catalogue
void catalogue::AfficherCatalogue()
{
for (int indice = 0; indice < index; indice++) {
lesBarres[indice]->AfficherCaracteristiques();
cout << lesBarres[indice]->CalculerMasse() << endl;
}
}
| true |
760526043f0d2e0c2cec6dcf1788f301cc204c2f | C++ | blockspacer/phd | /benchmarks/optional/source/references.transparent.cpp | UTF-8 | 3,881 | 2.546875 | 3 | [] | no_license | // Copyright � 2018-2020 ThePhD
#include "ensure.hpp"
#include "data.hpp"
#include "stats.hpp"
#include "optional.hpp"
#include "bench.hpp"
#include <benchmark/benchmark.h>
#include <barrier/barrier.hpp>
#include <algorithm>
#include <numeric>
#include <random>
static void int_by_ref_transparent_success(benchmark::State& state) {
size_t x = 0;
size_t expected_value = 0;
{
size_t ref_value = int_value;
tl::optional<size_t&> maybe_value = ref_value;
expected_value = bench_transparent_inplace_int(maybe_value);
}
for (auto _ : state) {
state.PauseTiming();
size_t ref_value = int_value;
tl::optional<size_t&> maybe_value = ref_value;
state.ResumeTiming();
x += bench_transparent_inplace_int(maybe_value);
}
if (!ensure(state, x, state.iterations() * expected_value)) {
return;
}
}
static void int_3x_by_ref_transparent_success(benchmark::State& state) {
size_t x = 0;
size_t expected_value = 0;
{
size_t ref_value = int_value;
tl::optional<size_t&> maybe_value = ref_value;
expected_value = bench_transparent_inplace_int_3x(maybe_value);
}
for (auto _ : state) {
state.PauseTiming();
size_t ref_value = int_value;
tl::optional<size_t&> maybe_value = ref_value;
state.ResumeTiming();
x += bench_transparent_inplace_int_3x(maybe_value);
}
if (!ensure(state, x, state.iterations() * expected_value)) {
return;
}
}
static void vector_by_ref_transparent_success(benchmark::State& state) {
std::vector<size_t> initial_value = create_random_vector();
size_t expected_value = 0;
{
// set up initial expected value
std::vector<size_t> value = initial_value;
tl::optional<std::vector<size_t>&> maybe_value = value;
expected_value = bench_transparent_inplace_vector(maybe_value);
}
for (auto _ : state) {
state.PauseTiming();
std::vector<size_t> value = initial_value;
tl::optional<std::vector<size_t>&> maybe_value = value;
state.ResumeTiming();
size_t x = bench_transparent_inplace_vector(maybe_value);
state.PauseTiming();
ensure(state, x, expected_value);
state.ResumeTiming();
}
}
static void vector_3x_by_ref_transparent_success(benchmark::State& state) {
std::vector<size_t> initial_value = create_random_vector();
size_t expected_value = 0;
{
// set up initial expected value
std::vector<size_t> value = initial_value;
tl::optional<std::vector<size_t>&> maybe_value = value;
expected_value = bench_transparent_inplace_vector(maybe_value);
}
for (auto _ : state) {
state.PauseTiming();
std::vector<size_t> value = initial_value;
tl::optional<std::vector<size_t>&> maybe_value = value;
state.ResumeTiming();
size_t x = bench_transparent_inplace_vector(maybe_value);
state.PauseTiming();
ensure(state, x, expected_value);
state.ResumeTiming();
}
}
BENCHMARK(int_by_ref_transparent_success)
->ComputeStatistics("max", &compute_max)
->ComputeStatistics("min", &compute_min)
->ComputeStatistics("variance", &compute_variance)
->ComputeStatistics("dispersion", &compute_index_of_dispersion);
BENCHMARK(int_3x_by_ref_transparent_success)
->ComputeStatistics("max", &compute_max)
->ComputeStatistics("min", &compute_min)
->ComputeStatistics("variance", &compute_variance)
->ComputeStatistics("dispersion", &compute_index_of_dispersion);
BENCHMARK(vector_by_ref_transparent_success)
->ComputeStatistics("max", &compute_max)
->ComputeStatistics("min", &compute_min)
->ComputeStatistics("variance", &compute_variance)
->ComputeStatistics("dispersion", &compute_index_of_dispersion);
BENCHMARK(vector_3x_by_ref_transparent_success)
->ComputeStatistics("max", &compute_max)
->ComputeStatistics("min", &compute_min)
->ComputeStatistics("variance", &compute_variance)
->ComputeStatistics("dispersion", &compute_index_of_dispersion);
| true |
53b7d651b9ead17b76315b1f7fbc99b3932be74d | C++ | kunhuicho/crawl-tools | /codecrawler/_code/hdu5051/12360196.cpp | UTF-8 | 1,000 | 2.609375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <iostream>
#include<string>
#include<sstream>
using namespace std;
int test,n,b,q;
double L,R,del;
string i2s(int x)
{
string y;
stringstream f;
f << x; f >> y;
return y;
}
bool check()
{
string sn,sb;
sn=i2s(n); sb=i2s(b);
for (int i=0; i<sn.length(); i++)
if (sn[i]!=sb[i]) return false;
return true;
}
int main()
{
cin >> test;
for (int i=1; i<=test; i++)
{
cin >> n >> b >> q;
if (q==1)
{
if (check()) printf("Case #%d: %.5lf\n",i,1.0);
else printf("Case #%d: %.5lf\n",i,0.0);
continue;
}
else if (q == 10 || q == 100 || q == 1000)
{
while (n % 10 == 0) n /= 10;
if (check()) printf("Case #%d: %.5lf\n",i,1.0);
else printf("Case #%d: %.5lf\n",i,0.0);
continue;
}
printf("Case #%d: %.5lf\n",i,log10(n+1)-log10(n));
}
return 0;
} | true |
c7488b4f8283d1dcdabfab58602fdb7533684d48 | C++ | 17326867021/ccf | /第一题/201512-1.cpp | UTF-8 | 176 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
long long n, sum = 0;
cin >> n;
while(n){
sum += n%10;
n /= 10;
}
cout << sum << endl;
return 0;
}
| true |
b8fe53d0162c21c0ba176731f7b8b4a5b95ee7b7 | C++ | RedSkiesIO/catalyst-network-simulation | /c++/scheduler.cpp | UTF-8 | 929 | 3.15625 | 3 | [] | no_license | #include "scheduler.h"
#include <iostream>
using simulation::scheduler;
void scheduler::run () {
while (! event_queue.empty () && !exit_called) {
event * next_event = event_queue.top ();
event_queue.pop ();
time = next_event->time;
next_event->process_event ();
delete next_event;
}
}
void scheduler::stop(){
exit_called =true;
}
void scheduler::schedule_event( event * new_event) {
//std::cout << "adding event" << std::endl;
if(new_event->time < end_time){
event_queue.push (new_event);
}
//std::cout << "no of events: " << event_queue.size() << std::endl;
}
void scheduler::schedule_event(std::vector<event *> new_events) {
for(auto const& new_event: new_events) { schedule_event(new_event);}
}
scheduler::t_t scheduler::get_time(){
return time;
}
/* Null, because instance will be initialized on demand. */
| true |
f04493496603dec4366bd483ad9d03be0a5cac99 | C++ | AhmetMelihIslam/crynn | /src/Core/Transform.h | UTF-8 | 3,365 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "glm/glm.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <iostream>
#include <memory>
#include <unordered_set>
#include "Math/Math.h"
#include <memory>
namespace crynn
{
/// <summary>
/// Matrix representation with easy functions to transform it.
/// This class is mostly intended to be inherited from.
/// Any transformations made, (translate, scale rotate) will be applied to the "transformMatrix" member.
/// You can use this matrix however you please. Its generally used as a model or view matrix, and works very well with MeshRenderer.
/// Inspired from the Unity transform class.
/// </summary>
class Transform
{
public:
Transform();
virtual ~Transform();
Transform(const Transform& other) = default;
Transform& operator=(const Transform& other) = default;
Transform(Transform&& other) = default;
Transform& operator=(Transform&& other) = default;
void Translate(Vec3 translation); //Applies a translation to this object.
void Scale(Vec3 scale); //Applies a scale to the object
void Rotate(Vec3 rot); //Applies a rotation to the object. rot is the XYZ euler angle rotation. Angles should be in degrees
void SetPosition(Vec3 position); //Sets the position of the object
Vec3 GetPosition() const; //Returns a Vec3 containing the XYZ position of the object
void SetScale(Vec3 scale); //Sets the scale of the object
Vec3 GetScale() const; //Returns a Vec3 containing the XYZ scale of the object
void SetRotation(Vec3 rot); //Sets the objects rotation. rot is the XYZ euler angle rotation. Angles should be in degrees
const Quat& GetRotation() const; //Returns a quaternion representing the objects rotation. If you would like euler angles, use GetRotationEuler().
Vec3 GetRotationEuler() const; //Returns a Vec3 with the euler angle rotation state.
Vec3 GetForwardVector() const;
Vec3 GetRightVector() const;
Vec3 GetUpVector() const;
//Returns a non-const reference to the model matrix struct this class is represented with.
Mat4& GetMatrix() const;
void SetParent(Transform* parent);
Transform& GetParent();
void RemoveParent();
protected:
bool ShouldRecalculateMatrices() const { return m_recalculateMatrix; }
private:
Vec3 m_position = Vec3(0, 0, 0);
Quat m_rotation = Quat(Vec3(0.0f, 0.0f, 0.0f));
Vec3 m_scale = Vec3(1, 1, 1);
Vec3 m_eulerRotation = Vec3(0, 0, 0); //Cache for the euler rotation of the object. Not used in any calculation. Degrees
mutable Mat4 m_worldMatrix = Mat4(1.0f); //model matrix with transformations relative to the world origin
mutable Mat4 m_localMatrix = Mat4(1.0f); //model matrix with transformations relative to the parents of this transform.
//Recursively computes a matrix that applies transformations from this matrice's parents, instead of the world.
//The matrix parameter passed to this function will have all the transformations from its parent transforms applied to it.
Mat4& ComputeLocalMatrixRecursive(Mat4& matrix, const Transform* const transform) const;
Transform* m_parent = nullptr;
std::unordered_set<Transform*> m_children; //pointers to this objects children.
mutable std::atomic_bool m_recalculateMatrix = true; //set to true after moving/rotating/scaling. Indicates model matrix needs to be recalculated.
};
}
| true |
430575f63653e66a13dec447b181ffb1a444a4c8 | C++ | starsnow/tuyaSmartLED | /tyCube2812/cube2812.cpp | UTF-8 | 5,546 | 2.78125 | 3 | [] | no_license | // cube2812.cpp
// Created by seesea 2021-07-07
// 2812 立方体的实现文件
#include <arduino.h>
#include "cube2812.h"
#include "rainbowMode.h"
#include "colourfulDreamMode.h"
#include "starSkyMode.h"
#include "rainMode.h"
#include "hackerMatrixMode.h"
#include "bubbleMode.h"
#include "energyCubeMode.h"
#include "snowMode.h"
#include "snakeGameMode.h"
// FastLED 的 LED 数据
// 内存不够用,只用三个面
CRGB leds[MATRIX_BUFFER_NUM][NUM_LEDS_PER_MATRIX];
// 各个 FastLED 控制器
CLEDController* FastLEDControllers[MATRIX_NUM];
/*
// 使用先创建一堆对象,再用指针数组的方式比较简单也不容易内存泄露,但是费内存
RainbowMode rainbowMode;
ColourfulDreamMode colourfulDreamMode;
StarSkyMode starSkyMode;
RenderMode *renderModes[] = { &rainbowMode, &colourfulDreamMode, &starSkyMode };
*/
RenderMode *renderMode = 0;
enum RENDER_MODE lastModeName = EMPTY;
// 初始化
void initCube2812()
{
FastLED.setBrightness(INIT_BRIGHTNESS);
// 内存不足,所以所有的侧面都用同样的显示
FastLEDControllers[UP_SIDE] = &FastLED.addLeds<CHIPSET, UP_PIN, COLOR_ORDER>(leds[UP_SIDE], NUM_LEDS_PER_MATRIX);
FastLEDControllers[DOWN_SIDE] = &FastLED.addLeds<CHIPSET, DOWN_PIN, COLOR_ORDER>(leds[LEFT_SIDE], NUM_LEDS_PER_MATRIX);
FastLEDControllers[LEFT_SIDE] = &FastLED.addLeds<CHIPSET, LEFT_PIN, COLOR_ORDER>(leds[LEFT_SIDE], NUM_LEDS_PER_MATRIX);
FastLEDControllers[RIGHT_SIDE] = &FastLED.addLeds<CHIPSET, RIGHT_PIN, COLOR_ORDER>(leds[LEFT_SIDE], NUM_LEDS_PER_MATRIX);
FastLEDControllers[FRONT_SIDE] = &FastLED.addLeds<CHIPSET, FRONT_PIN, COLOR_ORDER>(leds[LEFT_SIDE], NUM_LEDS_PER_MATRIX);
FastLEDControllers[BACK_SIDE] = &FastLED.addLeds<CHIPSET, BACK_PIN, COLOR_ORDER>(leds[LEFT_SIDE], NUM_LEDS_PER_MATRIX);
// setRenderMode(RAINBOW);
// setRenderMode(COLOURFUL_DREAM);
// setRenderMode(STAR_SKY);
// setRenderMode(HACKER_MATRIX);
// setRenderMode(BUBBLE);
// setRenderMode(ENERGY_CUBE);
// setRenderMode(SNOW);
setRenderMode(SNAKE_GAME);
// setRenderMode(EMPTY);
}
// 渲染刷新函数
void updateCube2812()
{
static unsigned long last_time = 0;
static unsigned int renderIntervalMs = 0;
if (millis() - last_time > renderIntervalMs)
{
last_time = millis();
if (renderMode == 0)
return;
// renderMode->input(random8(4) +1);
// inputDir(random8(4) + 1);
renderIntervalMs = renderMode->getRenderInterval();
renderMode->render();
FastLED.show();
}
}
void inputDir(uint8_t dir)
{
renderMode->input(dir);
}
// 设置渲染模式
void setRenderMode(enum RENDER_MODE mode)
{
// 使用先创建一堆对象,再用指针数组的方式比较简单也不容易内存泄露,但是费内存
// renderMode = renderModes[mode];
// renderMode->init();
RenderMode *newMode = 0;
switch (mode)
{
case RAINBOW: // 彩虹
newMode = new RainbowMode();
break;
case COLOURFUL_DREAM: // 五彩梦幻
newMode = new ColourfulDreamMode();
break;
case STAR_SKY: // 星空
newMode = new StarSkyMode();
break;
case HACKER_MATRIX: // 黑客帝国
newMode = new HackerMatrixMode();
break;
case RAIN: // 雨
newMode = new RainMode();
break;
case BUBBLE: // 气泡
newMode = new BubbleMode();
break;
case SNOW: // 雪
newMode = new SnowMode();
break;
case ENERGY_CUBE: // 能量魔方
newMode = new EnergyCubeMode();
break;
case SNAKE_GAME: // 贪吃蛇游戏
newMode = new SnakeGameMode();
break;
case EMPTY:
if (renderMode != 0)
{
delete renderMode;
renderMode = 0;
}
FastLED.clear();
FastLED.showColor(CRGB::Black);
return;
default:
return;
}
if (newMode == 0)
return;
if (renderMode != 0)
delete renderMode;
FastLED.clear();
lastModeName = mode;
renderMode = newMode;
renderMode->init();
}
void blinkLED(int times)
{
for (int i = 0; i < times; ++i)
{
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
}
// 8 x 8 点阵随机一个位置设置为指定颜色
void randomDot(CRGB pLeds[], const CRGB color)
{
uint8_t x = random8(8);
uint8_t y = random8(8);
pLeds[XY(x, y)] = color;
}
// FastLED 里的 XY 坐标转换行数的个人定制版
// 矩阵旋转公式,由新坐标换算为原坐标:
// 0: x = x', y = y'
// 90: x = y', y = height - x'
// 180: x = width - x', y = height - y'
// 270: x = width - y', y = x
inline uint16_t XY(uint8_t x, uint8_t y, uint8_t dir = CW0)
{
switch (dir)
{
case CW0:
return y * MATRIX_WIDTH + x;
case CW90:
return (MATRIX_HEIGHT - x - 1) * MATRIX_WIDTH + y;
case CW180:
return (MATRIX_WIDTH - y - 1) * MATRIX_WIDTH + MATRIX_HEIGHT - x - 1;
case CW270:
return x * MATRIX_WIDTH + MATRIX_WIDTH - y - 1;
}
return 0;
}
void turnOnCube2812()
{
setRenderMode(lastModeName);
}
void turnOffCube2812()
{
setRenderMode(EMPTY);
} | true |
2fa662b70b1b5907e3b9001856a24888acc81358 | C++ | geegatomar/Algorithms | /GraphAlgo/ShortestPaths/floyd_warshall.cpp | UTF-8 | 1,081 | 2.984375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define inf 1e7
int n, m;
vector<vector<int>> g;
void floyd()
{
// taking each vertex as intermediate each time
for(int intr = 0; intr < n; intr++)
{
for(int u = 0; u < n; u++)
{
for(int v = 0; v < n; v++)
{
if(u == intr || v == intr || u == v)
continue;
if(g[u][intr] + g[intr][v] < g[u][v])
{
g[u][v] = g[u][intr] + g[intr][v];
}
}
}
}
}
int main()
{
int i, j;
cin >> n >> m;
g.resize(n);
for(i = 0; i < n; i++)
{
g[i].resize(n);
for(j = 0; j < n; j++)
{
g[i][j] = inf;
if(i == j)
g[i][j] = 0;
}
}
for(i = 0; i < m; i++)
{
int u, v, w;
cin >> u >> v >> w;
g[u][v] = w; // this time we are using matrix representation
// unlike usually we used adjacency list representation
}
floyd();
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
cout << g[i][j] << " ";
cout << endl;
}
}
| true |
28f0c4aa4c37cddf8fc47dfefb96fc36add9e84d | C++ | newmri/API | /WarmmingUPLast/WarmmingUPLast/Question3.cpp | UTF-8 | 904 | 3.1875 | 3 | [] | no_license | #include "Question3.h"
void Question3::GetSentence()
{
cout << "Input sentence: ";
cin.ignore();
getline(cin, m_sentence);
}
void Question3::ShowSentence()
{
cout << "You entered " << m_sentence << endl;
}
void Question3::ModifySentence()
{
string tempstr;
string resultstr;
int paddingnum{};
srand((unsigned)time(NULL));
for (string::iterator itor = m_sentence.begin(); itor != m_sentence.end(); ++itor) {
char temp = *itor;
if (temp >= SMALL_MIN && temp <= SMALL_MAX) temp += CHAR_DIFFER;
else if (temp >= CAPITAL_MIN && temp <= CAPITAL_MAX) temp -= CHAR_DIFFER;
tempstr = temp;
resultstr.append(tempstr);
temp = (rand() % RAND_ADD) + RAND_MIN;
while (!('!' == temp || '@' == temp || '#' == temp || '$' == temp || '%' == temp))
temp = (rand() % RAND_ADD) + RAND_MIN;
tempstr = temp;
resultstr.append(tempstr);
}
cout << "Result is: " << resultstr << endl;
}
| true |
2511f36bd6dff5026d56c81103a3c64c7adbcedf | C++ | houwenqi/Tool-program | /other-program/stringreplace.cpp | UTF-8 | 481 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "123%40qq.com";/////指定串,可根据要求替换
string b = "%40";////要查找的串,可根据要求替换
string c = "@";
int pos;
pos = a.find(b);////查找指定的串
while (pos != -1)
{
a.replace(pos,b.length(),c);////用新的串替换掉指定的串
pos = a.find(b);//////继续查找指定的串,直到所有的都找到为止
}
cout << a << endl;
return 0;
} | true |
273be274de260f47e6c762ab622a35172f396876 | C++ | Yang-Pi/Pure-Cpp | /B-tasks/B3/task2.cpp | UTF-8 | 391 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include "factorial-container.hpp"
void task2()
{
FactorialContainer factorialCont;
std::copy(factorialCont.begin(), factorialCont.end(), std::ostream_iterator<size_t>(std::cout, " "));
std::cout << '\n';
std::reverse_copy(factorialCont.begin(), factorialCont.end(), std::ostream_iterator<size_t>(std::cout, " "));
std::cout << '\n';
}
| true |
0e80bfd981a4dfd0a6a3fa86a73b11801747ab76 | C++ | jayouimet/FirstMathEngine | /F4DVector3.h | UTF-8 | 1,582 | 2.921875 | 3 | [] | no_license | #pragma once
#include <iostream>
namespace F4DEngine {
class F4DVector3 {
private:
public:
// Directions
float x, y, z;
// Constructors
F4DVector3();
F4DVector3(float uX, float uY, float uZ);
// Destructor
~F4DVector3();
// Copying constructor
F4DVector3(const F4DVector3& v);
#pragma region Operators
#pragma region Vector with Vector Operators
// Equality operator
F4DVector3& operator=(const F4DVector3& v);
// Addition operator
F4DVector3 operator+(const F4DVector3& v) const;
void operator+=(const F4DVector3& v);
// Substraction operator
F4DVector3 operator-(const F4DVector3& v) const;
void operator-=(const F4DVector3& v);
// Dot operator
float operator*(const F4DVector3& v) const;
float dot(const F4DVector3& v) const;
// Cross operator
F4DVector3 cross(const F4DVector3& v) const;
F4DVector3 operator%(const F4DVector3& v) const;
void operator%=(const F4DVector3& v);
#pragma endregion
#pragma region Vector with Floating number Operators
// Multiplication operator
F4DVector3 operator*(const float& f) const;
void operator*=(const float& f);
// Division operator
F4DVector3 operator/(const float& f) const;
void operator/=(const float& f);
#pragma endregion
#pragma endregion
#pragma region Methods
float magnitude() const;
void normalize();
F4DVector3 rotateVectorAboutAngleAndAxis(float uAngle, F4DVector3& uAxis);
void show();
#pragma endregion
};
} | true |
ac8968de336a00a922b33a9e6dbdcd832fa1e367 | C++ | lihuafeng108/string_vector_iterator_test | /string_vector_iterator_test.cpp | GB18030 | 1,051 | 3.96875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
string str1 = "string͵һЩ:"; //string C++ͣһֳ
string str2 = "piece1: one, ";
string str3 = "piece2: two, ";
string str4 = "piece1: one, ";
cout << str1 << endl;
cout << "str1 size:" << str1.size() << endl;
cout << str2 + str3 << endl;
cout << "str2 == str3 ? :" << (str2 == str3) << endl;
cout << "str2 == str4 ? :" << (str2 == str4) << endl;
cout << "ַ:";
string str_input_1, str_input_2;
cin >> str_input_1 >> str_input_2;
cout << "ַӡ:" << str_input_1 << endl << str_input_2 << endl << endl;
cout << "stringiteratorһ:" << endl;
vector<string> vstr = { "ַ1", "ַ2", "ַ3", "ַ4" };
vstr.push_back("¼ַ");
vector<string>::const_iterator it;
for (it = vstr.begin(); it != vstr.end(); ++it)
{
cout << *it << endl;
}
return 0;
} | true |
40d5c1ef7646220383adb30d3a0283df31a0a210 | C++ | babu-thomas/ds-algos | /dutch_national_flag.cpp | UTF-8 | 1,054 | 4.25 | 4 | [
"MIT"
] | permissive | // Given an array containing only 0’s, 1’s and 2’s, sort the array in linear time and using
// constant space.
// For example,
// Input - 1, 1, 0, 2, 0, 1
// Output - 0, 0, 1, 1, 1, 2
// 1. Count occurrences of 0, 1 and 2. Then put them in correct order. Time - O(N), Space - O(1).
// 2. Use three way partitioning. Time - O(N), Space - O(1).
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
void linear_sort1(vector<int>& a)
{
int count[3] = {0};
for(int i = 0; i < a.size(); i++) {
count[a[i]]++;
}
int index = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < count[i]; j++)
a[index++] = i;
}
}
void linear_sort2(vector<int>& a)
{
int low = 0, mid = 0, high = a.size() - 1;
while(mid <= high) {
if(a[mid] == 0) {
swap(a[mid], a[low]);
low++;
mid++;
}
else if(a[mid] == 1) {
mid++;
}
else {
swap(a[mid], a[high]);
high--;
}
}
}
int main()
{
vector<int> a = {1, 2, 1, 0, 2, 0, 1};
linear_sort2(a);
for(auto& i: a)
cout << i << " ";
cout << "\n";
return 0;
} | true |
6c650bcd8bcb37b4da52097ad2ab868349f6915a | C++ | anagovitsyn/oss.FCL.sftools.dev.build | /imgtools/imglib/memmap/include/memmap.h | UTF-8 | 1,816 | 2.515625 | 3 | [] | no_license | /*
* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#if !defined(__MEMMAP_H__)
#define __MEMMAP_H__
#include "memmaputils.h"
/**
class Memmap
@internalComponent
@released
*/
class Memmap
{
private:
// Output image file name
string iOutFileName;
// Map pointer
char *iData;
// Maximum size of the memory map
unsigned long iMaxMapSize;
// Start offset of the memory map
unsigned long iStartOffset;
// Flag to fill the map after creating
int iFillFlg;
// Interface to platform utility functions
MemmapUtils *iUtils;
// Fill the memory map
int FillMemMap( unsigned char fillVal = 0 );
public:
Memmap( int aFillFlg, const string& aOutputFile );
Memmap( int aFillFlg = 1);
~Memmap( );
// Create memory map
int CreateMemoryMap( unsigned long aStartOffset = 0, unsigned char aFillVal = 0 );
// Close the memory map
void CloseMemoryMap( int aCloseFile = 1 );
// Dump the memory map into a file
void WriteToOutputFile( );
// Set the output image file name
void SetOutputFile(const string& aOutputFile );
// Set the maximum memory map size
void SetMaxMapSize( unsigned long aMaxSize );
// Get the memory map pointer
char* GetMemoryMapPointer( );
// Get the map size
unsigned long GetMapSize( );
// Operator [] for accessing memory map
char& operator[]( unsigned long aIndex );
};
#endif //__MEMMAP_H__
| true |
bd0db8c349013d0cb7759dbe2b8b19ef153f03f7 | C++ | HonestJack/acade-us | /project-cpp/src/Display.cpp | UTF-8 | 2,215 | 3.3125 | 3 | [] | no_license |
#include "Display.h"
Display::Display(/* args */)
{
}
Display::~Display()
{
}
void Display::print(char ch)
{
m_lcd.print(ch);
}
void Display::print(char string[])
{
m_lcd.print(string);
}
void Display::goto_display(unsigned char linha, unsigned char coluna)
{
if(linha == 2)
{
coluna |= 0x40;
}
m_lcd.lcd_function(0x80 | (coluna - 1));
}
void Display::clear()
{
limpa_linha(2);
limpa_linha(1);
}
void Display::limpa_linha(unsigned char linha)
{
goto_display(linha, 1);
print(" ");
goto_display(linha, 1);
}
void Display::print_horario(long count)
{
long aux_1, aux_2;
aux_1 = count/3600;
aux_2 = aux_1/10;
m_lcd.print(aux_2 + ASCII_SHIFT);
m_lcd.print(aux_1 - 10*aux_2 + ASCII_SHIFT);
m_lcd.print(':');
count = count - 3600*aux_1;
aux_1 = count/60;
aux_2 = aux_1/10;
m_lcd.print(aux_2 + ASCII_SHIFT);
m_lcd.print(aux_1 - 10*aux_2 + ASCII_SHIFT);
m_lcd.print(':');
aux_1 = count - 60*aux_1;
aux_2 = aux_1/10;
m_lcd.print(aux_2 + ASCII_SHIFT);
m_lcd.print(aux_1 - 10*aux_2 + ASCII_SHIFT);
}
void Display::print_tempo_restante(long tempo_restante)
{
limpa_linha(2);
goto_display(2,1);
if (tempo_restante > 0)
{
print("Restam: ");
print_horario(tempo_restante);
}else{
print("Seu Tempo Acabou");
}
}
void Display::print_relogio(long count)
{
goto_display(1,1);
print_horario(count);
}
void Display::print_usuarios_presentes(short capacity)
{
goto_display(1, 14);
print("U:");
print((capacity) + ASCII_SHIFT);
}
void Display::print_interfacie_padrao(long count, short capacity)
{
limpa_linha(1);
print_relogio(count);
print_usuarios_presentes(capacity);
}
void Display::print_duas_linhas(char string1[MAX_STRING_SIZE], char string2[MAX_STRING_SIZE])
{
limpa_linha(1);
print(string1);
limpa_linha(2);
print(string2);
}
void Display::print_user(short user)
{
int i;
short aux;
for(i=0;i<DIGIT_NUMBER;i++)
{
aux = user/pot(10, DIGIT_NUMBER - i - 1);
print(aux + ASCII_SHIFT);
user = user - aux*pot(10, DIGIT_NUMBER - i - 1);
}
}
void Display::print_menu_deslizante(short user)
{
limpa_linha(2);
print("<-2 ");
print_user(user);
print(" 1->");
} | true |
18152947a885be8ee610e0b660743025435b4e97 | C++ | lm-chinhtran/atcoder | /src/love_golf.cpp | UTF-8 | 602 | 2.796875 | 3 | [] | no_license | //
// love_golf.cpp
// learningCplusplus
//
// Created by Tran Duc Chinh on 2020/04/04.
// Copyright © 2020 Tran Duc Chinh. All rights reserved.
//
#include <iostream>
#include <queue>
#include <math.h>
using namespace std;
typedef long long ll;
ll mod = 1000000007;
#define PI 3.14159265
int main(int argc, const char* argv[]) {
int k, a, b;
std::cin >> k >> a >> b;
bool carry = false;
for (int i = a; i <=b; i++) {
if (i % k == 0) {
carry = true;
break;
}
}
if (carry) {
std::cout << "OK" << std::endl;
}
else {
std::cout << "NG" << std::endl;
}
return 0;
}
| true |
82b938f62108060b3e3d6080dda95b283270a020 | C++ | gabriel-bri/ccufcqx | /3º semestre/Estruturas de dados avançada/atividades/bin_tree/mexendo_folhas_arvores/main.cpp | UTF-8 | 424 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Tree.h"
using namespace std;
int main()
{
string line;
int value;
getline(cin, line);
cin >> value;
Tree bt(line);
cout << bt.count_leaves() << endl;
bt.delete_leaves();
bt.preorder();
cout << "\n";
bt.inorder();
cout << "\n";
bt.delete_leaves_with_value(value);
bt.preorder();
cout << "\n";
bt.inorder();
return 0;
} | true |
2f1bfefd2943cd015bde23f98f442b3ae797b6c5 | C++ | makbaranov/DependencyAnalyzer | /DependencyAnalyzer/DependencyNode.h | UTF-8 | 401 | 2.59375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include <memory>
class DependencyNode {
public:
DependencyNode(std::string name) {
name_ = name;
}
bool in_additional_dirs_ = false;
bool exist_ = false;
std::string name_;
std::string path_;
std::shared_ptr<DependencyNode> parent_ = nullptr;
std::vector<std::shared_ptr<DependencyNode>> dependencies_;
};
| true |
dc7f5875354f8ac232eeb65a92829d6801792777 | C++ | Lenium37/SigLight | /src/core/lib/lightshow/channel.cpp | UTF-8 | 650 | 2.984375 | 3 | [] | no_license | //
// Created by Johannes on 05.05.2019.
//
#include "channel.h"
Channel::Channel(int channel) {
this->channel = channel;
}
Channel::~Channel() {
}
int Channel::get_channel() const {
return this->channel;
}
std::vector<ValueChange> Channel::get_value_changes() {
return this->value_changes;
}
void Channel::set_channel(int channel) {
this->channel = channel;
}
void Channel::add_value_change(ValueChange value_change) {
this->value_changes.push_back(value_change);
}
int Channel::get_value_of_last_added_value_change() {
if (!this->value_changes.empty())
return this->value_changes.back().get_value();
else
return -1;
} | true |
896cb2be57370272d28a082f5f8c0ed84b8a1ef6 | C++ | cainiao22/lintcode-xcode | /lintcode-xcode/minimum-genetic-mutation.cpp | UTF-8 | 2,749 | 3.578125 | 4 | [] | no_license |
/**
1244. 最小基因变化
描述
基因序列可以用8个字符的字符串表示,可选择的字符包括 "A", "C", "G", "T"。
假设我们需要调查基因突变(从“起始点”到“结束点”突变),其中一个突变被定义为基因序列中的单个字符发生突变。
例如,"AACCGGTT" -> "AACCGGTA"是1个突变。
此外,还有一个给定的基因“库”,它记录了所有有效的基因突变。 基因必须在基因库中才有效。
现在,给出3个参数 - 起始点,结束点,基因库,你的任务是确定从“起始点”到“结束点”变异所需的最小突变数。 如果没有这样的突变,则返回-1。
假设起始点一定是合法的,它不一定在基因库中。
如果进行了多次突变,那么所有的突变过程中的序列必须是合法的
假设起始点和终止点的序列字符串不同。
您在真实的面试中是否遇到过这个题?
样例
样例1:
输入:
"AACCGGTT"
"AACCGGTA"
["AACCGGTA"]
输出:1
解释:
起始点: "AACCGGTT"
终止点: "AACCGGTA"
基因库: ["AACCGGTA"]
样例2:
输入:
"AACCGGTT"
"AAACGGTA"
["AACCGGTA", "AACCGCTA", "AAACGGTA"]
输出: 2
样例3:
输入:
"AAAAACCC"
"AACCCCCC"
["AAAACCCC", "AAACCCCC", "AACCCCCC"]
输出: 3
题解 BFS
*/
#include "CommonUtils.h"
class MinimumGeneticMutation
{
public:
int minMutation(string &start, string &end, vector<string> &bank)
{
vector<bool> flag(bank.size(), false);
queue<string> q;
q.push(start);
int step = 0;
while(!q.empty())
{
size_t len = q.size();
for(int i=0; i<len; i++)
{
string top = q.front();
if(top == end)
{
return step;
}
q.pop();
for(int j=0; j<bank.size(); j++)
{
if(!flag[j] && canConvert(top, bank[j]))
{
q.push(bank[j]);
flag[j] = true;
}
}
}
step ++;
}
return -1;
}
bool canConvert(string& from, string& target)
{
int cnt = 0;
for(int i=0; i<from.size(); i++)
{
if(from[i] != target[i])
{
cnt ++;
}
}
return cnt == 1;
}
void run()
{
string start = "AAAAACCC";
string end = "AACCCCCC";
vector<string> bank({"AAAACCCC", "AAACCCCC", "AACCCCCC"});
cout<<this->minMutation(start, end, bank)<<endl;
}
};
| true |
d187f4819b285cd732fc6377b95e9e7e36642783 | C++ | AryansRathi/Algorithms-and-Data-Structure | /Hw11/Greedy.cpp | UTF-8 | 799 | 3.546875 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
using namespace std;
struct Activity
{
int start, finish;
};
bool compare(Activity s1, Activity s2)
{
return (s1.finish < s2.finish);
}
void printMaxActivity(Activity arr[], int n)
{
sort(arr, arr + n, compare);
cout << "Selected activity" << endl;
int i = 0;
cout << "(" << arr[i].start << ", " << arr[i].finish << "), ";
for (int j = 1; j < n; j++)
{
if (arr[j].start >= arr[i].finish)
{
cout << "(" << arr[j].start << ", "
<< arr[j].finish << "), ";
i = j;
}
}
}
int main()
{
Activity arr[] = {{1, 2}, {2, 9}, {7, 10}};
int n = sizeof(arr) / sizeof(arr[0]);
printMaxActivity(arr, n);
return 0;
}
| true |
6c1af5ab8da069e1a8d66ba8a570f39dfaca424d | C++ | face4/yukicoder | /Level2/0306.cpp | UTF-8 | 263 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
typedef long double ld;
int main(){
ld xa, ya, xb, yb;
cin >> xa >> ya >> xb >> yb;
ld ans = xa * (yb-ya) / (xa+xb) + ya;
cout << fixed << setprecision(6) << ans << endl;
return 0;
} | true |
88f1975927ff9a98ac8ec9acafcde915adc98fc2 | C++ | githublizhipan/cppLearningNotes | /17.inherit_constructor.cpp | UTF-8 | 1,143 | 2.9375 | 3 | [] | no_license | /*************************************************************************
> File Name: 17.inherit_constructor.cpp
> Author: lizhipan
> Mail:
> Created Time: 2020年07月28日 星期二 19时55分36秒
************************************************************************/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
class D {
public:
D() { cout << "D constructor" << endl; }
~D() {
cout << "D destructor" << endl;
}
};
class A {
public:
A() = delete;
A(int x, int y) { cout << "A constructor" << endl; }
~A() {
cout << "A destructor" << endl;
}
};
class B {
public:
B() { cout << "B constructor" << endl; }
~B() {
cout << "B destructor" << endl;
}
};
class C : public D {
public:
C() : a(3, 4), b() { cout << "C constructor" << endl; } //显示的写出来初始化列表
~C() {
cout << "C destructor" << endl;
}
private:
B b;
A a;
};
int main() {
C c;
return 0;
}
| true |
0b8f6aa30a29bc23f323208d27e22624d2061f5c | C++ | Salimlou/Class-Work | /cs442/project.orig/project2/src/EntityQueue.cpp | UTF-8 | 1,875 | 2.9375 | 3 | [] | no_license | /****************************************************************************
Scott Harper, Tom Mancine, Ryan Scott
EntityQueue.cpp
The documentation within this file is sparse, and is only intended to provide
an overview of coding practices. For a more detailed description of
EntityQueue, see EntityQueue.h.
****************************************************************************/
#include "EntityQueue.h"
EntityQueue::EntityQueue()
{
size = 0;
front = 0;
back = 0;
}
EntityQueue::~EntityQueue()
{
}
void EntityQueue::addFirst( Entity* newEntity )
{
if( newEntity == 0 )
return;
if( size == 0 )
back = newEntity;
newEntity->beforeMe = 0;
newEntity->afterMe = front;
front = newEntity;
++size;
}
void EntityQueue::addLast( Entity* newEntity )
{
if( newEntity == 0 )
return;
if( size == 0 )
front = newEntity;
newEntity->beforeMe = back;
newEntity->afterMe = 0;
back = newEntity;
++size;
}
Entity* EntityQueue::removeFirst()
{
if( size == 0 )
return 0;
Entity* temp = front;
if( front->afterMe != 0 )
front = front->afterMe;
temp->afterMe = 0;
--size;
return temp;
}
Entity* EntityQueue::removeLast()
{
if( size == 0 )
return 0;
Entity* temp = back;
if( back->beforeMe != 0 )
back = back->beforeMe;
temp->beforeMe = 0;
--size;
return temp;
}
Entity* EntityQueue::removeEntity( unsigned int entityID )
{
if( size == 0 )
return 0;
Entity* temp = find( entityID );
if( temp != 0 )
{
if( temp->beforeMe != 0 )
temp->beforeMe->afterMe = temp->afterMe;
if( temp->afterMe != 0 )
temp->afterMe->beforeMe = temp->beforeMe;
temp->beforeMe = 0;
temp->afterMe = 0;
}
return temp;
}
Entity* EntityQueue::find( unsigned int entityID ) const
{
if( size == 0)
return 0;
Entity* temp = front;
while( temp != 0 )
{
if( temp->getID() == entityID )
return temp;
else
temp = temp->afterMe;
}
return temp;
}
| true |
45245aae4ed648101dc0450027ea29f9166bd259 | C++ | bugaevc/lets-write-sync-primitives | /src/condvar.h | UTF-8 | 445 | 2.71875 | 3 | [
"MIT"
] | permissive | #include <atomic>
#include <functional>
class Mutex;
class CondVar {
public:
CondVar(Mutex &mutex);
void wait();
void wait(std::function<bool()> condition);
void notify_one();
void notify_all();
private:
constexpr static uint32_t need_to_wake_one_bit = 1;
constexpr static uint32_t need_to_wake_all_bit = 2;
constexpr static uint32_t increment = 4;
Mutex &mutex;
std::atomic_uint32_t state { 0 };
};
| true |
137ddb8cd7ad732ca7bce7617b9ee4b1ce216a90 | C++ | ashwat-thama/Cpp_Programs | /cpp/for-tabel.cpp | UTF-8 | 216 | 2.828125 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
int main(){
int n,i;
int ans=0;
cout<<"ENTER THE NUMBER: ";
cin>>n;
for(i=1;i<=10;i++){
ans=i*n;
cout<<i<<"*"<<n<<": "<<ans<<"\n";
}
}
| true |
b420b92676d6c9cc130e461d1102e2f5d1a56234 | C++ | roddamatthew/uni | /2020/s1/oop/practical-02/function-1-3.cpp | UTF-8 | 872 | 3.5 | 4 | [] | no_license | #include <iostream>
void count_numbers(int array[4][4]){
int zeros=0;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
int fives=0;
int sixes=0;
int sevens=0;
int eights=0;
int nines=0;
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
switch(array[i][j]){
case 0:
zeros++;
break;
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
case 6:
sixes++;
break;
case 7:
sevens++;
break;
case 8:
eights++;
break;
case 9:
nines++;
break;
}
}
}
std::cout << "0:" << zeros << ";1:" << ones << ";2:" << twos << ";3:" << threes << ";4:" << fours << ";5:" << fives << ";6:" << sixes << ";7:" << sevens << ";8:" << eights << ";9:" << nines << ";" << std::endl;
}
| true |
a21f78c317600d5ba224f1ac13b649241e4faa0b | C++ | IRLSCU/QtController | /GpsBufferConsumeRunThread.cpp | UTF-8 | 2,231 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include "GpsBufferConsumeRunThread.h"
#include <QDebug>
GpsBufferConsumeRunThread::GpsBufferConsumeRunThread(GpsRingBuffer* gpsRingBuffer,QObject *parent=0):QThread(parent){
this->gpsRingBuffer=gpsRingBuffer;
m_startInit=false;
}
GpsBufferConsumeRunThread::~GpsBufferConsumeRunThread(){
qDebug()<<"GpsBufferReadInitRouteThread for initing route has been destoried";
}
void GpsBufferConsumeRunThread::stopImmediately(){
QMutexLocker locker(&m_lock);
m_isCanRun = false;
locker.unlock();
}
void GpsBufferConsumeRunThread::runSignal(bool signal){
QMutexLocker locker(&m_Initlock);
m_startInit=signal;
locker.unlock();
}
void GpsBufferConsumeRunThread::setSendStartGpsInfoSignal(){
QMutexLocker locker(&m_sendStartGpsInfoLock);
m_isSendStartGpsInfo=true;
locker.unlock();
}
void GpsBufferConsumeRunThread::run(){
m_isCanRun=true;
m_isSendStartGpsInfo=false;
//int i=0;
while(true){
GpsInfo gpsInfo;
if(gpsRingBuffer->pop(gpsInfo)){
//qDebug()<<(++i);
//gpsInfo.printInfo();
emit sendGpsInfo(QPointF(gpsInfo.longitude,gpsInfo.latitude));//绘图
if(m_startInit){//双重判断,由于加锁费时间
QMutexLocker locker2(&m_Initlock);
if(m_startInit){
emit sendRunGpsInfo(gpsInfo);//同时将数据发往ProcessRunDialog
}
locker2.unlock();
}
if(m_isSendStartGpsInfo){//发送起始坐标给ProcessRunDialog
QMutexLocker locker3(&m_sendStartGpsInfoLock);
if(m_isSendStartGpsInfo){
emit sendStartGpsInfo(gpsInfo);
m_isSendStartGpsInfo=false;
}
locker3.unlock();
}
}else{
this->msleep(GPSBUFFERCONSUMERUNTHREAD_BOLCKTIME);//阻塞否则cpu占用太高
}
QMutexLocker locker(&m_lock);
if(!m_isCanRun)//在每次循环判断是否可以运行,如果不行就退出循环
{
return;
}else{
locker.unlock();
}
}
qDebug()<<"GpsBufferConsumeRunThread for initing route has started";
}
| true |
98ed72172220e3d18de1a6fed4c953ad38fad4cb | C++ | xielongen/cpp_demo | /tests/Concurrent/test_thread.cpp | UTF-8 | 1,944 | 3.234375 | 3 | [] | no_license | //
// Created by x on 2020/4/18.
//
#include <gtest/gtest.h>
#include <thread>
#include <iostream>
#include <future>
class ThreadGuard{
std::thread& thread;
public:
explicit ThreadGuard(std::thread& t):thread(thread){}
~ThreadGuard(){
if(thread.joinable()){
thread.join();
}
}
ThreadGuard(ThreadGuard const &)=delete;
ThreadGuard& operator=(ThreadGuard const &)=delete;
};
int acc;
TEST(THREAD, JOIN){
struct RefCall{
int& acc;
RefCall(int& acc):acc(acc){}
void operator()(){
std::cout << "Thread Start" << std::endl;
for(int i=0; i < 100000000; i++){
acc += 1;
}
std::cout << "Thread Finished" << std::endl;
}
};
auto fun = RefCall(acc);
std::thread t(fun);
ThreadGuard tg(t);
// t.join();
std::cout << acc << std::endl;
}
void do_work(unsigned id){
std::cout << "Thread " << id << "is working!" << std::endl;
}
TEST(THREAD, BATCH){
std::cout << "Core Num:" << std::thread::hardware_concurrency() << std::endl;
std::vector<std::thread> threads;
for(unsigned i=0; i < 3; ++i)
{
threads.push_back(std::thread(do_work,i)); // 产生线程
}
std::for_each(threads.begin(),threads.end(), std::mem_fn(&std::thread::join));
}
#include <math.h>
double complex_compute(){
double res = 0;
for(long i=1; i < 3000000000; i++){
res += (1.0 / i / i);
}
std::this_thread::sleep_for(std::chrono::seconds(10));
return sqrt(res * 6);
}
std::string now(){
auto end_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return std::string(std::ctime(&end_time));
};
TEST(THREAD, FUTURE){
std::cout << now() << " Wait answer " << std::endl;
auto answer = std::async(complex_compute);
auto res = answer.get();
std::cout << now() << " The answer is " << res << std::endl;
} | true |
b83bb9baf5a0af5d73d80245d8471f5ffa28f385 | C++ | Nerja/EDA031 | /lab2_N/word.cc | UTF-8 | 630 | 3.28125 | 3 | [] | no_license | #include <string>
#include <vector>
#include "word.h"
using namespace std;
Word::Word(const string& w, const vector<string>& t) : word(w), trigrams(t) {}
string Word::get_word() const {
return word;
}
unsigned int Word::get_matches(const vector<string>& t) const {
unsigned int found = 0;
unsigned int t_index = 0;
unsigned int this_index = 0;
while(t_index < t.size() && this_index < trigrams.size()){
if(t.at(t_index) == trigrams.at(this_index)){
++found;
++t_index;
++this_index;
}
else if(t.at(t_index) < trigrams.at(this_index)){
t_index++;
}
else {
this_index++;
}
}
return found;
}
| true |
d46f8f6cd9a59caffcec64f6776bc71fe70bf0d7 | C++ | egorzainullin/workspace | /Old_projects/Projects/шаблоны и всякие нужные штуки/ConsoleApplication4/ConsoleApplication4/ConsoleApplication4.cpp | WINDOWS-1251 | 983 | 3.328125 | 3 | [
"Apache-2.0"
] | permissive | // ConsoleApplication4.cpp: .
//
#include <iostream>
using namespace std;
bool isInside(char s[], char s1[], int first)
{
int number = strlen(s);
int number1 = strlen(s1);
int count = 0;
for (int i = 0; i < number1; ++i)
{
if (s1[i] = s[i + first])
{
count++;
}
}
if (count = number1)
{
return true;
}
return false;
}
int countingHowmuch(char s[], char s1[])
{
int count = 0;
int number = strlen(s);
int number1 = strlen(s1);
int i = 0;
while (i <= (number - number1))
{
if (isInside(s, s1, i))
{
count++;
i = i + number1;
}
}
return count;
}
void getstring(char str[])
{
char symbol = ' ';
while (symbol != 13)
{
cin >> symbol;
cout << symbol;
str = str + symbol;
}
}
int main()
{
char s[] = "";
char s1[] = "";
cout << "enter s" << endl;
getstring(s);
cout << "enter s1" << endl;
getstring(s1);
system("pause");
return 0;
}
| true |
747fd837a893a35877fd15f0f7415566c7347225 | C++ | ahuertaalberca/C-Plus-Plus | /Chapter-7-Arrays/Review Questions and Exercises/Programming Challenges/05.cpp | UTF-8 | 4,164 | 4 | 4 | [
"MIT"
] | permissive | /************************************************************
*
* 05. Monkey Business
*
* A local zoo wants to keep track of how many pounds of
* food each of its three monkeys eats each day during a
* typical week. Write a program that stores this
* information in a two-dimensional 3 × 5 array, where
* each row represents a different monkey and each column
* represents a different day of the week. The program should
* first have the user input the data for each monkey. Then
* it should create a report that includes the following
* information:
*
* • Average amount of food eaten per day by the whole
* family of monkeys.
*
* • The least amount of food eaten during the week by
* any one monkey.
*
* • The greatest amount of food eaten during the week
* by any one monkey.
*
* Input Validation: Do not accept negative numbers for
* pounds of food eaten.
*
*************************************************************/
#include <iostream>
using namespace std;
// Global constants
const int ROWS = 3,
COLUMNS = 5;
// Function Prototypes
double inputValidate();
void getInfo(double[][COLUMNS]);
double getAverage(const double[][COLUMNS]);
double getLeast(const double[][COLUMNS]);
double getHighest(const double[][COLUMNS]);
int main()
{
double pounds_of_food[ROWS][COLUMNS];
double average_per_day,
least_per_week,
highest_per_week;
getInfo(pounds_of_food);
average_per_day = getAverage(pounds_of_food);
cout << "Average amount eaten during the week per day = "
<< average_per_day
<< endl;
least_per_week = getLeast(pounds_of_food);
cout << "Lowest amount eaten during the week = "
<< least_per_week
<< endl;
highest_per_week = getHighest(pounds_of_food);
cout << "Highest amount eaten during the week = "
<< highest_per_week
<< endl
<< endl;
return 0;
}
double inputValidate()
{
double number;
while(!(cin >> number) || number < 0)
{
cout << "Error, enter a positive number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return number;
}
void getInfo(double array[][COLUMNS])
{
double number_of_pounds;
cout << "\nEnter the following information, " << endl
<< "How many pounds of food eaten per day: " << endl;
for(int row = 0; row < ROWS; row++)
{
for(int column = 0; column < COLUMNS; column++)
{
cout << "Monkey #"
<< (row + 1)
<< ", on day "
<< (column + 1)
<< ": ";
array[row][column] = inputValidate();
}
cout << endl;
}
}
double getAverage(const double array[][COLUMNS])
{
double columns_sum;
int total_elements = ROWS * COLUMNS;
for(int row = 0; row < ROWS; row++)
{
for(int column = 0; column < COLUMNS; column++)
columns_sum += array[row][column];
}
return columns_sum / total_elements;
}
double getLeast(const double array[][COLUMNS])
{
double sum,
local_array[ROWS];
for(int row = 0; row < ROWS; row++)
{
sum = 0;
for(int column = 0; column < COLUMNS; column++)
sum += array[row][column];
local_array[row] = sum;
}
double lowest_number = local_array[0];
for (int number = 1; number < ROWS; number++)
{
if (local_array[number] <= lowest_number)
lowest_number = local_array[number];
}
return lowest_number;
}
double getHighest(const double array[][COLUMNS])
{
double sum,
local_array[ROWS];
for(int row = 0; row < ROWS; row++)
{
sum = 0;
for(int column = 0; column < COLUMNS; column++)
sum += array[row][column];
local_array[row] = sum;
}
double highest_number = local_array[0];
for (int number = 1; number < ROWS; number++)
{
if (local_array[number] >= highest_number)
highest_number = local_array[number];
}
return highest_number;
} | true |
1471b010d4e80e49a364a6f407c3d11369b12841 | C++ | DDHickey/dungeon-crawlers | /nationals.cpp | UTF-8 | 7,944 | 3.40625 | 3 | [] | no_license | /*
Legend for in game:
# is a wall
. is a floor
$ is a gold coin
x is a trap
s is the start of the level
f is the end of the game
@ is the player
2-5 is a level transition to the next level (indicated by the number)
Controls:
W forward
A left
S down
D right
(not case sens)
// NOTE TO SELF
Understand my logic in the future. I have created this application to test out arrays and specifically the multidimensional arrays.
SO problems I have encountered in this program is: passing arrays as parameters, returning arrays and parsing data from files.
Ways I have went to solve these issues started with using stringstream to parse the ints from the file (data on 1st line).
Next, I passed single dimension arrays to capture the entire data in one large array -- line by line, and then making a 2D array
and setting each character of the single array equal to the 2D array by using substring on each line of the 1D array.
Cool stuff to look at: ParseFile Function, copying data from single array to 2D array and the commented part in the main(),
specifically, the cycling through array using sizeof() to find the size of a 2D array, helps you determine the rows and cols size.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
void parseFile(string name, int intArray[]);
void mapToArray(string name, string map[]);
void clearScreen();
int main()
{
/*
NOTES:
string array[3][2] = {{"a", "b",} , {"c", "d"} , {"e", "f"}};
// CYCLE THROUGH ARRAY
for (int r = 0; r < sizeof(array) / sizeof(*array); r++) // ROWS
{
for (int c = 0; c < sizeof(array[0]) / sizeof(*array[0]); c++) // COLS
{
cout << array[r][c];
}
cout << endl;
}
//cout << endl;
//cout << sizeof(array) / sizeof(*array) << endl; // PRINTS ROWS.
//cout << sizeof(array[0]) / sizeof(*array[0]) << endl; // PRINTS COLS
*/
int intArray[2];
int currentLevel = 1;
int score = 0;
int health = 100;
int startLocationRow, startLocationCol;
string playerMovementFull;
bool gameEnd = false; // Game is ended when reach end of level 5.
while(currentLevel < 6)
{
stringstream loadMap;
loadMap << currentLevel;
string currentLevelPartOne = loadMap.str();
string currentLevelStr = "map" + currentLevelPartOne + ".txt";
parseFile(currentLevelStr, intArray);
string map[intArray[1] + 1];
mapToArray(currentLevelStr, map);
string map2D[intArray[1]][intArray[0]];
for (int row = 0; row < intArray[1]; row++)
{
for (int col = 0; col < intArray[0]; col++) // MAP
{
map2D[row][col] = map[row+1].substr(col,1);
//cout << map2D[row][col];
if (map[row+1].substr(col,1) == "s")
{
startLocationRow = row;
startLocationCol = col;
}
}
//cout << endl;
}
map2D[startLocationRow][startLocationCol] = "@";
///
//Print 2D Array
for (int r = 0; r < intArray[1]; r++) // ROWS
{
for (int c = 0; c < intArray[0]; c++) // COLS
{
cout << map2D[r][c];
}
cout << endl;
}
///
stringstream ss2;
ss2 << currentLevel + 1;
string nextLevel = ss2.str();
string playerMovement;
cin >> playerMovementFull;
while(!gameEnd)
{
clearScreen();
for (int run = 0; run < playerMovementFull.size(); run++ ){
playerMovement = playerMovementFull.substr(run,1);
if(playerMovement == "w" || playerMovement == "W")
{
if(startLocationRow - 1 >= 0)
{
if(map2D[startLocationRow-1][startLocationCol] != "#")
{
if(map2D[startLocationRow-1][startLocationCol] == "$")
{
score += 5;
}
if(map2D[startLocationRow-1][startLocationCol] == nextLevel || map2D[startLocationRow-1][startLocationCol] == "f")
{
clearScreen();
currentLevel += 1;
gameEnd = true;
}
if(map2D[startLocationRow-1][startLocationCol] == "x")
{
health -= 20;
if(health <= 0)
{
clearScreen();
cout << "You lost on level " << currentLevel << "!" << endl;
cout << "Your score was " << score << endl;
exit(1);
}
}
map2D[startLocationRow-1][startLocationCol] = "@";
map2D[startLocationRow][startLocationCol] = ".";
startLocationRow -= 1;
}
}
}
if(playerMovement == "s" || playerMovement == "S")
{
if(startLocationRow + 1 <= intArray[1]-1)
{
if(map2D[startLocationRow+1][startLocationCol] != "#")
{
if(map2D[startLocationRow+1][startLocationCol] == "$")
{
score += 5;
}
if(map2D[startLocationRow+1][startLocationCol] == nextLevel || map2D[startLocationRow+1][startLocationCol] == "f")
{
clearScreen();
currentLevel += 1;
gameEnd = true;
}
if(map2D[startLocationRow+1][startLocationCol] == "x")
{
health -= 20;
if(health <= 0)
{
clearScreen();
cout << "You lost on level " << currentLevel << "!" << endl;
cout << "Your score was " << score << endl;
exit(1);
}
}
map2D[startLocationRow+1][startLocationCol] = "@";
map2D[startLocationRow][startLocationCol] = ".";
startLocationRow += 1;
}
}
}
if(playerMovement == "a" || playerMovement == "A")
{
if(startLocationCol - 1 >= 0)
{
if(map2D[startLocationRow][startLocationCol-1] != "#")
{
if(map2D[startLocationRow][startLocationCol-1] == "$")
{
score += 5;
}
if(map2D[startLocationRow][startLocationCol-1] == nextLevel || map2D[startLocationRow][startLocationCol-1] == "f")
{
clearScreen();
currentLevel += 1;
gameEnd = true;
}
if(map2D[startLocationRow][startLocationCol-1] == "x")
{
health -= 20;
if(health <= 0)
{
clearScreen();
cout << "You lost on level " << currentLevel << "!" << endl;
cout << "Your score was " << score << endl;
exit(1);
}
}
map2D[startLocationRow][startLocationCol-1] = "@";
map2D[startLocationRow][startLocationCol] = ".";
startLocationCol -= 1;
}
}
}
if(playerMovement == "d" || playerMovement == "D")
{
if(startLocationCol + 1 <= intArray[0]-1)
{
if(map2D[startLocationRow][startLocationCol+1] != "#")
{
if(map2D[startLocationRow][startLocationCol+1] == "$")
{
score += 5;
}
if(map2D[startLocationRow][startLocationCol+1] == nextLevel || map2D[startLocationRow][startLocationCol+1] == "f")
{
clearScreen();
currentLevel += 1;
gameEnd = true;
}
if(map2D[startLocationRow][startLocationCol+1] == "x")
{
health -= 20;
if(health <= 0)
{
clearScreen();
cout << "You lost on level " << currentLevel << "!" << endl;
cout << "Your score was " << score << endl;
exit(1);
}
}
map2D[startLocationRow][startLocationCol+1] = "@";
map2D[startLocationRow][startLocationCol] = ".";
startLocationCol += 1;
}
}
}
}
///
//Print 2D Array
for (int r = 0; r < intArray[1]; r++) // ROWS
{
for (int c = 0; c < intArray[0]; c++) // COLS
{
cout << map2D[r][c];
}
cout << endl;
}
cout << "Score: " << score << endl;
cout << "Health: " << health << endl;
///
if(!gameEnd)
cin >> playerMovementFull;
}
clearScreen();
gameEnd = false;
}
cout << "You win with a score of: " << score << endl;
return 0;
}
void parseFile(string name, int intArray[])
{
ifstream myFile;
int count = 0;
myFile.open(name);
if(myFile.is_open())
{
string line;
getline(myFile, line);
stringstream stream(line);
while (1)
{
int n;
stream >> n;
if (!stream)
break;
intArray[count] = n;
count++;
}
myFile.close();
}
else
{
cout << "File could not open!" << endl;
exit(1);
}
}
void mapToArray(string name, string map[])
{
ifstream myFile;
myFile.open(name);
if(myFile.is_open())
{
string line;
int count = 0;
while(getline(myFile, line))
{
map[count] = line;
count ++;
}
myFile.close();
}
else
{
cout << "File could not open!" << endl;
exit(1);
}
}
void clearScreen()
{
for(int clear = 0; clear < 10; clear++)
{
cout << endl;
}
}
| true |
b0220d33b360ed83c5b3af62d774a698c8969248 | C++ | Anshnrag02/aglo-and-problem-solving | /arrayadt.cpp | UTF-8 | 2,607 | 3.53125 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(){
int length;
cout<<"Enter the number of elements in array.\n";
cin>>length;
int*arr=new int[length];
int size=0,num;
char resp='y';
do{
do{
cout<<"1.Add/Append\n2.Insert\n3.Change size\n4.Delete\n5.Search Index\n6.Search and Replace\n7.Reverse\n8.Show\n";
cin>>num;
}while(num<=1&&num>=8);
if(num==1)
{
if(size==length)
cout<<"Overflow";
else
{
cout<<"enter element at index "<<size<<endl;
cin>>arr[size];
size++;
}
}
if(num==2)
{
cout<<"enter the index\n";
int index,temp;
cin>>index;
cout<<"enter element at index"<<index<<endl;
cin>>temp;
for(int i=size;i>=index;i--)
{
arr[i]=arr[i+1];
}
arr[index]=temp;
size++;
}
if(num==3)
{
cout<<"enter new size"<<endl;
int m;
cin>>m;
int*q=new int[m];
for(int i=0;i<size;i++)
{
q[i]=arr[i];
}
delete []arr;
*arr=*q;
delete []q;
length=m;
}
if(num==4)
{
cout<<"enter the index\n";
int index;
cin>>index;
for(int i=index;i<size-1;i++)
{
arr[i]=arr[i+1];
}
size--;
}
if(num==6)
{
cout<<"enter the find\n";
int temp,index=-1,temp2;
cin>>temp;
cout<<"enter the replacement\n";
cin>>temp2;
for(int i=0;i<size;i++)
if(arr[i]==temp)
{
index=i;
break;
}
if(index>=0)
arr[index]=temp2;
else
cout<<"not found\n";
}
if(num==7)
{
int temp;
for(int i=0;i<size/2;i++)
{
temp=arr[size-i];
arr[size-i]=arr[i];
arr[i]=temp;
}
}
if(num==8)
{
for(int i=0;i<size;i++)
{
cout<<arr[i]<<"\t";
}
}
cout<<endl;
cout<<"press y to continue"<<endl;
cin>>resp;
}while(resp=='y');
delete []arr;
return 0;
}
| true |
5e8c01d4124eda367a467cce40e5cf0138a48c47 | C++ | philsmeby/SimpleJumpGame | /dasher.cpp | UTF-8 | 5,068 | 2.640625 | 3 | [] | no_license | #include "raylib.h"
#define global_variable static
global_variable int windowHeight;
global_variable int windowWidth;
struct AnimData
{
Rectangle rec;
Vector2 pos;
int frame;
float updateTime;
float runningTime;
};
bool isOnGround(AnimData *data)
{
return data->pos.y >= windowHeight - data->rec.height;
}
AnimData updateAnimData(AnimData *data, float deltaTime, int maxFrame)
{
data->runningTime += deltaTime;
if (data->runningTime >= data->updateTime)
{
data->runningTime = 0.0f;
// update animation frame
data->rec.x = data->frame * data->rec.width;
data->frame++;
if (data->frame > maxFrame)
{
data->frame = 0;
}
}
return *data;
}
int main()
{
windowHeight = 380;
windowWidth = 512;
// Initialize the window
InitWindow(windowWidth, windowHeight, "Dapper Dasher!");
const int gravity{1'000};
// nebula variables
Texture2D nebula = LoadTexture("textures/12_nebula_spritesheet.png");
const int sizeOfNebulae{5};
AnimData nebulae[sizeOfNebulae]{};
for (int i = 0; i < sizeOfNebulae; i++)
{
nebulae[i].rec.x = 0.0f;
nebulae[i].rec.y = 0.0f;
nebulae[i].rec.width = nebula.width/8;
nebulae[i].rec.height = nebula.height/8;
nebulae[i].pos.y = windowHeight - nebula.height/8;
nebulae[i].frame = 0;
nebulae[i].runningTime = 0.0f;
nebulae[i].updateTime = 0.0f;
nebulae[i].pos.x = windowWidth + i * 300;
}
float finishLine{ nebulae[sizeOfNebulae - 1].pos.x };
// nebula X velocity (pixels/second)
int nebVel{-200};
// Player Pawn
Texture2D playerSprite = LoadTexture("textures/scarfy.png");
AnimData player;
player.rec.width = playerSprite.width/6;
player.rec.height = playerSprite.height;
player.rec.x = 0;
player.rec.y = 0;
player.pos.x = windowWidth/2 - player.rec.width/2;
player.pos.y = windowHeight - player.rec.height;
player.frame = 0;
player.updateTime = 1.0/12.0;
player.runningTime = 0.0;
// Check player
bool isInAir{};
// Jump velocity is pixels/second
const int jumpVel{-600};
int velocity{0};
Texture2D background = LoadTexture("textures/far-buildings.png");
float bgX{};
Texture2D midground = LoadTexture("textures/back-buildings.png");
float mgX{};
Texture2D foreground = LoadTexture("textures/foreground.png");
float fgX{};
bool collision{};
// Game loop starts here
SetTargetFPS(60);
while(!WindowShouldClose())
{
// Delta time (time since last frame)
const float dT{GetFrameTime()};
BeginDrawing();
ClearBackground(WHITE);
// Scroll logic here
bgX -= 20 * dT;
if (bgX <= -background.width*2)
{
bgX = 0.0f;
}
mgX -= 40 * dT;
if (mgX <= -midground.width*2)
{
mgX = 0.0f;
}
fgX -= 80 *dT;
if (fgX <= -foreground.width*2)
{
fgX = 0.0f;
}
// Draw the background
// The two pictures are because we are displaying parts of each
Vector2 bg1Pos{bgX, 0.0};
DrawTextureEx(background, bg1Pos, 0.0f, 2.0f, WHITE);
Vector2 bg2Pos{bgX + background.width*2, 0.0};
DrawTextureEx(background, bg2Pos, 0.0f, 2.0f, WHITE);
// Draw the midground
Vector2 mg1Pos{mgX, 0.0};
DrawTextureEx(midground, mg1Pos, 0.0, 2.0, WHITE);
Vector2 mg2Pos{mgX + midground.width*2, 0.0};
DrawTextureEx(midground, mg2Pos, 0.0, 2.0, WHITE);
// Draw foreground
Vector2 fg1Pos{fgX, 0.0};
DrawTextureEx(foreground, fg1Pos, 0.0, 2.0, WHITE);
Vector2 fg2Pos{fgX + foreground.width*2, 0.0};
DrawTextureEx(foreground, fg2Pos, 0.0, 2.0, WHITE);
// TODO(Phil): Extract into void functions
if (isOnGround(&player))
{
velocity = 0;
isInAir = false;
}
else
{
velocity += gravity * dT;
isInAir = true;
}
if (IsKeyPressed(KEY_SPACE) && !isInAir)
{
velocity += jumpVel;
}
for (int i = 0; i < sizeOfNebulae; i++)
{
nebulae[i].pos.x += nebVel * dT;
}
finishLine += nebVel * dT;
player.pos.y += velocity * dT;
if (!isInAir)
{
player = updateAnimData(&player, dT, 5);
}
for (int i = 0; i < sizeOfNebulae; i++)
{
nebulae[i] = updateAnimData(&nebulae[i], dT, 7);
}
for (AnimData nebula : nebulae)
{
float pad{50};
Rectangle nebRec{
nebula.pos.x + pad,
nebula.pos.y + pad,
nebula.rec.width - 2*pad,
nebula.rec.height - 2*pad,
};
Rectangle playerRec{
player.pos.x,
player.pos.y,
player.rec.width,
player.rec.height,
};
if (CheckCollisionRecs(nebRec, playerRec))
{
collision = true;
}
}
// Handle win/lose condition
if (collision)
{
// If a collision has been detected we lose the game
DrawText("You Lose!", windowWidth/4, windowHeight/2, 40, RED);
}
else if (player.pos.x >= finishLine)
{
DrawText("You Won!", windowWidth/4, windowHeight/2, 40, RED);
}
else
{
for (int i = 0; i < sizeOfNebulae; i++)
{
DrawTextureRec(nebula, nebulae[i].rec, nebulae[i].pos, WHITE);
}
// Draw player pawn
DrawTextureRec(playerSprite, player.rec, player.pos, WHITE);
}
EndDrawing();
}
// On Exit code
UnloadTexture(playerSprite);
UnloadTexture(nebula);
UnloadTexture(background);
UnloadTexture(midground);
UnloadTexture(foreground);
CloseWindow();
} | true |
76512c74618d9ff4011144a98fa7b720bb92d2fd | C++ | even-wei/uva-practice | /679.cpp | UTF-8 | 501 | 2.71875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
using namespace std;
int main(void)
{
int T, D, I;
int power[20];
power[1] = 2;
for (int i = 2; i < 20; ++i)
power[i] = power[i - 1] << 1;
scanf("%d", &T);
while (T--) {
scanf("%d %d", &D, &I);
int v = (I - 1) % power[D - 1], w = 0;
for (int i = 1; i < D; ++i) {
w <<= 1;
w += v & 1;
v >>= 1;
}
printf("%d\n", power[D - 1] + w);
}
return 0;
}
| true |
00996ae92422d33e77ea3fbf3b31880daeeb4439 | C++ | timothyqiu/playground | /bilibili-live-danmaku/src/api.hpp | UTF-8 | 2,182 | 3.0625 | 3 | [] | no_license | #ifndef BLD_API_HPP_
#define BLD_API_HPP_
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
namespace api {
// 直播状态
enum class LiveStatus
{
Live = 1, // 直播中
Preparing = 2 // 准备中(包括轮播)
};
// 直播间信息
struct WebRoomInfo
{
int room_id; // 房间号
std::string title; // 房间标题
LiveStatus live_status; // 直播状态
int uid; // 主播号
std::string uname; // 主播名
int area_id; // 分区号
std::string area_name; // 分区名
// 支持短号
explicit WebRoomInfo(int id);
};
// 弹幕系统
namespace danmaku {
// 直播服务器信息
struct LiveServer
{
std::string host;
int ws_port;
int wss_port;
};
// 授权
struct Auth
{
std::vector<LiveServer> servers;
std::string token;
// servers 一定非空
explicit Auth(int room_id);
};
// 协议
enum class Protocol
{
Text = 0, // 负载为纯文本(如 JSON)
Binary = 1, // 负载为二进制
Compressed = 2, // 负载为 DEFLATE 压缩后的数据
};
// 指令
enum class Operation
{
// 请求
HeartbeatReq = 2, // 心跳(房间人气)
AuthReq = 7, // 鉴权
// 响应
HeartbeatResp = 3, // 心跳(房间人气)
AuthResp = 8, // 鉴权
Message = 5, // 一般消息
};
// 数据包
struct Packet
{
Protocol protocol;
Operation operation;
// 负载
std::uint8_t const *payload;
std::size_t payload_size;
// 构造心跳请求包
static auto make_heartbeat_req() -> Packet;
// 构造鉴权请求包
static auto make_auth_req(int room_id, std::string const& token) -> Packet;
// 反序列化
// 把原始数据切割、解析、解压成若干个包,得到的数据包不是 Text 就是 Binary 的
static auto load(void const *data, std::size_t size,
std::function<void(Packet const&)> packet_callback) -> void;
// 序列化
auto dump() const -> std::vector<std::uint8_t>;
};
} // namespace danmaku
} // namespace api
#endif // BLD_API_HPP_
| true |
169e39f26d3d08b9b788a10ea5578096350b3101 | C++ | SwitchDreams/simulador-tr1 | /src/CamadaFisicaTransmissora.cpp | UTF-8 | 2,653 | 3.0625 | 3 | [] | no_license | #include "../include/CamadaFisicaTransmissora.hpp"
BitArray *CFTBinaria::execute(BitArray *quadro) {
std::cout << "Codificação Binária: ";
quadro->print();
std::cout << std::endl;
return quadro;
}
BitArray *CFTManchester::execute(BitArray *quadro) {
int streamSize = 2*quadro->tam()*BYTE_SIZE;
BitArray* bitArray = new BitArray(streamSize);
for (unsigned int i = 0; i < streamSize/2 ; i++) {
if ((*quadro)[i]) {
//bitArray->setBit(i); // Copia informação do quadro
// Se o bit == 1, borda de caída 1->0
bitArray->setBit(i*2);
bitArray->clearBit(i*2 + 1);
} else {
//bitArray->clearBit(i); // Copia informação do quadro
// Se o bit == 0, borda de subida 0->1
bitArray->clearBit(i*2);
bitArray->setBit(i*2 + 1);
}
}
std::cout << "Codificação Manchester: ";
bitArray->print();
std::cout << std::endl;
return bitArray;
}
BitArray *CFTManchesterDiferencial::execute(BitArray *quadro) {
int streamSize = 2*quadro->tam()*BYTE_SIZE;
quadro->print();
std::cout << std::endl;
BitArray* bitArray = new BitArray(streamSize);
int lastState;
if ((*quadro)[0]) {
bitArray->setBit(0); // 0*2
bitArray->clearBit(1); // 0*2 + 1
lastState = 0;
} else {
bitArray->clearBit(0); // 0*2
bitArray->setBit(1); // 0*2 + 1
lastState = 1;
}
for (unsigned int i = 1; i < streamSize/2; i++) {
if ((*quadro)[i]) {
// Se o bit é 1, não há transição de estado
if (lastState) {
// Se terminou em 1, continua 1
bitArray->setBit(i*2);
bitArray->clearBit(i*2 + 1);
lastState = 0;
} else {
// Se terminou em 0, continua 0
bitArray->clearBit(i*2);
bitArray->setBit(i*2 + 1);
lastState = 1;
}
} else {
// Se o bit é 0, deve haver transição de estado
if (lastState) {
// Se terminou em 1, vai para 0
bitArray->clearBit(i*2);
bitArray->setBit(i*2 + 1);
lastState = 1;
} else {
// Se terminou em 0, vai para 1
bitArray->setBit(i*2);
bitArray->clearBit(i*2 + 1);
lastState = 0;
}
}
}
std::cout << "Codificação Manchester Diferencial: ";
bitArray->print();
std::cout << std::endl;
return bitArray;
}
| true |
fe2a52907aa30ec4c2fa387d6674b98f04236eaf | C++ | danielasun/ddd-oculus | /socket_stream/src/client_new/new_client.cpp | UTF-8 | 2,290 | 2.9375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <iostream>
#include <sstream>
#include <string.h>
#include "Packet.h"
void error(const char* msg)
{
perror(msg);
exit(0);
}
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
// open a connection
if (argc < 3)
{
std::cerr<< "usage hostname port\n" << std::endl;
return 0;
}
int portno = atoi(argv[2]);
int sockfd = socket(AF_INET,SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
struct hostent *server = gethostbyname(argv[1]);
if (server == NULL)
{
std::cerr << "usage " << argv[0] << " hostname port" << std::endl;
return 0;
}
struct sockaddr_in serv_addr;
bzero((char*) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) server->h_addr,
(char *) &serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if( connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0 )
error("ERROR connecting");
// read input from stdin
dxl_comm_packet pack;
for(int i=0; i<NUMBER_OF_MOTORS; i++)
{
while (true)
{
int pos;
std::cout << "Enter a number from 0 to 4096. ";
std::string input;
getline(std::cin, input);
if (std::stringstream(input) >> pos && pos >= 0 && pos <= 4096)
{
pack[2*i] = i;
pack[2*i+1] = pos;
break;
}
std::cerr << "Not a valid integer. (0 <= pos <= 4096)" << std::endl;
}
}
std::cout << pack[0] << std::endl;
std::cout << pack[1] << std::endl;
std::cout << pack[2] << std::endl;
std::cout << pack[3] << std::endl;
std::cout << PACKET_SIZE << std::endl;
// send packet
int n = write(sockfd,pack,PACKET_SIZE);
if ( n < 0)
error("ERROR problem writing to socket");
else
std::cout << n << " bytes written." << std::endl;
// close connection
close(sockfd);
}
| true |
732f752594c1119db62e55fe84dc98bd3e34e3d8 | C++ | litrod1733/210713_Minimum-Heap_LIS | /main.cpp | UTF-8 | 635 | 2.515625 | 3 | [
"MIT"
] | permissive | //
// Created by 이인성 on 2021/07/08.
//
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int main() {
// ios_base :: sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
priority_queue<int, vector<int>, greater<>> pq;
int N;
int x;
// cin >> N;
scanf("%d", &N);
for(int i=0; i<N; i++) {
// cin >> x;
scanf("%d", &x);
if(x == 0) {
if(pq.empty())
// cout << 0 << endl;
printf("%d\n", 0);
else {
// cout << pq.top() << endl;
printf("%d\n", pq.top());
pq.pop();
}
}
else
pq.push(x);
}
return 0;
} | true |
2a162d65300523fc72316fb172da89d705827877 | C++ | degarashi/spinner | /random/matrix.hpp | UTF-8 | 707 | 2.671875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../structure/range.hpp"
namespace spn {
namespace random {
// --------------- matrix ---------------
constexpr float DefaultRMatValue = 1e4f;
// ランダム値のデフォルト範囲
constexpr RangeF DefaultRMatRange{-DefaultRMatValue, DefaultRMatValue};
//! 要素の値がランダムな行列
template <class MT, class RDF>
auto GenRMatF(const RDF& rdf) {
MT m;
for(int i=0 ; i<MT::height ; i++) {
for(int j=0 ; j<MT::width ; j++)
m.ma[i][j] = rdf();
}
return m;
}
template <class MT, class RDF>
auto GenRMat(const RDF& rdf, const RangeF& r=DefaultRMatRange) {
auto rc = [&](){ return rdf(r); };
return GenRMatF<MT>(rc);
}
}
}
| true |
d9b789238918ffb87cb02ba28af60ef8c170b1c8 | C++ | sy2es94098/ITSA | /itsa/i33.cpp | UTF-8 | 781 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
int main(){
int i, sum, space = 0;
string str = "\n";
while(getline(cin, str))
{
space = 0 ;
sum = 0 ;
str=str.insert(str.size(), " ");
for( int i = 0 ; i < str.size() ; i++){
if(str[i] == ' ')
space++;
}
int data[space] = {0};
stringstream ss;
for( int i = 0 ; i < space ; i++){
ss.clear();
ss << str;
ss >> data[i];
sum += data[i];
}
cout << "Size: " << space << endl;
cout << "Average: " << fixed << setprecision(3) << (float)sum/(float)space << endl;
str = "\n";
}
}
| true |
bbef4cb5ee6d6e2d685d59ad4ffbd6fa4f08aa81 | C++ | Zzhc3321/cpp | /命名空间/05_共享数据的保护.cpp | GB18030 | 801 | 3.96875 | 4 | [] | no_license | #include <iostream>
using namespace std;
// ݳԱֵڶڼ䲻ܸı䡣
// гʼҲܱ¡
/*
const ˵ ;
Ա ˵ const;
ݳԱ const ˵ .
*/
class A{
public:
A(int i);
void print();
private:
const int a;
static const int b;
};
const int A::b = 10; //̬ݳԱ˵ͳʼ
A::A(int i):a(i){}//ݳԱֻͨʼбóֵ
void A::print(){
cout<<a<<":"<<b<<endl;
}
// õĶܱ¡
// const ˵ &
int main(){
A a1(100),a2(0);
a1.print();
a2.print();
return 0;
}
| true |
3919aa50bb39d2243f73f0f9fedd93eb1043dea4 | C++ | duttaANI/AL_Lab | /GFG/April2021/Longest Span in two Binary Arrays.cpp | UTF-8 | 522 | 2.5625 | 3 | [] | no_license | int longestCommonSum(bool arr1[], bool arr2[], int n) {
// code here
unordered_map<int,int> mp;
mp[0] = -1;
int X=0,Y=0;
int result =0;
for(int i=0;i<n;++i){
X += arr1[i];
Y += arr2[i];
int diff = X - Y;
if(mp.find(diff)==mp.end()){
mp[diff] = i;
}
else{
result = max({ result, i - mp[diff] });
}
}
return result;
} | true |
cf6dadb6910d25e8861fa7f75fe0cf1e9e533516 | C++ | jhke01/xolotl | /xolotl/xolotlCore/flux/PulsedFitFluxHandler.h | UTF-8 | 3,457 | 2.875 | 3 | [] | no_license | #ifndef PULSEDFITFLUXHANDLER_H
#define PULSEDFITFLUXHANDLER_H
#include "FluxHandler.h"
#include <cmath>
#include <MathUtils.h>
namespace xolotlCore {
/**
* This class realizes the IFluxHandler interface to calculate the incident V and I flux
* for tungsten material with a flux amplitude being intermittent.
*/
class PulsedFitFluxHandler: public FluxHandler {
private:
/**
* Total time length of the pulse
*/
double deltaTime;
/**
* Proportion of the total time where the flux amplitude is not 0.0
*/
double alpha;
/**
* Parameters for the gaussian profile
*/
double mu = 2000.0;
double sigma = 100.0;
/**
* Function that calculate the flux at a given position x (in nm).
* This function is not normalized.
*
* @param x The position where to evaluate the fit
* @return The evaluated value
*/
double FitFunction(double x) {
// Compute the polynomial fit
double value = exp(-pow((x - mu) / (sqrt(2.0) * sigma), 2.0));
return std::max(value, 0.0);
}
public:
/**
* The constructor
*/
PulsedFitFluxHandler() :
deltaTime(0.0), alpha(0.0) {
}
/**
* The Destructor
*/
~PulsedFitFluxHandler() {
}
/**
* Compute and store the incident flux values at each grid point.
* \see IFluxHandler.h
*/
void initializeFluxHandler(const IReactionNetwork& network, int surfacePos,
std::vector<double> grid) {
// Call the general method
FluxHandler::initializeFluxHandler(network, surfacePos, grid);
// Skip if the flux amplitude is 0.0 and we are not using a time profile
if (equal(fluxAmplitude, 0.0) && !useTimeProfile)
return;
// Set the flux index corresponding the the single vacancy cluster here
auto fluxCluster = network.get(Species::V, 1);
// Check that the vacancy cluster is present in the network
if (!fluxCluster) {
throw std::string(
"\nThe single vacancy cluster is not present in the network, "
"cannot use the flux option!");
}
fluxIndices.push_back(fluxCluster->getId() - 1);
// Set the flux index corresponding the the single interstitial cluster here
fluxCluster = network.get(Species::I, 1);
// Check that the interstitial cluster is present in the network
if (!fluxCluster) {
throw std::string(
"\nThe single interstitial cluster is not present in the network, "
"cannot use the flux option!");
}
fluxIndices.push_back(fluxCluster->getId() - 1);
return;
}
/**
* This operation computes the flux due to incoming particles at a given grid point.
* \see IFluxHandler.h
*/
void computeIncidentFlux(double currentTime, double *updatedConcOffset,
int xi, int surfacePos) {
// Check in which phase of the pulse we are
int cycle = currentTime / deltaTime;
// The flux is 0.0 after alpha * deltaTime
if (currentTime - ((double) cycle * deltaTime) > alpha * deltaTime
|| equal(deltaTime, 0.0) || equal(alpha, 0.0))
return;
// Update the concentration array
updatedConcOffset[fluxIndices[0]] += incidentFluxVec[0][xi - surfacePos]; // V
updatedConcOffset[fluxIndices[1]] += incidentFluxVec[0][xi - surfacePos]; // I
return;
}
/**
* This operation sets the time of the pulse.
* \see IFluxHandler.h
*/
void setPulseTime(double time) {
deltaTime = time;
return;
}
/**
* This operation sets proportion of the pulse that is on.
* \see IFluxHandler.h
*/
void setProportion(double a) {
alpha = a;
return;
}
};
//end class PulsedFitFluxHandler
}
#endif
| true |
44a487cfe5a46be5517cedc225af8921f88ae2be | C++ | shubhamguptaji/CPP | /4.cpp | UTF-8 | 1,662 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
int size;
class bill
{
protected:
int items[10];
float price[10];
public:
virtual void total()=0;
virtual void display()=0;
};
/*bill::bill(int items[],float price[],int size)
{
size=size;
for(int i=0;i<size;i++)
{
items[i]=items[i];
price[i]=price[i];
}
}*/
class Cheque:public bill
{
protected:
int no;
int sum;
char name[30];
float p[30];
int it[30];
public:
Cheque(int items[],float price[],int num,char n[],int s)
{
size=s;
strcpy(name,n);
no=num;
for(int i=0;i<size;i++)
{
it[i]=items[i];
p[i]=price[i];
}
}
void total()
{
for(int i=0;i<size;i++)
{
sum += p[i];
}
}
void display()
{
cout<<"payed by cheque"<<endl;
cout<<"cheque number:"<<no<<endl;
cout<<"name of bank:"<<name<<endl;
cout<<"total="<<sum<<endl;
}
};
class Cash:public bill
{
protected:
int sum=0;
int it[30];
float p[30];
public:
Cash(int items[],float price[],int s)
{
size=s;
for(int i=0;i<size;i++)
{
it[i]=items[i];
p[i]=price[i];
}
}
void total()
{
for(int i=0;i<size;i++)
{
sum += p[i];
}
}
void display()
{
cout<<"payed by cash"<<endl;
cout<<"total="<<sum<<endl;
}
};
//STUDENT CODE HERE
int main()
{
int s;
cin>>s;
int item[s];
for (int i=0;i<s;i++)
cin>>item[i];
float price[s];
for(int i=0;i<s;i++)
cin>>price[i];
int option;
cin>>option;
if(option==1)
{
int c_no;
char n[30];
cin>>c_no;
cin.ignore();
cin.getline(n,30);
Cheque Ch(item,price,c_no,n,s);
Ch.total();
Ch.display();
}
else if(option==2)
{
Cash C(item,price,s);
C.total();
C.display();
}
return 0;
}
| true |
8ce25f08db260a8384a2971ca272cdf558d3261e | C++ | yasir18/ncrwork | /CPP_Assignments/Assignment1/p7-matrix.cpp | UTF-8 | 1,280 | 3.3125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Matrix{
vector<vector<int> > vec;
public:
Matrix(){
// cout<<"Enter number of rows and columns :";
// int r,c;
// cin>>r>>c;
// vec.resize(r);
// for(int i=0;i<r;i++)
// {
// vec[i].resize(c);
// for(int j=0;j<vec[i].size();j++){
// vec[i][j]=0;
// }
// }
}
Matrix(int a,int b){
cout<<"Enter the values";
vec.resize(a);
for(int i=0;i<vec.size();i++){
vec[i].resize(b);
for(int j=0;j<vec[i].size();j++){
cin>>vec[i][j];
}
}
}
friend Matrix multiply(Matrix A,Matrix B){
Matrix C;
int rows=A.vec.size();
int cols=B.vec[0].size();
C.vec.resize(rows);
for(int i=0;i<C.vec.size();i++){
C.vec[i].resize(cols);
}
int c;
for(int i=0;i<rows;i++){
for(int k=0;k<cols;k++){
c=0;
for(int j=0;j<A.vec[0].size();j++){
c+=A.vec[i][j]*B.vec[j][k];
}
C.vec[i][k]=c;
}
}
return C;
}
void print(){
for(int i=0;i<vec.size();i++){
for(int j=0;j<vec[0].size();j++)
cout<<vec[i][j];
cout<<endl;
}
}
};
int main(){
int a,b;
cout<<"enter the number of rows and cols :";
cin>>a>>b;
Matrix A(a,b);
cout<<"enter the number of rows and cols :";
cin>>a>>b;
Matrix B(a,b);
Matrix C;
C=multiply(A,B);
C.print();
return 0;
} | true |
cfbc0156ec137f04fab449f1a7369d922111e18c | C++ | modernrio/Schulaufgaben | /06-3.3 ASCII-Alphabet/main.cpp | UTF-8 | 308 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int x = 0;
for (int i = 65; i <= 90 || i >= 96 && i <= 122; i++) {
x++;
printf("%c\t", i);
if (!(x % 7)) {
printf("\n");
}
if (i == 90) {
i = 96;
x = 0;
printf("\n\n");
}
}
printf("\n\n");
system("PAUSE");
return 0;
} | true |
139db5e1aad49cfb25fea9a33ee6665615ba782d | C++ | sniperswang/dev | /leetcode/leetCode/leetCode/nextPermutation.h | UTF-8 | 1,655 | 3.421875 | 3 | [] | no_license | //
// nextPermutation.h
// leetCode
//
// Created by Yao Wang on 9/28/13.
//
//
#ifndef leetCode_nextPermutation_h
#define leetCode_nextPermutation_h
class Solution { //my way
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int>::iterator iter;
vector<int>::iterator currPreIter;
int len = 1;
for(iter = num.end() -1;iter >= num.begin() + 1; iter--) {
currPreIter = iter -1;
if(*currPreIter >= *iter) {
len ++;
} else {
break;
}
}
std::sort(iter, iter+len);
if (iter != num.begin()) {
vector<int>::iterator preIter = iter-1;
for(vector<int>::iterator curr_iter = iter; curr_iter<=iter+len; curr_iter++) {
if(*curr_iter > *preIter) {
swap(*curr_iter, *preIter);
break;
}
}
}
}
};
class Solution { // STL way
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(next_permutation(num.begin(), num.end()) ) {
return;
} else {
sort(num.begin(),num.end());
}
}
};
/*
int myints [] = {2,3,5,4,2};
std::vector<int> num (myints, myints + sizeof(myints) / sizeof(int) );
Solution s;
s.nextPermutation(num);
for(int i = 0; i < num.size(); i++) {
cout << num[i] << " ";
}
cout << endl;
*/
#endif
| true |