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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2349d44a08f09758380eb5568f43f065567dcda3 | C++ | Osirisz/IoT101 | /ReadDHT11ToThingSpeak/ReadDHT11ToThingSpeak.ino | UTF-8 | 2,233 | 2.59375 | 3 | [] | no_license | #include "ThingSpeak.h"
#include <ESP8266WiFi.h>
#include "DHT.h"
//Define WiFi parameters
//const char* ssid = "Username";
//const char* password = "Password";
const char* ssid = "username";
const char* password = "password";
//Create WiFi Client and PubSub Client Object
WiFiClient wifiClient;
//Declare DHT sensor section
#define DHTPIN 12
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
//Declare ThingSpeak section
unsigned long myChannelNumber = channel_number; //change
const char* myWriteAPIKey = "write_apikey"; //change
String myStatus = "";
//Define loop variables
unsigned long previousMillis = 0;
const long interval = 20000;
void setup()
{
Serial.begin(115200);
setup_wifi();
ThingSpeak.begin(wifiClient);
dht.begin();
}
void loop()
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("% Temperature: ");
Serial.print(t);
Serial.println("*C");
// set the fields with the values
ThingSpeak.setField(1, (int) t);
ThingSpeak.setField(2, (int) h);
// figure out the status message
if((int)t >= 28)
{
myStatus = String("Air condition is closed");
}
else
{
myStatus = String("Air condition is opened");
}
// set the status
ThingSpeak.setStatus(myStatus);
// write to the ThingSpeak channel
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200)
{
Serial.println("Channel update successful.");
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}
}
void setup_wifi()
{
Serial.println();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.printf("Connecting to %s ", ssid);
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print(F("Connected, Your IP is "));
Serial.println(WiFi.localIP());
}
| true |
e30736319632ad5049f672643f8a654dabae7fb9 | C++ | scipianus/Algorithm-contests | /USACO/USACO - December 2011 - Silver/Rblock/Rblock.cpp | UTF-8 | 2,057 | 2.5625 | 3 | [] | no_license | /*
PROB: rblock
LANG: C++
*/
#include<fstream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
int n,m,sol;
struct Muchie{short x,y;int cost;};
vector <short> G[105],A;
Muchie v[10010];
int d1[105],dn[105],d[105];
void Citire()
{
int i;
ifstream fin("rblock.in");
fin>>n>>m;
for(i=1;i<=m;i++)
{
fin>>v[i].x>>v[i].y>>v[i].cost;
G[v[i].x].push_back(i);
G[v[i].y].push_back(i);
}
fin.close();
}
void Bellman_Ford_Initial()
{
vector <short>::iterator it;
short i,x,nod;
for(i=1;i<=n;i++)
d1[i]=2000000000;
queue <short> Q;
Q.push(1);
d1[1]=0;
while(!Q.empty())
{
x=Q.front();
Q.pop();
for(it=G[x].begin();it!=G[x].end();it++)
{
nod=v[*it].x+v[*it].y-x;
if(d1[nod]>d1[x]+v[*it].cost)
{
d1[nod]=d1[x]+v[*it].cost;
Q.push(nod);
}
}
}
for(i=1;i<=n;i++)
dn[i]=2000000000;
Q.push(n);
dn[n]=0;
while(!Q.empty())
{
x=Q.front();
Q.pop();
for(it=G[x].begin();it!=G[x].end();it++)
{
nod=v[*it].x+v[*it].y-x;
if(dn[nod]>dn[x]+v[*it].cost)
{
dn[nod]=dn[x]+v[*it].cost;
Q.push(nod);
}
}
}
}
void Selectare_Muchii()
{
short i;
int dist1,dist2,dist;
for(i=1;i<=m;i++)
{
dist1=d1[v[i].x]+dn[v[i].y]+v[i].cost;
dist2=d1[v[i].y]+dn[v[i].x]+v[i].cost;
dist=min(dist1,dist2);
if(dist==d1[n])
A.push_back(i);
}
}
void Bellman_Ford()
{
vector <short>::iterator it;
short i,x,nod;
for(i=1;i<=n;i++)
d[i]=2000000000;
queue <short> Q;
Q.push(1);
d[1]=0;
while(!Q.empty())
{
x=Q.front();
Q.pop();
for(it=G[x].begin();it!=G[x].end();it++)
{
nod=v[*it].x+v[*it].y-x;
if(d[nod]>d[x]+v[*it].cost)
{
d[nod]=d[x]+v[*it].cost;
Q.push(nod);
}
}
}
}
void Rezolvare()
{
vector <short>::iterator it;
Bellman_Ford_Initial();
Selectare_Muchii();
for(it=A.begin();it!=A.end();it++)
{
v[*it].cost*=2;
Bellman_Ford();
sol=max(sol,d[n]-d1[n]);
v[*it].cost/=2;
}
}
void Afisare()
{
ofstream fout("rblock.out");
fout<<sol<<"\n";
fout.close();
}
int main()
{
Citire();
Rezolvare();
Afisare();
return 0;
}
| true |
6ce12909f4654d58de7d784de480e5fd6168eaad | C++ | Creo2/Cits3002-Project | /QuestionServer/Source/QuizFactory/QuizFactory.cpp | UTF-8 | 3,740 | 2.78125 | 3 | [] | no_license | //=============================================================================
//Project: QuestionServer
//File:
//Author: Rhys Collier (22222918)
//CoAuthor: Alexander Slate (21498906)
//Created: 12/05/2018
//Description:
//
//Modified on: 25/05/2018
//Modified by: Rhys
//=============================================================================
#if __has_include("../BaseHeader.h")
#include "../BaseHeader.h"
#endif
#include "QuizFactory.h"
#include "../Questions/Quiz.h"
QuizFactory::QuizFactory() {
quizLookUpTable = {};
}
bool QuizFactory::Init(const char* dir) {
printf("\n----------*Initializing Quizes!*----------\n");
std::vector<std::string> files = getXMLsInDirectory(dir);
for (std::string file : files) {
tinyxml2::XMLDocument quizs;
if (quizs.LoadFile(file.c_str()) != 0) {
char message[BUFSIZ];
sprintf_s(message, "Error: could not open %s.\n Please check input data and ensure proper XML format\n", file.c_str());
DisplayErrorBox(TEXT(message));
continue;
}
tinyxml2::XMLElement* rootElement = quizs.RootElement();
if (rootElement == NULL) {
char message[BUFSIZ];
sprintf_s(message, "Warning: Nothing in file %s\n", file.c_str());
DisplayErrorBox(TEXT(message));
continue;
}
while (rootElement != NULL) {
StrongQuizPtr newQuiz = CreateQuiz(rootElement, file.c_str());
if (newQuiz != NULL) {
quizLookUpTable.insert(std::pair<QuizId, StrongQuizPtr>(newQuiz->quizID, newQuiz));
}
rootElement = rootElement->NextSiblingElement("Quiz");
}
}
if (quizLookUpTable.size() == 0) {
return false;
}
printf("\n----------*Initializing Quizes Done!*----------\n");
return true;
}
StrongQuizPtr QuizFactory::CreateQuiz(tinyxml2::XMLElement* quizData, std::string file) {
int quizID;
tinyxml2::XMLElement* IDElement = quizData->FirstChildElement("QuizId");
if (IDElement == NULL) {
char message[BUFSIZ];
sprintf_s(message, "Warning: Quiz in %s has no ID\n", file.c_str());
DisplayErrorBox(TEXT(message));
return StrongQuizPtr();
}
IDElement->QueryIntAttribute("v", &quizID);
StrongQuizPtr newQuiz = std::make_shared<Quiz>(quizID);
if (!newQuiz->Init(quizData)) {
char message[BUFSIZ];
sprintf_s(message, "Warning: Quiz %d in %s could not be initialised\n", quizID, file.c_str());
DisplayErrorBox(TEXT(message));
return StrongQuizPtr();
}
return newQuiz;
}
StrongQuizPtr QuizFactory::GetQuiz(QuizId id) {
//See if quiz id is in table of quizes if not then return an empty string
StrongQuizPtr quiz;
try {
quiz = quizLookUpTable.at(id);
}
catch (const std::out_of_range& oor) {
return NULL;
}
return quiz;
}
std::string QuizFactory::QuestionOutput(QuestionId id) {
QuizId quizID = QuizId((id / 1000) * 1000);
StrongQuizPtr quiz = GetQuiz(quizID);
if (quiz == NULL) {
return std::string();
}
return quiz->QuestionOutput(id);
}
int QuizFactory::QuestionMark(QuestionId id, std::string answer) {
QuizId quizID = QuizId((id / 1000) * 1000);
StrongQuizPtr quiz = GetQuiz(quizID);
if (quiz == NULL) {
return WRONG_ID;
}
return quiz->QuestionMark(id, answer);
}
std::string QuizFactory::QuizOutput(QuizId id) {
StrongQuizPtr quiz = GetQuiz(id);
if (quiz == NULL) {
return std::string();
}
return quiz->AllQuestionOutput();
}
std::string QuizFactory::ListOfQuizs(void) {
std::string answer = "";
for (std::pair<QuizId, StrongQuizPtr> quiz : quizLookUpTable) {
answer.append("QuizId=");
answer.append(std::to_string(quiz.first));
answer.append("&MultipleChoice=");
answer.append(std::to_string(quiz.second->numbMultipleChoice));
answer.append("&Coding=");
answer.append(std::to_string(quiz.second->numbCoding));
answer.append("&");
}
answer.pop_back();
return answer;
} | true |
f8e83bf047012f0b154ed4909627617c3446f757 | C++ | drewdzzz/drew | /Onegin1.cpp | WINDOWS-1251 | 5,737 | 3.375 | 3 | [] | no_license | #include <stdio.h>
#define INPUTFILE_NAME "onegin.txt"
#define OUTPUTFILE_NAME "oneginOut.txt"
#define SIZE 50
#define STRING_LIMIT 50
//#define DEBUG
//{----------------------------------------------------------------------------
//! @brief
//!
//! @param sortingArray ,
//!
//! @param left
//!
//! @param right
//!
//!
//}----------------------------------------------------------------------------
void quickSort ( char sortingArray[SIZE][STRING_LIMIT], int left, int right);
//{----------------------------------------------------------------------------
//!
//! @brief
//!
//! @param fp ,
//!
//! @param poem char,
//!
//! @param [out] *sizeofpoem , - ( STRING_LIMIT)
//!
//! @par :
//! @code
//! readInput ( fp, poem, &sizeofpoem);
//! @endcode
//}----------------------------------------------------------------------------
void readInput ( FILE* fp, char poem[SIZE][STRING_LIMIT], int* sizeofpoem );
//int bubbleSort ( char poem [SIZE][STRING_LIMIT], int );
int main ()
{
FILE* fp;
if ( !(fp = fopen ( INPUTFILE_NAME, "r")) )
{
printf ("Input file is not open");
return 1;
}
int sizeofpoem = STRING_LIMIT;
char poem[SIZE][STRING_LIMIT];
readInput ( fp, poem, &sizeofpoem );
#ifdef DEBUG
printf ("Reading complete!\n");
for ( int i = 0; i < sizeofpoem; i++)
puts(poem[i]);
#endif
quickSort ( poem, 0, sizeofpoem-1);
//bubbleSort ( poem, sizeofpoem);
#ifdef DEBUG
printf ("Poem Sorted!");
#endif
fclose(fp);
if ( !(fp = fopen ( OUTPUTFILE_NAME, "w")) )
{
printf ("Output file is not open");
return 1;
}
for (int i = 0; i < sizeofpoem; i++)
fputs ( poem[i], fp);
return 0;
}
void readInput ( FILE* fp, char inputArray[SIZE][STRING_LIMIT], int* sizeofpoem)
{
for (int i = 0; i < *sizeofpoem; i++)
if (!feof (fp))
fgets ( inputArray[i], SIZE, fp);
else
{
*sizeofpoem = i;
return;
}
}
void quickSort ( char sortingArray[SIZE][STRING_LIMIT], int left, int right)
{
void swap ( char [SIZE][STRING_LIMIT], int, int);
int strcmp (char*, char*);
char* mid = sortingArray[ (left + right) / 2];
int l = left;
int r = right;
while ( right > left )
{
while ( strcmp ( sortingArray[left], mid) < 0 ) left++;
while ( strcmp ( sortingArray[right] , mid ) > 0 ) right--;
if (left < right) swap ( sortingArray, left, right);
left++;
right--;
}
if ( l < right ) quickSort( sortingArray, l, right);
if ( r > left ) quickSort( sortingArray, left, r);
}
/*
int bubbleSort( char poem [SIZE][STRING_LIMIT], int arraySize)
{
int strcmp (char*, char*);
void swap ( char [SIZE][STRING_LIMIT], int, int);
for (int i = 0; i < arraySize; i++)
for (int j = i; j < arraySize; j++)
if ( strcmp ( poem[i], poem[j]) > 0 )
{
swap (poem, i, j);
#ifdef DEBUG
printf("SWAPPED!");
#endif
}
}
*/
//{----------------------------------------------------------------------------
//! @brief ( )
//!
//! @return (0 , >0 a>b, <0 a<b)
//!
//!
//!
//!
//}----------------------------------------------------------------------------
int strcmp ( char* a, char* b )
{
#ifdef DEBUG
printf ("IS COMPARING...\n");
#endif
int i = 0;
char* string1 = a;
char* string2 = b;
while ( string1[i] != '\0' && string2[i] != '\0' )
{
if ( string1[i] >= 'A' && string1[i] <= 'Z' ) string1 += 'a' - 'A';
if ( string2[i] >= 'A' && string2[i] <= 'Z' ) string2 += 'a' - 'A';
if ( string1[i] != string2[i] ) return string1[i] - string2[i];
i++;
}
return string1[i] - string2[i];
}
//{----------------------------------------------------------------------------
//!
//! @brief char
//!
//! @param array ,
//! @param a
//! @param b
//!
//}----------------------------------------------------------------------------
void swap (char array[SIZE][STRING_LIMIT], int a, int b)
{
#ifdef DEBUG
printf("IS SWAPPING...\n");
#endif
for (int i = 0; i < SIZE; i++)
{
char temp = array[a][i];
array[a][i] = array[b][i];
array[b][i] = temp;
}
}
| true |
59b6453e53527deb4552c220362f7e6593695740 | C++ | mrboorger/TEST | /4.cpp | UTF-8 | 476 | 3.21875 | 3 | [] | no_license | //
// Created by mrboorger on 05.09.2020.
//
#include <iostream>
int main() {
long long x = 0;
long long y = 0;
std::cout << "Enter x and y" << std::endl;
std::cin >> x >> y;
if (y < 0) {
y = -y;
}
bool negative = false;
if (x < 0) {
x = -x;
negative = true;
}
x <<= 5;
long long ans = x & ((1ll << y) - 1);
if (negative) {
ans = (1ll << y) - ans;
}
std::cout << "(32 * x) mod (2 ^ |y|) = " << ans << std::endl;
return 0;
} | true |
a3c5598706ddac87b2db5afb20e2186f847a6322 | C++ | abufarhad/Programming | /C++ Practice/prime add.cpp | UTF-8 | 846 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define ll long long
int SieveOfEratosthenes(long long int n)
{
int cnt=2,count=0,i;
bool prime[n+1];
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++)
{
if (prime[p] == true)
{
for (int i=p*2; i<=n; i += p)
prime[i] = false;
}
}
int a[100000];
for(int m=1;m<=n;m++){ a[m]=0; }
for (int p=2; p<=n; p++)
if (prime[p]==true)
p=a[i]; cnt++;
for (int k=2; k<cnt; k++)
if(prime[k]+prime[cnt]==n)
count++;
}
int main()
{
ll n,i,t,j,cnt; cin>>t;
for( int j = 1; j <=t; j++ ){ cin>>n; cnt=0;
if(SieveOfEratosthenes(n)){ cnt++;//cout<<endl<<i<<" " <<n-i; return 0;
printf("%d %d\n",i,n-i); }}
cout<<"Case "<<j<<": "<<cnt<<endl;
return 0;
}
| true |
39ec9938bf7a1a0bfdfa12b4c9c5b6370e2f2dac | C++ | marion2016/LeetcodeAndHuaweiOJ | /Huawei_oj/003MingmingRandomNum/MingmingRandomNum/MingmingRandomNum.cpp | GB18030 | 1,086 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
void Qsort(vector<int> &a, int left, int right){
int l = left, r = right;
if (l >= r) return;
int key = a[l];
while (l<r){
while (a[r] >= key && l<r) r--;//ҵǰұߵһkeyСֵ
a[l] = a[r];//keyСֵֵǰa[l]ʹkeyֵ߶keyС
while (a[l] <= key && l<r) l++;//ҵǰߵһkeyֵ
a[r] = a[l];//keyֵֵǰa[r]ʹkeyֵұ߶key
}
a[l] = key;//keyֵֵٽl||r
//ǰl߶keyСұ߶key ֻҪ[left,l-1][l+1,right]
Qsort(a, left, l - 1);
Qsort(a, l + 1, right);
}
int main()
{
int n;
cin >> n;
int num;
vector<int> v;
for (int i = 0; i < n; i++)
{
cin >> num;
if (v.end() == find(v.begin(), v.end(), num))
{
v.push_back(num);
}
}
Qsort(v, 0, v.size() - 1);
for (int j = 0; j < v.size(); j++)
{
cout << v[j] << endl;
}
// system("pause");
return 0;
} | true |
0ed52c18b1ba3de35af0592c6d32f37345153c6b | C++ | jackwadden/mnrl | /C++/include/MNRLError.hpp | UTF-8 | 2,793 | 2.984375 | 3 | [
"BSD-3-Clause"
] | permissive | // Kevin Angstadt
// angstadt {at} virginia.edu
//
// MNRLError.hpp
#ifndef MNRLERROR_HPP
#define MNRLERROR_HPP
#include <stdexcept>
namespace MNRL{
namespace MNRLError {
class MNRLError : public std::runtime_error {
public:
MNRLError() : runtime_error("Unspecified MNRL Error!") {}
MNRLError(std::string msg):runtime_error(msg.c_str()){}
};
class DuplicateIdError: public MNRLError {
public:
DuplicateIdError(std::string id) : MNRLError(id + " is already defined"), id(id) {}
std::string get_id() { return id; }
private:
std::string id;
};
class DuplicatePortError: public MNRLError {
public:
DuplicatePortError(std::string port_id) : MNRLError(port_id + " is already defined"), port_id(port_id) {}
std::string get_port_id() { return port_id; }
private:
std::string port_id;
};
class EnableError : public MNRLError {
public:
EnableError(std::string enable) : MNRLError("unknown enable code " + enable), enable(enable) {}
std::string get_enable() { return enable; }
private:
std::string enable;
};
class UpCounterThresholdError : public MNRLError {
public:
UpCounterThresholdError(int threshold) : MNRLError("threshold must be a non-negative integer"), threshold(threshold) {}
int get_threshold() { return threshold; }
private:
int threshold;
};
class UpCounterModeError : public MNRLError {
public:
UpCounterModeError(std::string mode) : MNRLError("invalid mode " + mode), mode(mode) {}
std::string get_mode() { return mode; }
private:
std::string mode;
};
class InvalidGatePortCount : public MNRLError {
public:
InvalidGatePortCount(int port_count) : MNRLError("gate port count must be a positive integer"), port_count(port_count) {}
int get_port_count() { return port_count; }
private:
int port_count;
};
class InvalidGateType : public MNRLError {
public:
InvalidGateType(std::string gate) : MNRLError("unknown gate type " + gate), gate(gate) {}
std::string get_gate() { return gate; }
private:
std::string gate;
};
class UnknownNode : public MNRLError{
public:
UnknownNode(std::string id) : MNRLError("node not found"), id(id) {}
std::string get_id() { return id; }
private:
std::string id;
};
class UnknownPort : public MNRLError {
public:
UnknownPort(std::string id) : MNRLError("port not found: " + id), id(id) {}
std::string get_id() { return id; }
private:
std::string id;
};
class PortWidthMismatch : public MNRLError {
public:
PortWidthMismatch(int source, int destination) : MNRLError("port widths do not align"), source(source), destination(destination) {}
int get_source() { return source; }
int get_destination() { return destination; }
private:
int source, destination;
};
}
}
#endif
| true |
050f0d1ce1908a08ae47f40757882384b4d84179 | C++ | Aandree5/BinaryTree-Graph | /BinaryTree.cpp | UTF-8 | 11,986 | 3.1875 | 3 | [] | no_license | #include "pch.h"
#include "BinaryTree.h"
#include "BinaryTreeNode.h"
#include "StackSingly.h"
#include "ConsoleHelpers.h"
using namespace ConsoleHelpers;
BinaryTree::BinaryTree()
{
root = nullptr;
}
shared_ptr<BinaryTreeNode> BinaryTree::insert(string value)
{
shared_ptr<BinaryTreeNode> nodeToReturn;
if (!root)
{
root = make_shared<BinaryTreeNode>(value);
nodeToReturn = root;
}
else
{
shared_ptr<BinaryTreeNode> current = root;
while (!nodeToReturn)
{
if (current->value == value)
{
current->frequency++;
nodeToReturn = current;
}
else
{
tempMarked.push_back(current->value);
shared_ptr<BinaryTreeNode> &childReference = (value < current->value ? current->left : current->right);
if (!childReference)
{
nodeToReturn = make_shared<BinaryTreeNode>(value);
nodeToReturn->parent = current;
childReference = nodeToReturn;
balanceTree(nodeToReturn);
}
else
current = childReference;
}
}
}
lastChanged = value;
return nodeToReturn;
}
shared_ptr<BinaryTreeNode> BinaryTree::find(string value)
{
if (value == "")
throw invalid_argument("'value' can't be empty.");
shared_ptr<BinaryTreeNode> current = root;
printC("?(" + value + "): ", C_CYAN);
if (!current)
{
printC(" ### NO ###", C_RED);
cout << endl << endl;
}
else
{
do
{
if (current->value == value)
{
cout << current->value;
printC(" ### YES ###", C_GREEN);
cout << endl << endl;
lastChanged = current->value;
break;
}
else
{
cout << current->value << " > ";
tempMarked.push_back(current->value);
current = (value < current->value ? current->left : current->right);
if (!current)
{
printC(" ### NO ###", C_RED);
cout << endl << endl;
}
}
} while (current);
}
return current;
}
shared_ptr<BinaryTreeNode> BinaryTree::remove(string value)
{
if (value == "")
throw invalid_argument("'value' can't be empty.");
shared_ptr<BinaryTreeNode> node = find(value);
return (node ? remove(node) : nullptr);
}
shared_ptr<BinaryTreeNode> BinaryTree::remove(shared_ptr<BinaryTreeNode> node)
{
if (!node)
throw invalid_argument("'node' can't be null.");
shared_ptr<BinaryTreeNode> parent = node->parent.lock();
if (node->frequency > 1)
node->frequency--;
else if (node->isLeaf())
{
if (parent)
{
(parent->left == node ? parent->left : parent->right) = nullptr;
balanceTree(parent);
lastChanged = parent->value;
}
else
{
root = nullptr;
lastChanged = "";
}
}
else if (shared_ptr<BinaryTreeNode> child = node->hasOnlyOnechild())
{
if (parent)
{
(parent->left == node ? parent->left : parent->right) = child;
child->parent = parent;
}
else // Node parent is a weak pointer. no need to set null
root = child;
balanceTree(child);
lastChanged = child->value;
}
else
{
shared_ptr<BinaryTreeNode> replacerNode = getFurthestReplacerNode(node);
shared_ptr<BinaryTreeNode> balanceFrom = replacerNode->parent.lock();
// When replacerNode is removed there's only two options, or is leaf or has only one child
// Because getFurthestReplacerNode() will choose the min or max of either side, if it had two children the function would continue
if (shared_ptr<BinaryTreeNode> child = replacerNode->hasOnlyOnechild())
{
child->parent = replacerNode;
// No need to check if is root, replacernode will always be on top of every child, forcing this node to have a parent
(balanceFrom->left == replacerNode ? balanceFrom->left : balanceFrom->right) = child;
balanceFrom = child;
}
else
(balanceFrom->left == replacerNode ? balanceFrom->left : balanceFrom->right) = nullptr;
replacerNode->parent = node->parent;
replacerNode->left = node->left;
replacerNode->right = node->right;
if (parent)
(parent->left == node ? parent->left : parent->right) = replacerNode;
else
root = replacerNode;
if (node->left)
node->left->parent = replacerNode;
if (node->right)
node->right->parent = replacerNode;
balanceTree(balanceFrom);
lastChanged = replacerNode->value;
}
return node;
}
int BinaryTree::checkBalance(shared_ptr<BinaryTreeNode> node)
{
if (!node)
throw invalid_argument("'node' can't be null.");
int depthLeft = (node->left ? node->left->depth : 0);
int depthRight = (node->right ? node->right->depth : 0);
return depthRight - depthLeft;
}
int BinaryTree::getCorrectDepth(shared_ptr<BinaryTreeNode> node)
{
if (!node)
throw invalid_argument("'node' can't be null.");
if (node->isLeaf())
return 1;
else if (shared_ptr<BinaryTreeNode> child = node->hasOnlyOnechild())
return child->depth + 1;
else
return (node->left->depth > node->right->depth ? node->left->depth : node->right->depth) + 1;
}
void BinaryTree::balanceTree(shared_ptr<BinaryTreeNode> node)
{
if (!node)
throw invalid_argument("'node' can't be null.");
int balance = checkBalance(node);
if (balance >= -1 && balance <= 1)
{
node->depth = getCorrectDepth(node);
if (shared_ptr<BinaryTreeNode> parent = node->parent.lock())
balanceTree(parent);
}
else
{
if (balance < -1) // Left Heavy
{
int childBalance = checkBalance(node->left);
// Left Right Heavy
/* T -> R
/ -> / \
O -> O T
\ ->
R -> */
if (childBalance > 0)
{
shared_ptr<BinaryTreeNode> tempLeftRight = node->left->right;
if (tempLeftRight->left)
tempLeftRight->left->parent = node->left;
if (tempLeftRight->right)
tempLeftRight->right->parent = node;
node->left->right = tempLeftRight->left;
tempLeftRight->left = node->left;
node->left = tempLeftRight->right;
tempLeftRight->right = node;
if (shared_ptr<BinaryTreeNode> parent = node->parent.lock())
(parent->left == node ? parent->left : parent->right) = tempLeftRight;
else
root = tempLeftRight;
tempLeftRight->parent = node->parent;
tempLeftRight->left->parent = tempLeftRight;
node->parent = tempLeftRight;
tempLeftRight->depth = getCorrectDepth(tempLeftRight);
tempLeftRight->left->depth = getCorrectDepth(tempLeftRight->left);
}
// Left Left Heavy
/* T -> O
/ -> / \
O -> L T
/ ->
L -> */
else
{
shared_ptr<BinaryTreeNode> tempRight = node->left->right;
node->left->right = node;
node->left->parent = node->parent;
if (shared_ptr<BinaryTreeNode> parent = node->parent.lock())
(parent->left == node ? parent->left : parent->right) = node->left;
else
root = node->left;
node->parent = node->left;
if (tempRight)
{
node->left = tempRight;
tempRight->parent = node;
}
else
node->left = nullptr;
}
}
else if (balance > 1) // Right Heavy
{
int childBalance = checkBalance(node->right);
// Right Left Heavy
/* T -> V
\ -> / \
X -> T X
/ ->
V -> */
if (childBalance < 0)
{
shared_ptr<BinaryTreeNode> tempRightLeft = node->right->left;
if (tempRightLeft->right)
tempRightLeft->right->parent = node->right;
if (tempRightLeft->left)
tempRightLeft->left->parent = node;
node->right->left = tempRightLeft->right;
tempRightLeft->right = node->right;
node->right = tempRightLeft->left;
tempRightLeft->left = node;
if (shared_ptr<BinaryTreeNode> parent = node->parent.lock())
(parent->left == node ? parent->left : parent->right) = tempRightLeft;
else
root = tempRightLeft;
tempRightLeft->parent = node->parent;
tempRightLeft->right->parent = tempRightLeft;
node->parent = tempRightLeft;
tempRightLeft->depth = getCorrectDepth(tempRightLeft);
tempRightLeft->right->depth = getCorrectDepth(tempRightLeft->right);
}
// Right Right Heavy
/* T -> X
\ -> / \
X -> T Z
\ ->
Z -> */
else
{
shared_ptr<BinaryTreeNode> tempLeft = node->right->left;
node->right->left = node;
node->right->parent = node->parent;
if (shared_ptr<BinaryTreeNode> parent = node->parent.lock())
(parent->left == node ? parent->left : parent->right) = node->right;
else
root = node->right;
node->parent = node->right;
if (tempLeft)
{
node->right = tempLeft;
tempLeft->parent = node;
}
else
node->right = nullptr;
}
}
node->depth = getCorrectDepth(node);
if (shared_ptr<BinaryTreeNode> parent = node->parent.lock())
{
parent->depth = getCorrectDepth(parent);
if (parent = parent->parent.lock())
balanceTree(parent);
}
}
}
pair<shared_ptr<BinaryTreeNode>, int> BinaryTree::findMax(shared_ptr<BinaryTreeNode> node)
{
int count = 1;
while (node->right)
{
count++;
node = node->right;
}
return pair<shared_ptr<BinaryTreeNode>, int>(node, count);
}
pair<shared_ptr<BinaryTreeNode>, int> BinaryTree::findMin(shared_ptr<BinaryTreeNode> node)
{
int count = 1;
while (node->left)
{
count++;
node = node->left;
}
return pair<shared_ptr<BinaryTreeNode>, int>(node, count);
}
shared_ptr<BinaryTreeNode> BinaryTree::getFurthestReplacerNode(shared_ptr<BinaryTreeNode> node)
{
pair<shared_ptr<BinaryTreeNode>, int> min = findMin(node->right);
pair<shared_ptr<BinaryTreeNode>, int> max = findMax(node->left);
return (min.second > max.second ? min.first : max.first);
}
void BinaryTree::printInOrder(shared_ptr<BinaryTreeNode> node)
{
if (!node)
node = root;
if (node->left)
printInOrder(node->left);
cout << to_string(node->frequency) << " " << node->value << endl;
if (node->right)
printInOrder(node->right);
}
void BinaryTree::printPostOrder(shared_ptr<BinaryTreeNode> node)
{
if (!node)
node = root;
if (node->left)
printInOrder(node->left);
if (node->right)
printInOrder(node->right);
cout << to_string(node->frequency) << " " << node->value << endl;
}
void BinaryTree::print()
{
if (!root)
cout << "Tree is empty";
StackSingly<BinaryTreeNode> stack = StackSingly<BinaryTreeNode>();
stack.push(root);
while (!stack.isEmpty())
{
shared_ptr<BinaryTreeNode> current = stack.pop();
// FILO: Right has to go first so left will be poped first
if (current->right)
stack.push(current->right);
if (current->left)
stack.push(current->left);
shared_ptr<BinaryTreeNode> parent = root;
while (parent != current)
{
if (parent->right == current || (parent == current->parent.lock() && parent->hasOnlyOnechild()))
{
cout << char(192) << char(196);
break;
}
else if (parent->left == current)
{
cout << char(195) << char(196);
break;
}
else if (parent->value > current->value && !parent->hasOnlyOnechild()) // Left child
{
cout << char(179) << " ";
if (!parent->left)
break;
parent = parent->left;
}
else //Right child or just one child
{
cout << " ";
if (parent->right)
parent = parent->right;
else if (parent->hasOnlyOnechild())
parent = parent->hasOnlyOnechild();
else
break;
}
}
// Root doens't have parent
if (parent = current->parent.lock())
cout << " " << (current == parent->left ? "-" : "+") << "> ";
// DEBUG SHOW NODE DEPTH
//cout << to_string(current->depth) << ". ";
if (lastChanged != "" && current->value == lastChanged)
{
printC(*current, Color::C_CYAN);
printC(" '" + to_string(current->frequency), C_DARKGREY);
lastChanged = "";
tempMarked.clear();
}
else
{
bool printed = false;
if (lastChanged != "")
for (string marked : tempMarked)
if (current->value == marked)
{
printC(*current, Color::C_BLUE);
printC(" '" + to_string(current->frequency), C_DARKGREY);
printed = true;
break;
}
if (!printed)
{
cout << *current;
printC(" '" + to_string(current->frequency), C_DARKGREY);
}
}
cout << endl;
}
cout << endl;
} | true |
c3da05269d2c143324d304ceb3c84f622cd5eb89 | C++ | kusstas/CrazyTanks2 | /CrazyTanks/GameObject.cpp | UTF-8 | 2,970 | 2.90625 | 3 | [] | no_license | // CrazyTanks game, @kusstas 2018. All Rights Reserved.
#include "GameObject.h"
#include "World.h"
#include "Pixel.h"
GameObject::GameObject(World& world) : world(&world)
{
active_ = true;
isStatic_ = false;
blockObject_ = true;
shouldBeDestroyed_ = false;
}
GameObject::~GameObject()
{
}
bool GameObject::isActive() const
{
return active_;
}
bool GameObject::isStatic() const
{
return isStatic_;
}
bool GameObject::isBlockObject() const
{
return blockObject_;
}
bool GameObject::isShouldBeDestroyed() const
{
return shouldBeDestroyed_;
}
const DVector2D& GameObject::getLocation() const
{
return location_;
}
const DVector2D& GameObject::getPrevLocation() const
{
return prevLocation_;
}
RotationZ GameObject::getRotationZ() const
{
return rotationZ_;
}
World* GameObject::getWorld() const
{
return world;
}
void GameObject::setActive(bool active)
{
active_ = active;
}
void GameObject::setBlockObject(bool blockObject)
{
blockObject_ = blockObject;
}
void GameObject::setLocation(const DVector2D& locaction)
{
location_ = locaction;
if (isStatic())
prevLocation_ = getLocation();
}
void GameObject::setLocation(int x, int y)
{
setLocation(DVector2D(x, y));
}
void GameObject::setRotationZ(RotationZ rotationZ)
{
rotationZ_ = rotationZ;
}
void GameObject::move(DVector2D vector)
{
setLocation(getLocation() + vector);
}
void GameObject::move(RotationZ direct, int scale)
{
move(getVector2DFromDirect(direct) * scale);
}
Pixel GameObject::getDrawing() const
{
return Pixel('#', COLOR_LIGHT_GREEN, COLOR_BLACK);
}
void GameObject::beginPlay()
{
}
void GameObject::tick(float deltaTime)
{
checkOnOverstepBorder();
}
void GameObject::physTick()
{
prevLocation_ = location_;
}
void GameObject::onOverlap(GameObject& object, DVector2D location)
{
}
void GameObject::onOverstepBorder()
{
}
void GameObject::destroy()
{
shouldBeDestroyed_ = true;
}
void GameObject::checkOnOverstepBorder()
{
DVector2D sizeWorld = world->getSize();
bool isOverstep = false;
if (location_.x < 0) {
location_.x = 0;
isOverstep = true;
}
else if (location_.x > sizeWorld.x - 1) {
location_.x = sizeWorld.x - 1;
isOverstep = true;
}
if (location_.y < 0) {
location_.y = 0;
isOverstep = true;
}
else if (location_.y > sizeWorld.y - 1) {
location_.y = sizeWorld.y - 1;
isOverstep = true;
}
if (isOverstep)
onOverstepBorder();
}
DVector2D GameObject::getVector2DFromDirect(RotationZ direct)
{
DVector2D vec;
switch (direct)
{
case ROTATION_Z_DOWN:
vec = DVector2D(0, 1);
break;
case ROTATION_Z_UP:
vec = DVector2D(0, -1);
break;
case ROTATION_Z_LEFT:
vec = DVector2D(-1, 0);
break;
case ROTATION_Z_RIGHT:
vec = DVector2D(1, 0);
break;
}
return vec;
} | true |
9f8689de30136d5a57b68a95430a790c7e26a846 | C++ | RayFerr000/Robot-Path | /Rectangle.h | UTF-8 | 594 | 2.5625 | 3 | [] | no_license | //
// Rectangle.h
// Robot_Path
//
// Created by raymond ferranti on 11/4/14.
// Copyright (c) 2014 raymond ferranti. All rights reserved.
//
#ifndef __Robot_Path__Rectangle__
#define __Robot_Path__Rectangle__
#include <stdio.h>
class Rectangle{
public:
//Stores the values of the left-upper point of a Rectangle
int x, y, width, height;
int getX();
int getY();
Rectangle(int x, int y , int width , int height);
Rectangle();
int getWidth();
int getHeight();
int area();
};
#endif /* defined(__Robot_Path__Rectangle__) */
| true |
a8deb11af665fe428a72a9c75b11dee68ffdf240 | C++ | mascotli/Way-to-Algorithm | /src/TextMatch/ACAutomation.hpp | UTF-8 | 6,623 | 3 | 3 | [
"MIT"
] | permissive | // MIT License
// Copyright 2017 zhaochenyou16@gmail.com
#pragma once
#ifndef MAX
#define MAX 64
#endif
#include <cstring>
#include <cassert>
#include <vector>
#include <unordered_map>
#include <string>
#include <queue>
//
// interface
//
struct Node {
int count;
Node *child[MAX];
Node *father;
Node *fail;
Node();
Node(const Node &other);
Node& operator=(const Node &other);
};
struct ACAutomation {
Node root;
};
ACAutomation *ACAutomationNew(const std::vector<std::string> &str);
void ACAutomationFree(ACAutomation *ac);
std::unordered_map<std::string, std::vector<int>> ACAutomationMatch(ACAutomation *ac, const std::string &text);
// implement
#define INVALID_CHAR '@'
namespace detail {
void Insert(ACAutomation *ac, const std::string &str);
char GetChar(Node *p);
std::string GetString(Node *p, const std::string &str = "");
void FailPath(ACAutomation *ac);
}
ACAutomation *ACAutomationNew(const std::vector<std::string> &str) {
ACAutomation *ac = new ACAutomation();
// 建立AC自动机
// 插入待查寻字符串
// 建立失败路径
for (int i = 0; i < str.size(); i++)
detail::Insert(ac, str[i]);
detail::FailPath(ac);
return ac;
}
std::unordered_map<std::string, std::vector<int>> ACAutomationMatch(ACAutomation *ac, const std::string &text) {
//扫描文本t
//返回其中出现的字典树中的字符串及其位置 存储于映射表pos中
std::unordered_map<std::string, std::vector<int>> pos;
int i = 0;
Node *p = &ac->root;
while (i < text.length()) {
int index = (int)text[i] - (int)'a';
while (!p->child[index] && p != &ac->root) {
//若字典树中该节点不存在
//则沿着fail指针递归 直到回到根节点
p = p->fail;
}
if (p->child[index] == NULL) {
p = &ac->root;
} else {
//若点p的孩子节点index存在
//即该孩子节点与文本下标i处字符匹配
p = p->child[index];
Node *tmp = p;
//http://store.steampowered.com/app/252490/Rust/?snr=1_4_4__128
while (tmp != &ac->root) {
//通过指针tmp找出所有可能与文本下标i处匹配的字符串
//因为除了p的孩子节点index 还可能存在其他字符串此时也与i处匹配
//
//在文档"AC自动机算法详解" 作者"极限定律"中
//第一个有问题的地方是:
//原文中该处的判断条件是:
//while(tmp != root and tmp->a_cnt == 0)
//(原文与本文中的变量名不一样 但代码的含义没有曲解)
//但是经过测试这里tmp->a_cnt == 0的条件恰好应该是相反的
//即tmp->a_cnt != 0 也可写作tmp->a_cnt(该值为正时即true)
if (tmp->count) {
std::string s = detail::GetString(tmp);
pos.insert(std::make_pair(s, i - s.length() + 1));
//文档"AC自动机算法详解" 作者"极限定律"中
//第二个有问题的地方则是:
//原文中该处有一处操作:
//tmp->a_cnt = 0;
//(原文与本文中的变量名不一样 但代码的含义没有曲解)
//但我不太明白为何要将字典树中该字符串删除
//也可能只求字符串第一次出现的位置
//本文的代码中没有删除字符串
//测试用例中可以看出本文的代码找出了所有匹配到的字符串位置
}
tmp = tmp->fail;
}
}
++i;
}
return pos;
}
void ACAutomationFree(ACAutomation *ac) {
(void)ac;
}
namespace detail {
void Insert(ACAutomation *ac, const std::string &str) {
Node *p = &ac->root;
for (int i = 0; i < str.length(); i++) {
int index = (int)str[i] - (int)'a';
if (p->child[index] == NULL) {
p->child[index] = new Node();
//将孩子节点成员中的父节点指针指向自己
//加入父节点成员完全是为了输出当前节点所在的字符串
p->child[index]->father = p;
}
p = p->child[index];
}
++p->count;
}
char GetChar(Node *p) {
//返回节点p的字母 若为根节点则输出@
if (p->father == NULL)
return INVALID_CHAR;
Node *fa = p->father;
for (int i = 0; i < MAX; ++ i)
if (fa->child[i] == p)
return (char)((int)'a' + (int)i);
return INVALID_CHAR;
}
std::string GetString(Node *p, const std::string &str) {
//返回以节点p为最后一个字母的字符串
//若节点增加字母和字符串成员
//插入字符串时在相应节点中进行标记
//则可不需要a_getstring和a_getchar函数
//递归终止条件 当节点p是根节点时返回字符串
if (p->father == NULL)
return str;
char ch = GetChar(p);
//继续向上递归求字符串
return GetString(p->father, ch + str);
}
void FailPath(ACAutomation *ac) {
//通过bfs给字典树中所有节点建立失败指针
std::queue<Node*> q;
//根节点的失败指针为NULL
ac->root.fail = NULL;
//根节点的所有孩子节点的失败指针指向根节点
for (int i = 0; i < MAX; ++ i) {
if (ac->root.child[i] != NULL) {
ac->root.child[i]->fail = &ac->root;
q.push(ac->root.child[i]);
}
}
while (!q.empty()) {
Node *p = q.front();
q.pop();
for (int i = 0; i < MAX; ++ i) {
if (p->child[i] != NULL) {
//设置节点p的孩子节点i的失败节点
Node *f = p->fail;
//f是节点i的父节点p的失败指针
while (f) {
if (f->child[i]) {
//若f有与节点i字符相同的孩子节点
//则节点i的失败指针指向f的这个孩子节点
p->child[i]->fail = f->child[i];
break;
}
//若f没有这样的孩子节点
//递归考察f的失败指针指向的节点
f = f->fail;
}
if(!f) {
//若f为空则节点i的失败指针指向根节点
p->child[i]->fail = &ac->root;
}
q.push(p->child[i]);
}
} // for
} // while
}
}
Node::Node() {
count = 0;
father = NULL;
fail = NULL;
memset(child, 0, sizeof(child));
}
Node::Node(const Node &other) {
count = other.count;
father = other.father;
fail = other.fail;
memcpy(child, other.child, sizeof(child));
}
Node& Node::operator=(const Node &other) {
if (this == &other)
return *this;
count = other.count;
father = other.father;
fail = other.fail;
memcpy(child, other.child, sizeof(child));
return *this;
}
| true |
70f9adcb71499368126a37727fd336cc9d5ec44e | C++ | Levintsky/topcoder | /cc/leetcode/string/415_add_strings.cc | UTF-8 | 853 | 3 | 3 | [] | no_license | class Solution {
public:
string addStrings(string num1, string num2) {
string res;
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int i = 0, carry = 0;
while (i < num1.size() || i < num2.size()) {
int tmp = 0;
if (i < num1.size())
tmp += num1[i] - '0';
if (i < num2.size())
tmp += num2[i] - '0';
if (carry > 0)
tmp += carry;
if (tmp < 10) {
res += '0' + tmp;
carry = 0;
} else {
tmp -= 10;
res += '0' + tmp;
carry = 1;
}
i++;
}
if (carry > 0)
res += '1';
reverse(res.begin(), res.end());
return res;
}
};
| true |
27e230cc0dcc4c92135f47d056c242f3a5799208 | C++ | eubr-atmosphere/a-GPUBench | /apps/tf_deepspeech/deepspeech/native_client/alphabet.h | UTF-8 | 1,821 | 3.359375 | 3 | [
"Apache-2.0",
"MPL-2.0"
] | permissive | #ifndef ALPHABET_H
#define ALPHABET_H
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
/*
* Loads a text file describing a mapping of labels to strings, one string per
* line. This is used by the decoder, client and Python scripts to convert the
* output of the decoder to a human-readable string and vice-versa.
*/
class Alphabet {
public:
Alphabet(const char *config_file) {
std::ifstream in(config_file, std::ios::in);
unsigned int label = 0;
for (std::string line; std::getline(in, line);) {
if (line.size() == 2 && line[0] == '\\' && line[1] == '#') {
line = '#';
} else if (line[0] == '#') {
continue;
}
label_to_str_[label] = line;
str_to_label_[line] = label;
++label;
}
size_ = label;
in.close();
}
const std::string& StringFromLabel(unsigned int label) const {
assert(label < size_);
auto it = label_to_str_.find(label);
if (it != label_to_str_.end()) {
return it->second;
} else {
// unreachable due to assert above
abort();
}
}
unsigned int LabelFromString(const std::string& string) const {
auto it = str_to_label_.find(string);
if (it != str_to_label_.end()) {
return it->second;
} else {
std::cerr << "Invalid label " << string << std::endl;
abort();
}
}
size_t GetSize() {
return size_;
}
bool IsSpace(unsigned int label) const {
//TODO: we should probably do something more i18n-aware here
const std::string& str = StringFromLabel(label);
return str.size() == 1 && str[0] == ' ';
}
private:
size_t size_;
std::unordered_map<unsigned int, std::string> label_to_str_;
std::unordered_map<std::string, unsigned int> str_to_label_;
};
#endif //ALPHABET_H
| true |
6e7eed441398243b0856be67f98fd35816d4d433 | C++ | st3v3nmw/competitive-programming | /uva/10608_Friends.cpp | UTF-8 | 2,386 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
#define eol "\n"
#define _(x) #x << "=" << to_str(x) << ", "
#define debug(x) { ostringstream stream; stream << x; string s = stream.str(); cout << s.substr(0, s.length() - 2) << eol; }
string to_string(basic_string<char>& x) { return "\"" + x + "\""; }
string to_string(char x) { string r = ""; r += x; return "\'" + r + "\'";}
string to_string(bool x) { return x ? "true" : "false"; }
template <typename T> string to_str(T x) { return to_string(x); }
template <typename T1, typename T2> string to_str(pair<T1, T2> x) { return "(" + to_str(x.first) + ", " + to_str(x.second) + ")"; }
template <typename T> string to_str(vector<T> x) { string r = "{"; for (auto t : x) r += to_str(t) + ", "; return r.substr(0, r.length() - 2) + "}"; }
template <typename T1, typename T2> string to_str(map<T1, T2> x) { string r = "{"; for (auto t : x) r += to_str(t.first) + ": " + to_str(t.second) + ", "; return r.substr(0, r.length() - 2) + "}"; }
#define ll long long
const ll MOD = 1e9 + 7;
class union_find {
public:
union_find(unsigned int n) {
parent = vector<unsigned int> (n);
size = vector<unsigned int> (n, 1);
for (unsigned int i = 0; i < n; i++)
parent[i] = i;
}
unsigned int find(unsigned int x) {
if (parent[x] == x)
return x;
parent[x] = find(parent[x]);
return parent[x];
}
void unify(unsigned int x, unsigned int y) {
unsigned int p_x = find(x);
unsigned int p_y = find(y);
if (p_x == p_y)
return; // x and y are already in the same set
parent[p_x] = p_y;
size[p_y] += size[p_x];
if (size[p_y] > largest)
largest = size[p_y];
}
bool connected(unsigned int x, unsigned int y) {
return find(x) == find(y);
}
vector<unsigned int> parent, size;
unsigned int largest = 0;
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
unsigned int t, n, m, f1, f2;
cin >> t;
for (int d = 0; d < t; d++) {
cin >> n >> m;
union_find q(n);
while (m--) {
cin >> f1 >> f2;
q.unify(f1 - 1, f2 - 1);
}
cout << q.largest << eol;
}
} | true |
31be078e94b6e68a3711105e43a2f6c97b220b33 | C++ | bharath154/codingground | /New Project/Heap.h | UTF-8 | 370 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
typedef struct Node
{
int data;
Node* left;
Node* right;
Node* parent;
} Node;
class Heap
{
public:
Heap(bool isMinHeap);
virtual ~Heap();
void Insert(int val);
int GetRoot();
int size();
HeapifyUp();
HeapifyDown();
private:
bool _isMinHeap;
Node* _root;
};
| true |
6665317f96d4951f6554d02f95ba08897e91e9f4 | C++ | Thiago-SMerces/Proj_IA_Sudoku | /sudoku.hpp | UTF-8 | 4,918 | 3.609375 | 4 | [
"MIT"
] | permissive | /*
* Header file for sudoku solver
* define key classes and macros (LEN)
*/
#ifndef __SUDOKU_HPP
#define __SUDOKU_HPP
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
/*
* Macro to define default sudoku LEN, as for now, it will always assume
* that the sudoku is a 9x9 matrix
*/
#define LEN 9
/*
* Structure to represent each state from the board
* i.e. each time a different number is added on the
* sudoku matrix (board), a new state is created.
* Note that there are two names to the structure just to
* make it easier to identify in which step we are when
* solving it.
*/
typedef struct State
{
char sudoku_matrix[LEN][LEN];
int costF;
int costG;
int costH;
bool solved;
// AC3 default domain
std::vector<int> valid_numbers;
// define default operator so priority queue may work
bool operator<(const State& next) const
{
return costF < next.costF;
}
} State, Node;
// class to define common functions to solve sudoku
class Solver
{
public:
// default initializer to start solving sudoku
virtual State solve(State problem) = 0;
// print the entire solved sudoku in one line
void printSudoku(char matrix[LEN][LEN]);
// check if sudoku matrix is the goal (fully filled with non-clashing numbers)
bool isGoal(State state);
};
class Uninformed_Searches
{
public:
// check if the number we are trying to assign does not conflict with the row, column or square
bool isValid(State state, int row, int col, int number);
// find the first empty spot (dot) while iterating over the sudoku
int* findDot(State state);
// count how many possible numbers a spot with a dot could be filled with
int numbersInRegion(State state, int row, int col);
};
class Informed_Searches
{
public:
// to continue with the idea of continuously solving the matrix
// use pointers instead of direct copies of values to find the
// dot location (coordinates). Returns bool so we can know if
// there is still a dot or not on the matrix
// This function also selects the most constrained value
// as the next candidate to replace instead of randomly
// trying values
bool findDot(State *state, int* i, int* j);
// literally the same function defined in the Uninformed class,
// but it accepts a pointer to the state we are solving
bool isValid(State* state, int row, int col, int number);
};
// class to implement bfs search to solve sudoku
class BFS : public Solver, Uninformed_Searches
{
public:
// solve problem using breadth-first search (bfs)
State bfs(State problem);
// overwrite default Solver initializer to solve problem using bfs
State solve(State problem)
{
return bfs(problem);
}
};
// class to implement dfs search to solve sudoku
class DFS : public Solver, Uninformed_Searches
{
public:
// solve problem using depth-first search (dfs)
State dfs(State problem);
// overwrite default Solver initializer to solve problem using dfs
State solve(State problem)
{
return dfs(problem);
}
};
// class to implement a* search to solve sudoku
class AStar : public Solver, Uninformed_Searches
{
public:
// solve problem using a star search (a*)
State aStar(State problem);
// overwrite default Solver initializer to solve problem using a*
State solve(State problem)
{
return aStar(problem);
}
};
// class to implement backtracking search to solve sudoku
class BACK : public Solver, Informed_Searches
{
public:
// solve problem using backtracking
// i and j are optional parameters (defined in the source code)
// since we want a continuos solution to a state instead of creating
// new ones
void back(State* problem);
// overwrite default Solver initializer to solve problem using backtracking
// this one needs a little more set up, since we need the problem to
// be returned as a State instead of a pointer to keep the code working
State solve(State problem)
{
back(&problem);
return problem;
}
};
// class to implement ac3 search to solve sudoku
class AC3 : public Solver, Informed_Searches
{
// default domain
std::vector<int> D;
public:
// solve problem using as a Constraint Satisfaction Problem
State ac3(State problem);
// revise function
int revise(State* X1, int i, int j);
// overwrite default Solver initializer to solve problem using ac3
State solve(State problem)
{
for (int i = 0; i < 10; i++)
D[i] = i + 49;
problem.valid_numbers = D;
return ac3(problem);
}
AC3() : D(10) {}
};
#endif | true |
d806820dffb59240e90288e56cfebc5e973d30a7 | C++ | iiicp/cptoyc | /Lex/MacroInfo.cpp | UTF-8 | 2,327 | 2.671875 | 3 | [] | no_license | /***********************************
* File: MacroInfo.cpp
*
* Author: caipeng
*
* Email: iiicp@outlook.com
*
* Date: 2020/12/1
***********************************/
#include "MacroInfo.h"
#include "Preprocessor.h"
using namespace CPToyC::Compiler;
MacroInfo::MacroInfo(SourceLocation DefLoc) : Location(DefLoc) {
IsFunctionLike = false;
IsC99Varargs = false;
IsGNUVarargs = false;
IsBuiltinMacro = false;
IsDisabled = false;
IsUsed = true;
ArgumentList = nullptr;
NumArguments = 0;
}
/// isIdenticalTo - Return true if the specified macro definition is equal to
/// this macro in spelling, arguments, and whitespace. This is used to emit
/// duplicate definition warnings. This implements the rules in C99 6.10.3.
///
bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP) const {
// Check # tokens in replacement, number of args, and various flags all match.
if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
getNumArgs() != Other.getNumArgs() ||
isFunctionLike() != Other.isFunctionLike() ||
isC99Varargs() != Other.isC99Varargs() ||
isGNUVarargs() != Other.isGNUVarargs())
return false;
// Check arguments.
for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
I != E; ++I, ++OI)
if (*I != *OI) return false;
// Check all the tokens.
for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
const Token &A = ReplacementTokens[i];
const Token &B = Other.ReplacementTokens[i];
if (A.getKind() != B.getKind())
return false;
// If this isn't the first first token, check that the whitespace and
// start-of-line characteristics match.
if (i != 0 &&
(A.isAtStartOfLine() != B.isAtStartOfLine() ||
A.hasLeadingSpace() != B.hasLeadingSpace()))
return false;
// If this is an identifier, it is easy.
if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
if (A.getIdentifierInfo() != B.getIdentifierInfo())
return false;
continue;
}
// Otherwise, check the spelling.
if (PP.getSpelling(A) != PP.getSpelling(B))
return false;
}
return true;
}
| true |
61f6de8177fff42c4e611621c5b39512a005ae4c | C++ | JesusMiramontes/QT-MatrixTransformations | /mainwindow.cpp | UTF-8 | 10,098 | 2.875 | 3 | [] | no_license | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QPen"
#include "QPainter"
#include <QtMath>
#include <math.h>
#include "triangulo.h"
#include "QDebug"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Establece el tamaño del pixmap segun el label
pix = new QPixmap(ui->drawing_area->width(), ui->drawing_area->height()); //Tamaño canvas
pix->fill(Qt::black); //Fondo negro
paint = new QPainter(pix);
// Configura los cuadrantes
configurarPlano();
// Dibuja las lineas separadoras
dibujarLineas();
// Asigna un triangulo a cada cuadrante
t1 = new triangulo(cuadrante_uno);
t2 = new triangulo(cuadrante_dos);
t3 = new triangulo(cuadrante_tres);
t4 = new triangulo(cuadrante_cuatro);
// Dibuja los triangulos
dibujarTriangulos();
// El angulo inicial de cada triangulo es 90
// Esta variable se usa en el giro
global_angle = 90;
// Configura los timers
timer_rotacion = new QTimer(this);
timer_apuntar_al_centro = new QTimer(this);
timer_mover_al_centro = new QTimer(this);
timer_helice = new QTimer(this);
// Crea las coneciones a los eventos
connect(timer_rotacion, SIGNAL(timeout()), this, SLOT(timerRotar()));
connect(timer_apuntar_al_centro, SIGNAL(timeout()), this, SLOT(timerApuntarAlCentro()));
connect(timer_mover_al_centro, SIGNAL(timeout()), this, SLOT(timerMoverAlCentro()));
connect(timer_helice, SIGNAL(timeout()), this, SLOT(timerHelice()));
// Explicación de los botones
QMessageBox msgBox;
msgBox.setText("Girar => Gira los triangulos sobre un punto fijo.\nApuntar => Apunta los triangulos hacía el centro\nMover => Mueve los triangulos al centro.\nHelice => Efecto de helice.\nNota: Pueden ejecutarse varias acciones al mismo tiempo, el resultado varía.");
msgBox.exec();
}
// Obtiene el centro del lienzo, establece las coordenadas de las lineas que separan el plano
void MainWindow::configurarPlano()
{
float x = (ui->drawing_area->width()/2);
float y = ui->drawing_area->height()/2;
centro = new QPointF(x,y);
linea_horizontal_inicio = new QPointF(0,y);
linea_horizontal_fin = new QPointF(ui->drawing_area->width(),y);
linea_vertical_inicio = new QPointF(x,0);
linea_vertical_fin = new QPointF(x,ui->drawing_area->height());
cuadrante_uno = new QPointF();
cuadrante_uno->setX(centro->x() + (ui->drawing_area->width()/4));
cuadrante_uno->setY(centro->y() - (ui->drawing_area->height()/4));
cuadrante_dos = new QPointF();
cuadrante_dos->setX(centro->x() + (ui->drawing_area->width()/4));
cuadrante_dos->setY(centro->y() + (ui->drawing_area->height()/4));
cuadrante_tres = new QPointF();
cuadrante_tres->setX(centro->x() - (ui->drawing_area->width()/4));
cuadrante_tres->setY(centro->y() - (ui->drawing_area->height()/4));
cuadrante_cuatro = new QPointF();
cuadrante_cuatro->setX(centro->x() - (ui->drawing_area->width()/4));
cuadrante_cuatro->setY(centro->y() + (ui->drawing_area->height()/4));
}
// Rota un punto con respecto a otro punto
QPointF *MainWindow::rotar(QPointF *posicion_actual, int angle, int length)
{
qreal new_x, new_y;
float fradians = qDegreesToRadians((float)angle);
qreal radians = (qreal)fradians;
new_x = (qreal)(posicion_actual->x() + length * qCos(radians));
new_y = (qreal)(posicion_actual->y() + length * qSin(radians));
QPointF* new_point = new QPointF(new_x, new_y);
return new_point;
}
// Dibuja una linea en base a un punto posicion actual con un angulo angle a una distancia lenght
void MainWindow::dibujarLineaWithAngle(int angle, QPointF* posicion_actual, int length)
{
qreal new_x, new_y;
float fradians = qDegreesToRadians((float)angle);
qreal radians = (qreal)fradians;
new_x = (qreal)(posicion_actual->x() + length * qCos(radians));
new_y = (qreal)(posicion_actual->y() + length * qSin(radians));
QPointF* new_point = new QPointF(new_x, new_y);
dibujarLinea(posicion_actual,new_point);
}
// Dibuja una linea de punto A a un punto B
void MainWindow::dibujarLinea(QPointF *p1, QPointF *p2, int width)
{
QPen pen; // creates a default pen
pen.setStyle(Qt::SolidLine); //Estilo de linea
pen.setWidth(width); //Ancho de linea
pen.setBrush(Qt::green); //Color de lina
pen.setCapStyle(Qt::RoundCap); //Forma de extremos de lina (cuadrado, redondeado, etc)
pen.setJoinStyle(Qt::RoundJoin);
paint->setPen(pen); //Color separador
paint->drawLine(*p1, *p2);
ui->drawing_area->setPixmap(*pix);
}
// Recibe tres puntos y dibuja tres lineas de punto a punto
void MainWindow::dibujarTriangulo(QPointF *p1, QPointF *p2, QPointF *p3)
{
dibujarLinea(p1,p2);
dibujarLinea(p2,p3);
dibujarLinea(p3,p1);
}
// Dibuja un triangulo en base a las propiedades del objeto triangulo
void MainWindow::dibujarTriangulo(triangulo *t)
{
dibujarTriangulo(t->punto,t->wingA, t->wingB);
}
// Borra lo que esté dibujado en el label
void MainWindow::update_canvas()
{
//pix = new QPixmap(ui->drawing_area->width(), ui->drawing_area->height()); //Tamaño canvas
pix->fill(Qt::black); //Fondo
//paint = new QPainter(pix);
}
// Gira todos los triangulos al mismo tiempo en base a un ángulo
void MainWindow::girarTriangulos(float theta)
{
t1->setAngle(theta);
t2->setAngle(theta);
t3->setAngle(theta);
t4->setAngle(theta);
qDebug() << t1->getAngle() << " " << t2->getAngle() << " " << t3->getAngle() << " " << t4->getAngle() << " ";
}
// Dibuja todos los triangulos
void MainWindow::dibujarTriangulos()
{
dibujarTriangulo(t1);
dibujarTriangulo(t2);
dibujarTriangulo(t3);
dibujarTriangulo(t4);
}
// Dibuja las lineas separadoras
void MainWindow::dibujarLineas()
{
dibujarLinea(linea_horizontal_inicio, linea_horizontal_fin);
dibujarLinea(linea_vertical_inicio, linea_vertical_fin);
}
// Limpia el lienzo, dibuja las lineas, y los triangulos
void MainWindow::redibujar()
{
update_canvas();
dibujarLineas();
dibujarTriangulos();
}
// Mueve el triangulo t al centro
bool MainWindow::trasladarAlCentro(triangulo *t)
{
// Banderas que indican si X y Y ya se encuentran en el centro
bool fx, fy;
fx = false;
fy = false;
// Manipula X
if(t->punto->x() > centro->x()){
t->setPosition(t->punto->x()-1, t->punto->y());
} else if (t->punto->x() < centro->x()){
t->setPosition(t->punto->x()+1, t->punto->y());
} else{
fx = true;
}
// Manipula Y
if(t->punto->y() > centro->y()){
t->setPosition(t->punto->x(), t->punto->y()-1);
} else if(t->punto->y() < centro->y()){
t->setPosition(t->punto->x(), t->punto->y()+1);
} else{
fy = true;
}
redibujar();
// Si X y Y estan en el centro regresa true
if (fx && fy){
return true;
} else {
return false;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnGirarTriangulos_clicked()
{
}
// Gira todos los triangulos en base al angulo que proporciones el slider
void MainWindow::on_horizontalSlider_valueChanged(int value)
{
girarTriangulos((float)value);
update_canvas();
redibujar();
}
// Metodo que se ejecuta en cada tick del timer_rotar
// gira todos los angulos simultaneamente
void MainWindow::timerRotar()
{
// Dado que el angulo 450 es igual a 90 se regresa a 90
if (global_angle >= 450)
global_angle = 90;
// en cada iteracion aumenta el angulo en uno
global_angle ++;
// Gira todos los triangulos en base al global_angle
girarTriangulos(global_angle);
redibujar();
ui->label->setText(QString::number(global_angle));
}
// metodo que se ejecuta en cada tick del timer_apuntar
void MainWindow::timerApuntarAlCentro()
{
// Banderas que indican si los triangulos ya apuntan al centro
bool f1, f2, f3, f4;
f1 = false;
f2 = false;
f3 = false;
f4 = false;
if (t4->getAngle() > 450)
t4->setAngle(90);
// Compara los angulos de cada triangulo y los altera hasta que llegan al deseado
if(t4->getAngle() != 135){
t4->setAngle(t4->getAngle()+1);
redibujar();
}
else{
f4 = true;
}
if(t3->getAngle() != 225){
t3->setAngle(t3->getAngle()+1);
redibujar();
}
else{
f3 = true;
}
if(t2->getAngle() != 405){
t2->setAngle(t2->getAngle()+1);
redibujar();
}
else{
f2 = true;
}
if(t1->getAngle() != 315){
t1->setAngle(t1->getAngle()+1);
redibujar();
}
else{
f1 = true;
}
if (f1 && f2 && f3 && f4)
timer_apuntar_al_centro->stop();
qDebug() << t1->getAngle() << " " << t2->getAngle() << " " << t3->getAngle() << " " << t4->getAngle() << " ";
}
// Metodo que se ejecuta en cada tick del timer timer_mover_al_centro
void MainWindow::timerMoverAlCentro()
{
// Traslada todos los triangulos al centro
trasladarAlCentro(t1);
trasladarAlCentro(t2);
trasladarAlCentro(t3);
trasladarAlCentro(t4);
}
// metodo que se ejecuta a cada tick de timer_helice
void MainWindow::timerHelice()
{
// Le suma uno al angulo de cada triangulo
t1->addAngle(1);
t2->addAngle(1);
t3->addAngle(1);
t4->addAngle(1);
redibujar();
}
void MainWindow::on_btnGirar_clicked()
{
timer_rotacion->start(5);
}
void MainWindow::on_btnDetener_clicked()
{
timer_rotacion->stop();
}
void MainWindow::on_btnApuntar_clicked()
{
timer_apuntar_al_centro->start(5);
}
void MainWindow::on_btnMover_clicked()
{
timer_mover_al_centro->start(5);
}
void MainWindow::on_btnDetenerApuntar_clicked()
{
timer_apuntar_al_centro->stop();
}
void MainWindow::on_btnDetenerMover_clicked()
{
timer_mover_al_centro->stop();
}
void MainWindow::on_btnHelice_clicked()
{
timer_helice->start(5);
}
void MainWindow::on_btnDetenerHelice_clicked()
{
timer_helice->stop();
}
| true |
33ec97fa97b9afe232861bcdb554e047a5d2bf7f | C++ | harrywaugh/blas_tracing_tests | /src/dgemm_test.cpp | UTF-8 | 1,247 | 2.984375 | 3 | [] | no_license | #include <random>
#include <mkl.h>
#include <sys/time.h>
// Get the current time in seconds since the Epoch
double wtime(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec*1e-6;
}
int main ( int argc, char* argv[] ) {
double main_tic = wtime();
// Random numbers
std::mt19937_64 rnd;
std::uniform_real_distribution<double> doubleDist(0, 1);
// Create arrays that represent the matrices A,B,C
const int m = 20;
const int n = 150;
const int k = 5;
double* A = new double[m*k];
double* B = new double[n*k];
double* C = new double[m*n];
// Fill A and B with random numbers
for(uint i =0; i <m*k; i++){
A[i] = doubleDist(rnd);
}
for(uint i =0; i <k*n; i++){
B[i] = doubleDist(rnd);
}
for (int i=0; i < 50000; i++) {
// Calculate A*B=C
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 0.0, C, n);
//dgemm_(m, n, k, 1.0, A, k, B, n, 0.0, C, n);
}
// Clean up
delete[] A;
delete[] B;
delete[] C;
double main_toc = wtime();
main_toc -= main_tic;
printf("Main function time: %.3f\n", main_toc);
return 0;
}
| true |
509dddc19d3997ee1a3ebacd633945f379675153 | C++ | niuxu18/logTracker-old | /second/download/git/gumtree/git_patch_hunk_964.cpp | UTF-8 | 2,535 | 2.53125 | 3 | [] | no_license | }
static int edit_and_replace(const char *object_ref, int force, int raw)
{
char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
enum object_type type;
- unsigned char old[20], new[20], prev[20];
- char ref[PATH_MAX];
+ struct object_id old, new, prev;
+ struct strbuf ref = STRBUF_INIT;
- if (get_sha1(object_ref, old) < 0)
+ if (get_oid(object_ref, &old) < 0)
die("Not a valid object name: '%s'", object_ref);
- type = sha1_object_info(old, NULL);
+ type = sha1_object_info(old.hash, NULL);
if (type < 0)
- die("unable to get object type for %s", sha1_to_hex(old));
+ die("unable to get object type for %s", oid_to_hex(&old));
- check_ref_valid(old, prev, ref, sizeof(ref), force);
+ check_ref_valid(&old, &prev, &ref, force);
+ strbuf_release(&ref);
- export_object(old, type, raw, tmpfile);
+ export_object(&old, type, raw, tmpfile);
if (launch_editor(tmpfile, NULL, NULL) < 0)
die("editing object file failed");
- import_object(new, type, raw, tmpfile);
+ import_object(&new, type, raw, tmpfile);
free(tmpfile);
- if (!hashcmp(old, new))
- return error("new object is the same as the old one: '%s'", sha1_to_hex(old));
+ if (!oidcmp(&old, &new))
+ return error("new object is the same as the old one: '%s'", oid_to_hex(&old));
- return replace_object_sha1(object_ref, old, "replacement", new, force);
+ return replace_object_oid(object_ref, &old, "replacement", &new, force);
}
static void replace_parents(struct strbuf *buf, int argc, const char **argv)
{
struct strbuf new_parents = STRBUF_INIT;
const char *parent_start, *parent_end;
int i;
/* find existing parents */
parent_start = buf->buf;
- parent_start += 46; /* "tree " + "hex sha1" + "\n" */
+ parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
parent_end = parent_start;
while (starts_with(parent_end, "parent "))
parent_end += 48; /* "parent " + "hex sha1" + "\n" */
/* prepare new parents */
for (i = 0; i < argc; i++) {
- unsigned char sha1[20];
- if (get_sha1(argv[i], sha1) < 0)
+ struct object_id oid;
+ if (get_oid(argv[i], &oid) < 0)
die(_("Not a valid object name: '%s'"), argv[i]);
- lookup_commit_or_die(sha1, argv[i]);
- strbuf_addf(&new_parents, "parent %s\n", sha1_to_hex(sha1));
+ lookup_commit_or_die(oid.hash, argv[i]);
+ strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
}
/* replace existing parents with new ones */
strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
new_parents.buf, new_parents.len);
| true |
0b5c242d799f22cd9ac171f9b3003899cb5cdf19 | C++ | emilmoham/SignDetectionSystemCIS4398 | /cpp/sd_common/ConfigParser.h | UTF-8 | 1,250 | 3.375 | 3 | [] | no_license | #ifndef __CONFIG_PARSER_H_
#define __CONFIG_PARSER_H_
#include <sstream>
#include <string>
#include <unordered_map>
/**
* @class ConfigParser
* @brief A simple I/O class for configuration file settings
*/
class ConfigParser
{
public:
/// Default constructor
ConfigParser() = default;
/// Attempts to load the configuration file at the given path, returning true on success, false on failure.
bool load(std::string filePath);
/// Returns the value associated with the given key
template <typename T>
T getValue(const std::string &key)
{
T value;
std::string strVal = m_configMap[key];
std::istringstream ss(strVal);
ss >> value;
return value;
}
private:
/// Map of configurable settings
std::unordered_map<std::string, std::string> m_configMap;
};
#endif //__CONFIG_PARSER_H_
| true |
fe0c4bfaa27b5faddd5bdad00cb3c1b23bdd923b | C++ | JW-CHEN/leetcode | /mergeInterval/main.cc | UTF-8 | 2,538 | 3.09375 | 3 | [] | no_license | #include "../common/comm.h"
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
class Solution {
public:
void quickSortSet(int* startSet, int* endSet, int left, int right) {
//remeber to add new feature
if (left >= right)
return;
int l = left;
int r = right;
int pivot = startSet[l];
int backup = endSet[l];
while (l < r) {
while (l < r && startSet[r] > pivot || startSet[r] == pivot && endSet[r] > backup) r--;
startSet[l] = startSet[r];
endSet[l] = endSet[r];
while (l < r && startSet[l] < pivot || startSet[r] == pivot && endSet[r] <= backup ) l++;
startSet[r] = startSet[l];
endSet[r] = endSet[l];
}
// Complexity analyze
startSet[l] = pivot;
endSet[l] = backup;
quickSortSet(startSet, endSet, left, l-1);
quickSortSet(startSet, endSet, l+1, right);
return;
}
vector<Interval> merge(vector<Interval> &intervals) {
int sz = intervals.size();
int numInt = 0;
vector<Interval> nullRes;
if (sz == 0)
return nullRes;
int* startSet = new int[sz];
int* endSet = new int[sz];
for (int i = 0; i < sz; i++) {
startSet[i] = intervals[i].start;
endSet[i] = intervals[i].end;
}
quickSortSet(startSet, endSet, 0, sz-1);
stack<int> stk;
stk.push(startSet[0]);
stk.push(endSet[0]);
numInt++;
int preEnd;
for (int i = 1; i < sz; i++) {
preEnd = stk.top();
if (startSet[i] <= preEnd && endSet[i] > preEnd) {
stk.pop();
stk.push(endSet[i]);
}
else if (preEnd < startSet[i]) {
stk.push(startSet[i]);
stk.push(endSet[i]);
numInt++;
}
}
vector<Interval> res(numInt, Interval(0,0));
for (int i = numInt-1; i >= 0; i--) {
res[i].end = stk.top();
stk.pop();
res[i].start = stk.top();
}
return res;
}
};
int main() {
vector<Interval> test;
vector<Interval> res;
Interval elem1(1,4);
Interval elem2(1,4);
test.push_back(elem1);
test.push_back(elem2);
Solution sl;
res = sl.merge(test);
cout<<res[0].start<<endl<<res[0].end<<endl;
return 1;
}
| true |
d1269b0dee7f1281e7f7efb4b21f0a755ba0300f | C++ | zhou78yang/homeworks | /ccf/1604-1.cc | UTF-8 | 387 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define N 1005
int main()
{
int n, a[N], count = 0;
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 2; i < n; i++)
{
if( (a[i] > a[i-1] && a[i] > a[i+1]) ||
(a[i] < a[i-1] && a[i] < a[i+1]))
{
count++;
}
}
cout << count << endl;
return 0;
}
| true |
bca4be2272a4e895b122e7a049507646263ab59a | C++ | amg1127/PROGRAMAS-DA-FACULDADE | /Compactador-Huffman/comdeshuff/tcell.h | UTF-8 | 1,674 | 2.65625 | 3 | [] | no_license | class TCell {
private:
int _id;
int _weight;
char _character;
TCell *_parent;
TCell *_son0;
TCell *_son1;
bool _hasSons;
std::string _pathToSon (TCell *);
template <typename SWPTYPE>
inline void swapvar (SWPTYPE &v1, SWPTYPE &v2) { SWPTYPE aux; aux=v1; v1=v2; v2=aux; }
public:
TCell (TCell * = NULL);
~TCell ();
int id (void);
void setId (int);
char character (void);
void setCharacter (char);
int weight ();
void setWeight (int);
int distanceToRoot (void);
int maxDistanceToSons (void);
bool isRoot (void);
bool hasSons (void);
void killSons (void);
void makeSons (void);
TCell *son0 (void);
TCell *son1 (void);
TCell *son (int);
TCell *parent (void);
TCell *root (void);
TCell *findSonByWeight (int);
TCell *findSonById (int);
TCell *findSonByCharacter (char);
TCell *findSonByPath (std::string);
TCell *self (void);
std::string pathFromRootToMe (void);
std::string pathToSon (TCell &);
std::string pathToSon (TCell *);
bool isSonOf (TCell &);
bool isSonOf (TCell *);
bool isParentOf (TCell &);
bool isParentOf (TCell *);
void swap (TCell &, bool = false);
void swap (TCell *, bool = false);
void copyFrom (TCell &, bool = false);
void copyFrom (TCell *, bool = false);
void copyTo (TCell &, bool = false);
void copyTo (TCell *, bool = false);
std::string dump (int = 0);
};
| true |
9868a69e9cffc6edd998c901ecabccea47d05567 | C++ | joshcv2112/ProgramingProblems | /nextPrimeNumber.cpp | UTF-8 | 1,033 | 4.03125 | 4 | [] | no_license | /*
Author: Joshua Vaughan
Simple program that computes prime numbers until user
indicates termination.
*/
#include <iostream>
using namespace std;
bool isPrime(int number)
{
if (number == 2 || number == 3)
return true;
if (number % 2 == 0 || number % 3 == 0)
return false;
int divisor = 6;
while (divisor * divisor - 2 * divisor + 1 <= number)
{
if (number % (divisor - 1) == 0)
return false;
if (number % (divisor + 1) == 0)
return false;
divisor += 6;
}
return true;
}
int nextPrime(int p)
{
while (!isPrime(++p))
{}
return p;
}
int main()
{
bool continueLoop = true;
int prime = 0;
char input;
while (continueLoop)
{
prime = nextPrime(prime);
cout << prime << " is a prime number." << endl;
cout << "Would you like to find another prime number? (Y/N) ";
cin >> input;
if (input == 'n' || input == 'N')
continueLoop = false;
}
return 0;
}
| true |
2ea8e4495d86e9cb8bb1ee8244db98bbeb2494a3 | C++ | tdaros/vendingMachine | /Node.h | UTF-8 | 1,521 | 3.265625 | 3 | [
"MIT"
] | permissive |
/*
Arquivo: Node.h
Autor: Thiago Daros Fernandes
Data: 15/11/2019
Descricao: Este arquivo e responsavel por declarar a classe Node que formara a lista duplamente encadeada.
O nodo pode ter como valor um tipo de dado T definido pelo template, por isso pode ser utilizado em diferentes contextos.
*/
#ifndef NODE_H
# define NODE_H
#include "ClockCalendar.h" //Bibli
#include <iostream>
/*
Classe: entry
Descricao: Estrutura que guarda informacoes sobre as entradas do log da maquina.
Possui um relogio, o preco do produto vendido e o nome do produto.
Pode ser alterada para guardar outras informacoes como codigo de barras, etc.
*/
class entry{
public:
ClockCalendar time;
double price;
std::string refri;
};
/*
Struct: task_t
Descricao: Estrutura que guarda informacoes de cada tarefa do escalonador,
tal como o ponteiro para a funcao a ser executada, a periodicidade da tarefa
e o tempo restante para executar a tarefa novamente.
*/
typedef struct {
int period;
int elapsed;
int enabled;
void (*task)(void);
} task_t;
/*
Classe: Node
Descricao: Alem da variavel template, possui ponteiros para os Nodos adjacentes
para formar a lista encadeada.
Possui funcoes para definir e ler os objetos adjacentes e retornar seu dado
guardado.
*/
template <class T>
class Node {
T val;
Node* next;
Node* prev;
public:
Node(T dat, Node* nxt, Node* prv);
T getVal();
Node* getNext();
Node* getPrev();
void setVal(T dat);
void setNext(Node<T>* nxt);
void setPrev(Node<T>* prv);
};
#endif
| true |
8a09e2d822febc6636c68fdea2a4d6c8c4b6fe9f | C++ | vishal-1010/Introduction-to-C-coding-ninjas | /add_two_numbers.cpp | UTF-8 | 215 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int a = 10;
int b = 15;
int c = a + b;
cout << c << endl;
char d = 'd';
cout << d << endl;
float f = 2.34;
cout << sizeof(f);
} | true |
fce2848f1fa58f190d8ccb1bbaf9494c51079667 | C++ | enaim/Competitive_Programming | /2016/April/ABSULATE.cpp | UTF-8 | 555 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define deb(a) cout<<__LINE__<<"# "<<#a<<" -> "<<a<<endl;
template<class T> T abs(T x){
if(x<0) return -x;
return x;
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("output.txt","w",stdout);
int x;
long long l;
double y;
cin>>x>>l>>y;
deb(abs(x));
deb(abs(l));
deb(abs(y));
return 0;
}
| true |
015a50c400fa94320222f38add262a5a431556c8 | C++ | DcmTruman/my_acm_training | /HDU/2050/10384332_AC_0ms_1980kB.cpp | UTF-8 | 337 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<stdio.h>
#include<cmath>
using namespace std;
int dp[10020];
void DP()
{
dp[1] = 2;
for(int i =2;i<10010;i++)
{
dp[i] = dp[i-1] +4*i-3;
}
}
int main()
{
int Case,n;
DP();
cin>>Case;
while(Case--)
{
cin>>n;
cout<<dp[n]<<endl;
}
} | true |
6387b92d7bf29f67f53c54132abaae8be4d6d98c | C++ | chenxian0723/LeetCode | /122.Best-Time-to-Buy-and-Sell-Stock-II/Solution.cpp | UTF-8 | 693 | 3.265625 | 3 | [] | no_license | class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()==0)
return 0;
int profit=0;
int low=prices[0];
for(int i=0;i<prices.size();i++){
if(prices[i]>low){
profit=prices[i]-low+profit; //每有一次利润就累加
low=prices[i]; //表示一个新交易后,当前价格为最低点
}
else
low=prices[i]; //表示没有交易,但是产生了新的最低点
//其实可以把上升的一段过程作为一次买卖,那样就不用每天累加
}
return profit;
}
};
| true |
1a9d0984594d308da7df1da5569bfbac0ed4ff90 | C++ | jeremy24/UnitTests | /source/TestAdderClass.cpp | UTF-8 | 745 | 3.203125 | 3 | [] | no_license | /*! \file
* \brief
* \author
* \date
*/
#include <iostream>
#include <set>
#include <vector>
#include <UnitTest++.h>
#include "Adder.hpp"
using namespace std;
typedef Adder<double> AdderDouble;
TEST_FIXTURE(AdderDouble, TestingAdding) {
double result = Add(1.0, 3.0);
CHECK(result == 4.0);
}
TEST_FIXTURE(AdderDouble, TestingVectorAddition) {
vector<double> a,b, expected;
a.push_back(1); a.push_back(2); a.push_back(3);
b.push_back(1); b.push_back(2); b.push_back(3);
for(unsigned int i = 0; i < a.size(); i++)
expected.push_back(a.at(i)+b.at(i));
vector<double> result = AddArray(a,b);
CHECK(result.size() == expected.size());
CHECK_ARRAY_EQUAL(result, expected, expected.size());
}
| true |
437bbb98d8ae6e6bb2d158f248b6264f7974c990 | C++ | prasadsilva/advent-of-code-2018 | /src/main.cpp | UTF-8 | 3,365 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <array>
#include <vector>
#include <functional>
// Forward declarations
namespace day1 {
void problem1();
void problem2();
}
namespace day2 {
void problem1();
void problem2();
}
namespace day3 {
void problem1();
void problem2();
}
namespace day4 {
void problem1();
void problem2();
}
namespace day5 {
void problem1();
void problem2();
}
namespace day6 {
void problem1();
void problem2();
}
namespace day7 {
void problem1();
void problem2();
}
namespace day8 {
void problem1();
void problem2();
}
namespace day9 {
void problem1();
void problem2();
}
namespace day10 {
void problem1();
void problem2();
}
namespace day11 {
void problem1();
void problem2();
}
namespace day12 {
void problem1();
void problem2();
}
namespace day13 {
void problem1();
void problem2();
}
namespace day14 {
void problem1();
void problem2();
}
namespace day15 {
void problem1();
void problem2();
}
namespace day16 {
void problem1();
void problem2();
}
namespace day17 {
void problem1();
void problem2();
}
namespace day18 {
void problem1();
void problem2();
}
namespace day19 {
void problem1();
void problem2();
}
namespace day20 {
void problem1();
void problem2();
}
namespace day21 {
void problem1();
void problem2();
}
namespace day22 {
void problem1();
void problem2();
}
namespace day23 {
void problem1();
void problem2();
}
int main(int argc, char const *argv[]) {
std::vector<std::vector<std::function<void(void)>>> days = {
{day1::problem1, day1::problem2},
{day2::problem1, day2::problem2},
{day3::problem1, day3::problem2},
{day4::problem1, day4::problem2},
{day5::problem1, day5::problem2},
{day6::problem1, day6::problem2},
{day7::problem1, day7::problem2},
{day8::problem1, day8::problem2},
{day9::problem1, day9::problem2},
{day10::problem1, day10::problem2},
{day11::problem1, day11::problem2},
{day12::problem1, day12::problem2},
{day13::problem1, day13::problem2},
{day14::problem1, day14::problem2},
{day15::problem1, day15::problem2},
{day16::problem1, day16::problem2},
{day17::problem1, day17::problem2},
{day18::problem1, day18::problem2},
{day19::problem1, day19::problem2},
{day20::problem1, day20::problem2},
{day21::problem1, day21::problem2},
{day22::problem1, day22::problem2},
{day23::problem1, day23::problem2},
};
if (argc > 2) {
std::cerr << "ERROR: Specify no params or a day # to run a specific day" << std::endl;
return -1;
}
int dayToRun = -1;
if (argc == 2) {
try {
dayToRun = std::stoi(argv[1]);
} catch (...) {
std::cerr << "ERROR: Invalid parameter!" << std::endl;
return -2;
}
if (dayToRun < 1 || dayToRun > days.size()) {
std::cerr << "ERROR: Day parameter is invalid!" << std::endl;
return -3;
}
}
if (dayToRun != -1) {
// Run a specific day
auto &problems = days[dayToRun - 1];
std::cout << "Running day " << dayToRun << std::endl;
for (auto &problem : problems) {
problem();
std::cout << std::endl;
}
} else {
// Run all days
for (auto &problems : days) {
for (auto &problem : problems) {
problem();
std::cout << std::endl;
}
}
}
return 0;
}
| true |
4b03fa5e80dc9be539efbd72f58a384afd206e62 | C++ | WhiZTiM/coliru | /Archive2/81/f548f490be838f/main.cpp | UTF-8 | 1,052 | 3 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
struct shared_ptr_s
{
// struct impl_t* inst;
int *use_cnt;
};
typedef struct shared_ptr_s shared_ptr_t; // unadorned type
#define shared_ptr struct shared_ptr_s __attribute__((cleanup(free_shared)))
#define SHARED_PTR_GET_ADD_REF(sp_in, sp_name) ++(*sp_in.use_cnt); printf("add use_cnt = %d\n", *sp_in.use_cnt); shared_ptr sp_name = sp_in;
void free_shared(struct shared_ptr_s* ptr)
{
if(!ptr) return;
printf("del use_cnt = %d\n", *ptr->use_cnt - 1);
if(0 == --(*ptr->use_cnt)) {
// dtor(ptr->inst);
printf("freeing %p\n", (void *)ptr->use_cnt);
free(ptr->use_cnt);
}
// ptr->inst = 0;
ptr->use_cnt = 0;
}
void func(shared_ptr_t sp)
{
SHARED_PTR_GET_ADD_REF(sp, sp_loc);
return;
}
int main(void)
{
shared_ptr_t sp = { // original type does not use __attribute__(cleanup)
// .inst = ctor(),
.use_cnt = malloc(sizeof(int))
};
SHARED_PTR_GET_ADD_REF(sp, sp_loc);
func(sp_loc);
return 0;
}
| true |
e63df57dcd3e50d8a128859527e4b9c98bf6ec77 | C++ | sakshamtaneja21/CPP | /file-1.cpp | UTF-8 | 424 | 3.515625 | 4 | [] | no_license | //Arithmetic Operations (27-8-19)
#include <iostream>
#include <conio.h>
int main(){
using namespace std;
cout << "18BCAN024\n\n";
int x, y, sum, diff, prod, quo;
cout << "Enter 2 numbers ";
cin >> x >> y;
sum = x+y; diff = x-y;
prod = x*y; quo = x/y;
cout << "Sum is " << sum;
cout << "\nDifference is " << diff;
cout << "\nProduct is " << prod;
cout << "\nQuotient is " << quo;
getch();
} | true |
50e954d7cb47b047bf7228e6055166e04a2363dc | C++ | SensorsINI/slasher | /arduino/firmware/3ch_ros_pub/3ch_ros_pub.ino | UTF-8 | 7,456 | 2.59375 | 3 | [] | no_license | #include <ros.h>
#include <ArduinoHardware.h>
#include <std_msgs/Float64.h>
#include <rally_msgs/Pwm.h>
#include "Servo.h"
ros::NodeHandle nh;
rally_msgs::Pwm raw_pwm_msg;
ros::Publisher raw_pwm_pub("raw_pwm", &raw_pwm_msg);
#define PWM_PUBLISH_RATE 10 //hz
// Assign your channel in pins
#define CHANNEL1_IN_PIN 2
#define CHANNEL2_IN_PIN 7
#define CHANNEL3_IN_PIN 3
// Assign your channel out pins
#define CHANNEL1_OUT_PIN 11
#define CHANNEL2_OUT_PIN 10
#define CHANNEL3_OUT_PIN 9
// Servo objects generate the signals expected by Electronic Speed Controllers and Servos
// We will use the objects to output the signals we read in
// this example code provides a straight pass through of the signal with no custom processing
Servo servoChannel1;
Servo servoChannel2;
Servo servoChannel3;
// These bit flags are set in bUpdateFlagsShared to indicate which
// channels have new signals
#define CHANNEL1_FLAG 1
#define CHANNEL2_FLAG 2
#define CHANNEL3_FLAG 4
// holds the update flags defined above
volatile uint32_t bUpdateFlagsShared;
// shared variables are updated by the ISR and read by loop.
// In loop we immediatley take local copies so that the ISR can keep ownership of the
// shared ones. To access these in loop
// we first turn interrupts off with noInterrupts
// we take a copy to use in loop and the turn interrupts back on
// as quickly as possible, this ensures that we are always able to receive new signals
volatile uint32_t unChannel1InShared;
volatile uint32_t unChannel2InShared;
volatile uint32_t unChannel3InShared;
void setup()
{
digitalWrite(CHANNEL2_IN_PIN, HIGH);
pciSetup(CHANNEL2_IN_PIN);
//Serial.begin(115200);
//Serial.println("multiChannels");
// attach servo objects, these will generate the correct
// pulses for driving Electronic speed controllers, servos or other devices
// designed to interface directly with RC Receivers
servoChannel1.attach(CHANNEL1_OUT_PIN);
servoChannel2.attach(CHANNEL2_OUT_PIN);
servoChannel3.attach(CHANNEL3_OUT_PIN);
// attach the interrupts used to read the channels
attachInterrupt(digitalPinToInterrupt(CHANNEL1_IN_PIN), calcChannel1, CHANGE);
//attachInterrupt(digitalPinToInterrupt(CHANNEL2_IN_PIN), calcChannel2, CHANGE); //pin_change_ISR
attachInterrupt(digitalPinToInterrupt(CHANNEL3_IN_PIN), calcChannel3, CHANGE);
// for loop back test only, lets set each channel to a known value
// servoChannel1.writeMicroseconds(1100);
// servoChannel2.writeMicroseconds(1200);
// servoChannel3.writeMicroseconds(1300);
nh.initNode(); // intialize ROS node
nh.getHardware()->setBaud(57600);
nh.advertise(raw_pwm_pub); // start the publisher..can be used for debugging.
while (!nh.connected())
{
nh.spinOnce();
}
nh.loginfo("LINOBASE CONNECTED");
delay(1);
}
void loop()
{
static unsigned long publish_pwm_time = 0;
// create local variables to hold a local copies of the channel inputs
// these are declared static so that thier values will be retained
// between calls to loop.
static uint32_t unChannel1In;
static uint32_t unChannel2In;
static uint32_t unChannel3In;
// local copy of update flags
static uint32_t bUpdateFlags;
// check shared update flags to see if any channels have a new signal
if (bUpdateFlagsShared)
{
noInterrupts(); // turn interrupts off quickly while we take local copies of the shared variables
// take a local copy of which channels were updated in case we need to use this in the rest of loop
bUpdateFlags = bUpdateFlagsShared;
// in the current code, the shared values are always populated
// so we could copy them without testing the flags
// however in the future this could change, so lets
// only copy when the flags tell us we can.
if (bUpdateFlags & CHANNEL1_FLAG)
{
unChannel1In = unChannel1InShared;
}
if (bUpdateFlags & CHANNEL2_FLAG)
{
unChannel2In = unChannel2InShared;
}
if (bUpdateFlags & CHANNEL3_FLAG)
{
unChannel3In = unChannel3InShared;
}
// clear shared copy of updated flags as we have already taken the updates
// we still have a local copy if we need to use it in bUpdateFlags
bUpdateFlagsShared = 0;
interrupts(); // we have local copies of the inputs, so now we can turn interrupts back on
// as soon as interrupts are back on, we can no longer use the shared copies, the interrupt
// service routines own these and could update them at any time. During the update, the
// shared copies may contain junk. Luckily we have our local copies to work with :-)
}
// do any processing from here onwards
// only use the local values unChannel1, unChannel2, unChannel3, unChannel4, unChannel5, unChannel6, unChannel7, unChannel8
// variables unChannel1InShared, unChannel2InShared, etc are always owned by the
// the interrupt routines and should not be used in loop
if (bUpdateFlags & CHANNEL1_FLAG)
{
// remove the // from the line below to implement pass through updates to the servo on this channel -
servoChannel1.writeMicroseconds(unChannel1In);
//////Serial.println();
//Serial.print("CH1: ");
//Serial.print(unChannel1In);
//Serial.print(",");
}
if (bUpdateFlags & CHANNEL2_FLAG)
{
// remove the // from the line below to implement pass through updates to the servo on this channel -
servoChannel2.writeMicroseconds(unChannel2In);
//Serial.print("CH2: ");
//Serial.print(unChannel2In);
//Serial.print(",");
}
if (bUpdateFlags & CHANNEL3_FLAG)
{
// remove the // from the line below to implement pass through updates to the servo on this channel -
servoChannel3.writeMicroseconds(unChannel3In);
//Serial.print("CH3: ");
//Serial.print(unChannel3In);
//Serial.print(",");
}
if ((millis() - publish_pwm_time) >= (1000 / PWM_PUBLISH_RATE))
{
publishPWM(unChannel1In, unChannel2In, unChannel3In);
publish_pwm_time = millis();
}
bUpdateFlags = 0;
nh.spinOnce();
}
void calcChannel1()
{
static uint32_t ulStart;
if (digitalRead(CHANNEL1_IN_PIN))
{
ulStart = micros();
}
else
{
unChannel1InShared = (uint32_t)(micros() - ulStart);
bUpdateFlagsShared |= CHANNEL1_FLAG;
}
}
void calcChannel2()
{
static uint32_t ulStart;
if (digitalRead(CHANNEL2_IN_PIN))
{
ulStart = micros();
}
else
{
unChannel2InShared = (uint32_t)(micros() - ulStart);
bUpdateFlagsShared |= CHANNEL2_FLAG;
}
}
void calcChannel3()
{
static uint32_t ulStart;
if (digitalRead(CHANNEL3_IN_PIN))
{
ulStart = micros();
}
else
{
unChannel3InShared = (uint32_t)(micros() - ulStart);
bUpdateFlagsShared |= CHANNEL3_FLAG;
}
}
void pciSetup(byte pin)
{
*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin)); // enable pin
PCIFR |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
PCICR |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group
}
ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here
{
//Serial.println("Ha");
calcChannel2();
}
void publishPWM(uint32_t CH1, uint32_t CH2, uint32_t CH3)
{
//pass accelerometer data to imu object
raw_pwm_msg.steering = CH1;
//pass gyroscope data to imu object
raw_pwm_msg.throttle = CH2;
//pass accelerometer data to imu object
raw_pwm_msg.gear_shift = CH3;
//publish raw_imu_msg object to ROS
raw_pwm_pub.publish(&raw_pwm_msg);
}
| true |
b7d2c7a48e4454d0afc62aa21c2cb2f618b4a15d | C++ | heiyanbin/leetcode | /61 Rotate List_4.cpp | UTF-8 | 727 | 3.328125 | 3 | [] | no_license | // 61
// Rotate List
// https://leetcode.com//problems/rotate-list/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(!head || !head->next||k<1) return head;
ListNode* p=head, *q=head;
int n=0;
while(q && n<k)
{
q=q->next;
n++;
}
if(q==NULL && n==k)
return head;
else if(n<k)
{
k= k%n;
for(n=0,q=head;n<k;n++)
q=q->next;
}
while(q->next)
{
p=p->next;
q=q->next;
}
q->next = head;
head=p->next;
p->next=NULL;
return head;
}
}; | true |
995f29905215393a0aa7c968c8579939c15a36c5 | C++ | ukiras123/Ser321 | /Assigns/Assign1/src/cpp/Fraction.cpp | UTF-8 | 2,052 | 2.96875 | 3 | [] | no_license | #include "Fraction.hpp"
#include <iostream>
#include <stdlib.h>
#include <cmath>
/**
* Copyright 2015 Tim Lindquist,
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Purpose: demonstrate simple C++ class
* Ser321 Foundations of Distributed Applications
* see http://pooh.poly.asu.edu/Ser321
* @author Tim Lindquist Tim.Lindquist@asu.edu
* Software Engineering, CIDSE, IAFSE, ASU Poly
* @version July 2015
*/
Fraction::Fraction(){
numerator = 0;
denominator = 1;
}
Fraction::~Fraction() {
//cout << "Fraction destructor called." << endl;
numerator=0;
denominator=0;
}
void Fraction::setNumerator(int n) {
numerator = n;
}
int Fraction::getNumerator() {
return numerator;
}
void Fraction::setDenominator(int n) {
denominator = n;
}
int Fraction::getDenominator() {
return denominator;
}
Fraction Fraction::operator+(const Fraction& b){
Fraction a;
a.numerator = numerator*b.denominator+b.numerator*denominator;
a.denominator = denominator * b.denominator;
return a;
}
Fraction Fraction::operator*(const Fraction& b){
Fraction a;
a.numerator = numerator * b.numerator;
a.denominator = denominator * b.denominator;
return a;
}
void Fraction::reduce(){
for (int i = denominator * numerator; i > 1; i--) {
if ((denominator % i == 0) && (numerator % i == 0)) {
denominator /= i;
numerator /= i;
}
}
}
string Fraction::toString(){
string ret = "fraction "+std::to_string(numerator)+"/"+std::to_string(denominator);
return ret;
}
| true |
34ef56859e546a8db9f591c1e23eb1312cd06cff | C++ | JYILY/ds | /list.cpp | UTF-8 | 2,939 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
//顺序表的最大容量
#define MAXSIZE 100
//操作状态
#define OK 1
#define ERROR 0
//错误信息
#define ILLEGAL_INDEX "illegal index"
#define OUTOFMEMORY "out of memory"
//数据类型
typedef int ElemType;
//状态信息
typedef struct {
int status;
string msg;
}Status;
typedef struct{
ElemType *elem;
int length;
}SqList;
Status InitList(SqList& L); //初始化顺序表
Status DestroyList(SqList& L); //销毁顺序表
Status ClearList(SqList& L); //清空顺序表
Status ListEmpty(SqList L); //表是否为空
Status GetElem(SqList L,int index, ElemType &elem); //获取元素
int LocateElem(SqList L,ElemType elem); //返回元素的位置,不存在返回-1
Status ListInsert(SqList& L,int index,ElemType elem); //插入元素
Status ListDelete(SqList& L,int index); //删除元素
void PrintList(SqList L); //打印元素
void CheckError(Status s);
bool auto_check = true;
int main(){
SqList l;
InitList(l);
PrintList(l);
for(int i=0;i<5;i++){
ListInsert(l,i,i);
PrintList(l);
}
ListInsert(l,3,55);
PrintList(l);
ListDelete(l,2);
PrintList(l);
ElemType e;
GetElem(l,1,e);
cout<<"e : "<<e<<endl;
return 0;
}
void CheckError(Status s){
cout<<"---> ";
switch (s.status){
case OK: cout<<s.msg<<" sucessful"<<endl;break;
case ERROR: cout<<"ERROR! "<<s.msg<<endl;break;
}
}
Status InitList(SqList& L){
Status s;
L.elem = new ElemType[MAXSIZE];
if(!L.elem) s = {ERROR,OUTOFMEMORY};
L.length = 0;
s = {OK,"InitList"};
if(auto_check)CheckError(s);
return s;
}
Status ListInsert(SqList &L,int index,ElemType elem){
Status s;
if(index<0||index>L.length) s = {ERROR, ILLEGAL_INDEX};
else if(L.length == MAXSIZE) s = {ERROR, OUTOFMEMORY};
else {
for (int i=L.length-1;i>=index;i--) L.elem[i+1] = L.elem[i];
L.elem[index] = elem;
++L.length;
s = {OK,"Insert " + to_string(elem) + " at " + to_string(index)};
}
if(auto_check) CheckError(s);
return s;
}
Status GetElem(SqList L,int index, ElemType &elem){
Status s;
if(index<0||index>=L.length) s = {ERROR,ILLEGAL_INDEX};
else{
elem = L.elem[index];
s = {OK,"get "+to_string(elem)+" from index "+to_string(index)};
}
if(auto_check) CheckError(s);
return s;
}
Status ListDelete(SqList& L,int index){
Status s;
if(index<0||index>=L.length) s = {ERROR,ILLEGAL_INDEX};
else{
s = {OK,"delete "+to_string(L.elem[index])+" from index "+to_string(index)};
for(int i=index;i<L.length-1;i++) L.elem[i] = L.elem[i+1];
--L.length;
}
if(auto_check) CheckError(s);
return s;
}
void PrintList(SqList L){
cout<<"List("+to_string(L.length)<<") : ";
for(int i=0;i<L.length;i++){
cout<<L.elem[i]<<" ";
}
cout<<endl;
} | true |
943f042b0b8209412aeb9c2dd294d53c42c4d353 | C++ | outInsideOut/SmartSudoku | /SmartSudokuMk2/Sudoku.cpp | UTF-8 | 16,347 | 3.671875 | 4 | [] | no_license | #include "Sudoku.h"
#include <cmath>
Sudoku::Sudoku(char input[9][9]) {
try {
if (!GridChecker(input)) {
throw(ImpossiblePuzzleException("Duplicate value in grid"));
}
}
catch (ImpossiblePuzzleException& e) {
//msg = " duplicate in row, col or 3x3 "
//print exception message
std::cout << e.getMessage() << std::endl;
//exit program
std::cout << std::endl << "exiting program" << std::endl;
exit(0);
}
for (short i = 0; i < 9; i++) {
for (short j = 0; j < 9; j++) {
//pointer to cell object
Cell* currCell = &grid[i][j];
try {
//if ! ('0' <= char <= '9')
if (input[i][j] < 48 || input[i][j] > 57) {
//create message string for exception
std::string errorCode = "Invalid character in input grid at (" + std::to_string(j) + ", " + std::to_string(i) + ")";
//throw exception
throw (InputException(errorCode));
}
//set grid Cell's value to the inputted Grid's value at the same index
currCell->value = input[i][j];
}
catch (InputException& e) {
//print exception message
std::cout << e.getMessage() << std::endl;
//exit program
std::cout << std::endl << "exiting program" << std::endl;
exit(0);
}
//if value isn't 0 it will be a constant vbalue so cell's locked == true
if (input[i][j] != '0') {
currCell->Lock();
}
//set cell's coordinates
currCell->SetY(&i); //y coord
currCell->SetX(&j);//x coord
short ThreesIndex = getThreesIndex(i,j);
currCell->setThreex3Index(&ThreesIndex);
//Cell* smallestOptions is consciously left uninitialised
//this is as it will have a cell assigned to it as a pointer, rather than it being dynamic memory
//initialising now would be uneeded work (memory allocation & construction) for this variable's use
}
}
solved = false;
}
short getThreesIndex(short i, short j) {
//set cell's 3x3 index
//there is some simple calculations and conditions here to work out the 3x3 index
short rowStart = std::floor(i / 3) * 3;
short col = std::floor(j / 3);
return rowStart + col;
}
bool Sudoku::GridChecker(char gridIn[][9]) {
short x = 0;
short y = 0;
//pattern repeats in 3s, 3 times
for (short i = 0; i < 3; i++) {
for (short j = 0; j < 3; j++) {
char val;
//CheckRow
std::vector<char>* tmpList = new std::vector<char>;
for (int z = 0; z < 9; z++) {
val = gridIn[y][z];
if (val != '0') {
if (Is_x_Possible(tmpList, &val)) {
tmpList->push_back(val);
}
else {
return false;
}
}
}
tmpList->clear();
//CheckCol
for (int z = 0; z < 9; z++) {
val = gridIn[z][x];
if (val != '0') {
if (Is_x_Possible(tmpList, &val)) {
tmpList->push_back(val);
}
else {
return false;
}
}
}
tmpList->clear();
//get 3x3 starting point for the cell passed
short rowStart = y - (y % 3);
short colStart = x - (x % 3);
//loop through all cells in 3x3
for (short rowIndex = rowStart; rowIndex < (rowStart + 3); rowIndex++) {
for (short colIndex = colStart; colIndex < (colStart + 3); colIndex++) {
//if the cell is still unsolved
val = gridIn[colIndex][rowIndex];
if (val != '0') {
if (Is_x_Possible(tmpList, &val)) {
tmpList->push_back(val);
}
else {
return false;
}
}
}
}
delete tmpList;
x += 3;
y++;
}
x -= 8;
}
return true;
}
void Sudoku::SolveInit() {
//fill vectors for all cells, rows, cols and 3x3s
FindImpossibleValues();
//While puzzle is imcomplete
while (!CheckComplete()) {
//set a pointer to the next cell to fill
Cell* c =FindNextCell();
//if there is more than one option for the best next cell then estimate
if (c == nullptr) {
Estimate(smallestOptions);
}
//if there is only one option for best next cell
else {
char x = '1';
//find the fill option and fill
for (short i = 0; i < 8; i++) {
if (Is_x_Possible(&c->impossibleValues, &x))
break;
x++;
}
FillCell(c, x);
}
}
PrintSudoku();
}
void Sudoku::PrintSudoku() {
for (short i = 0; i < 9; i++) {
if (i % 3 == 0) {
std::cout << " ========================================= \n";
}
else {
std::cout << " ----------------------------------------- \n";
}
for (short j = 0; j < 9; j++) {
if (j % 3 == 0) {
std::cout << " || " << grid[i][j].value;
}
else {
std::cout << " | " << grid[i][j].value;
}
}
std::cout << " || \n";
}
std::cout << " ========================================= \n";
}
bool Sudoku::CheckComplete()
{
for (short i = 0; i < 9; i++) {
for (short j = 0; j < 9; j++) {
if (grid[j][i].value == '0')
return false;
}
}
return true;
}
void Sudoku::FillCell(Cell* cellIn, char c) {
if (c == '0') {
int a = 1;
}
//if a cell is trying to be filled but all possible values are tried
if (cellIn->impossibleValues.size() == 9) {
//Backtrack
Backtrack(cellIn);
//Update all vectors
FindImpossibleValues();
return;
}
//Fill Cell with char
cellIn->Fill(c);
//update cell's impossible values
cellIn->PushToImpossibleValues(cellIn->value);
//get coords of cell
short* y = cellIn->getY();
short* x = cellIn->getX();
short* threesIndex = cellIn->get3x3();
//Add cell's values to Puzzle's relevant vectors
AddToVector(&rows[*y], &c);
AddToVector(&cols[*x], &c);
AddToVector(&threeBy3s[*threesIndex], &c);
//update the estiamations path for potential, future backtracking
if (estimating == true) {
path[long long (estimateDepth) - 1].push_back(cellIn);
}
//update relevant
FindImpossibleValues(cellIn);
noOfFills++;
}
//empties cell
void Sudoku::EmptyCell(Cell* cellIn) {
cellIn->Empty();
}
//checks if a char value is possible for a passed vector
bool Sudoku::Is_x_Possible(std::vector<char>* vectIn, char* valueIn) {
std::vector<char>::iterator it;
for (it = begin(*vectIn); it != end(*vectIn); it++) {
if (*it == *valueIn) {
return false;
}
}
return true;
}
void Sudoku::AddToVector(std::vector<char>* vectPtr, char* cIn) {
//check vector for cIn value
if (Is_x_Possible(vectPtr, cIn)) {
//if cIn not already in vector, add it
vectPtr->push_back(*cIn);
}
}
void Sudoku::FindImpossibleValues() {
//perform checks on all rows, cols and 3x3s
for (short i = 0; i < 9; i++) {
cols[i].clear();
rows[i].clear();
threeBy3s[i].clear();
}
//check: row, col, 3x3 of following cells to check all of each type
/*
=========================================
|| x | | || | | || | | ||
-----------------------------------------
|| | | || x | | || | | ||
-----------------------------------------
|| | | || | | || x | | ||
=========================================
|| | x | || | | || | | ||
-----------------------------------------
|| | | || | x | || | | ||
-----------------------------------------
|| | | || | | || | x | ||
=========================================
|| | | x || | | || | | ||
-----------------------------------------
|| | | || | | x || | | ||
-----------------------------------------
|| | | || | | || | | x ||
=========================================
(0,0), (3, 1), (6, 2), (1, 3), (4, 4), (7, 5), (2, 6), (5, 7), (8, 8)
if the length returned by completeing these is ever 8:
find and fill the empty cell then restart
else
UpdateImpossibleValues for all cells:
if (Cell.impossibleValues.len() == 8):
then input the missing value
*/
//
//x + y of points to be checked
short x = 0;
short y = 0;
Cell* tempCell;
//pattern repeats in 3s, 3 times
for (short i = 0; i < 3; i++) {
for (short j = 0; j < 3; j++) {
/*cout << "\n(" << x << ", " << y << ")";*/
tempCell = &grid[y][x];
//update row, col & 3x3 the the tempCell belongs to
CheckRow(tempCell);
CheckCol(tempCell);
Check3x3(tempCell);
x += 3;
y++;
}
x -= 8;
}
//if no row, col or 3x3 only had one option, try each cell
for (short i = 0; i < 9; i++) {
for (short j = 0; j < 9; j++) {
tempCell = &grid[i][j];
if (tempCell->value == '0') {
UpdateImpossibleValues(tempCell);
}
}
}
}
void Sudoku::FindImpossibleValues(Cell* cellIn) {
short* y = cellIn->getY();
short* x = cellIn->getX();
short* threesIndex = cellIn->get3x3();
//update row, col & 3x3 the the passed cell belongs to
CheckRow(cellIn);
CheckCol(cellIn);
Check3x3(cellIn);
Cell* tempCell;
//update cells in row and column
for (short i = 0; i < 9; i++) {
//row
tempCell = &grid[i][*x];
if (tempCell->value == '0')
UpdateImpossibleValues(tempCell);
//column
tempCell = &grid[*y][i];
if (tempCell->value == '0')
UpdateImpossibleValues(tempCell);
}
//get 3x3 starting point for the cell passed
short rowStart = *y - (*y % 3);
short colStart = *x - (*x % 3);
//loop through all cells in 3x3, updating their "impvals"
for (short rowIndex = rowStart; rowIndex < (rowStart + 3); rowIndex++) {
for (short colIndex = colStart; colIndex < (colStart + 3); colIndex++) {
//store pointer to cell's value var
tempCell = &grid[rowIndex][colIndex];
if (tempCell->value == '0')
UpdateImpossibleValues(tempCell);
}
}
UpdateImpossibleValues(cellIn);
}
void Sudoku::UpdateImpossibleValues(Cell* cellIn) {
//std::cout << "updating (" << *cellIn->getX() << ", " << *cellIn->getY() << ")\n";
short* y = cellIn->getY();
short* x = cellIn->getX();
short* threesIndex = cellIn->get3x3();
cellIn->impossibleValues.clear();
for (std::vector<char>::iterator it = begin(cols[*x]); it != end(cols[*x]); it++) {
cellIn->PushToImpossibleValues(*it);
}
for (std::vector<char>::iterator it = begin(rows[*y]); it != end(rows[*y]); it++) {
cellIn->PushToImpossibleValues(*it);
}
for (std::vector<char>::iterator it = begin(threeBy3s[*threesIndex]); it != end(threeBy3s[*threesIndex]); it++ ) {
cellIn->PushToImpossibleValues(*it);
}
}
//if there is a cell with only one option, a ptr to that cell is returned
// else, the cell with the least options is pointed to with Sudoku::smallestOptions
//and a nullptr is returned
Cell* Sudoku::FindNextCell() {
short length, index;
char type = 'z';
Cell* tempCell = &grid[0][0];
//check for a row, column or 3x3 with 8 values
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 9; i++) {
if (j == 0) {
length = short(cols[i].size());
if (length == 8) {
type = 'c';
index = i;
break;
}
}
else if (j == 1) {
length = short(rows[i].size());
if (length == 8) {
type = 'r';
index = i;
break;
}
}
else if (j == 2) {
length = short(threeBy3s[i].size());
if (length == 8) {
type = 't';
index = i;
break;
}
}
}
}
if (type != 'z') {
if (type == 'c') {
tempCell = FindEmptyInCol(&index);
}
else if (type == 'r') {
tempCell = FindEmptyInRow(&index);
}
else if (type == 't') {
tempCell = FindEmptyIn3x3(&index);
}
return tempCell;
}
smallestOptionsSize = 0;
for (short i = 0; i < 9; i++) {
for (short j = 0; j < 9; j++) {
tempCell = &grid[i][j];
if (tempCell->value == '0') {
length = short(tempCell->impossibleValues.size());
if (length == 8) {
return tempCell;
}
if (length > smallestOptionsSize) {
smallestOptions = tempCell;
smallestOptionsSize = length;
}
}
}
}
return nullptr;
}
short getLocalIndex(short i) {
return i - (i % 3);
}
void Sudoku::Check3x3(Cell* cellIn) {
//get cell's coordinates
short* cellX = cellIn->getX();
short* cellY = cellIn->getY();
//get 3x3 starting point for the cell passed
short rowStart = *cellY- (*cellY % 3);
short colStart = *cellX - (*cellX % 3);
//loop through all cells in 3x3
for (short rowIndex = rowStart; rowIndex < (rowStart + 3); rowIndex++) {
for (short colIndex = colStart; colIndex < (colStart + 3); colIndex++) {
//store pointer to cell's value var
char* value = &grid[rowIndex][colIndex].value;
//if the cell is still unsolved
if (*value != '0') {
AddToVector(&threeBy3s[*cellIn->get3x3()], value);
}
}
}
}
void Sudoku::CheckCol(Cell* cellIn) {
//get column position from cell objects coordinates
short* col = cellIn->getX();
//loow through the row's cells
for (short i = 0; i < 9; i++) {
//temp stor cell's value
char* tempChar = &grid[i][*col].value;
//if value isn't '0' try and add it to the row's vector
if (*tempChar != '0') {
AddToVector(&cols[*col], tempChar);
}
}
}
void Sudoku::CheckRow(Cell* cellIn) {
//get row position from cell objects coordinates
short* row = cellIn->getX();
//loow through the row's cells
for (short i = 0; i < 9; i++) {
//temp stor cell's value
char* tempChar = &grid[*row][i].value;
//if value isn't '0' try and add it to the row's vector
if (*tempChar != '0') {
AddToVector(&rows[*row], tempChar);
}
}
}
//finds empty cell in row
Cell* Sudoku::FindEmptyInRow(short* rowIndex) {
for (short i = 0; i < 9; i++) {
char value = grid[*rowIndex][i].value;
if (value == '0') {
return &grid[*rowIndex][i];
}
}
return nullptr;
}
//finds empty cell in column
Cell* Sudoku::FindEmptyInCol(short* colIndex) {
for (short i = 0; i < 9; i++) {
char value = grid[i][*colIndex]long.value;
if (value == '0') {
return &grid[i][*colIndex];
}
}
return nullptr;
}
//finds empty cell in 3x3
Cell* Sudoku::FindEmptyIn3x3(short* threeX3Index) {
short rowStart;
short colStart;
//find starting cell of 3x3
if (*threeX3Index < 3) {
rowStart = 0;
}
else if (*threeX3Index < 6) {
rowStart = 3;
}
else rowStart = 6;
if (*threeX3Index % 3 == 0) {
colStart = 0;
}
else if (*threeX3Index % 3 == 1) {
colStart = 3;
}
else colStart = 6;
for (short rowIndex = rowStart; rowIndex < rowStart + 3; rowIndex++) {
for (short colIndex = colStart; colIndex < colStart + 3; colIndex++) {
//store pointer to cell's value var
char* value = &grid[rowIndex][colIndex].value;
//if the cell is still unsolved
if (*value == '0') {
return &grid[rowIndex][colIndex];
}
}
}
return nullptr;
}
//Makes estimate if no certain cell
void Sudoku::Estimate(Cell* c) {
if (c->impossibleValues.size() < 9) {
char x = '1';
estimating = true;
//std::cout << "\nestimating at cell(" << *c->getX() << ", " << *c->getY() << ")\n";
//loop '1' to '9'
for (short i = 0; i < 9; i++) {
//if the value is valid
if (c->Is_x_Possible(&x) == true) {
//set cell's estimation indicator to true
c->estimate = true;
//increase the estimation depth
estimateDepth += 1;
//add cell_ptr to path
path.push_back({ });
//input the value to the cell
FillCell(c, x);
return;
}
x++;
}
}
else {
//backtrack or broken (y)
Backtrack(c);
FindImpossibleValues();
}
}
void Sudoku::Backtrack(Cell* cellIn) {
std::vector<Cell*>::iterator it;
try {
if (cellIn->value == '0') {
EmptyCell(cellIn);
it = path[long long(estimateDepth) - 1].end();
it -= 1;
Cell* cellPtr = *it;
Backtrack(cellPtr);
return;
}
else {
if (cellIn->estimate) {
if (estimateDepth == 9) {
//...
int i = 1;
}
//if there are more values to put in
if (cellIn->impossibleValues.size() < 9) {
//put in another estimate
cellIn->value = '0';
path.pop_back();
estimateDepth -= 1;
Estimate(cellIn);
return;
}
else {
if (path.size() == 1) {
//throw impossiblePuzzle exception
throw (ImpossiblePuzzleException("Estimation options are exhausted!"));
}
EmptyCell(cellIn);
path.pop_back();
estimateDepth -= 1;
it = path[long long(estimateDepth) - 1].end();
it -= 1;
Cell* cellPtr = *it;
Backtrack(cellPtr);
return;
}
}
else {
EmptyCell(cellIn);
path[long long(estimateDepth) - 1].pop_back();
it = path[long long(estimateDepth) - 1].end();
it -= 1;
Cell* cellPtr = *it;
Backtrack(cellPtr);
return;
}
}
}
catch (ImpossiblePuzzleException& e) {
//print exception message
std::cout << e.getMessage() << std::endl;
//exit program
std::cout << std::endl << "exiting program" << std::endl;
exit(0);
}
} | true |
93c1beba2058c0d88a604b0255a6a0bf2667753f | C++ | twpspu/SimpleMVCExample | /resortreservationrecord.h | UTF-8 | 970 | 2.734375 | 3 | [] | no_license | // Class ResortReservationRecord
// Original author is and all rights reserved for Andrew Mclain @ SPU ECS
#ifndef RESORTRESERVATIONRECORD_H
#define RESORTRESERVATIONRECORD_H
#include <string>
#include <sstream>
using std::string;
class ResortReservationRecord
{
private:
// add your private member variables here.
string customerName;
int roomType;
int numNights;
bool parking;
double totalCost;
public:
static const std::string ROOM_NAME[];
static const double ROOM_RATE_PER_NIGHT[];
static const double PARKING_PER_NIGHT;
ResortReservationRecord();
// add your public member function declarations here.
string getCustomerName()const;
void setCustomerName(string name);
void setRoomType(int num);
int getNumNights()const;
void setNumNights(int a);
bool getParking()const;
void setParking(bool arg);
double CalculateCost();
string CurrentChoice();
};
#endif // RESORTRESERVATIONRECORD_H
| true |
865b427a05e5cb8e7c2166b7b171bc7d1c1a42de | C++ | roytwu/cpp | /oop/static/main.cpp | UTF-8 | 1,138 | 3.234375 | 3 | [] | no_license | /* *********************************************************
Author: Roy Wu
Description: static class members/member funcitons
********************************************************* */
//#include <iostream>
//#include <string>
#include <vector>
#include <Eigen/Core> //* this needs to added before <opencv2/core/eigen.hpp>
#include <Eigen/Dense> //* Eigen library: Matrix
#include <Eigen/Geometry> //* Eigen library: quaternion
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
#include "account.h"
//using std::cout;
//using std::endl;
//using std::string;
int main()
{
//* access a static member using the scope operator
//* note that there is no Account object
double r = Account::findRate();
cout << r << endl;
//* access static member by using an object, reference or pointer
Account o_ac1;
Account * o_ac2 = &o_ac1;
r = o_ac1.findRate(); //* through an Account object
r = o_ac2->findRate(); //* through a pointer to an Account object
//* through an Account object reference
double result = ref_a().findRate();
cout << result << endl;
return 0;
}
| true |
a927b161f0c70fc76052064faaafea95ab97123d | C++ | tnakaicode/jburkardt | /r83p/r83p.cpp | UTF-8 | 49,302 | 3.125 | 3 | [] | no_license | # include <cmath>
# include <cstdlib>
# include <ctime>
# include <fstream>
# include <iomanip>
# include <iostream>
using namespace std;
# include "r83p.hpp"
//****************************************************************************80
int i4_log_10 ( int i )
//****************************************************************************80
//
// Purpose:
//
// I4_LOG_10 returns the integer part of the logarithm base 10 of ABS(X).
//
// Example:
//
// I I4_LOG_10
// ----- --------
// 0 0
// 1 0
// 2 0
// 9 0
// 10 1
// 11 1
// 99 1
// 100 2
// 101 2
// 999 2
// 1000 3
// 1001 3
// 9999 3
// 10000 4
//
// Discussion:
//
// I4_LOG_10 ( I ) + 1 is the number of decimal digits in I.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, the number whose logarithm base 10 is desired.
//
// Output, int I4_LOG_10, the integer part of the logarithm base 10 of
// the absolute value of X.
//
{
int i_abs;
int ten_pow;
int value;
if ( i == 0 )
{
value = 0;
}
else
{
value = 0;
ten_pow = 10;
i_abs = abs ( i );
while ( ten_pow <= i_abs )
{
value = value + 1;
ten_pow = ten_pow * 10;
}
}
return value;
}
//****************************************************************************80
int i4_max ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MAX returns the maximum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, are two integers to be compared.
//
// Output, int I4_MAX, the larger of I1 and I2.
//
{
int value;
if ( i2 < i1 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4_min ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MIN returns the minimum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, two integers to be compared.
//
// Output, int I4_MIN, the smaller of I1 and I2.
//
{
int value;
if ( i1 < i2 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4_power ( int i, int j )
//****************************************************************************80
//
// Purpose:
//
// I4_POWER returns the value of I^J.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, J, the base and the power. J should be nonnegative.
//
// Output, int I4_POWER, the value of I^J.
//
{
int k;
int value;
if ( j < 0 )
{
if ( i == 1 )
{
value = 1;
}
else if ( i == 0 )
{
cerr << "\n";
cerr << "I4_POWER - Fatal error!\n";
cerr << " I^J requested, with I = 0 and J negative.\n";
exit ( 1 );
}
else
{
value = 0;
}
}
else if ( j == 0 )
{
if ( i == 0 )
{
cerr << "\n";
cerr << "I4_POWER - Fatal error!\n";
cerr << " I^J requested, with I = 0 and J = 0.\n";
exit ( 1 );
}
else
{
value = 1;
}
}
else if ( j == 1 )
{
value = i;
}
else
{
value = 1;
for ( k = 1; k <= j; k++ )
{
value = value * i;
}
}
return value;
}
//****************************************************************************80
int r83_np_fa ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R83_NP_FA factors an R83 system without pivoting.
//
// Discussion:
//
// The R83 storage format is used for a tridiagonal matrix.
// The superdiagonal is stored in entries (1,2:min(M+1,N)).
// The diagonal in entries (2,1:min(M,N)).
// The subdiagonal in (3,min(M-1,N)).
//
// Because this routine does not use pivoting, it can fail even when
// the matrix is not singular, and it is liable to make larger
// errors.
//
// R83_NP_FA and R83_NP_SL may be preferable to the corresponding
// LINPACK routine SGTSL for tridiagonal systems, which factors and solves
// in one step, and does not save the factorization.
//
// Example:
//
// An R83 matrix of order 3x5 would be stored:
//
// * A12 A23 A34 *
// A11 A22 A33 * *
// A21 A32 * * *
//
// An R83 matrix of order 5x5 would be stored:
//
// * A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 *
//
// An R83 matrix of order 5x3 would be stored:
//
// * A12 A23
// A11 A22 A33
// A21 A32 A43
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 2.
//
// Input/output, double A[3*N].
// On input, the tridiagonal matrix. On output, factorization information.
//
// Output, int R83_NP_FA, singularity flag.
// 0, no singularity detected.
// nonzero, the factorization failed on the INFO-th step.
//
{
int i;
for ( i = 1; i <= n-1; i++ )
{
if ( a[1+(i-1)*3] == 0.0 )
{
cerr << "\n";
cerr << "R83_NP_FA - Fatal error!\n";
cerr << " Zero pivot on step " << i << "\n";
exit ( 1 );
}
//
// Store the multiplier in L.
//
a[2+(i-1)*3] = a[2+(i-1)*3] / a[1+(i-1)*3];
//
// Modify the diagonal entry in the next column.
//
a[1+i*3] = a[1+i*3] - a[2+(i-1)*3] * a[0+i*3];
}
if ( a[1+(n-1)*3] == 0.0 )
{
cerr << "\n";
cerr << "R83_NP_FA - Fatal error!\n";
cerr << " Zero pivot on step " << n << "\n";
exit ( 1 );
}
return 0;
}
//****************************************************************************80
double *r83_np_ml ( int n, double a_lu[], double x[], int job )
//****************************************************************************80
//
// Purpose:
//
// R83_NP_ML computes Ax or xA, where A has been factored by R83_NP_FA.
//
// Discussion:
//
// The R83 storage format is used for a tridiagonal matrix.
// The superdiagonal is stored in entries (1,2:min(M+1,N)).
// The diagonal in entries (2,1:min(M,N)).
// The subdiagonal in (3,min(M-1,N)).
//
// Example:
//
// An R83 matrix of order 3x5 would be stored:
//
// * A12 A23 A34 *
// A11 A22 A33 * *
// A21 A32 * * *
//
// An R83 matrix of order 5x5 would be stored:
//
// * A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 *
//
// An R83 matrix of order 5x3 would be stored:
//
// * A12 A23
// A11 A22 A33
// A21 A32 A43
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 2.
//
// Input, double A_LU[3*N], the LU factors from R83_FA.
//
// Input, double X[N], the vector to be multiplied by A.
//
// Output, double B[N], the product.
//
// Input, int JOB, specifies the product to find.
// 0, compute A * x.
// nonzero, compute A' * x.
//
{
double *b;
int i;
b = new double[n];
for ( i = 0; i < n; i++ )
{
b[i] = x[i];
}
if ( job == 0 )
{
//
// Compute X := U * X
//
for ( i = 1; i <= n; i++ )
{
b[i-1] = a_lu[1+(i-1)*3] * b[i-1];
if ( i < n )
{
b[i-1] = b[i-1] + a_lu[0+i*3] * b[i];
}
}
//
// Compute X: = L * X.
//
for ( i = n; 2 <= i; i-- )
{
b[i-1] = b[i-1] + a_lu[2+(i-2)*3] * b[i-2];
}
}
else
{
//
// Compute X: = L' * X.
//
for ( i = 1; i <= n-1; i++ )
{
b[i-1] = b[i-1] + a_lu[2+(i-1)*3] * b[i];
}
//
// Compute X: = U' * X.
//
for ( i = n; 1 <= i; i-- )
{
b[i-1] = a_lu[1+(i-1)*3] * b[i-1];
if ( 1 < i )
{
b[i-1] = b[i-1] + a_lu[0+(i-1)*3] * b[i-2];
}
}
}
return b;
}
//****************************************************************************80
double *r83_np_sl ( int n, double a_lu[], double b[], int job )
//****************************************************************************80
//
// Purpose:
//
// R83_NP_SL solves an R83 system factored by R83_NP_FA.
//
// Discussion:
//
// The R83 storage format is used for a tridiagonal matrix.
// The superdiagonal is stored in entries (1,2:min(M+1,N)).
// The diagonal in entries (2,1:min(M,N)).
// The subdiagonal in (3,min(M-1,N)).
//
// Example:
//
// An R83 matrix of order 3x5 would be stored:
//
// * A12 A23 A34 *
// A11 A22 A33 * *
// A21 A32 * * *
//
// An R83 matrix of order 5x5 would be stored:
//
// * A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 *
//
// An R83 matrix of order 5x3 would be stored:
//
// * A12 A23
// A11 A22 A33
// A21 A32 A43
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 2.
//
// Input, double A_LU[3*N], the LU factors from R83_NP_FA.
//
// Input, double B[N], the right hand side of the linear system.
// On output, B contains the solution of the linear system.
//
// Input, int JOB, specifies the system to solve.
// 0, solve A * x = b.
// nonzero, solve A' * x = b.
//
// Output, double R83_NP_SL[N], the solution of the linear system.
//
{
int i;
double *x;
x = new double[n];
for ( i = 0; i < n; i++ )
{
x[i] = b[i];
}
if ( job == 0 )
{
//
// Solve L * Y = B.
//
for ( i = 1; i < n; i++ )
{
x[i] = x[i] - a_lu[2+(i-1)*3] * x[i-1];
}
//
// Solve U * X = Y.
//
for ( i = n; 1 <= i; i-- )
{
x[i-1] = x[i-1] / a_lu[1+(i-1)*3];
if ( 1 < i )
{
x[i-2] = x[i-2] - a_lu[0+(i-1)*3] * x[i-1];
}
}
}
else
{
//
// Solve U' * Y = B
//
for ( i = 1; i <= n; i++ )
{
x[i-1] = x[i-1] / a_lu[1+(i-1)*3];
if ( i < n )
{
x[i] = x[i] - a_lu[0+i*3] * x[i-1];
}
}
//
// Solve L' * X = Y.
//
for ( i = n-1; 1 <= i; i-- )
{
x[i-1] = x[i-1] - a_lu[2+(i-1)*3] * x[i];
}
}
return x;
}
//****************************************************************************80
double r83p_det ( int n, double a_lu[], double work4 )
//****************************************************************************80
//
// Purpose:
//
// R83P_DET computes the determinant of a matrix factored by R83P_FA.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored
// as a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 March 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input, double A_LU[3*N], the LU factors from R83P_FA.
//
// Input, double WORK4, factorization information from R83P_FA.
//
// Output, double R83P_DET, the determinant of the matrix.
//
{
double det;
int i;
det = work4;
for ( i = 0; i <= n-2; i++ )
{
det = det * a_lu[1+i*3];
}
return det;
}
//****************************************************************************80
int r83p_fa ( int n, double a[], double work2[], double work3[], double *work4 )
//****************************************************************************80
//
// Purpose:
//
// R83P_FA factors an R83P matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Once the matrix has been factored by R83P_FA, R83P_SL may be called
// to solve linear systems involving the matrix.
//
// The logical matrix has a form which is suggested by this diagram:
//
// D1 U1 L1
// L2 D2 U2
// L3 R83 U3
// L4 D4 U4
// L5 R85 U5
// U6 L6 D6
//
// The algorithm treats the matrix as a border banded matrix:
//
// ( A1 A2 )
// ( A3 A4 )
//
// where:
//
// D1 U1 | L1
// L2 D2 U2 | 0
// L3 R83 U3 | 0
// L4 D4 U4 | 0
// L5 R85 | U5
// ---------------+---
// U6 0 0 0 L6 | D6
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Method:
//
// The algorithm rewrites the system as:
//
// X1 + inverse(A1) A2 X2 = inverse(A1) B1
//
// A3 X1 + A4 X2 = B2
//
// The first equation can be "solved" for X1 in terms of X2:
//
// X1 = - inverse(A1) A2 X2 + inverse(A1) B1
//
// allowing us to rewrite the second equation for X2 explicitly:
//
// ( A4 - A3 inverse(A1) A2 ) X2 = B2 - A3 inverse(A1) B1
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input/output, double A[3*N].
// On input, the periodic tridiagonal matrix.
// On output, the arrays have been modified to hold information
// defining the border-banded factorization of submatrices A1
// and A3.
//
// Output, int R83P_FA, singularity flag.
// 0, no singularity detected.
// nonzero, the factorization failed on the INFO-th step.
//
// Output, double WORK2[N-1], WORK3[N-1], *WORK4, factorization information.
//
{
int i;
int info;
int job;
double *work1;
work1 = new double[n-1];
//
// Compute inverse(A1):
//
info = r83_np_fa ( n-1, a );
if ( info != 0 )
{
cerr << "\n";
cerr << "R83P_FA - Fatal error!\n";
cerr << " R83_NP_FA returned INFO = " << info << "\n";
cerr << " Factoring failed for column INFO.\n";
cerr << " The tridiagonal matrix A1 is singular.\n";
cerr << " This algorithm cannot continue!\n";
exit ( 1 );
}
//
// WORK2 := inverse(A1) * A2.
//
work2[0] = a[2+(n-1)*3];
for ( i = 1; i < n-2; i++)
{
work2[i] = 0.0;
}
work2[n-2] = a[0+(n-1)*3];
job = 0;
work1 = r83_np_sl ( n-1, a, work2, job );
for ( i = 0; i < n-1; i++ )
{
work2[i] = work1[i];
}
//
// WORK3 := inverse ( A1' ) * A3'.
//
work3[0] = a[0+0*3];
for ( i = 1; i < n-2; i++)
{
work3[i] = 0.0;
}
work3[n-2] = a[2+(n-2)*3];
job = 1;
work1 = r83_np_sl ( n-1, a, work3, job );
for ( i = 0; i < n-1; i++ )
{
work3[i] = work1[i];
}
//
// A4 := ( A4 - A3 * inverse(A1) * A2 )
//
*work4 = a[1+(n-1)*3] - a[0+0*3] * work2[0] - a[2+(n-2)*3] * work2[n-2];
if ( *work4 == 0.0 )
{
cerr << "\n";
cerr << "R83P_FA - Fatal error!\n";
cerr << " The factored A4 submatrix is zero.\n";
cerr << " This algorithm cannot continue!\n";
exit ( 1 );
}
delete [] work1;
return 0;
}
//****************************************************************************80
double *r83p_indicator ( int n )
//****************************************************************************80
//
// Purpose:
//
// R83P_INDICATOR sets up an R83P indicator matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored
// as a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Here are the values as stored in an indicator matrix:
//
// 51 12 23 34 45
// 11 22 33 44 55
// 21 32 43 54 15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 2.
//
// Output, double R83P_INDICATOR[3*N], the R83P indicator matrix.
//
{
double *a;
int fac;
int i;
int j;
a = new double[3*n];
fac = i4_power ( 10, i4_log_10 ( n ) + 1 );
i = n;
j = 1;
a[0+(j-1)*3] = ( double ) ( fac * i + j );
for ( j = 2; j <= n; j++ )
{
i = j - 1;
a[0+(j-1)*3] = ( double ) ( fac * i + j );
}
for ( j = 1; j <= n; j++ )
{
i = j;
a[1+(j-1)*3] = ( double ) ( fac * i + j );
}
for ( j = 1; j <= n-1; j++ )
{
i = j + 1;
a[2+(j-1)*3] = ( double ) ( fac * i + j );
}
i = 1;
j = n;
a[2+(j-1)*3] = ( double ) ( fac * i + j );
return a;
}
//****************************************************************************80
double *r83p_ml ( int n, double a_lu[], double x[], int job )
//****************************************************************************80
//
// Purpose:
//
// R83P_ML computes A * x or x * A, where A has been factored by R83P_FA.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored
// as a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input, double A_LU[3*N], the LU factors from R83P_FA.
//
// Input, double X[N], the vector to be multiplied by the matrix.
//
// Input, int JOB, indicates what product should be computed.
// 0, compute A * x.
// nonzero, compute A' * x.
//
// Output, double R83P_ML[N], the result of the multiplication.
//
{
double *b;
double *b_short;
int i;
//
// Multiply A(1:N-1,1:N-1) and X(1:N-1).
//
b_short = r83_np_ml ( n-1, a_lu, x, job );
b = new double[n];
for ( i = 0; i < n-1; i++ )
{
b[i] = b_short[i];
}
b[n-1] = 0.0;
delete [] b_short;
//
// Add terms from the border.
//
if ( job == 0 )
{
b[0] = b[0] + a_lu[2+(n-1)*3] * x[n-1];
b[n-2] = b[n-2] + a_lu[0+(n-1)*3] * x[n-1];
b[n-1] = a_lu[0+0*3] * x[0] + a_lu[2+(n-2)*3] * x[n-2]
+ a_lu[1+(n-1)*3] * x[n-1];
}
else
{
b[0] = b[0] + a_lu[0+0*3] * x[n-1];
b[n-2] = b[n-2] + a_lu[2+(n-2)*3] * x[n-1];
b[n-1] = a_lu[2+(n-1)*3] * x[0] + a_lu[0+(n-1)*3] * x[n-2]
+ a_lu[1+(n-1)*3] * x[n-1];
}
return b;
}
//****************************************************************************80
double *r83p_mtv ( int n, double a[], double x[] )
//****************************************************************************80
//
// Purpose:
//
// R83P_MTV multiplies a vector times an R83P matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input, double A[3*N], the R83P matrix.
//
// Input, double X, the vector to be multiplied by A.
//
// Output, double R83P_MTV[N], the product X * A.
//
{
double *b;
int i;
b = new double[n];
b[0] = a[0+0*3] * x[n-1] + a[1+0*3] * x[0] + a[2+0*3] * x[1];
for ( i = 2; i <= n-1; i++ )
{
b[i-1] = a[0+(i-1)*3] * x[i-2] + a[1+(i-1)*3] * x[i-1] + a[2+(i-1)*3] * x[i];
}
b[n-1] = a[0+(n-1)*3] * x[n-2] + a[1+(n-1)*3] * x[n-1] + a[2+(n-1)*3] * x[0];
return b;
}
//****************************************************************************80
double *r83p_mv ( int n, double a[], double x[] )
//****************************************************************************80
//
// Purpose:
//
// R83P_MV multiplies an R83P matrix times a vector.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input, double A[3*N], the R83P matrix.
//
// Input, double X[N], the vector to be multiplied by A.
//
// Output, double R83P_MV[N], the product A * x.
//
{
double *b;
int i;
b = new double[n];
b[0] = a[2+(n-1)*3] * x[n-1] + a[1+0*3] * x[0] + a[0+1*3] * x[1];
for ( i = 1; i < n-1; i++ )
{
b[i] = a[2+(i-1)*3] * x[i-1] + a[1+i*3] * x[i] + a[0+(i+1)*3] * x[i+1];
}
b[n-1] = a[2+(n-2)*3] * x[n-2] + a[1+(n-1)*3] * x[n-1] + a[0+0*3] * x[0];
return b;
}
//****************************************************************************80
void r83p_print ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R83P_PRINT prints an R83P matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 April 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double A[3*N], the R83P matrix.
//
// Input, string TITLE, a title.
//
{
r83p_print_some ( n, a, 1, 1, n, n, title );
return;
}
//****************************************************************************80
void r83p_print_some ( int n, double a[], int ilo, int jlo, int ihi, int jhi,
string title )
//****************************************************************************80
//
// Purpose:
//
// R83P_PRINT_SOME prints some of an R83P matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 April 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double A[3*N], the R83P matrix.
//
// Input, int ILO, JLO, IHI, JHI, designate the first row and
// column, and the last row and column, to be printed.
//
// Input, string TITLE, a title.
//
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int inc;
int j;
int j2;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
//
// Print the columns of the matrix, in strips of 5.
//
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
j2hi = i4_min ( j2hi, n );
j2hi = i4_min ( j2hi, jhi );
inc = j2hi + 1 - j2lo;
cout << "\n";
cout << " Col: ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(7) << j << " ";
}
cout << "\n";
cout << " Row\n";
cout << " ---\n";
//
// Determine the range of the rows in this strip.
//
i2lo = i4_max ( ilo, 1 );
if ( 1 < i2lo || j2hi < n )
{
i2lo = i4_max ( i2lo, j2lo - 1 );
}
i2hi = i4_min ( ihi, n );
if ( i2hi < n || 1 < j2lo )
{
i2hi = i4_min ( i2hi, j2hi + 1 );
}
for ( i = i2lo; i <= i2hi; i++ )
{
//
// Print out (up to) 5 entries in row I, that lie in the current strip.
//
cout << setw(4) << i << " ";
for ( j2 = 1; j2 <= inc; j2++ )
{
j = j2lo - 1 + j2;
if ( i == n && j == 1 )
{
cout << setw(12) << a[0+(j-1)*3] << " ";
}
else if ( i == 1 && j == n )
{
cout << setw(12) << a[2+(j-1)*3] << " ";
}
else if ( 1 < i-j || 1 < j-i )
{
cout << " ";
}
else if ( j == i+1 )
{
cout << setw(12) << a[0+(j-1)*3] << " ";
}
else if ( j == i )
{
cout << setw(12) << a[1+(j-1)*3] << " ";
}
else if ( j == i-1 )
{
cout << setw(12) << a[2+(j-1)*3] << " ";
}
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
double *r83p_random ( int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R83P_RANDOM randomizes an R83P matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 May 2016
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R83P_RANDOM[3*N], the R83P matrix.
//
{
double *a;
a = r8mat_uniform_01_new ( 3, n, seed );
return a;
}
//****************************************************************************80
double *r83p_sl ( int n, double a_lu[], double b[], int job, double work2[],
double work3[], double work4 )
//****************************************************************************80
//
// Purpose:
//
// R83P_SL solves an R83P system factored by R83P_FA.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input, double A_LU[3*N], the LU factors from R83P_FA.
//
// Input, double B[N], the right hand side of the linear system.
//
// Input, int JOB, specifies the system to solve.
// 0, solve A * x = b.
// nonzero, solve A' * x = b.
//
// Input, double WORK2(N-1), WORK3(N-1), WORK4, factor data from R83P_FA.
//
// Output, double R83P_SL[N], the solution to the linear system.
//
{
int i;
double *x;
double *xnm1;
x = new double[n];
for ( i = 0; i < n; i++ )
{
x[i] = b[i];
}
if ( job == 0 )
{
//
// Solve A1 * X1 = B1.
//
xnm1 = r83_np_sl ( n-1, a_lu, x, job );
//
// X2 = B2 - A3 * X1
//
for ( i = 0; i < n-1; i++ )
{
x[i] = xnm1[i];
}
delete [] xnm1;
x[n-1] = x[n-1] - a_lu[0+0*3] * x[0] - a_lu[2+(n-2)*3] * x[n-2];
//
// Solve A4 * X2 = X2
//
x[n-1] = x[n-1] / work4;
//
// X1 := X1 - inverse ( A1 ) * A2 * X2.
//
for ( i = 0; i < n-1; i++ )
{
x[i] = x[i] - work2[i] * x[n-1];
}
}
else
{
//
// Solve A1' * X1 = B1.
//
xnm1 = r83_np_sl ( n-1, a_lu, x, job );
//
// X2 := X2 - A2' * B1
//
for ( i = 0; i < n-1; i++ )
{
x[i] = xnm1[i];
}
delete [] xnm1;
x[n-1] = x[n-1] - a_lu[2+(n-1)*3] * x[0] - a_lu[0+(n-1)*3] * x[n-2];
//
// Solve A4 * X2 = X2.
//
x[n-1] = x[n-1] / work4;
//
// X1 := X1 - transpose ( inverse ( A1 ) * A3 ) * X2.
//
for ( i = 0; i < n-1; i++ )
{
x[i] = x[i] - work3[i] * x[n-1];
}
}
return x;
}
//****************************************************************************80
double *r83p_to_r8ge ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R83P_TO_R8GE copies an R83P matrix to an R8GE matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Input, double A[3*N], the R83P matrix.
//
// Output, double R83P_TO_R8GE[N*N], the R8GE matrix.
//
{
double *b;
int i;
int j;
b = new double[n*n];
for ( i = 1; i <= n; i++ )
{
for ( j = 1; j <= n; j++ )
{
if ( i == j )
{
b[i-1+(j-1)*n] = a[1+(j-1)*3];
}
else if ( j == i-1 )
{
b[i-1+(j-1)*n] = a[2+(j-1)*3];
}
else if ( j == i+1 )
{
b[i-1+(j-1)*n] = a[0+(j-1)*3];
}
else if ( i == 1 && j == n )
{
b[i-1+(j-1)*n] = a[2+(j-1)*3];
}
else if ( i == n && j == 1 )
{
b[i-1+(j-1)*n] = a[0+(j-1)*3];
}
else
{
b[i-1+(j-1)*n] = 0.0;
}
}
}
return b;
}
//****************************************************************************80
double *r83p_zeros ( int n )
//****************************************************************************80
//
// Purpose:
//
// R83P_ZEROS zeros an R83P matrix.
//
// Discussion:
//
// The R83P storage format stores a periodic tridiagonal matrix is stored as
// a 3 by N array, in which each row corresponds to a diagonal, and
// column locations are preserved. The matrix value
// A(1,N) is stored as the array entry A(1,1), and the matrix value
// A(N,1) is stored as the array entry A(3,N).
//
// Example:
//
// Here is how an R83P matrix of order 5 would be stored:
//
// A51 A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 A15
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be at least 3.
//
// Output, double S3P[3*N], the R83P matrix.
//
{
double *a;
int i;
int j;
a = new double[3*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < 3; i++ )
{
a[i+j*3] = 0.0;
}
}
return a;
}
//****************************************************************************80
double r8ge_det ( int n, double a_lu[], int pivot[] )
//****************************************************************************80
//
// Purpose:
//
// R8GE_DET computes the determinant of a matrix factored by R8GE_FA or R8GE_TRF.
//
// Discussion:
//
// The R8GE storage format is used for a "general" M by N matrix.
// A physical storage space is made for each logical entry. The two
// dimensional logical array is mapped to a vector, in which storage is
// by columns.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 March 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
// LINPACK User's Guide,
// SIAM, 1979,
// ISBN13: 978-0-898711-72-1,
// LC: QA214.L56.
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double A_LU[N*N], the LU factors from R8GE_FA or R8GE_TRF.
//
// Input, int PIVOT[N], as computed by R8GE_FA or R8GE_TRF.
//
// Output, double R8GE_DET, the determinant of the matrix.
//
{
double det;
int i;
det = 1.0;
for ( i = 1; i <= n; i++ )
{
det = det * a_lu[i-1+(i-1)*n];
if ( pivot[i-1] != i )
{
det = -det;
}
}
return det;
}
//****************************************************************************80
int r8ge_fa ( int n, double a[], int pivot[] )
//****************************************************************************80
//
// Purpose:
//
// R8GE_FA performs a LINPACK-style PLU factorization of an R8GE matrix.
//
// Discussion:
//
// The R8GE storage format is used for a "general" M by N matrix.
// A physical storage space is made for each logical entry. The two
// dimensional logical array is mapped to a vector, in which storage is
// by columns.
//
// R8GE_FA is a simplified version of the LINPACK routine SGEFA.
//
// The two dimensional array is stored by columns in a one dimensional
// array.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 September 2003
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
// LINPACK User's Guide,
// SIAM, 1979,
// ISBN13: 978-0-898711-72-1,
// LC: QA214.L56.
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input/output, double A[N*N], the matrix to be factored.
// On output, A contains an upper triangular matrix and the multipliers
// which were used to obtain it. The factorization can be written
// A = L * U, where L is a product of permutation and unit lower
// triangular matrices and U is upper triangular.
//
// Output, int PIVOT[N], a vector of pivot indices.
//
// Output, int R8GE_FA, singularity flag.
// 0, no singularity detected.
// nonzero, the factorization failed on the INFO-th step.
//
{
int i;
int j;
int k;
int l;
double t;
//
for ( k = 1; k <= n-1; k++ )
{
//
// Find L, the index of the pivot row.
//
l = k;
for ( i = k+1; i <= n; i++ )
{
if ( fabs ( a[l-1+(k-1)*n] ) < fabs ( a[i-1+(k-1)*n] ) )
{
l = i;
}
}
pivot[k-1] = l;
//
// If the pivot index is zero, the algorithm has failed.
//
if ( a[l-1+(k-1)*n] == 0.0 )
{
cerr << "\n";
cerr << "R8GE_FA - Fatal error!\n";
cerr << " Zero pivot on step " << k << "\n";
exit ( 1 );
}
//
// Interchange rows L and K if necessary.
//
if ( l != k )
{
t = a[l-1+(k-1)*n];
a[l-1+(k-1)*n] = a[k-1+(k-1)*n];
a[k-1+(k-1)*n] = t;
}
//
// Normalize the values that lie below the pivot entry A(K,K).
//
for ( i = k+1; i <= n; i++ )
{
a[i-1+(k-1)*n] = -a[i-1+(k-1)*n] / a[k-1+(k-1)*n];
}
//
// Row elimination with column indexing.
//
for ( j = k+1; j <= n; j++ )
{
if ( l != k )
{
t = a[l-1+(j-1)*n];
a[l-1+(j-1)*n] = a[k-1+(j-1)*n];
a[k-1+(j-1)*n] = t;
}
for ( i = k+1; i <= n; i++ )
{
a[i-1+(j-1)*n] = a[i-1+(j-1)*n] + a[i-1+(k-1)*n] * a[k-1+(j-1)*n];
}
}
}
pivot[n-1] = n;
if ( a[n-1+(n-1)*n] == 0.0 )
{
cerr << "\n";
cerr << "R8GE_FA - Fatal error!\n";
cerr << " Zero pivot on step " << n << "\n";
exit ( 1 );
}
return 0;
}
//****************************************************************************80
void r8ge_print ( int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8GE_PRINT prints an R8GE matrix.
//
// Discussion:
//
// The R8GE storage format is used for a "general" M by N matrix.
// A physical storage space is made for each logical entry. The two
// dimensional logical array is mapped to a vector, in which storage is
// by columns.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 April 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Input, double A[M*N], the R8GE matrix.
//
// Input, string TITLE, a title.
//
{
r8ge_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
//****************************************************************************80
void r8ge_print_some ( int m, int n, double a[], int ilo, int jlo, int ihi,
int jhi, string title )
//****************************************************************************80
//
// Purpose:
//
// R8GE_PRINT_SOME prints some of an R8GE matrix.
//
// Discussion:
//
// The R8GE storage format is used for a "general" M by N matrix.
// A physical storage space is made for each logical entry. The two
// dimensional logical array is mapped to a vector, in which storage is
// by columns.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 April 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Input, double A[M*N], the R8GE matrix.
//
// Input, int ILO, JLO, IHI, JHI, designate the first row and
// column, and the last row and column to be printed.
//
// Input, string TITLE, a title.
//
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
//
// Print the columns of the matrix, in strips of 5.
//
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
j2hi = i4_min ( j2hi, n );
j2hi = i4_min ( j2hi, jhi );
cout << "\n";
//
// For each column J in the current range...
//
// Write the header.
//
cout << " Col: ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(7) << j << " ";
}
cout << "\n";
cout << " Row\n";
cout << " ---\n";
//
// Determine the range of the rows in this strip.
//
i2lo = i4_max ( ilo, 1 );
i2hi = i4_min ( ihi, m );
for ( i = i2lo; i <= i2hi; i++ )
{
//
// Print out (up to) 5 entries in row I, that lie in the current strip.
//
cout << setw(5) << i << " ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(12) << a[i-1+(j-1)*m] << " ";
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
double *r8mat_uniform_01_new ( int m, int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_01_NEW returns a unit pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8's, stored as a vector
// in column-major order.
//
// This routine implements the recursion
//
// seed = 16807 * seed mod ( 2^31 - 1 )
// unif = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Springer Verlag, pages 201-202, 1983.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, pages 362-376, 1986.
//
// Philip Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, pages 136-143, 1969.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0, otherwise the output value of SEED
// will still be 0, and R8_UNIFORM will be 0. On output, SEED has
// been updated.
//
// Output, double R8MAT_UNIFORM_01_NEW[M*N], a matrix of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
double *r;
r = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = ( double ) ( seed ) * 4.656612875E-10;
}
}
return r;
}
//****************************************************************************80
double *r8vec_indicator1_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDICATOR1_NEW sets an R8VEC to the indicator1 vector {1,2,3...}.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, double R8VEC_INDICATOR1_NEW[N], the array to be initialized.
//
{
double *a;
int i;
a = new double[n];
for ( i = 0; i <= n-1; i++ )
{
a[i] = ( double ) ( i + 1 );
}
return a;
}
//****************************************************************************80
void r8vec_print ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PRINT prints an R8VEC.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 November 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i < n; i++ )
{
cout << setw(6) << i + 1 << " "
<< setw(14) << a[i] << "\n";
}
return;
}
//****************************************************************************80
void r8vec2_print_some ( int n, double x1[], double x2[], int max_print,
string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_PRINT_SOME prints "some" of two real vectors.
//
// Discussion:
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vectors, is no more than MAX_PRINT, then
// the entire vectors are printed, one entry of each per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 November 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vectors.
//
// Input, double X1[N], X2[N], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << setw(6) << i + 1 << " "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print-2; i++ )
{
cout << setw(6) << i + 1 << " "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
cout << "...... .............. ..............\n";
i = n - 1;
cout << setw(6) << i + 1 << " "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << setw(6) << i + 1 << " "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
i = max_print - 1;
cout << setw(6) << i + 1 << " "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "...more entries...\n";
}
return;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct std::tm *tm_ptr;
size_t len;
std::time_t now;
now = std::time ( NULL );
tm_ptr = std::localtime ( &now );
len = std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr );
std::cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
| true |
b5f424146ab50f355f3014b489b8f5e7e85836de | C++ | RKalampattel/ES1D-linux | /ES1D/Particle.h | UTF-8 | 441 | 2.765625 | 3 | [] | no_license | #pragma once
/*!
The Particle class has two member variables representing position and velocity of the
particle set. The second constructor is used to initialise these values.
*/
#include "Parameters.h"
class Particle
{
public:
vector<double> x; //!< Position vector
vector<double> v; //!< Velocity vector
Particle() {}; //!< Default constructor
Particle(Parameters inputs, double v0, double dx0); //!< Second constructor
}; | true |
abd8b97156cb2732f175daa4f706acee85facfa6 | C++ | LinkItONEDevGroup/LASS | /WaterBox/firmware/library/ArduinoJson/test/JsonArray/copyTo.cpp | UTF-8 | 1,302 | 3.140625 | 3 | [
"MIT"
] | permissive | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("JsonArray::copyTo()") {
DynamicJsonBuffer jsonBuffer;
SECTION("BiggerOneDimensionIntegerArray") {
char json[] = "[1,2,3]";
JsonArray& array = jsonBuffer.parseArray(json);
int destination[4] = {0};
size_t result = array.copyTo(destination);
REQUIRE(3 == result);
REQUIRE(1 == destination[0]);
REQUIRE(2 == destination[1]);
REQUIRE(3 == destination[2]);
REQUIRE(0 == destination[3]);
}
SECTION("SmallerOneDimensionIntegerArray") {
char json[] = "[1,2,3]";
JsonArray& array = jsonBuffer.parseArray(json);
int destination[2] = {0};
size_t result = array.copyTo(destination);
REQUIRE(2 == result);
REQUIRE(1 == destination[0]);
REQUIRE(2 == destination[1]);
}
SECTION("TwoOneDimensionIntegerArray") {
char json[] = "[[1,2],[3],[4]]";
JsonArray& array = jsonBuffer.parseArray(json);
int destination[3][2] = {{0}};
array.copyTo(destination);
REQUIRE(1 == destination[0][0]);
REQUIRE(2 == destination[0][1]);
REQUIRE(3 == destination[1][0]);
REQUIRE(0 == destination[1][1]);
REQUIRE(4 == destination[2][0]);
REQUIRE(0 == destination[2][1]);
}
}
| true |
d79026d71418d156cc4362256bf4672c0c3a378f | C++ | Tanavya/Competitive-Programming | /DynamicProgramming/CC_SealingUp.cpp | UTF-8 | 2,128 | 2.703125 | 3 | [] | no_license | //Problem Link: https://www.codechef.com/LTIME44/problems/SEALUP
//Problem type: Dynamic Programming
//learning experience: freaking make sure to keep INF as 1000000000000000000LL, LONG_MAX is too less lmao ugh
//also, try not to keep 2D DP arrays and see if it can be reduced to 1D, otherwise TLE chances increase.
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <stdio.h>
#include <queue>
#include <set>
#include <cmath>
#include <assert.h>
#include <bitset>
#include <map>
#include <unordered_map>
#include <iomanip> //cout << setprecision(n) << fixed << num
#define MAXN 1007
#define mp make_pair
#define ii pair<int, int>
#define PI 3.14159265
#define INF 1000000000000000000LL
#define print(arr) for (auto it = arr.begin(); it != arr.end(); ++it) cout << *it << " "; cout << "\n";
typedef long long int ll;
using namespace std;
inline int calc(pair<ll,ll> a, pair<ll,ll> b) {
return (int) ceil(sqrt( (ll)pow(a.first-b.first,2) + (ll)pow(a.second-b.second,2)));
}
int main() {
int t, n, m;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
vector <pair<ll,ll>> points(n);
for (int i = 0; i < n; i++) {
scanf("%lld %lld", &points[i].first, &points[i].second);
}
vector <int> sides;
for (int i = 0; i < n-1; i++) {
sides.push_back(calc(points[i], points[i+1]));
}
sides.push_back(calc(points[n-1], points[0]));
scanf("%d", &m);
int length[m];
ll cost[m];
for (int i = 0; i < m; i++) {
scanf("%d %lld", &length[i], &cost[i]);
}
ll MAX = 2.5e6+10;
vector <ll> dp(MAX, INF);
dp[0] = 0;
for (int i = 0; i < m; i++) {
for (int d = length[i]; d < MAX; d++) {
dp[d] = min(dp[d], dp[d - length[i]] + cost[i]);
}
}
for (int i = MAX-2; i >= 0; i--) {
dp[i] = min(dp[i], dp[i+1]);
}
ll ans = 0;
for (int i = 0; i < n; i++) {
ans += dp[sides[i]];
}
cout << ans << endl;
}
} | true |
a365df146ee0e9f5a71194290a4d6276bcdc4424 | C++ | sergij525bog/test | /src/Arithmetic.cpp | UTF-8 | 296 | 2.96875 | 3 | [] | no_license | #include "Arithmetic.hpp"
#include <iostream>
#include <string>
double addNum (double x, double y)
{
std::cout << "Sum of numbers..." << std::endl;
return x + y;
}
double differenceNum (double x, double y)
{
std::cout << "Difference of numbers..." << std::endl;
return x - y;
}
| true |
7d3ffb6f989d7dcd57c5c3a222e74837a822db54 | C++ | felipecaon/RPN-Calculator-QT | /no.cpp | UTF-8 | 432 | 3.046875 | 3 | [] | no_license | #include "no.h"
No::No(No *prox, No *prev, int numero)
{
this->prev = prev;
this->prox = prox;
this->numero = numero;
}
No *No::getProx() const
{
return prox;
}
void No::setProx(No *value)
{
prox = value;
}
No *No::getPrev() const
{
return prev;
}
void No::setPrev(No *value)
{
prev = value;
}
int No::getNumero() const
{
return numero;
}
void No::setNumero(int value)
{
numero = value;
}
| true |
37be863fd4b6d4977e38b55215684511a423c683 | C++ | acisoru/ctfcup-2020-quals | /path/solution/crypto_solver.cpp | UTF-8 | 3,785 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include "crypto_solver.h"
using namespace std;
void crypto::func1(word32* dataBlock) {
word32 tempWord[3];
tempWord[0] = tempWord[1] = tempWord[2] = 0;
for (int i = 0; i < 32; i++) {
tempWord[0] <<= 1;
tempWord[1] <<= 1;
tempWord[2] <<= 1;
tempWord[0] |= dataBlock[2] & 1;
tempWord[1] |= dataBlock[1] & 1;
tempWord[2] |= dataBlock[0] & 1;
dataBlock[0] >>= 1;
dataBlock[1] >>= 1;
dataBlock[2] >>= 1;
}
dataBlock[0] = tempWord[0];
dataBlock[1] = tempWord[1];
dataBlock[2] = tempWord[2];
}
void crypto::func2(word32* dataBlock) {
word32 tempWord[3];
tempWord[0] = (~dataBlock[0]) ^ (~dataBlock[1]) & dataBlock[2];
tempWord[1] = (~dataBlock[1]) ^ (~dataBlock[2]) & dataBlock[0];
tempWord[2] = (~dataBlock[2]) ^ (~dataBlock[0]) & dataBlock[1];
dataBlock[0] = tempWord[0];
dataBlock[1] = tempWord[1];
dataBlock[2] = tempWord[2];
}
void crypto::func3(word32* dataBlock) {
word32 tempWord[3];
tempWord[0] = dataBlock[0] ^ (dataBlock[0] >> 16)
^ (dataBlock[1] << 16) ^ (dataBlock[1] >> 16)
^ (dataBlock[2] << 16) ^ (dataBlock[1] >> 24)
^ (dataBlock[2] << 8) ^ (dataBlock[2] >> 8)
^ (dataBlock[0] << 24) ^ (dataBlock[2] >> 16)
^ (dataBlock[0] << 16) ^ (dataBlock[2] >> 24)
^ (dataBlock[0] << 8);
tempWord[1] = dataBlock[1] ^ (dataBlock[1] >> 16)
^ (dataBlock[2] << 16) ^ (dataBlock[2] >> 16)
^ (dataBlock[0] << 16) ^ (dataBlock[2] >> 24)
^ (dataBlock[0] << 8) ^ (dataBlock[0] >> 8)
^ (dataBlock[1] << 24) ^ (dataBlock[0] >> 16)
^ (dataBlock[1] << 16) ^ (dataBlock[0] >> 24)
^ (dataBlock[1] << 8);
tempWord[2] = dataBlock[2] ^ (dataBlock[2] >> 16)
^ (dataBlock[0] << 16) ^ (dataBlock[0] >> 16)
^ (dataBlock[1] << 16) ^ (dataBlock[0] >> 24)
^ (dataBlock[1] << 8) ^ (dataBlock[1] >> 8)
^ (dataBlock[2] << 24) ^ (dataBlock[1] >> 16)
^ (dataBlock[2] << 16) ^ (dataBlock[1] >> 24)
^ (dataBlock[2] << 8);
dataBlock[0] = tempWord[0];
dataBlock[1] = tempWord[1];
dataBlock[2] = tempWord[2];
}
void crypto::func4(word32* dataBlock) {
dataBlock[0] = (dataBlock[0] >> 10) ^ (dataBlock[0] << 22);
dataBlock[2] = (dataBlock[2] << 1) ^ (dataBlock[2] >> 31);
}
void crypto::func5(word32* dataBlock) {
dataBlock[0] = (dataBlock[0] << 1) ^ (dataBlock[0] >> 31);
dataBlock[2] = (dataBlock[2] >> 10) ^ (dataBlock[2] << 22);
}
void crypto::func6(word32* dataBlock) {
func3(dataBlock);
func4(dataBlock);
func2(dataBlock);
func5(dataBlock);
}
crypto::crypto(word32 key[]) {
this->key[0] = key[0];
this->key[1] = key[1];
this->key[2] = key[2];
}
void crypto::func7(word32 text[]) {
for(int i = 0; i < 11; i++) {
text[0] ^= key[0];
text[1] ^= key[1];
text[2] ^= key[2];
func6(text);
}
text[0] ^= key[0];
text[1] ^= key[1];
text[2] ^= key[2];
func3(text);
}
void crypto::decryptBlock(word32 text[]) {
word32 inverseKey[3];
inverseKey[0] = this->key[0];
inverseKey[1] = this->key[1];
inverseKey[2] = this->key[2];
func3(inverseKey);
func1(inverseKey);
func1(text);
for(int i = 0; i < 11; i++) {
text[0] ^= inverseKey[0];
text[1] ^= inverseKey[1];
text[2] ^= inverseKey[2];
func6(text);
}
text[0] ^= inverseKey[0];
text[1] ^= inverseKey[1];
text[2] ^= inverseKey[2];
func3(text);
func1(text);
}
void crypto::encrypt(word32 *text, int size) {
for (int i = 0; i < size/3; i++){
word32 d[3];
d[0] = text[i * 3];
d[1] = text[i * 3 + 1];
d[2] = text[i * 3 + 2];
func7(d);
text[i * 3] = d[0];
text[i * 3 + 1] = d[1];
text[i * 3 + 2] = d[2];
}
}
void crypto::decrypt(word32 *text, int size) {
for (int i = 0; i < size / 3; i++) {
word32 d[3];
d[0] = text[i * 3];
d[1] = text[i * 3 + 1];
d[2] = text[i * 3 + 2];
decryptBlock(d);
text[i * 3] = d[0];
text[i * 3 + 1] = d[1];
text[i * 3 + 2] = d[2];
}
}
| true |
cb53928914667942547f6c445e1007d18cf7153b | C++ | langsound/Digital-Electronics | /1154.digital/ADC-lab/ADC_Smoothed_DAC/ADC_Smoothed_DAC.ino | UTF-8 | 856 | 3.046875 | 3 | [] | no_license | /*
analog read to analog write with mapping and smoothing
connect a switch or button to analog input pin 2 for most easily observable results
*/
//set pwm Min/Max here, as needed
int pwmMin = 0;
int pwmMax = 255;
// change pwmSmooth here
float pwmSmooth = 0.5;
float pwmOut;
int pwmPin = 3;
int onOffPin = 4;
void setup(){
pinMode(pwmPin, OUTPUT);
pinMode(onOffPin, OUTPUT);
}//endsetup
void loop(){
//read analog pin TWO, map to min and max range smooth and, write to pwmPin
pwmOut = map(analogRead(2), 0, 1024, pwmMin, pwmMax) * (1-pwmSmooth) + pwmOut * pwmSmooth;
//write output smoothed
analogWrite(pwmPin, pwmOut );
// write output not smoothed
analogWrite(onOffPin, map(analogRead(2), 0, 1024, pwmMin, pwmMax));
delay(33); // change the delay so that smoothing can be more easily observed.
}//endloop
| true |
6ad79c65901a1c9a8278249dbbab8f82cb478103 | C++ | AadityaJ/CP | /codechef/aug17/5.cpp | UTF-8 | 889 | 2.875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
void f(string str,set<string> &s){
set<string> :: iterator it;
it=s.find(str);
if(it!=s.end()) return ;
s.insert(str);
//cout<<str<<" ";
for(int i=0;i<str.length()-1;i++){
if(str[i]>'0' && str[i+1]>'0'){
str[i]=((str[i]-'0')-1)+'0';
str[i+1]=((str[i+1]-'0')-1)+'0';
if(i+2!=str.length()){
str[i+2]=((str[i+2]-'0')+1)+'0';
f(str,s);
str[i]=((str[i]-'0')+1)+'0';
str[i+1]=((str[i+1]-'0')+1)+'0';
str[i+2]=((str[i+2]-'0')-1)+'0';
}else{
str.push_back('1');
f(str,s);
}
}
}
}
int main(int argc, char const *argv[]) {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int x;
string str="";
for(int i=0;i<n;i++){
cin>>x;
str.push_back(x+'0');
}
set<string> s;
f(str,s);
cout<<s.size()<<endl;
}
return 0;
}
| true |
2160c862dcbfe3a7cbff44c9d9b6659737e0919b | C++ | lzhaozi/oj | /oj51t.cpp | UTF-8 | 728 | 3.375 | 3 | [] | no_license | #include <stdio.h>
int primeNumber[10000];
int primeSize;
bool isPrime[10001];// true stands for not prime, false stands for prime
void init(){
primeSize=0;
for(int i=0;i<10001;i++)
isPrime[i]=false;
for(int i=2;i<10001;i++){
if(isPrime[i]==true) continue;
primeNumber[primeSize++]=i;
for(int j=i*i;j<10001;j+=i){
isPrime[j]=true;
}
}
}
int main(){
init();
int n;
while(scanf("%d",&n)!=EOF){
bool isOutput=false;
for(int i=0;primeNumber[i]<n;i++){
if(primeNumber[i]%10==1){
if(isOutput==false){
isOutput=true;
printf("%d",primeNumber[i]);
}else{
printf(" %d",primeNumber[i]);
}
}
}
if(isOutput==false)
printf("-1\n");
else
printf("\n");
}
return 0;
}
| true |
417c46573ccbe51be9e34046346116c383d67e14 | C++ | Intissar-Addali/diskpp | /core/bases/bases_new.hpp | UTF-8 | 3,100 | 2.734375 | 3 | [] | no_license | /*
* /\ Matteo Cicuttin (C) 2016, 2017
* /__\ matteo.cicuttin@enpc.fr
* /_\/_\ École Nationale des Ponts et Chaussées - CERMICS
* /\ /\
* /__\ /__\ DISK++, a template library for DIscontinuous SKeletal
* /_\/_\/_\/_\ methods.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* If you use this code or parts of it for scientific publications, you
* are required to cite it as following:
*
* Implementation of Discontinuous Skeletal methods on arbitrary-dimensional,
* polytopal meshes using generic programming.
* M. Cicuttin, D. A. Di Pietro, A. Ern.
* Journal of Computational and Applied Mathematics.
* DOI: 10.1016/j.cam.2017.09.017
*/
template<typename Mesh, typename T>
class abstract_basis
{
public:
abstract_basis()
{}
};
template<typename Basis>
class gradient_op
{
const Basis& m_target_basis;
public:
typedef typename Basis::gradient_type gradient_type;
gradient_op(const Basis& basis)
m_target_basis(basis)
{}
gradient_type operator()(const point_type& pt)
{
return m_target_basis->evaluate_gradients(pt);
}
};
template<typename Basis>
auto grad(const Basis& basis)
{
return gradient_op<Basis>(basis);
}
template<typename Mesh, typename T>
class scaled_monomial_scalar_basis
{
public:
typedef Mesh mesh_type;
typedef mesh_type::point_type point_type;
typedef T value_type;
typedef T function_type;
scaled_monomial_scalar_basis()
{}
function_type operator()(const point_type& pt)
{
return evaluate_functions(pt);
}
};
template<typename Basis>
class scaled_monomial_scalar_basis_view
{
};
template<typename Mesh, typename T>
class hho_global_space
{
public:
hho_global_space() {}
hho_global_space(size_t degree) {}
hho_global_space(size_t cell_degree, size_t face_degree) {}
get_local_space(T) {}
};
template<typename Mesh, typename T>
class hho_basis
{
typedef T value_type;
typedef Mesh mesh_type;
typedef typename mesh_type::cell_type cell_type;
typedef typename mesh_type::face_type face_type;
typedef scaled_monomial_scalar_basis<mesh_type, cell_type> cell_basis_type;
typedef scaled_monomial_scalar_basis<mesh_type, face_type> face_basis_type;
mesh_type m_msh;
cell_type m_cl;
public:
hho_basis(const mesh_type& msh, const cell_type& cl)
: m_msh(msh), m_cl(cl)
{}
hho_basis(const mesh_type& msh, const cell_type& cl, size_t degree)
: m_msh(msh), m_cl(cl)
{}
hho_basis(const mesh_type& msh, const cell_type& cl, const std::vector<size_t>& degrees)
: m_msh(msh), m_cl(cl)
{}
cell_basis_type T() const
{
return cell_basis;
}
face_basis_type F(size_t which) const
{
return face_basis;
}
};
| true |
b37a9cf20bc3117ef288442b0446b995ef459e45 | C++ | Skunkynator/SkunkyRayMarchEngine | /Source/shader.cpp | UTF-8 | 4,534 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "shader.h"
#include <glad/glad.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <glm/gtc/type_ptr.hpp>
#include <filesystem>
#include <unistd.h>
bool checkShader(int shader);
void checkProgram(int program);
std::stringstream PreProcessShader(std::stringstream& shaderCode);
std::string readShader(const char* filePath);
Shader::Shader(const char* vertexPath, const char* fragmentPath)
{
std::string vCode = readShader(vertexPath);
const char* vShaderCode = vCode.c_str();
std::string fCode = readShader(fragmentPath);
const char* fShaderCode = fCode.c_str();
//Compile Shaders
unsigned int vertex, fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex,1,&vShaderCode,NULL);
glCompileShader(vertex);
if(!checkShader(vertex))
std::cout << vCode << std::endl;
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment,1,&fShaderCode,NULL);
glCompileShader(fragment);
if(!checkShader(fragment))
std::cout << fCode << std::endl;
//Shader Program
ID = glCreateProgram();
glAttachShader(ID,vertex);
glAttachShader(ID,fragment);
glLinkProgram(ID);
checkProgram(ID);
glDeleteShader(vertex);
glDeleteShader(fragment);
}
void Shader::use()
{
glUseProgram(ID);
}
void Shader::setBool(const std::string &name, bool value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()),(int)value);
}
void Shader::setFloat(const std::string &name, float value) const
{
glUniform1f(glGetUniformLocation(ID, name.c_str()),value);
}
void Shader::setInt(const std::string &name, int value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()),value);
}
void Shader::setMatrix4fv(const std::string &name, float* value) const
{
glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()),1,GL_FALSE,value);
}
void Shader::setVec3(const std::string& name, float xVal, float yVal, float zVal) const
{
glUniform3f(uniformLocation(name),xVal,yVal,zVal);
}
void Shader::setVec3(const std::string& name, glm::vec3 value) const
{
setVec3(name,glm::value_ptr(value));
}
void Shader::setVec3(const std::string& name, float* value) const
{
glUniform3fv(uniformLocation(name),1,value);
}
void Shader::setFloatArr(const std::string& name, float* value, float size) const
{
glUniform1fv(uniformLocation(name),size,value);
}
int Shader::uniformLocation(const std::string& name) const
{
return glGetUniformLocation(ID, name.c_str());
}
bool checkShader(int shader)
{
int success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if(!success)
{
char infoLog[512];
glGetShaderInfoLog(shader,512,NULL,infoLog);
std::cout << "ERROR SHADER COMPILATEION FAILED\n" << infoLog << std::endl;
}
return success;
}
void checkProgram(int program)
{
int success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if(!success)
{
char infoLog[512];
glGetProgramInfoLog(program,512,NULL,infoLog);
std::cout << "ERROR Program LINKING FAILED\n" << infoLog << std::endl;
}
}
std::string readShader(const char* filePath)
{
std::string shaderCode;
std::ifstream shaderFile;
shaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
std::cout << filePath << std::endl;
try
{
shaderFile.open(filePath);
std::stringstream shaderStream;
// read file content into streams
shaderStream << shaderFile.rdbuf();
shaderFile.close();
// PreProcessIncludes
shaderStream = PreProcessShader(shaderStream);
// convert into string
shaderCode = shaderStream.str();
}
catch(std::ifstream::failure e)
{
std::cout << "ERROR SHADER FILE NOT SUCCESFULLY READ" << std::endl << e.what() << std::endl;
}
return shaderCode;
}
std::stringstream PreProcessShader(std::stringstream& shaderCode)
{
std::stringstream out;
std::string line;
std::string pragma("#pragma include");
while (std::getline(shaderCode, line))
{
if (size_t pos = line.find(pragma) != std::string::npos)
{
std::string include = line.substr(pos+pragma.size()+1, pos+line.size() - pragma.size()-4);
std::cout << include << std::endl;
out << readShader(("../Shaders/"+include).c_str()) << std::endl;
}
else
out << line <<std:: endl;
}
return out;
}
| true |
117fc240bff24094e494fc4d3345bec031942995 | C++ | youarefree123/DataStructure-Algorithm | /牛客网/DFS/16695数的划分.cpp | UTF-8 | 576 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int key[7];
int n,k;
int remaining; //剩余量
int ans = 0;
void dfs(int index , int re){ //考虑第index位,剩余量为re
if(index > k && re != 0)
return;
if(index > k && re == 0){ //已经考虑到第n位并且剩余量为0
ans++;
return;
}
for(int i = key[index-1] ; i <= re; i++){ //以字典序排列
re -= i;
key[index] = i;
dfs(index+1,re);
re += i;
}
}
int main(int argc, char const *argv[])
{
key[0] = 1; //特化
cin>>n>>k;
remaining = n;
dfs(1,remaining);
cout<<ans<<endl;
return 0;
}
| true |
bba288259fd7d5a17ce8df4dc3a07f2067cad6d3 | C++ | gauravahlawat81/Codeforces | /StringTask.cpp | UTF-8 | 393 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
string st,answer="";
cin>>st;
transform(st.begin(),st.end(),st.begin(),::tolower);
//cout<<st<<"\n";
for(int i=0;i<st.length();)
{
if(st[i]=='a' or st[i]=='e' or st[i]=='i' or st[i]=='o' or st[i]=='u' or st[i]=='y')
{
i++;
}
else
{
answer+=".";
answer+=st[i];
i++;
}
}
cout<<answer<<"\n";
return 0;
} | true |
01ea3569a0d66d34226013aeb7e92266e50005e6 | C++ | BekzhanKassenov/olymp | /acmp.ru/201...300/296/296.cpp | UTF-8 | 259 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int n;
cin>>n;
int b=n/5;
int a=n%5;
while (a%3!=0)
{
b-=1;
a+=5;
}
cout<<b<<" "<<a/3;
return 0;
}
| true |
1c8c35b3b6bafb745e00e091227f97ce2be999fe | C++ | c437yuyang/ProgramerCodeInterviewInstruction | /08_01_PrintMatrixSpiralOrder/PrintMatrixSpiralOrder.cpp | GB18030 | 1,308 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
//ָ˳ΧһȦmatrix
void printEdge(int mat[], int m, int n, int lt_x, int lt_y, int rb_x, int rb_y)
{
int x, y;
x = lt_x;
//Ƶİ汾ǵֻһкֻһеʵô
while (x < rb_x)//ȴ
{
cout << mat[lt_y*n + x] << " ";
++x;
}
y = lt_y;
while (y < rb_y)//ϵ
{
cout << mat[y*n + rb_x] << " ";
++y;
}
//ҵ
x = rb_x;
while (x > lt_x)
{
cout << mat[rb_y*n + x] << " ";
--x;
}
//µ
y = rb_y;
while (y > lt_y)
{
cout << mat[y*n + lt_x] << " ";
--y;
}
}
void spiralOrderPrint(int mat[], int m, int n)
{
int lt_x = 0, lt_y = 0; //Ͻ
int rb_x = n - 1, rb_y = m - 1; //½
while (lt_y <= rb_y && lt_x <= rb_y)
{
printEdge(mat, m, n, lt_x++, lt_y++, rb_x--, rb_y--);
}
}
int main()
{
//int matrix[] = { 1, 2, 3, 4 ,
// 5, 6, 7, 8 ,
// 9, 10, 11, 12 ,
// 13, 14, 15, 16 };
//int matrix[] = { 1, 2, 3, 4 ,
// 5, 6, 7, 8 ,
// 9, 10, 11, 12 };
int matrix[] = { 1, 2, 3 ,
5, 6, 7 ,
9, 10, 11 ,
13, 14, 15};
//spiralOrderPrint(matrix, 4, 4);
//spiralOrderPrint(matrix, 3, 4);
spiralOrderPrint(matrix, 4, 3);
system("pause");
return 0;
}
| true |
15de4f8561469031a58b0c3ef58878db5025b5c1 | C++ | flavorfree/p | /排序/20.8.28/选择.cpp | UTF-8 | 850 | 3.3125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
//void ChooseSort(int* a, int n)
//{
//
// for (int i = 0; i < n; i++)
// {
// int min = i;
// for (int j = i; j < n; j++)
// {
// if (a[min] > a[j])
// min = j;
// }
// swap(a[i], a[min]);
// }
//
//}
void ChooseSort(int* a, int n)
{
int begin = 0, end = n - 1;
while (begin < end)
{
int min = begin, max = end;
for (int i = begin; i <= end; i++)
{
if (a[i] > a[max])
max = i;
if (a[i] < a[min])
min = i;
}
swap(a[begin], a[min]);
if (a[max] > a[min])
swap(a[max], a[end]);
begin++;
end--;
}
}
int main3()
{
int a[] = { 4, 5, 2, 7, 9, 1, 0, 6, 8, 3 };
ChooseSort(a, sizeof(a) / sizeof(a[0]));
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
} | true |
a5d154a35d0a95a38448333e0456cd34482a3d7e | C++ | MahboobeSh/AP-HW4 | /Q3/cube.h | UTF-8 | 439 | 2.953125 | 3 | [] | no_license | #include"ThreeDimensionalShape.h"
class Cube : public ThreeDimensionalShape
{
public:
Cube(double, double x = 0, double y = 0, double z = 0); //constructor
Cube(const Cube&);//copy constructor
virtual double volume() const{ return side * side * side; };
virtual double area() const{ return 6 * side * side; };
virtual void print() const;//virtual function for print
Cube operator+(point&);
private:
double side;
};
| true |
11d1ee570edfe842922e71cdf4a7b9118736c534 | C++ | kakothke/DX11 | /src/SpriteRenderer.cpp | SHIFT_JIS | 7,742 | 2.578125 | 3 | [] | no_license | #include "SpriteRenderer.h"
//-------------------------------------------------------------------------------------------------
#include "TextureLoader.h"
#include "Math.h"
//-------------------------------------------------------------------------------------------------
namespace KDXK {
//-------------------------------------------------------------------------------------------------
/// VOgNX
const static auto D3D11 = Direct3D11::getInst();
const static auto TEXTURE_LOADER = TextureLoader::getInst();
const static auto SHADER_LOADER = ShaderLoader::getInst();
//-------------------------------------------------------------------------------------------------
/// RXgN^
SpriteRenderer::SpriteRenderer()
: mVertexBuffer(nullptr)
, mTextureName(nullptr)
, mTextureSize(1)
, mShaderData()
, mColor()
, mPivot()
, mAnchor()
, mSplit(1.0f, 1.0f)
, mUVPos()
{
}
//-------------------------------------------------------------------------------------------------
/// fXgN^
SpriteRenderer::~SpriteRenderer()
{
if (mVertexBuffer) {
mVertexBuffer->Release();
mVertexBuffer = nullptr;
}
}
//-------------------------------------------------------------------------------------------------
/// `
/// @param aTransform gXtH[
void SpriteRenderer::render(Transform aTransform, const bool& a3DModeFlag)
{
// ǂݍ݃`FbN
if (!mTextureName || !mShaderData || !mVertexBuffer) {
return;
}
// TCYeNX`[̃TCYɍ킹
aTransform.scale.x *= mTextureSize.x;
aTransform.scale.y *= mTextureSize.y;
if (a3DModeFlag) {
aTransform.scale /= 100.0f;
}
// v~eBǔ`w
D3D11->getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
// VF[_[̎w
D3D11->setShader(mShaderData);
UINT strides = sizeof(VertexData);
UINT offsets = 0;
// IAɐݒ肷钸_obt@̎w
D3D11->getContext()->IASetVertexBuffers(0, 1, &mVertexBuffer, &strides, &offsets);
// RX^gobt@XV
D3D11->getConstantBuffer()->updateColor(mColor, mColor);
D3D11->getConstantBuffer()->setSpriteSplit(mSplit);
D3D11->getConstantBuffer()->setSpriteUVpos(mUVPos);
if (a3DModeFlag) {
D3D11->getConstantBuffer()->setMatrixW(aTransform);
D3D11->getConstantBuffer()->updateMatrix();
} else {
D3D11->getConstantBuffer()->setSpriteMatrixW(aTransform, mPivot);
D3D11->getConstantBuffer()->setSpriteMatrixP(mAnchor);
D3D11->getConstantBuffer()->updateSprite();
}
// eNX`[Zbg
D3D11->setTexture(TEXTURE_LOADER->getTexture(mTextureName));
// `
D3D11->getContext()->Draw(8, 0);
}
//-------------------------------------------------------------------------------------------------
/// eNX`[ݒ肷
/// @param aFileName t@CpX
void SpriteRenderer::setTexture(const LPCSTR aFileName)
{
mTextureName = aFileName;
mTextureSize = TEXTURE_LOADER->getTextureSize(aFileName);
// eNX`[擾G[
if (mTextureSize == Vector2(0)) {
mTextureName = nullptr;
mTextureSize = Vector2(1);
return;
}
// _obt@܂쐬ĂȂꍇ쐬
if (!mVertexBuffer) {
createVertexBuffer();
}
}
//-------------------------------------------------------------------------------------------------
/// VF[_[ݒ肷
/// @param aFileName t@CpX
void SpriteRenderer::setShader(const LPCSTR aFileName)
{
mShaderData = SHADER_LOADER->getShaderData(aFileName);
}
//-------------------------------------------------------------------------------------------------
/// J[ݒ肷
/// @param aColor J[
void SpriteRenderer::setColor(const Color& aColor)
{
mColor = aColor;
}
//-------------------------------------------------------------------------------------------------
/// `挴_ݒ肷
/// @param aX _x(-1~1)
/// @param aY _y(-1~1)
void SpriteRenderer::setPivot(float aX, float aY)
{
aX = Math::Clamp(aX, -1.0f, 1.0f);
aY = Math::Clamp(aY, -1.0f, 1.0f);
mPivot.x = (mTextureSize.x / 2) * -aX;
mPivot.y = (mTextureSize.y / 2) * aY;
}
//-------------------------------------------------------------------------------------------------
/// `Jnʒuݒ肷
/// @param aX `Jnʒux(-1~1)
/// @param aY `Jnʒuy(-1~1)
void SpriteRenderer::setAnchor(float aX, float aY)
{
aX = Math::Clamp(aX, -1.0f, 1.0f);
aY = Math::Clamp(aY, -1.0f, 1.0f);
mAnchor.x = aX;
mAnchor.y = aY;
}
//-------------------------------------------------------------------------------------------------
/// UVݒ肷
/// @param aX x
/// @param aY y
void SpriteRenderer::setSplit(const UINT& aX, const UINT& aY)
{
mSplit.x = (float)aX;
mSplit.y = (float)aY;
mTextureSize.x /= aX;
mTextureSize.y /= aY;
}
//-------------------------------------------------------------------------------------------------
/// UVʒuݒ肷
void SpriteRenderer::setUVPos(const UINT& aX, const UINT& aY)
{
mUVPos.x = (float)aX;
mUVPos.y = (float)aY;
}
//-------------------------------------------------------------------------------------------------
/// _obt@쐬
/// @return (true)
bool SpriteRenderer::createVertexBuffer()
{
// _쐬
VertexData vertexes[8] = {};
Vector2 size = 0.5f;
// _0
vertexes[0].pos[0] = -size.x;
vertexes[0].pos[1] = -size.y;
vertexes[0].uv[0] = 0.0f;
vertexes[0].uv[1] = 1.0f;
vertexes[0].nor[2] = -1.0f;
// _1
vertexes[1].pos[0] = size.x;
vertexes[1].pos[1] = -size.y;
vertexes[1].uv[0] = 1.0f;
vertexes[1].uv[1] = 1.0f;
vertexes[1].nor[2] = -1.0f;
// _2
vertexes[2].pos[0] = -size.x;
vertexes[2].pos[1] = size.y;
vertexes[2].uv[0] = 0.0f;
vertexes[2].uv[1] = 0.0f;
vertexes[2].nor[2] = -1.0f;
// _3
vertexes[3].pos[0] = size.x;
vertexes[3].pos[1] = size.y;
vertexes[3].uv[0] = 1.0f;
vertexes[3].uv[1] = 0.0f;
vertexes[3].nor[2] = -1.0f;
// _4
vertexes[4].pos[0] = -size.x;
vertexes[4].pos[1] = -size.y;
vertexes[4].uv[0] = 0.0f;
vertexes[4].uv[1] = 1.0f;
vertexes[4].nor[2] = 1.0f;
// _5
vertexes[5].pos[0] = size.x;
vertexes[5].pos[1] = -size.y;
vertexes[5].uv[0] = 1.0f;
vertexes[5].uv[1] = 1.0f;
vertexes[5].nor[2] = 1.0f;
// _6
vertexes[6].pos[0] = -size.x;
vertexes[6].pos[1] = size.y;
vertexes[6].uv[0] = 0.0f;
vertexes[6].uv[1] = 0.0f;
vertexes[6].nor[2] = 1.0f;
// _7
vertexes[7].pos[0] = size.x;
vertexes[7].pos[1] = size.y;
vertexes[7].uv[0] = 1.0f;
vertexes[7].uv[1] = 0.0f;
vertexes[7].nor[2] = 1.0f;
D3D11_BUFFER_DESC bufferDesc;
{
// obt@̃TCY
bufferDesc.ByteWidth = sizeof(VertexData) * 8;
// gp@
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
// BINDݒ
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
// \[XւCPŨANZXɂĂ̐ݒ
bufferDesc.CPUAccessFlags = 0;
// \[XIvṼtO
bufferDesc.MiscFlags = 0;
// \̂̃TCY
bufferDesc.StructureByteStride = 0;
}
// \[X
D3D11_SUBRESOURCE_DATA subResource;
{
// obt@̒g̐ݒ
subResource.pSysMem = &vertexes[0];
// texturef[^gpۂɎgp郁o
subResource.SysMemPitch = 0;
// texturef[^gpۂɎgp郁o
subResource.SysMemSlicePitch = 0;
}
// obt@쐬
HRESULT hr;
hr = D3D11->getDevice()->CreateBuffer(&bufferDesc, &subResource, &mVertexBuffer);
if (FAILED(hr)) {
return false;
}
return true;
}
} // namespace
// EOF
| true |
e381ce2216dccea3115e4ac895379dee6e92049a | C++ | xehoth/OnlineJudgeCodes | /BZOJ/BZOJ3711-Druzyny-线段树.cpp | UTF-8 | 6,442 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /**
* Copyright (c) 2017-2018, xehoth
* All rights reserved.
* 「BZOJ 3711」Druzyny 15-01-2018
* 线段树
* @author xehoth
*/
#include <bits/stdc++.h>
namespace {
inline char read() {
static const int IN_LEN = 1 << 18 | 1;
static char buf[IN_LEN], *s, *t;
return (s == t) && (t = (s = buf) + fread(buf, 1, IN_LEN, stdin)),
s == t ? -1 : *s++;
}
struct InputStream {
template <typename T>
inline InputStream &operator>>(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) return *this;
iosig |= c == '-';
}
for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0');
iosig && (x = -x);
return *this;
}
} io;
const int MAXN = 1000000 + 9;
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
int n, c[MAXN], d[MAXN], g[MAXN];
inline int add(const int x, const int v) {
return x + v >= MOD ? x + v - MOD : x + v;
}
struct Info {
int max, cnt;
Info() {}
Info(const int max, const int cnt) : max(max), cnt(cnt) {}
inline Info operator+(const Info &p) const {
return max < p.max ? p
: (max > p.max ? *this : Info(max, add(cnt, p.cnt)));
}
inline Info operator+(const int x) const { return Info(max + x, cnt); }
inline void operator+=(const Info &p) { *this = *this + p; }
} f[MAXN];
struct Node {
int maxPosC;
int minValD;
Info f, tag;
} pool[2097153];
inline void build(int p, int l, int r) {
if (l == r) {
p[pool].maxPosC = l;
p[pool].minValD = d[l];
return;
}
register int mid = (l + r) >> 1;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
p[pool].maxPosC = c[pool[p << 1].maxPosC] > c[pool[p << 1 | 1].maxPosC]
? pool[p << 1].maxPosC
: pool[p << 1 | 1].maxPosC;
p[pool].minValD = std::min(pool[p << 1].minValD, pool[p << 1 | 1].minValD);
}
inline void buildUpdate(int p, int l, int r) {
p[pool].tag.max = -INF;
p[pool].tag.cnt = 0;
if (l == r) {
p[pool].minValD = d[l];
p[pool].f = f[l];
return;
}
register int mid = (l + r) >> 1;
buildUpdate(p << 1, l, mid);
buildUpdate(p << 1 | 1, mid + 1, r);
p[pool].f = pool[p << 1].f + pool[p << 1 | 1].f;
p[pool].minValD = std::min(pool[p << 1].minValD, pool[p << 1 | 1].minValD);
}
inline void modifyAdd(int p, int l, int r, int s, int t, const Info &v) {
if (s <= l && t >= r) {
p[pool].tag += v;
return;
}
register int mid = (l + r) >> 1;
if (s <= mid) modifyAdd(p << 1, l, mid, s, t, v);
if (t > mid) modifyAdd(p << 1 | 1, mid + 1, r, s, t, v);
}
inline int queryC(int p, int l, int r, int s, int t) {
if (s <= l && t >= r) return p[pool].maxPosC;
register int mid = (l + r) >> 1;
register int pos = 0, res;
if (s <= mid) {
res = queryC(p << 1, l, mid, s, t);
(c[res] > c[pos]) && (pos = res);
}
if (t > mid) {
res = queryC(p << 1 | 1, mid + 1, r, s, t);
(c[res] > c[pos]) && (pos = res);
}
return pos;
}
inline int queryD(int p, int l, int r, int s, int t) {
if (s <= l && t >= r) return p[pool].minValD;
register int mid = (l + r) >> 1, min = INF;
if (s <= mid) min = std::min(min, queryD(p << 1, l, mid, s, t));
if (t > mid) min = std::min(min, queryD(p << 1 | 1, mid + 1, r, s, t));
return min;
}
inline Info queryF(int p, int l, int r, int s, int t) {
if (s > t) return Info(-INF, 0);
if (s <= l && t >= r) return p[pool].f;
register int mid = (l + r) >> 1;
if (t <= mid) return queryF(p << 1, l, mid, s, t);
if (s > mid) return queryF(p << 1 | 1, mid + 1, r, s, t);
return queryF(p << 1, l, mid, s, mid) +
queryF(p << 1 | 1, mid + 1, r, mid + 1, t);
}
inline void modifyCover(int p, int l, int r, int pos, const Info &v) {
if (l == r) {
p[pool].f = v;
return;
}
register int mid = (l + r) >> 1;
pos <= mid ? modifyCover(p << 1, l, mid, pos, v)
: modifyCover(p << 1 | 1, mid + 1, r, pos, v);
p[pool].f = pool[p << 1].f + pool[p << 1 | 1].f;
}
inline Info query(const int x, register int l, register int r) {
register int p = 1;
Info ret(-INF, 0);
for (register int mid; l != r;) {
ret += p[pool].tag;
mid = (l + r) >> 1;
if (x <= mid) {
p = p << 1;
r = mid;
} else {
p = p << 1 | 1;
l = mid + 1;
}
}
return ret + p[pool].tag;
}
inline void update(int l, int mid, int r) {
register int i = std::max(c[mid] + l, mid);
if (i > r || g[i] >= mid) return;
register int newL = std::max(l, g[i]), newR = i - c[mid];
Info tmp = queryF(1, 0, n, newL, newR) + 1;
for (; i <= mid - 1 + c[mid] && i <= r; i++) {
if (g[i] > newL) {
if (g[i] >= mid) return;
newL = g[i];
tmp = queryF(1, 0, n, newL, newR) + 1;
}
f[i] += tmp;
newR++;
if (newR >= newL) tmp += f[newR] + 1;
}
while (i <= r) {
if (g[i] > newL) {
if (g[i] >= mid) return;
newL = g[i];
}
tmp = queryF(1, 0, n, newL, mid - 1) + 1;
int t = queryD(1, 0, n, newL + 1, n);
if (t > r) {
modifyAdd(1, 0, n, i, r, tmp);
return;
}
modifyAdd(1, 0, n, i, t - 1, tmp);
i = t;
}
}
void solve(int l, int r) {
if (l == r) {
if (l) modifyCover(1, 0, n, l, f[l] = f[l] + query(l, 0, n));
return;
}
register int mid = queryC(1, 0, n, l + 1, r);
solve(l, mid - 1);
update(l, mid, r);
solve(mid, r);
}
inline void solve() {
io >> n;
for (register int i = 1; i <= n; i++) io >> c[i] >> d[i];
build(1, 0, n);
for (register int i = 0; i <= n; i++) {
d[i] = n + 1;
f[i] = Info(-INF, 0);
}
f[0] = Info(0, 1);
for (register int i = 0, j = 0; i <= n; i++) {
while (j < i && i - j > queryD(1, 0, n, j + 1, i)) j++;
g[i] = j;
if (d[g[i]] > n) d[g[i]] = i;
}
buildUpdate(1, 0, n);
solve(0, n);
printf(f[n].max > 0 ? "%d %d\n" : "NIE\n", f[n].max, f[n].cnt);
}
} // namespace
int main() {
// freopen("sample/1.in", "r", stdin);
solve();
return 0;
} | true |
2d54bd340c9f53f5ebdc7aa73e9b785de13ae045 | C++ | nikolas8309/Eeprom-256B | /i2cEepromUtilities.ino | UTF-8 | 1,673 | 2.6875 | 3 | [] | no_license | void readFromEeprom()
{
byte readVal = 0;
for(unsigned long i=0; i<MEM_SIZE; i++)
{
// Read from EEPROM at the current address
readVal = readAddress(i);
// For debugging/info only
if((i % KB_VAL == 0) && (i > 1))
{
unsigned long total = (unsigned long) (i / KB_VAL);
Serial.print(F("Wrote "));
Serial.print(total);
Serial.println(F(" Kb"));
}
// Write the value to the SDE Card
myFile.write(readVal);
// delay (150);
}
}
//-------------------------------------------
void writeFileToEeprom(){
byte valToWrite=0;
for(unsigned long i=0; i<MEM_SIZE; i++)
{
if(!myFile.available()){
Serial.print("EOF reached. Aborting");
break;
}
valToWrite=myFile.read();
i2c_eeprom.write(i, valToWrite);
//Serial.print("Write: 0x");
//Serial.print(i, HEX);
//Serial.print(" (address) -> 0x");
//Serial.print(valToWrite, HEX);
//Serial.print(" (data)\n");
// For debugging/info only
if((i % KB_VAL == 0) && (i > 1))
{
unsigned long total = (unsigned long) (i / KB_VAL);
Serial.print(F("Wrote "));
Serial.print(total);
Serial.println(F(" Kb"));
}
}
}
//-------------------------------------------
byte readAddress(unsigned int address)
{
byte rData = 0xFF;
Wire.beginTransmission(EEPROM_I2C_ADDRESS);
//Wire.write((unsigned int)(address >> 8)); // MSB
Wire.write((unsigned int)(address & 0xFF)); // LSB
// Wire.endTransmission();
for (unsigned long i=0; i<200; i++){
Wire.requestFrom(EEPROM_I2C_ADDRESS, 1);
rData = Wire.read();
Serial.println (rData);
}
return rData;
}
| true |
8e9e2921d8d8e987279c989540c97076d5f56ac5 | C++ | HururuekChapChap/Winter_Algorithm | /Tree_Diameter-1967/Tree_Diameter-1967/main.cpp | UTF-8 | 2,884 | 3.5 | 4 | [] | no_license | //
// main.cpp
// Tree_Diameter-1967
//
// Created by yoon tae soo on 2020/01/23.
// Copyright © 2020 yoon tae soo. All rights reserved.
//
#include <iostream>
#include <queue>
using namespace std;
/*
내 알고리즘은 운 좋게 1.2초가 나와서 통과 하였다.
이 알고리즘은, 모든 정점에 대해서 탐색을 해주는 방식이다.
총 N 번 탐색을 해주는데, 이때, 가장 길이가 긴 것을 반환해준다.
그런데 visited 값을 초기화 해줘야 하기 때문에 총 N*N 정도의 시간이 나온다.
그래서 구린 알고리즘이다 ㅎㅎ.
다른 사람들은 원의 지름 방법을 이용했다. 루트가 1이라는 전제 하에, 1에서 부터 가장 먼 곳을 찾아준다.
그리고 그곳에서 다시 탐색을 해준다. 그러면 최장 길이의 지름이 나온다.
1
/ \
2. 3
/ \ \
4. 5. 6
이렇다고 할 때, 1에서 부터 6 까지 가는 지름이 가장 길다고 할 때, 6에서 부터 다시 가장 길이가 긴 곳을 찾아주면
5 - 2 - 1 - 3- 6 이렇게 나올 수 있는 것이다.
*/
class Data{
public:
int to;
int weight;
};
int visited[10001] = {0};
vector<Data> v[10001];
int N;
int BFS(int current){
//방문 표시를 초기화 해준다.
for(int i = 0; i< 10001; i++){
visited[i] = 0;
}
//노드 번호와 길이 값을 저장해준다.
queue<pair<int, int>> q;
int MAX = 0;
visited[current] = 1;
q.push(make_pair(current, 0));
while(! q.empty()){
int from = q.front().first;
int weight = q.front().second;
//길이가 더 긴 지름이 있다면 갱신해준다.
if(weight > MAX){
MAX = weight;
}
q.pop();
for(int i = 0; i<v[from].size(); i++){
int temp_to = v[from][i].to;
int temp_weight = v[from][i].weight;
if(visited[temp_to] == 0){
visited[temp_to] = 1;
//현재 까지의 길이에서 다음 노드 까지의 길이를 더해준다.
q.push(make_pair(temp_to, temp_weight + weight));
}
}
}
return MAX;
}
int main(int argc, const char * argv[]) {
cin >> N;
int to, from , weight;
int anw = 0;
for(int i = 2; i<=N; i++){
cin >> from >> to >> weight;
v[from].push_back({to,weight});
v[to].push_back({from,weight});
}
//모든 노드를 탐색해준다.
for(int i = 1 ; i<=N; i++){
int temp = BFS(i);
if(temp > anw){
anw = temp;
}
}
cout << anw;
return 0;
}
| true |
cd320c1d2ad9de7f7f58c342f67ed30bbb8b7049 | C++ | EricDDK/3DEngineEC | /3DEngine/Component/Component.cpp | UTF-8 | 834 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "Component.h"
ENGINE_NAMESPACE_START
Component::Component()
:_order(0)
{
}
Component::Component(GameObject *gameObject, int order)
:_gameObject(gameObject)
,_order(order)
{
_gameObject->addComponent(this);
}
Component::~Component()
{
_gameObject->removeComponent(this);
}
void Component::update(float deltaTime)
{
}
void Component::processInput(const unsigned char* keyState)
{
}
void Component::onUpdateWorldTransform()
{
}
void Component::setgameObject(GameObject *gameObject)
{
if (_gameObject)
{
_gameObject->removeComponent(this);
}
_gameObject = gameObject;
gameObject->addComponent(this);
}
GameObject *Component::getgameObject() const
{
return _gameObject;
}
void Component::setOrder(int order)
{
_order = order;
}
int Component::getOrder() const
{
return _order;
}
ENGINE_NAMESPACE_END | true |
4ef0d1fbd8a4181169111d0a69f3a7713976238a | C++ | dastyk/Radiant | /Radiant/Radiant/Projectile.h | UTF-8 | 1,164 | 2.8125 | 3 | [] | no_license | #ifndef _PROJECTILE_H_
#define _PROJECTILE_H_
#pragma once
//////////////
// Includes //
//////////////
////////////////////
// Local Includes //
////////////////////
//#include "System.h"
#include "General.h"
#include "EntityBuilder.h"
class Projectile
{
protected:
Projectile(EntityBuilder* builder, Entity owner, float damageModifier) : _builder(builder), _owner(owner), _damageModifier(damageModifier),_lifeTime(0),_damage(0),_alive(false),_projectileEntity(Entity()) {}
public:
virtual void Update(float deltaTime) = 0;
virtual ~Projectile() { _builder->GetEntityController()->ReleaseEntity(_projectileEntity); }
virtual bool GetState() = 0;
virtual Entity GetEntity()
{
return _projectileEntity;
}
virtual float GetDamage()
{
return _damage*_damageModifier;
}
virtual void SetState(bool value)
{
_alive = value;
}
virtual Entity GetOwner()
{
return _owner;
}
virtual void CollideWithEntity(DirectX::XMVECTOR& outMTV, const Entity& entity) { _alive = false; }
protected:
float _lifeTime;
float _damage;
float _damageModifier;
bool _alive;
Entity _owner;
Entity _projectileEntity;
EntityBuilder* _builder;
};
#endif | true |
8451349d3f65e15da73401f4ddcac20d7c05ec07 | C++ | adbacker/duinobattletanks | /demo_RF24Net/demo_RF24Net.ino | UTF-8 | 2,540 | 2.9375 | 3 | [] | no_license |
#define NODE1
//#define NODE2
/*-----( Import needed libraries )-----*/
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include "printf.h"
//create object
struct NET_DATA_STRUCTURE{
//put your variable definitions here for the data you want to send
//THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
int controller_x;
int controller_y;
};
//give a name to the group of data
NET_DATA_STRUCTURE myNetData;
/*-----( Declare Constants and Pin Numbers )-----*/
/////////////////////////////////////////
// RADIO assignments BEGIN
/////////////////////////////////////////
#define CE_PIN 9
#define CSN_PIN 10
#ifdef NODE1
#define this_node 00
#define other_node 01
#endif
#ifdef NODE2
#define this_node 01
#define other_node 00
#endif
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
RF24Network network(radio);
/////////////////////////////////////////
// RADIO assignments END
/////////////////////////////////////////
byte incomingByte=0; //necessary for serial read
void setup() /****** SETUP: RUNS ONCE ******/
{
Serial.begin(57600);
printf_begin();
randomSeed(analogRead(0));
Serial.println("Nrf24L01 Receiver Starting");
// radio setup BEGIN
SPI.begin();
radio.begin();
network.begin(/*channel*/ 90, /*node address*/ this_node);
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
// Pump the network regularly
network.update(); //network pump
check_network(); //check for network updates
if (Serial.available() > 0) { //if someone hits a key..
incomingByte = Serial.read(); //gotta do this, else the byte stays in the buffer
myNetData.controller_x = random(1024);
myNetData.controller_y = random(1024);
printf("sending xval: %i, yval: %i to node %i \n",myNetData.controller_x, myNetData.controller_y, other_node);
RF24NetworkHeader header(other_node);
bool ok = network.write(header,&myNetData,sizeof(myNetData));
if (ok) {
Serial.println("send succeeded!");
} else {
Serial.println("ooohh...you FAILED! (well, your send did anyway)");
}
}
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
void check_network() {
// Is there anything ready for us?
while ( network.available() )
{
// If so, grab it and print it out
RF24NetworkHeader header;
network.read(header,&myNetData,sizeof(myNetData));
printf("Received xval: %i, yval: %i from %i\n",myNetData.controller_x, myNetData.controller_y, other_node);
}
}
//*********( THE END )***********
| true |
04f022f575a60c8ee610bff92a86065ffd9d5259 | C++ | AJnad/Software-Programming-in-C-- | /Assignment C/AssignmentC3.cpp | UTF-8 | 4,787 | 4.03125 | 4 | [] | no_license | /**
Ajay Nadhavajhala
CIS 22B
Winter 2017
Assignment C
Problem C3
This program is based off of the Car program
from problem C1. However, we make use of
copy and default constructors based off of
the user input.
*/
#include <iostream>
#include <iomanip>
using namespace std;
class Car
{
private:
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
public:
friend bool operator== (const Car &c1, const Car &c2);
Car()
{
setup(reportingMark = "", carNumber = 0, kind = "other", loaded = false, destination ="NONE");
}
Car (const Car &userCar)
{
setup(userCar.reportingMark, userCar.carNumber, userCar.kind, userCar.loaded, userCar.destination);
}
Car(std::string reportingMark, int carNumber, std::string kind, bool loaded, std::string destination)
{
setup(reportingMark, carNumber, kind, loaded, destination);
}
~Car() {};
void setup(string, int, string, bool, string);
void output();
};
/*************** setup ********************
takes in the user input and sets that data to
the class variables in Car
*/
void Car::setup (string rep, int cnum, string kd, bool load, string dest)
{
reportingMark = rep;
carNumber = cnum;
kind = kd;
loaded = load;
destination = dest;
}
/************** output ********************
prints out to console the values of reportingMark,
carNumber, kind, loaded or not, and destination
*/
void Car::output()
{
cout << endl;
cout << left << setw(20) << "reportingMark " << reportingMark << endl;
cout << setw(20) <<"carNumber " << carNumber << endl;
cout << setw(20) <<"kind " << kind << endl;
cout << setw(20) << "loaded " << boolalpha << loaded << endl;
cout << setw(20) << "destination " << destination << endl;
}
bool operator== (const Car &c1, const Car &c2)
{
if ((c1.reportingMark == c2.reportingMark) && (c1.carNumber == c2.carNumber))
return true;
else
return false;
}
void input (string&, int&, string&, bool&, string&);
int main()
{
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
input(reportingMark, carNumber, kind, loaded, destination);
Car *car1 = new Car(reportingMark, carNumber, kind, loaded, destination);
Car *car2 = new Car(*car1);
Car *car3 = new Car;
cout << "\nContents of car1:";
car1->output();
cout << "\nContents of car2: ";
car2->output();
cout << "\nContents of car3: ";
car3->output();
cout << endl;
if (*car1 == *car2)
cout << "car1 is the same car as car2\n";
else
cout << "car1 is not the same car as car2\n";
if (*car2 == *car3)
cout << "car2 is the same car as car3\n";
else
cout << "car2 is not the same car as car3\n";
delete car1;
delete car2;
delete car3;
return 0;
}
/************** input ********************
asks the user to enter the various characteristics
of the car
*/
void input (string& reportingMark, int& carNumber, string& kind, bool& loaded, string& destination)
{
cout << "Please enter the reporting mark: ";
cin >> reportingMark;
cout << "Please enter the car number: ";
cin >> carNumber;
cout << "Please enter what kind of car it is: ";
cin >> kind;
cout << "Please enter the number 1 if the car is loaded, 0 otherwise: ";
cin >> loaded;
if(loaded == false)
{
destination = "NONE";
}
else
{
cin.ignore(80, '\n');
cout << "Please enter your destination: ";
getline(cin, destination);
}
}
/* Execution Results
Please enter the reporting mark: SP
Please enter the car number: 34567
Please enter what kind of car it is: business
Please type the number 1 if the car is loaded, 0 otherwise: 1
Please enter your destination: Salt Lake City
Contents of car1:
reportingMark SP
carNumber 34567
kind business
loaded true
destination Salt
Contents of car2:
reportingMark SP
carNumber 34567
kind business
loaded true
destination Salt
Contents of car3:
reportingMark
carNumber 0
kind other
loaded false
destination NONE
car1 is the same car as car2
car2 is not the same car as car3
Process returned 0 (0x0) execution time : 9.260 s
Press any key to continue.
*/
| true |
3002c09854eac15d0a780efd957e86719e8f7e58 | C++ | roshihie/At_Coder | /ABC_C/ABC098_C_Attention.cpp | UTF-8 | 662 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void input(string& rsLine)
{
int nSize;
cin >> nSize >> rsLine;
}
int calcMinChgDir(const string& cnrsLine)
{
int nMinChgDir = 0;
for (int nx = 1; nx < cnrsLine.size(); ++nx)
if (cnrsLine[nx] == 'E') ++nMinChgDir;
int nChgDir = nMinChgDir;
for (int nx = 1; nx < cnrsLine.size(); ++nx)
{
if (cnrsLine[nx - 1] == 'W') ++nChgDir;
if (cnrsLine[nx] == 'E') --nChgDir;
nMinChgDir = min(nMinChgDir, nChgDir);
}
return nMinChgDir;
}
int main()
{
string sLine;
input(sLine);
cout << calcMinChgDir(sLine) << endl;
return 0;
}
| true |
e23b61e841a1661cfe87fd4cd5423f1b5d7c310a | C++ | ig92/cp-course | /52-subset-sum/subset.cpp | UTF-8 | 1,030 | 3.046875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
int numbers [101];
bool knapsack(int c, int n) {
bool M [n+1][c+1];
// init
for (int i = 0; i <= c; ++i)
M[0][i] = false;
for (int i = 0; i <= n; ++i)
M[i][0] = true;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= c; ++j)
M[i][j] = (M[i-1][j] || (j >= numbers[i-1] && M[i-1][j-numbers[i-1]]));
return M[n][c];
}
int main() {
std::ios_base::sync_with_stdio(false);
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
for(int i = 0; i < n; ++i)
cin >> numbers[i];
int sum = 0;
for (int i = 0; i < n; i++)
sum += numbers[i];
if (sum % 2 != 0) {
cout << "NO" << endl;
continue;
}
int target = sum / 2;
if (knapsack(target, n) == 0)
cout << "NO" << endl;
else
cout << "YES" << endl;
}
return 0;
}
| true |
6af49dfc6417e4beb849812c751c999d3a88fec7 | C++ | MESH-Model/MESH_Project_Baker_Creek | /Model/Ostrich/GeomParamABC.h | UTF-8 | 8,088 | 2.671875 | 3 | [] | no_license | /******************************************************************************
File : GeomParamABC.h
Author : L. Shawn Matott
Copyright : 2004, L. Shawn Matott
Encapsulates a 'geometry' parameter. Geometry parameters are variables in the model
which are composed on one or more spatial vertices. The ABC for the geometry
parameters encapsulates the interface used by other Ostrich modules, allowing
various specific geometry parameter relationships (line3, poly2, poly3, etc.) to be
implemented as needed with minimal code change (just need to add the specific
geometry parameter class and some additional input file parsing). The purpose of a
geometry parameter is to facilitate changes to geometric model properties as part of
a calibration or optimization exercise. Ostrich will ensure that all geometry parameters
are topologically correct in that:
1) vertices will be automatically inserted if elements overlap
2) if a given ordering of vertices is not valid, the polygon vertices will be
randomly reordered until a valid polygon is found
These specific geometry-parameter classes are supported:
GeomParamLine3 : a polyline containing a set of (x,y,z) values, where (x,y) are
the spatial coordinates and z is a non-geometric value (i.e. head). When
vertices are inserted, the z-value of the new vertex is interpolated.
GeomParamPoly3 : a polygon containing a set of (x,y,z) values, where (x,y) are
the spatial coordinates and z is a non-geometric value (i.e. head). When
vertices are inserted, the z-value of the new vertex is interpolated.
GeomParamPoly2 : a polygon containing a set of (x,y) values, where (x,y) are
the spatial coordinates.
Version History
11-29-04 lsm Created
******************************************************************************/
#ifndef GEOM_PARAM_ABC_H
#define GEOM_PARAM_ABC_H
#include "MyHeaderInc.h"
//forward decs
struct AUG_VERT_LIST_STRUCT;
struct VERTEX_LIST_STRUCT;
struct AUG_CIRCLE_STRUCT;
#define MY_POLYGON_TYPE (0)
#define MY_LINE_TYPE (1)
#define MY_CIRCLE_TYPE (2)
/******************************************************************************
class GeomParamABC
Abstract base class of a geometry-parameter.
******************************************************************************/
class GeomParamABC
{
public:
virtual ~GeomParamABC(void){ DBG_PRINT("GeomParamABC::DTOR"); }
virtual void Destroy(void) = 0;
virtual void Convert(void) = 0;
virtual bool Reorder(void) = 0;
virtual bool FixVertices(GeomParamABC * pOther) = 0;
virtual int GetValStrSize(void) = 0;
virtual void GetValAsStr(UnmoveableString valStr) = 0;
virtual void Write(FILE * pFile, int type) = 0;
virtual UnchangeableString GetName(void) = 0;
virtual void InsertVertex(struct AUG_VERT_LIST_STRUCT * pNew) = 0;
virtual struct VERTEX_LIST_STRUCT * FixVertex(Segment2D * pSeg) = 0;
virtual struct VERTEX_LIST_STRUCT * GetVertexList(int * type) = 0;
}; /* end class GeomParamABC */
/******************************************************************************
class GeomParamLine3
Represents a line geometry having 2 spatial coordinates (x,y) and one
non-spatial value (z) at each vertex.
******************************************************************************/
class GeomParamLine3 : public GeomParamABC
{
public:
GeomParamLine3(void);
GeomParamLine3(IroncladString name);
~GeomParamLine3(void){ DBG_PRINT("GeomParamLine3::DTOR"); Destroy(); }
void Destroy(void);
void Convert(void);
bool Reorder(void);
bool FixVertices(GeomParamABC * pOther);
int GetValStrSize(void);
void GetValAsStr(UnmoveableString valStr);
void Write(FILE * pFile, int type);
UnchangeableString GetName(void){ return m_pName;}
void InsertVertex(struct AUG_VERT_LIST_STRUCT * pNew);
struct VERTEX_LIST_STRUCT * GetVertexList(int * type){ *type = MY_LINE_TYPE; return m_pFixed;}
private:
struct VERTEX_LIST_STRUCT * FixVertex(Segment2D * pSeg);
StringType m_pName;
struct AUG_VERT_LIST_STRUCT * m_pInit;
struct VERTEX_LIST_STRUCT * m_pFixed;
}; /* end class GeomParamLine3 */
/******************************************************************************
class GeomParamPoly3
Represents a polygon geometry having 2 spatial coordinates (x,y) and one
non-spatial value (z) at each vertex.
******************************************************************************/
class GeomParamPoly3 : public GeomParamABC
{
public:
GeomParamPoly3(void);
GeomParamPoly3(IroncladString name);
~GeomParamPoly3(void){ DBG_PRINT("GeomParamPoly3::DTOR"); Destroy(); }
void Destroy(void);
void Convert(void);
bool Reorder(void);
bool FixVertices(GeomParamABC * pOther);
int GetValStrSize(void);
void GetValAsStr(UnmoveableString valStr);
void Write(FILE * pFile, int type);
UnchangeableString GetName(void){ return m_pName;}
void InsertVertex(struct AUG_VERT_LIST_STRUCT * pNew);
struct VERTEX_LIST_STRUCT * GetVertexList(int * type){ *type = MY_POLYGON_TYPE; return m_pFixed;}
private:
struct VERTEX_LIST_STRUCT * FixVertex(Segment2D * pSeg);
StringType m_pName;
struct AUG_VERT_LIST_STRUCT * m_pInit;
struct VERTEX_LIST_STRUCT * m_pFixed;
}; /* end class GeomParamPoly3 */
/******************************************************************************
class GeomParamPoly2
Represents a polygon geometry having 2 spatial coordinates (x,y) at each vertex.
******************************************************************************/
class GeomParamPoly2 : public GeomParamABC
{
public:
GeomParamPoly2(void);
GeomParamPoly2(IroncladString name);
~GeomParamPoly2(void){ DBG_PRINT("GeomParamPoly2::DTOR"); Destroy(); }
void Destroy(void);
void Convert(void);
bool Reorder(void);
bool FixVertices(GeomParamABC * pOther);
int GetValStrSize(void);
void GetValAsStr(UnmoveableString valStr);
void Write(FILE * pFile, int type);
UnchangeableString GetName(void){ return m_pName;}
void InsertVertex(struct AUG_VERT_LIST_STRUCT * pNew);
struct VERTEX_LIST_STRUCT * GetVertexList(int * type){ *type = MY_POLYGON_TYPE; return m_pFixed;}
private:
struct VERTEX_LIST_STRUCT * FixVertex(Segment2D * pSeg);
StringType m_pName;
struct AUG_VERT_LIST_STRUCT * m_pInit;
struct VERTEX_LIST_STRUCT * m_pFixed;
}; /* end class GeomParamPoly2 */
/******************************************************************************
class GeomParamCirc4
Represents a circle geometry having center at (x,y) radius of r and one
non-spatial value (z).
******************************************************************************/
class GeomParamCirc4 : public GeomParamABC
{
public:
GeomParamCirc4(void);
GeomParamCirc4(IroncladString name, struct AUG_CIRCLE_STRUCT * pData);
~GeomParamCirc4(void){ DBG_PRINT("GeomParamCirc4::DTOR"); Destroy(); }
void Destroy(void);
void Convert(void);
bool Reorder(void){ return true;}
bool FixVertices(GeomParamABC * pOther);
int GetValStrSize(void){ return 100;}
void GetValAsStr(UnmoveableString valStr);
void Write(FILE * pFile, int type);
UnchangeableString GetName(void){ return m_pName;}
void InsertVertex(struct AUG_VERT_LIST_STRUCT * pNew){ return; }
struct VERTEX_LIST_STRUCT * GetVertexList(int * type);
private:
struct VERTEX_LIST_STRUCT * FixVertex(Segment2D * pSeg);
StringType m_pName;
struct AUG_CIRCLE_STRUCT * m_pInit;
Circle2D m_Fixed;
double m_Zcur;
}; /* end class GeomParamCirc4 */
#endif /* GEOM_PARAM_ABC_H */
| true |
4e9c2ac61e75cf31495f9941f89fa1b6a60306d9 | C++ | ailyanlu/zhwj184-zoj | /1003.cpp | UTF-8 | 326 | 2.515625 | 3 | [] | no_license | #include <math.h>
#include <iostream.h>
#include <stdio.h>
int main()
{
double n,p;
double k;
while( cin >> n >> p )
{
/*k=log10(p)/n;
//k=ceil(k);
k=pow(10,k);
if((int)k!=k)k+=1; */
// cout << (int ) k << endl;
k=pow(p,1.0/n);
printf("%.0lf\n",k);
}
}
| true |
2843a92b9183e47fe365529ee1f999a1fbcd81d2 | C++ | FancyKillerPanda/PandEdit | /PandEdit/include/shader.hpp | UTF-8 | 562 | 2.71875 | 3 | [] | no_license | // ===== Date Created: 14 April, 2020 =====
#if !defined(SHADER_HPP)
#define SHADER_HPP
#include <string>
#include <unordered_map>
#include <glad/glad.h>
class Shader
{
public:
std::string name;
GLuint programID;
private:
inline static std::unordered_map<std::string, Shader*> shadersMap;
public:
Shader(std::string name, const char* vertexPath, const char* fragmentPath);
~Shader();
static Shader* get(const std::string& shaderName);
private:
GLuint compileShader(GLenum type, const char* source);
void destroyShader(GLuint shader);
};
#endif
| true |
94f79663681b3087434bd6f3cdbf477c9f55ca9c | C++ | SmirkingWolf/QT-Asteroids | /QT Asteroids SOURCE CODE FOR PRESENTATION/ship.h | UTF-8 | 1,042 | 2.75 | 3 | [] | no_license | #ifndef SHIP_H
#define SHIP_H
#include "scene.h"
#include <QKeyEvent>
#include <QGraphicsObject> //A combination of QGraphicsItem and QObject
class Ship : public QGraphicsObject
{
public:
//Default constructor - positions the ship to the middle of the screen.
Ship();
//Updates the ship position
void updateShip();
//Reimplementation of the keyPressEvent
void keyPressEvent(QKeyEvent *);
//Paint and Hitbox functions for the Ship
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QRectF boundingRect() const
{return QRectF(-20, -25, 25, 36); }
private:
//Angle of the Ship, used to set it's rotation
qreal angle;
//These values take into account the rotation of the ship
//Which are then used to move the ship to the proper position
qreal xCoor;
qreal yCoor;
//Determines whether the ship's action key(s) have been pressed.
bool keyCCWPressed;
bool keyCWPressed;
bool keyMove;
bool keyShoot;
};
#endif
| true |
2a16c34c580f626c49462e749db5612c6412c12d | C++ | mahajanayush77/OS_Lab | /Disk Scheduling/fcfs_disk.cpp | UTF-8 | 615 | 2.9375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n,seek=0;
cout<<"Enter size of queue request : ";
cin>>n;
int queue[n+1];
cout<<"Enter the request queue : ";
for(int i=1;i<=n;i++)
cin>>queue[i];
cout<<"Enter the head : ";
cin>>queue[0];
for(int j=0;j<n;j++){
seek += abs(queue[j+1]-queue[j]);
cout<<"Serviced request from "<<queue[j]<<" to "<<queue[j+1]<<" seek is "<<abs(queue[j]-queue[j+1])<<endl;
}
float avg_seek = seek/n;
cout<<"Average seek time is "<<avg_seek<<endl;
return 0;
}
// 98,183,37,122,14,124,65,67 | true |
f4d62d9cef03468e4bcee3f2a13909b806ed2d4e | C++ | vadymtolkachev/track-c | /dz1/SolveSquare.cpp | UTF-8 | 975 | 3.203125 | 3 | [] | no_license | #include "SolveSquare.hpp"
int solveLinear(double b, double c, double *x)
{
if((std::isfinite(b) == 0) || (std::isfinite(c) == 0))
return -1;
if(x == nullptr)
return -1;
if(b == 0)
{
if(c == 0)
return 3;
return 0;
}
*x = -c/b;
if(std::isfinite(*x) == 0)
return -1;
return 1;
}
int solveSquare(double a, double b, double c, double *x1, double *x2)
{
if((std::isfinite(a) == 0) || (std::isfinite(b) == 0) || (std::isfinite(c) == 0))
return -1;
if((x1 == nullptr) || (x2 == nullptr))
return -1;
if(x1 == x2)
return -1;
if(a == 0)
{
int res = solveLinear(b, c, x1);
if(res == 1)
*x2 = *x1;
return res;
}
double d = b*b - 4*a*c;
if(d < 0)
return 0;
if(d == 0)
{
*x1 = -b/(2*a);
if(std::isfinite(*x1) == 0)
return -1;
*x2 = *x1;
return 1;
}
*x1 = (-b + sqrt(d))/(2*a);
*x2 = (-b - sqrt(d))/(2*a);
if((std::isfinite(*x1) == 0) || (std::isfinite(*x2) == 0))
return -1;
return 2;
}
| true |
5a433814724293c37fd607355becb5e637728051 | C++ | CoderConspiracy/TetrisLearn | /TetrisLearn/TetrisLearn/ITetraminoManager.cpp | UTF-8 | 566 | 2.65625 | 3 | [] | no_license | #include "ITetraminoManager.hpp"
ITetraminoManager::~ITetraminoManager()
{
}
Tetramino * ITetraminoManager::current() const
{
return current_custom();
}
void ITetraminoManager::activate_next()
{
activate_next_custom();
}
void ITetraminoManager::holdTetramino()
{
holdTetramino_custom();
}
TetraminoTypes ITetraminoManager::getNextType(size_t index) const
{
return getNextType_custom(index);
}
TetraminoTypes ITetraminoManager::getHoldType() const
{
return getHoldType_custom();
}
bool ITetraminoManager::isHolding() const
{
return isHolding_custom();
}
| true |
8ec5f4b671aad1a608586638d8a54bd8496bcb7b | C++ | adamtew/USU | /2014/CS1400/Challenges/Chapter 3/3.12_Currency.cpp | UTF-8 | 832 | 3.890625 | 4 | [] | no_license | /*Write a program that will convert U.S. dollar amounts to Japanese yen and to euros,
storing the conversion factors in the constant variables YEN_PER_DOLLAR and
EUROS_PER_DOLLAR. To get the most up-to-date exchange rates, search the internet
using the term "currency exchange rate" or "currency converter". If you cannot find
the most recent exchange rates, use the following:
1 Dollar = 78.18 Yen
1 Dollar = .8235 Euros*/
// Adam Tew ---- CS1400
#include <iostream>
using namespace std;
int main(){
const float YEN_PER_DOLLAR = 78.18, EUROS_PER_DOLLAR = .8235;
float inputDollar = 0, yen, euro;
cout << "\nEnter a dollar amount ";
cin >> inputDollar;
yen = inputDollar * YEN_PER_DOLLAR;
euro = inputDollar * EUROS_PER_DOLLAR;
cout << "\nThat comes out to " << yen << " yen and " << euro << " euros\n";
return 0;
} | true |
83bdf02ea177b526e16d1468fe9df92b62a34b35 | C++ | DobromirTopalov/My-Cpp-Junk-Pouch | /IntroCourse/Week 9/Exercise 4.cpp | WINDOWS-1251 | 819 | 3.734375 | 4 | [] | no_license | /*.4 Where is izdislav
, true, izdislav false .*/
#include <iostream>
#include <cstring>
bool compare(char* arr1, char* arr2)
{
int len1 = strlen(arr1);
int len2 = strlen(arr2);
if (len2 > len1)
{
return false;
}
int start = len1 - len2 + 1;
for (int i = start, p = 0; arr1[i] != '\0'; i++, p++)
{
if (arr1[i] == arr2[p])
{
continue;
}
else if (arr1[i] < arr2[p])
{
return -1;
}
else
{
return 1;
}
}
return 0;
}
int main()
{
char string1[] = "Kurec and Putec izdislav";
char string2[] = "izdislav";
std::cout << std::boolalpha << compare(string1, string2);
std::cout << "\n";
return 0;
} | true |
6d26375d5f112eeeb35c61faa1d47573842fc409 | C++ | LeeHeungrok/BaekjoonAlgorithm | /Level_2/6_Remainder/Remainder.cpp | UTF-8 | 326 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(){
int left, center, right;
cin>>left>>center>>right;
cout<<(left + center) % right<<endl;
cout<<(left % right + center % right) % right<<endl;
cout<<(left * center) % right<<endl;
cout<<(left % right * center % right) % right<<endl;
return 0;
} | true |
bd9bf9422a3bbb3bf5b2c039f670aeabc1537244 | C++ | albinopapa/BoxWars | /BoxWars v0.0.4/Keyboard.h | UTF-8 | 1,106 | 2.90625 | 3 | [] | no_license | #pragma once
#include "Def.h"
#include <bitset>
#include <optional>
#include <queue>
#include <variant>
class KeyboardServer;
class KeyboardClient
{
public:
struct KeyPress { char code = 0; };
struct KeyRelease { char code = 0; };
using Event = std::variant<KeyPress, KeyRelease>;
public:
KeyboardClient( KeyboardServer& kServer );
bool IsKeyPressed( char _code )const noexcept;
bool IsKeyReleased( char _code )const noexcept;
std::optional<KeyboardClient::Event> ReadEvent();
std::optional<KeyboardClient::Event> PeekEvent()const noexcept;
std::optional<char> ReadChar();
std::optional<char> PeekChar()const noexcept;
private:
KeyboardServer& server;
};
class KeyboardServer
{
public:
void OnKeyPress( char _code );
void OnKeyRelease( char _code );
void OnChar( char _code );
void PopEvent();
void PopChar();
private:
friend KeyboardClient;
std::bitset<256> m_keys;
std::queue<char> m_chars;
std::queue<KeyboardClient::Event> m_events;
};
using KeyPressEvent = KeyboardClient::KeyPress;
using KeyReleaseEvent = KeyboardClient::KeyRelease;
using KeyEvent = KeyboardClient::Event; | true |
7e2716cffa902030b33783aa1e59f004b3182edb | C++ | Eternal4869/SqStack | /main.cpp | UTF-8 | 3,395 | 3.953125 | 4 | [] | no_license | #include <iostream>
using namespace std;
#define DEFAULT_SIZE 10
template <class Elem>
class SqStack
{
private:
int count;
int maxSize;
Elem *elems;
public:
SqStack(int size = DEFAULT_SIZE); //构造函数
virtual ~SqStack(); //析构函数
int Length() const; //计算栈的长度
bool Empty() const; //判断栈是否为空
void Clear(); //清空栈
void Traverse() const; //遍历顺序栈
bool Push(const Elem &e); //入栈
bool Top(Elem &e) const; //取栈顶元素
bool Pop(Elem &e); //出栈
SqStack(const SqStack<Elem> ©); //复制构造函数
SqStack<Elem> &operator=(const SqStack<Elem> ©); //重载
};
template <class Elem>
SqStack<Elem>::SqStack(int size)
{
maxSize = size;
count = 0;
elems = new Elem[maxSize];
}
template <class Elem>
SqStack<Elem>::~SqStack()
{
delete[] elems;
}
template <class Elem>
int SqStack<Elem>::Length() const
{
return count;
}
template <class Elem>
bool SqStack<Elem>::Empty() const
{
return count == 0;
}
template <class Elem>
void SqStack<Elem>::Clear()
{
count = 0;
}
template <class Elem>
void SqStack<Elem>::Traverse() const
{
if (Empty())
{
cout << "No elems!" << endl;
}
else
{
for (int i = 0; i < count; i++)
{
cout << elems[i] << endl;
}
}
}
template <class Elem>
bool SqStack<Elem>::Push(const Elem &e)
{
if (count == maxSize)
{
return false; //栈已满,无法继续插入
}
else //栈未满,可以继续插入元素
{
elems[count++] = e;
return true;
}
}
template <class Elem>
bool SqStack<Elem>::Top(Elem &e) const
{
if (Empty())
{
return false; //栈处于空状态,无元素,无法取栈顶
}
else
{
e = elems[count - 1]; //取出在count计数之前的数据,就是栈顶
return true;
}
}
template <class Elem>
bool SqStack<Elem>::Pop(Elem &e)
{
if (Empty()) //如果栈空,无元素可以出栈
{
return false;
}
else
{
e = elems[count - 1];
count--;
return true;
}
}
template <class Elem>
SqStack<Elem>::SqStack(const SqStack<Elem> ©) //复制构造函数
{
//复制原栈的各种属性
maxSize = copy.maxSize;
count = copy.count;
elems = new Elem[maxSize];
for (int i = 0; i < count; i++) //从栈底到栈顶,复制元素
{
elems[i] = copy.elems[i];
}
}
template <class Elem>
SqStack<Elem> &SqStack<Elem>::operator=(const SqStack<Elem> ©) //重载 = 符号函数
{
if (© != this)
{
maxSize = copy.maxSize;
count = copy.count;
delete[] elems;
elems = new Elem[maxSize];
for (int i = 0; i < count; i++)
{
elems[i] = copy.elems[i];
}
}
return *this;
}
int main()
{
//A test case.
SqStack<int> S1;
int a = 0;
cout << "a = " << a << endl;
S1.Push(1);
S1.Traverse();
S1.Pop(a);
S1.Traverse();
cout << "a = " << a << endl;
return 0;
}
| true |
ca1d449698e172cf34f383ba0da8b2d8f11dc810 | C++ | wofead/OpenGL | /OpenGLTest/VertexShader.cpp | GB18030 | 1,578 | 2.890625 | 3 | [] | no_license | #include "VertexShader.h"
#include <glad/glad.h>
#include <iostream>
//ɫҪĿǰ3DתΪһ3D꣨ͣͬʱɫǶԶԽһЩ
//#version 330 core ʾOpenGl3.3汾
//layout(location = 0) in vec3 aPos; //inؼ֣ڶɫе붥(Input Vertex Attribute)
//
//void main()
//{
//vec.xvec.yvec.zvec.w,vec.wռеλõģǴ3D4Dνӳ(Perspective Division)
// gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
//}
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"out vec4 vertexColor;;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
" vertexColor = vec4(0.5, 0.0, 0.0, 1.0);\n"
"}\0";
unsigned int vertexShader;
VertexShader::VertexShader()
{
initVertex();
}
void VertexShader::initVertex()
{
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
}
unsigned int VertexShader::getVertexShader()
{
return vertexShader;
}
VertexShader::~VertexShader()
{
glDeleteShader(vertexShader);
}
| true |
45aa7a0f2ad8fd9e8a5a1d786dc8c830baff6e4c | C++ | SarthPatel67/group1_cecapstone | /Senior-Design-Car/remote-ctl/src/base-ctl/src/ArduinoPWM.cpp | UTF-8 | 8,590 | 2.84375 | 3 | [] | no_license | #include "ArduinoMessenger.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <exception>
#include <stdexcept>
using namespace std;
void* send_mesg_loop(void* arduino_pwm_ptr)
{
ArduinoMessenger* arduino_pwm = (ArduinoMessenger*)arduino_pwm_ptr;
bool running = arduino_pwm->running;
bool empty = false;
while (running)
{
pthread_mutex_lock(&arduino_pwm->write_lock);
if (!arduino_pwm->mesg_queue.empty())
{
struct PWMMesg mesg = arduino_pwm->mesg_queue.front();
arduino_pwm->mesg_queue.pop();
empty = arduino_pwm->mesg_queue.empty();
pthread_mutex_unlock(&arduino_pwm->write_lock);
if (write(arduino_pwm->uart_gateway, (void*)&mesg.header, sizeof(char)) == -1)
{
printf("Error: ArduinoMessenger::send_mesg_loop(): failed to send message header: %d\n", errno);
}
else if (write(arduino_pwm->uart_gateway, (void*)mesg.packets, (int)mesg.packets_num) == -1)
{
printf("Error: ArduinoMessenger::send_mesg_loop(): failed to send message body: %d\n", errno);
}
else if (write(arduino_pwm->uart_gateway, (void*)&mesg.checksum, sizeof(char)) == -1)
{
printf("Error: ArduinoMessenger::send_mesg_loop(): failed to send message checksum: %d\n", errno);
}
//usleep(50000);
}
else
{
pthread_mutex_unlock(&arduino_pwm->write_lock);
}
// sleep until new data arrives
if (empty)
{
pthread_cond_wait(&arduino_pwm->new_mesg_sig, &arduino_pwm->new_mesg_lock);
}
// could have been waiting for a while. check for exit condition
pthread_mutex_lock(&arduino_pwm->write_lock);
running = arduino_pwm->running;
pthread_mutex_unlock(&arduino_pwm->write_lock);
}
return NULL;
}
ArduinoMessenger::ArduinoMessenger()
{
uart_gateway = open("/dev/ttyACM0", O_RDWR);
if (uart_gateway == -1)
{
printf("Error: ArduinoMessenger(): open(): failed to open serial line: %d\n", errno);
uart_gateway = 0;
throw runtime_error("open(): failed to open serial line");
}
if (tcgetattr(uart_gateway, &uart_props) == -1)
{
printf("Error: ArduinoMessenger(): tcgetattr(): failed to get serial line attributes: %d\n", errno);
close(uart_gateway);
throw runtime_error("tcgetattr(): failed to get serial line attributes");
}
if (cfsetspeed(&uart_props, B4800) == -1)
{
printf("Error: ArduinoMessenger(): cfsetspeed(): failed to set serial line speed: %d\n", errno);
close(uart_gateway);
throw runtime_error("cfsetspeed(): failed to set serial line speed");
}
if (tcsetattr(uart_gateway, TCSANOW, &uart_props) == -1)
{
close(uart_gateway);
throw runtime_error("tcsetattr(): failed to set serial line properties");
}
cfmakeraw(&uart_props);
if (pthread_mutex_init(&write_lock, NULL) == -1)
{
printf("Error: ArduinoMessenger(): pthread_mutex_init(): failed to initialize ArduinoMessenger::write_lock mutex: %d\n", errno);
close(uart_gateway);
throw runtime_error("pthread_mutex_init(): failed to initialize ArduinoMessenger::write_lock mutex");
}
if (pthread_mutex_init(&new_mesg_lock, NULL) == -1)
{
printf("Error: ArduinoMessenger(): pthread_mutex_init(): failed to initialize ArduinoMessenger::new_mesg_lock mutex: %d\n", errno);
close(uart_gateway);
throw runtime_error("pthread_mutex_init(): failed to initialize ArduinoMessenger::new_mesg_lock mutex");
}
if (pthread_cond_init(&new_mesg_sig, NULL) == -1)
{
printf("Error: ArduinoMessenger(): pthread_cond_init(): failed to initialize ArduinoMessenger::new_mesg_sig condition: %d\n", errno);
close(uart_gateway);
throw runtime_error("pthread_cond_init(): failed to initialize ArduinoMessenger::new_mesg_sig condition");
}
running = true;
if (pthread_create(&send_mesg_thread, NULL, &send_mesg_loop, (void*)this) == -1)
{
printf("Error: ArduinoMessenger(): pthread_create(): failed to create background transfer thread: %d\n", errno);
close(uart_gateway);
throw runtime_error("pthread_create(): failed to create background transfer thread");
}
}
ArduinoMessenger::~ArduinoMessenger()
{
if (send_mesg_thread)
{
pthread_mutex_lock(&write_lock);
running = false;
pthread_mutex_unlock(&write_lock);
pthread_cond_signal(&new_mesg_sig);
pthread_join(send_mesg_thread, NULL);
pthread_cond_destroy(&new_mesg_sig);
pthread_mutex_destroy(&write_lock);
pthread_mutex_destroy(&new_mesg_lock);
}
if (uart_gateway)
{
close(uart_gateway);
}
}
int ArduinoMessenger::buf_to_mesg(struct PWMMesg& mesg, int address, const void* buf, int size)
{
if (address >= MAX_ADDR || address < 0)
{
printf("Error: ArduinoMessenger.buf_to_mesg(): address %d is out of range\n", address);
return -1;
}
if (size >= MAX_MESG_SIZE || size < 1)
{
printf("Error: ArduinoMessenger.buf_to_mesg(): message size of %d bytes is out of range\n", size);
return -1;
}
mesg.address = (unsigned char)address;
mesg.bytes = (unsigned char)size - 1;
mesg.packets_num = (unsigned char)(size * 8 / 7);
if (size * 8 % 7 > 0)
{
mesg.packets_num += 1;
}
unsigned char* byte_buf = (unsigned char*)buf;
// translate the 8-bit per byte stream into 7-bit per byte stream
for (int index = 0; index < size; index++)
{
unsigned char next_byte = byte_buf[index];
unsigned char remainder_mask = 0x7F >> (6 - index % 7);
unsigned char new_bits_mask = 0xFE << (index % 7);
mesg.packets[index + index / 7] |= ((new_bits_mask & next_byte) >> (index % 7 + 1)) & 0x7F;
mesg.packets[index + index / 7 + 1] |= ((remainder_mask & next_byte) << (6 - index % 7));
}
mesg.checksum = mesg.packets[0] ^ mesg.packets[1];
for (int index = 2; index < mesg.packets_num; index++)
{
mesg.checksum ^= mesg.packets[index];
}
mesg.checksum &= 0x7F; // ensure top bit is clear
mesg.header = 0x80 | (mesg.address << 4) | mesg.bytes;
return 0;
}
void display_mesg(const struct PWMMesg& mesg)
{
for (int bit = 0; bit < 8; bit++)
{
if (bit % 4 == 0)
{
printf(" ");
}
char digit = '0';
if (mesg.header & (0x80 >> bit))
{
digit = '1';
}
printf("%c", digit);
}
printf(" ");
for (int packet = 0; packet < mesg.packets_num; packet++)
{
for (int bit = 0; bit < 8; bit++)
{
if (bit % 4 == 0)
{
printf(" ");
}
char digit = '0';
if (mesg.packets[packet] & (0x80 >> bit))
{
digit = '1';
}
printf("%c", digit);
}
printf(" ");
}
for (int bit = 0; bit < 8; bit++)
{
if (bit % 4 == 0)
{
printf(" ");
}
char digit = '0';
if (mesg.checksum & (0x80 >> bit))
{
digit = '1';
}
printf("%c", digit);
}
printf("\n");
}
int ArduinoMessenger::send_mesg(int address, const void* buf, int size)
{
struct PWMMesg mesg;
memset(&mesg, 0, sizeof(struct PWMMesg));
if (buf_to_mesg(mesg, address, buf, size) == -1)
{
return -1;
}
//display_mesg(mesg);
pthread_mutex_lock(&write_lock);
mesg_queue.push(mesg);
pthread_mutex_unlock(&write_lock);
pthread_cond_signal(&new_mesg_sig);
return 0;
}
int ArduinoMessenger::send_mesg(const struct PWMMesg& mesg)
{
if (mesg.address >= MAX_ADDR)
{
printf("Error: ArduinoMessenger.send_mesg(): address %d is out of range\n", (int)mesg.address);
return -1;
}
if (mesg.bytes >= MAX_MESG_SIZE)
{
printf("Error: ArduinoMessenger.send_mesg(): message size of %d bytes is out of range\n", (int)mesg.bytes + 1);
return -1;
}
//display_mesg(mesg);
pthread_mutex_lock(&write_lock);
mesg_queue.push(mesg);
pthread_mutex_unlock(&write_lock);
pthread_cond_signal(&new_mesg_sig);
return 0;
}
| true |
e2d1eb3ff49602328b8af7b72a8ebb4a36e210cd | C++ | nishant-sachdeva/Snippets | /BST.cpp | UTF-8 | 3,015 | 3.5 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define get(a) ll a; cin >> a;
#define show(a) cout << a << endl;
#define full(p) p.begin(), p.end()
#define sz(a) ll(a.size())
struct node
{
int key;
int sum;
int number_of_students_before_this;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item , int sum, int number_of_students_before_this);
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->sum = sum;
temp->number_of_students_before_this = number_of_students_before_this;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key, int sum, int number_of_students_before_this)
{
/* If the tree is empty, return a new node */
if (node == NULL)
return newNode(key, sum, number_of_students_before_this); // key, sum_For_That_Key, number_of elements before that key
/* Otherwise, recur down the tree */
if (key < node->key)
{
node->sum += sum;
node->number_of_students_before_this++;
///////////////////// now we have updated the parameters , now we will put the node at the further apt place
node->left = insert(node->left, key, sum, number_of_students_before_this);
}
else if (key > node->key)
{
sum += node->sum;
number_of_students_before_this += node->number_of_students_before_this;
//////////////////// now we have updated the parameters , now we will put the node at the further apt place
node->right = insert(node->right, key, sum, number_of_students_before_this);
}
/* return the (unchanged) node pointer */
return node;
}
int number_of_students_before(struct node * root, int sum_limit)
{
if(!root)
return 0;
// we want the predecessor of the given sum_limit
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout<<fixed;
////////////////////////////////
get(n);
get(m);
struct node * root = NULL;
std::vector<int> vec;
for (int i = 0; i < n; ++i)
{
get(ni);
vec.push_back(ni);
}
// now we have all the guys ,,now we need to see who all need to fail
cout << 0 << " ";
insert(root, vec[0], vec[0], 0) ; //we assume that first guy will always passs
for(int i = 1 ; i<n ; i++)
{
int j = number_of_students_before(root, m - vec[i]);
// m -vec[i] marks bache hain, uske predecessor nikalna hai
//usla parameters will tell how many students will pass within that window
int students_who_fail = i - 1 - j;
cout << students_who_fail << " ";
insert(root, vec[i], vec[i], 0 );
}
cout << endl;
return 0;
}
| true |
865b01b4b82587e205f4ea1827c83bd7a1a0a511 | C++ | Aviral044/C-Codes-1 | /factorial/main.cpp | UTF-8 | 350 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
long findTrailingZeros(long n)
{
long count = 0;
for (long i = 5; n / i >= 1; i *= 5)
{count += n / i;}
return count;
}
int main()
{
int t,i;
cin>>t;
for(i=0;i<t;i++)
{
long f;long j;
cin>>f;
j=findTrailingZeros(f);
cout<<j<<"\n";
}
return 0;
}
| true |
98119bd7688ccfa1e6eeed76783997a1589ecc73 | C++ | poros666/cocos_2d_moba | /Classes/ArmorLayer.cpp | WINDOWS-1252 | 7,017 | 2.578125 | 3 | [] | no_license | #include"ArmorLayer.h"
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in StartSceneScene.cpp\n");
}
cocos2d::Layer* ArmorLayer::createLayer(Hero* owner)
{
auto layer = new(std::nothrow)ArmorLayer();
if (layer && layer->init(owner)) {
layer->autorelease();
return layer;
}
CC_SAFE_DELETE(layer);
return nullptr;
}
bool ArmorLayer::init(Hero* owner)
{
if (!Layer::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//weapon one
auto BuyOne = MenuItemImage::create(
"equipment/buy.png",
"equipment/buy.png",
CC_CALLBACK_1(ArmorLayer::menuArmorOneCallback, this,owner)
);
if (BuyOne == nullptr ||
BuyOne->getContentSize().width <= 0 ||
BuyOne->getContentSize().height <= 0)
{
problemLoading("'equipment/swordone.png' and 'equipment/swordone.png'");
}
else
{
BuyOne->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 275, origin.y + 660));
}
//weapontwo
auto BuyTwo = MenuItemImage::create(
"equipment/buy.png",
"equipment/buy.png",
CC_CALLBACK_1(ArmorLayer::menuArmorTwoCallback, this,owner)
);
if (BuyTwo == nullptr ||
BuyTwo->getContentSize().width <= 0 ||
BuyTwo->getContentSize().height <= 0)
{
problemLoading("'equipment/swordone.png' and 'equipment/swordone.png'");
}
else
{
BuyTwo->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 275, origin.y + 527));
}
//three
auto BuyThree = MenuItemImage::create(
"equipment/buy.png",
"equipment/buy.png",
CC_CALLBACK_1(ArmorLayer::menuArmorThreeCallback, this,owner)
);
if (BuyThree == nullptr ||
BuyThree->getContentSize().width <= 0 ||
BuyThree->getContentSize().height <= 0)
{
problemLoading("'equipment/swordone.png' and 'equipment/swordone.png'");
}
else
{
BuyThree->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 275, origin.y + 393));
}
//four
auto BuyFour = MenuItemImage::create(
"equipment/buy.png",
"equipment/buy.png",
CC_CALLBACK_1(ArmorLayer::menuArmorFourCallback, this,owner)
);
if (BuyFour == nullptr ||
BuyFour->getContentSize().width <= 0 ||
BuyFour->getContentSize().height <= 0)
{
problemLoading("'equipment/swordone.png' and 'equipment/swordone.png'");
}
else
{
BuyFour->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 275, origin.y + 260));
}
//Esc
auto Esc = MenuItemImage::create(
"equipment/esc.png",
"equipment/esc.png",
CC_CALLBACK_1(ArmorLayer::menuEscCallback, this)
);
if (Esc == nullptr ||
Esc->getContentSize().width <= 0 ||
Esc->getContentSize().height <= 0)
{
problemLoading("'equipment/esc.png' and 'equipment/esc.png'");
}
else
{
Esc->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 - 100, origin.y + 160));
}
//
//ͼƬ
auto ArmorOne = MenuItemImage::create("equipment/armorone.jpg", "equipment/armorone.jpg");
ArmorOne->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 - 125, origin.y + 660));
auto DescribeOne = MenuItemImage::create("equipment/Darmorone.png", "equipment/Darmorone.png");
DescribeOne->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 50, origin.y + 660));
auto PriceOne = MenuItemImage::create("equipment/100.png", "equipment/100.png");
PriceOne->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 210, origin.y + 660));
auto ArmorTwo = MenuItemImage::create("equipment/armortwo.jpg", "equipment/armortwo.jpg");
ArmorTwo->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 - 125, origin.y + 527));
auto DescribeTwo = MenuItemImage::create("equipment/Darmortwo.png", "equipment/Darmortwo.png");
DescribeTwo->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 50, origin.y + 527));
auto PriceTwo = MenuItemImage::create("equipment/300.png", "equipment/300.png");
PriceTwo->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 210, origin.y + 527));
auto ArmorThree = MenuItemImage::create("equipment/armorthree.jpg", "equipment/armorthree.jpg");
ArmorThree->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 - 125, origin.y + 393));
auto DescribeThree = MenuItemImage::create("equipment/Darmorthree.png", "equipment/Darmorthree.png");
DescribeThree->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 50, origin.y + 393));
auto PriceThree = MenuItemImage::create("equipment/500.png", "equipment/500.png");
PriceThree->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 210, origin.y + 393));
auto ArmorFour = MenuItemImage::create("equipment/armorfour.jpg", "equipment/armorfour.jpg");
ArmorFour->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 - 125, origin.y + 260));
auto DescribeFour = MenuItemImage::create("equipment/Darmorfour.png", "equipment/Darmorfour.png");
DescribeFour->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 50, origin.y + 260));
auto PriceFour = MenuItemImage::create("equipment/999.png", "equipment/999.png");
PriceFour->setPosition(Vec2(origin.x + visibleSize.width * 3 / 4 + 210, origin.y + 260));
auto menu = Menu::create(BuyOne, BuyTwo, BuyThree, BuyFour,
ArmorOne, ArmorTwo, ArmorThree, ArmorFour,
DescribeOne, DescribeTwo, DescribeThree, DescribeFour,
PriceOne, PriceTwo, PriceThree, PriceFour,
NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 3);
;
return true;
}
void ArmorLayer::menuArmorOneCallback(cocos2d::Ref* pSender, Hero* owner)
{
int money = owner->getGold();
if (money >= 100 && owner->equipment.size() < 6) {
owner->setGold(money - 100);
owner->setInitHealthPointsLimit(owner->getInitHealthPointsLimit() + 200);
owner->setHealthPoints(owner->getHealthPoints() + 200);
owner->equipment.push_back(31);
}
}
void ArmorLayer::menuArmorTwoCallback(cocos2d::Ref* pSender, Hero* owner)
{
int money = owner->getGold();
if (money >= 300 && owner->equipment.size() < 6) {
owner->setGold(money - 300);
owner->setInitHealthPointsLimit(owner->getInitHealthPointsLimit() + 500);
owner->setHealthPoints(owner->getHealthPoints() + 500);
owner->equipment.push_back(32);
}
}
void ArmorLayer::menuArmorThreeCallback(cocos2d::Ref* pSnender, Hero* owner)
{
int money = owner->getGold();
if (money >= 500 && owner->equipment.size() < 6) {
owner->setGold(money - 500);
owner->setInitHealthPointsLimit(owner->getInitHealthPointsLimit() + 900);
owner->setHealthPoints(owner->getHealthPoints() + 900);
owner->equipment.push_back(33);
}
}
void ArmorLayer::menuArmorFourCallback(cocos2d::Ref* pSender, Hero* owner)
{
int money = owner->getGold();
if (money >= 999 && owner->equipment.size() < 6) {
owner->setGold(money - 999);
owner->setInitHealthPointsLimit(owner->getInitHealthPointsLimit() + 2000);
owner->setHealthPoints(owner->getHealthPoints() + 2000);
owner->equipment.push_back(34);
}
}
void ArmorLayer::menuEscCallback(cocos2d::Ref* pSender)
{
this->removeFromParentAndCleanup(true);
}
| true |
6b0ac85b42852bbd1f45cdbec3467e2c1b401aeb | C++ | mehranagh20/ACM-ICPC | /uva/11088-End-up-with-More-Teams/11088-End-up-with-More-Teams.cpp | UTF-8 | 1,300 | 2.703125 | 3 | [] | no_license | //In The Name Of God
#include <bits/stdc++.h>
using namespace std;
bool func(int a, int b) { return a > b;}
int main() {
ios::sync_with_stdio(0);
int n, tc = 1;
while(cin >> n && n) {
cout << "Case " << tc++ << ": ";
vector<int> nums(n);
for(int i = 0; i < n; i++) cin >> nums[i];
if(n < 3) {
cout << "0\n";
continue;
}
sort(nums.begin(), nums.end(), func);
int ans = 0, tmp = 0;
vector<bool> vis (nums.size(), false);
for(int i = 0; i < n; i++) {
if(vis[i]) continue;
int j = n - 1;
bool f = false;
for(j; j > i; j--) {
if(vis[j]) continue;
for(int k = j - 1; k > i; k--){
if(vis[k]) continue;
if(nums[i] + nums[j] + nums[k] >= 20) {
ans++;
f = true;
vis[j] = vis[i] = vis[k] = true;
break;
}
else {
int tmp = k;
k = j;
j = tmp;
}
}
if(f) break;
}
}
cout << ans << endl;
}
return 0;
}
| true |
f41e73e55ba241b2947d17d5f0552e5cbc99e7ee | C++ | benrmn/AugmentedBinarySearchTree | /AugmentedBinarySearchTree.cpp | UTF-8 | 13,266 | 2.96875 | 3 | [] | no_license | /*****************************************
** File: AugmentedBinarySearchTree.cpp
** Project: CSCE 221 Project 2
** Author: Benjamin Ramon
** Date: 03/05/2020
** Section: 518
** E-mail: bramon24@tamu.edu
**
** C++ file:
** Breif Description of the file
** conains all methods that need to be implemented for our binary search tree
**
*****************************************
**note: I know there is an issue with remove residue, I assure that remove residue is working,
** worked when I tested on some other sample, but for some reason, print levels is doing something wrong command
** I did not have time to figure it out with out causing my program to segfault, this also makes isPerfect
** to be wrong, but again it works with other examples with no dummy nodes, I know I will recieve points off
** but hopefully if you see this you can see that my logic should be correct for those functions, just print numLevels
** should be a bit off for some of the outputs
*******************************************/
#ifndef AUGMENTED_BINARY_SEARCH_TREE_CPP_
#define AUGMENTED_BINARY_SEARCH_TREE_CPP_
#include "AugmentedBinarySearchTree.h"
#include <cmath>
using namespace std;
// constructor
template <class Comparable>
AugmentedBinarySearchTree<Comparable>::AugmentedBinarySearchTree() :
root(NULL)
{
//no code
}
// copy constructor
template <class Comparable>
AugmentedBinarySearchTree<Comparable>::
AugmentedBinarySearchTree(const AugmentedBinarySearchTree<Comparable> & rhs) :
root(NULL)
{
*this = rhs; //checs self assignment
}
// destructor
template <class Comparable>
AugmentedBinarySearchTree<Comparable>::~AugmentedBinarySearchTree()
{
makeEmpty();// calls make empty bootstrap
}
// make empty bootstrap - callls internal method of makeEmpty
template <class Comparable>
void AugmentedBinarySearchTree<Comparable>::makeEmpty()
{
makeEmpty(root); // calls make empty with internal method
}
//make empty-internal method, acts as our clear function for the desructor
template <class Comparable>
void AugmentedBinarySearchTree<Comparable>::
makeEmpty(BinaryNode<Comparable> * & t) const
{
if (t != NULL)
{
// recusursivley iterates through the tree to delete each node
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t = NULL;
}
// find min stuff
template <class Comparable>
BinaryNode<Comparable> * AugmentedBinarySearchTree<Comparable>::
findMin(BinaryNode<Comparable> *t) const
{
// iterates through the left of the tree until the child is null, aka a leaf
if (t == NULL)
return NULL;
if (t->left == NULL)
return t;
return findMin(t->left);
}
// insert boostrap
template<class Comparable>
int AugmentedBinarySearchTree<Comparable>::
insert(const Comparable & x) {
return insert(x, root);// calls interanl method for insert
}
//internal method for insert
template <class Comparable>
int AugmentedBinarySearchTree<Comparable>::
insert(const Comparable & x, BinaryNode<Comparable> * & t) const {
int idx;// need to keep track of the size of each tree and sub tree
if (t == NULL) { t = new BinaryNode<Comparable>(x, NULL, NULL, 1); return 1; }//complete insert
else if (x < t->element) { idx = insert(x, t->left); }//iterates through tree
else if (t->element < x) { idx = insert(x, t->right); }
else { return 0; }//duplicate
if (idx == 0) { return 0; }//duplicate
else { t->m_size++; return 1; }// complete insert
return -1;
}
// remove bootstrap
template <class Comparable>
int AugmentedBinarySearchTree<Comparable>::remove(const Comparable & x) {
return remove(x, root);//calls internal method for bootstrap
}
//internal method for remove
template <class Comparable>
int AugmentedBinarySearchTree<Comparable>::
remove(const Comparable & x, BinaryNode < Comparable > * & t) const {
int idx;//keep track of the size of each tree
if (t == NULL) { return 0; }//size 0
if (x < t->element) { idx = remove(x, t->left); }//iterate through tree
else if (t->element < x) { idx = remove(x, t->right); }
else {
if (t->left != NULL && t->right != NULL) {//check if it is a leaf
t->element = findMin(t->right)->element;
remove(t->element, t->right);
} else {//any other case
BinaryNode <Comparable> *oldNode = t;
t = (t->left != NULL) ? t->left : t->right;
delete oldNode;//actually deletes the node
}
return 1;
}
if (idx == 0) { return 0; }
else { t->m_size--; return 1; }//decrement size
}
// Nthelement bootstrap
template<class Comparable>
const Comparable & AugmentedBinarySearchTree<Comparable>::
NthElement(int n) {
// checks if tree is empty and if our n is greater than our size, i.e. cannot check for n element if
// greater than size
if (root == NULL) throw NULLArguemntException("No nth element for tree of zero size. ");
if (n > root->m_size) throw ItemNotFound("There does not exist an nth element in the BST.");
int nodesVisited = 1;
int* nv_ptr = &nodesVisited;//create a pointer to our nodesVisited
return NthElement(root, nv_ptr, n)->element;
}
// internal method for nth elelemnt
template<class Comparable>
BinaryNode<Comparable> * AugmentedBinarySearchTree<Comparable>::
NthElement(BinaryNode<Comparable> *t, int *nodesVisited, int n) const {
if (t->left) {// recur left
BinaryNode<Comparable>* temp = NthElement(t->left, nodesVisited, n);
if (temp) return temp;
}
if (*nodesVisited == n) return t;//found
++(*nodesVisited);// increment nodes visiited
if (t->right) {// recur right
BinaryNode<Comparable>* temp = NthElement(t->right, nodesVisited, n);
if (temp) return temp;
}
return NULL;
}
// rank bootstrap
template<class Comparable>
int AugmentedBinarySearchTree<Comparable>::
Rank(const Comparable & x) {
// check if tree is empty
if (root == NULL) throw NULLArguemntException("No rank for tree of zero size. ");
int nodesVisited = 0;
int* nv_ptr = &nodesVisited;
Rank(x, root, nv_ptr);
// check if we are at the begining or end of our tree
if ((nodesVisited == root->m_size && NthElement(root->m_size) != x) ||
(nodesVisited == 0 && NthElement(1) != x)) {
throw NodeNotFound("BST does not contain element " + to_string(x));
}
return nodesVisited;
}
template<class Comparable>
void AugmentedBinarySearchTree<Comparable>::
Rank(const Comparable & x, BinaryNode<Comparable> *t, int *nodesVisited) const {
if (t != NULL) {
Rank(x, t->left, nodesVisited);// recur left
if (t->element > x) { return; }//checks if we need to stop when iterating
++(*nodesVisited);//increment counter
if (t->element == x) { return; }//found
Rank(x, t->right, nodesVisited);//recur right
} else {
return;
}
}
// median boostrap
template<class Comparable>
const Comparable & AugmentedBinarySearchTree<Comparable>::
Median() {
// empty tree
if (root == NULL) throw NULLArguemntException("No median value for a tree of zero size.");
int nodesVisited = 1;
int* nv_ptr = &nodesVisited;// create our poitner to nodesVisited
if (root->m_size%2==0) {// need 2 cases for where our indexing of the tree could fall
Comparable fst = NthElement(root,nv_ptr,(root->m_size/2))->element;
Comparable sst = NthElement(root,nv_ptr,(root->m_size/2)+1)->element;
return (fst < sst) ? fst : sst;// returns the smaller value at index of the tree
} else {
return NthElement(root,nv_ptr,(root->m_size/2)+1)->element;
}
}
// isPerfect bootstrap
template<class Comparable>
bool AugmentedBinarySearchTree<Comparable>::
IsPerfect() {
if (root->m_size==1) return true; //tree of size one is always perfect
int height = getHeight(root); //call function to get the height of the tree
queue <BinaryNode<Comparable>*> q;//instantiat
q.push(root);// push the root
return IsPerfect(q, height);
}
//internal method
template<class Comparable>
bool AugmentedBinarySearchTree<Comparable>::
IsPerfect(queue <BinaryNode<Comparable> *> q, int height) {
int lvlIdx = 1;
int numN = 0;
while (!q.empty()) {// while the queue is not empty
if (numN == pow(2, height) - 1) {// check if we need to go down a level
lvlIdx++;
if (lvlIdx - 1 == height) {
break;
}
}
BinaryNode<Comparable>* cur = q.front();// grabs first element of queue
if (!cur->left && !cur->right) {// checks if children exist(a leaf)
if (lvlIdx != height) {
return false;
}
} else {// any other node on a given level
if (!(cur->left && cur->right)) {
return false;
}
}
numN++;// counter to chekc number of nodes on each level
q.pop();// pop cur, enqueue the next set of data
q.push(cur->left);
q.push(cur->right);
}
return true;// if we get through everything it is a perfect tree
}
// printlevels bootstrap
template<class Comparable>
void AugmentedBinarySearchTree<Comparable>::
PrintLevels(int numLevels) {
// same thing as bootstrap for isperfect
queue <BinaryNode<Comparable>*> q;
q.push(root);
PrintLevels(q, numLevels);
}
// print level s internal
template<class Comparable>
void AugmentedBinarySearchTree<Comparable>::
PrintLevels(queue <BinaryNode<Comparable> * > q, int levels) {
int lvlIdx = 0;
int numN = 0;
//std::cout << "\n\nLEVEL " << lvlIdx << ":" << std::endl;
while (!q.empty()) {// 2 cases, cur is null and is not null
BinaryNode<Comparable> * cur = q.front();
if (cur->element) {
if (numN == pow(2, lvlIdx) - 1) {// check curretn level
lvlIdx++;
if (lvlIdx == levels+1) {
break;
}
std::cout << "\n\nLEVEL " << lvlIdx - 1<< ":" << std::endl;
}
BinaryNode<Comparable>* parent = getP(cur);// get the parent of a node
if (parent->element) {
if (cur == root) {// if the root is what we are printing hard coded output
std::cout << "(" << cur->element << ", " << cur->m_size << ", NULL) ";
} else {
std::cout << "(" << cur->element << ", " << cur->m_size << ", " << parent->element << ") ";
}
} else {
std::cout << "(" << cur->element << ", " << cur->m_size << ", NULL) ";
}
} else { // if cur is NULL
if (numN == pow(2, lvlIdx) - 1) {
lvlIdx++;
if (lvlIdx == levels+1) {
break;
}
std::cout << "\n\nLEVEL " << lvlIdx - 1<< ":" << std::endl;
}
BinaryNode<Comparable>* parent = getP(cur);
if (parent->element || parent->element>10000) {
std::cout << "(NULL, NULL, NULL) ";
} else {
std::cout << "(NULL, NULL, " << parent->element << ") ";
}
}
numN++;// increase number of total nodes
q.pop();
if (cur->left) {// push left, if mull make a new dummy node with null
q.push(cur->left);
} else {
BinaryNode<Comparable> * dummyNode = new BinaryNode<Comparable>(0, NULL, NULL);
q.push(dummyNode);
cur->left = dummyNode;
}
if (cur->right) {// push right, then do same as left
q.push(cur->right);
} else {
BinaryNode<Comparable> * dummyNode = new BinaryNode<Comparable>(0, NULL, NULL);
q.push(dummyNode);
cur->right = dummyNode;
}
}
std::cout << std::endl;
}
// removeresidue bootstrap
template<class Comparable>
int AugmentedBinarySearchTree<Comparable>::
RemoveResidue() {
int d = 0;
int* deletions = &d;// pointer to deleetions
RemoveResidue(root, deletions);
return d;
}
// removeresidue internal
template<class Comparable>
void AugmentedBinarySearchTree<Comparable>::
RemoveResidue(BinaryNode<Comparable> * & t, int *deletions) const {
if (t!=NULL) {//if roo tis not null or iterating till null
RemoveResidue(t->left,deletions);// iterate left
if (t->left) {
if (!t->left->element) {// if element is null instanttiated by print levels
delete t->left;//delete node
t->left = NULL;
++(*deletions);// increment deletions
}
}
// do same as left with right to iterate through tree
RemoveResidue(t->right,deletions);// iterate right
if (t->right) {
if (!t->right->element) {// if element is null instanttiated by print levels
delete t->right;// delete node
t->right = NULL;
++(*deletions);
}
}
}
}
// height stuff
template<class Comparable>
int AugmentedBinarySearchTree<Comparable>::
getHeight(BinaryNode<Comparable>* t) {
// getter function to get hieght of a given tree
if (t == NULL) { return 0; }
int lH = getHeight(t->left);
int rH = getHeight(t->right);
return (lH < rH) ? (1 + rH) : (1 + lH);
}
// bootstrap for geting the parent of a node
template<class Comparable>
BinaryNode<Comparable>* AugmentedBinarySearchTree<Comparable>::
getP(BinaryNode<Comparable>* p) {
return findP(root,p);
}
// find parent internal
template<class Comparable>
BinaryNode<Comparable>* AugmentedBinarySearchTree<Comparable>::
findP(BinaryNode<Comparable>* t, BinaryNode<Comparable>* p) {
if (t) {// if our node is not null
if (t->left == p || t->right == p) { return t; }// check if found
else {
if (t->element < p->element) { return findP(t->right, p); }//iterate right
else { return findP(t->left, p); }//iterate left
}
}
// I am getting a makefile warning for not returning anthing, but if i return nullptr or null i segfault
}
#endif
| true |
e30f17afdd182ab4d6c0ae93bdd87553157a7d8c | C++ | alexandraback/datacollection | /solutions_5731331665297408_0/C++/BrightDays/c.cpp | UTF-8 | 1,793 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <math.h>
#include <utility>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
bool g[10];
string ans = "";
string code[10];
int u[10];
vector<bool> f[10];
vector<pair<int,int> > a[10];
int n,m;
bool T = false;
int check(int v)
{
int p = -1;
for(int i = 0; i<n;i++)
if (g[u[i]]==false)
{
p = u[i];
break;
}
if (p==-1) return -1;
for(int e = 0;e<n;e++)
{
for(int i = 0; i < a[v].size(); i++)
{
if (a[v][i].first==p && a[v][i].second == 1)
{
g[p]=true;
p = check(p);
if (p==-1) return -1; else
break;
}
}
}
return p;
}
void check_code()
{
string s="";
for(int i = 0;i<n;i++)
s+=code[u[i]];
if (ans=="") ans=s; else
{
for(int i = 0;i<ans.length();i++)
{
if (ans[i]==s[i]) continue;
if (ans[i]< s[i]) return;
ans = s;
return;
}
}
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int t;
cin >> t;
for(int q = 1;q <=t;q++)
{
cin >> n >> m;
for(int i=0;i<10;i++)
{
f[i].clear();
a[i].clear();
g[i] = false;
}
ans="";
for(int i=0;i<n;i++)
{
cin >> code[i];
}
for(int i=0;i<m;i++)
{
int x,y;
cin >> x >> y;
x--;
y--;
a[x].push_back(make_pair(y,1));
f[x].push_back(false);
a[y].push_back(make_pair(x,1));
f[y].push_back(false);
}
for(int i=0;i<n;i++)
u[i] = i;
do{
g[u[0]]=true;
if (check(u[0])==-1)
check_code();
for(int j=0;j<n;j++)
g[j] = false;
}while(next_permutation(u,u+n));
cout <<"Case #" << q << ": " << ans << endl;
}
return 0;
} | true |
cf41a2f62c37dcdfc76d3cf07c8730bb3bc60a7d | C++ | Sathler/desimpalgo | /8_F.cpp | UTF-8 | 281 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
long long fp, fh, v, a, f, i=1;
while(cin >> fp >> fh){
f = fp + fh;
a = (5*fp + 6*fh)/2;
v = a + 2 - f;
cout << "Molecula #" << i << ".:.\nPossui " << v << " atomos e " << a << " ligacoes\n" << endl;
i++;
}
}
| true |
ca352c678ac0ffbf1d456519bf96d88b63f27aa4 | C++ | scanberg/lab5 | /Entity3D.h | UTF-8 | 1,454 | 2.859375 | 3 | [] | no_license | #pragma once
#ifndef ENTITY3D_H
#define ENTITY3D_H
#include "Types.h"
#include "DrawableObject.h"
#define TEXTUREID_UNUSED 0
class Entity3D
{
protected:
vec3 position;
vec3 orientation;
f32 scale;
vec3 color;
Entity3D *parent;
DrawableObject *drawObj;
u32 textureID;
public:
Entity3D() : scale(1.0f), color(1.0f), parent(NULL), drawObj(NULL), textureID(TEXTUREID_UNUSED) {}
virtual ~Entity3D() {}
void setPosition(f32 x, f32 y, f32 z) { position = vec3(x,y,z); }
void setPosition(const vec3 &pos) { position = pos; }
void setOrientationXYZ(f32 x, f32 y, f32 z) { orientation = vec3(x,y,z); }
void setOrientationXYZ(const vec3 &ori) { orientation = ori; }
void setScale(f32 s) { scale = s; }
void setColor(f32 r, f32 g, f32 b) { color = vec3(r,g,b); }
void setDrawable(DrawableObject *_drawObj){ drawObj = _drawObj; }
void setTexture(u32 _tex) { textureID=_tex; }
vec3 getPosition() { return position; }
vec3 getOrientationXYZ() { return orientation; }
f32 getScale() { return scale; }
void rotate(f32 x, f32 y, f32 z) { orientation += vec3(x,y,z); }
void rotate(const vec3 &v) { orientation += v; }
void translate(f32 x, f32 y, f32 z) { position += vec3(x,y,z); }
void translate(const vec3 &v) { position += v; }
mat4 getLocalMatrix();
mat4 getWorldMatrix();
virtual void draw();
void writeData();
void getData();
};
#endif
| true |
ed9bc0f5b320d2b528a1e9e0c62cf1dbb60854f0 | C++ | increedBull7/Cpp_city | /Data_Structure/Array/String03countingNumberofWordstring.cpp | UTF-8 | 617 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
string s = "Hello World, How are YOU?";
int vowel = 0;
int word = 1;
for(int i = 0; s[i] != '\0'; i++){
if((s[i] >= 65 && s[i] <= 90) || (s[i] >= 97 && s[i] <= 122)){
if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')
vowel++;
}
if(s[i] == ' ' && s[i - 1] != ' ')
word++;
}
cout<<"Number of vowels are: "<<vowel<<endl;
cout<<"Number of word are: "<<word<<endl;
} | true |
99a2c0d7c9041f79ae422fd47cc986c63e96a2fd | C++ | Barsane/barsane | /lib/include/Node.hxx | UTF-8 | 2,287 | 2.875 | 3 | [] | no_license |
inline Node::Node(Indexer<Symbol>* tokens): indexer(tokens) {
__indexers__.insert(tokens);
};
inline Node::~Node() {
set<Indexer<Symbol>*>::iterator it;
if (__indexers__.count(indexer)) {
delete indexer;
__indexers__.erase(indexer);
}
}
inline bool Node::validate(bool cond, string msg) {
if (!nextIf(cond)) {
unsigned int line = current()->getLine();
unsigned int colon = current()->getColon();
Error syntax = Error(SYNTAX_ERROR, msg, line, colon);
errorHandler.add(syntax);
jump(SEMI_COLON);
return false;
}
return true;
}
inline void Node::jump(SymbolType type) {
while (!indexer->end() && current()->getType() != type) {
indexer->next();
}
}
inline Symbol* Node::current() {
Symbol* current = indexer->current();
if (current)
return current;
string unknown = "";
static Symbol symbol = Symbol(unknown, 1, 1);
return &symbol;
}
inline bool Node::nextIf(const bool cond) {
if (indexer->end()) {
unsigned int line = current()->getLine();
unsigned int colon = current()->getColon();
Error missing = Error(MISSING_TOKEN, "Missing delimiter ;", line, colon);
errorHandler.add(missing);
return false;
}
if (cond) {
indexer->next();
return true;
}
return false;
}
inline bool Node::grantNext(const bool cond) {
return !indexer->end() && cond;
}
inline bool Node::isFactor() {
str token = str(current()->getToken());
return current()->isMinus() ||
current()->isId() ||
token.isNumeric() ||
current()->isLeftBracket();
}
inline bool Node::isExpression() {
return isFactor() || current()->isValue();
}
inline bool Node::isDeclaration() {
unsigned int pos = indexer->position();
bool isOk = nextIf(current()->isId()) && grantNext(current()->isColon());
indexer->reindex(pos);
return isOk;
}
inline bool Node::isAffect() {
unsigned int pos = indexer->position();
bool isOk = nextIf(current()->isId()) && grantNext(current()->isAssignment());
indexer->reindex(pos);
return isOk;
}
inline bool Node::isBuiltin() {
return grantNext(current()->isPrint());
}
| true |
7f3ccca7a92ff1c7ad4e05cb5a16146b22ccbe78 | C++ | Jackpon/Data-Structures | /Stack_栈/LinkStack.h | GB18030 | 545 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
typedef char ElemType;
struct SNode
{ //ջ
ElemType data; //
struct SNode *next; //ָ̽
};
//ʼջ
int InitStack(SNode* &top);
//ջ
int StackEmpty(SNode *top);
//ջ
int Push(SNode *top, ElemType item);
//ջ
int Pop(SNode *top, ElemType &item);
//ȡջ
int GetTop(SNode *top, ElemType &item);
//ͷջ
void Destroy(SNode *&top);
//
int TraverseStack(SNode *top);
//
int IsReverse(char *s); | true |
a08afc00410a9d9de89fb36f1d081fca6e78ea75 | C++ | atskae/gameboy-emulator | /src/CPU.h | UTF-8 | 1,072 | 2.921875 | 3 | [] | no_license | #ifndef GB_CPU_H
#define GB_CPU_H
#include "Insn.h"
#define NUM_REGS 8 // four 16-bit registers, each can be split in half
#define MEMORY_SIZE 0xFFFF // p,8
#define ROM_START_ADDR 0x0100 // p.10
class CPU {
private:
// instruction set table
Insn* insn_table[16][16];
Insn* cb_insn_table[16][16]; // insn with CB prefix
// registers (p.61)
unsigned short regs[NUM_REGS/2]; // 8-bit registers ; use enum reg to index into regs[]
unsigned short pc; // 16-bit program counter
unsigned short sp; // 16-bit stack pointer
char memory[MEMORY_SIZE];
int rom_size; // in bytes
public:
// constructor
CPU(const char* rom_name);
// methods
void read_opcodes_file(std::string filename, bool is_cb);
unsigned short read_reg(operand_t reg);
void write_reg(operand_t reg, unsigned short val);
void print(short mem_start); // print CPU state and memory specified by parameters
void print_mem(int start, int end);
Insn decode(); // decodes 1 instruction at pc
void execute(Insn insn);
// destructor
~CPU();
};
#endif // GB_CPU_H
| true |
80983794095cfceaddca7e2f78b2422a50a29bb5 | C++ | tessus/apachetop | /src/filters.h | UTF-8 | 623 | 3.0625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef _FILTERS_H_
#define _FILTERS_H_
/* Filter class
**
** Each instance has one filter, which is either plaintext or regular
** expression (if HAVE_PCRE2_H is defined): Quick example:
**
** f = new Filter();
** f->store("(movies|music)");
** if (f->isactive() && f->match("some string with movies in it"))
** // you got a match
*/
class Filter
{
public:
Filter(void);
~Filter(void);
void store(const char *filter);
bool isactive(void);
bool match(const char *string);
void empty(void);
private:
char *filter_text;
#if HAVE_PCRE2_H
bool regex_isvalid;
RegEx *regexp;
#endif
};
#endif /* _FILTERS_H_ */
| true |
40a8a43956a9bfe072da15d477a542093a72040d | C++ | varaste/Data-Structure | /Part 1/matadd.cpp | UTF-8 | 1,224 | 3.546875 | 4 | [] | no_license | #include <iostream.h>
int count =0;
void add (float (*a)[7], float (*b)[7], float (*c)[7], int m, int n)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
c[i][j] = a[i][j] + b[i][j];
}
void cadd (float (*a)[7], float (*b)[7], float (*c)[7], int m, int n)
{
for (int i = 0 ; i < m; i++)
{
count++; // for for i
for (int j = 0; j < n; j++)
{
count++; // for for j
c[i][j] = a[i][j] + b[i][j];
count++; // for assignment
}
count++; // for last time of for j
}
count++; // for last time of for i
}
void conly (float (*a)[7], float (*b)[7], float (*c)[7], int m, int n)
{
for (int i = 0; i < m; i++)
{
count+=2;
for (int j = 0; j < n; j++)
count += 2;
}
count++;
}
main()
{
float a[8][7], b[8][7], c[8][7];
a[0][0] = 1.3; a[0][1] = 2.43; a[0][2] = 3.1;
a[1][0] = 4; a[1][1] = 5; a[1][2] = 6;
b[0][0] = -1.3; b[0][1] = -2.43; b[0][2] = -3.1;
b[1][0] = -4; b[1][1] = -5; b[1][2] = -6;
cadd(a,b,c,2,3);
cout << c[0][0] << "," << c[0][1] << "," << c[0][2] << endl;
cout << c[1][0] << "," << c[1][1] << "," << c[1][2] << endl;
cout << count << endl;
conly(a,b,c,2,3);
cout << "count = " << count << endl;
}
| true |
91873e35bdba4008a07d297640b2bef247de5d45 | C++ | t16cs054/Perceptron | /simple_perceptron.cpp | UTF-8 | 10,980 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<fstream>//ファイル読み込み用
#include<sstream>//文字列を数値へ変換する
//#include<stdio.h>
//#include<string>
#include<map>//map用
//#include<stdlib.h>
using namespace std;
class Iris{
private:
static const double p = 0.25;//学習率
static const int articles = 150;//全データ
static const int feature = 4;//菖蒲の特徴数
static const int species = 3;//分類する菖蒲の種類
public:
//アヤメの特徴を格納する配列
string Iris_data[articles][feature+1];
double Iris_setosa[articles/species][feature];
double Iris_versicolor[articles/species][feature];
double Iris_virginica[articles/species][feature];
//拡張重みベクトル
double w[5];
void readIris();//ファイルの読み込みを行う
bool simple_perceptron();//setosaとversicolorを比較
bool simple_perceptron2();//setosaとvirginiaを比較
bool simple_perceptron3();//versicolorとvirginicaを比較
Iris(){
for(int i=0; i < feature+1; i++){ w[i] = 0.1;}//重みの初期化:全て0.1
};
};
//ファイルの読み込み////////////////////////////////////////////////////////////
void Iris::readIris(){
//データファイルを読み込む
ifstream ifs("bezdekIris.data");
// 開かなかったらエラー
if (!ifs){
cout << "Error! File can not be opened" << endl;
return;
}
string str = "";
int i = 0; // Iris[i][ ]のカウンタ。
int j = 0; // Iris[ ][j]のカウンタ。
// ファイルの中身を一行ずつ読み取る
while(getline(ifs, str)){
string tmp = "";
istringstream stream(str);
// 区切り文字がなくなるまで文字を区切っていく
while (getline(stream, tmp, ',')){
// 区切られた文字がtmpに入る
Iris_data[i][j] = tmp;
j++;
}
j = 0;
i++;
}
//stringで読み込んでいるので,stringstreamでstring型をdouble型に変換
for(int i=0; i < articles; i++){//菖蒲の数
for(int j=0; j < feature; j++){//特徴の数
stringstream buf;
buf << Iris_data[i][j];
double d;
buf >> d;
if(i<articles/species) Iris_setosa[i][j] =d;//sretosa
else if(i<(articles/species)*2)Iris_versicolor[i%50][j] =d;//versicolor
else if(i<articles)Iris_virginica[i%100][j] =d;//virginica
}
}
return;
}
////////////////////////////////////////////////////////////////////////////
//setosaとversicolorを識別////////////////////////////////////////
bool Iris::simple_perceptron(){
double sum1;
double sum2;
int complete = 0;//比較回数のカウンター(正しく分離できて入れば++)
double w1[5];//setosaの重み
double w2[5];//versicolorの重み
for(int i=0; i<5;i++){
w1[i] = w[i];
w2[i] = w[i]-0.1;
}
int times = 0;
while(times< 10000){
complete = 0;
// setosaの学習データに関する修正///////////////////////////////////////
for(int i=0; i<50; i++){
sum1 = 0;
sum2 = 0;
//setosa
for(int j=0; j<5; j++){
if(j==0)sum1 += 1*w1[j];//係数用
else sum1 += Iris_setosa[i][j-1]*w1[j];
}
//versicolor
for(int j=0; j<5; j++){
if(j==0)sum2 += 1*w2[j];
else sum2 += Iris_setosa[i][j-1]*w2[j];
}
//cout << sum1 << "-" << sum2 << endl;
//重みベクトルの修正
if(sum1-sum2 > 0)complete++;
else{
for(int j=0;j<5;j++){
if(j==0){
w1[j] = w1[j]+p*1;
w2[j] = w2[j]-p*1;
}else{
w1[j] = w1[j]+(p*Iris_setosa[i][j-1]);
w2[j] = w2[j]-(p*Iris_setosa[i][j-1]);
}
}
}
}
// versicolorの学習データに関する修正///////////////////////////////////
for(int i=0; i<50; i++){
sum1 = 0;
sum2 = 0;
//setosa
for(int j=0; j<5; j++){
if(j==0)sum1 += 1*w1[j];//係数用
else sum1 += Iris_versicolor[i][j-1]*w1[j];
}
//versicolor
for(int j=0; j<5; j++){
if(j==0)sum2 += 1*w2[j];
else sum2 += Iris_versicolor[i][j-1]*w2[j];
}
//cout << sum1 << "-" << sum2 << endl;
//重みベクトルの修正
if(sum1-sum2 < 0)complete++;
else{
for(int j=0;j<5;j++){
if(j==0){
w1[j] = w1[j]-p*1;
w2[j] = w2[j]+p*1;
}else{
w1[j] = w1[j]-(p*Iris_versicolor[i][j-1]);
w2[j] = w2[j]+(p*Iris_versicolor[i][j-1]);
}
}
}
}
if(complete == 100){
cout << times << "回繰り返し" << endl;
cout << "setosa:";
for(int i = 0; i<5; i++)
cout << w1[i] << ", ";
cout << endl;
cout << "versicolor:";
for(int i = 0; i<5; i++)
cout << w2[i] << ", ";
cout << endl;
for(int i = 0; i< 5; i++){
cout << w1[i]-w2[i] <<", ";
}
cout << endl;
return true;
}
times++;
}
cout <<times << "回繰り返し" << endl;
return false;
}
////////////////////////////////////////////////////////////////////////
//setosaとvirginicaを識別する///////////////////////////////////////////
bool Iris::simple_perceptron2(){
double sum1;
double sum2;
int complete = 0;
double w1[5];//setosaの重み
double w2[5];//virginicaの重み
for(int i=0; i<5;i++){
w1[i] = w[i];
w2[i] = w[i]-0.1;
}
int times = 0;
while(times< 10000){
complete = 0;
// setosaの学習データに関する修正///////////////////////////////////////
for(int i=0; i<50; i++){
sum1 = 0;
sum2 = 0;
//setosa
for(int j=0; j<5; j++){
if(j==0)sum1 += 1*w1[j];//係数用
else sum1 += Iris_setosa[i][j-1]*w1[j];
}
//virginica
for(int j=0; j<5; j++){
if(j==0)sum2 += 1*w2[j];
else sum2 += Iris_setosa[i][j-1]*w2[j];
}
//cout << sum1 << "-" << sum2 << endl;
//重みベクトルの修正
if(sum1-sum2 > 0)complete++;
else{
for(int j=0;j<5;j++){
if(j==0){
w1[j] = w1[j]+p*1;
w2[j] = w2[j]-p*1;
}else{
w1[j] = w1[j]+(p*Iris_setosa[i][j-1]);
w2[j] = w2[j]-(p*Iris_setosa[i][j-1]);
}
}
}
}
// virginicaの学習データに関する修正///////////////////////////////////
for(int i=0; i<50; i++){
sum1 = 0;
sum2 = 0;
//setosa
for(int j=0; j<5; j++){
if(j==0)sum1 += 1*w1[j];//係数用
else sum1 += Iris_virginica[i][j-1]*w1[j];
}
//virginica
for(int j=0; j<5; j++){
if(j==0)sum2 += 1*w2[j];
else sum2 += Iris_virginica[i][j-1]*w2[j];
}
//cout << sum1 << "-" << sum2 << endl;
//重みベクトルの修正
if(sum1-sum2 < 0)complete++;
else{
for(int j=0;j<5;j++){
if(j==0){
w1[j] = w1[j]-p*1;
w2[j] = w2[j]+p*1;
}else{
w1[j] = w1[j]-(p*Iris_virginica[i][j-1]);
w2[j] = w2[j]+(p*Iris_virginica[i][j-1]);
}
}
}
}
if(complete == 100){
cout << times << "回繰り返し" << endl;
cout << "setosa:";
for(int i = 0; i<5; i++)
cout << w1[i] << ", ";
cout << endl;
cout << "virginica:";
for(int i = 0; i<5; i++)
cout << w2[i] << ", ";
cout << endl;
for(int i = 0; i< 5; i++){
cout << w1[i]-w2[i] <<", ";
}
cout << endl;
return true;
}
times++;
}
cout <<times << "回繰り返し" << endl;
return false;
}
/////////////////////////////////////////////////////////////////////////
//versicolorとvirginicaを識別する///////////////////////////////////////
bool Iris::simple_perceptron3(){
double sum1;
double sum2;
int complete = 0;
double w1[5];//versicolorの重み
double w2[5];//virginicaの重み
for(int i=0; i<5;i++){
w1[i] = w[i];
w2[i] = w[i]-0.1;
}
int times = 0;
while(times< 10000){
complete = 0;
// vergicolorの学習データに関する修正///////////////////////////////////////
for(int i=0; i<50; i++){
sum1 = 0;
sum2 = 0;
//versicolor
for(int j=0; j<5; j++){
if(j==0)sum1 += 1*w1[j];//係数用?
else sum1 += Iris_versicolor[i][j-1]*w1[j];
}
//virginica
for(int j=0; j<5; j++){
if(j==0)sum2 += 1*w2[j];
else sum2 += Iris_versicolor[i][j-1]*w2[j];
}
//cout << sum1 << "-" << sum2 << endl;
//重みベクトルの修正
if(sum1-sum2 > 0)complete++;
else{
for(int j=0;j<5;j++){
if(j==0){
w1[j] = w1[j]+p*1;
w2[j] = w2[j]-p*1;
}else{
w1[j] = w1[j]+(p*Iris_versicolor[i][j-1]);
w2[j] = w2[j]-(p*Iris_versicolor[i][j-1]);
}
}
}
}
// virginicaの学習データに関する修正///////////////////////////////////
for(int i=0; i<50; i++){
sum1 = 0;
sum2 = 0;
//versicolor
for(int j=0; j<5; j++){
if(j==0)sum1 += 1*w1[j];//係数用?
else sum1 += Iris_virginica[i][j-1]*w1[j];
}
//virginica
for(int j=0; j<5; j++){
if(j==0)sum2 += 1*w2[j];
else sum2 += Iris_virginica[i][j-1]*w2[j];
}
//cout << sum1 << "-" << sum2 << endl;
//重みベクトルの修正
if(sum1-sum2 < 0)complete++;
else{
for(int j=0;j<5;j++){
if(j==0){
w1[j] = w1[j]-p*1;
w2[j] = w2[j]+p*1;
}else{
w1[j] = w1[j]-(p*Iris_virginica[i][j-1]);
w2[j] = w2[j]+(p*Iris_virginica[i][j-1]);
}
}
}
}
if(complete == 100){
cout << times << "回繰り返し" << endl;
cout << "versicolor:";
for(int i = 0; i<5; i++)
cout << w1[i] << ", ";
cout << endl;
cout << "virginica:";
for(int i = 0; i<5; i++)
cout << w2[i] << ", ";
cout << endl;
for(int i = 0; i< 5; i++){
cout << w1[i]-w2[i] <<", ";
}
cout << endl;
return true;
}
times++;
}
cout << times << "回繰り返し" << endl;
return false;
}
//////////////////////////////////////////////////////////////////
//main文/////////////////////////////////////////////////////////
int main(void){
Iris q;
q.readIris();
//特徴を出力する
/*
for(int i=0; i<150; i++){
for(int j=0; j<4; j++){
if(i < 50)cout << q.Iris_setosa[i][j] << ", ";
else if(i<100)cout << q.Iris_versicolor[i%50][j] << ", ";
else if(i<150)cout << q.Iris_virginica[i%100][j] << ", ";
}
cout << endl;
}
cout << endl;
*/
cout << "重みの初期値 : ";
for(int i = 0; i<5; i++)
cout << q.w[i] << ", ";
cout << endl;
for(int i=0;i<60;i++) cout <<"-";
cout <<endl;
if(q.simple_perceptron()){
cout << "線形分離可能である" <<endl;
}else{cout << "線形分離可能でないと判断" << endl;}
for(int i=0;i<60;i++) cout <<"-";
cout <<endl;
if(q.simple_perceptron2()){
cout << "線形分離可能である" <<endl;
}else{cout << "線形分離可能でないと判断" << endl;}
for(int i=0;i<60;i++) cout <<"-";
cout << endl;
if(q.simple_perceptron3()){
cout << "線形分離可能である" <<endl;
}else{cout << "線形分離可能でないと判断" << endl;}
return 0;
}
| true |
996e24ebecb4396708843312cac0974820a4ad33 | C++ | mlpack/mlpack | /src/mlpack/methods/ann/convolution_rules/naive_convolution.hpp | UTF-8 | 10,726 | 2.984375 | 3 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | /**
* @file methods/ann/convolution_rules/naive_convolution.hpp
* @author Shangtong Zhang
* @author Marcus Edel
*
* Implementation of the convolution.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_CONVOLUTION_RULES_NAIVE_CONVOLUTION_HPP
#define MLPACK_METHODS_ANN_CONVOLUTION_RULES_NAIVE_CONVOLUTION_HPP
#include <mlpack/prereqs.hpp>
#include "border_modes.hpp"
namespace mlpack {
/**
* Computes the two-dimensional convolution. This class allows specification of
* the type of the border type. The convolution can be compute with the valid
* border type of the full border type (default).
*
* FullConvolution: returns the full two-dimensional convolution.
* ValidConvolution: returns only those parts of the convolution that are
* computed without the zero-padded edges.
*
* @tparam BorderMode Type of the border mode (FullConvolution or
* ValidConvolution).
*/
template<typename BorderMode = FullConvolution>
class NaiveConvolution
{
public:
/**
* Perform a convolution (valid mode).
*
* @param input Input used to perform the convolution.
* @param filter Filter used to perform the convolution.
* @param output Output data that contains the results of the convolution.
* @param dW Stride of filter application in the x direction.
* @param dH Stride of filter application in the y direction.
* @param dilationW The dilation factor in x direction.
* @param dilationH The dilation factor in y direction.
* @param appending If true, it will not initialize the output. Instead,
* it will append the results to the output.
*/
template<typename eT, typename Border = BorderMode>
static typename std::enable_if<
std::is_same<Border, ValidConvolution>::value, void>::type
Convolution(const arma::Mat<eT>& input,
const arma::Mat<eT>& filter,
arma::Mat<eT>& output,
const size_t dW = 1,
const size_t dH = 1,
const size_t dilationW = 1,
const size_t dilationH = 1,
const bool appending = false)
{
// Compute the output size. The filterRows and filterCols computation must
// take into account the fact that dilation only adds rows or columns
// *between* filter elements. So, e.g., a dilation of 2 on a kernel size of
// 3x3 means an effective kernel size of 5x5, *not* 6x6.
if (!appending)
{
const size_t filterRows = filter.n_rows * dilationH - (dilationH - 1);
const size_t filterCols = filter.n_cols * dilationW - (dilationW - 1);
const size_t outputRows = (input.n_rows - filterRows + dH) / dH;
const size_t outputCols = (input.n_cols - filterCols + dW) / dW;
output.zeros(outputRows, outputCols);
}
// It seems to be about 3.5 times faster to use pointers instead of
// filter(ki, kj) * input(leftInput + ki, topInput + kj) and output(i, j).
eT* outputPtr = output.memptr();
for (size_t j = 0; j < output.n_cols; ++j)
{
for (size_t i = 0; i < output.n_rows; ++i, outputPtr++)
{
const eT* kernelPtr = filter.memptr();
for (size_t kj = 0; kj < filter.n_cols; ++kj)
{
const eT* inputPtr = input.colptr(kj * dilationW + j * dW) + i * dH;
for (size_t ki = 0; ki < filter.n_rows; ++ki, ++kernelPtr,
inputPtr += dilationH)
*outputPtr += *kernelPtr * (*inputPtr);
}
}
}
}
/**
* Perform a convolution (full mode).
*
* @param input Input used to perform the convolution.
* @param filter Filter used to perform the convolution.
* @param output Output data that contains the results of the convolution.
* @param dW Stride of filter application in the x direction.
* @param dH Stride of filter application in the y direction.
* @param dilationW The dilation factor in x direction.
* @param dilationH The dilation factor in y direction.
* @param appending If true, it will not initialize the output. Instead,
* it will append the results to the output.
*/
template<typename eT, typename Border = BorderMode>
static typename std::enable_if<
std::is_same<Border, FullConvolution>::value, void>::type
Convolution(const arma::Mat<eT>& input,
const arma::Mat<eT>& filter,
arma::Mat<eT>& output,
const size_t dW = 1,
const size_t dH = 1,
const size_t dilationW = 1,
const size_t dilationH = 1,
const bool appending = false)
{
// First, compute the necessary padding for the full convolution. It is
// possible that this might be an overestimate. Note that these variables
// only hold the padding on one side of the input.
const size_t filterRows = filter.n_rows * dilationH - (dilationH - 1);
const size_t filterCols = filter.n_cols * dilationW - (dilationW - 1);
const size_t paddingRows = filterRows - 1;
const size_t paddingCols = filterCols - 1;
// Pad filter and input to the working output shape.
arma::Mat<eT> inputPadded(input.n_rows + 2 * paddingRows,
input.n_cols + 2 * paddingCols, arma::fill::zeros);
inputPadded.submat(paddingRows, paddingCols, paddingRows + input.n_rows - 1,
paddingCols + input.n_cols - 1) = input;
NaiveConvolution<ValidConvolution>::Convolution(inputPadded, filter,
output, dW, dH, dilationW, dilationH, appending);
}
/**
* Perform a convolution using 3rd order tensors.
*
* @param input Input used to perform the convolution.
* @param filter Filter used to perform the convolution.
* @param output Output data that contains the results of the convolution.
* @param dW Stride of filter application in the x direction.
* @param dH Stride of filter application in the y direction.
* @param dilationW The dilation factor in x direction.
* @param dilationH The dilation factor in y direction.
* @param appending If true, it will not initialize the output. Instead,
* it will append the results to the output.
*/
template<typename eT>
static void Convolution(const arma::Cube<eT>& input,
const arma::Cube<eT>& filter,
arma::Cube<eT>& output,
const size_t dW = 1,
const size_t dH = 1,
const size_t dilationW = 1,
const size_t dilationH = 1,
const bool appending = false)
{
arma::Mat<eT> convOutput;
NaiveConvolution<BorderMode>::Convolution(input.slice(0), filter.slice(0),
convOutput, dW, dH, dilationW, dilationH, appending);
if (!appending)
output = arma::Cube<eT>(convOutput.n_rows, convOutput.n_cols,
input.n_slices);
output.slice(0) = convOutput;
for (size_t i = 1; i < input.n_slices; ++i)
{
NaiveConvolution<BorderMode>::Convolution(input.slice(i), filter.slice(i),
output.slice(i), dW, dH, dilationW, dilationH, appending);
}
}
/**
* Perform a convolution using dense matrix as input and a 3rd order tensors
* as filter and output.
*
* @param input Input used to perform the convolution.
* @param filter Filter used to perform the convolution.
* @param output Output data that contains the results of the convolution.
* @param dW Stride of filter application in the x direction.
* @param dH Stride of filter application in the y direction.
* @param dilationW The dilation factor in x direction.
* @param dilationH The dilation factor in y direction.
* @param appending If true, it will not initialize the output. Instead,
* it will append the results to the output.
*/
template<typename eT>
static void Convolution(const arma::Mat<eT>& input,
const arma::Cube<eT>& filter,
arma::Cube<eT>& output,
const size_t dW = 1,
const size_t dH = 1,
const size_t dilationW = 1,
const size_t dilationH = 1,
const bool appending = false)
{
arma::Mat<eT> convOutput;
NaiveConvolution<BorderMode>::Convolution(input, filter.slice(0),
convOutput, dW, dH, dilationW, dilationH, appending);
if (!appending)
output = arma::Cube<eT>(convOutput.n_rows, convOutput.n_cols,
filter.n_slices);
output.slice(0) = convOutput;
for (size_t i = 1; i < filter.n_slices; ++i)
{
NaiveConvolution<BorderMode>::Convolution(input, filter.slice(i),
output.slice(i), dW, dH, dilationW, dilationH, appending);
}
}
/**
* Perform a convolution using a 3rd order tensors as input and output and a
* dense matrix as filter.
*
* @param input Input used to perform the convolution.
* @param filter Filter used to perform the convolution.
* @param output Output data that contains the results of the convolution.
* @param dW Stride of filter application in the x direction.
* @param dH Stride of filter application in the y direction.
* @param dilationW The dilation factor in x direction.
* @param dilationH The dilation factor in y direction.x
* @param appending If true, it will not initialize the output. Instead,
* it will append the results to the output.
*/
template<typename eT>
static void Convolution(const arma::Cube<eT>& input,
const arma::Mat<eT>& filter,
arma::Cube<eT>& output,
const size_t dW = 1,
const size_t dH = 1,
const size_t dilationW = 1,
const size_t dilationH = 1,
const bool appending = false)
{
arma::Mat<eT> convOutput;
NaiveConvolution<BorderMode>::Convolution(input.slice(0), filter,
convOutput, dW, dH, dilationW, dilationH, appending);
if (!appending)
output = arma::Cube<eT>(convOutput.n_rows, convOutput.n_cols,
input.n_slices);
output.slice(0) = convOutput;
for (size_t i = 1; i < input.n_slices; ++i)
{
NaiveConvolution<BorderMode>::Convolution(input.slice(i), filter,
output.slice(i), dW, dH, dilationW, dilationH, appending);
}
}
}; // class NaiveConvolution
} // namespace mlpack
#endif
| true |