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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ea58141c17f5d12cc084b2044c57c281610e4c16 | C++ | yair-go/sadna-examples | /lesson1/Rect.h | UTF-8 | 722 | 3.359375 | 3 | [] | no_license |
// name:
// ID:
#pragma once
#ifndef RECT_H
#define RECT_H
#include<iostream>
using namespace std;
class Rect
{
private:
int length, width;
public:
//ctor
//Rect(){length=width=1;}
////Rect(int a, int b){length=a; width=b;}
//Rect(int a, int b):length(a),width(b){}
//Rect(int x){length=width=x;}
//Rect (int n=1){length =width = n;}
//Rect (int x=1, int y=1){length =x; width = y; }
Rect(int x = 1, int y = 1) :width(y), length(x){}
//dtor
~Rect();
void SetLength(int);
int GetLength(){return length;};
void SetWidth(int);
int getArea();
void Print(){cout<<"length= "<<length<<" , width= "<<width <<endl;};
bool equal(Rect r){return (length==r.length && width==r.width);}
};
#endif | true |
1d7fac089ba96989de9840f63a941b656afe97a5 | C++ | omssp/CollegePracticals | /DAAP/EXP8.cpp | UTF-8 | 1,687 | 3.578125 | 4 | [] | no_license | // prim's algorithm
#include "iostream"
#include "bits/stdc++.h"
class Prim {
private:
int V;
int **graph;
int *key;
int *parent;
bool *MSTset;
public:
Prim( int V ) {
this->V = V;
graph = new int*[V];
for (int i = 0; i < V; ++i) {
graph[i] = new int[V];
}
key = new int[V];
parent = new int[V];
MSTset = new bool[V];
for (int i = 0; i < V; ++i) {
key[i] = INT_MAX;
MSTset[i] = false;
}
key[0] = 0;
parent[0] = -1;
}
int minKey() {
int min = INT_MAX, min_index;
for (int i = 0; i < V; ++i)
if (MSTset[i] == false && key[i] < min)
min = key[i], min_index = i;
return min_index;
}
void primMST() {
for (int i = 0; i < V - 1; ++i) {
int u = minKey();
MSTset[u] = true;
for (int j = 0; j < V; ++j)
if (graph[u][j] && MSTset[j] == false && graph[u][j] < key[j])
parent[j] = u, key[j] = graph[u][j];
}
}
void display() {
int total_weight = 0;
std :: cout << "\n EDGE\tWeight\n";
for (int i = 1; i < V; ++i) {
std :: cout << " " << parent[i] << "->" << i << "\t"
<< graph[i][parent[i]] << std :: endl;
total_weight += graph[i][parent[i]];
}
std :: cout << "\n Total Weight : " << total_weight << std :: endl;
}
void input() {
std :: cout << "Enter The Graph in form of Matrix\n\t";
for (int i = 0; i < V; ++i) {
std :: cout << i << " ";
}
std :: cout << std :: endl;
for (int i = 0; i < V; ++i) {
std :: cout << " " << i << "\t";
for (int j = 0; j < V; ++j) {
std :: cin >> graph[i][j];
}
}
}
};
int main() {
int n;
std :: cout << "Enter the total Number of Vertices : ";
std :: cin >> n;
Prim a(n);
a.input();
a.primMST();
a.display();
return 0;
} | true |
aa36af3a0e9e3af3128e9c350c694b32396b22fe | C++ | hzhou/usaco | /1902/demo/revegetate_bronze.cpp | UTF-8 | 1,156 | 2.671875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cstdio>
#include <algorithm>
int main(int argc, char** argv)
{
FILE* In = fopen("revegetate.in", "r");
if (!In) {
fprintf(stderr, "Can't open In\n");
exit(-1);
}
int N;
int M;
fscanf(In, " %d %d" ,&N,&M);
int A[M];
int B[M];
for (int i = 0; i<M; i++) {
fscanf(In, " %d %d" ,&A[i],&B[i]);
A[i]--;
B[i]--;
if (A[i] > B[i]) {
int temp;
temp = A[i];
A[i] = B[i];
B[i] = temp;
}
}
fclose(In);
int F[N];
F[0] = 0;
for (int i = 1; i<N; i++) {
int P[4] = {0,0,0,0};
for (int j = 0; j<M; j++) {
if (B[j] == i) {
P[F[A[j]]]++;
}
}
std::cout<<"i="<<i<<'\n';
for (int j = 0; j<4; j++) {
if (P[j] == 0) {
F[i] = j;
break;
}
}
}
FILE* Out = fopen("revegetate.out", "w");
for (int j = 0; j<N; j++) {
fprintf(Out, "%d", F[j] + 1);
}
fprintf(Out, "\n");
fclose(Out);
return 0;
}
| true |
1b5d1e1612d20c1fd2887e628b347be92831a35a | C++ | CE-02FED/HARFS | /diskNodes/storageBlock.h | UTF-8 | 732 | 2.75 | 3 | [] | no_license | #ifndef RES_STORAGEBLOCK_H_
#define RES_STORAGEBLOCK_H_
#include <string>
#include "../res/structs/linkedList.h"
#include "../res/vector.h"
using namespace std;
class StorageBlock {
private: //Atributos
string _name;
int _tipo;
int _tipoRaid;
Vector<string>* _esquema;
/** Estructuras posibles */
LinkedList* _lista;
public: //Metodos
string getName();
StorageBlock();
StorageBlock(string pName, int pTipoEstructura, int pTipoRAID);
void definirEsquema(Vector<string>* pEsquema);
void almacenarRegistro(Vector<string>* pDato);
void borrarRegistro(int pDesplazamiento);
string buscar(string pClave, string pColumna);
string obtenerRegistro(int pDesplazamiento);
};
#endif /* RES_STORAGEBLOCK_H_ */
| true |
860bbcddf576f249d47ba33c51db56811603ea30 | C++ | zzz1114/Learn_OOP | /OOP/案例:制作饮品.cpp | GB18030 | 1,327 | 3.46875 | 3 | [] | no_license | //#include <iostream>
//
//// boil ˮ
//// crew
//// pour in cup 뱭
//
//class AbstractDrinking
//{
//public:
// //ĸ裺ˮ - - 뱭 - 븨
// void Water() { std::cout << "ˮ" << std::endl; }
// virtual void Crew() = 0;
// void PourInCup() { std::cout << "ݺˮ뱭 " << std::endl; }
// virtual void AddOther() = 0;
// void MakeDrink() {
// Water();
// Crew();
// PourInCup();
// AddOther();
// }
//};
//
//class Tea : public AbstractDrinking
//{
//public:
// void Crew() { std::cout << "ݲҶ" << std::endl; }
// void AddOther() { std::cout << "õ" << std::endl; }
//};
//
//class Coffee : public AbstractDrinking
//{
//public:
// void Crew() { std::cout << "ݿ" << std::endl; }
// void AddOther() { std::cout << "Ǻţ" << std::endl; }
//};
//
//void DoWork(AbstractDrinking* abs)
//{
// if (abs != NULL)
// abs->MakeDrink();
// delete abs;
// abs = NULL;
//}
//
//void DoWork(AbstractDrinking& abs)
//{
// abs.MakeDrink();
//}
//
//void test01()
//{
// Tea tea;
// Coffee coffee;
// DoWork(tea);
// DoWork(coffee);
//}
//
//int main()
//{
// test01();
// return 0;
//} | true |
d64068bb5036406b351ded9390be40146bd76b28 | C++ | emevonlou/philosophycpp | /src/06.cpp | UTF-8 | 734 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <locale.h>
using namespace std;
int main()
{
setlocale(LC_ALL, "");
char eme[] = {0x1b, '[', '1', ';', '3', '4', 'm', 0};
cout << eme;
int i = 6;
const char n = 'n';
for (i = 0; i <= 6; i++)
{
if (n)
{
cout << i << endl;
}
cout << "Friedrich Nietzsche" << endl;
cout << "O medo é o pai da moralidade." << endl;
cout << "Aquele que abandonou a Deus prende-se em redobrada severidade à crença na moral." << endl;
cout << "Através da moral conduz-se a humanidade mais facilmente pelo bico!" << endl;
}
cout << "Ate entao temos um 'tu deves'." << endl;
cout << "Precisamos de uma moral que nos entregue um 'tu sentes?'" << endl;
cout << endl;
return 0;
} | true |
99a58b8afdbd76ca005fdf91bc1d78ce2f027b01 | C++ | mrlzla/sarkisyan_labs | /lab3_2/customer.h | UTF-8 | 744 | 3.109375 | 3 | [] | no_license | #ifndef CUSTOMER_H
#define CUSTOMER_H
#include "basictypes.h"
class Customer
{
private:
std::map<std::string, boost::any> props;
public:
Customer(std::string name, std::string contact_phone, double revenue);
std::string GetName(){return boost::any_cast<std::string>(props["name"]);}
std::string GetContactPhone(){return boost::any_cast<std::string>(props["contact_phone"]);}
double GetRevenue(){return boost::any_cast<double>(props["revenue"]);}
void SetContactPhone(const std::string & contact_phone)
{
props["contact_phone"] = contact_phone;
}
void SetRevenue(const double revenue)
{
props["revenue"] = revenue;
}
void Print(std::string pattern);
};
#endif // CUSTOMER_H
| true |
09a873f735d8fcd7d349dea6038d9b48890aacf7 | C++ | MikeS96/autonomous_landing_uav | /drone_controller/include/drone_controller/pid.h | UTF-8 | 1,961 | 2.53125 | 3 | [
"MIT"
] | permissive | /**
* @file pid.h
* @author Miguel Saavedra (miguel.saaruiz@gmail@gmail.com)
* @brief PID controller header files
* @version 0.1
* @date 05-01-2020
*
* Copyright (c) 2020 Miguel Saavedra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef PID_H
#define PID_H
class PID
{
private:
double max; // max - maximum output value
double min; // min - minimum output value
double kp; // Kp - proportional gain
double kd; // Kd - derivative gain
double ki; // Ki - Integral gain
double pre_error; // Error at (t-1)
double integral; // Integral term
double pre_integral; // Integral term at (t-1)
public:
// Class constructor
PID(double cmax, double cmin, double ckp, double ckd, double cki);
// Compute PID output
double calculate( double setpoint, double pv, double cdt);
// Class destructor
~PID();
};
#endif
| true |
9144da044352202ce88d2c104d978122128ef8d9 | C++ | PrateekJain999/cpp-Codes | /B Multiple.cpp | UTF-8 | 601 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
class College
{
public:
string name;
void getname(string n)
{
name=n;
}
};
class Year
{
public:
int years;
void getyear(int y)
{
years=y;
}
};
class Student:public College,public Year
{
public:
int id;
void display(int i)
{
id=i;
cout<<name<<endl<<years<<endl<<id<<endl;
}
};
main()
{
Student o;
o.getname("Cu");
o.getyear(2000);
o.display(01);
}
| true |
21964fd15d6264a6175b654a11c16dc5b9bb29b1 | C++ | Good-Morning/echo | /client.cpp | UTF-8 | 1,721 | 2.734375 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
#include <exception>
#include <algorithm>
#include "utils.h"
int _main(int argc, char** argv) {
u_int32_t addr_ip4;
if (argc >= 2) {
addr_ip4 = get_ip4(argv[1]);
} else {
std::cout << "address to connect to: ";
std::string st;
std::cin >> st;
char* s = &st[0];
addr_ip4 = get_ip4(s);
}
socket_t sock;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(1337);
addr.sin_addr.s_addr = htonl(addr_ip4);
timeval timeout{2, 0};
if (-1 == setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))) {
throw std::runtime_error("While setting socket an error occurred: "_str + strerror(errno));
}
if (connect(sock, (sockaddr*)&addr, sizeof(addr)) < 0) {
throw std::runtime_error("While connecting an error occurred: "_str + strerror(errno));
}
while(true) {
std::cout << "enter message: ";
std::string st;
std::getline(std::cin, st);
std::cout << "sending" << std::endl;
blocking_send(sock, st);
if (st == "exit") {
break;
}
std::cout << "receiving..." << std::endl;
st = blocking_recv(sock);
std::cout << "received: " << st;
}
return 0;
}
int main(int argc, char** argv) {
try {
return _main(argc, argv);
} catch (std::runtime_error e) {
std::cerr << e.what();
return -1;
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
}
}
| true |
56700af21a91716f2db97534a90b801c871e0fdd | C++ | Mumbaikar007/Code | /Logics/Arduino's map.cpp | UTF-8 | 260 | 2.859375 | 3 | [] | no_license | //
// Created by optimus on 8/1/18.
//
# include <iostream>
using namespace std;
int main(){
int a = 1;
int b = 10;
int c = 1;
int d = 100;
int x = 5;
int y = ( (double) (x-a) / (b-a) ) * (d-c) + c;
cout << y;
return 0;
} | true |
b84839fcb194083234f883f90ebd7158a272ff81 | C++ | StefanFabian/ros_babel_fish | /ros_babel_fish/include/ros_babel_fish/babel_fish.h | UTF-8 | 6,855 | 2.625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2019 Stefan Fabian. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifndef ROS_BABEL_FISH_BABEL_FISH_H
#define ROS_BABEL_FISH_BABEL_FISH_H
#include "ros_babel_fish/generation/description_provider.h"
#include "ros_babel_fish/generation/message_template.h"
#include "ros_babel_fish/babel_fish_message.h"
#include "ros_babel_fish/message_description.h"
#include "ros_babel_fish/message_types.h"
#include <ros/publisher.h>
#include <ros/service_server.h>
namespace ros_babel_fish
{
/*!
* The Message internally points to the buffer of the BabelFishMessage, hence, this ensures that this buffer is not
* destroyed as long as the message exists or it is detached from the buffer using Message::detachFromStream.
*/
struct TranslatedMessage
{
typedef std::shared_ptr<TranslatedMessage> Ptr;
typedef std::shared_ptr<const TranslatedMessage> ConstPtr;
TranslatedMessage( IBabelFishMessage::ConstPtr input, Message::Ptr translated )
: input_message( std::move( input )), translated_message( std::move( translated )) { }
IBabelFishMessage::ConstPtr input_message;
Message::Ptr translated_message;
};
/*!
* Allows communication using message types that are not known at compile time.
*/
class BabelFish
{
public:
/*!
* Constructs an instance of BabelFish with a new instance of the default description provider.
* If you have to use multiple BabelFish instances, it is recommended to shae the description provider to
* prevent multiple look ups of the same message.
*/
BabelFish();
/*!
* Constructs an instance of BabelFish with the given description provider.
* @param description_provider The description provider to be used.
* @throws BabelFishException If the passed description_provider is a nullptr.
*/
explicit BabelFish( DescriptionProvider::Ptr description_provider );
~BabelFish();
/*!
* Translates the given BabelFishMessage into a TranslatedMessage containing a reference to the input message and the
* translated message. The reference to the input message is needed to ensure the data is not destroyed because
* the translated message may depend on it.
* @param msg The received BabelFishMessage
* @return A struct containing the input and the translated message.
*/
TranslatedMessage::Ptr translateMessage( const IBabelFishMessage::ConstPtr &msg );
/*!
* Translates the given BabelFishMessage into a translated message.
* Since the passed BabelFishMessage is only passed as const reference, BabelFish can not make sure that it is
* not destroyed during the lifetime of Message (or until Message is detached using Message::detachFromStream).
* Hence, the user has to ensure the BabelFishMessage is not destroyed or detach the Message before it is destroyed.
* @param msg The received BabelFishMessage
* @return The translated message.
*/
Message::Ptr translateMessage( const IBabelFishMessage &msg );
/*!
* Translates a message created by BabelFish into a BabelFishMessage that can be sent using the implementations
* provided by ROS.
* @param msg The input message
* @return The serialized ROS compatible message
*/
BabelFishMessage::Ptr translateMessage( const Message::ConstPtr &msg );
/*!
* @copydoc BabelFish::translateMessage(const Message::ConstPtr&)
*/
BabelFishMessage::Ptr translateMessage( const Message &msg );
/*!
* @copydetails BabelFish::translateMessage(const Message::ConstPtr&)
* @param msg The input message
* @param result Container for the serialized ROS compatible message
* @return True if successful, false otherwise
*/
bool translateMessage( const Message &msg, BabelFishMessage &result );
/*!
* Advertises a publisher on the given topic.
* @param nh The ros::NodeHandle used to advertise the topic
* @param type The message type that is advertised, e.g.: "std_msgs/Header"
* @param topic The topic to publish on
* @param queue_size The maximum number of outgoing messages to be queued for delivery to subscribers
* @param latch Whether or not this publisher should latch, i.e., always send out the last message to new subscribers
* @param connect_cb Function to call whenever a subscriber connects to this topic
* @param disconnect_cb Function to call whenever a subscriber disconnects from this topic
* @return A ros::Publisher that can be used to publish BabelFishMessages filled with the given type on the given topic
*/
ros::Publisher advertise( ros::NodeHandle &nh, const std::string &type, const std::string &topic,
uint32_t queue_size, bool latch = false,
const ros::SubscriberStatusCallback &connect_cb = ros::SubscriberStatusCallback(),
const ros::SubscriberStatusCallback &disconnect_cb = ros::SubscriberStatusCallback());
/*!
* Advertises a service on the given topic.
* @param nh The ros::NodeHandle used to advertise the service
* @param type The service type that is advertised, e.g.: "rosapi/GetParam"
* @param service The topic this service is advertised on
* @param callback The callback to be executed for each service request
* @return A ros::ServiceServer that can be used to provide a service of the given type on the given topic
*/
ros::ServiceServer advertiseService( ros::NodeHandle &nh, const std::string &type, const std::string &service,
const std::function<bool( Message &, Message & )> &callback );
/*!
* Creates an empty message of the given type.
* @param type The message type, e.g.: "std_msgs/Header"
* @return An empty message of the given type
*
* @throws BabelFishException If the message description was not found
*/
Message::Ptr createMessage( const std::string &type );
/*!
* Creates a service request message for the given service type.
* @param type The type of the service, e.g., rosapi/GetParam
* @return An empty service request message that can be used to call a service of the given type
*
* @throws BabelFishException If the service description was not found
*/
Message::Ptr createServiceRequest( const std::string &type );
/*!
* Calls a service on the given topic with the given request
* @param service
* @param req
* @param res
* @return
*
* @throws BabelFishException If the passed req message is not a request
* @throws BabelFishException If the service description was not found
*/
bool callService( const std::string &service, const Message::ConstPtr &req, TranslatedMessage::Ptr &res );
DescriptionProvider::Ptr &descriptionProvider();
private:
DescriptionProvider::Ptr description_provider_;
};
} // ros_babel_fish
#endif //ROS_BABEL_FISH_BABEL_FISH_H
| true |
55eda0738aeebf554b0f7ea8e66bab67b0ae5f4a | C++ | E1P0TR0/Algorithms-and-Data-Structures_2 | /Hash Tables/Hashes.hpp | UTF-8 | 1,537 | 3.625 | 4 | [] | no_license | #pragma once
#ifndef __HASH_HPP__
#define __HASH_HPP__
#include <iostream>
#include <vector>
#include <cmath>
template <typename T>
class Hash
{
private:
std::vector<T> vect;
public:
Hash(int size);
int hash(T data);
void insert(T data);
int search(T data);
void dleted(T data);
bool primeNumber(T data);
void hashPrime(T data);
void print();
};
template <typename T>
Hash<T>::Hash(int size)
{
vect.resize(size);
}
template <typename T>
void Hash<T>::insert(T data)
{
int index = hash(data);
vect.at(index) = data;
}
template <typename T>
int Hash<T>::search(T data)
{
int index = hash(data);
return (data == (vect.at(index))) ? index : -1;
}
template <typename T>
void Hash<T>::dleted(T data)
{
int index = search(data);
if(index != -1)
vect.at(index) = "deleted";
}
template <typename T>
int Hash<T>::hash(T data)
{
unsigned int hashValue = 0;
int length = data.length() - 1;
for(auto value : data)
{
hashValue += ( (value - 96) * (pow(27, length)) );
length--;
}
std::cout << hashValue % vect.size()<< " ";
return hashValue % vect.size();
}
template <typename T>
bool Hash<T>::primeNumber(T data)
{
for(int i = 2; i < data; ++i)
if(data % i == 0)
return false;
return true;
}
template <typename T>
void Hash<T>::hashPrime(T data) { return data % 19; }
template <typename T>
void Hash<T>::print()
{
for(auto value : vect) std::cout << value << " ";
std::cout << "\n";
}
#endif | true |
4d95f2e17d0eccba781c4e8134e528010f837c50 | C++ | neizod/problems | /acm/uva/136-ugly-number.cpp | UTF-8 | 2,190 | 3.359375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
long double pow(int base, int exponent) {
if (exponent == 0) {
return 1;
}
return (exponent % 2 == 0 ? 1 : base) * pow(base*base, exponent/2);
}
bool found_ugly(int index, vector<long double> numbers) {
if (numbers.size() < index) {
return false;
}
}
int least_pow(int e2, int e3, int e5) {
long double p2 = pow(2, e2);
long double p3 = pow(3, e3);
long double p5 = pow(5, e5);
if (p2 < p3 && p2 < p5) {
return 2;
} else if (p3 < p5) {
return 3;
}
return 5;
}
bool satisfy(vector<long double> numbers, int index, int e2, int e3, int e5) {
if (numbers.size() < index) {
return false;
}
long double ugly = numbers[index-1];
return ugly <= pow(2, e2) && ugly <= pow(3, e3) && ugly <= pow(5, e5);
}
long double find_ugly(int index) {
vector<long double> numbers = { 1.0L };
int e2 = 0, e3 = 0, e5 = 0;
while (!satisfy(numbers, index, e2, e3, e5)) {
switch (least_pow(e2, e3, e5)) {
case 2:
e2 += 1;
for (int i=0; i<=e3; i++) {
for (int j=0; j<=e5; j++) {
numbers.push_back(pow(2, e2) * pow(3, i) * pow(5, j));
}
}
break;
case 3:
e3 += 1;
for (int i=0; i<=e2; i++) {
for (int j=0; j<=e5; j++) {
numbers.push_back(pow(2, i) * pow(3, e3) * pow(5, j));
}
}
break;
case 5:
e5 += 1;
for (int i=0; i<=e2; i++) {
for (int j=0; j<=e3; j++) {
numbers.push_back(pow(2, i) * pow(3, j) * pow(5, e5));
}
}
break;
}
sort(numbers.begin(), numbers.end());
}
return numbers[index-1];
}
int main(void) {
cout << "The 1500'th ugly number is "
<< fixed << setprecision(0) << find_ugly(1500) << "." << endl;
return 0;
}
| true |
95925ca754d5225970c8ec0f8dd2735e8e2a252c | C++ | Tomas-Homola/PG_cv8 | /src/SurfaceRepresentation.cpp | UTF-8 | 5,602 | 2.71875 | 3 | [] | no_license | #include "SurfaceRepresentation.h"
// Vertex stuff
Vertex::Vertex(double x, double y, double z, int index)
{
this->x = x;
this->y = y;
this->z = z;
this->index = index;
edge = nullptr;
}
void Vertex::setCoordinates(double newX, double newY, double newZ)
{
x = newX;
y = newY;
z = newZ;
}
void Vertex::setVertexColor(double red, double green, double blue)
{
if ((red - 1.0) > 0.000001)
vertexColor.setRedF(1.0);
else if ((red - 1.0) < 0.000001)
vertexColor.setRedF(0.0);
else
vertexColor.setRedF(red);
if ((green - 1.0) > 0.000001)
vertexColor.setGreenF(1.0);
else if ((green - 1.0) < 0.000001)
vertexColor.setGreenF(0.0);
else
vertexColor.setGreenF(red);
if ((blue - 1.0) > 0.000001)
vertexColor.setBlueF(1.0);
else if ((blue - 1.0) < 0.000001)
vertexColor.setBlueF(0.0);
else
vertexColor.setBlueF(red);
}
void Vertex::setVertexColor(int red, int green, int blue)
{
if (red > 255)
vertexColor.setRed(255);
else if (red < 0)
vertexColor.setRed(0);
else
vertexColor.setRed(red);
if (green > 255)
vertexColor.setGreen(255);
else if (green < 0)
vertexColor.setGreen(0);
else
vertexColor.setGreen(green);
if (blue > 255)
vertexColor.setBlue(255);
else if (blue < 0)
vertexColor.setBlue(0);
else
vertexColor.setBlue(blue);
}
QString Vertex::vertexInfo(int precision)
{
return QString("%1 %2 %3").arg(QString::number(x, 'f', precision)).arg(QString::number(y, 'f', precision)).arg(QString::number(z, 'f', precision));
}
bool Vertex::operator==(Vertex v)
{
double x = this->x - v.x;
double y = this->y - v.y;
double z = this->z - v.z;
double distance = sqrt(x * x + y * y + z * z);
if (distance < 0.000001)
return true;
else
return false;
}
void Vertex::projectToUnitSphere()
{
double d = getDistanceFromOrigin();
if (qAbs(1.0 - d) > 0.000001) // ak by bola vzdialenost bodu mimo jednotkovej sfery
{
x = x / d;
y = y / d;
z = z / d;
}
}
// H_edge stuff
H_edge::H_edge(Vertex* vert_origin, Face* face, H_edge* edge_prev, H_edge* edge_next, H_edge* pair)
{
this->vert_origin = vert_origin;
this->face = face;
this->edge_prev = edge_prev;
this->edge_next = edge_next;
this->pair = pair;
}
void H_edge::setAll(Vertex* vert_origin, Face* face, H_edge* edge_prev, H_edge* edge_next, H_edge* pair)
{
this->vert_origin = vert_origin;
this->vert_end = edge_next->getVertexOrigin();
this->face = face;
this->edge_prev = edge_prev;
this->edge_next = edge_next;
this->pair = pair;
}
bool H_edge::hasPair()
{
if (pair == nullptr)
return false;
else
return true;
}
QString H_edge::edgeVerticesInfo()
{
return QString("%1 %2").arg(QString::number(vert_origin->getIndex())).arg(QString::number(edge_next->vert_origin->getIndex()));
}
// Octahedron stuff
Octahedron::~Octahedron()
{
for (int i = 0; i < vertices.size(); i++)
delete vertices[i];
for (int i = 0; i < edges.size(); i++)
delete edges[i];
for (int i = 0; i < faces.size(); i++)
delete faces[i];
vertices.clear(); edges.clear(); faces.clear();
}
bool Octahedron::isEmpty()
{
if (vertices.isEmpty() && edges.isEmpty() && faces.isEmpty())
return true;
else
return false;
}
void Octahedron::clear()
{
if (!vertices.isEmpty())
for (int i = 0; i < vertices.size(); i++)
delete vertices[i];
if (!edges.isEmpty())
for (int i = 0; i < edges.size(); i++)
delete edges[i];
if (!faces.isEmpty())
for (int i = 0; i < faces.size(); i++)
delete faces[i];
vertices.clear(); edges.clear(); faces.clear();
}
void Octahedron::calculateNormals()
{
Vertex* vertex1 = nullptr, * vertex2 = nullptr, * vertex3 = nullptr;
QVector3D faceNormal(0.0, 0.0, 0.0);
// normlay vo vrcholoch, tie nedelim normou, lebo uz su na jedntkovej sfere -> maju normu == 1
for (int i = 0; i < vertices.size(); i++)
{
vertices[i]->setVertexNormal(vertices[i]->getX(), vertices[i]->getY(), vertices[i]->getZ());
}
// nomraly pre plosky
for (int i = 0; i < faces.size(); i++)
{
vertex1 = faces[i]->getEdge()->getVertexOrigin();
vertex2 = faces[i]->getEdge()->getEdgeNext()->getVertexOrigin();
vertex3 = faces[i]->getEdge()->getEdgePrevious()->getVertexOrigin();
faceNormal = (vertex1->getVertexNormal() + vertex2->getVertexNormal() + vertex3->getVertexNormal()) / 3.0;
faceNormal.normalize(); // normalizovanie vektoru normaly na plosku
faces[i]->setFaceNormal(faceNormal);
}
}
QString Face::faceVerticesInfo()
{
// edge, edge_next, edge_prev
return QString("%1 %2 %3").arg(QString::number(edge->getVertexOrigin()->getIndex())).arg(QString::number(edge->getEdgeNext()->getVertexOrigin()->getIndex())).arg(QString::number(edge->getEdgePrevious()->getVertexOrigin()->getIndex()));
}
void Face::setFaceColor(double red, double green, double blue)
{
if ((red - 1.0) > 0.000001)
faceColor.setRedF(1.0);
else if ((red - 1.0) < 0.000001)
faceColor.setRedF(0.0);
else
faceColor.setRedF(red);
if ((green - 1.0) > 0.000001)
faceColor.setGreenF(1.0);
else if ((green - 1.0) < 0.000001)
faceColor.setGreenF(0.0);
else
faceColor.setGreenF(red);
if ((blue - 1.0) > 0.000001)
faceColor.setBlueF(1.0);
else if ((blue - 1.0) < 0.000001)
faceColor.setBlueF(0.0);
else
faceColor.setBlueF(red);
}
void Face::setFaceColor(int red, int green, int blue)
{
if (red > 255)
faceColor.setRed(255);
else if (red < 0)
faceColor.setRed(0);
else
faceColor.setRed(red);
if (green > 255)
faceColor.setGreen(255);
else if (green < 0)
faceColor.setGreen(0);
else
faceColor.setGreen(green);
if (blue > 255)
faceColor.setBlue(255);
else if (blue < 0)
faceColor.setBlue(0);
else
faceColor.setBlue(blue);
}
| true |
36263098418a01c88c66ab5f84c084ba492a37b7 | C++ | dzamkov/ChronoTank | /ChronoTank/src/vehicle.h | UTF-8 | 564 | 2.515625 | 3 | [] | no_license | #ifndef CTANK_VEHICLE_H
#define CTANK_VEHICLE_H
#include <irrlicht.h>
#include "nullity/object.h"
namespace ctank {
/// Enumeration of vehicle control values that can be set.
enum VehicleControl {
VehicleControlFoward,
VehicleControlTurn,
};
/// Interface to a vehicle that moves n stuff.
class IVehicle : public nullity::IObject {
public:
/// Sets a control value for the vehicle.
virtual void SetVehicleControl(VehicleControl Key, float Value) = 0;
};
/// Creates the tank used by the player.
IVehicle* CreatePlayerTank();
}
#endif | true |
8a152c75cb8270e3e624d5eaa3bf9dbc78d840b5 | C++ | Kripash/CS-477 | /hw5/heap.cpp | UTF-8 | 1,822 | 4.4375 | 4 | [] | no_license | //author KRIPASH SHRESTHA
//CLASS CS 477
//ASSIGNMENT HOMEWORK 5
//FILE HEAP
//This program DOES CHECK FOR MAX HEAP.
#include <iostream>
bool isMaxHeap(int array[], int size);
//This function prints out the elements of the array and checks if it is a maxHeap or not by calling isMaxHeap and then properly outputs the response to if it is a max heap or not.
void printOut(int array[], int size)
{
std::cout << "[ ";
for(int i = 0; i < size; i++)
{
std::cout << array[i] << " ";
}
std::cout << "] = ";
//calls isMaxHeap to check if it is a maxHeap and then properly does the output based on the return.
if(isMaxHeap(array, size))
{
std::cout << "YES,heap" << std::endl;
}
else if(!isMaxHeap(array, size))
{
std::cout << "Not a heap" << std::endl;
}
}
/*This function checks to see if the given array of size is a max heap or not. I took the iterative approach and iterated with the (size - 2)/2 of the array.
The Loop continues until the stopping condition is met. During this loop, the function checks to see if the current inddex's left and right child is larger than itself.
If either children is larger than the parent, the function will return false. Otherwise the function will complete the loop and if it did not return false, it will return true, implying it is a max heap.
*/
bool isMaxHeap(int array[], int size)
{
for(int i = 0; i <= ((size-2)/2); i++)
{
if(array[(2 * i) + 1] > array[i]) //checks if left child is larger than parent.
{
return false;
}
if(array[(2 * i) + 2] > array[i]) //checks if right child is larger than parent.
{
return false;
}
}
return true;
}
int main()
{
int maxHeap[10] = {16, 14, 10, 8, 7, 9, 3, 2, 4, 1};
int notMaxHeap[9] = {10, 3, 9, 7, 2, 11, 5, 1, 6};
printOut(maxHeap, 10);
printOut(notMaxHeap, 9);
return 0;
}
| true |
6d7ec8befe03266462fa5671b47871881d36ad0b | C++ | lpxxn/code | /src/libs/comdatagui/detail/tableviewbase.cpp | UTF-8 | 2,564 | 2.5625 | 3 | [] | no_license | #include "tableviewbase.h"
#include <QDebug>
#include <QMouseEvent>
namespace ComDataGui
{
static const qreal ZoomInDelta = 1.2;
static const qreal ZoomOutDelta = 0.8;
TableViewBase::TableViewBase(QWidget *parent) :
QTableView(parent), m_lastRow(-1), m_zoomFactor(1.0)
{
}
void TableViewBase::resetLastRow()
{
m_lastRow = -1;
}
void TableViewBase::setLastRow(int lastRow)
{
m_lastRow = lastRow;
}
/*!
* \reimp
*/
QModelIndex TableViewBase::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
{
QModelIndex current = QTableView::moveCursor(cursorAction, modifiers);
emit customClearSelection();
return current;
}
/*!
* \brief 计算出选中区域的矩形
* \return 选中区域的矩形
*/
Selection TableViewBase::selectionRangeRegion()
{
QModelIndexList modelList = selectionModel()->selectedIndexes();
Selection seRange;
if (modelList.isEmpty())
return seRange;
qSort(modelList.begin(),modelList.end());
seRange.startColIndex = modelList.first().column();
seRange.endColIndex = modelList.first().column();
seRange.startRowIndex = modelList.first().row();
seRange.endRowIndex = modelList.last().row();
foreach (const QModelIndex& mo, modelList) {
seRange.endColIndex = qMax(mo.column(), seRange.endColIndex);
seRange.startColIndex = qMin(mo.column(), seRange.startColIndex);
}
return seRange;
}
/*!
* \reimp
*/
void TableViewBase::mousePressEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::RightButton) {
e->ignore();
} else {
emit pressed(); // prepared for resolving the bug
QTableView::mousePressEvent(e);
}
}
/*!
* \reimp
*/
void TableViewBase::zoomIn()
{
m_zoomFactor *= ZoomInDelta;
for (int row = 0; row < model()->rowCount(); ++row)
setRowHeight(row, rowHeight(row) * m_zoomFactor);
}
/*!
* \reimp
*/
void TableViewBase::zoomOut()
{
m_zoomFactor *= ZoomOutDelta;
for (int row = 0; row < model()->rowCount(); ++row)
setRowHeight(row, rowHeight(row) * m_zoomFactor);
}
/*!
* \brief 设置放大倍数.
* \param zoomFactor 放大倍数
*/
void TableViewBase::setZoomFactor(qreal zoomFactor)
{
if (zoomFactor != m_zoomFactor) {
m_zoomFactor = zoomFactor;
for (int row = 0; row < model()->rowCount(); ++row)
setRowHeight(row, rowHeight(row) * m_zoomFactor);
}
}
/*!
* \brief 获取放大倍数.
* \return 放大倍数
*/
qreal TableViewBase::zoomFactor()
{
return m_zoomFactor;
}
} // namespace ComDataGui
| true |
86d4fda3ca21ddf262241129031b44c051e7c5ef | C++ | gorylpe/FlexBisonCompiler | /cmds/CommandsBlock.h | UTF-8 | 4,141 | 2.90625 | 3 | [] | no_license | #pragma once
#include "Command.h"
class CommandsBlock : public Command {
public:
vector<Command*> commands;
CommandsBlock() = default;
CommandsBlock(const CommandsBlock& block2){
for(auto cmd : block2.commands){
addCommand(cmd->clone());
}
}
CommandsBlock* clone() const final {
return new CommandsBlock(*this);
}
void addCommand(Command* command){
commands.push_back(command);
}
void addCommands(vector<Command*>& newCommands){
commands.insert(commands.end(), newCommands.begin(), newCommands.end());
}
void print(int nestedLevel) final {
for(auto cmd : commands){
cmd->print(nestedLevel);
}
}
string toString() final {return "";}
bool equals(Command* command) final {
auto block2 = dynamic_cast<CommandsBlock*>(command);
if(block2 == nullptr)
return false;
if(this->commands.size() != block2->commands.size())
return false;
for(int i = 0; i < this->commands.size(); ++i){
if(!this->commands[i]->equals(block2->commands[i]))
return false;
}
return true;
}
void semanticAnalysis() final {
for(auto cmd : this->commands){
//cerr << "Semantic analysis for " << typeid(*cmd).name() << endl;
cmd->semanticAnalysis();
}
}
void generateCode() final {
for(auto cmd : this->commands){
cmd->generateCode();
}
}
void calculateVariablesUsage(cl_I numberOfNestedLoops) final {
for(auto cmd : this->commands){
cmd->calculateVariablesUsage(numberOfNestedLoops);
}
}
void simplifyExpressions() final {
for(auto cmd : this->commands){
cmd->simplifyExpressions();
}
}
void collectUsagesData(IdentifiersUsagesHelper &helper) final {
for(auto cmd : this->commands){
cmd->collectUsagesData(helper);
}
}
int searchUnusedAssignmentsAndSetForDeletion(IdentifiersUsagesHelper &helper) final {
int removed = 0;
for(auto cmd : this->commands) {
removed += cmd->searchUnusedAssignmentsAndSetForDeletion(helper);
}
return removed;
}
void collectAssignmentsForIdentifiers(IdentifiersAssignmentsHelper& helper) final {
for(auto cmd : this->commands) {
cmd->collectAssignmentsForIdentifiers(helper);
}
}
int propagateValues(IdentifiersAssignmentsHelper &assgnsHelper, IdentifiersUsagesHelper &usagesHelper) final {
int propagated = 0;
for(auto cmd : this->commands) {
//cerr << "Propagating " << typeid(*cmd).name() << endl;
propagated += cmd->propagateValues(assgnsHelper, usagesHelper);
}
return propagated;
}
CommandsBlock* blockToReplaceWith() final {
return this;
}
void replaceCommands() final {
for(int i = 0; i < commands.size(); ++i) {
CommandsBlock* block = commands[i]->blockToReplaceWith();
if (block != nullptr) {
block->replaceCommands();
commands.erase(commands.begin() + i);
commands.insert(commands.begin() + i, block->commands.begin(), block->commands.end());
i--;
i += block->commands.size();
} else {
commands[i]->replaceCommands();
}
}
}
void replaceValuesWithConst(string pid, cl_I number) final {
for(auto cmd : this->commands){
cmd->replaceValuesWithConst(pid, number);
}
}
void collectSSANumbersInIdentifiers(IdentifiersSSAHelper &prevStats) final {
for(auto cmd : this->commands){
//cerr << "STATS FOR " << typeid(*cmd).name() << endl;
cmd->collectSSANumbersInIdentifiers(prevStats);
}
};
void collectNumberValues(map<cl_I, NumberValueStats>& stats) final {
for(auto cmd : this->commands){
cmd->collectNumberValues(stats);
}
}
};
| true |
9ad7a8a132c534133624cb0a2f46d959505a8d7f | C++ | lab132/PyBind | /PyBindUnit/src/BindingTests.cpp | UTF-8 | 5,783 | 2.953125 | 3 | [] | no_license | #include "catch.hpp"
#include "PyBindUnit.hpp"
#include <string>
bool calledFunction = false;
void TestFunction1()
{
calledFunction = true;
}
struct Function2Result
{
int i;
unsigned char b;
char B;
short h;
unsigned short H;
unsigned int I;
unsigned long long K;
long long L;
bool p;
std::string s;
float f;
double d;
std::string str;
};
Function2Result f2Result;
void TestFunction2(
int i
,unsigned char b
,char B
,unsigned short H
,short h
,unsigned int I
,unsigned long long K
,long long L
,bool p
,const char* s
,float f
,double d
,std::string str)
{
f2Result.i = i;
f2Result.b = b;
f2Result.B = B;
f2Result.H = H;
f2Result.h = h;
f2Result.I = I;
f2Result.K = K;
f2Result.L = L;
f2Result.p = p;
f2Result.s = s;
f2Result.f = f;
f2Result.d = d;
f2Result.str = str;
calledFunction = true;
}
int TestFunction3(int a, int b)
{
calledFunction = true;
return a + b;
}
int TestFunction4(Object a, Object b)
{
calledFunction = true;
REQUIRE(a.IsValid());
REQUIRE(b.IsValid());
return Dictionary::FromObject(a).GetItem<int>("f") + Dictionary::FromObject(b).GetItem<int>("f");
}
SCENARIO("Module bind Test", "[binding][module]")
{
GIVEN("An interpreter")
{
Interpreter interpreter;
interpreter.Initialize();
WHEN("Binding a module")
{
Module module = Module("testModule");
interpreter.RegisterModule(&module);
THEN("It should be importable")
{
auto result = interpreter.RunString("import testModule");
REQUIRE(result.IsValid());
}
}
interpreter.Finalize();
}
}
SCENARIO("Function bind Test", "[binding][function]")
{
GIVEN("An interpreter with a bound module")
{
Interpreter interpreter;
interpreter.Initialize();
{
Module module = Module("testModule");
interpreter.RegisterModule(&module);
interpreter.RunString("import testModule");
calledFunction = false;
WHEN("Binding a function to the module")
{
REQUIRE(calledFunction == false);
module.AddFunction(PY_BIND_FUNCTION(TestFunction1));
REQUIRE(calledFunction == false);
THEN("It should be callable")
{
auto result = interpreter.RunString("testModule.TestFunction1()");
REQUIRE(calledFunction == true);
REQUIRE(result.IsValid());
}
}
WHEN("Binding a function to the module with a custom name")
{
REQUIRE(calledFunction == false);
module.AddFunction(PY_BIND_FUNCTION_NAMED(TestFunction1, "myNamedFunction"));
REQUIRE(calledFunction == false);
THEN("It should be callable")
{
auto result = interpreter.RunString("testModule.myNamedFunction()");
REQUIRE(calledFunction == true);
REQUIRE(result.IsValid());
}
}
WHEN("Binding a function with parameters")
{
REQUIRE(calledFunction == false);
module.AddFunction(PY_BIND_FUNCTION(TestFunction2));
REQUIRE(calledFunction == false);
THEN("The parameters should be passed correctly")
{
auto result = interpreter.RunString("testModule.TestFunction2("
"-2147483647"
",255"
",-127"
",65535"
",-32768"
",4294967295"
",18446744073709551615"
",-9223372036854775808"
",True"
",'hello'"
",3.4E+38"
",1.7E-308"
",'hello again'"
")");
REQUIRE(calledFunction == true);
REQUIRE(result.IsValid());
REQUIRE(f2Result.i == -2147483647);
REQUIRE(f2Result.b == 255);
REQUIRE(f2Result.B == -127);
REQUIRE(f2Result.H == 65535);
REQUIRE(f2Result.h == -32768);
REQUIRE(f2Result.I == 4294967295U);
REQUIRE(f2Result.K == 18446744073709551615ULL);
REQUIRE(f2Result.L == -9223372036854775808LL);
REQUIRE(f2Result.p == true);
REQUIRE(f2Result.s == "hello");
REQUIRE(f2Result.f == 3.4E+38f);
REQUIRE(f2Result.d == 1.7E-308);
REQUIRE(f2Result.str == "hello again");
}
}
WHEN("Binding a function with a return value")
{
REQUIRE(calledFunction == false);
module.AddFunction(PY_BIND_FUNCTION(TestFunction3));
REQUIRE(calledFunction == false);
THEN("It should return the expected value")
{
auto result = interpreter.RunString("f=testModule.TestFunction3(3,5)");
REQUIRE(calledFunction);
REQUIRE(result.IsValid());
auto mainDictObj = interpreter.GetMainDict();
REQUIRE(mainDictObj.IsValid());
REQUIRE(mainDictObj.IsDictionary());
Dictionary dict = Dictionary::FromObject(mainDictObj);
int resultInt = dict.GetItem<int>("f");
REQUIRE(resultInt == 8);
}
}
WHEN("Binding a function with an object as parameter")
{
REQUIRE(calledFunction == false);
module.AddFunction(PY_BIND_FUNCTION(TestFunction4));
REQUIRE(calledFunction == false);
THEN("It should return the expected value")
{
auto result = interpreter.RunString("f=testModule.TestFunction4({'f':3},{'f':5})");
REQUIRE(calledFunction);
REQUIRE(result.IsValid());
auto mainDictObj = interpreter.GetMainDict();
REQUIRE(mainDictObj.IsValid());
REQUIRE(mainDictObj.IsDictionary());
Dictionary dict = Dictionary::FromObject(mainDictObj);
int resultInt = dict.GetItem<int>("f");
REQUIRE(resultInt == 8);
}
}
}
interpreter.Finalize();
}
}
| true |
d1602bccca1ce20aa5274ee73790746c5156971f | C++ | FinixLei/leetcode_finix | /src/41_hard_FirstMissingPositive.cpp | UTF-8 | 1,493 | 3.921875 | 4 | [] | no_license | /*
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
int firstMissingPositive(vector<int>& nums) {
set<int> num_set;
int max = 0;
for (auto i : nums) {
if (i>0) {
num_set.insert(i);
if (i > max) max = i;
}
}
if (num_set.size() == 0) return 1;
for (int i=1; i<=max; i++) {
if (num_set.find(i) == num_set.end()) return i;
}
return max+1;
}
int way2_firstMissingPositive(vector<int>& nums) {
vector<int> array;
int max = 0;
for (auto i : nums) {
if (i>0) {
array.push_back(i);
if (i > max) max = i;
}
}
sort(array.begin(), array.end());
if (array.size() == 0 || array[0] > 1) return 1;
// Note, some C++11 compilier need to use int(array.size())-2 as below, cannot use array.size()-2 directly.
for (int i=0; i<=int(array.size())-2; i++) {
if (array[i] + 1 < array[i+1]) return array[i]+1;
}
return max+1;
}
int main()
{
// int array[] = {3,4,-1,1};
int array[] = {7,8,9,11};
vector<int> init(array, array+sizeof(array)/sizeof(int));
cout << firstMissingPositive(init);
cout << way2_firstMissingPositive(init);
return 0;
} | true |
e5926577b3d43a53fefb16ec065158f6c69a5191 | C++ | maayan92/experis_C_basicCpp | /cpp/ds/inchToCentimeter/inch.cpp | UTF-8 | 400 | 2.953125 | 3 | [] | no_license | #include "inch.h"
#include "centimeter.h"
Inch::Inch()
: m_value() {
}
Inch::Inch(double a_value)
: m_value(a_value) {
}
Inch& Inch::operator=(const Inch& a_inch) {
if(this != &a_inch) {
m_value = a_inch.m_value;
}
return *this;
}
Inch::operator Centimeter() {
return Centimeter(m_value / convertToCentimeter);
}
double Inch::GetVal() {
return m_value;
} | true |
d43714e116aab7aad8d24e2a5d9d6f2aca22d37c | C++ | ichyo/atcoder-submissions | /cpp/ABC006/C.cpp | UTF-8 | 604 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
bool calc(int n, int m, int& a, int& b, int& c){
int k = m - 2 * n;
for(int C = 0; 2 * C <= k; C++){
int B = k - 2 * C;
int A = n - B - C;
if(A >= 0 && B >= 0 && C >= 0){
a = A, b = B, c = C;
return true;
}
}
return false;
}
int main(){
int n, m;
cin >> n >> m;
int a, b, c;
if(calc(n, m, a, b, c)){
cout << a << " " << b << " " << c << endl;
}else{
cout << "-1 -1 -1" << endl;
}
return 0;
}
| true |
cf8c44ca3a5e9e493ad052068cdc65c9d13c5a38 | C++ | maksverver/lynx | /cpp/Lynx3.cpp | UTF-8 | 25,564 | 2.875 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
// Simulation heuristics parameters
const int EDGE_BIAS_THRESHOLD = 50; // Avoid playing at the edge for this number of simulation steps
// Tree search parameters
const int SAMPLES = 32; // Number of samples at tree nodes, has a huge effect on performance
const double ALPHA = 0.75; // Blending parameter for AMAF samples and actual samples in the computation of the score of a node
// Timing parameters
const double TOTAL_TIME = 20.0; // Maximum amount of time that may be used for a game (actual time may be higher)
const int TIME_DIVIDER = 10; // The remaining time is divided by this number to determine the time for the current move
const double MINIMUM_TIME = 0.1; // The minimum amount of time used for a move
const int POSITIONS = 106; // Total number of positions on the board
// Masks for the 'edges' array
const int TOP_LEFT_EDGE = 1;
const int BOT_LEFT_EDGE = 2;
const int BOT_EDGE = 4;
const int BOT_RIGHT_EDGE = 8;
const int TOP_RIGHT_EDGE = 16;
// Masks for the 'corners' array
const int TOP_CORNER = 1;
const int TOP_LEFT_CORNER = 2;
const int BOT_LEFT_CORNER = 4;
const int BOT_RIGHT_CORNER = 8;
const int TOP_RIGHT_CORNER = 16;
// Determines whether we win with a given set of captured corners
// Given a set of captured corners encoded as the bitmask i, win[i] is true if this set of captured corners is winning, otherwise win[i] is false
const bool win[] = {0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,1,1,1,1,1,1,1};
// Corner masks for a given edge mask, determines which corners we captured given a set of edges
// Given a set of edges encoded as a bitmask i, cornerSet[i] gives the corners captured by a component that connects these edges
const int cornerSet[107] = {0,0,0,0,0,0,0,6,0,0,0,2,0,8,12,14,0,0,0,3,0,1,4,7,0,17,16,19,24,25,28,31};
// A list of board positions that are on the edge of the playing board
// We only use this to find connections between edges in the 'winner' method, as we dont need to check from every edge, this array only contains the moves from three edges
const int edge[107] = {1,4,9,16,25,36,49,2,5,10,17,26,37,61,72,82,91,99,106};
// The neighbour positions of each positions in either clockwise or counter-clockwise order
const int neighbours[107][8] = {{},{4,3,2},{5,6,3,1},{1,2,6,7,8,4},{9,8,3,1},{10,11,6,2},{2,3,7,12,11,5},{3,6,12,13,14,8},{3,4,9,15,14,7},{4,8,15,16},{5,11,18,17},{19,18,10,5,6,12},{19,20,13,7,6,11},{21,20,12,7,14,22},{23,22,13,7,8,15},
{16,24,23,14,8,9},{9,15,24,25},{26,27,18,10},{17,27,28,19,11,10},{18,11,12,20,29,28},{19,29,30,21,13,12},{32,22,13,20,30,31},{32,33,23,14,13,21},{34,33,22,14,15,24},{34,35,25,16,15,23},{36,35,24,16},{37,38,27,17},{17,18,28,39,38,26},{19,18,27,39,40,29},
{19,20,30,41,40,28},{21,20,29,41,42,31},{32,21,30,42,43,44},{33,22,21,31,44,45},{34,23,22,32,45,46},{35,24,23,33,46,47},{34,24,25,36,48,47},{25,35,48,49},{26,38,50},{51,50,37,26,27,39},{51,38,27,28,40,52},{39,52,53,41,29,28},{54,53,40,29,30,42},
{55,54,41,30,31,43},{55,42,31,44,56},{32,31,43,56,57,45},{32,33,46,58,57,44},{34,33,45,58,59,47},{34,35,48,60,59,46},{35,36,49,61,60,47},{61,48,36},{62,51,38,37},{50,38,39,52,63,62},{51,39,40,53,64,63},{64,65,54,41,40,52},
{55,66,65,53,41,42},{54,66,67,56,43,42},{68,67,55,43,44,57},{68,69,58,45,44,56},{69,70,59,46,45,57},{70,71,60,47,46,58},{71,59,47,48,61,72},{72,60,48,49},{73,63,51,50},{51,52,64,74,73,62},{65,53,52,63,74,75},{64,53,54,66,76,75},{55,54,65,76,77,67},
{68,78,77,66,55,56},{69,57,56,67,78,79},{68,57,58,70,80,79},{69,80,81,71,59,58},{70,81,82,72,60,59},{61,60,71,82},{62,63,74,83},{84,83,73,63,64,75},{85,84,74,64,65,76},{85,86,77,66,65,75},{87,86,76,66,67,78},{68,67,77,87,88,79},{68,69,80,89,88,78},
{69,70,81,90,89,79},{70,71,82,91,90,80},{91,81,71,72},{73,74,84,92},{85,93,92,83,74,75},{84,93,94,86,76,75},{85,76,77,87,95,94},{86,77,78,88,96,95},{87,96,97,89,79,78},{98,97,88,79,80,90},{98,99,91,81,80,89},{82,81,90,99},{83,84,93,100},
{85,84,92,100,101,94},{85,86,95,102,101,93},{102,103,96,87,86,94},{103,95,87,88,97,104},{98,89,88,96,104,105},{99,106,105,97,89,90},{91,90,98,106},{92,93,101},{100,93,94,102},{101,94,95,103},{104,96,95,102},{105,97,96,103},{104,97,98,106},{105,98,99}};
// The edge mask of the edges a position is connected to
// edges[i] is an edge mask that encodes the set of a edges to which position i is adjacent
const int edges[107] = {0,17,1,0,16,1,0,0,0,16,1,0,0,0,0,0,16,1,0,0,0,0,0,0,0,16,1,0,0,0,0,0,0,0,0,0,16,3,0,0,0,0,0,0,0,0,0,0,0,24,2,0,0,0,0,0,0,0,0,0,0,8,2,0,0,0,0,0,0,0,0,0,8,2,0,0,0,0,0,0,0,0,8,2,0,0,0,0,0,0,0,8,2,0,0,0,0,0,0,8,6,4,4,4,4,4,12};
// The distance of a position from the edge
// edgeDistance[i] is the smallest number of positions between position i and the edge
const int edgeDistance[107] = {0,0,0,1,0,0,1,2,1,0,0,1,2,3,2,1,0,0,1,2,3,4,3,2,1,0,0,1,2,3,4,5,4,3,2,1,0,0,1,2,3,4,5,6,5,4,3,2,1,0,0,1,2,3,4,5,5,4,3,2,1,0,0,1,2,3,4,4,4,3,2,1,0,0,1,2,3,3,3,3,2,1,0,0,1,2,2,2,2,2,1,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0};
// Patterns for the monte carlo simulation
// See Lynx3-patterns.cpp
extern const std::vector<unsigned long long> patterns[107]; // defined in Lynx3-patterns.cpp
// Get a move from the opening book based on the moves played so far
// Returns either the move from the opening book, or 0 if the opening book does not contain the given move sequence
extern int getOpeningMove(const std::vector<int> &history); // defined in Lynx3-opening.cpp
static long long nanoTime()
{
return clock()*(1000000000LL/CLOCKS_PER_SEC);
}
// A random number generator.
// Derived from Random.java, removed synchronization and other checks to improve performance
class Rng
{
unsigned long long seed;
public:
Rng(unsigned long long s) : seed(s) { }
unsigned randomInt() {
seed = seed * 0x5deece66dULL + 0xbULL;
return (seed >> 16);
}
int randomInt(int n)
{
// Not completely correct, as results are a little biased, but good enough for our purpose
// We shift by 16 because the higher bits provide higher quality randomness
return (randomInt() >> 16) % n;
}
};
// The result of a set of AMAF playouts (as constructed by)
struct AmafPlayout
{
int samples; // The number of samples performed
int wins; // The number of times we won
int mySamples[POSITIONS + 1]; // mySamples[i] is the number of samples where move i was played by me
int myWins[POSITIONS + 1]; // myWins[i] is the number of samples where move i was played by me and I won
int opSamples[POSITIONS + 1]; // opSamples[i] is the number of samples where move i was played by the opponent
int opWins[POSITIONS + 1]; // opWins[i] is the number of samples where move i was played by the opponent and I won
};
// This class encodes a game state
struct GameState
{
// The moves that can still be played in this state, up to index 'end' defined below
unsigned char remainingMoves[POSITIONS];
// The position of a given move in the remainingMoves array, i.e. positions[i] is the position of move i in the remainingMoves array
// This array is used to allow O(1) removal of moves from the remainingMoves array
unsigned char positions[POSITIONS + 1];
// Moves in remainingMoves starting from index end have already been played
int end;
// Bit sets encoding the board state
unsigned long long myMovesLeft, myMovesRight; // Moves played by me
unsigned long long opMovesLeft, opMovesRight; // Moves played by the opponent
public:
// Constructs the initial game state
GameState()
{
for(int i = 0; i < POSITIONS; i++) {
remainingMoves[i] = (i + 1);
positions[i + 1] = i;
}
end = POSITIONS;
myMovesLeft = myMovesRight = 0;
opMovesLeft = opMovesRight = 0;
}
// Copy constructor
GameState(const GameState &other)
{
std::copy(other.remainingMoves, other.remainingMoves + other.end, remainingMoves);
std::copy(other.positions + 1, other.positions + POSITIONS + 1, positions + 1);
end = other.end;
myMovesLeft = other.myMovesLeft;
myMovesRight = other.myMovesRight;
opMovesLeft = other.opMovesLeft;
opMovesRight = other.opMovesRight;
}
// Swaps the moves done by the players
void swapPlayers()
{
unsigned long long mML = myMovesLeft;
unsigned long long mMR = myMovesRight;
myMovesLeft = opMovesLeft;
myMovesRight = opMovesRight;
opMovesLeft = mML;
opMovesRight = mMR;
}
// Sets the move at the given index as unavailable for playing
// Swaps the move at the given index in remainingMoves with the move at remainingMoves[end - 1] and reduces end by one
void swapOut(int index)
{
end--;
swapMoveIndices(index, end);
}
// Sets a given move as unavailable for playing
void remove(int move)
{
swapOut(positions[move]);
}
// Swaps two entries in the remainingMoves array
void swapMoveIndices(int i, int j)
{
unsigned char temp = remainingMoves[i];
remainingMoves[i] = remainingMoves[j];
remainingMoves[j] = temp;
// Update the positions of the entries
positions[remainingMoves[i]] = i;
positions[remainingMoves[j]] = j;
}
// Updates the state with my move
void updateMyMove(int move)
{
remove(move);
if (move < 64) {
myMovesLeft |= 1ULL << move;
} else {
myMovesRight |= 1ULL << (move - 64);
}
}
// Updates the state with an opponent move
void updateOpMove(int move)
{
remove(move);
if (move < 64) {
opMovesLeft |= 1ULL << move;
} else {
opMovesRight |= 1ULL << (move - 64);
}
}
// Monte carlo sampling with the all-moves-as-first (AMAF) heuristic
AmafPlayout sample(const bool myMoveAtStart, Rng &rng)
{
AmafPlayout result = AmafPlayout();
result.samples += SAMPLES;
unsigned long long _cML, _cMR; // The moves done by the current player
unsigned long long _oML, _oMR; // The moves done by the opponent of the current player
if (myMoveAtStart) {
_cML = myMovesLeft;
_cMR = myMovesRight;
_oML = opMovesLeft;
_oMR = opMovesRight;
} else {
_cML = opMovesLeft;
_cMR = opMovesRight;
_oML = myMovesLeft;
_oMR = myMovesRight;
}
const bool myMoveAtEnd = myMoveAtStart ^ ((end & 1) == 1); // Is it my move at the end of the game?
int play[11]; // Stack that encodes possible moves that can be played based on patterns
// Perform the given number of sample games
for(int m = 0; m < SAMPLES; m++) {
// The moves done by the current player
unsigned long long cML = _cML;
unsigned long long cMR = _cMR;
// The moves done by the opponent of the current player
unsigned long long oML = _oML;
unsigned long long oMR = _oMR;
int end = this->end; // We use a copy of end to see which moves we can still do in this simulation run
int lastMove = 0; // The last move done by the opponent
while(end > 0) {
int move = 0;
// Respond to the last opponent move based on patterns
if(lastMove != 0) {
int pc = 0; // Index pointing to the top of the 'play' stack
const std::vector<unsigned long long> &ps = patterns[lastMove]; // Patterns that we have to apply
for(int i = 0; i < (int)ps.size(); i += 4) {
// Check if pattern matches
if((ps[i] & cML) == ps[i] && (ps[i + 1] & cMR) == ps[i + 1] && (ps[i + 2] & oML) == 0 && (ps[i + 3] & oMR) == 0 && !isSet(cML, cMR, (int)(ps[i + 3] >> 48))) {
// Pattern matches, add the move corresponding to this pattern to the play stack
play[pc++] = (int)(ps[i + 3] >> 48);
}
}
if(pc > 0) {
// Select a random move from the play stack
move = play[rng.randomInt(pc)];
}
}
// If the patterns did not result in a move, do a random move
if(move == 0) {
move = remainingMoves[rng.randomInt(end)];
// Bias moves early in the game away from the edges, the idea is that more patterns will develop than fully random play
if(end > 96) {
// At the beginning of the game (first 10 moves), only play in the middle of the board
while(edgeDistance[move] < 2) {
move = remainingMoves[rng.randomInt(end)];
}
} else if(end > EDGE_BIAS_THRESHOLD) {
while(edgeDistance[move] < 1) {
// Avoid moves at edges early in the simulation
move = remainingMoves[rng.randomInt(end)];
}
}
}
// Remove the chosen move from available moves
swapMoveIndices(positions[move], --end);
// Add the move to current player
if (move < 64) {
cML |= 1ULL << move;
} else {
cMR |= 1ULL << (move - 64);
}
lastMove = move;
// Swap players
unsigned long long cML_ = cML;
unsigned long long cMR_ = cMR;
cML = oML;
cMR = oMR;
oML = cML_;
oMR = cMR_;
}
// Did we win?
// 1: we won
// 0: we lost
int win = myMoveAtEnd == (winner(cML, cMR) ? 1 : 0);
// Update the AMAF playout result
result.wins += win;
for(int j = 1; j < POSITIONS + 1; j++) {
if((myMoveAtEnd == isSet(cML, cMR, j))) { // We have set j
result.mySamples[j]++; // Our samples with this move
result.myWins[j] += win; // Our wins with this move
} else {
result.opSamples[j]++; // Our samples when the opponent played this move
result.opWins[j] += win; // Our number of wins when the opponent played this move
}
}
}
return result;
}
// Is a given position set in the bitset given by l and r?
bool isSet(unsigned long long l, unsigned long long r, int i)
{
return (i < 64 && ((1ULL << i) & l) != 0) || (i >= 64 && ((1ULL << (i - 64)) & r) != 0);
}
// Determine the winner given a board encoded in the bitset given by l and r
bool winner(unsigned long long l, unsigned long long r)
{
int todo[POSITIONS]; // Stack for depth first search
// l and r encode the positions on the board that have been played by us.
// Note that we update l and r in this method to remove nodes that we have already seen in the DFS search
// I.e. l and r encode the nodes played by us that we have not yet processed
int corners = 0; // The corners that we have captured
// Do a depth first search from the positions along long the edge to find the edges connected from this position
for(int i : edge) {
if(isSet(l, r, i)) { // Did we play this move?
int top = 0; // Index for the top of the stack
todo[top++] = i; // Start the search from position i
int edges = 0; // The edges connected by the current component
while(top != 0) {
// Process the node on the top of the stack
int current = todo[--top]; // Pop one position from the stack
edges |= ::edges[current]; // Update the edges reachable
// Add neighbours of the current node to the stack
for(int j = 0; neighbours[current][j] != 0; j++) {
int n = neighbours[current][j];
if(isSet(l, r, n)) { // Is this node played by us?
// Mark the neighbour as processed
if (n < 64) {
l &= ~(1ULL << n);
} else {
r &= ~(1ULL << (n - 64));
}
// Add the neighour to the top of the stack
todo[top++] = n;
// Optimization: we do not have to check the next neighbour
// Proven by hand waving and the absence of a counter example
j++;
}
}
}
// Update the corners captured by the connected edges
corners |= cornerSet[edges];
// If we won with the given captured corners, we can stop
if(win[corners]) {
return true;
}
}
}
// We did not win
return false;
}
};
// The statistics stored in a node
class Statistics
{
private:
friend class Tree;
int samples; // The number of times this node has been sampled
int wins; // The number of samples where we have won
int amafSamples[POSITIONS + 1]; // amafSamples[i] is the number of times move i was played in a monte carlo game
int amafWins[POSITIONS + 1]; // amafWins[i] is the number of times move i was played in a monte carlo game, and we won
// Update the statistics with a given playout result
void add(const AmafPlayout &playout, bool myMove)
{
samples += playout.samples;
wins += playout.wins;
if(myMove) {
// If it is my move, add the statistics for my moves
for(int i = 1; i < POSITIONS + 1; i++) {
amafSamples[i] += playout.mySamples[i];
amafWins[i] += playout.myWins[i];
}
} else {
// If it is the opponent move, add the statistics for the opponent moves
for(int i = 1; i < POSITIONS + 1; i++) {
amafSamples[i] += playout.opSamples[i];
amafWins[i] += playout.opWins[i];
}
}
}
};
// Implementation of a tree node for monte carlo tree search (MTCS)
class Tree
{
private:
friend class TreeBotFinal;
GameState state; // The game state at the current node
bool myMove; // Is it my move? (note that this could also be passed around instead of storing it in tree nodes)
// Statistics gathered about child nodes based on the AMAF heuristic
Statistics statistics;
// A mapping of moves to child nodes
// FIXME: turn this into a hash-map?
Tree* children[POSITIONS + 1];
public:
// Constructs a tree node given a state and whether it is my move
Tree(const GameState &state, bool myMove)
: state(state), myMove(myMove), statistics(), children() { }
// Constructs a tree node with a default state
Tree(bool myMove) : state(), myMove(myMove), statistics(), children() { }
// Constructs a child node from a parent node and a given move
Tree(const Tree &parent, int m)
: state(parent.state), myMove(!parent.myMove), statistics(), children()
{
if(parent.myMove) state.updateMyMove(m);
else state.updateOpMove(m);
}
// Destructs a tree node and frees all child nodes
~Tree()
{
for (auto child : children) delete child;
}
// Gets the child node of this node for a given move
// NOTE: this removes the subtree from its parent, to avoid double-freeing!
Tree *treeAfterMove(int move)
{
Tree *child = children[move];
if (child == nullptr) {
return new Tree(*this, move);
}
children[move] = nullptr;
return child;
}
// Computes the best move given some amount of computation time
int findBestMove(double time, int fixedIterations, Rng &rng)
{
long long start = nanoTime();
// Call expand() as long long as we have time, or if fixedIterations > 0,
// just run the required number of iterations.
int iterations = 0;
while(state.end > 0) {
expand(rng);
++iterations;
if (fixedIterations > 0) {
if (iterations >= fixedIterations) break;
} else if (iterations%64 == 0) {
if ((nanoTime() - start >= time * 1000000000)) break;
}
}
std::cerr << "Expanded " << iterations << " nodes." << std::endl;
// Select the move with the highest number of samples
int bestScore = -1;
int bestMove = state.remainingMoves[0];
for(int i = 0; i < state.end; i++) {
int move = state.remainingMoves[i];
const Tree *child = children[move];
if(child != nullptr) {
int score = child->statistics.samples;
if(score > bestScore) {
bestScore = score;
bestMove = move;
}
}
}
return bestMove;
}
// Expands the tree by creating the most promising child node, playing a monte carlo playout in this child node, and updating the statistics in all parent nodes
AmafPlayout expand(Rng &rng) {
AmafPlayout result = AmafPlayout();
// If there are no moves remaining in this node, we are done
if(state.end == 0) return result;
int selected = 0;
// Select the best node for the current player
if(myMove) {
// Select the node with the highest win rate
double bestScore = -1.0;
for(int i = 0; i < state.end; i++) {
int move = state.remainingMoves[i];
// Compute the win rate based on the AMAF heuristic
double score = ((double) statistics.amafWins[move]) / statistics.amafSamples[move];
// If we have actual samples of this node available, we do a linear interpolation of the
// AMAF score with the actual samples based on the ALPHA parameter (alpha-AMAF)
const Tree *child = children[move];
if(child != nullptr) {
score = score * ALPHA + (((double) child->statistics.wins) / child->statistics.samples) * (1.0 - ALPHA);
}
// If there is no data at all available for this node, we must investigate it
if(statistics.amafSamples[move] == 0) {
score = 100.0;
}
if(score > bestScore) {
bestScore = score;
selected = move;
}
}
} else {
// Select the node with the lowest win rate
double bestScore = -1.0;
for(int i = 0; i < state.end; i++) {
int move = state.remainingMoves[i];
// Compute the win rate based on the AMAF heuristic
double score = ((double) (statistics.amafSamples[move] - statistics.amafWins[move])) / statistics.amafSamples[move];
// If we have actual samples of this node available, we do a linear interpolation of the
// AMAF score with the actual samples based on the ALPHA parameter (alpha-AMAF)
const Tree *child = children[move];
if(child != nullptr) {
score = score * ALPHA + (((double) (child->statistics.samples - child->statistics.wins)) / child->statistics.samples) * (1.0 - ALPHA);
}
// If there is no data at all available for this node, we must investigate it
if(statistics.amafSamples[move] == 0) {
score = 100.0;
}
if(score > bestScore) {
bestScore = score;
selected = move;
}
}
}
Tree *&child = children[selected];
if(child == nullptr) {
// If this child does not exist, create it
child = new Tree(*this, selected);
// Evaluate this node with monte-carlo sampling
// The result is a AmafPlayout instance containing number of wins, samples and AMAF statistics (number of wins and samples for all other moves played)
result = child->state.sample(child->myMove, rng);
// Update the statistics of the child node
child->statistics.add(result, child->myMove);
} else {
// The child exists, recursively expand this child
result = child->expand(rng);
}
// Update the statistics of this node
statistics.add(result, myMove);
return result;
}
};
// Our player
class TreeBotFinal
{
private:
// The game tree for the current game position
Tree *tree = nullptr;
// The moves that have been played so far, used for querying the opening book
std::vector<int> playedMoves;
// Is this the first time we are playing?
bool isFirst = true;
// The random number generator.
Rng rng;
public:
TreeBotFinal(unsigned long long rng_seed = time(NULL))
: rng(rng_seed)
{
}
~TreeBotFinal()
{
delete tree;
}
int play(int lastMove, double remainingTime, int fixedIterations = 0)
{
if(lastMove > 0) {
playedMoves.push_back(lastMove);
}
// Process opponent move
{
Tree *old_tree = tree;
if(lastMove > 0) {
if(old_tree == nullptr) {
// If there is no game tree yet, construct one
old_tree = new Tree(false);
}
// Update the root of the tree to the child tree corresponding to the opponents move
tree = old_tree->treeAfterMove(lastMove);
} else {
// I start the game
if(lastMove == 0) {
tree = new Tree(true);
}
// Opponent chose to swap places
if(lastMove == -1) {
old_tree->state.swapPlayers();
tree = new Tree(old_tree->state, true);
}
}
delete old_tree;
}
// The move that we are going to play
int bestMove;
if(isFirst && lastMove != 0 && (edgeDistance[lastMove] > 1 || lastMove == 15 || lastMove == 24 || lastMove == 71 || lastMove == 81 || lastMove == 96 || lastMove == 95 || lastMove == 74 || lastMove == 63 || lastMove == 18 || lastMove == 11)) {
bestMove = -1; // We swap for all symmetries of move 15, and for all center moves (edge distance > 1)
} else {
// Query the opening book
bestMove = getOpeningMove(playedMoves);
if(bestMove == 0) {
// If the opening book has no entry, compute the best move
bestMove = tree->findBestMove(std::max(remainingTime / TIME_DIVIDER, MINIMUM_TIME), fixedIterations, rng);
if(bestMove == 0) bestMove = tree->state.remainingMoves[0];
}
}
// Update the game tree based on the move that we have selected
{
Tree *old_tree = tree;
if(bestMove == -1) {
old_tree->state.swapPlayers();
tree = new Tree(tree->state, false);
} else {
// Update the root of the tree to the move corresponding to our move
tree = old_tree->treeAfterMove(bestMove);
}
delete old_tree;
}
isFirst = false;
if(bestMove != -1) {
playedMoves.push_back(bestMove);
}
return bestMove;
}
};
// Plays the oppenent's given move, and returns the bot's response.
// If the move is 0, the bot will start. (This is a function separate from
// main() so it can be called interactively in the web frontend.)
extern "C" int play(int move, int fixedIterations = 0)
{
static TreeBotFinal bot;
static double remainingTime = TOTAL_TIME;
long long start = nanoTime();
int response = bot.play(move, remainingTime, fixedIterations);
long long end = nanoTime();
double time = (double)(end - start)/1000000000;
remainingTime -= time;
std::cerr << response << std::endl;
std::cerr << "Used " << time << " seconds, " << remainingTime << " seconds remaining." << std::endl;
return response;
}
static int getMove()
{
std::string line;
std::getline(std::cin, line);
int move;
if (line == "Start") return 0;
if (line == "Quit") exit(0);
if (std::istringstream(line) >> move) return move;
exit(1);
}
static void doMove(int position)
{
std::cout << position << std::endl;
}
int main(int argc, char *argv[])
{
while(true) {
doMove(play(getMove()));
}
}
| true |
9505da2df99b277d4b2eb2f9035e1568146d5a54 | C++ | jarble/transpiler | /translated_functions/translated_functions.cpp | UTF-8 | 684 | 3.53125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
template <class T>
void print(T a) {
std::cout << a << "\n";
}
template <class T>
int abs(T a){
return std::abs(a);
}
template <class T>
int len(T a){
return a.size();
}
template <class t1,class t2,class t3>t3 add(t1 A,t1 B){
return A+B;
}
int main ()
{
std::vector<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i=0; i<10; i++) myints.push_back(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert (myints.end(),10,100);
print("2. size: ");
print(len(myints));
print(add(3,4));
myints.pop_back();
std::cout << "3. size: " << myints.size() << '\n';
return 0;
}
| true |
2f11a2968f75eed00c44939eb5d21f618357bfeb | C++ | Finkman/json-schema-validator | /src/string-format-check.cpp | UTF-8 | 13,654 | 3.140625 | 3 | [
"MIT"
] | permissive | #include <nlohmann/json-schema.hpp>
#include <algorithm>
#include <exception>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
/**
* Many of the RegExes are from @see http://jmrware.com/articles/2009/uri_regexp/URI_regex.html
*/
namespace
{
template <typename T>
void range_check(const T value, const T min, const T max)
{
if (!((value >= min) && (value <= max))) {
std::stringstream out;
out << "Value " << value << " should be in interval [" << min << "," << max << "] but is not!";
throw std::invalid_argument(out.str());
}
}
/** @see date_time_check */
void rfc3339_date_check(const std::string &value)
{
const static std::regex dateRegex{R"(^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$)"};
std::smatch matches;
if (!std::regex_match(value, matches, dateRegex)) {
throw std::invalid_argument(value + " is not a date string according to RFC 3339.");
}
const auto year = std::stoi(matches[1].str());
const auto month = std::stoi(matches[2].str());
const auto mday = std::stoi(matches[3].str());
const auto isLeapYear = (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
range_check(month, 1, 12);
if (month == 2) {
range_check(mday, 1, isLeapYear ? 29 : 28);
} else if (month <= 7) {
range_check(mday, 1, month % 2 == 0 ? 30 : 31);
} else {
range_check(mday, 1, month % 2 == 0 ? 31 : 30);
}
}
/** @see date_time_check */
void rfc3339_time_check(const std::string &value)
{
const static std::regex timeRegex{R"(^([0-9]{2})\:([0-9]{2})\:([0-9]{2})(\.[0-9]+)?(?:[Zz]|((?:\+|\-)[0-9]{2})\:([0-9]{2}))$)"};
std::smatch matches;
if (!std::regex_match(value, matches, timeRegex)) {
throw std::invalid_argument(value + " is not a time string according to RFC 3339.");
}
auto hour = std::stoi(matches[1].str());
auto minute = std::stoi(matches[2].str());
auto second = std::stoi(matches[3].str());
// const auto secfrac = std::stof( matches[4].str() );
range_check(hour, 0, 23);
range_check(minute, 0, 59);
int offsetHour = 0,
offsetMinute = 0;
/* don't check the numerical offset if time zone is specified as 'Z' */
if (!matches[5].str().empty()) {
offsetHour = std::stoi(matches[5].str());
offsetMinute = std::stoi(matches[6].str());
range_check(offsetHour, -23, 23);
range_check(offsetMinute, 0, 59);
if (offsetHour < 0)
offsetMinute *= -1;
}
/**
* @todo Could be made more exact by querying a leap second database and choosing the
* correct maximum in {58,59,60}. This current solution might match some invalid dates
* but it won't lead to false negatives. This only works if we know the full date, however
*/
auto day_minutes = hour * 60 + minute - (offsetHour * 60 + offsetMinute);
if (day_minutes < 0)
day_minutes += 60 * 24;
hour = day_minutes % 24;
minute = day_minutes / 24;
if (hour == 23 && minute == 59)
range_check(second, 0, 60); // possible leap-second
else
range_check(second, 0, 59);
}
/**
* @see https://tools.ietf.org/html/rfc3339#section-5.6
*
* @verbatim
* date-fullyear = 4DIGIT
* date-month = 2DIGIT ; 01-12
* date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
* ; month/year
* time-hour = 2DIGIT ; 00-23
* time-minute = 2DIGIT ; 00-59
* time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second
* ; rules
* time-secfrac = "." 1*DIGIT
* time-numoffset = ("+" / "-") time-hour ":" time-minute
* time-offset = "Z" / time-numoffset
*
* partial-time = time-hour ":" time-minute ":" time-second
* [time-secfrac]
* full-date = date-fullyear "-" date-month "-" date-mday
* full-time = partial-time time-offset
*
* date-time = full-date "T" full-time
* @endverbatim
* NOTE: Per [ABNF] and ISO8601, the "T" and "Z" characters in this
* syntax may alternatively be lower case "t" or "z" respectively.
*/
void rfc3339_date_time_check(const std::string &value)
{
const static std::regex dateTimeRegex{R"(^([0-9]{4}\-[0-9]{2}\-[0-9]{2})[Tt]([0-9]{2}\:[0-9]{2}\:[0-9]{2}(?:\.[0-9]+)?(?:[Zz]|(?:\+|\-)[0-9]{2}\:[0-9]{2}))$)"};
std::smatch matches;
if (!std::regex_match(value, matches, dateTimeRegex)) {
throw std::invalid_argument(value + " is not a date-time string according to RFC 3339.");
}
rfc3339_date_check(matches[1].str());
rfc3339_time_check(matches[2].str());
}
const std::string decOctet{R"((?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]))"}; // matches numbers 0-255
const std::string ipv4Address{"(?:" + decOctet + R"(\.){3})" + decOctet};
const std::string h16{R"([0-9A-Fa-f]{1,4})"};
const std::string h16Left{"(?:" + h16 + ":)"};
const std::string ipv6Address{
"(?:"
"(?:" +
h16Left + "{6}"
"|::" +
h16Left + "{5}"
"|(?:" +
h16 + ")?::" + h16Left + "{4}"
"|(?:" +
h16Left + "{0,1}" + h16 + ")?::" + h16Left + "{3}"
"|(?:" +
h16Left + "{0,2}" + h16 + ")?::" + h16Left + "{2}"
"|(?:" +
h16Left + "{0,3}" + h16 + ")?::" + h16Left +
"|(?:" + h16Left + "{0,4}" + h16 + ")?::"
")(?:" +
h16Left + h16 + "|" + ipv4Address + ")"
"|(?:" +
h16Left + "{0,5}" + h16 + ")?::" + h16 +
"|(?:" + h16Left + "{0,6}" + h16 + ")?::"
")"};
const std::string ipvFuture{R"([Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&'()*+,;=:]+)"};
const std::string regName{R"((?:[A-Za-z0-9\-._~!$&'()*+,;=]|%[0-9A-Fa-f]{2})*)"};
const std::string host{
"(?:"
R"(\[(?:)" +
ipv6Address + "|" + ipvFuture + R"()\])" +
"|" + ipv4Address +
"|" + regName +
")"};
const std::string uuid{R"([0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12})"};
// from http://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
const std::string hostname{R"(^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$)"};
/**
* @see https://tools.ietf.org/html/rfc5322#section-4.1
*
* @verbatim
* atom = [CFWS] 1*atext [CFWS]
* word = atom / quoted-string
* phrase = 1*word / obs-phrase
* obs-FWS = 1*WSP *(CRLF 1*WSP)
* FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
* ; Folding white space
* ctext = %d33-39 / ; Printable US-ASCII
* %d42-91 / ; characters not including
* %d93-126 / ; "(", ")", or "\"
* obs-ctext
* ccontent = ctext / quoted-pair / comment
* comment = "(" *([FWS] ccontent) [FWS] ")"
* CFWS = (1*([FWS] comment) [FWS]) / FWS
* obs-local-part = word *("." word)
* obs-domain = atom *("." atom)
* obs-dtext = obs-NO-WS-CTL / quoted-pair
* quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
* obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
* %d11 / ; characters that do not
* %d12 / ; include the carriage
* %d14-31 / ; return, line feed, and
* %d127 ; white space characters
* obs-ctext = obs-NO-WS-CTL
* obs-qtext = obs-NO-WS-CTL
* obs-utext = %d0 / obs-NO-WS-CTL / VCHAR
* obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
* obs-body = *((*LF *CR *((%d0 / text) *LF *CR)) / CRLF)
* obs-unstruct = *((*LF *CR *(obs-utext *LF *CR)) / FWS)
* obs-phrase = word *(word / "." / CFWS)
* obs-phrase-list = [phrase / CFWS] *("," [phrase / CFWS])
* qtext = %d33 / ; Printable US-ASCII
* %d35-91 / ; characters not including
* %d93-126 / ; "\" or the quote character
* obs-qtext
* qcontent = qtext / quoted-pair
* quoted-string = [CFWS]
* DQUOTE *([FWS] qcontent) [FWS] DQUOTE
* [CFWS]
* atext = ALPHA / DIGIT / ; Printable US-ASCII
* "!" / "#" / ; characters not including
* "$" / "%" / ; specials. Used for atoms.
* "&" / "'" /
* "*" / "+" /
* "-" / "/" /
* "=" / "?" /
* "^" / "_" /
* "`" / "{" /
* "|" / "}" /
* "~"
* dot-atom-text = 1*atext *("." 1*atext)
* dot-atom = [CFWS] dot-atom-text [CFWS]
* addr-spec = local-part "@" domain
* local-part = dot-atom / quoted-string / obs-local-part
* domain = dot-atom / domain-literal / obs-domain
* domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
* dtext = %d33-90 / ; Printable US-ASCII
* %d94-126 / ; characters not including
* obs-dtext ; "[", "]", or "\"
* @endverbatim
* @todo Currently don't have a working tool for this larger ABNF to generate a regex.
* Other options:
* - https://github.com/ldthomas/apg-6.3
* - https://github.com/akr/abnf
*
* The problematic thing are the allowed whitespaces (even newlines) in the email.
* Ignoring those and starting with
* @see https://stackoverflow.com/questions/13992403/regex-validation-of-email-addresses-according-to-rfc5321-rfc5322
* and trying to divide up the complicated regex into understandable ABNF definitions from rfc5322 yields:
*/
const std::string obsnowsctl{R"([\x01-\x08\x0b\x0c\x0e-\x1f\x7f])"};
const std::string obsqp{R"(\\[\x01-\x09\x0b\x0c\x0e-\x7f])"};
const std::string qtext{R"((?:[\x21\x23-\x5b\x5d-\x7e]|)" + obsnowsctl + ")"};
const std::string dtext{R"([\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f])"};
const std::string quotedString{R"("(?:)" + qtext + "|" + obsqp + R"()*")"};
const std::string atext{R"([A-Za-z0-9!#$%&'*+/=?^_`{|}~-])"};
const std::string domainLiteral{R"(\[(?:(?:)" + decOctet + R"()\.){3}(?:)" + decOctet + R"(|[A-Za-z0-9-]*[A-Za-z0-9]:(?:)" + dtext + "|" + obsqp + R"()+)\])"};
const std::string dotAtom{"(?:" + atext + R"(+(?:\.)" + atext + "+)*)"};
const std::string stackoverflowMagicPart{R"((?:[[:alnum:]](?:[[:alnum:]-]*[[:alnum:]])?\.)+)"
R"([[:alnum:]](?:[[:alnum:]-]*[[:alnum:]])?)"};
const std::string email{"(?:" + dotAtom + "|" + quotedString + ")@(?:" + stackoverflowMagicPart + "|" + domainLiteral + ")"};
} // namespace
namespace nlohmann
{
namespace json_schema
{
/**
* Checks validity for built-ins by converting the definitions given as ABNF in the linked RFC from
* @see https://json-schema.org/understanding-json-schema/reference/string.html#built-in-formats
* into regular expressions using @see https://www.msweet.org/abnf/ and some manual editing.
*
* @see https://json-schema.org/latest/json-schema-validation.html
*/
void default_string_format_check(const std::string &format, const std::string &value)
{
if (format == "date-time") {
rfc3339_date_time_check(value);
} else if (format == "date") {
rfc3339_date_check(value);
} else if (format == "time") {
rfc3339_time_check(value);
} else if (format == "email") {
static const std::regex emailRegex{email};
if (!std::regex_match(value, emailRegex)) {
throw std::invalid_argument(value + " is not a valid email according to RFC 5322.");
}
} else if (format == "hostname") {
static const std::regex hostRegex{hostname};
if (!std::regex_match(value, hostRegex)) {
throw std::invalid_argument(value + " is not a valid hostname according to RFC 3986 Appendix A.");
}
} else if (format == "ipv4") {
const static std::regex ipv4Regex{"^" + ipv4Address + "$"};
if (!std::regex_match(value, ipv4Regex)) {
throw std::invalid_argument(value + " is not an IPv4 string according to RFC 2673.");
}
} else if (format == "ipv6") {
static const std::regex ipv6Regex{ipv6Address};
if (!std::regex_match(value, ipv6Regex)) {
throw std::invalid_argument(value + " is not an IPv6 string according to RFC 5954.");
}
} else if (format == "uuid") {
static const std::regex uuidRegex{uuid};
if (!std::regex_match(value, uuidRegex)) {
throw std::invalid_argument(value + " is not an uuid string according to RFC 4122.");
}
} else if (format == "regex") {
try {
std::regex re(value, std::regex::ECMAScript);
} catch (std::exception &exception) {
throw exception;
}
} else {
/* yet unsupported JSON schema draft 7 built-ins */
static const std::vector<std::string> jsonSchemaStringFormatBuiltIns{
"date-time", "time", "date", "email", "idn-email", "hostname", "idn-hostname", "ipv4", "ipv6", "uri",
"uri-reference", "iri", "iri-reference", "uri-template", "json-pointer", "relative-json-pointer", "regex"};
if (std::find(jsonSchemaStringFormatBuiltIns.begin(), jsonSchemaStringFormatBuiltIns.end(), format) != jsonSchemaStringFormatBuiltIns.end()) {
throw std::logic_error("JSON schema string format built-in " + format + " not yet supported. " +
"Please open an issue or use a custom format checker.");
}
throw std::logic_error("Don't know how to validate " + format);
}
}
} // namespace json_schema
} // namespace nlohmann
| true |
c43777fac6887ee1edabc64eb94c202f4d5d7377 | C++ | marsteen/mvobjreader | /project/include/CRectT.hpp | ISO-8859-1 | 3,880 | 3.078125 | 3 | [] | no_license | /**********************************************************************
*
* CRect Modul
*
* (c) 2003 Martin Steen / imagon GmbH
*
* Version 1.0
*
* 07-2003
*
* Rechteck Klasse
*
************************************************************************/
template<class T>
T maxT(T a, T b)
{
return (a > b) ? a : b;
}
template<class T>
T minT(T a, T b)
{
return (a < b) ? a : b;
}
//---------------------------------------------------------------------------
//
// Klasse: CRectT
// Methode: IntersectLine
//
// Die Schnittmenge zweier eindimensionaler Linien wird berechnet.
//
// Linie 1: von A1 nach B1
// Linie 2: von A2 nach B2
// Linie 3: von A3 nach B3
//
// Linie 3 ist die Schnittmenge der Linien 1 und 2. Fr den Fall, dass
// die beiden Linien sich nicht berschneiden, ist das Ergebnis
// undefiniert und false wird zurckgegeben.
//
// Rckgabewert: true - Linien berschneiden sich, Linie 3 (A3/B3)
// enthlt die Schnittmenge
//
// false - Schnittmenge ist leer
//
//---------------------------------------------------------------------------
template<class T>
bool CRectT<T>::IntersectLine(T A1, T B1, T A2, T B2, T* A3, T* B3) const
{
*A3 = maxT(A1, A2);
if ((*A3 > B1) || (*A3 > B2))
{
return false;
}
*B3 = minT(B1, B2);
if ((*B3 < A1) || (*B3 < A2))
{
return false;
}
return true;
}
//---------------------------------------------------------------------------
//
// Klasse: CRectT
// Methode: InterSectRect
//
// Die Schnittmenge zweier Rechtecke wird berechnet.
//
// ri enthalt die Schnittmenge der Rechtecke r1 und r2
//
// Rckgabewert: true - r1 und r2 haben Schnittmenge
//
// false - Schnittmenge leer
//
//---------------------------------------------------------------------------
template<class T>
bool CRectT<T>::InterSectRect(const CRectT* r2, CRectT* ri) const
{
if (IntersectLine(left, right, r2->left, r2->right, &(ri->left), &(ri->right)))
{
if (IntersectLine(top, bottom, r2->top, r2->bottom, &(ri->top), &(ri->bottom)))
{
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
//
// Klasse: CRectT
// Methode: TrimRect
//
//---------------------------------------------------------------------------
template<class T>
void CRectT<T>::TrimRect()
{
T SwapVal;
if (right < left)
{
SwapVal = left;
left = right;
right = SwapVal;
}
if (bottom < top)
{
SwapVal = top;
top = bottom;
bottom = SwapVal;
}
}
//---------------------------------------------------------------------------
//
// Klasse: CRectT
// Methode: InRect
//
// Rckgabewert: true - Punkt x,y ist im Rechteck
//
// false - nicht im Rechteck
//---------------------------------------------------------------------------
template<class T>
bool CRectT<T>::InRect(T x, T y)
{
return (x >= left) && (x <= right) &&
(y >= top) && (y <= bottom);
}
//---------------------------------------------------------------------------
//
// Klasse: CRectT
// Methode: Add
//
//---------------------------------------------------------------------------
template<class T>
void CRectT<T>::Add(T xoff, T yoff)
{
left += xoff;
top += yoff;
right += xoff;
bottom += yoff;
}
//---------------------------------------------------------------------------
//
// Klasse: CRect
// Methode: Show
//
//
//---------------------------------------------------------------------------
template<class T>
void CRectT<T>::Show(const char* title, std::stringstream& mstr)
{
mstr << title
<< " l=" << left
<< " t=" << top
<< " r=" << right
<< " b=" << bottom;
}
| true |
1882d68b6ea7325afbeb6019fd3953c802bd5a88 | C++ | cliff000/TeamProject2019 | /TeamProject2019/State.h | SHIFT_JIS | 689 | 2.6875 | 3 | [] | no_license | #pragma once
#include "Image.h"
//O錾
class Unit;
class AttackState;
class DefenseState;
class ThrowState;
class BlockState;
class State
{
protected:
int img;
Unit* owner; //statȅ
public:
State();
~State();
virtual void update() {}
virtual void draw(int x, int y, double extRate, bool turnFlag);
void setOwner(Unit* owner);
//jbgmՓ˂̏
void hitAction(State* other);
//ȉ̃NXI[o[ChĎg
virtual void hitAction(AttackState* other){}
virtual void hitAction(DefenseState* other){}
virtual void hitAction(ThrowState* other){}
virtual void hitAction(BlockState* other){}
};
| true |
a6b120647fa624ad9b1f464e67ce01fde7d4961c | C++ | xyuan/Tempest | /src/matrix.cpp | UTF-8 | 10,087 | 2.921875 | 3 | [] | no_license | /*!
* \file matrix.cpp
* \brief Class for simplified matrix storage & manipulation
*
* \author - Jacob Crabill
* Aerospace Computing Laboratory (ACL)
* Aero/Astro Department. Stanford University
*
* \version 0.0.1
*
* Flux Reconstruction in C++ (Flurry++) Code
* Copyright (C) 2014 Jacob Crabill.
*
*/
#include "../include/matrix.hpp"
#include <set>
template<typename T, uint N>
matrixBase<T,N>::matrixBase()
{
data.resize(0);
dims = {{0,0,0,0}};
}
template<typename T, uint N>
matrixBase<T,N>::matrixBase(uint inDim0, uint inDim1, uint inDim2, uint inDim3)
{
data.resize(inDim0*inDim1*inDim2*inDim3);
dims = {{inDim0,inDim1,inDim2,inDim3}};
}
template<typename T>
matrix<T>::matrix()
{
}
template<typename T>
matrix<T>::matrix(uint inDim0, uint inDim1)
{
this->data.resize(inDim0*inDim1);
this->dims = {{inDim0,inDim1,1,1}};
}
template<typename T, uint N>
matrixBase<T,N>::matrixBase(const matrixBase<T,N> &inMatrix)
{
data = inMatrix.data;
dims = inMatrix.dims;
}
template<typename T, uint N>
matrixBase<T,N> matrixBase<T,N>::operator=(const matrixBase<T,N> &inMatrix)
{
data = inMatrix.data;
dims = inMatrix.dims;
return *this;
}
template<typename T, uint N>
void matrixBase<T,N>::setup(uint inDim0, uint inDim1, uint inDim2, uint inDim3)
{
dims = {{inDim0,inDim1,inDim2,inDim3}};
data.resize(inDim0*inDim1*inDim2*inDim3);
}
template<typename T, uint N>
T* matrixBase<T,N>::operator[](int inRow)
{
if (inRow < (int)this->dims[0] && inRow >= 0) {
return &data[inRow*dims[1]];
}
else {
FatalError("Attempted out-of-bounds access in matrix.");
}
}
template<typename T, uint N>
T& matrixBase<T,N>::operator()(int i, int j, int k, int l)
{
if (i<(int)this->dims[0] && i>=0 && j<(int)this->dims[1] && j>=0 &&
k<(int)this->dims[2] && k>=0 && l<(int)this->dims[3] && l>= 0)
{
return data[l+dims[3]*(k+dims[2]*(j+dims[1]*i))];
}
else {
cout << "i=" << i << ", dim0=" << dims[0] << ", j=" << j << ", dim1=" << dims[1] << ", ";
cout << "k=" << k << ", dim2=" << dims[2] << ", l=" << l << ", dim3=" << dims[3] << endl;
FatalError("Attempted out-of-bounds access in Array.");
}
}
template<typename T>
T& matrix<T>::operator()(int i, int j)
{
if (i<(int)this->dims[0] && i>=0 && j<(int)this->dims[1] && j>=0) {
return this->data[j+this->dims[1]*i];
}
else {
cout << "i=" << i << ", dim0=" << this->dims[0] << ", j=" << j << ", dim1=" << this->dims[1];
FatalError("Attempted out-of-bounds access in matrix.");
}
}
template<typename T>
void matrix<T>::initializeToZero(void)
{
for (uint i=0; i<this->dims[0]; i++)
for (uint j=0; j<this->dims[1]; j++)
for (uint k=0; k<this->dims[2]; k++)
for (uint l=0; l<this->dims[3]; l++)
this->data[l+this->dims[3]*(k+this->dims[2]*(j+this->dims[1]*i))] = 0;
}
template<typename T>
void matrix<T>::initializeToValue(T val)
{
for (uint i=0; i<this->dims[0]; i++)
for (uint j=0; j<this->dims[1]; j++)
for (uint k=0; k<this->dims[2]; k++)
for (uint l=0; l<this->dims[3]; l++)
this->data[l+this->dims[3]*(k+this->dims[2]*(j+this->dims[1]*i))] = val;
}
//template<typename T>
//void matrix<T,1>::insertRow(const vector<T> &vec, int rowNum)
//{
// data.insert(data.begin()+rowNum,vec.begin(),1);
// if (dims[0] == 0) {
// dims = {{1,1,1,1}};
// }
// else {
// dims = {{dims[0]+1,1,1,1}};
// }
//}
template<typename T, uint N>
void matrixBase<T,N>::insertRow(const vector<T> &vec, int rowNum)
{
if (N!=2)
FatalError("InsertRow only supported for 2D arrays.");
if (this->dims[1]!= 0 && vec.size()!=this->dims[1])
FatalError("Attempting to assign row of wrong size to matrix.");
if (rowNum==INSERT_AT_END || rowNum==(int)this->dims[0]) {
// Default action - add to end
this->data.insert(this->data.end(),vec.begin(),vec.end());
}else{
// Insert at specified location
this->data.insert(this->data.begin()+rowNum*this->dims[1],vec.begin(),vec.end());
}
if (this->dims[1]==0) {
this->dims[1] = vec.size(); // This may not be needed (i.e. may never have dim1==0). need to verify how I set up dim0, dim1...
this->dims[2] = 1;
this->dims[3] = 1;
}
this->dims[0]++;
}
template<typename T>
void matrix<T>::insertRow(const vector<T> &vec, int rowNum)
{
if (this->dims[1]!= 0 && vec.size()!=this->dims[1])
FatalError("Attempting to assign row of wrong size to matrix.");
if (rowNum==INSERT_AT_END || rowNum==(int)this->dims[0]) {
// Default action - add to end
this->data.insert(this->data.end(),vec.begin(),vec.end());
}else{
// Insert at specified location
this->data.insert(this->data.begin()+rowNum*this->dims[1],vec.begin(),vec.end());
}
if (this->dims[1]==0) this->dims[1]=vec.size(); // This may not be needed (i.e. may never have dim1==0). need to verify how I set up dim0, dim1...
this->dims[0]++;
}
template<typename T>
void matrix<T>::insertRow(T *vec, uint rowNum, uint length)
{
if (this->dims[1]!=0 && length!=(int)this->dims[1])
FatalError("Attempting to assign row of wrong size to matrix.");
if (rowNum==INSERT_AT_END || rowNum==(int)this->dims[0]) {
// Default action - add to end
this->data.insert(this->data.end(),vec,vec+length);
}else{
// Insert at specified location
this->data.insert(this->data.begin()+rowNum*this->dims[1],vec,vec+length);
}
if (this->dims[0]==0)
this->dims = {{0,length,1,1}};
this->dims[0]++;
}
template<typename T>
void matrix<T>::insertRowUnsized(const vector<T> &vec)
{
// Add row to end, and resize matrix (add columns) if needed
if (vec.size() > this->dims[1]) addCols(vec.size()-this->dims[1]);
this->data.insert(this->data.end(),vec.begin(),vec.end());
// If row too short, finish filling with 0's
if (vec.size() < this->dims[1]) this->data.insert(this->data.end(),this->dims[1]-vec.size(),(T)0);
this->dims[0]++;
}
template<typename T>
void matrix<T>::insertRowUnsized(T* vec, int length)
{
// Add row to end, and resize matrix (add columns) if needed
if (length > this->dims[1]) addCols(length-this->dims[1]);
this->data.insert(this->data.end(),vec,vec+length);
// If row too short, finish filling with 0's
if (length < this->dims[1]) this->data.insert(this->data.end(),this->dims[1]-length,(T)0);
this->dims[0]++;
}
template<typename T>
void matrix<T>::addCol(void)
{
typename vector<T>::iterator it;
for (uint row=0; row<this->dims[0]; row++) {
it = this->data.begin() + (row+1)*(this->dims[1]+1) - 1;
this->data.insert(it,1,(T)0);
}
this->dims[1]++;
}
template<typename T>
void matrix<T>::addCols(int nCols)
{
typename vector<T>::iterator it;
for (uint row=0; row<this->dims[0]; row++) {
it = this->data.begin() + (row+1)*(this->dims[1]+nCols) - nCols;
this->data.insert(it,nCols,(T)0);
}
this->dims[1] += nCols;
}
//template<typename T>
//void matrix<T,1>::addCol(void)
//{
// FatalError("addCol not supported for 1D matrices.");
//}
//template<typename T>
//void matrix<T,1>::addCols(int)
//{
// FatalError("addCols not supported for 1D matrices.");
//}
template<typename T>
void matrix<T>::removeCols(int nCols)
{
if (nCols == 0) return;
typename vector<T>::iterator it;
for (uint row=this->dims[0]; row>0; row--) {
it = this->data.begin() + row*this->dims[1];
this->data.erase(it-nCols,it);
}
this->dims[1] -= nCols;
}
template<typename T>
vector<T> matrix<T>::getRow(uint row)
{
vector<T> out;
out.assign(&(this->data[row*this->dims[1]]),&(this->data[row*this->dims[1]])+this->dims[1]);
return out;
}
template<typename T>
matrix<T> matrix<T>::getRows(vector<int> ind)
{
matrix<T> out;
for (auto& i:ind) out.insertRow(&(this->data[i*this->dims[1]]),-1,this->dims[1]);
return out;
}
template<typename T>
vector<T> matrix<T>::getCol(int col)
{
vector<T> out;
for (uint i=0; i<this->dims[0]; i++) out.push_back(this->data[i*this->dims[1]+col]);
return out;
}
template<typename T, uint N>
void matrixBase<T,N>::print()
{
// for (uint i=0; i<dims[0]; i++) {
// for (uint j=0; j<dims[1]; j++) {
// cout << left << setw(10) << setprecision(8) << data[i*dims[1]+j] << " ";
// }
// cout << endl;
// }
}
template<typename T>
void matrix<T>::unique(matrix<T>& out, vector<int> &iRow)
{
out.setup(0,0);
// Setup vector for rows of final matrix that map to each row of initial matrix
iRow.resize(this->dims[0]);
iRow.assign(this->dims[0],-1);
/* --- For each row in the matrix, compare to all
previous rows to get first unique occurence --- */
typename vector<T>::iterator itI, itJ;
for (uint i=0; i<this->dims[0]; i++) {
itI = this->data.begin() + i*this->dims[1];
for (uint j=0; j<i; j++) {
itJ = this->data.begin() + j*this->dims[1];
if (equal(itI,itI+this->dims[1],itJ)) {
iRow[i] = iRow[j];
break;
}
}
// If no prior occurance found, put in 'out' matrix
if (iRow[i]==-1) {
out.insertRow(&(this->data[i*this->dims[1]]),-1,this->dims[1]);
iRow[i] = out.getDim0() - 1;
}
}
}
template<typename T, uint N>
T *matrixBase<T,N>::getData(void)
{
return data.data();
}
// Fix for compiler to know which template types will be needed later (and therefore must now be compiled):
template class matrixBase<int,1>;
template class matrixBase<int,2>;
template class matrixBase<int,3>;
template class matrixBase<int,4>;
template class matrixBase<double,1>;
template class matrixBase<double,2>;
template class matrixBase<double,3>;
template class matrixBase<double,4>;
template class matrixBase<double*,1>;
template class matrixBase<double*,2>;
template class matrixBase<double*,3>;
template class matrixBase<double*,4>;
template class matrixBase<point,1>;
template class matrixBase<point,2>;
template class matrixBase<point,3>;
template class matrixBase<point,4>;
template class matrixBase<set<int>,1>;
template class matrixBase<set<int>,2>;
template class matrixBase<set<int>,3>;
template class matrixBase<set<int>,4>;
template class matrix<int>;
template class matrix<double>;
| true |
c8b35ba0ec033681d204f5fe4e89c2b169578bc2 | C++ | Al3xDu/RezolvariInfo2021 | /subiecte/asd/20sub3ex1.cpp | UTF-8 | 313 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int b, n, c, k = 0, S = 0;
cout << "n=";
cin >> n;
cout << "b=";
cin >> b;
while (n)
{
c = n % 10;
S = S + pow(b, k) * c;
k++;
n /= 10;
}
cout << "S=" << S;
return 0;
} | true |
7b60ddde44108a3de5ee7b6a2feff30c2fd627df | C++ | yuta1024/aoj | /Volume 1/0113.cpp | UTF-8 | 678 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int p, q;
while (cin >> p >> q) {
int loop = -1;
vector<int> rem;
rem.push_back(p%q);
while (p != 0) {
p *= 10;
int tmp = p / q;
p %= q;
cout << tmp;
if (find(rem.begin(), rem.end(), p) != rem.end()) {
loop = find(rem.begin(), rem.end(), p) - rem.begin();
break;
}
rem.push_back(p);
}
cout << endl;
if (loop != -1) {
for (int i = 0; i < loop; ++i)
cout << " ";
for (int i = loop; i < rem.size(); ++i)
cout << "^";
cout << endl;
}
}
return 0;
}
| true |
3334940382c0e761e12a74eb2bcae4ef04352f9a | C++ | fatmaashraframadan/Problem_Solving | /CodeForces_Solutions_2/ShaassAndOskols.cpp | UTF-8 | 631 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100;
int main()
{
int n , nom_of_shots;
int arr[MAX];
cin >>n;
for(int i = 0 ; i < n ; ++i)
{
cin >> arr[i];
}
cin >> nom_of_shots;
for(int i = 0 ; i < nom_of_shots ; ++i)
{
int x , y;
cin >> x >> y;
--x;
if(x !=0)
{
arr[x-1]+=y-1;
}
if(x!=n -1)
{
arr[x+1]+=arr[x]-y;
}
arr[x]=0;
}
for(int i = 0 ; i < n ; ++i)
{
cout << arr[i]<<endl;
}
return 0;
}
| true |
912f030071c0a5c4888bd91f5f77bca21310725c | C++ | kamelCased/learningCplusplus | /hw10_timed/2.cpp | UTF-8 | 885 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int* findMissing(int arr[], int n, int& resArrSize);
int main() {
int arr[7] = {0,3,2,5,4,2,5};
int missCount;
int* miss = findMissing(arr, 7, missCount);
for (int i = 0; i < missCount; i++) {
cout << miss[i] << " " << endl;
}
return 0;
}
int* findMissing(int arr[], int n, int& resArrSize) {
int* nums = new int[n+1]{0};
for (int i = 0; i < n; i++) {
nums[arr[i]]++;
}
int missingCount = 0;
for (int i = 0; i <= n; i++) {
if (nums[i] == 0) {
missingCount++;
}
}
int* missingNums = new int[missingCount];
for (int i = 0, j = 0; i <= n; i++) {
if (nums[i] == 0) {
missingNums[j] = i;
j++;
}
}
delete[] nums;
nums = nullptr;
resArrSize = missingCount;
return missingNums;
} | true |
4b5d3625bd29948f86148f00d661c0f64fadf866 | C++ | WishSun/TeamDocShare | /TeamDocShare/server/src/GroupManage.cpp | UTF-8 | 2,202 | 2.828125 | 3 | [] | no_license | /*************************************************************************
> File Name: GroupManage.cpp
> Author: WishSun
> Mail: WishSun_Cn@163.com
> Created Time: 2018年08月23日 星期四 19时21分59秒
************************************************************************/
#include "./GroupManage.h"
#include <assert.h>
/*----------------------------------private----------------------------------*/
GroupManage* GroupManage::m_pGM = NULL;
/* 构造函数*/
GroupManage::GroupManage()
{
}
/*----------------------------------public----------------------------------*/
/* 获取群组管理类单例对象*/
GroupManage* GroupManage::CreateGroupManage()
{
if(m_pGM == NULL)
{
m_pGM = new GroupManage();
}
return m_pGM;
}
/* 增加一个新的组*/
bool GroupManage::AddNewGroup(GroupInfo *pG)
{
sprintf(sql,
"insert into groupInfo(groupName, groupMemberNum, groupInfo) values('%s', %d, '%s')",
pG->m_groupName, 0, pG->m_groupInfo);
return m_sqlConn.ExecuteInsertSql(NULL, sql);
}
/* 查找所有群组信息*/
bool GroupManage::GetGroupList(list<GroupInfo>& groupList)
{
/* 获取一条数据库连接*/
MYSQL *p_mysql = m_sqlConn.AllocConn();
sprintf(sql, "select * from groupInfo");
/* 执行sql语句*/
if( mysql_query(p_mysql, sql) != 0 )
{
printf("query sql error: %s\n", mysql_error(p_mysql));
m_sqlConn.FreeConn(p_mysql);
return false;
}
/* 获取执行结果集*/
MYSQL_RES *p_res = mysql_store_result(p_mysql);
if( p_res == NULL )
{
printf("store result error: %s\n", mysql_error(p_mysql));
m_sqlConn.FreeConn(p_mysql);
return false;
}
MYSQL_ROW p_row = NULL;
GroupInfo gInfo;
while( (p_row = mysql_fetch_row(p_res)) )
{
gInfo.m_groupID = atoi(p_row[0]);
sprintf(gInfo.m_groupName, "%s", p_row[1]);
gInfo.m_groupMemNum = atoi(p_row[2]);
sprintf(gInfo.m_groupInfo, "%s", p_row[3]);
groupList.push_back(gInfo);
}
/* 释放结果集*/
mysql_free_result(p_res);
/* 归还数据库连接*/
m_sqlConn.FreeConn(p_mysql);
return true;
}
| true |
4285db1959e5006ccf7a27ff24b51f8aa416c7fd | C++ | AlexTuckner/School_Projects | /Software Engineering Voting System/src/userInput.cpp | UTF-8 | 2,220 | 2.9375 | 3 | [] | no_license | /**
* @file userInput.cpp
*
*
*/
/*******************************************************************************
* Includes
******************************************************************************/
#include <string>
#include <iostream>
#include "userInput.h"
/*******************************************************************************
* Namespaces
******************************************************************************/
/**
* \namespace csci5801
* @{
*/
/*******************************************************************************
* Static Variables
******************************************************************************/
/*******************************************************************************
* Constructors/Destructor
******************************************************************************/
userInput::userInput() :
candidatesCount(0),
ballotsCount(0),
seatsCount(0),
votingAlgorithm(0) {
toshuffle = 0;
}
/*******************************************************************************
* Member Functions
******************************************************************************/
void userInput::getUserInput(){
std::string in;
int num;
std::cout << "Please enter the filename: ";
std::cin >> in;
setFilePath(in);
/*std::cout << "Please enter the number of candidates: ";
std::cin >> num;
setCandidatesCount(num);
std::cout << "Please enter the number of ballots: ";
std::cin >> num;
setBallotsCount(num);
std::cout << "Please enter the number of seats to be filled: ";
std::cin >> num;
setSeatsCount(num);
std::cout << "Which Algorithm would you like to use? (Enter 0 for Plurality or 1 for Droop): ";
std::cin >> num;
setVotingAlgorithm(num);
std::cout << "Input " << getFilePath() << " NumCan: " << getCandidatesCount() << " NumBal " << getBallotsCount() << " NumSeats: " << getSeatsCount() << " Algorithm: " << getVotingAlgorithm() << std::endl;
*/
}
void userInput::shuffleInput() {
int num;
/* std::cout << "Would you like to shuffle? (Enter 0 for 'no' or 1 for 'yes'): ";
std::cin >> num; */
setToShuffle(num);
}
/**
* @} End of Doxygen Namespace
*/
| true |
d98f61e7eada1241404f0fef6b6dece0dc44d93d | C++ | Learpcs/HashMap | /Source.cpp | UTF-8 | 2,656 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <random>
using namespace std;
//unsigned types doesn't work properly
template <class key, class value>
class HashMap
{
//nested class pairs (like pair xd)
template<class key, class value>
struct pairs
{
key Key;
value Value;
pairs& operator= (const value& value)
{
this->Value = value;
return *this;
}
};
pairs<key, value>* arr;
size_t Size = 0;
key KEY_MIN;
value VALUE_MIN;
size_t mod = 0;
size_t HashFunction(const key& k) //O(log n).
{
string s;
if constexpr (is_same_v<key, string>)
s = k;
else
s = to_string(k);
size_t n = s.size();
unsigned long long sum = 0;
for (size_t i = 0; i < n; i++)
sum += s[i];
return sum % mod;
}
public:
HashMap(const size_t& n)
{
Size = n, mod = n;
if constexpr(is_same_v<key, string>)
KEY_MIN = "";
else
KEY_MIN = -(1 << sizeof(key) * 8 - 1);
if constexpr(is_same_v<value, string>)
VALUE_MIN = "";
else
KEY_MIN = -(1 << sizeof(key) * 8 - 1);
arr = new pairs<key, value>[n];
for (size_t i = 0; i < n; i++)
{
arr[i].Key = KEY_MIN;
arr[i].Value = VALUE_MIN;
}
}
void insert(const key& Key, const value& Value) //O(n)
{
size_t hash_index = HashFunction(Key), cycle_cnt = 0;
do
{
if (arr[hash_index].Key == KEY_MIN)
{
arr[hash_index].Key = Key;
arr[hash_index].Value = Value;
break;
}
hash_index++;
if (hash_index == Size)
{
hash_index = 0;
cycle_cnt++;
}
} while (cycle_cnt < 2);
//Exception - size of map is too small
if(cycle_cnt == 2)
throw "SmallSize";
}
void remove(const key& Key) //O(1)
{
size_t hash_index = HashFunction(Key);
arr[hash_index].Key = KEY_MIN;
arr[hash_index].Value = VALUE_MIN;
}
void reconstruct(size_t size)
{
}
value& operator[](const key& i) //O(n)
{
size_t hash_index = HashFunction(i), cycle_cnt = 0;
do
{
if (arr[hash_index].Key == i)
{
return arr[hash_index].Value;
}
hash_index++;
if (hash_index == Size)
{
hash_index = 0;
cycle_cnt++;
}
} while (cycle_cnt < 2);
//Exception - element not found
throw "NotFound";
}
size_t count_collisions() //O(n * log n)
{
size_t cnt = 0;
for (size_t i = 0; i < Size; i++)
if (arr[i].Key != KEY_MIN && i != HashFunction(arr[i].Key))
cnt++;
return cnt;
}
~HashMap()
{
delete[] arr;
}
};
int main()
{
HashMap<string, int> prices(10);
prices.insert("test", 100);
cout << prices["test"];
}
| true |
7c38192fdaecd65f7c2d555a525cb031ffe8d28d | C++ | timepp/bdlog | /tplogview/colorselector.h | UTF-8 | 1,256 | 2.53125 | 3 | [] | no_license | #pragma once
class CColorSelector : public CWindowImpl<CColorSelector, CStatic>
{
public:
void SetColor(COLORREF cr)
{
m_color = cr;
InvalidateRect(NULL);
}
COLORREF GetColor() const
{
return m_color;
}
CColorSelector() : m_color(0)
{
}
public:
BEGIN_MSG_MAP(CColorSelector)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
END_MSG_MAP()
private:
COLORREF m_color;
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnPaint(UINT , WPARAM , LPARAM , BOOL& /*bHandled*/)
{
CPaintDC dc(m_hWnd);
CRect rc;
GetClientRect(&rc);
int val = dc.SaveDC();
dc.SelectPen((HPEN)::GetStockObject(BLACK_PEN));
dc.SelectBrush((HBRUSH)::GetStockObject(WHITE_BRUSH));
dc.Rectangle(&rc);
rc.DeflateRect(2, 2, 2, 2);
dc.FillSolidRect(&rc, m_color);
dc.RestoreDC(val);
return 1;
}
LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CColorDialog dlg(m_color);
if (dlg.DoModal(m_hWnd) == IDOK)
{
SetColor(dlg.GetColor());
}
return 0;
}
}; | true |
5eae77791faf904b6ea63ffe1255971738c62c3a | C++ | hyunny0463/ProblemSolving | /BOJ/15650_N과_M_(2).cpp | UHC | 850 | 3.140625 | 3 | [] | no_license | /*
* 15650. N M (2)
*
* ð : O(nCm)
*
* combination
* ⺻
* N ڿ M Ѵ.
*
*/
#define fastio() ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#include <iostream>
using namespace std;
int N, M; // ڿ ,
int t[8] = { 0 }; // 迭
void dfs(int d, int idx) { // , ε
if (d == M) { // ̰ ũⰡ
for (int i = 0; i < d; ++i)
cout << t[i] << ' ';
cout << '\n';
return;
}
for (int i = idx + 1; i <= N; ++i) { // ε ķ
t[d] = i;
dfs(d + 1, i);
}
}
int main(int argc, char** argv) {
fastio();
cin >> N >> M;
dfs(0, 0);
return 0;
} | true |
2473b87e50f8e59357d495561cf2958804e0b357 | C++ | peide/Gray | /test/test_viewable.cpp | UTF-8 | 4,042 | 2.546875 | 3 | [
"MIT"
] | permissive | /*
* Gray: A Ray Tracing-based Monte Carlo Simulator for PET
*
* Copyright (c) 2018, David Freese, Peter Olcott, Sam Buss, Craig Levin
*
* This software is distributed under the terms of the MIT License unless
* otherwise noted. See LICENSE for further details.
*
*/
#include "gtest/gtest.h"
#include <cmath>
#include <unordered_map>
#include "Gray/VrMath/LinearR3.h"
#include "Gray/Gray/Load.h"
TEST(AnnulusCylinderTest, NoTriangles) {
auto pieces = Load::MakeAnnulusCylinder(50, 60, 20);
ASSERT_EQ(pieces.size(), 8 * 100);
}
TEST(AnnulusCylinderTest, SharedPointsFace) {
auto pieces = Load::MakeAnnulusCylinder(50, 60, 20);
ASSERT_EQ(pieces.size() % 2, 0);
for (size_t ii = 0; ii < pieces.size(); ii += 2) {
const auto & first = pieces[ii];
const auto & second = pieces[ii + 1];
int no_shared_points = ((first.GetVertexA() == second.GetVertexA()) +
(first.GetVertexA() == second.GetVertexB()) +
(first.GetVertexA() == second.GetVertexC()) +
(first.GetVertexB() == second.GetVertexA()) +
(first.GetVertexB() == second.GetVertexB()) +
(first.GetVertexB() == second.GetVertexC()) +
(first.GetVertexC() == second.GetVertexA()) +
(first.GetVertexC() == second.GetVertexB()) +
(first.GetVertexC() == second.GetVertexC()));
EXPECT_EQ(no_shared_points, 2);
}
}
TEST(AnnulusCylinderTest, SharedPointsAll) {
const double inner_radius = 50;
const double outer_radius = 60;
auto pieces = Load::MakeAnnulusCylinder(inner_radius, outer_radius, 20);
std::unordered_map<VectorR3, int> point_counts;
for (const auto & triangle: pieces) {
point_counts[triangle.GetVertexA()]++;
point_counts[triangle.GetVertexB()]++;
point_counts[triangle.GetVertexC()]++;
}
for (const auto & point_count: point_counts) {
const VectorR3 & a = point_count.first;
const double radius = std::sqrt(a.x * a.x + a.y * a.y);
constexpr double rel_tol = 1e-6;
const double tol = inner_radius * rel_tol;
const bool inner = std::abs(radius - inner_radius) < tol;
const bool outer = std::abs(radius - outer_radius) < tol;
EXPECT_TRUE(inner ^ outer);
// This number is dependent on the rotation model in the implementation
// but could be 4 or 8 for other implementations.
EXPECT_EQ(point_count.second, 6);
}
}
TEST(AnnulusCylinderTest, Radius) {
const double inner_radius = 50;
const double outer_radius = 60;
auto pieces = Load::MakeAnnulusCylinder(inner_radius, outer_radius, 20);
ASSERT_EQ(pieces.size() % 2, 0);
for (const auto & triangle: pieces) {
const VectorR3 & a = triangle.GetVertexA();
const VectorR3 & b = triangle.GetVertexB();
const VectorR3 & c = triangle.GetVertexC();
const double radius_a = std::sqrt(a.x * a.x + a.y * a.y);
const double radius_b = std::sqrt(b.x * b.x + b.y * b.y);
const double radius_c = std::sqrt(c.x * c.x + c.y * c.y);
constexpr double rel_tol = 1e-6;
const double tol = inner_radius * rel_tol;
ASSERT_GT(radius_a, inner_radius - tol);
ASSERT_LT(radius_a, outer_radius + tol);
const bool a_inner = std::abs(radius_a - inner_radius) < tol;
const bool b_inner = std::abs(radius_b - inner_radius) < tol;
const bool c_inner = std::abs(radius_c - inner_radius) < tol;
const bool a_outer = std::abs(radius_a - outer_radius) < tol;
const bool b_outer = std::abs(radius_b - outer_radius) < tol;
const bool c_outer = std::abs(radius_c - outer_radius) < tol;
const int no_inner = a_inner + b_inner + c_inner;
const int no_outer = a_outer + b_outer + c_outer;
const int no_on = no_inner + no_outer;
ASSERT_EQ(no_on, 3);
}
}
| true |
b9ddfea7bbd1262396b90351b9682495f2a32fe3 | C++ | Ryednap/Contest | /Ujjwal/Halim/Ch2/Linear/10264.cpp | UTF-8 | 1,070 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "uj.h"
#endif
// O(2^n * n) complexity
// Look at the statement how bogus it is . It's actually want's to say that for any two adjacent corner sum of all the weights of the reachable corner
// from those. Hence once first compute the potency of each corner and then for adjacent we can do that for p[x] + p[y] - w[x] - w[y] because in p[x] +
// p[y] we have counted the weights of corner x and y twice.
int main( ) {
int n;
while( scanf("%d", &n) != EOF ) {
vector<int> store(1 << n);
for(int i = 0; i < (1 << n); ++i) {
scanf("%d", &store[i]);
}
vector<int> answer(1 << n);
for(int i = 0; i < (1 << n ); ++i) {
int maybe = store[i];
for(int j = 0; j < n; ++j) {
int x = (i ^ (1 << j));
maybe += store[x];
}
answer[i] = maybe;
}
int ans = 0;
for(int i = 0; i < (1 << n); ++i) {
for(int j = 0; j < n; ++j) {
int x = (i ^ (1 << j));
ans = max(ans, answer[i] + answer[x] - store[i] - store[x]);
}
}
printf("%d\n", ans);
}
return 0;
}
| true |
870acc483245fc9e4371c9ee9ae67f6fa88891c9 | C++ | Yoruichigo/SurvivalDungeon | /SurvivalDungeon/FileSaveClass.cpp | SHIFT_JIS | 962 | 2.921875 | 3 | [] | no_license |
#include <stdio.h>
#include "FileSaveClass.h"
using namespace std;
/*
dat`fileName.datf[^݂邩mF
*/
bool FileSaveClass::FileCheckDat(string fileName)
{
string datName = fileName + ".dat";
FILE *fp;
if(fopen_s(&fp,datName.c_str(), "rb") != 0)
{
return false; // s
}
// f[^݂
fclose(fp);
return true;
}
/*
dat`ŕۑ
*/
bool FileSaveClass::WriteDat(string fileName, const void* data, size_t dataSize)
{
string datName = fileName + ".dat";
FILE *fp;
if(fopen_s(&fp, datName.c_str(), "wb") != 0)
{
return false; // s
}
fwrite(data, dataSize, 1, fp);
fclose(fp);
return true;
}
/*
dat`œǂݍ
*/
bool FileSaveClass::ReadDat(string fileName, void* data, size_t dataSize)
{
string datName = fileName + ".dat";
FILE *fp;
if(fopen_s(&fp, datName.c_str(), "rb") != 0)
{
return false; // s
}
fread(data, dataSize, 1, fp);
fclose(fp);
return true;
} | true |
11d42591a8f9ec41051ce92a39c0df11a37b367d | C++ | sahil-rajput/Algorithm-Implementation | /Library/graph/euler_tour_tree.cc | UTF-8 | 3,987 | 3.015625 | 3 | [] | no_license | //
// Euler Tour Tree
//
// Description:
// Maintain dynamic unrooted tree with supporting
// - make_node(x) : return singleton with value x
// - link(u,v) : add link between u and v
// - cut(uv) : remove edge uv
// - sum_in_component(u): return sum of all values in the component
//
// Algorithm:
// Maintain euler tours by splay trees.
// This data structure is originally proposed by Miltersen et al,
// and independently by Fredman and Henzinger.
//
// Complexity:
// O(log n)
//
// References:
// M. L. Fredman and M. R. Henzinger (1998):
// Lower bounds for fully dynamic connectivity problems in graphs.
// Algorithmica, vol. 22, no. 3, pp. 351–362.
//
// P. B. Miltersen, S. Subramanian, J. S. Vitter, and R. Tamassia (1994):
// Complexity models for incremental computation.
// Theoretical Computer Science, vol. 130. no. 1, pp. 203–236.
\bibitem{old2}
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <cmath>
#include <cstring>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define fst first
#define snd second
#define all(c) ((c).begin()), ((c).end())
struct euler_tour_tree {
struct node {
int x, s; // value, sum
node *ch[2], *p, *r;
};
int sum(node *t) { return t ? t->s : 0; }
node *update(node *t) {
if (t) t->s = t->x + sum(t->ch[0]) + sum(t->ch[1]);
return t;
}
int dir(node *t) { return t != t->p->ch[0]; }
void connect(node *p, node *t, int d) {
p->ch[d] = t; if (t) t->p = p;
update(p);
}
node *disconnect(node *t, int d) {
node *c = t->ch[d]; t->ch[d] = 0; if (c) c->p = 0;
update(t);
return c;
}
void rot(node *t) {
node *p = t->p;
int d = dir(t);
if (p->p) connect(p->p, t, dir(p));
else t->p = p->p;
connect(p, t->ch[!d], d);
connect(t, p, !d);
}
void splay(node *t) {
for (; t->p; rot(t))
if (t->p->p) rot(dir(t) == dir(t->p) ? t->p : t);
}
void join(node *s, node *t) {
if (!s || !t) return;
for (; s->ch[1]; s = s->ch[1]); splay(s);
for (; t->ch[0]; t = t->ch[0]); connect(t, s, 0);
}
node *make_node(int x, node *l = 0, node *r = 0) {
node *t = new node({x});
connect(t, l, 0); connect(t, r, 1);
return t;
}
node *link(node *u, node *v, int x = 0) {
splay(u); splay(v);
node *uv = make_node(x, u, disconnect(v,1));
node *vu = make_node(0, v, disconnect(u,1));
uv->r = vu; vu->r = uv;
join(uv, vu);
return uv;
}
void cut(node *uv) {
splay(uv); disconnect(uv,1); splay(uv->r);
join(disconnect(uv,0), disconnect(uv->r,1));
delete uv, uv->r;
}
int sum_in_component(node *u) {
splay(u);
return u->s;
}
};
int main() {
euler_tour_tree ETT;
auto a = ETT.make_node(3);
auto b = ETT.make_node(1);
auto c = ETT.make_node(4);
auto d = ETT.make_node(1);
auto e = ETT.make_node(5);
auto f = ETT.make_node(9);
auto g = ETT.make_node(2);
// 3
// 1 4
// 1 5 9 2
auto ab = ETT.link(a, b);
ETT.link(a, c);
ETT.link(b, d);
ETT.link(b, e);
auto cf = ETT.link(c, f);
ETT.link(c, g);
cout << ETT.sum_in_component(a) << endl;
cout << ETT.sum_in_component(b) << endl;
cout << ETT.sum_in_component(c) << endl;
cout << ETT.sum_in_component(d) << endl;
cout << endl;
ETT.cut(ab);
cout << ETT.sum_in_component(a) << endl;
cout << ETT.sum_in_component(b) << endl;
cout << ETT.sum_in_component(c) << endl;
cout << ETT.sum_in_component(d) << endl;
cout << endl;
ETT.cut(cf);
cout << ETT.sum_in_component(a) << endl;
cout << ETT.sum_in_component(b) << endl;
cout << ETT.sum_in_component(c) << endl;
cout << ETT.sum_in_component(d) << endl;
cout << endl;
ETT.link(a,b);
cout << ETT.sum_in_component(a) << endl;
cout << ETT.sum_in_component(b) << endl;
cout << ETT.sum_in_component(c) << endl;
cout << ETT.sum_in_component(d) << endl;
cout << endl;
}
| true |
aad208470d85d4f807f1e6eff4c6e6b03e454f66 | C++ | allandemiranda/linguagem_de_programa-ao_IMD_2018.2 | /Aula 12/questões/questao 2/main.cpp | UTF-8 | 1,190 | 4.0625 | 4 | [] | no_license | /**
* @brief Questão 2
*
* @file main.cpp
* @author Allan de Miranda Silva
* @date 2018-09-24
*/
#include <iostream>
#include <iterator>
#include <algorithm>
#include <cstring>
using byte = unsigned char;
/**
* @brief Function called reverse that reverses the order of the elements located in a range defined over a generic array
*
* @param first the range of elementos to examine
* @param last the range of elementos to examine
* @param size size of each element in the array in bytes
*/
void reverse ( void * first , void * last , size_t size ){
byte *primeiro = static_cast<byte*>(first);
byte *segundo = static_cast<byte*>(last);
byte temporario[size];
segundo-=size;
while(primeiro<segundo){
std::memcpy(temporario,primeiro,size);
std::memcpy(primeiro,segundo,size);
std::memcpy(segundo,temporario,size);
primeiro+=size;
segundo-=size;
}
}
int main(void){
int A[] = {1,2,3,4,5,6,7,8,9};
for(int i : A){
std::cout << i << " ";
}
std::cout << std::endl;
reverse(std::begin(A), std::end(A), 4);
for(int i : A){
std::cout << i << " ";
}
std::cout << std::endl;
} | true |
a404ad1e4372625e8015c36e3d9a5e2d4699155a | C++ | l-iberty/MyCode | /CandC++/对象引用.cpp | GB18030 | 643 | 3.640625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Demo {
private:
int data;
public:
Demo(int inData) {
data = inData;
}
int getData() {
return data;
}
void setData(int inData) {
data = inData;
}
void setData(Demo &p) {
data = p.data;
}
};
int main() {
Demo d1 = Demo(3);
Demo &r1_Demo = d1; //
/* ñΪֵ,ʱʼ */
cout << "d1.data = " << d1.getData() << endl;
cout << "d1.data = " << r1_Demo.getData() << endl;
Demo d2 = Demo(9);
Demo &r2_Demo = d2;
r1_Demo.setData(r2_Demo);
cout << "d1.data = " << d1.getData() << endl;
return 0;
} | true |
b56ce1b9e4d1438386825366f99c90a3b8131cd2 | C++ | xsafran1/pepmc2 | /lrparser/conflict.hpp | UTF-8 | 1,252 | 2.859375 | 3 | [] | no_license | #ifndef LRPARSER_CONFLICT_HPP
#define LRPARSER_CONFLICT_HPP
#include <exception>
#include "parsing_action.hpp"
template <typename Nonterminal, typename ReduceAction>
class conflict_error
: public std::exception
{
public:
typedef parsing_action<Nonterminal, ReduceAction> action_type;
conflict_error(action_type new_action, action_type old_action)
: m_new_action(new_action), m_old_action(old_action)
{
}
~conflict_error() throw()
{
}
virtual const char* what() const throw()
{
return "conflict";
}
action_type new_action() const { return m_new_action; }
action_type old_action() const { return m_old_action; }
private:
action_type m_new_action;
action_type m_old_action;
};
template <typename Itemset, typename Nonterminal, typename ReduceAction>
class statetrace_conflict_error
: public conflict_error<Nonterminal, ReduceAction>
{
public:
typedef parsing_action<Nonterminal, ReduceAction> action_type;
statetrace_conflict_error(action_type new_action, action_type old_action)
: conflict_error<Nonterminal, ReduceAction>(new_action, old_action)
{
}
~statetrace_conflict_error() throw()
{
}
void add_state(Itemset const & itemset)
{
m_states.push_back(itemset);
}
std::vector<Itemset> m_states;
};
#endif
| true |
6b26dd9dce227fc3c65f14dd295beec99e674abe | C++ | kennykthoang/UTD-CS-Assignments | /CS1136 - Computer Science Lab/Lab6_Optional.cpp | UTF-8 | 1,626 | 4.15625 | 4 | [] | no_license | // Lab6_Optional
// Sum of all integers within a range
//
// Program by: Kenny Hoang
#include <iostream>
using namespace std;
int main()
{
int larger; // variable of type int that holds the "larger"(first) integer inputted by the user
int smaller; // variable of type int that holds the "smaller"(second) integer inputted by the user
int count; // variable of type int that holds the smaller or larger integer depending on the numbers inputted
// along with being the number being changed to calculate the sum of numbers within a range
int sum = 0; // variable of type int that holds the sum of numbers within a given range
// Prompting the user to enter the larger number of the range [a,b]
cout << "Please enter the larger number within the range: ";
cin >> larger;
// Prompting the user to enter the smaller number of the range [a,b]
cout << "Please enter the smaller number within the range: ";
cin >> smaller;
if (smaller != larger && smaller < larger)
{
count = smaller;
while (count <= larger)
{
sum += count;
count++;
}
cout << "The sum of " << smaller << " and " << larger << " is " << sum << endl;
}
else if (smaller != larger && smaller > larger)
{
count = larger;
while (count <= smaller)
{
sum += count;
count++;
}
cout << "The sum of " << smaller << " and " << larger << " is " << sum << endl;
}
else
{
sum = smaller;
cout << "The sum of " << smaller << " and " << larger << " is " << sum << endl;
}
system("pause");
} | true |
db36f24c0e918a7b21f128be8a63e947cfe4f57c | C++ | akaplyar/Abstract_VM | /includes/Token.hpp | UTF-8 | 1,559 | 2.625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Token.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akaplyar <akaplyar@student.unit.ua> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/01 16:20:00 by akaplyar #+# #+# */
/* Updated: 2017/12/01 16:20:00 by akaplyar ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef TOKEN_HPP
# define TOKEN_HPP
#include "IOperand.hpp"
class Token {
public:
enum eTokenType {
push, pop, dump, assert, add, sub, mul, div, mod, print, exit
};
Token() = delete;
Token(Token const &) = delete;
Token &operator=(Token const &) = delete;
Token(const int line, const eTokenType type,
const std::string &value, const IOperand::eOperandType &operand);
~Token() = default;
eTokenType getType() const;
const std::string &getValue() const;
int getLine() const;
IOperand::eOperandType getOperandType() const;
private:
const int line;
const eTokenType type;
const std::string value;
const IOperand::eOperandType operandType;
};
#endif
| true |
4471bbb302d8c47a310b3c72bdaad5de4b0e8ab6 | C++ | hristoivanov/master-ucm-GC | /p2/allInOne/freeglut project 3D/Roble.cpp | UTF-8 | 1,319 | 2.6875 | 3 | [] | no_license | #include "Roble.h"
Roble::Roble() {
//trash
int divs = 40;
float ratioTronco = 0.7f;
GLfloat alturaTronco = 6.0f;
GLfloat anchuraCopa = 2.5f;
numHijos = 3;
hijos = new Objeto3D*[numHijos];
hijos[0] = new Cilindro(ratioTronco, divs, divs);
hijos[0]->mT->setEscala(1.0, 1.0f, alturaTronco + 1.0f);
hijos[0]->mT->setRota(-90.0, 0.0, 0.0);
hijos[0]->setColor(.4f, .0f, .0f);
hijos[1] = new Disco(0, divs, divs);
hijos[1]->mT->setRota(90.0, 0.0, 0.0);
hijos[1]->setColor(.4f, .0f, .0f);
hijos[2] = new Esfera(divs, divs);
hijos[2]->mT->setTraslada(0.0, alturaTronco, 0.0);
hijos[2]->mT->setEscala(anchuraCopa, anchuraCopa, anchuraCopa);
hijos[2]->setColor(.4f, 1.0f, .4f);
colorEsp = new float[3]();
colorEsp[0] = .5f; colorEsp[1] = .5f; colorEsp[2] = 0.5f;
}
void Roble::dibuja() {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glMultMatrixf(this->mT->m);
for (int i = 0; i < numHijos; i++){
if (i != 2)
hijos[i]->dibuja();
else{
glMaterialfv(GL_FRONT, GL_SPECULAR, colorEsp);
hijos[i]->dibuja();
GLfloat amb[] = { 0.0f, 0.0f, 0.0f};
glMaterialfv(GL_FRONT, GL_SPECULAR, amb);
}
}
glPopMatrix();
}
void Roble::cambiaEsp(float aux) {
GLfloat a = colorEsp[0] + aux;
if (a > 1.0f)
a = 1.0f;
if (a < .0f)
a = .0f;
colorEsp[0] = a;
colorEsp[1] = a;
colorEsp[2] = a;
} | true |
dfe517c35f31b8c63175e0b2c33d07892f59555d | C++ | conglanjun/algorithm1 | /datastructure/Link_clj.cpp | UTF-8 | 3,288 | 3.046875 | 3 | [] | no_license | //
// Created by conglj-a on 2019/7/4.
//
#include <malloc.h>
#include <cstdlib>
#include <cstdio>
#include "Link_clj.h"
LinkList Link_clj::CreateList1(LinkList &L){
LNode* s;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d", &x);
while (x != 9999){
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
LinkList Link_clj::CreateList2(LinkList &L){
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode* s, *r = L;
scanf("%d", &x);
while (x != 9999){
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
void Link_clj::PrintLinkList(LinkList L){
LNode* node = L->next;
while (node != NULL){
printf("%d\t", node->data);
node = node->next;
}
printf("\n");
}
void Link_clj::PrintDLinkList(DLinkList L){
DNode* node = L->next;
while (node != NULL){
printf("%d\t", node->data);
node = node->next;
}
printf("\n");
}
LNode* Link_clj::GetElem(LinkList L, int i){
int j = 1;
LNode* p = L->next;
if(i == 0) return L;
if(i < 1) return NULL;
while (p && j < i){
p = p->next;
j++;
}
return p;
}
LNode* Link_clj::LocateElem(LinkList L, Elemtype e){
LNode* p = L->next;
while (p != NULL && p->data != e){
p = p->next;
}
return p;
}
bool Link_clj::InsertLink(LinkList &L, int i){
if(i < 1) return false;
int x;
LNode *pNode = GetElem(L, i - 1);
if(pNode == NULL) return false;
LNode* s = (LNode*)malloc(sizeof(LNode));
scanf("%d", &x);
s->data = x;
s->next = pNode->next;
pNode->next = s;
return true;
}
bool Link_clj::DeleteLink(LinkList &L, int i){
if(i < 1){
return false;
}
LNode *p = GetElem(L, i - 1);
LNode *q = p->next;// delete element
p->next = q->next;
free(q);
return true;
}
DLinkList Link_clj::CreateListD2(DLinkList &L){
int x;
L = (DLinkList)malloc(sizeof(DNode));
L->next = NULL;
DNode *s, *r = L;
scanf("%d", &x);
while (x != 9999){
s = (DNode*)malloc(sizeof(DNode));
s->data = x;
s->next = r->next;
r->next = s;
s->piror = r;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
DNode* Link_clj::DGetElem(DLinkList &DL, int i){
int j = 1;
DNode *p = DL->next;
if(i == 0) return DL;
if(i < 1) return NULL;
while (p && j < i){
p = p->next;
j++;
}
return p;
}
bool Link_clj::DInsertLink(DLinkList &DL, int i){
if(i < 1){
return false;
}
DNode *p = DGetElem(DL, i - 1);
DNode *s = (DNode*)malloc(sizeof(LNode));
int x;
scanf("%d", &x);
s->data = x;
s->next = p->next;
p->next->piror = s;
p->next = s;
s->piror = p;
return true;
}
bool Link_clj::DDeleteLink(DLinkList &DL, int i){
if(i < 1){
return false;
}
DNode *p = DGetElem(DL, i - 1);
DNode *q = p->next;
p->next = p->next->next;
p->next->piror = p;
free(q);
return true;
}
| true |
1ff4ae9c19cddf551bc6f4ba2d0689fbdbfbd409 | C++ | JaroslawSlabik/game-bfc | /game_app/gui_items/map_of_pawn.cpp | UTF-8 | 8,643 | 2.53125 | 3 | [] | no_license | #include "map_of_pawn.h"
MapOfPawn::MapOfPawn(QObject *parent)
{
m_selected_pawn = std::make_pair(-1, -1);
m_selected_cell = std::make_pair(-1, -1);
m_selected_enemy_pawn = std::make_pair(-1, -1);
m_do_something = false;
}
MapOfPawn::~MapOfPawn()
{
m_map_of_pawn.clear();
}
void MapOfPawn::setPositionPawn(int x, int y, int new_x, int new_y)
{
Pawn* selected_pawn = m_map_of_pawn.value(std::make_pair(x, y), nullptr);
if(nullptr == selected_pawn)
{
//pionek nie istnieje
return;
}
Pawn* possible_pawn = m_map_of_pawn.value(std::make_pair(new_x, new_y), nullptr);
if(nullptr != possible_pawn )
{
if(false == possible_pawn->getInfo().m_enemy)
{
// na nowym miejscu jest pionek który nie jest przeciwnikiem
return;
}
}
selected_pawn->setPosition(m_position_map.x() + (new_x * m_size_cell.x()), m_position_map.y() + (new_y * m_size_cell.y()));
m_map_of_pawn.remove(std::make_pair(x, y));
m_map_of_pawn.insert(std::make_pair(new_x, new_y), selected_pawn);
}
void MapOfPawn::movePawnBaseVector(int x, int y, std::pair<int, int> vector)
{
Pawn* selected_pawn = m_map_of_pawn.value(std::make_pair(x, y), nullptr);
if(nullptr == selected_pawn)
{
//pionek nie istnieje
return;
}
int new_x = x + vector.first;
int new_y = y + vector.second;
if(nullptr != m_map_of_pawn.value(std::make_pair(new_x, new_y), nullptr))
{
// na nowym miejscu jest pionek
return;
}
selected_pawn->setPosition(m_position_map.x() + (new_x * m_size_cell.x()), m_position_map.y() + (new_y * m_size_cell.y()));
m_map_of_pawn.remove(std::make_pair(x, y));
m_map_of_pawn.insert(std::make_pair(new_x, new_y), selected_pawn);
}
bool MapOfPawn::draw(Shader* shader)
{
for(Pawn* p : m_map_of_pawn.values())
{
if(nullptr != p)
{
p->draw(shader);
}
}
return true;
}
void MapOfPawn::loadPawnsFromServer()
{
}
void MapOfPawn::kayboardEventRec(QEvent::Type type, Qt::Key key, QString text)
{
}
void MapOfPawn::mouseEventRec(QEvent::Type type, QVector2D pos, Qt::MouseButton button)
{
}
void MapOfPawn::receiveFromServer(const QString& response)
{
//TODO: response actual pawn
//init or update m_map_of_pawn
CreatureInfo info;
info.m_id = 1;
info.m_name = "Octo";
info.m_health = 2;
info.m_actual_health = 2;
info.m_shield = 2;
info.m_actual_shield = 2;
info.m_attack = 2;
info.m_point_of_move = 15;
info.m_actual_move = 15;
info.m_enemy = true;
info.m_texture = QByteArray(QByteArray::fromBase64("iV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K4fT5YqBYsXLvKbsO+P739/7tlol/9SdO9qd/Y8i+cAofT14Np34tAqdwoQOuWP/w1282lwUXVw+XRwP3A6zce8rk1t7+f873JF+0zYJiKMMX7sVjviKym7lWAhoP3jjMSE7ydBPdFYAQ17wY/Oa1Vx86+o18d/P27DfWcsHm18LIqz3o5baWC7a3tqa/P3TdWHgDl9YPtAshrneZje1U8VPw5eb93lWsa718nFWsc8ALBcgbh5syuNQBXHug/Uf8rR5bPzF/4vb2hT8LPPwcn5hezbYuv/mhYiRbaUYzfOHGgX8HPruKdROv5r+ZayvAxcB5IpBzdG9I0BftEpFcsvzB975Ccq/HXlNCP8seffuGk1ziHNb9I4L/Ah5exbrJ/63PKtalwMWbufZLwHKsP91bf6LwnAZ87xfF8qa9ab+E/Q8AqAOb7PPZEAAAAABJRU5ErkJggg=="));
CreatureInfo info_2;
info_2.m_id = 2;
info_2.m_name = "Nose";
info_2.m_health = 4;
info_2.m_actual_health = 4;
info_2.m_shield = 4;
info_2.m_actual_shield = 4;
info_2.m_attack = 4;
info_2.m_point_of_move = 5;
info_2.m_actual_move = 5;
info_2.m_enemy = true;
info_2.m_texture = QByteArray(QByteArray::fromBase64("iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAAJXRFWHRjcmVhdGUtZGF0ZQAyMDA4LTA4LTI0VDAwOjI2OjExLTA1OjAw7PaYmAAAACV0RVh0bW9kaWZ5LWRhdGUAMjAwOC0wOC0yMFQxNDoyODowNC0wNTowMLqbNkEAAA5cSURBVGiB3ZpbkGVXWcd/31p777PPOX3vnslcejpzSWYYYEKCEAiGi0VUKEspoZTCC2VpWWWVClWWL+qLaJXAm2AJglIKT0CJghcwCGUSSEhMMMGEmWFmMjPdPdM9fTnTl9Pn7Mu6+bBP3yY9YzqEB11Vq/fZ++y19/+/vsv6r+80/B9v8nI/8DNfCOsf68Ae4ACwH7gNGAyBGPDACjAFnBdhMgQyEfiN9+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8c3apdfnvzp3+l/8EOlQ5udNenVl54lsfu3L8lT/75MGJN76r3hh5paio7r1ZWF2e/tT3nvzbKyKfXF/jXrIFMmBqcf7szOL82S1bc3yP4OYiATSae0REdLU2VNeKfPWhC2e/9nmgu+VeCyw7W2Rn/vvvZy6d/8Y39+6/a7zeGKl3O4uzs9NPnre2WLsR/G4JrJOwvX6rJkBI06FUUNH6JWu6p2evPPXR6UvfnmZjWdv27Bwo8mx5eeriIxd6118wMT8MgRfbAlCYsnPeuvKKEpWW5dqT164+/edPP/HXj1FlkluNfTGTBPwI/ldiS9ONvr1DR+58+wkRpa9dffri4tzpBSrwO5cYXkL7URLY6fkvG/D/N+1/AE5V0XkMsvHJAAAAAElFTkSuQmCC"));
CreatureInfo info_3;
info_3.m_id = 3;
info_3.m_name = "Smile";
info_3.m_health = 6;
info_3.m_actual_health = 6;
info_3.m_shield = 6;
info_3.m_actual_shield = 6;
info_3.m_attack = 6;
info_3.m_point_of_move = 2;
info_3.m_actual_move = 2;
info_3.m_enemy = true;
info_3.m_texture = QByteArray(QByteArray::fromBase64("iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAM0ElEQVRoge2Zaaxd1XXHf2uf6c5v8PPzEDvGNoNdUhMwLSnQDBSV0lIhglCLkqhN0+YLCerwBTVfqkoRQqloOkoliISkShTSJiEpTVSqRqGtoLiliYMJGMexjXl+83333fmcvffqh3Pv4/nh56kmUqUu3atz7z3n7PP/r7X2mi78Hxd5KxZN7/9wVUSuEWE/InsF2YnoVlEmgCKCF9UlVI8h8j2MeRqR78iffKZ3oc+6pAQ69/3GzQa5V0RuQ9gpggHJX2GIFItQKiHFIhLH4By0W1CvI1n6gor5tHn40S/8xAk0P/qhnxMjDwj8CiKBAIiygl8U4iQHniRIkuREymUoFBBn4dQpdGYGnP0y8Pvhpx+b+okQWPrIB37XiDwIFEQAyZfMD5IfBURBAUEH5wUxAlGEqdVgbAyxF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IV51FJFnWep0fV/fezI1766MP30nE3TXVHx7caq9NIMn0dh2Z4UJ24b2/i+ySiZeLa59HceXWbNmOV8CKy2xOh11ZF7bhudvNaqkrdpglqP9BxZJ6Xdy5jp95ZeaDcOp6qyIYrLGCGK8kc559Gu5W+O/eiLj0yfeODH/c6/PtusP/dKt13fV65dvSlOCm4Q5awqDthTrOx7tlX/7kzWP7oW1IX0xAr0nlqc+Xwkwv7y6L6SMRUF13RueTbrT5/sd48f7XdePtJrH2pY29kaF255/Ip3frKcStRudjGBIXDKDxvLxx+ffu1B4Phg7YVnm/Wpjx198Qf3bbnsY7eOTtwQieTltRim0t7yYpYungnUhU5eDflGLgNjJi8vvEIXWAba5CZ2QKkcBL/4lav2f2kkjBKneRIrGMMfnTj8wFP1mbX/fQWDdXe+uzb+q+8dmXjP5jjZNJ+l01+Zn/rMDzrNJ4F0LaALnUr4AcgOMLeqyjrTyMFujpKRxATR8GTFGP6pMf/dby/NPnaG6x25El56ZnnxyDPLi48ZoeSVBrDIOuPFi/2X8hwzkhxQOQijUmBMgCExhuea9e8/dPLIx53q3Fnuywbv9rlmYXBhm/iCpafe7i6U35mp7399cfprD08d/YO6zQ69lc+8lCJAJDAZi9lOnkP+X9bK/wDrs0uV2ZqR8AAAAABJRU5ErkJggg=="));
CreatureInfo info_4;
info_4.m_id = 4;
info_4.m_name = "Octo";
info_4.m_health = 2;
info_4.m_actual_health = 2;
info_4.m_shield = 2;
info_4.m_actual_shield = 2;
info_4.m_attack = 2;
info_4.m_point_of_move = 15;
info_4.m_actual_move = 15;
info_4.m_enemy = false;
info_4.m_move_type = MovingCreatureType_e::fly;
info_4.m_texture = QByteArray(QByteArray::fromBase64("iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAQ4UlEQVRoge2ZebReVXnGf3s453zTHZPcTBAhxAAJCSbVaoqkDCIJUqAgplSXWliL2pZWxFZti7YutEutpdQKFaylXWIVsK2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m18LIqz3o5baWC7a3tqa/P3TdWHgDl9YPtAshrneZje1U8VPw5eb93lWsa718nFWsc8ALBcgbh5syuNQBXHug/Uf8rR5bPzF/4vb2hT8LPPwcn5hezbYuv/mhYiRbaUYzfOHGgX8HPruKdROv5r+ZayvAxcB5IpBzdG9I0BftEpFcsvzB975Ccq/HXlNCP8seffuGk1ziHNb9I4L/Ah5exbrJ/63PKtalwMWbufZLwHKsP91bf6LwnAZ87xfF8qa9ab+E/Q8AqAOb7PPZEAAAAABJRU5ErkJggg=="));
CreatureInfo info_5;
info_5.m_id = 5;
info_5.m_name = "Nose";
info_5.m_health = 4;
info_5.m_actual_health = 4;
info_5.m_shield = 4;
info_5.m_actual_shield = 4;
info_5.m_attack = 4;
info_5.m_point_of_move = 5;
info_5.m_actual_move = 5;
info_5.m_enemy = false;
info_5.m_texture = QByteArray(QByteArray::fromBase64("iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAAJXRFWHRjcmVhdGUtZGF0ZQAyMDA4LTA4LTI0VDAwOjI2OjExLTA1OjAw7PaYmAAAACV0RVh0bW9kaWZ5LWRhdGUAMjAwOC0wOC0yMFQxNDoyODowNC0wNTowMLqbNkEAAA5cSURBVGiB3ZpbkGVXWcd/31p777PPOX3vnslcejpzSWYYYEKCEAiGi0VUKEspoZTCC2VpWWWVClWWL+qLaJXAm2AJglIKT0CJghcwCGUSSEhMMMGEmWFmMjPdPdM9fTnTl9Pn7Mu6+bBP3yY9YzqEB11Vq/fZ++y19/+/vsv6r+80/B9v8nI/8DNfCOsf68Ae4ACwH7gNGAyBGPDACjAFnBdhMgQyEfiN9+4O0stCYAvoEeD1wFt7x6PAGNAQIVIKdK+LgPMYa1lwnqdD4B9E+OcAC8KLJ/JDEdgCfC/wXuCXgVNAY9tLBOII0gRqvZ7EEGmwDtpdWGljS8MTwJ8BDwLuxZB4yQR64AV4G/AnwH2AvumLpPcyqT5rBVGPVL1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a7zeGKl3O4uzs9NPnre2WLsR/G4JrJOwvX6rJkBI06FUUNH6JWu6p2evPPXR6UvfnmZjWdv27Bwo8mx5eeriIxd6118wMT8MgRfbAlCYsnPeuvKKEpWW5dqT164+/edPP/HXj1FlkluNfTGTBPwI/ldiS9ONvr1DR+58+wkRpa9dffri4tzpBSrwO5cYXkL7URLY6fkvG/D/N+1/AE5V0XkMsvHJAAAAAElFTkSuQmCC"));
CreatureInfo info_6;
info_6.m_id = 6;
info_6.m_name = "Smile";
info_6.m_health = 6;
info_6.m_actual_health = 6;
info_6.m_shield = 6;
info_6.m_actual_shield = 6;
info_6.m_attack = 6;
info_6.m_point_of_move = 2;
info_6.m_actual_move = 2;
info_6.m_enemy = false;
info_6.m_texture = QByteArray(QByteArray::fromBase64("iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAM0ElEQVRoge2Zaaxd1XXHf2uf6c5v8PPzEDvGNoNdUhMwLSnQDBSV0lIhglCLkqhN0+YLCerwBTVfqkoRQqloOkoliISkShTSJiEpTVSqRqGtoLiliYMJGMexjXl+83333fmcvffqh3Pv4/nh56kmUqUu3atz7z3n7PP/r7X2mi78Hxd5KxZN7/9wVUSuEWE/InsF2YnoVlEmgCKCF9UlVI8h8j2MeRqR78iffKZ3oc+6pAQ69/3GzQa5V0RuQ9gpggHJX2GIFItQKiHFIhLH4By0W1CvI1n6gor5tHn40S/8xAk0P/qhnxMjDwj8CiKBAIiygl8U4iQHniRIkuREymUoFBBn4dQpdGYGnP0y8Pvhpx+b+okQWPrIB37XiDwIFEQAyZfMD5IfBURBAUEH5wUxAlGEqdVgbAyxFp0+BVn2AnBX/OefPfGWElj4zXvvNyJ/NlxJhu4ygCoyQD4konraQ/PfBtcbg1QqSBhCuw3ovwG3Ff7yc52zYQgvFvzsB3/tOnX+Qbda4yqIGaIDweefVZHBPjBxDIUEiSIkDHICqmia4vs96PXAeYCbReTjwENnw3FRFp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6/PtusP/dKt13fV65dvSlOCm4Q5awqDthTrOx7tlX/7kzWP7oW1IX0xAr0nlqc+Xwkwv7y6L6SMRUF13RueTbrT5/sd48f7XdePtJrH2pY29kaF255/Ip3frKcStRudjGBIXDKDxvLxx+ffu1B4Phg7YVnm/Wpjx198Qf3bbnsY7eOTtwQieTltRim0t7yYpYungnUhU5eDflGLgNjJi8vvEIXWAba5CZ2QKkcBL/4lav2f2kkjBKneRIrGMMfnTj8wFP1mbX/fQWDdXe+uzb+q+8dmXjP5jjZNJ+l01+Zn/rMDzrNJ4F0LaALnUr4AcgOMLeqyjrTyMFujpKRxATR8GTFGP6pMf/dby/NPnaG6x25El56ZnnxyDPLi48ZoeSVBrDIOuPFi/2X8hwzkhxQOQijUmBMgCExhuea9e8/dPLIx53q3Fnuywbv9rlmYXBhm/iCpafe7i6U35mp7399cfprD08d/YO6zQ69lc+8lCJAJDAZi9lOnkP+X9bK/wDrs0uV2ZqR8AAAAABJRU5ErkJggg=="));
m_map_of_pawn.insert(std::make_pair(0, 0), new Pawn(info));
m_map_of_pawn.insert(std::make_pair(0, 1), new Pawn(info_2));
m_map_of_pawn.insert(std::make_pair(1, 0), new Pawn(info_3));
m_map_of_pawn.insert(std::make_pair(8, 0), new Pawn(info_4));
m_map_of_pawn.insert(std::make_pair(6, 1), new Pawn(info_5));
m_map_of_pawn.insert(std::make_pair(7, 2), new Pawn(info_6));
QMap<std::pair<int, int>, CreatureInfo> map_of_creature_info;
for(auto it = m_map_of_pawn.begin(); it != m_map_of_pawn.end(); ++it)
{
map_of_creature_info.insert(it.key(), it.value()->getInfo());
}
emit initializationPawns(map_of_creature_info);
Update(m_position_map, m_size_cell);
}
void MapOfPawn::selectedCell(int x, int y, bool mark)
{
if(true == m_do_something)
{
return;
}
Pawn* selected_pawn = m_map_of_pawn.value(std::make_pair(x, y), nullptr);
if(true == mark)
{
if(nullptr == selected_pawn)
{
if(m_selected_pawn.first != -1 && m_selected_pawn.second != -1)
{
m_selected_cell = std::make_pair(x, y);
m_selected_enemy_pawn = std::make_pair(-1, -1);
emit selectNotPawn(true);
//BEGIN WORK
m_do_something = true;
emit setNewPositionPawn(m_selected_pawn.first, m_selected_pawn.second, m_selected_cell.first, m_selected_cell.second);
}
}
else
{
if(true == selected_pawn->getInfo().m_enemy && m_selected_pawn.first != -1 && m_selected_pawn.second != -1)
{
m_selected_cell = std::make_pair(-1, -1);
m_selected_enemy_pawn = std::make_pair(x, y);
//BEGIN WORK
m_do_something = true;
emit setNewPositionPawn(m_selected_pawn.first, m_selected_pawn.second, m_selected_enemy_pawn.first, m_selected_enemy_pawn.second);
}
if(false == selected_pawn->getInfo().m_enemy)
{
m_selected_pawn = std::make_pair(x, y);
m_selected_cell = std::make_pair(-1, -1);
m_selected_enemy_pawn = std::make_pair(-1, -1);
emit selectPawn(selected_pawn->getInfo(), true);
}
}
}
else
{
if(nullptr != selected_pawn)
{
emit selectPawn(selected_pawn->getInfo(), false);
}
else
{
emit selectNotPawn(false);
}
}
}
void MapOfPawn::selectedNotCell()
{
endWork();
emit selectNotPawn(true);
}
void MapOfPawn::Initialization(QVector2D position, QVector2D size)
{
loadPawnsFromServer();
m_position_map = position;
m_size_cell = size;
//TODO: przenieść gdy komunikacja bedzie gotowa
receiveFromServer(QString());
}
void MapOfPawn::Update(QVector2D position, QVector2D size)
{
m_position_map = position;
m_size_cell = size;
for(std::pair<int, int> key : m_map_of_pawn.keys())
{
Pawn* selected_pawn = m_map_of_pawn.value(key, nullptr);
if(nullptr == selected_pawn)
{
//pionek nie istnieje
continue;
}
selected_pawn->setPosition(m_position_map.x() + (key.first * m_size_cell.x()), m_position_map.y()+ (key.second * m_size_cell.y()));
selected_pawn->setSize(m_size_cell.x(), m_size_cell.y());
}
}
void MapOfPawn::endWork()
{
m_do_something = false;
m_selected_pawn = std::make_pair(-1, -1);
m_selected_cell = std::make_pair(-1, -1);
m_selected_enemy_pawn = std::make_pair(-1, -1);
}
void MapOfPawn::updatePawnInfo(std::pair<int, int> position, CreatureInfo info)
{
Pawn* pawn = m_map_of_pawn.value(position, nullptr);
if(nullptr == pawn)
{
return;
}
pawn->setInfo(info);
}
| true |
86d123201d7f5ae7a03267cd3a4b17de1e3171a0 | C++ | vtwireless/crts | /bin/stdoutOverride.cpp | UTF-8 | 3,145 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include "crts/crts.hpp"
#include "crts/debug.h"
// This gets called before we can know whither or not we really need to do
// this, because we cannot parse command-line options before libuhd.so is
// loaded.
// If libboost*.so and libuhd.so get fixed, and stops writing to stdout
// when they are loaded, this code will not be required for crts_radio to
// be able to use bash pipe lines, but this hack will not do anything that
// bad.
//
// Since now we are loading libuhd only in plugins it will be loaded
// after the calling of main(). That was not the case when we linked
// with libuhd with crts_radio.
//
// In the past: we needed to link to a dynamic linked library to programs that link
// with libuhd.so. We get this library to load before libuhd.so so we can
// stop libuhd.so from doing stupid things when it is loaded.
// Putting a constructor function in the source of the binary program did
// not get called before the libuhd.so constructor. We link our programs
// so that this constructor is called before the constructor in libuhd.so.
// The linker command line order mattered.
/*
Related discussion but not what we did here, ref:
https://stackoverflow.com/questions/22941756/how-do-i-prevent-a-\
library-to-print-to-stdout-in-linux-c
*/
static FILE *stdoutOverride(void)
{
FILE *crtsOut;
//fprintf(stderr, "%s:%d: calling %s()\n", __FILE__, __LINE__, __func__);
// When this is called we assume that there has been no data written
// to the stdout stream or stdout file descriptor. We need to setup a
// new file descriptor to catch the stdout stream data from the stupid
// libuhd.so library and send it to the stderr file descriptor.
// playing dup games requires that we know what STDOUT_FILENO is and
// etc.
DASSERT(STDIN_FILENO == 0, "");
DASSERT(STDOUT_FILENO == 1, "");
DASSERT(STDERR_FILENO == 2, "");
ASSERT(dup2(1,3) == 3, ""); // save stdout FD in 3
// The file in the kernel which was fd 1 is now fd 3,
// so writing to fd 3 will go to what the shell setup
// before now as stdout and fd 1.
ASSERT(dup2(2,1) == 1, ""); // make 1 be like stderr
// now stdout is writing to what is also stderr. The awkward thing is
// that stdout and stderr have different buffers and different
// flushing rules. The two streams will be in correct order within
// themselves but there will be no way to know the order between the
// two merged streams.
// Make crtsOut act like stdout stream used to.
ASSERT((crtsOut = fdopen(3, "w")) != NULL, "");
// Now writing to crtsOut will write out to a bash pipe line, for
// example.
// We can now write to crtsOut to write to what appears as stdout in a
// bash pipe line.
#if 0 // testing crtsOut
fprintf(crtsOut, "crtsOut %s:%d: calling %s()\n", __FILE__, __LINE__, __func__);
fflush(crtsOut);
#endif
return crtsOut;
}
// crtsOut will act like stdout after startupFunction() gets called.
// Note: that will happen before main() is called.
FILE *crtsOut = stdoutOverride();
| true |
77743e7cca62d570274b5c4b2f34a82c8fee2814 | C++ | mchmilar/RiskGroup | /BuilderDirector.h | UTF-8 | 505 | 2.734375 | 3 | [] | no_license | #ifndef DIRECTOR_H
#define DIRECTOR_H
#include <string>
#include <iostream>
#include "Map.h"
#include "MapBuilder.h"
#include "Game.h"
using namespace std;
class Director //Director
{
public:
void setMapBuilder(MapBuilder* mapBuild)
{
mapBuilder = mapBuild;
}
Map* getMap()
{
return mapBuilder->getMap();
}
Game* getGame()
{
return mapBuilder->getGame();
}
bool constructMap(string location)
{
return mapBuilder->createNewMap(location);
}
private:
MapBuilder* mapBuilder;
};
#endif
| true |
9ddb582d4cee6c8a1c90eb6eba96b276ac412a22 | C++ | mziobro/scene_recognition | /config.h | UTF-8 | 802 | 2.78125 | 3 | [] | no_license | #ifndef CONFIG_H
#define CONFIG_H
#include <QString>
/*!
* \brief The Config class is responsible for storing
* paths and other configurable settings
*
* \details Klasa wczytująca ścieżki do plików modelu YOLO
* i do streamu video
*/
class Config
{
public:
Config();
void read();
void save();
QString get_video_path() const;
QString get_yolo_cfg_path() const;
QString get_yolo_weights() const;
QString get_yolo_names_path() const;
private:
QString m_video_path;
QString m_yolo_cfg_path;
QString m_yolo_names_path;
QString m_yolo_weigths_path;
const QString m_video_path_default;
const QString m_yolo_cfg_path_default;
const QString m_yolo_names_path_default;
const QString m_yolo_weigths_path_default;
};
#endif // CONFIG_H
| true |
b3708eb431e1017055d54ac5feece9f121d90ef1 | C++ | JohnGoods/assembly | /汇编/012_无符号数条件转移指令JA JNBE(大于)/012_无符号数条件转移指令JA JNBE(大于).cpp | GB18030 | 363 | 2.859375 | 3 | [] | no_license | // 012_תָJA JNBE().cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
printf("begin\n");
int a = 3, b = -5;
unsigned int a2 = a, b2 = b; //
if (a2 <= b2)//ja{
{
if (a <= b) //jg
{
printf("do this");
}
}
printf("end");
return 0;
}
| true |
ffe6fbb830f94ac712753e6c2de0a1733c2b80e6 | C++ | ShravanCool/spoj-classical | /NegativeScore.cpp | UTF-8 | 1,616 | 3.015625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define SIZE 100000
class SegmentTree {
int tree[4*SIZE];
int parents[SIZE];
vector<int> elements;
int size;
int mergeNodes(int a, int b) { return std::min(a, b); }
public:
SegmentTree(vector<int> arr) : size(arr.size()) {
elements = arr;
buildTree(0, 0, size-1);
}
void buildTree(int curNode, int start, int end) {
if(start == end) {
tree[curNode] = elements[start];
parents[start] = curNode;
}
else {
int l = curNode*2 + 1;
int r = curNode*2 + 2;
int mid = (start+end)/2;
buildTree(l, start, mid);
buildTree(r, mid+1, end);
tree[curNode] = mergeNodes(tree[l], tree[r]);
}
}
int query(int curNode, int start, int end,
int qx, int qy) {
if(qx == start && qy == end)
return tree[curNode];
int l = curNode*2 + 1;
int r = curNode*2 + 2;
int mid = (start+end)/2;
if(qy <= mid)
return query(l, start, mid, qx, qy);
else if(qx > mid)
return query(r, mid+1, end, qx, qy);
else
return mergeNodes(
query(l, start, mid, qx, mid),
query(r, mid+1, end, mid+1, qy));
}
};
int main() {
int N, Q, T;
scanf("%d", &T);
for(int t = 1; t <= T; t++) {
scanf("%d%d", &N, &Q);
vector<int> arr(N);
for(int i = 0; i < N; i++)
scanf("%d", &arr[i]);
SegmentTree ss(arr);
printf("Scenario #%d:\n", t);
for(int i = 0; i < Q; i++) {
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", ss.query(0, 0, N-1, a-1, b-1));
}
}
return 0;
}
| true |
ae7dbef40c848b0b1a78db549f08315170a8c7aa | C++ | VipulKhandelwal1999/Data-Structures-Algorithms | /Leetcode/Tree/Maximum Difference between Node and Ancestor.cpp | UTF-8 | 851 | 3.625 | 4 | [] | no_license | /*
Intution: To make sure min/max values belong to an ancestor, we track min/max from the root till the leaf, and pick the biggest difference among all leaves.
and check if the difference between the (max_value - min_value) is greater than the current difference in such a case update the diff
*/
class Solution {
public:
int maxAncestorDiff(TreeNode* root)
{
int diff=INT_MIN;
util(root, INT_MAX, INT_MIN, diff);
return diff;
}
private:
void util(TreeNode* root, int mn, int mx, int &diff)
{
if(root==NULL)
return;
mn=min(mn, root->val); //preorder traversal
mx=max(mx, root->val);
diff=max(diff, mx-mn);
util(root->left, mn, mx, diff);
util(root->right, mn, mx, diff);
}
}; | true |
6703f6ffb554521355a022dc68c8032c7e98dec7 | C++ | MrFICAX/StrukturePodataka | /Tudji labovi/LabPraktikum/Lab2HashTabilice/StruktureLab2Zad4/HashObject.cpp | UTF-8 | 638 | 3.234375 | 3 | [] | no_license | #include"HashObject.h"
HashObject::HashObject()
{
this->key = 0;
record = NULL;
next = NULL;
}
HashObject::HashObject(int br)
{
this->key = br;
record = NULL;
next = NULL;
}
HashObject::HashObject(int br, char* ime)
{
this->key = br;
this->record = ime;
}
HashObject::HashObject(int br, char* ime, HashObject* obj)
{
this->key = br;
this->record = ime;
next = obj;
}
HashObject HashObject::operator=(HashObject obj)
{
this->key = obj.getKey();
this->record = obj.getRecord();
this->next = obj.next;
return *this;
}
HashObject::~HashObject() {}
void HashObject::print()
{
cout << getKey() << "|" << getRecord() << " ";
}
| true |
e088570e684cd9e91e474e9759de93849b43da31 | C++ | jlegendary/CPP-Practice-Programs | /Federal Tax Calculator/main.cpp | UTF-8 | 8,051 | 3.375 | 3 | [] | no_license | //
// main.cpp
// Federal Tax Calculator
//
// Created by JLegendary on 8/24/15.
// Copyright (c) 2015 JLegendary. All rights reserved.
//
#include <iostream> //Input and output
void getInfo(int &numPerson, int &salary, int &standardExemption, int &pretaxSavings);
int taxAmount(int numPerson, int salary, int standardExemption,
int pretaxSavings, int &taxableIncome, int &baseTax, int &marginTax);
// Main function
int main ()
{
int numPerson, salary, standardExemption, pretaxSavings, taxableIncome, baseTax, marginTax;
int totalTax;
//get getInfo
getInfo(numPerson, salary, standardExemption, pretaxSavings);
//get taxableIncome, baaseTax, marginTax, and totalTax.
totalTax = taxAmount(numPerson, salary, standardExemption, pretaxSavings, taxableIncome, baseTax, marginTax);
// Output adjusted income
std::cout << "\n\n\nAdjusted income: $" << taxableIncome << std::endl;
// Output base tax
std::cout << "Base tax: $" << baseTax << std::endl;
// Output additional tax
std::cout << "Addtional tax: $" << marginTax << std::endl;
// Output total tax owed
std::cout << "Total tax owed: $" << totalTax << std::endl;
return 0;
}
// Gets the input and stores them
void getInfo(int &numPerson, int &salary, int &standardExemption, int &pretaxSavings)
{
char maritalStatus, answer, rAnswer;
int numChildren;
int pensionPlan;
// Ask if single or married
std::cout << "What is your marital status?" << std::endl;
std::cout << "\tM for Married and S for Single: \n";
std::cout << "=====> ";
std::cin >> maritalStatus;
std::cout << std::endl;
// If married, standard exemption is 7000, and asks for kids
if (maritalStatus == 'm' || maritalStatus == 'M')
{
std::cout << "Please enter number of Children: " << std::endl;
std::cout << "\tMust be under the age of 14"<< std::endl;
std::cout << "=====> ";
std::cin >> numChildren;
std::cout << std::endl;
// stanardExemption for married couple
standardExemption = 7000;
// If both earn income, then combine income.
std::cout << "Do both spouses earn income?" << std::endl;
std::cout << "\tY or y for Yes" << std::endl;
std::cout << "\tAny other key for No : "<< std::endl;
std::cout << "====> ";
std::cin >> answer;
std::cout << std::endl;
// Enter combined salary:
if (answer == 'y' || answer == 'Y' )
{
std::cout << "\tYour combined salary is: $" << std::endl;
std::cout << "=====> $";
std::cin >> salary;
std::cout << std::endl;
}
// Enter just your salary
else
{
std::cout << "Enter your salary: " << std::endl;
std::cout << "=====> $";
std::cin >> salary;
std::cout << std::endl;
}
// Personal Exemption equals couple plus the number of children
numPerson = 2 + numChildren;
// Retirement contribution for married couple
std::cout << "Did you contribute to your retirement account?" << std::endl;
std::cout << "\tEnter y or Y, for Yes" << std::endl;
std::cout << "\tAnything else for No." << std::endl;
std::cout << "=====> ";
std::cin >> rAnswer;
// If answer is yes, put the percentage up to 6%
if (rAnswer == 'y' || rAnswer == 'Y')
{
std::cout << "\nEnter the percentage you put into the pension plan: " << std::endl;
std::cout << "\t6% is max" << std::endl;
std::cout << "=====> ";
std::cin >> pensionPlan;
// If above 0 and below 6% contributed
if (pensionPlan >0 && pensionPlan <=6)
{
pretaxSavings = pensionPlan * salary/100;
// Output pretax Savings from pension contribution
std::cout << "\tPre-tax saving from retirement account: $" << pretaxSavings << std::endl;
}
// If entered something beside 1 through 6
else
{
std::cout << "\tPlease put int 1-6%" << std::endl;
std::cin >>pensionPlan;
pretaxSavings = pensionPlan * salary/100;
std::cout << "\tPre-tax saving from retirement account: " << pretaxSavings << std::endl;
}
}
// If answer is no, didn't contribute to retirement
else
{
std::cout << "You didn't contribute to your retirement account." << std::endl;
pensionPlan = 0;
pretaxSavings = pensionPlan * salary/100;
std::cout << "Pre-tax saving from retirement account: " << pretaxSavings << std::endl;
}
}
// Single
else
{
// Input salary
std::cout << "Enter your salary: $";
std::cin >> salary;
std::cout << std::endl;
standardExemption = 4000;
numPerson = 1;
// Asks if contributed to retirement account
std::cout << "Did you contribute to your retirement account?" << std::endl;
std::cout << "\tType y or Y, for Yes" << std::endl;
std::cout << "\tAnything else for No." << std::endl;
std::cout << "=====> ";
std::cin >> rAnswer;
// if Yes
if (rAnswer == 'y' || rAnswer == 'Y')
{
std::cout << "\nEnter the percentage you put into the pension plan: \n";
std::cout << "\t6% is max" << std::endl;
std::cout << "=====> " << std::endl;
std::cin >> pensionPlan;
if (pensionPlan >0 && pensionPlan <=6)
{
pretaxSavings = pensionPlan * salary/100;
std::cout << "\tPre-tax saving from retirement account: $" << pretaxSavings << std::endl;
}
else
{
std::cout << "\tPlease put int 1-6%" << std::endl;
std::cout << "=====> ";
std::cin >>pensionPlan;
pretaxSavings = pensionPlan * salary/100;
std::cout << "\tPre-tax saving from retirement account: $" << pretaxSavings << std::endl;
}
}
// if No
else
{
std::cout << "\tYou didn't contribute to your retirement account." << std::endl;
pensionPlan = 0;
pretaxSavings = pensionPlan * salary/100;
std::cout << "\tPre-tax saving from retirement account: $" << pretaxSavings << std::endl;
}
}
}
// Calculate taxes owed
int taxAmount(int numPerson, int salary, int standardExemption, int pretaxSavings, int &taxableIncome, int &baseTax, int &marginTax)
{
int marginalIncome;
int totalTax;
// Taxable income
taxableIncome = salary - (1500 * numPerson) - standardExemption - pretaxSavings;
// Bracket 1
if (taxableIncome >= (0) && taxableIncome <= 15000)
{
baseTax =.15 * taxableIncome;
marginTax = 0;
totalTax = baseTax+marginTax;
}
// Bracket 2
else if (taxableIncome >= (15001) && taxableIncome <= 40000)
{
marginalIncome = taxableIncome - 15000;
marginTax = .25 * marginalIncome;
baseTax = 2250;
totalTax = baseTax+marginTax;
}
// Bracket 3
else if (taxableIncome > (40000))
{
marginalIncome = taxableIncome - 40000;
marginTax = .35 * taxableIncome;
baseTax = 8460;
totalTax = baseTax + marginTax;
}
// Returns the total tax owed
return totalTax;
}
| true |
436a62a97ca1d96a3b78b41fe5231d979bcbd231 | C++ | agudeloandres/C_Struct_Files | /data_structures/FILE3.CPP | UTF-8 | 1,880 | 2.96875 | 3 | [] | no_license | #include<iostream.h> //CREAR REGISTRO , ES UN ARCHIVO BINARIO
#include<stdio.h> // NO SE PUEDE EDITAR ESTUD.DAT
#include<fstream.h> // SOLO SE PUEDE CONSULTAR CON EL PROGRAMA FILE 2
#include<string.h>
#include<stdlib.h>
#include<conio.h>
void inse_inde (float,int);
//programa para el manejo de archivos
typedef struct alumno{
float codigo;
char nombre[35];
float telefono;
};
void main()
{
clrscr();
fstream archivo;
alumno estudiante;
char op,c,nom[35];
float cod,tel;
int n,i,k;
unsigned int sw;
//abrir el archivo en forma output=salida=escribir
archivo.open("estud.dat",ios::in|ios::binary);
//proceso de validacion de la existencia archivo
if (archivo.good()){
cout<<"archivo estud.dat ya existe-continua (S/N)";
do{
op=getchar();
}while(op !='S' && op!='s' && op!='N' && op!='n');
if (op=='N' || op=='n'){
exit (1);
}
}
archivo.close();
archivo.open("estud.dat",ios::out|ios::binary);
//captura de datos a grabar en el archivo
clrscr();
gotoxy(31,2);
printf("MANEJO DE ARCHIVOS");
gotoxy(10,4);
printf("CEDULA :");
gotoxy(10,6);
printf("NOMBRE :");
gotoxy(10,8);
printf("TELEFONO :");
do{
gotoxy(23,4);
printf(" ");
gotoxy(23,6);
printf(" ");
gotoxy(23,8);
printf(" ");
gotoxy(23,4);
scanf("%f",&cod);
gotoxy(23,6);
cin.getline(nom,35);
gotoxy(23,8);
scanf("%f",&tel);
estudiante.codigo=cod;
n=strlen(nom);
for(i=0;i<=n;i++){
estudiante.nombre[i]=nom[i];
}
estudiante.telefono=tel;
//escritura del registro captura en el archivo
archivo.write((char*) &estudiante,sizeof(estudiante));
gotoxy(10,16);
printf("Mas Datos (S/N) : ");
do{
op=getchar();
}while(op!='S' && op!='s' && op!='N' && op!='n');
gotoxy(10,16);
printf(" ");
}while (op=='S' || op=='s');
archivo.close();
getch();
} | true |
6293a5d681b85737bd99525707e3706bced25506 | C++ | jwqe764241/http-server | /lib/get_option/src/option_not_found_exception.hpp | UTF-8 | 463 | 3.203125 | 3 | [] | no_license | #pragma once
#include <string>
#include <exception>
namespace cmd
{
class option_not_found_exception : public std::exception
{
private:
std::string msg;
std::string option;
public:
option_not_found_exception(const std::string& message, const std::string& option)
: msg(msg), option(option)
{
}
const char* what() const noexcept
{
return msg.c_str();
}
const std::string& get_option() const noexcept
{
return option;
}
};
} | true |
6cd45167c26dc0baeae8b7f50472fc71cdc6cfae | C++ | Shao-Group/rnabridge-align | /src/hyper_node.cc | UTF-8 | 473 | 2.5625 | 3 | [
"BSD-3-Clause",
"BSL-1.0"
] | permissive | /*
Part of rnabridge-align
(c) 2019 by Mingfu Shao and The Pennsylvania State University.
See LICENSE for licensing.
*/
#include "hyper_node.h"
#include <cstdio>
hyper_node::hyper_node(const vector<int> &a, const vector<int> &b, int c)
{
origin = a;
todate = b;
count = c;
}
int hyper_node::print(int index) const
{
printf("hyper-node %d: count = %d", index, count);
for(int k = 0; k < origin.size(); k++)
{
printf("(%d, %d) ", origin[k], todate[k]);
}
return 0;
}
| true |
05e7331cd5fb2b58383f04a9ece804496fd686f4 | C++ | theoden8/snake | /Image.cpp | UTF-8 | 1,813 | 3.15625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <sstream>
#include "Image.hpp"
Image::Image()
{
width = 0;
height = 0;
id = 0;
}
bool Image::load(const std::string &filename) {
std::ifstream File(filename.c_str(), std::ios::in | std::ios::binary);
unsigned char header[20];
/* std::cerr << "TGA loading: " << filename << std::endl; */
if(!File.is_open()) {
id = 0;
std::cerr << "TGA loading: Wasn't able to find image " << filename << std::endl;
return false;
}
File.read(reinterpret_cast <char *> (header), sizeof(char) * 18);
if(header[2] != 2) {
File.close();
id = 0;
std::cerr << "TGA loading: wrong file header " << filename << std::endl;
return false;
}
if(header[0])
File.seekg(header[0], std::ios_base::cur);
width = header[13] * 256 + header[12];
height = header[15] * 256 + header[14];
int bpp = header[16] / 8;
if(bpp != 4) {
File.close();
id = 0;
std::cerr << "TGA loading: wrong bit depth: " << filename << std::endl;
return false;
}
long ImageSize = width * height * bpp;
unsigned char *data = new unsigned char[ImageSize];
File.read(reinterpret_cast <char *> (data), sizeof(char) * ImageSize);
for(GLuint cswap = 0; cswap < (unsigned int) ImageSize; cswap += bpp)
std::swap(data[cswap], data[cswap + 2]);
File.close();
unsigned int color_mode = GL_RGBA;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, color_mode, width, height, 0, color_mode, GL_UNSIGNED_BYTE, data);
delete [] data;
data = NULL;
/* std::cerr << "TGA loading: finished id = " << id << std::endl; */
return true;
}
| true |
4c5f8110034b2eda8d63150e85e077074a1aa25f | C++ | thaddeusdiamond/Social-Hierarchical-Learning | /src/Primitives/Student/CreateSensor.cc | UTF-8 | 3,223 | 2.890625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* @file
* @author Thaddeus Diamond <diamond@cs.yale.edu>
* @version 0.1
*
* @section DESCRIPTION
*
* This is the implementation for create controller/sensor
*/
/** @todo This should really have a unit test, but it's not super important
* since this is a pretty dumb sensor **/
#include "Student/CreateSensor.h"
namespace Primitives {
CreateSensor::CreateSensor(int port, int recipient_ipv4, int recipient_port)
: Sensor(std::string("Create Controller")), num_values_(4),
received_(false) {
/** @todo max/min values, sig figs, and nearby thresholds need to be set **/
// Create vanilla socket
controller_socket_ = socket(PF_INET, SOCK_DGRAM, 0);
if (controller_socket_ < 0)
Die("Could not create a Create I/O socket");
// Bind the socket to listen
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if (bind(controller_socket_, reinterpret_cast<struct sockaddr*>(&server),
sizeof(server)))
Die("Could not bind Create socket to specified port");
// Set the socket to be reusable
int on = 1;
if (setsockopt(controller_socket_, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<char*>(&on), sizeof(on)) < 0)
Die("Failed to make Create socket reusable");
// Who are we communicating with?
struct sockaddr_in controller_ipv4;
memset(&controller_ipv4, 0, sizeof(controller_ipv4));
controller_ipv4.sin_family = PF_INET;
controller_ipv4.sin_addr.s_addr = recipient_ipv4;
controller_ipv4.sin_port = htons(recipient_port);
controller_address_ = reinterpret_cast<struct sockaddr*>(&controller_ipv4);
// Spawn thread to poll
pthread_create(&controller_thread_, NULL, &CommunicateWithCreate, this);
}
void CreateSensor::ListenOnSocket() {
while (true) {
char buffer[4096];
memset(buffer, 0, sizeof(buffer));
recv(controller_socket_, buffer, sizeof(buffer), 0);
received_ = true;
CreateController* controller = new CreateController();
assert(controller->ParseFromString(buffer));
double new_values[4] =
{ controller->right_motor(), controller->left_motor(),
controller->right_led(), controller->left_led() };
values_ = new_values;
}
}
bool CreateSensor::SetValues(double const * const values, int num_values) {
// Must be exactly four motors (R/L and two LEDs)
if (num_values != 4)
return false;
// Create a serializable protobuf and send it
CreateController* controller = new CreateController();
controller->set_right_motor(values[0]);
controller->set_left_motor(values[1]);
controller->set_right_led(values[2]);
controller->set_left_led(values[3]);
// Send on wire
string message;
assert(controller->SerializeToString(&message));
sendto(controller_socket_, message.c_str(), message.length() + 1, 0,
controller_address_, sizeof(*controller_address_));
return true;
}
double const * const CreateSensor::GetValues() {
// Return a one-element array to most recent value
Poll();
return values_;
}
bool CreateSensor::Poll() {
if (received_) {
received_ = false;
return true;
}
return false;
}
} // namespace Primitives
| true |
6773d22066e78eb3e7a8a6ee2c2533df0761becb | C++ | PabloTabilo/codeforces-challenge | /problems_A/p30/p23_A_BlackJack.cpp | UTF-8 | 905 | 2.59375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int cardsVals[9] = {2,3,4,5,6,7,8,9,10};
int kingJack[2] = {10, 10};
int rQ[1] = {10};
int a1[1] = {1};
int a11[1] = {11};
n -= 10;
int poss = 0;
int res=0;
for(int i=0;i<9;i++){
if(cardsVals[i] == n)
res++;
}
res*=4;
poss+=res;
res = 0;
for(int i=0;i<2;i++){
if(kingJack[i] == n)
res++;
}
res*=4;
poss+=res;
res = 0;
for(int i=0;i<1;i++){
if(rQ[i] == n)
res++;
}
res*=3;
poss+=res;
res = 0;
for(int i=0;i<1;i++){
if(a1[i] == n)
res++;
}
res*=4;
poss+=res;
res = 0;
for(int i=0;i<1;i++){
if(a11[i] == n)
res++;
}
res*=4;
poss+=res;
cout<<poss<<endl;
return 0;
}
| true |
5346b4c79a72fcb0aabe2b091b693da5623e5172 | C++ | ervivekbind/kineticball | /MasterProgram.ino | UTF-8 | 170,686 | 2.65625 | 3 | [] | no_license | // Include the AccelStepper library:
#include <AccelStepper.h>
// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPin 22
#define stepPin 23
#define dirPin 24
#define stepPin 25
#define dirPin 26
#define stepPin 27
#define dirPin 28
#define stepPin 29
#define dirPin 30
#define stepPin 31
#define dirPin 32
#define stepPin 33
#define dirPin 34
#define stepPin 35
#define dirPin 36
#define stepPin 37
#define dirPin 38
#define stepPin 39
#define dirPin 40
#define stepPin 41
#define dirPin 42
#define stepPin 43
#define dirPin 44
#define stepPin 45
#define motorInterfaceType 1
//Check condition of power failur or off instruction
int Check1 = 12;
//for wave next again
int i = 0;
// Create a new instance of the AccelStepper class:
AccelStepper Motor1 = AccelStepper(motorInterfaceType, 23, 22);
AccelStepper Motor2 = AccelStepper(motorInterfaceType, 25, 24);
AccelStepper Motor3 = AccelStepper(motorInterfaceType, 27, 26);
AccelStepper Motor4 = AccelStepper(motorInterfaceType, 29, 28);
AccelStepper Motor5 = AccelStepper(motorInterfaceType, 31, 30);
AccelStepper Motor6 = AccelStepper(motorInterfaceType, 33, 32);
AccelStepper Motor7 = AccelStepper(motorInterfaceType, 35, 34);
AccelStepper Motor8 = AccelStepper(motorInterfaceType, 37, 36);
AccelStepper Motor9 = AccelStepper(motorInterfaceType, 39, 38);
AccelStepper Motor10 = AccelStepper(motorInterfaceType, 41, 40);
AccelStepper Motor11 = AccelStepper(motorInterfaceType, 43, 42);
AccelStepper Motor12 = AccelStepper(motorInterfaceType, 45, 44);
void setup() {
// Set the maximum speed in steps per second:
Motor1.setMaxSpeed(1000);
Motor2.setMaxSpeed(1000);
Motor3.setMaxSpeed(1000);
Motor4.setMaxSpeed(1000);
Motor5.setMaxSpeed(1000);
Motor6.setMaxSpeed(1000);
Motor7.setMaxSpeed(1000);
Motor8.setMaxSpeed(1000);
Motor9.setMaxSpeed(1000);
Motor10.setMaxSpeed(1000);
Motor11.setMaxSpeed(1000);
Motor12.setMaxSpeed(1000);
//pin type as input
pinMode(Check1, INPUT);
Serial.begin(9600);
}
void loop() {
//Pattern1:All UP & Down----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
//Speed=Distance/time
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
}
delay(1000);
// Reset the position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
// Speed=Distance/Time
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
}
delay(2000);
//Pattern2:Moving Square------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
}
delay(1000);
// Reset the position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
}
delay(1000);
// Reset the position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 )
{
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
}
delay(1000);
// Reset the position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 )
{
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
}
delay(1000);
// Reset the position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 )
{
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
}
delay(2000);
//Pattern2:Moving Square Fast Not Done Yet!!
//Pattern3:StairCase----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
for(int repeat = 1; repeat <= 3; repeat++)
{
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 3000 || Motor4.currentPosition() != 3000 || Motor7.currentPosition() != 3000 || Motor10.currentPosition() != 3000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
if(Motor1.currentPosition() == 2000 || Motor4.currentPosition() == 2000 || Motor7.currentPosition() == 2000 || Motor10.currentPosition() == 2000)
break;
}
delay(1000);
while(Motor2.currentPosition() != 3000 || Motor5.currentPosition() != 3000 || Motor8.currentPosition() != 3000 || Motor11.currentPosition() != 3000 )
{
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
if(Motor2.currentPosition() == 2000 || Motor5.currentPosition() == 2000 || Motor8.currentPosition() == 2000 || Motor11.currentPosition() == 2000)
break;
}
delay(1000);
while(Motor3.currentPosition() != 3000 || Motor6.currentPosition() != 3000 || Motor9.currentPosition() != 3000 || Motor12.currentPosition() != 3000 )
{
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor3.currentPosition() == 2000 || Motor6.currentPosition() == 2000 || Motor9.currentPosition() == 2000 || Motor12.currentPosition() == 2000)
break;
} delay(1000);
}
delay(2000);
for(int repeat = 1; repeat <= 3; repeat++)
{
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor3.currentPosition() != -3000 || Motor6.currentPosition() != -3000 || Motor9.currentPosition() != -3000 || Motor12.currentPosition() != -3000 )
{
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor3.currentPosition() == -2000 || Motor6.currentPosition() == -2000 || Motor9.currentPosition() == -2000 || Motor12.currentPosition() == -2000)
break;
}
delay(1000);
while(Motor2.currentPosition() != -3000 || Motor5.currentPosition() != -3000 || Motor8.currentPosition() != -3000 || Motor11.currentPosition() != -3000 )
{
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
if(Motor2.currentPosition() == -2000 || Motor5.currentPosition() == -2000 || Motor8.currentPosition() == -2000 || Motor11.currentPosition() == -2000)
break;
}
delay(1000);
while(Motor1.currentPosition() != -3000 || Motor4.currentPosition() != -3000 || Motor7.currentPosition() != 3000 || Motor10.currentPosition() != -3000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
if(Motor1.currentPosition() == -2000 || Motor4.currentPosition() == -2000 || Motor7.currentPosition() == -2000 || Motor10.currentPosition() == -2000)
break;
}
delay(1000);
}
delay(2000);
//Pattern5:Pyramid-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == 3000 || Motor2.currentPosition() == 3000 || Motor3.currentPosition() == 3000 || Motor4.currentPosition() == 3000 || Motor5.currentPosition() == 3000 || Motor6.currentPosition() == 3000 || Motor7.currentPosition() == 3000 || Motor8.currentPosition() == 3000 || Motor9.currentPosition() == 3000 || Motor10.currentPosition() == 3000 || Motor11.currentPosition() == 3000 || Motor12.currentPosition() == 3000 )
break;
}
delay(1000);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == 3000 || Motor2.currentPosition() == 3000 || Motor3.currentPosition() == 3000 || Motor4.currentPosition() == 3000 || Motor6.currentPosition() == 3000 || Motor7.currentPosition() == 3000 || Motor9.currentPosition() == 3000 || Motor10.currentPosition() == 3000 || Motor11.currentPosition() == 3000 || Motor12.currentPosition() == 3000 )
break;
}
delay(500);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == -3000 || Motor2.currentPosition() == -3000 || Motor3.currentPosition() == -3000 || Motor4.currentPosition() == -3000 || Motor6.currentPosition() == -3000 || Motor7.currentPosition() == -3000 || Motor9.currentPosition() == -3000 || Motor10.currentPosition() == -3000 || Motor11.currentPosition() == -3000 || Motor12.currentPosition() == -3000 )
break;
}
delay(500);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == 3000 || Motor2.currentPosition() == 3000 || Motor3.currentPosition() == 3000 || Motor4.currentPosition() == 3000 || Motor5.currentPosition() == -3000 || Motor6.currentPosition() == 3000 || Motor7.currentPosition() == 3000 || Motor8.currentPosition() == -3000 || Motor9.currentPosition() == 3000 || Motor10.currentPosition() == 3000 || Motor11.currentPosition() == 3000 || Motor12.currentPosition() == 3000 )
break;
}
delay(500);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
}
delay(500);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == 3000 || Motor2.currentPosition() == 3000 || Motor3.currentPosition() == 3000 || Motor4.currentPosition() == 3000 || Motor5.currentPosition() == -3000 || Motor6.currentPosition() == 3000 || Motor7.currentPosition() == 3000 || Motor8.currentPosition() == -3000 || Motor9.currentPosition() == 3000 || Motor10.currentPosition() == 3000 || Motor11.currentPosition() == 3000 || Motor12.currentPosition() == 3000 )
break;
}
delay(500);
// Reset the position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
// Speed=Distance/Time
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == -3000 || Motor2.currentPosition() == -3000 || Motor3.currentPosition() == -3000 || Motor4.currentPosition() == -3000 || Motor5.currentPosition() == -3000 || Motor6.currentPosition() == -3000 || Motor7.currentPosition() == -3000 || Motor8.currentPosition() == -3000 || Motor9.currentPosition() == -3000 || Motor10.currentPosition() == -3000 || Motor11.currentPosition() == -3000 || Motor12.currentPosition() == -3000 )
break;
}
delay(2000);
//Pattern5A:Snake------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
//Program5:SnakeMovement
//Speed=Distance/time
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
if(Motor1.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
if(Motor2.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
if(Motor3.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor6.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
if(Motor6.currentPosition() == 1000)
{
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor5.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
if(Motor5.currentPosition() == 1000)
{
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor4.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
if(Motor4.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
if(Motor7.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
if(Motor8.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
if(Motor9.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor5.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor4.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor12.currentPosition() != 6000 || Motor11.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
if(Motor11.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor6.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor5.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != -6000)
{
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
if(Motor10.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor4.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != 6000)
{
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
if(Motor10.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor11.currentPosition() != -6000 || Motor10.currentPosition() != -6000)
{
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
if(Motor10.currentPosition() == -1000)
{
Motor11.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
while(Motor10.currentPosition() != -1000)
{
Motor10.setSpeed(-1000);
Motor10.runSpeed();
if(Motor10.currentPosition() == -1000)
{ Motor10.setCurrentPosition(0);
goto Again;
}
}
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
Again:
delay(2000);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
//Program5B:Semi-Snake------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Speed=Distance/time
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
if(Motor1.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
if(Motor2.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
if(Motor3.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
if(Motor4.currentPosition() == 1000)
{
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
if(Motor5.currentPosition() == 1000)
{
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
if(Motor6.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
if(Motor7.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
if(Motor8.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
if(Motor9.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
if(Motor10.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
if(Motor11.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != 6000)
{
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor12.currentPosition() != -1000)
{
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -1000)
{ Motor12.setCurrentPosition(0);
goto Next;
}
}
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
Next:
delay(2000);
//Program6:Wave------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
//Speed=Distance/time
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor1.currentPosition() == 3000 || Motor2.currentPosition() == 3000 || Motor3.currentPosition() == 3000 || Motor4.currentPosition() == 3000 || Motor5.currentPosition() == 3000 || Motor6.currentPosition() == 3000 || Motor7.currentPosition() == 3000 || Motor8.currentPosition() == 3000 || Motor9.currentPosition() == 3000 || Motor10.currentPosition() == 3000 || Motor11.currentPosition() == 3000 || Motor12.currentPosition() == 3000 )
break;
}
delay(1000);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
//Speed=Distance/time
nextagain:
{ i = i+1;
delay(10);
}
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
if(Motor9.currentPosition() == 3000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 3000)
{
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -3000)
{
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != 6000 || Motor2.currentPosition() != 6000 || Motor3.currentPosition() != 6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
Motor2.setSpeed(1000);
Motor2.runSpeed();
Motor3.setSpeed(1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(-1000);
Motor7.runSpeed();
Motor8.setSpeed(-1000);
Motor8.runSpeed();
Motor9.setSpeed(-1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -3000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != 6000 || Motor5.currentPosition() != 6000 || Motor6.currentPosition() != 6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(1000);
Motor4.runSpeed();
Motor5.setSpeed(1000);
Motor5.runSpeed();
Motor6.setSpeed(1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -3000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor1.currentPosition() != -6000 || Motor2.currentPosition() != -6000 || Motor3.currentPosition() != -6000 || Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor7.currentPosition() != 6000 || Motor8.currentPosition() != 6000 || Motor9.currentPosition() != 6000 || Motor10.currentPosition() != 6000 || Motor11.currentPosition() != 6000 || Motor12.currentPosition() != 6000)
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
Motor2.setSpeed(-1000);
Motor2.runSpeed();
Motor3.setSpeed(-1000);
Motor3.runSpeed();
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
Motor10.setSpeed(1000);
Motor10.runSpeed();
Motor11.setSpeed(1000);
Motor11.runSpeed();
Motor12.setSpeed(1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == 3000)
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
if(i <= 6)
{
goto nextagain;
}
else
{ goto nextagain1;}
}}}}}}}}}}}}
nextagain1:
{ Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor4.currentPosition() != -6000 || Motor5.currentPosition() != -6000 || Motor6.currentPosition() != -6000 || Motor10.currentPosition() != -6000 || Motor11.currentPosition() != -6000 || Motor12.currentPosition() != -6000)
{
Motor4.setSpeed(-1000);
Motor4.runSpeed();
Motor5.setSpeed(-1000);
Motor5.runSpeed();
Motor6.setSpeed(-1000);
Motor6.runSpeed();
Motor10.setSpeed(-1000);
Motor10.runSpeed();
Motor11.setSpeed(-1000);
Motor11.runSpeed();
Motor12.setSpeed(-1000);
Motor12.runSpeed();
if(Motor12.currentPosition() == -3000)
while(Motor7.currentPosition() != -6000 || Motor8.currentPosition() != -6000 || Motor9.currentPosition() != -6000 )
{ Motor7.setSpeed(1000);
Motor7.runSpeed();
Motor8.setSpeed(1000);
Motor8.runSpeed();
Motor9.setSpeed(1000);
Motor9.runSpeed();
if(i==7)
{
goto nextagain2;
}
}
}
}
nextagain2:
while(1)
{}
delay(2000);
//Pattern7:Rain---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(digitalRead(Check1) == HIGH)
{
Serial.print("Stop ");
}
while(Motor2.currentPosition() != 6000 )
{
Motor2.setSpeed(1000);
Motor2.runSpeed();
}
delay(100);
while(Motor10.currentPosition() != 6000 )
{
Motor10.setSpeed(1000);
Motor10.runSpeed();
}
delay(100);
while(Motor9.currentPosition() != 6000 )
{
Motor9.setSpeed(1000);
Motor9.runSpeed();
}
delay(100);
while(Motor5.currentPosition() != 6000 )
{
Motor5.setSpeed(1000);
Motor5.runSpeed();
}
delay(100);
while(Motor4.currentPosition() != 6000 )
{
Motor4.setSpeed(1000);
Motor4.runSpeed();
}
delay(100);
while(Motor6.currentPosition() != 6000 )
{
Motor6.setSpeed(1000);
Motor6.runSpeed();
}
delay(100);
while(Motor8.currentPosition() != 6000 )
{
Motor8.setSpeed(1000);
Motor8.runSpeed();
}
delay(100);
while(Motor1.currentPosition() != 6000 )
{
Motor1.setSpeed(1000);
Motor1.runSpeed();
}
delay(100);
while(Motor12.currentPosition() != 6000 )
{
Motor12.setSpeed(1000);
Motor12.runSpeed();
}
delay(100);
while(Motor7.currentPosition() != 6000 )
{
Motor7.setSpeed(1000);
Motor7.runSpeed();
}
delay(100);
while(Motor11.currentPosition() != 6000 )
{
Motor11.setSpeed(1000);
Motor11.runSpeed();
}
delay(100);
while(Motor3.currentPosition() != 6000 )
{
Motor3.setSpeed(1000);
Motor3.runSpeed();
}
delay(2000);
// Set the current position to 0:
Motor1.setCurrentPosition(0);
Motor2.setCurrentPosition(0);
Motor3.setCurrentPosition(0);
Motor4.setCurrentPosition(0);
Motor5.setCurrentPosition(0);
Motor6.setCurrentPosition(0);
Motor7.setCurrentPosition(0);
Motor8.setCurrentPosition(0);
Motor9.setCurrentPosition(0);
Motor10.setCurrentPosition(0);
Motor11.setCurrentPosition(0);
Motor12.setCurrentPosition(0);
while(Motor7.currentPosition() != -6000 )
{
Motor7.setSpeed(-1000);
Motor7.runSpeed();
}
delay(100);
while(Motor11.currentPosition() != -6000 )
{
Motor11.setSpeed(-1000);
Motor11.runSpeed();
}
delay(100);
while(Motor9.currentPosition() != -6000 )
{
Motor9.setSpeed(-1000);
Motor9.runSpeed();
}
delay(100);
while(Motor2.currentPosition() != -6000 )
{
Motor2.setSpeed(-1000);
Motor2.runSpeed();
}
delay(100);
while(Motor12.currentPosition() != -6000 )
{
Motor12.setSpeed(-1000);
Motor12.runSpeed();
}
delay(100);
while(Motor4.currentPosition() != -6000 )
{
Motor4.setSpeed(-1000);
Motor4.runSpeed();
}
delay(100);
while(Motor6.currentPosition() != -6000 )
{
Motor6.setSpeed(-1000);
Motor6.runSpeed();
}
delay(100);
while(Motor10.currentPosition() != -6000 )
{
Motor10.setSpeed(-1000);
Motor10.runSpeed();
}
delay(100);
while(Motor5.currentPosition() != -6000 )
{
Motor5.setSpeed(-1000);
Motor5.runSpeed();
}
delay(100);
while(Motor1.currentPosition() != -6000 )
{
Motor1.setSpeed(-1000);
Motor1.runSpeed();
}
delay(100);
while(Motor3.currentPosition() != -6000 )
{
Motor3.setSpeed(-1000);
Motor3.runSpeed();
}
delay(100);
while(Motor8.currentPosition() != -6000 )
{
Motor8.setSpeed(-1000);
Motor8.runSpeed();
}
delay(2000);
}
| true |
349cc885c47988a88354157b60083d1265c9362f | C++ | ArtemMinder/Parking-Lot | /Bussiness_logic/motorcyclespot.h | UTF-8 | 332 | 2.671875 | 3 | [] | no_license | #ifndef MOTORCYCLESPOT_H
#define MOTORCYCLESPOT_H
#include "parkingspot.h"
class MotorcycleSpot : public ParkingSpot
{
public:
MotorcycleSpot(int const& newNumberOfSpot);
int getNumberOfSpot() const;
private:
int numberOfSpot = 0;
Types::SpotType type = Types::SpotType::Motorcycle;
};
#endif // MOTORCYCLESPOT_H
| true |
693c8d97ac07976c20e222865c07ab71e7c55c2f | C++ | mandyedi/craftinginterpreters-cpp | /interpreter/lox/lox/token.h | UTF-8 | 1,856 | 3.34375 | 3 | [
"MIT"
] | permissive | #ifndef TOKEN_H
#define TOKEN_H
#include "token_type.h"
struct Null
{
template<typename T>
bool operator==( T const& rhs ) const
{
return false;
}
bool operator==( Null const& rhs ) const
{
return true;
}
bool operator<( Null const& rhs ) const
{
return false;
}
};
typedef std::variant<Null, double, std::string> Object;
class Token
{
public:
Token( const Token &other )
{
Type = other.Type;
Lexeme = other.Lexeme;
Literal = other.Literal;
Line = other.Line;
}
Token( Token&& other ) noexcept
: Type(std::move(other.Type))
, Lexeme(std::move(other.Lexeme))
, Literal(std::move(other.Literal))
, Line(std::exchange(other.Line, 0))
{}
Token& operator= ( const Token &other )
{
if (this != &other)
{
Type = other.Type;
Lexeme = other.Lexeme;
Literal = other.Literal;
Line = other.Line;
}
return *this;
}
Token& operator=( Token &&other ) noexcept
{
if (this != &other)
{
Type = std::move(other.Type);
Lexeme = std::move(other.Lexeme);
Literal = std::move(other.Literal);
Line = std::exchange(other.Line, 0);
}
return *this;
}
Token()
: Type( TokenType::EOFILE )
, Lexeme( "" )
, Literal( 0.0 )
, Line( 0 )
{}
Token( TokenType type, const std::string& lexeme, const Object& literal, int line )
: Type( type )
, Lexeme( lexeme )
, Literal( literal )
, Line( line )
{}
~Token() {}
inline std::string GetString()
{
std::string literalString = TokenTypeString[(unsigned int)Type] + " " + Lexeme + " ";
if ( Type == TokenType::NUMBER )
{
literalString += std::to_string( std::get<double>( Literal ) );
}
else if ( Type == TokenType::STRING )
{
literalString += std::get<std::string>( Literal );
}
return literalString;
}
TokenType Type;
std::string Lexeme;
Object Literal;
int Line;
};
#endif // TOKEN_H | true |
c10d22776f8c7b4b638704c7ac580e62251b002b | C++ | Kaldie/GeRoBot | /motor/JointController.cpp | UTF-8 | 8,043 | 2.640625 | 3 | [] | no_license | // Copyright [2014] Ruud Cools
#include <macroHeader.h>
#include <JointController.h>
#include <ArduinoMotorDriver.h>
#include <StateSequence.h>
#include <SequenceVector.h>
#include <BaseJoint.h>
#include <BaseMotor.h>
#include <PinState.h>
#include <EndStop.h>
JointController::JointController()
:m_jointPointerVector({}),
m_actuator(ArduinoMotorDriver("/dev/ttyUSB*")),
m_sequenceVector() {
}
JointController::~JointController()
{}
bool JointController::validateJoint(const BaseJoint::JointPointer& i_baseJoint) const {
// pins should not be other then 2 t/m 7
if (!i_baseJoint) {
LOG_ERROR("Invalid JointPointer!");
}
PinVector pins = i_baseJoint->getMotor()->getPins();
for (PinVector::const_iterator itr = pins.begin();
itr != pins.end();
itr++) {
if (((*itr) > std::get<1>(m_actuator.getJointPinRange())) ||
((*itr) < std::get<0>(m_actuator.getJointPinRange()))) {
LOG_INFO("Pin: " << (*itr) << " is not within range: " <<
std::get<0>(m_actuator.getJointPinRange()) <<
", " << std::get<1>(m_actuator.getJointPinRange())) ;
return false;
}
}
return true;
}
bool JointController::validateJointVector(
const JointController::JointPointerVector& i_jointVector) const {
// determines if the pinIterator-> is able to grow into a good JointVector
for (JointController::JointPointerVector::const_iterator itr = i_jointVector.begin();
itr != i_jointVector.end();
itr++) {
// All joints should be valid
if (!validateJoint(*itr))
return false;
}
// Number of joints should not be other then 2....or max 2...
if (i_jointVector.size() > 2)
return false;
// If the number of joints is 1 we're done!
if (i_jointVector.size() == 1)
return true;
// Movement type of the joints should not be equal
if (i_jointVector[0]->getMovementType() ==
i_jointVector[1]->getMovementType())
return false;
// get all pins
PinVector pinVector;
for (auto jointIterator = i_jointVector.begin();
jointIterator != i_jointVector.end();
jointIterator++) {
PinVector jointPins = (*jointIterator)->getMotor()->getPins();
pinVector.insert(pinVector.end(), jointPins.begin(), jointPins.end());
}
for (auto pinIterator = pinVector.begin();
pinIterator != pinVector.end();
pinIterator++) {
if (std::find(pinIterator, pinVector.end(), *pinIterator) ==
pinVector.end()) {
LOG_DEBUG("Joint is not available, defines the same pins!");
return false;
}
}
return true;
}
bool JointController::addJoint(const BaseJoint::JointPointer& i_joint) {
/*
This gonna be fun!!
We want to store the joints in a pinIterator->, however they are defined as base joints
If we want to use the derived stuff, we need to:
clone it
put the clone on the heap
put a pointer in the m_jointPointerVector
*/
if (!hasJoint(i_joint)) {
m_jointPointerVector.push_back(i_joint);
if (!validateJointVector(m_jointPointerVector)){
m_jointPointerVector.pop_back();
LOG_ERROR("Joint is not valid!");
}
}
LOG_DEBUG("Resetting pin state sequence");
LOG_DEBUG("Current size: " << m_jointPointerVector.size());
resetPinStateSequence();
return true;
}
BaseJoint::JointPointer JointController::getJoint(const BaseJoint::MovementType &i_movementType) const {
if (m_jointPointerVector.size() == 0)
LOG_ERROR("No joints defined yet");
for (JointController::JointPointerVector::const_iterator itr = m_jointPointerVector.begin();
itr != m_jointPointerVector.end();
itr++) {
if ((*itr)->getMovementType() == i_movementType) {
return *itr;
}
}
LOG_ERROR("Could not find joint with the correct movement type!");
}
void JointController::resetPinStateSequence() {
StateSequence stateSequence;
for (auto& joint : m_jointPointerVector) {
stateSequence.addToSequence(joint->getMotor()->getCurrentPinState(), true);
}
m_sequenceVector.appendStateSequence(stateSequence, false);
m_sequenceVector.clean();
}
bool JointController::hasJoint(const BaseJoint::JointPointer& i_jointPointer) const {
for (JointPointerVector::const_iterator itr = m_jointPointerVector.begin();
itr != m_jointPointerVector.end();
itr++) {
if (i_jointPointer == (*itr))
return true;
}
return false;
}
const BaseJoint::JointPointer JointController::getRootJoint() const {
for (auto jointPointer : m_jointPointerVector) {
if (jointPointer->getParent().expired()) {
return jointPointer;
}
}
LOG_ERROR("Could not find a parent joint!");
}
void JointController::moveSteps(const std::string& i_directionString,
const int& i_numberOfSteps) {
resolveJoint(i_directionString)->
moveSteps(i_directionString, i_numberOfSteps, &m_sequenceVector);
}
// Brief: Actuate the robot from the given pin state sequence
void JointController::actuate() {
m_actuator.actuate();
resetPinStateSequence();
}
void JointController::uploadSequence(const bool& i_condense) {
LOG_DEBUG("Sending: " << m_sequenceVector.numberOfSequences() << " sequences!");
LOG_DEBUG("Sending: " << m_sequenceVector.numberOfSteps() << " steps!");
m_sequenceVector.normalise();
if (i_condense) {
m_sequenceVector.condenseVector();
}
#ifdef DEBUG
unsigned long sendCount = 0;
unsigned long totalSize = m_sequenceVector.getSequenceVector().size();
#endif
for (const auto& stateSequence : m_sequenceVector) {
/// Get the integer sequence of this pin state
if (stateSequence.getNumberOfRepetitions() > 0) {
m_actuator.upload(stateSequence.createArduinoBuffer());
#ifdef DEBUG
++sendCount;
LOG_DEBUG("Percentage send: " <<
static_cast<float>(sendCount) / totalSize * 100 << "%.");
#endif
}
}
}
std::shared_ptr<EndStop> JointController::resolveEndStopHit() {
int jointValue, endStopValue;
m_actuator.resolveEndStopHit(&jointValue, &endStopValue);
LOG_DEBUG("Actuator resolved end stop");
LOG_DEBUG("Recieved joint value: " << jointValue);
LOG_DEBUG("Received end stop value: " << endStopValue);
PinState jointPinState, stopPinState;
std::tuple<int, int> pinRange(m_actuator.getJointPinRange());
for (int i= std::get<0>(pinRange);
i <= std::get<1>(pinRange); ++i) {
jointPinState.update(i, (jointValue & (1<<i))>>i);
}
pinRange = m_actuator.getStopPinRange();
for (int i = std::get<0>(pinRange);
i <= std::get<1>(pinRange); ++i) {
stopPinState.update(i, (endStopValue & 1<<i)>>i);
}
std::string jointDirection;
std::shared_ptr<EndStop> endStop;
for (const auto& joint : m_jointPointerVector) {
if (joint->getJointStatus(jointPinState, &jointDirection)) {
endStop = joint->getEndStop(stopPinState, jointDirection);
if (endStop) {
joint->updateJointOnEndStopHit(endStop);
}
}
}
return endStop;
}
BaseJoint::JointPointer JointController::resolveJoint(const std::string& i_movementDirection) const {
if (i_movementDirection == "CCW" or i_movementDirection == "CW") {
return getJoint(BaseJoint::Rotational);
}
if (i_movementDirection == "IN" or i_movementDirection == "OUT") {
return getJoint(BaseJoint::Translational);
}
LOG_ERROR("Could not resolve movement direction: " << i_movementDirection);
}
BaseJoint::JointPointer JointController::resolveJoint(const BaseJoint::MovementType& i_movementType) const {
return getJoint(i_movementType);
}
JointController::JointPointerVector JointController::resolveJoints
(const BaseJoint::MovementType& i_type) const {
JointPointerVector vector;
for (const auto& joint : m_jointPointerVector) {
if (joint->getMovementType() == i_type) {
vector.push_back(joint);
}
}
return vector;
}
int JointController::getNumberOfJoints(const BaseJoint::MovementType& i_type) const {
int number(0);
for (const auto& joint : m_jointPointerVector) {
if (joint->getMovementType() == i_type) {
++number;
}
}
return number;
}
| true |
092e87dd645d425fb897b68af07437fa1609f92d | C++ | thousandvoices/memb | /src/huffman_encoder.cpp | UTF-8 | 3,207 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "huffman_encoder.h"
#include "bit_stream.h"
#include <queue>
namespace memb {
namespace {
struct TreeNode {
uint8_t key;
size_t count;
std::shared_ptr<TreeNode> left;
std::shared_ptr<TreeNode> right;
};
struct TreeNodeComparator {
bool operator()(std::shared_ptr<TreeNode>& lhs, std::shared_ptr<TreeNode>& rhs) const
{
return lhs->count > rhs->count;
}
};
void aggregatePrefixCodes(
const std::shared_ptr<TreeNode>& node,
size_t length,
std::vector<CodeInfo>* codeLengths)
{
if (node->left && node->right) {
aggregatePrefixCodes(
node->left,
length + 1,
codeLengths);
aggregatePrefixCodes(
node->right,
length + 1,
codeLengths);
} else {
codeLengths->push_back({node->key, length});
}
}
std::vector<CodeInfo> calculatePrefixCodeLengths(
const std::unordered_map<uint8_t, size_t>& valueCounts)
{
std::priority_queue<
std::shared_ptr<TreeNode>,
std::vector<std::shared_ptr<TreeNode>>,
TreeNodeComparator
> mergedCounts;
for (const auto& count : valueCounts) {
mergedCounts.push(std::make_shared<TreeNode>(
TreeNode{count.first, count.second, nullptr, nullptr}));
}
while (mergedCounts.size() > 1) {
auto newLeftNode = mergedCounts.top();
mergedCounts.pop();
auto newRightNode = mergedCounts.top();
mergedCounts.pop();
mergedCounts.push(std::make_shared<TreeNode>(
TreeNode{0, newLeftNode->count + newRightNode->count, newLeftNode, newRightNode}));
}
auto rootNode = mergedCounts.top();
std::vector<CodeInfo> codeLengths;
aggregatePrefixCodes(rootNode, 0, &codeLengths);
return codeLengths;
}
} // namespace
HuffmanEncoder::HuffmanEncoder(const std::unordered_map<uint8_t, size_t>& counts):
codeLengths_(calculatePrefixCodeLengths(counts))
{
std::sort(
codeLengths_.begin(),
codeLengths_.end(),
[](const CodeInfo& lhs, const CodeInfo& rhs)
{
return lhs.length < rhs.length;
});
codebook_ = createCanonicalPrefixCodes(codeLengths_);
}
std::vector<uint8_t> HuffmanEncoder::encode(const std::vector<uint8_t>& data) const
{
BitStream valuesStream;
for (const auto& value : data) {
valuesStream.push(codebook_.at(value));
}
return valuesStream.data();
}
HuffmanDecoder HuffmanEncoder::createDecoder() const
{
std::vector<uint8_t> keys;
std::vector<uint32_t> sizeOffsets;
size_t currentSize = 0;
for (size_t i = 0; i < codeLengths_.size(); ++i) {
while (currentSize < codeLengths_[i].length) {
++currentSize;
sizeOffsets.push_back(i);
}
keys.push_back(codeLengths_[i].key);
}
sizeOffsets.push_back(codeLengths_.size());
return HuffmanDecoder(keys, sizeOffsets);
}
void HuffmanEncoderBuilder::updateFrequencies(const std::vector<uint8_t>& data)
{
for (auto value : data) {
counts_[value] += 1;
}
}
HuffmanEncoder HuffmanEncoderBuilder::createEncoder() const
{
return HuffmanEncoder(counts_);
}
}
| true |
026d54fb9e09f53a622c854f5850240579df5bf4 | C++ | hyojin38/Algorithm-code | /BOJ-Code/05567_결혼식/05567_결혼식.cpp | UHC | 1,176 | 2.59375 | 3 | [] | no_license | // 5567 ȥ
// 20210112
// hyojin
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
#define endl "\n"
#define MAX 1000
int N,M,Answer;
int Map[MAX][MAX];
int check[MAX];
queue<pair<int,int>> Q;
void Solution() {
for (int i = 1; i <= N; i++) {
if (Map[1][i] == 1) {
Q.push(make_pair(i, 1));
check[i] = 1;
}
}
while (Q.empty()==false) {
int frend = Q.front().first;
int cnt = Q.front().second;
Q.pop();
Answer++;
if (cnt == 1) {
for (int i = 2; i <= N; i++) {
if (Map[frend][i] == 1) {
if (check[i] == 1) {
continue;
}
else {
Q.push(make_pair(i, cnt + 1));
check[i] = 1;
}
}
}
}
}
}
void init() {
for (int i = 0; i < MAX; i++) {
memset(Map[i], 0, sizeof(Map[i]));
}
memset(check, 0, sizeof(check));
check[1] = 1;
Answer = 0;
}
void input() {
cin >> N; //
cin >> M;
int x, y;
for (int i = 0; i < M; i++) {
cin >> x >> y;
Map[x][y] = 1;
Map[y][x] = 1;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
freopen("Text.txt", "r", stdin);
init();
input();
Solution();
cout << Answer;
return 0;
} | true |
c53a0d43b4f656dfa0b6314aee407a21671d4e3c | C++ | 7kia/OOD | /Lab4/Shapes/ShapeFactory.cpp | UTF-8 | 2,781 | 3.125 | 3 | [] | no_license | #include "stdafx.h"
#include "ShapeFactory.h"
using namespace std;
namespace
{
const std::vector<std::string> COMMANDS_NAME =
{
"Triangle" ,
"Rectangle" ,
"Circle"
};
const std::vector<int> AMOUNT_ARGUMENTS_FOR_COMMAND =
{
9 ,
7 ,
6
};
const std::string MESSAGE_INCORRECT_COMMAND = "Incorrect command.";
const std::string MESSAGE_INCORRECT_AMOUNT_ARGUMENTS = "Incorrect amount arguments! Must will be ";
}
CShapePtr CShapeFactory::CreateShape(const listArguments & arguments)
{
if (arguments[0] == COMMANDS_NAME[size_t(IdCommand::Triangle)])
{
return CreateTriangle(arguments);
}
else if (arguments[0] == COMMANDS_NAME[size_t(IdCommand::Rectangle)])
{
return CreateRectangle(arguments);
}
else if (arguments[0] == COMMANDS_NAME[size_t(IdCommand::Circle)])
{
return CreateCircle(arguments);
}
else
{
throw invalid_argument(MESSAGE_INCORRECT_COMMAND);
}
}
void CShapeFactory::CheckAmountArguments(const listArguments & arguments, IdCommand id)
{
if (arguments.size() != AMOUNT_ARGUMENTS_FOR_COMMAND[size_t(id)])
{
throw invalid_argument(MESSAGE_INCORRECT_AMOUNT_ARGUMENTS
+ to_string(AMOUNT_ARGUMENTS_FOR_COMMAND[size_t(id)]) + " now " + to_string(arguments.size()));
}
}
std::shared_ptr<CTriangle> CShapeFactory::CreateTriangle(const listArguments & arguments)
{
CheckAmountArguments(arguments, IdCommand::Triangle);
std::shared_ptr<CTriangle> addTriangle = make_shared<CTriangle>();
addTriangle->SetFirstPoint(sf::Vector2f(stof(arguments[1]), stof(arguments[2])));
addTriangle->SetSecondPoint(sf::Vector2f(stof(arguments[3]), stof(arguments[4])));
addTriangle->SetThirdPoint(sf::Vector2f(stof(arguments[5]), stof(arguments[6])));
addTriangle->SetFillColor(ToColor(arguments[7]));
addTriangle->SetOutlineColor(ToColor(arguments[8]));
return addTriangle;
}
std::shared_ptr<CRectangle> CShapeFactory::CreateRectangle(const listArguments & arguments)
{
CheckAmountArguments(arguments, IdCommand::Rectangle);
std::shared_ptr<CRectangle> addRectangle = make_shared<CRectangle>();
addRectangle->SetLeftTopPoint(sf::Vector2f(stof(arguments[1]), stof(arguments[2])));
addRectangle->SetSize(SSize(stof(arguments[3]), stof(arguments[4])));
addRectangle->SetFillColor(ToColor(arguments[5]));
addRectangle->SetOutlineColor(ToColor(arguments[6]));
return addRectangle;
}
std::shared_ptr<CCircle> CShapeFactory::CreateCircle(const listArguments & arguments)
{
CheckAmountArguments(arguments, IdCommand::Circle);
std::shared_ptr<CCircle> addCircle = make_shared<CCircle>();
addCircle->SetPosition(sf::Vector2f(stof(arguments[1]), stof(arguments[2])));
addCircle->SetRadius(stof(arguments[3]));
addCircle->SetFillColor(ToColor(arguments[4]));
addCircle->SetOutlineColor(ToColor(arguments[5]));
return addCircle;
} | true |
47b653b15e3f8990d0f193e024725546b4882e2d | C++ | Rufian55/Cpp | /A Public Library/Library.cpp | UTF-8 | 11,118 | 3.203125 | 3 | [
"MIT"
] | permissive | /**********************************************************************************************************
** Author: Chris Kearns
** Date: 12/3/2015
** Description: Library.cpp is the Library class function implementation file and as such has the
** Library.hpp specification file included. Program is geared towards a public library, but could be any
** system of checkout with monetary accountabilty for return.
**********************************************************************************************************/
#include "Library.hpp"
#include <iostream>
using std::cout;
using std::endl;
Library::Library(){
currentDate = 0;
}
/**********************************************************************************************************
** function Library::addBook()
**
** Description: Library addBook function definition that adds a Book object to the Library holdings vector.
** Parameter is a pointer to a Book object.
**********************************************************************************************************/
void Library::addBook(Book *aBook) {
holdings.push_back(aBook);
}
/**********************************************************************************************************
** function Library::addPAtron()
**
** Description: Library addPatron function definition that accepts a Patron object and adds it to the
** Library's members vector.
**********************************************************************************************************/
void Library::addPatron(Patron *aPatronID){
members.push_back(aPatronID);
}
/**********************************************************************************************************
** function Library::checkOutBook()
**
** Description: Library checkOutBook function definition that is designed as follows:
** If the specified Book is not in the Library, return "book not found".
** if the specified Patron is not in the Library, return "patron not found".
** if the specified Book is already checked out, return "book already checked out".
** if the specified Book is on hold by another Patron, return "book on hold by other patron".
** otherwise update the Book's checkedOutBy, dateCheckedOut and Location;
** also, if the Book was on hold for this Patron, update requestedBy; update the Patron's checkedOutBooks;
** and assuming everything executed, return "check out successful"
**********************************************************************************************************/
std::string Library::checkOutBook(std::string pID, std::string bID) {
if (getBook(bID) != NULL) {
if (getPatron(pID) != NULL) {
if (getBook(bID)->getLocation() == CHECKED_OUT) {
return "book already checked out";
}
else {
if (((getBook(bID)->getLocation() == ON_HOLD_SHELF)
&& (getBook(bID)->getRequestedBy() == getPatron(pID)))
|| (getBook(bID)->getLocation() == ON_SHELF)) {
getBook(bID)->setCheckedOutBy(getPatron(pID));
getBook(bID)->setDateCheckedOut(currentDate);
getBook(bID)->setLocation(CHECKED_OUT);
getBook(bID)->setRequestedBy(NULL);
getPatron(pID)->addBook(getBook(bID));
return "Check out successful";
}
else {
return "Book on hold by anoother patron";
}
}
}
else { return "Patron not found"; }
}
else { return "Book not found"; }
}
/**********************************************************************************************************
** function Library::returnBook()
**
** Description: Library returnBook function definition that:
** if the specified Book is not in the Library, returns "book not found".
** if the Book is not checked out, return "book already in library".
** updates the Patron's checkedOutBooks.
** updates the Book's location depending on whether another Patron has requested it
** updates the Book's checkedOutBy
** and finally returns "return successful"
** Note that we do not call the Books setCheckedOutDate(NULL) method as we want to calculate any fines due.
**********************************************************************************************************/
std::string Library::returnBook(std::string bID){
if (getBook(bID) != NULL) {
if (getBook(bID)->getLocation() == CHECKED_OUT) {
std::string pID = getBook(bID)->getCheckedOutBy()->getIdNum();
getPatron(pID)->removeBook(getBook(bID));
if(getBook(bID)->getRequestedBy() != NULL) {
getBook(bID)->setLocation(ON_HOLD_SHELF);
}
else {
getBook(bID)->setLocation(ON_SHELF);
}
getBook(bID)->setCheckedOutBy(NULL);
return "Return successful";
}
else { return "Book already in library"; }
}
else { return "Book not found"; }
}
/**********************************************************************************************************
** function Library::requestBook()
**
** Description: Library requestBook function definition that:
** if the specified Book is not in the Library, returns "Book not found"
** if the specified Patron is not in the Library, returns "Patron not found"
** if the specified Book is already requested, return "Book already on hold"
** updates the Book's requestedBy var
** if the Book is on the shelf, update its location to ON_HOLD_SHELF
** and finally, return "request successful"
**********************************************************************************************************/
std::string Library::requestBook(std::string pID, std::string bID){
if (getBook(bID) != NULL) {
if (getPatron(pID) != NULL) {
if (getBook(bID)->getRequestedBy() == NULL) {
getBook(bID)->setRequestedBy(getPatron(pID));
if (getBook(bID)->getLocation() == ON_SHELF) {
getBook(bID)->setLocation(ON_HOLD_SHELF);
}
return "Request successful";
}
else { return "Book already on hold"; }
}
else { return "Patron not found"; }
}
else { return "Book not found"; }
}
/**********************************************************************************************************
** function Library::payFine()
**
** Description: Library payFine function definition that checks if Patron specified by pID argument exists
** in the Library memebers vector utilizing the getPatron function, and if so, modifies the Patron's
** fineAmount variable via the amendFine function. Returns "payemnt successful" if Patron is found, "patron
** not found" otherwise.
**********************************************************************************************************/
std::string Library::payFine(std::string pID, double payment){
if (getPatron(pID) != NULL) {
getPatron(pID)->amendFine(payment);
return "Payment successful";
}
else
return "Patron not found";
}
/**********************************************************************************************************
** function Library::incrementCurrentDate()
**
** Description: Library incrementCurrentDate function definition that increments the currentDate
** variable for the Library simulator, increases each Patron's fines by 10 cents for each overdue Book
** they have checked out (using amendFine) as follows:
** If a book is checked out on day 0, then on day 1, the patron has had it for 1 day. On day 21, the
** patron has had it for 21 days, so it is still not overdue. On day 22, the book is overdue and fines
** will begin accrueing.
**********************************************************************************************************/
void Library::incrementCurrentDate() {
currentDate++;
for (int i = 0; i < members.size(); i++) {
std::string pId = members[i]->getIdNum();
std::vector<Book*> temp = getPatron(pId)->getCheckedOutBooks();
for (int i = 0; i < temp.size(); i++) {
if (currentDate - temp[i]->getDateCheckedOut() > temp[i]->getCheckOutLength()) {
getPatron(pId)->amendFine(-0.10);
}
}
}
}
/**********************************************************************************************************
** function Library::getPatron()
**
** Description: Library getPatron function definition that searchs the Library "members" vector of pointers
** to Patron objects, accesses each Patron object's IdNum field with getIdNum() and if equivalent to the
** getPatron function argument pID, returns the corresponding members vector pointer to that Patron object.
**********************************************************************************************************/
Patron * Library::getPatron(std::string pID) {
Patron* ptr = NULL;
for (int i = 0; i < members.size(); i++) {
if (members[i]->getIdNum() == pID) {
ptr = members[i];
}
}
return ptr;
}
/**********************************************************************************************************
** function Library::getBook()
**
** Description: Library getBook function definition that searchs the Library "holdings" vector of pointers
** to Book objects, accesses each Book object's IdCode field with getIdCode() and if equivalent to the
** getBook function argument bID, returns the corresponding holdings vector pointer to that Book object.
**********************************************************************************************************/
Book * Library::getBook(std::string bID){
Book* ptr = NULL;
for (int i = 0; i < holdings.size(); i++) {
if ( holdings[i]->getIdCode() == bID) {
ptr = holdings[i];
}
}
return ptr;
}
int main() {
Book b1("123", "War and Peace", "Tolstoy");
Book b2("234", "Moby Dick", "Melville");
Book b3("345", "Phantom Tollbooth", "Juster");
Patron p1("abc", "Felicity");
Patron p2("bcd", "Waldo");
Patron p3("cgk", "Coder");
Library lib;
lib.addBook(&b1);
lib.addBook(&b2);
lib.addBook(&b3);
lib.addPatron(&p1);
lib.addPatron(&p2);
lib.addPatron(&p3);
cout << "1. Book b2 location is " << b2.getLocation() << endl;
cout << "2. Book b2 checkOutBook call returns " << lib.checkOutBook("bcd", "234") << endl;
cout << "3. Book b2 location is " << b2.getLocation() << endl;
cout << "4. Book b2 request for ON_HOLD_SHELF returns " << lib.requestBook("abc", "234") << endl;
cout << "5. book b2 location after after ON_HOLD_SHELF request call returns " << b2.getLocation() << endl;
cout << "6. Book b2 request for ON_HOLD_SHELF returns " << lib.requestBook("cgk", "234") << endl;
cout << "7. book b2 location after 2nd b2 requestBook call returns " << b2.getLocation() << endl;
for (int i = 0; i < 27; i++)
lib.incrementCurrentDate();
cout << "8. Book b2 returnBook call returns " << lib.returnBook("234") << endl;
cout << "9. book b2 location after returnBook call returns " << b2.getLocation() << endl;
cout << "10. Book b2 checkout_2 call returns " << lib.checkOutBook("bcd", "234") << endl;
cout << "11. Book b2 checkout_2 call returns " << lib.checkOutBook("abc", "234") << endl;
lib.checkOutBook("abc", "345");
for (int i = 0; i < 24; i++)
lib.incrementCurrentDate();
lib.payFine("bcd", 0.40);
lib.payFine("abc", 0.00);
double p1Fine = p1.getFineAmount();
double p2Fine = p2.getFineAmount();
cout << "Patron p1 fine is " << p1Fine << endl;
cout << "Patron p2 fine is " << p2Fine << endl;
return 0;
}
| true |
1007dc00537428cf2ff4543220d3b2d4507b789a | C++ | kl4kennylee81/Canon | /source/InputController.cpp | UTF-8 | 1,958 | 2.59375 | 3 | [] | no_license | //
// InputController.cpp
// Canon
//
// Created by Kenneth Lee on 3/29/17.
// Copyright © 2017 Game Design Initiative at Cornell. All rights reserved.
//
#include <stdio.h>
#include "InputController.hpp"
using namespace cugl;
bool InputController::_touch;
bool InputController::_isPressed;
Vec2 InputController::_curPos;
bool InputController::_wasPressed;
Vec2 InputController::_prevPos;
void InputController::setTouch(bool touch) {
InputController::_touch = touch;
}
/**
* Returns the screen coordinates of the input. If the input is a
* touch screen, return the screen coordinates of the first touch.
*/
cugl::Vec2 InputController::getInputVector() {
if (_touch) {
return _curPos;
}
else {
return Input::get<Mouse>()->pointerPosition();
}
}
cugl::Vec2 InputController::getPrevVector(){
return _prevPos;
}
bool InputController::getIsPressed() {
return _isPressed;
}
bool InputController::getIsPressedUp(){
return _wasPressed && !_isPressed;
}
void InputController::update(){
_wasPressed = _isPressed;
if (_touch) {
auto set = Input::get<Touchscreen>()->touchSet();
_isPressed = set.size() > 0;
if (_isPressed){
_prevPos = _curPos;
_curPos = Input::get<Touchscreen>()->touchPosition(set.at(0));
}
}
else {
_isPressed = Input::get<Mouse>()->buttonDown().hasLeft();
if (_isPressed){
_prevPos = _curPos;
_curPos = Input::get<Mouse>()->pointerPosition();
}
}
}
bool InputController::getDoubleTouch(){
{
if (_touch) {
return Input::get<Touchscreen>()->touchSet().size() > 1;
}
else {
return Input::get<Mouse>()->buttonDown().hasLeft() &&
Input::get<Mouse>()->buttonDown().hasRight();
}
}
}
std::vector<cugl::KeyCode> InputController::getPressedKeys() {
return Input::get<Keyboard>()->keySet();
}
| true |
293abdb7ec1ffd9b4e5c61d7ca5a883e3cf36170 | C++ | TimSnedden138/BinaryFilesFin | /BinaryFiles/SaveData.cpp | UTF-8 | 1,052 | 2.859375 | 3 | [] | no_license | //#include<iostream>
//#include<fstream>
//#include<string>
//using namespace std;
//int main() {
// string saveFile;
// fstream sFile;
// string SaveName;
// string Output;
// string deathCounter;
// string charLevel;
// string timePlayed;
// cout << "What would you like to call your save file"<<endl;
// cout << "Name Character Level Deaths Time in Seconds please" << endl;
// cin >> saveFile;
// cin >> SaveName;
// cin >> charLevel;
// cin >> deathCounter;
// cin >> timePlayed;
// sFile.open(saveFile.c_str(), ios::out | ios::binary);
// sFile.clear();
// sFile.seekp(0, std::ios_base::end);
// sFile << "Name: "<<SaveName << endl;
// sFile << "Character Level: "<<charLevel << endl;
// sFile << "Deaths: "<<deathCounter << endl;
// sFile << "Time in Seconds: "<<timePlayed << endl;
// sFile.flush();
// sFile.close();
// cout<<"Name: "<<SaveName << endl;
// cout << "Character Level: " << charLevel << endl;
// cout << "Deaths: " << deathCounter << endl;
// cout << "Time in Seconds: " << timePlayed << endl;
// system("pause");
// return 0;
//} | true |
4a068b5cdc9c4cc99ae44935acb65df1fd1f5afa | C++ | raulhsant/algorithms | /C++/tests/problems/0152_sequential_digits_test.cpp | UTF-8 | 498 | 3.09375 | 3 | [
"MIT"
] | permissive | #include "../../problems/0152_sequential_digits.hpp"
#include <bits/stdc++.h>
#include "../../frameworks/catch.hpp"
#include "../../frameworks/asserts.hpp"
using namespace std;
TEST_CASE( "Sequential Digits" ) {
Solution sol;
vector<int> result1 = {123,234};
REQUIRE( areVectorsEqual(sol.sequentialDigits(100,300),result1) );
vector<int> result2 = {1234,2345,3456,4567,5678,6789,12345};
REQUIRE( areVectorsEqual(sol.sequentialDigits(1000,13000),result2) );
} | true |
42dca48c1f113c07289e51e66e9a361e386439fd | C++ | c-shewchuk/454-design-project | /Pong/Puck.cpp | UTF-8 | 739 | 2.890625 | 3 | [] | no_license | //
// Created by Alex on 2018-09-20.
//
#include "Puck.h"
Puck::Puck() {
xpos = xpos0;
ypos = ypos0;
srand (time(NULL));
xspeed = rand()% 3 + 1;
srand (time(NULL)*time(NULL));
yspeed = rand()% 3 + 1;
}
Puck::Puck(double x, double y, double vx, double vy){
xpos = x;
ypos = y;
xspeed = vx;
yspeed = vy;
}
Puck::~Puck() {}
void Puck::slide(){
xpos = xpos + xspeed;
ypos = ypos + yspeed;
}
void Puck::edges() {
if (ypos >= height || ypos <= 0)
yspeed = -yspeed;
if (xpos >= width || xpos <= 0) {
xpos = 0;
ypos = 0;
srand (time(NULL));
xspeed = rand()% 3 + 1;
srand (time(NULL)*time(NULL));
yspeed = rand()% 3 + 1;
}
} | true |
709bed7e44cef15e2b4c935d678458e264428def | C++ | JustinMorritt/Indee-Games | /DopeWarz/Market.h | UTF-8 | 663 | 2.578125 | 3 | [] | no_license | #ifndef MARKET_H__
#define MARKET_H__
#include <map>
#include <vector>
#include <iostream>
#include "randgen.h"
using namespace std;
class Market
{
public:
Market();
~Market();
void BuildMarket();
void SetDrugMap(vector<pair<string, unsigned>> map);
void DisplayMarket();
unsigned GetPrice(int choice) const;
bool MarketCompare(string drug);
unsigned MarketPrice(string drug);
string GetName(int choice) const;
vector<pair<string, unsigned>>& GetMap();
void SetMarketShown(bool shown);
bool GetMarketShown();
private:
//DRUG NAME PRICE
vector<pair<string, unsigned>> m_Drugs;
bool MarketShown;
};
#endif
| true |
5f6fe518feaea25ae90a0126b20022a89ae3f5d4 | C++ | 5cript/star-tape | /src/star-tape/tape_header.cpp | UTF-8 | 18,153 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <star-tape/tape_core.hpp>
#include <star-tape/tape_header.hpp>
#include <star-tape/tape_utility.hpp>
#include <boost/filesystem.hpp>
#include <chrono>
namespace fs = boost::filesystem;
namespace StarTape
{
//#####################################################################################################################
void preprocessPath(std::string& path)
{
std::replace(std::begin(path), std::end(path), '\\', '/');
path.erase(std::unique(std::begin(path), std::end(path), [](char lhs, char rhs) {return lhs == '/' && rhs == '/';}), std::end(path));
}
//---------------------------------------------------------------------------------------------------------------------
template <std::size_t Size>
void assign(std::array <char, Size>& arr, std::string const& str)
{
for (unsigned i = 0u; i != std::min(Size, str.length()); ++i)
{
arr[i] = str[i];
}
if (str.length() < Size)
for (unsigned i = str.length(); i != Size; ++i)
{
arr[i] = '\0';
}
}
//---------------------------------------------------------------------------------------------------------------------
template <std::size_t Size>
void assignOctal(std::array <char, Size>& arr, uint64_t num)
{
assign <Size>(arr, makeOctal <Size-1> (num));
}
//---------------------------------------------------------------------------------------------------------------------
template <std::size_t Size>
void clear(std::array <char, Size>& arr)
{
std::fill(std::begin(arr), std::end(arr), '\0');
}
//#####################################################################################################################
#define HEADER_ASSIGN(FIELD, STRING) \
assign <StarHeaderEntrySizes::FIELD>(header.FIELD, STRING)
#define HEADER_ASSIGN_OCTAL(FIELD, STRING) \
assignOctal <StarHeaderEntrySizes::FIELD> (header.FIELD, STRING)
#define HEADER_CLEAR(FIELD) \
clear <StarHeaderEntrySizes::FIELD> (header.FIELD)
//---------------------------------------------------------------------------------------------------------------------
void calculateChecksum(StarHeader& header)
{
uint32_t checksum = 0u;
std::array <char, 7> sum;
#define CHKSUM(FIELD) \
for (auto const& i : header.FIELD) \
checksum += static_cast <unsigned char> (i);
CHKSUM(fileName)
CHKSUM(fileMode)
CHKSUM(uid)
CHKSUM(gid)
CHKSUM(size)
CHKSUM(mTime)
CHKSUM(linkName)
CHKSUM(magic)
CHKSUM(version)
CHKSUM(uName)
CHKSUM(gName)
CHKSUM(devMajor)
CHKSUM(devMinor)
CHKSUM(prefix)
checksum += 8u * 32u;
checksum += static_cast <unsigned char> (header.typeflag);
assignOctal <7> (sum, checksum);
for (int i = 0; i != 7; ++i)
header.chksum[i] = sum[i];
header.chksum[7] = ' ';
#undef CHKSUM
}
//---------------------------------------------------------------------------------------------------------------------
fs::path splitPath(StarHeader& header, std::string path, bool isDir = false)
{
preprocessPath(path);
fs::path p{path};
if (path.length() > 255)
throw std::invalid_argument("path size is too large (>255)");
// path is too long, try to split:
if (path.length() > 100)
{
// 2. rule (might be false): other than that, put as much into the prefix as possible
// 3. rule: directories end with slash, but not in the prefix, because that is implicit.
// ?. rule (likely false): files that are in subdirs have a dir+slash in fileName, if possible.
// first count if its actually possible to split based on amount of dirs.
auto SlashCount = std::count_if (std::begin(path), std::end(path), [](char c) {return c == '/';});
if (SlashCount < 2)
throw std::invalid_argument("could not split - path is too large");
fs::path fileNamePart = p.filename();
fs::path prefixPart = p.parent_path();
while (fileNamePart.string().length() + (isDir?1:0) > 100 ||
prefixPart.string().length() > 155)
{
auto previousPrefixPart = prefixPart;
fileNamePart = prefixPart.filename() / fileNamePart;
prefixPart = prefixPart.parent_path();
if (prefixPart == previousPrefixPart)
throw std::invalid_argument("could not find a split to save the path");
}
std::string fn = fileNamePart.string();
if (isDir)
fn.push_back('/');
HEADER_ASSIGN(fileName, fn);
HEADER_ASSIGN(prefix, prefixPart.string());
}
else
{
std::string fn = p.string();
if (isDir)
fn.push_back('/');
HEADER_ASSIGN(fileName, fn);
HEADER_CLEAR(prefix);
}
return p;
}
//---------------------------------------------------------------------------------------------------------------------
std::pair <StarHeader, fs::path> createHeaderCommon(std::string path, bool isDir = false)
{
StarHeader header;
/////////////////////////////////////////////////////////////////////////////////////////////
// PATH
/////////////////////////////////////////////////////////////////////////////////////////////
auto p = splitPath(header, path, isDir);
/////////////////////////////////////////////////////////////////////////////////////////////
// MODE
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_CLEAR(fileMode);
/////////////////////////////////////////////////////////////////////////////////////////////
// UID
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_CLEAR(uid);
/////////////////////////////////////////////////////////////////////////////////////////////
// GID
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_CLEAR(gid);
/////////////////////////////////////////////////////////////////////////////////////////////
// LINK NAME
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_CLEAR(linkName);
/////////////////////////////////////////////////////////////////////////////////////////////
// MAGIC
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN(magic, "ustar");
/////////////////////////////////////////////////////////////////////////////////////////////
// VERSION
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN(version, "00");
/////////////////////////////////////////////////////////////////////////////////////////////
// USER NAME
/////////////////////////////////////////////////////////////////////////////////////////////
// I cannot be bothered with a proper solution here. try for env. variables, and clear if not available.
char * user_name = getenv("USER");
if (!user_name)
user_name = getenv("USERNAME");
if (user_name)
HEADER_ASSIGN(uName, user_name);
else
HEADER_CLEAR(uName);
/////////////////////////////////////////////////////////////////////////////////////////////
// GROUP NAME
/////////////////////////////////////////////////////////////////////////////////////////////
// not portable -> clear
HEADER_CLEAR(gName);
/////////////////////////////////////////////////////////////////////////////////////////////
// DEV MAJOR
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN_OCTAL(devMajor, 0);
/////////////////////////////////////////////////////////////////////////////////////////////
// DEV MINOR
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN_OCTAL(devMinor, 0);
/////////////////////////////////////////////////////////////////////////////////////////////
// FILE TYPE
/////////////////////////////////////////////////////////////////////////////////////////////
header.typeflag = '0';
return {header, p};
}
//---------------------------------------------------------------------------------------------------------------------
StarHeader createHeaderFromString(std::string const& path, std::string const& dataString)
{
auto header = createHeader(path, dataString.length(), false);
/////////////////////////////////////////////////////////////////////////////////////////////
// MODE
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN_OCTAL(fileMode,
fs::owner_read | fs::owner_write |
fs::group_read | fs::group_write |
fs::others_read | fs::others_write
);
/////////////////////////////////////////////////////////////////////////////////////////////
// CHECKSUM
/////////////////////////////////////////////////////////////////////////////////////////////
calculateChecksum(header);
return header;
}
//---------------------------------------------------------------------------------------------------------------------
StarHeader createHeader(std::string const& path, std::size_t size, bool checksum = true)
{
StarHeader header = createHeaderCommon(path).first;
/////////////////////////////////////////////////////////////////////////////////////////////
// MODIFY TIME
/////////////////////////////////////////////////////////////////////////////////////////////
auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
HEADER_ASSIGN_OCTAL(mTime, time);
/////////////////////////////////////////////////////////////////////////////////////////////
// SIZE
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN_OCTAL(size, size);
/////////////////////////////////////////////////////////////////////////////////////////////
// CHECKSUM
/////////////////////////////////////////////////////////////////////////////////////////////
if (checksum)
calculateChecksum(header);
return header;
}
//---------------------------------------------------------------------------------------------------------------------
StarHeader createHeaderFromDiskNode(std::string path, std::string pathOverwrite)
{
preprocessPath(path);
fs::path p{path};
if (!fs::exists(p))
throw std::invalid_argument("file does not exist");
auto isDir = fs::is_directory(p);
auto isRegFile = fs::is_regular_file(p);
auto isSymLink = fs::is_symlink(p);
if (!isDir && !isRegFile)
throw std::invalid_argument("disk node is neither a regular file nor a directory");
if (pathOverwrite.empty())
pathOverwrite = path;
else
preprocessPath(pathOverwrite);
std::pair <StarHeader, fs::path> res = createHeaderCommon(pathOverwrite, isDir);
auto header = res.first;
/////////////////////////////////////////////////////////////////////////////////////////////
// MODE
/////////////////////////////////////////////////////////////////////////////////////////////
auto status = fs::status(p);
HEADER_ASSIGN_OCTAL(fileMode, status.permissions());
/////////////////////////////////////////////////////////////////////////////////////////////
// SIZE
/////////////////////////////////////////////////////////////////////////////////////////////
if (isDir)
HEADER_CLEAR(size);
else
HEADER_ASSIGN_OCTAL(size, fs::file_size(p));
/////////////////////////////////////////////////////////////////////////////////////////////
// MODIFY TIME
/////////////////////////////////////////////////////////////////////////////////////////////
auto time = fs::last_write_time(p);
HEADER_ASSIGN_OCTAL(mTime, time);
/////////////////////////////////////////////////////////////////////////////////////////////
// FILE TYPE
/////////////////////////////////////////////////////////////////////////////////////////////
if (isRegFile)
header.typeflag = '0';
else if (isSymLink)
header.typeflag = '2';
else
header.typeflag = '5';
/////////////////////////////////////////////////////////////////////////////////////////////
// CHECKSUM
/////////////////////////////////////////////////////////////////////////////////////////////
calculateChecksum(header);
return header;
}
//---------------------------------------------------------------------------------------------------------------------
StarHeader createLinkHeader(std::string originalFile, std::string linkName, bool checksum)
{
preprocessPath(originalFile);
preprocessPath(linkName);
if (linkName.size() > 100)
throw std::runtime_error("link is too long");
StarHeader header = createHeaderCommon(linkName, false).first;
/////////////////////////////////////////////////////////////////////////////////////////////
// MODIFY TIME
/////////////////////////////////////////////////////////////////////////////////////////////
auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
HEADER_ASSIGN_OCTAL(mTime, time);
/////////////////////////////////////////////////////////////////////////////////////////////
// SIZE
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN_OCTAL(size, 0);
/////////////////////////////////////////////////////////////////////////////////////////////
// LINK
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN(linkName, originalFile);
/////////////////////////////////////////////////////////////////////////////////////////////
// FILEMODE & TYPE
/////////////////////////////////////////////////////////////////////////////////////////////
HEADER_ASSIGN_OCTAL(fileMode,
fs::owner_read | fs::owner_write | fs::owner_exe |
fs::group_read | fs::group_write | fs::group_exe |
fs::others_read | fs::others_write | fs::others_exe
);
header.typeflag = '2';
/////////////////////////////////////////////////////////////////////////////////////////////
// CHECKSUM
/////////////////////////////////////////////////////////////////////////////////////////////
if (checksum)
calculateChecksum(header);
return header;
}
//---------------------------------------------------------------------------------------------------------------------
#undef HEADER_ASSIGN
#undef HEADER_ASSIGN_OCTAL
#undef HEADER_CLEAR
//---------------------------------------------------------------------------------------------------------------------
std::string headerToString(StarHeader const& head)
{
std::string res;
int offset = 0;
res.resize(Constants::ChunkSize);
#define WRITE(FIELD) \
for (int i = 0; i != head.FIELD.size(); ++i) \
{ \
res[i + offset] = head.FIELD[i]; \
} \
offset += head.FIELD.size();
//read <head.NAME.size()>(reader, head.NAME)
WRITE(fileName)
WRITE(fileMode)
WRITE(uid)
WRITE(gid)
WRITE(size)
WRITE(mTime)
WRITE(chksum)
res[offset] = head.typeflag; ++offset;
WRITE(linkName)
WRITE(magic)
WRITE(version)
WRITE(uName)
WRITE(gName)
WRITE(devMajor)
WRITE(devMinor)
WRITE(prefix)
#undef WRITE
return res;
}
//---------------------------------------------------------------------------------------------------------------------
std::string concatFileName(StarHeader const& head)
{
if (head.prefix[0] == '\0')
return {std::begin(head.fileName), std::end(head.fileName)};
else
{
std::string fname;
for (int i = 0; i != head.prefix.size() && head.prefix[i] != '\0'; ++i)
fname.push_back(head.prefix[i]);
return fname + "/" + std::string{std::begin(head.fileName), std::end(head.fileName)};
}
}
//#####################################################################################################################
}
| true |
21c28d468eacfb53d1b037a752725146b02d12f2 | C++ | duzhanyuan/BeeeOnIOTServer | /ada_server/sqlCommands.h | UTF-8 | 7,665 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file sqlCommands.h
*
* @brief definition of namespace SQLQueries
*
* @author Matus Blaho
* @version 1.0
*/
#ifndef SQLCOMMANDS_H_
#define SQLCOMMANDS_H_
#include <string>
/** @namespace SQLQueries
* @brief groups SQL queries to database used by application
*/
namespace SQLQueries
{
using namespace std;
/**Q to insert adapter uses ( :AdapterID, :FMver, ':socket')*/
const string InsertGateway = "insert into gateway (gateway_id,version,socket) values (:GATEWAY_ID,:FM_VERSION,:SOCKET);"; //"insert into adapters (adapter_id,version,socket) values ( "+ std::to_string(message->adapterINTid)+ ", " + std::to_string(message->fm_version) + ", '" + std::to_string(message->socket) + "');" ;
/** Q to update adapter uses ( :AdapterID, :FMver)*/
const string UpdateGateway = "update gateway set version = :FM_VERSION where gateway_id = :GATEWAY_ID;"; //"update adapters set version=" + std::to_string(message->fm_version) + ", socket=" + std::to_string(message->socket) + " where adapter_id=" + std::to_string(message->adapterINTid) + ";" ;
/** Q to update socket of adapter uses ( :AdapterID, :FMver, :socket)*/
const string UpdateGatewaySocket = "update gateway set version = :FM_VERSION, socket = :SOCKET where gateway_id = :GATEWAY_ID;"; //"update adapters set version=" + std::to_string(message->fm_version) + ", socket=" + std::to_string(message->socket) + " where adapter_id=" + std::to_string(message->adapterINTid) + ";" ;
/** Q to select socket of adapter uses (:ID) */
const string SelectSocket = "SELECT socket FROM gateway where gateway_id=:ID;";
/**Q to insert facility uses ( ':deviceID',:battery, :signal, :adapterID, :timestamp , :timestamp)*/
const string InsertDevice = "insert into device (device_type,device_euid,refresh,gateway_id,involved,measured_at) values (:DEVICE_TYPE,:DEVICE_EUID,15,:GATEWAY_ID,:TIMESTAMP,:TIMESTAMP);"; /*"insert into facilities (mac,refresh,battery,quality,fk_adapter_id,involved,timestamp) values
( '" + message->DeviceIDstr + "', 5 ," + std::to_string(message->battery)+ ", " + std::to_string(message->signal_strength) + ", " +std::to_string(message->adapterINTid)+ ", " +std::to_string(message->timestamp) + ", " + std::to_string(message->timestamp) +" );" ;*/
/** Q to update facility uses ( :battery, :quality, :timestamp, :mac)*/
const string UpdateDevice = "update device set measured_at = :MEASURED_AT where (device_euid = :DEVICE_EUID) AND gateway_id = :GATEWAY_ID;"; //"update facilities set battery=" + std::to_string(message->battery) + ",quality=" + std::to_string(message->signal_strength) + ",timestamp=" + std::to_string(message->timestamp) +" where (mac='" + message->DeviceIDstr + "');" ;
/** Q to Delete facility uses (:ID) */
const string DeleteDevice = "Delete from device where device_euid=:DEVICE_EUID AND gateway_id=:GATEWAY_ID;";
/** Q to select wake up time of record uses ( :record)*/
const string SelectTime = "select refresh from device where device_euid=:record AND gateway_id=:GATEWAY_ID;"; //"select refresh from facilities where mac = '" + record + "';";
const string SelectDeviceParametersXml = "select xmlagg( xmlelement(name parameter, xmlattributes(parameter_key as key, parameter_value as value))) from device_parameter where device_euid=:record AND gateway_id=:GATEWAY_ID;";
/**Q to insert device uses ( ':devID', :type, ':value')*/
const string InsertModule = "insert into module (device_euid,module_id,measured_value, gateway_id) values (:DEVICE_EUID,:MODULE_ID,:MEASURED_VALUE, :GATEWAY_ID);"; //"insert into devices (fk_facilities_mac,type,value) values ( '" + message->DeviceIDstr + "', " + std::to_string(message->values[i].intType) + ", '" + val + "');" ;
/** Q to update device uses ( :value, :FMver, ':mac', :type)*/
const string UpdateModule = "update module set measured_value = :MEASURED_VALUE, status = 'available' where (device_euid = :DEVICE_EUID AND module_id = :MODULE_ID AND gateway_id=:GATEWAY_ID);"; //"update devices set value=" + val +" where (fk_facilities_mac='" + message->DeviceIDstr + "' AND type =" + std::to_string(message->values[i].intType) +");" ;
/** Q to update device uses ( :status, :FMver, ':mac', :type)*/
const string UpdateModuleWithStatus = "update module set status = :STATUS where (device_euid = :DEVICE_EUID AND module_id = :MODULE_ID AND gateway_id=:GATEWAY_ID);";
/** Q to insert history row uses ( ':deviceID', :timeStamp , :type, :value)*/
const string InsertLog = "insert into log (device_euid,measured_at,module_id,measured_value, gateway_id) values (:DEVICE_EUID,:MEASURED_AT,:MODULE_ID,:MEASURED_VALUE, :GATEWAY_ID);"; //"insert into logs (fk_facilities_mac,timestamp,fk_devices_type,value) values ( '"+ message->DeviceIDstr + "', " + std::to_string(message->timestamp) + " , " + std::to_string(message->values[i].intType) + ", " + val + " );" ;
/** Q to select count of record uses ( :coulmnName :tableName :coumnName :record)*/
const string SelectCount = "select count(*) from :tableName where :columnName = :record;"; //"select count(*)" + columnName + " from " + tableName + " where " + columnName + " = "+ record + ";";
/** Q to select timestamp of last value for device uses (:DEVICE_EUID)*/
const string SelectTimestamp = "select measured_at from device where (device_euid = :DEVICE_EUID);";
/** Q to select all devices for adapter uses (:GATEWAY_ID, :DEVICE_INITIALIZED)*/
const string SelectAllDevices = "select device_euid, device_type from device where (gateway_id = :GATEWAY_ID) and (init = :DEVICE_INITIALIZED);";
/** Q to select all devices for adapter uses (:GATEWAY_ID, :DEVICE_INITIALIZED)*/
const string SelectAllDevicesCount = "select count(*) from device where (gateway_id = :GATEWAY_ID) and (init = :DEVICE_INITIALIZED);";
/** Q to select last value of the module from sensor uses (:GATEAY_ID, :DEVICE_EUID, :MODULE_ID)*/
const string SelectLastModuleValue = "select measured_value from module where (gateway_id = :GATEWAY_ID) and (device_euid = :DEVICE_EUID) and (module_id = :MODULE_ID);";
/** Q to select last value of the module from sensor uses (:GATEAY_ID, :DEVICE_EUID, :MODULE_ID)*/
const string SelectLastModuleValueCount = "select count(*) from module where (gateway_id = :GATEWAY_ID) and (device_euid = :DEVICE_EUID) and (module_id = :MODULE_ID);";
/** Q to select user's label for device uses (:GATEWAY_ID, :DEVICE_EUID)*/
const string SelectUserLabelForDeviceID = "select device_name from device where (gateway_id = :GATEWAY_ID) and (device_euid = :DEVICE_EUID);";
/** Q to select user's label for device uses (:GATEWAY_ID, :DEVICE_EUID)*/
const string SelectUserLabelForDeviceIDCount = "select count(*) from device where (gateway_id = :GATEWAY_ID) and (device_euid = :DEVICE_EUID);";
/** Q to select user's room for device uses (:GATEWAT_ID, :DEVICE_EUID)*/
const string SelectUserRoomForDevice = "select location.location_name from device natural join location join gateway on location.gateway_id = gateway.gateway_id where device.gateway_id = :GATEWAY_ID and device.device_euid = :DEVICE_EUID;";
/** Q to select user's room for device uses (:GATEWAY_ID, :DEVICE_EUID)*/
const string SelectUserRoomForDeviceCount = "select count(*) from device natural join location join gateway on location.gateway_id = gateway.gateway_id where device.gateway_id = :GATEWAY_ID and device.device_euid = :DEVICE_EUID;";
/** Q to update gateway status uses (:STATUS, :GATEWAY_ID)*/
const string UpdateGatewayStatus = "update gateway set status = :STATUS where gateway_id = :GATEWAY_ID;";
/**Q to update all gateways status uses(:STATUS)*/
const string UpdateAllGatewayStatus = "update gateway set status = :STATUS";
}
#endif /* SQLCOMMANDS_H_ */
| true |
3cd9c50e5acf61eed3f828ab47d1572703a8cc5a | C++ | thecodingwizard/competitive-programming | /POI/POI15-Three.cpp | UTF-8 | 8,018 | 2.6875 | 3 | [] | no_license | /*
* Same as editorial
*
* Make the following observation: The optimal subset is [i...j] where either:
* Case 1. 0 <= i < 3, i <= j < n
* Case 2. i <= j < n, j >= n-3
*
* Editorial has proof, here's how to set the proof up: Assume the contrapositive, that the optimal subset [i...j]
* doesn't meet one of the two cases above. That means that there are at least three blocks on the left and right of
* the optimal subset, for the proof let's assume three on either side.
*
* Do casework for proof.
* Case #1: [i...j] is all one color. Then we can easily extend the optimal subset by taking one more block
* on either the left or right side of the optimal subset. But what if i=j? Then the max length is 1 and we can
* take [0...0] instead of [i...j]
*
* Case #2: [i...j] is two colors. This case can be merged with Case #3.
*
* Case #3: [i...j] contains three colors. Denote |X| = number of blocks of color X in optimal subset. WLOG,
* assume |B| < |S| < |C|. The proof for this is much longer (see editorial), but basically the idea is to
* make observations as to what the immediate left/right cube colors can be, and do more casework from there.
*/
//#pragma GCC optimize ("O3")
//#pragma GCC target ("sse4")
#include <bits/stdc++.h>
#include <utility>
using namespace std;
template<class T> using min_heap = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i, a, b) for (int i=a; i<(b); i++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define F0R1(i, a) for (int i=1; i<=(a); i++)
#define FORd(i, a, b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--)
#define trav(a, x) for (auto& a : x)
#define MIN(a, b) a = min(a, b)
#define MAX(a, b) a = max(a, b)
#define INF 1000000010
#define LL_INF 4500000000000000000LL
#define LSOne(S) (S & (-S))
#define EPS 1e-9
#define pA first
#define pB second
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define PI acos(-1.0)
// #define MOD (int)(2e+9+11)
#define MOD (int)(1e+9+7)
#define SET(vec, val, size) for (int i = 0; i < size; i++) vec[i] = val;
#define SET2D(arr, val, dim1, dim2) F0R(i, dim1) F0R(j, dim2) arr[i][j] = val;
#define SET3D(arr, val, dim1, dim2, dim3) F0R(i, dim1) F0R(j, dim2) F0R(k, dim3) arr[i][j][k] = val;
#define SET4D(arr, val, dim1, dim2, dim3, dim4) F0R(i, dim1) F0R(j, dim2) F0R(k, dim3) F0R(l, dim4) arr[i][j][k][l] = val;
#define lb lower_bound
#define ub upper_bound
#define sz(x) (int)x.size()
#define beg(x) x.begin()
#define en(x) x.end()
#define all(x) beg(x), en(x)
#define resz resize
#define SORT(vec) sort(all(vec))
#define RSORT(vec) sort(vec.rbegin(),vec.rend())
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<ll> vl;
// @formatter:off
// Source: Benq (https://github.com/bqi343/USACO) [Modified]
namespace input {
template<class T> void re(complex<T>& x);
template<class T1, class T2> void re(pair<T1,T2>& p);
template<class T> void re(vector<T>& a);
template<class T, size_t SZ> void re(array<T,SZ>& a);
template<class T> void reA(T A[], int sz);
template<class T> void re(T& x) { cin >> x; }
void re(double& x) { string t; re(t); x = stod(t); }
void re(ld& x) { string t; re(t); x = stold(t); }
template<class Arg, class... Args> void re(Arg& first, Args&... rest) {
re(first); re(rest...);
}
template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.pA,p.pB); }
template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
template<class T> void reA(T A[], int sz) { F0R(i, sz) re(A[i]); }
void setupIO(const string &PROB = "") {
ios::sync_with_stdio(false);
cin.tie(nullptr);
if (PROB.length() != 0) {
ifstream infile(PROB + ".in");
if (infile.good()) {
freopen((PROB + ".in").c_str(), "r", stdin);
freopen((PROB + ".out").c_str(), "w", stdout);
}
}
}
}
using namespace input;
namespace output {
template<class T1, class T2> void prD(const pair<T1,T2>& x);
template<class T, size_t SZ> void prD(const array<T,SZ>& x);
template<class T> void prD(const vector<T>& x);
template<class T> void prD(const set<T>& x);
template<class T1, class T2> void prD(const map<T1,T2>& x);
template<class T1, class T2> void pr(const pair<T1,T2>& x);
template<class T, size_t SZ> void pr(const array<T,SZ>& x);
template<class T> void pr(const vector<T>& x);
template<class T> void pr(const set<T>& x);
template<class T1, class T2> void pr(const map<T1,T2>& x);
template<class T> void prD(const T& x) { cout << x; }
template<class Arg, class... Args> void prD(const Arg& first, const Args&... rest) {
prD(first); prD(rest...);
}
template<class T1, class T2> void prD(const pair<T1,T2>& x) {
prD("{",x.pA,", ",x.pB,"}");
}
template<class T> void prDContain(const T& x) {
prD("{");
bool fst = 1; for (const auto& a: x) prD(!fst?", ":"",a), fst = 0; // const needed for vector<bool>
prD("}");
}
template<class T, size_t SZ> void prD(const array<T,SZ>& x) { prDContain(x); }
template<class T> void prD(const vector<T>& x) { prDContain(x); }
template<class T> void prD(const set<T>& x) { prDContain(x); }
template<class T1, class T2> void prD(const map<T1,T2>& x) { prDContain(x); }
void psD() { prD("\n"); }
template<class Arg> void psD(const Arg& first) {
prD(first); psD(); // no space at end of line
}
template<class Arg, class... Args> void psD(const Arg& first, const Args&... rest) {
prD(first," "); psD(rest...); // print w/ spaces
}
template<class T> void pr(const T& x) { cout << x; }
template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) {
pr(first); pr(rest...);
}
template<class T1, class T2> void pr(const pair<T1,T2>& x) {
pr(x.pA, " ", x.pB);
}
template<class T> void prContain(const T& x) {
bool fst = 1; for (const auto& a: x) pr(!fst?" ":"",a), fst = 0; // const needed for vector<bool>
}
template<class T, size_t SZ> void pr(const array<T,SZ>& x) { prContain(x); }
template<class T> void pr(const vector<T>& x) { prContain(x); }
template<class T> void pr(const set<T>& x) { prContain(x); }
template<class T1, class T2> void pr(const map<T1,T2>& x) { prContain(x); }
void ps() { pr("\n"); }
template<class Arg> void ps(const Arg& first) {
pr(first); ps(); // no space at end of line
}
template<class Arg, class... Args> void ps(const Arg& first, const Args&... rest) {
pr(first," "); ps(rest...); // print w/ spaces
}
}
using namespace output;
// @formatter:on
/* ============================ */
int A[1000000], B[1000000], C[1000000];
bool legal(int end, int start) {
if (end < 0) return false;
int c = C[end] - (start >= 0 ? C[start] : 0);
int b = B[end] - (start >= 0 ? B[start] : 0);
int a = A[end] - (start >= 0 ? A[start] : 0);
return (c == 0 || b == 0 || c != b) && (b == 0 || a == 0 || b != a) && (c == 0 || a == 0 || c != a);
}
int main() {
setupIO();
int n; re(n);
SET(A, 0, n); SET(B, 0, n); SET(C, 0, n);
F0R(i, n) {
char c; re(c);
if (c == 'B') A[i]++;
else if (c == 'S') B[i]++;
else C[i]++;
}
FOR(i, 1, n) {
A[i] += A[i-1];
B[i] += B[i-1];
C[i] += C[i-1];
}
int best = 1;
FOR(start, 0, 3) {
FOR(end, start, n) {
if (legal(end, start - 1)) MAX(best, end - start + 1);
}
}
FOR(end, n-3, n) {
F0R(start, end) {
if (legal(end, start - 1)) MAX(best, end - start + 1);
}
}
ps(best);
} | true |
aa71b801f723a82d6bcf5b0c22fe8ac581854533 | C++ | HydrazineClient/Ghost-1-16-Old | /Horion/Menu/ClickGui.h | UTF-8 | 1,937 | 2.578125 | 3 | [] | no_license | #pragma once
#include <map>
#include <vector>
#include "../../Memory/GameData.h"
#include "../DrawUtils.h"
#include "../GuiUtils.h"
#include "../Module/ModuleManager.h"
struct ClickModule {
bool isExtended = false;
};
struct ClickWindow {
ClickWindow() {
pos.x = 0;
pos.y = 0;
size.x = 30;
size.y = 30;
}
vec2_t pos;
vec2_t size;
bool isExtended = true;
bool isInAnimation = false;
float animation = 0;
const char* name;
std::map<unsigned int, std::shared_ptr<ClickModule>> moduleMap;
int yOffset = 0;
};
class ClickGui {
private:
inline static std::shared_ptr<ClickWindow> getWindow(const char* id);
inline static std::shared_ptr<ClickModule> getClickModule(std::shared_ptr<ClickWindow> window, const char* id);
static void renderLabel(const char* text);
static void renderTooltip(std::string* text);
static void renderCategory(Category category);
inline static void getModuleListByCategory(Category category, std::vector<std::shared_ptr<IModule>>* modList);
inline static const char* catToName(Category cat) {
const char* categoryName;
// Get Category Name
{
switch (cat) {
case Category::COMBAT:
categoryName = "Combat";
break;
case Category::VISUAL:
categoryName = "Visual";
break;
case Category::MOVEMENT:
categoryName = "Movement";
break;
case Category::PLAYER:
categoryName = "Player";
break;
case Category::WORLD:
categoryName = "Severs";
break;
case Category::MISC:
categoryName = "Misc";
break;
case Category::BLATANT:
categoryName = "Blatant";
break;
}
}
return categoryName;
}
public:
static void init();
static void render();
static void onKeyUpdate(int key, bool isDown);
static void onMouseClickUpdate(int key, bool isDown);
static void onWheelScroll(bool direction); // true = up, false = down
static void onLoadConfig(void* confVoid);
static void onSaveConfig(void* confVoid);
};
| true |
c90b66c59b925298140d9294297cf7db963dcb4a | C++ | wudenghui/DX10Frame012202 | /CPP/Bullet.h | GB18030 | 1,162 | 2.546875 | 3 | [] | no_license | #ifndef BULLET
#define BULLET
#include"BulletObj.h"
#include"MeshCopyNew.h"
#define BULLET_TIME_GAP 0.1f
#define MAX_BULLET_TYPE 7
#define BULLET_LIFE_TIME 1.0f
#define MAX_BULLET_NUM 80 // 80ӵ
class Bullet : public GameObj
{
public:
Bullet();
~Bullet();
virtual void ActionUpdate(float dt);
void SetBulletList(DemoList* list){ mBulletList = list; }
bool AddBulletMesh(Mesh& mesh);
int SetBulletMesh(Mesh& mesh, int index); // ӵ
void SetBulletMeshIndex(int index){ curBulletTypeIndex = index<numBulletType ?index : numBulletType; } // ӵ
void SetSpeed(float speed, int index){ mSpeed[index] = speed; }
void CreateOneBullet(D3DXVECTOR3& position, D3DXVECTOR3& direction); // һӵ
protected:
// ӵ
MeshCopyNew* bulletTypeArray[MAX_BULLET_TYPE];
float mSpeed[MAX_BULLET_TYPE];
int maxBulletNum[MAX_BULLET_TYPE];
int numBulletNum[MAX_BULLET_TYPE];
int curBulletTypeIndex;
int maxBulletType;
int numBulletType;
// ӵٶ
DemoList* mBulletList;
// PVģ
bool existBullet; // ѴӵPVĿƱ
};
#endif
| true |
e245c0a0160e8572a52b7430bc2e90328e172450 | C++ | liutingjieni/learn_cpp | /C++_learn/func_test.cpp | UTF-8 | 538 | 3.03125 | 3 | [] | no_license | /*************************************************************************
> File Name: func_test.cpp
> Author:
> Mail:
> Created Time: 2019年10月16日 星期三 14时27分27秒
************************************************************************/
#include<iostream>
using namespace std;
int *calc(int *);
double *calc(double *);
int main()
{
int a = 0;
double b = 1.1;
cout << *calc(&a) << endl;
cout << *calc(&b) << endl;
}
int *calc(int *a)
{
return a;
}
double *calc(double *b)
{
return b;
}
| true |
d80deebb23fbc21b5548b7380d02de0375dfb743 | C++ | TRex22/COMS3008_Parallel_Computing | /Test/Test1_redux_rev/Question3.cpp | UTF-8 | 2,652 | 3.390625 | 3 | [
"MIT"
] | permissive | /*
COMS 3008 PC Test 1
Jason Chalom 711985
Question 3.1 and 3.2
*/
#include "stdio.h"
#include "omp.h"
#include <iostream>
#include <cmath>
#include <fstream>
#include "stdlib.h"
using namespace std;
//parameter values chosen as consts here to make code more explicit
const double analytical_ans = exp(50) - exp(5);
const double target_error = 0.001;
const int number_intervals = 1000000;
const int a_ = 5;
const int b_ = 50;
double functionx (double x)
{
return exp(x);
}
double calcError (double ans)
{
double difference = analytical_ans - ans;
double percent = (abs(difference) / analytical_ans) * 100;
return percent;
}
void checkError (double ans)
{
double err = calcError(ans);
if (err < target_error)
{
cout << "Error is below target error of 0.001. Error = " << err << endl;
}
else
{
cout << "Error is above target error of 0.001. Error = " << err << endl;
}
}
//question 3.1 serial
double calcRiemannSum(int m)
{
//work out the iterval width
double h = (double)((double)(b_-a_) / m);
double sum = 0.0;
double x0 = a_;
double x1 = a_ + h;
for (int i = 0; i < number_intervals; i++)
{
sum += (double)(h*(functionx((double)(a_) + h*(i+1)) + functionx((double)(a_) + h*(i))));
}
double integral = sum;
return integral;
}
//question 3.2 parallel - is faster than serial.
double calcParallelRiemannSum(int m)
{
//work out the iterval width
double h = (double)((double)(b_-a_) / m);
double sum = 0.0;
double x0 = a_;
double x1 = a_ + h;
#pragma omp parallel for reduction(+: sum)
for (int i = 0; i < number_intervals; i++)
{
sum += (double)(functionx((double)(a_) + h*(i+1)) + functionx((double)(a_) + h*(i)));/*(double)(h*(functionx((double)(a_) + h*(i+1)) + functionx((double)(a_) + h*(i)))); */
}
double integral = h*sum;
return integral;
}
int main (int argc, char** argv)
{
cout << "Serial Version:" << endl;
double start_serial = omp_get_wtime();
double integration = calcRiemannSum(number_intervals);
double end_serial = omp_get_wtime();
cout << "The integration of the function from 5 to 50 is: " << integration << endl;
checkError(integration);
double diff_serial = end_serial - start_serial;
cout<< "Serial Time: " << diff_serial << " seconds." << endl;
cout << "\nParallel Version:" << endl;
double start_p = omp_get_wtime();
double integration_parallel = calcParallelRiemannSum(number_intervals);
double end_p = omp_get_wtime();
cout << "The integration of the function from 5 to 50 is: " << integration_parallel << endl;
checkError(integration_parallel);
double diff_p = end_p - start_p;
cout<< "Parallel Time: " << diff_p << " seconds." << endl;
return 0;
}
| true |
f5790bb6b1d415a04199a92866a0418afb4a2c44 | C++ | CooperXJ/VScode | /exercise/寻找第几个小的元素.cpp | UTF-8 | 759 | 3.09375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int paration(int a[],int low,int high)
{
int pivot = a[low];
int i = low;
int j = high;
while(i<j)
{
while(i<j&&a[j]>=pivot)j--;
a[i] = a[j];
while(i<j&&a[i]<=pivot)i++;
a[j] = a[i];
}
pivot = a[i];
return i;
}
int findkey(int a[],int start,int end,int k)
{
if(start<end)
{
int loc = paration(a,start,end);
if(loc==k-1)
return a[loc];
if(k-1<loc)return findkey(a,start,loc-1,k);
else return findkey(a,loc+1,end,k);
}
return a[start];
}
int main()
{
int i,k;
int n;
int a[] = {19,12,7,30,11,11,7,53,78,25,7};
n = sizeof(a)/sizeof(int);
for(k = 1;k<n+1;k++)
{
for(i = 0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<findkey(a,0,n-1,k);
}
return 0;
}
| true |
63cb3699aca92a869e53c3ffe3d62d265db50acb | C++ | Mesmeyy/web_server | /server2/src/server_fzjh.h | UTF-8 | 5,070 | 2.53125 | 3 | [] | no_license | /*************************************************************************
> File Name: server_fzjh.h
> Author: 朱紫钰
> Mail: zhuziyu1157817544@gmail.com
> Created Time: 2017年11月13日 星期一 19时56分37秒
************************************************************************/
#ifndef _SERVER_FZJH_H
#define _SERVER_FZJH_H
#include <string>
#include <iostream>
#include<vector>
#include<list>
#include"hong.h"
#define Bucket_size 128
#define Bucket_number 255
#define Ip_number 255
//#include <ptypes.h>
using namespace std;
class bser
{
public:
string ip;
unsigned int port;
//bser的构造函数1
bser(){
ip = "";
port=(rand()%101);//0-100随机整数
}
//bser的构造函数2
bser(string& ip,unsigned int& port){
this -> ip = ip;
this -> port = port;
}
};
class ip_homes
{
private:
//string ip;//存放ip
//unsigned int port;
bser bs;
int weight;//也算是性质标志
int now_weight;
bool att ;//当前服务器是否可用 ,false不可用 true可用
//int hashnum;
public:
void * endpoint;//用作结尾标识符,为以后的hash作,这个先保留
int hashnum;
//unsigned int inde ;//这个元素在vector中的位置
public:
//ip_homes的构造函数1
ip_homes(){
bser *bsp = new bser;
bs = *bsp;
weight = Server_user_exhaust;//初始权重为0
now_weight = weight;//初始当前权重是本身权重
att = false;
endpoint = NULL;
hashnum = 0;
}
//ip_homes的构造函数2
ip_homes(string& ip,unsigned int& port,int& weight){
bser *bsp = new bser(ip,port);
bs = *bsp;
this -> weight = weight;
now_weight = weight;
att = false;
endpoint = NULL;
hashnum = 0;
}
~ip_homes();//ip_homes的析构函数
bool set_bser(string& ip,unsigned int& port);//设置bser
bser get_bser() const ;//获取bser
//设置ip和端口
bool set_ip_port(string& ip,unsigned int& port){
bs.ip = ip;
bs.port = port;
}
string get_ip() const;//获取ip
unsigned int get_port() const;//获取端口
bool set_weight(int w);//设置权重
int get_weight() const;//获取权重
bool set_nowweight(int w);//设置当前权重
bool set_deduct_nowweight();//权重减少一个表示它被选中且被使用
int get_nowweight() const;//获取当前权重
bool set_attr(bool att);//设置服务器是否使用的标记
bool get_attr() const;//获取服务器的是否可以使用的状态
};
class fzjh
{
public:
vector<ip_homes > home_use;//当前服役的服务器头头
//ip_homes* home_use_end;//当前服役的服务器尾巴
ip_homes *home_now;//当前该选它作为负载均衡的服务器
vector<ip_homes > home_lazy;//目前gg服务器
list<ip_homes> * buckets;//为以后ip hash用,如果这是引用的话,当weight,nowweight发生改变,ip_weight的hash中也会发生改变
const int buckets_default_size = Bucket_size;//一个桶的大小撑死128,里面可以有上限的ip_homes个数
const int max_buckets_number = Bucket_number;//桶的个数最多是255个
const int max_ip_number = Ip_number;//负载均衡管理的ip最多是255个
int ip_number;//ip数量
int home_use_number;
int home_lazy_number;
int turn;//代表上次被选择的iphome所在home_use的位置
bool over;//是否轮寻完一圈,true轮寻完一圈,要重置了,false没有轮寻完一圈
public:
fzjh();//构造函数
bool addip(string& ip,unsigned int& port,int& weight);//添加新的ip,需要解析好ip和端口和权重
bool delip(ip_homes& ipho);//删除旧的ip
bool reset();//重置ip队列,即让当前权重为属性权重
ip_homes& get_turn_ip(unsigned int turn);//获取负载均衡的ip
bool get_ok_ips();//列出当前的可用ip和属性们
bool get_bad_ips();//列出当前不可用的ip和属性们
int get_ok_ip_number()const;//获取可用ip数量
int get_ip_number() const;//获取总ip数量
int get_bad_ip_number() const;//获取不可用ip数量
bool ip_weight_hash();//进行ip到weight的哈希
bool set_hash_weight(ip_homes& ipho,int& weight);
int get_hash_weight(ip_homes& ipho);
bool set_hash_nowweight(ip_homes& ipho,int& nowweight);
int get_hash_nowweight(ip_homes& ipho);
bool set_hash_deduct_nowweight(ip_homes& ipho);//对指定的ip的nowweight进行自减操作
/*为什么要用hash,假设服务器必须要往一个有特定功能的服务器上发送请求,也就是服务器维护者很多目标服务器的状态,ip_weight _hash能告诉服务器当前目标的那个特定功能的服务器可不可能接受你这个请求,这个目标服务器是否处于压力状态。那么我需要的是根据ip和端口找当前权重的。*/
};
vector<int> divide_ip(ip_homes& ipho);
bool combine_ip_homes(ip_homes& a,ip_homes& b);
#endif
| true |
f5a2c05464c08078b52203ac1ca0f887674e4b85 | C++ | IngInx747/xengine | /xengine/graphics/uniform_block.h | UTF-8 | 759 | 2.640625 | 3 | [] | no_license | #pragma once
#ifndef XE_UNIFORM_BLOCK_H
#define XE_UNIFORM_BLOCK_H
#include "uniform_buffer.h"
namespace xengine
{
class UniformBlock
{
public:
void Register(UniformBuffer* ub);
void SetBlock(unsigned int offset, unsigned int size);
// clear runtime status before committing data
void Refresh();
// push data into uniform block
// data should be registered in the order they are defined in shaders
void CommitData(const glm::vec3& data);
void CommitData(const glm::vec4& data);
void CommitData(const glm::mat4& data);
private:
// customer
UniformBuffer* m_ub;
// block attributes
unsigned int m_offset;
unsigned int m_size;
// runtime
unsigned int m_position; // current offset
};
}
#endif // !XE_UNIFORM_BLOCK_H
| true |
ed9933fe28ea08dfa13e391e8fb5354928a9e364 | C++ | dattapro001/C-Codes-3G | /task4/number-10.cpp | UTF-8 | 1,423 | 3.46875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *prev;
Node *next;
};
Node *wave;
Node *java;
Node *fact;
void create_doubly_linkedlist();
void display();
int search_item();
int main()
{
create_doubly_linkedlist();
display();
int x = search_item();
if(x==1)
{
cout<<"\n Item not found in list."<<endl;
}
else
{
cout<<"\nitem not found in list."<<endl;
}
return 0;
}
void create_doubly_linkedlist()
{
int n, i;
cout<<"\nEnter any number: ";
cin>>n;
for(i=1; i<=n; i++)
{
java = new Node;
cin>>java->data;
java->next =java->prev = NULL;
if(i==1)
{
wave=java;
}
else
{
fact->next=java;
java->prev= fact;
}
fact=java;
}
}
void display()
{
java=wave;
while(java !=NULL)
{
cout<<java->data<<" ";
java=java->next;
}
}
int search_item()
{
cout<<"\nEnter the number :"<<endl;
int n , c=0;
cin>>n;
java=wave;
while(java !=NULL)
{
if(java->data==n)
{
c++;
return c;
}
java=java->next;
}
}
| true |
dee24184ccec99cadb1e4c373900701eb4aa1211 | C++ | PorygonSeizure/Complex-Game-Systems | /Projects/04_BehaviouralMathematics/src/BaseNPC.h | UTF-8 | 1,733 | 3.015625 | 3 | [] | no_license | #ifndef _BASE_NPC_H_
#define _BASE_NPC_H_
#include <glm/glm.hpp>
class World;
class BaseNPC
{
public:
//Don't want any base constructor
BaseNPC() = delete;
BaseNPC(World* world);
virtual ~BaseNPC() {};
void Update(float deltaTime);
void Render();
//This will just output the NPC's vitals and information to the console
void ReportStatus();
unsigned int GetWaterValue() const { return m_water; }
unsigned int GetFoodValue() const { return m_food; }
unsigned int GetRestValue() const { return m_rested; }
unsigned int GetNumberOfLogs() const { return m_numberOfLogs; }
unsigned int GetHouseWeight() const { return m_houseWeight; }
glm::vec3 GetPosition() const { return m_position; }
protected:
//Called every frame by update - should call one of the behaviour functions below.
virtual void SelectAction(float deltaTime) { CollectWater(deltaTime); }
//Different behaviours that our AI can run - these will move the AI towards the required location
//and then do the task.
void CollectWater(float deltaTime);
void CollectFood(float deltaTime);
void Rest(float deltaTime);
void ChopTree(float deltaTime);
void BuildHouse(float deltaTime);
World* m_world;
private:
bool TravelTo(glm::vec3 loc, float deltaTime);
void CheckAlive();
void CalculateStatusChange();
glm::vec3 m_position;
unsigned int m_food;
unsigned int m_water;
unsigned int m_rested;
unsigned int m_numberOfLogs;
unsigned int m_houseWeight;
float m_moveSpeed;
bool m_alive;
float m_lastReportTime;
float m_reportTime;
float m_lastFoodReductionTime;
float m_lastWaterReductionTime;
float m_lastRestedReductionTime;
float m_foodReductionTime;
float m_waterReductionTime;
float m_restedReductionTime;
};
#endif | true |
9f4ba2a846b83f5e40867cf26873cc74fdfbb362 | C++ | sk8erpunk/LeetCode-Solutions | /Number of Islands.cpp | UTF-8 | 1,453 | 3.703125 | 4 | [] | no_license | /*
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
*/
class Solution {
public:
bool isLegalBorder(int i, int j, int m, int n){
return ((i >=0 && i < m) && (j >=0 && j < n));
}
void DFS(vector<vector<char>>& grid, int i, int j){
grid[i][j] = '0';
int n = grid[0].size();
int m = grid.size();
if(isLegalBorder(i, j+1, m, n) && grid[i][j+1] == '1'){
DFS(grid, i, j+1);
}
if(isLegalBorder(i+1, j, m, n) && grid[i+1][j] == '1'){
DFS(grid, i+1, j);
}
if(isLegalBorder(i, j-1, m, n) && grid[i][j-1] == '1'){
DFS(grid, i, j-1);
}
if(isLegalBorder(i-1, j, m, n) && grid[i-1][j] == '1'){
DFS(grid, i-1, j);
}
}
int numIslands(vector<vector<char>>& grid) {
int islands = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == '1'){
islands++;
DFS(grid, i , j);
}
}
}
return islands;
}
}; | true |
c05ff4215a5e03161945698d15ed93453fdaaece | C++ | ragusa/EV | /conservation_law/src/fct/MultipassLimiter.cc | UTF-8 | 6,842 | 3.125 | 3 | [] | no_license | /**
* \file MultipassLimiter.cc
* \brief Provides the function definitions for the MultipassLimiter class.
*/
/**
* \brief Constructor.
*
* \param[in] n_dofs_ number of degrees of freedom
* \param[in] limiter_ limiter for which multiple passes are to be made
* \param[in] sparsity_pattern_ sparsity pattern
* \param[in] percent_tolerance_ percent tolerance for ending passes
* \param[in] report_antidiffusion_ flag to report amount of accepted
* antidiffusion
*/
template <int dim>
MultipassLimiter<dim>::MultipassLimiter(
const unsigned int & n_dofs_,
std::shared_ptr<Limiter<dim>> limiter_,
const std::shared_ptr<SparsityPattern> sparsity_pattern_,
const double & percent_tolerance_,
const bool & report_antidiffusion_)
: Limiter<dim>(n_dofs_, report_antidiffusion_),
limiter(limiter_),
sparsity_pattern(sparsity_pattern_),
percent_tolerance(percent_tolerance_),
accepted_antidiffusion(n_dofs_)
{
// initialize matrices with sparsity pattern
remainder_matrix.reinit(*sparsity_pattern);
}
/**
* \brief Computes the limiting coefficient matrix.
*
* This function takes passes through a limiter until no more antidiffusion
* is accepted.
*
* \param[in] antidiffusion_matrix matrix of antidiffusion fluxes
* \f$\mathbf{P}\f$
* \param[in] antidiffusion_bounds lower and upper bounds of antidiffusive
* fluxes into each node \f$\mathbf{Q}^-\f$ and \f$\mathbf{Q}^+\f$
* \param[in] cumulative_antidiffusion_vector antidiffusion accepted in previous
* iterations \f$\bar{\mathbf{p}}^{(\ell-1)}\f$
* \param[out] limiter_matrix matrix of limiting coeffients \f$\mathbf{L}\f$
*/
template <int dim>
void MultipassLimiter<dim>::compute_limiter_matrix(
const SparseMatrix<double> & antidiffusion_matrix,
const DoFBounds<dim> & antidiffusion_bounds,
const Vector<double> &,
SparseMatrix<double> & limiter_matrix)
{
// pass index
unsigned int pass_index = 1;
// initialize remainder matrix and accepted antidiffusion vector
remainder_matrix.copy_from(antidiffusion_matrix);
accepted_antidiffusion = 0;
// compute total possible antidiffusion; used for reporting
const double total_possible_antidiffusion =
this->compute_total_possible_antidiffusion(antidiffusion_matrix);
// infinite loop
while (true)
{
// call limiter
limiter->compute_limiter_matrix(remainder_matrix,
antidiffusion_bounds,
accepted_antidiffusion,
limiter_matrix);
// determine if and how much antidiffusion was accepted in this pass
const double antidiffusion_added =
this->compute_total_antidiffusion(remainder_matrix, limiter_matrix);
const double percentage_antidiffusion =
antidiffusion_added / total_possible_antidiffusion * 100.0;
// report antidiffusion added in this iteration
if (this->report_antidiffusion)
printf(" Pass %i: %.2f%% of antidiffusion accepted.\n",
pass_index,
percentage_antidiffusion);
// break if no antidiffusion was accepted in this pass
if (percentage_antidiffusion < percent_tolerance)
break;
// update remainder antidiffusion matrix
update_remainder_matrix_and_accepted_antidiffusion(limiter_matrix);
// increment pass index
pass_index++;
}
// compute total limiting coefficients for all passes
compute_total_limiter_matrix(
antidiffusion_matrix, remainder_matrix, limiter_matrix);
}
/**
* \brief Updates the remainder antidiffusion matrix and the accepted
* antidiffusion vector.
*
* The update to each remainder antidiffusion matrix entry is performed as
* follows:
* \f[
* \Delta P_{i,j}^{(\ell+1)} = (1 - L_{i,j}^{(\ell)})\Delta P_{i,j}^{(\ell)} \,.
* \f]
* The update to each accepted antidiffusion vector entry is performed as
* follows:
* \f[
* \bar{p}_i^{(\ell+1)} = \bar{p}_i^{(\ell)}
* + \sum\limits_j L_{i,j}^{(\ell)}\Delta P_{i,j}^{(\ell)} \,.
* \f]
*
* \param[in] limiter_matrix matrix of limiting coeffients \f$\mathbf{L}\f$
*/
template <int dim>
void MultipassLimiter<dim>::update_remainder_matrix_and_accepted_antidiffusion(
const SparseMatrix<double> & limiter_matrix)
{
// loop over degrees of freedom
for (unsigned int i = 0; i < this->n_dofs; ++i)
{
// create sparse matrix iterators
SparseMatrix<double>::iterator it_remainder = remainder_matrix.begin(i);
SparseMatrix<double>::iterator it_end = remainder_matrix.end(i);
SparseMatrix<double>::const_iterator it_lim = limiter_matrix.begin(i);
// loop over entries in row
for (; it_remainder != it_end; ++it_remainder, ++it_lim)
{
const double DPij = it_remainder->value();
const double Lij = it_lim->value();
// update remainder antidiffusion matrix entry
it_remainder->value() *= (1.0 - Lij);
// update accepted antidiffusion
accepted_antidiffusion[i] += Lij * DPij;
}
}
}
/**
* \brief Computes the total limiting coefficients for all passes.
*
* This function uses the remainder antidiffusive fluxes after the last pass to
* compute total limiting coefficients:
* \f[
* \Delta P_{i,j} = P_{i,j} - L_{i,j}^{total}P_{i,j} \,,
* \f]
* and thus the total limiting coefficients are
* \f[
* L_{i,j}^{total} = 1 - \frac{\Delta P_{i,j}}{P_{i,j}} \,.
* \f]
* In case there would be division by zero (when \f$P_{i,j} = 0\f$),
* \f$L_{i,j}^{total}\f$ is taken to be one.
*
* \param[in] antidiffusion_matrix matrix of antidiffusion fluxes
* \f$\mathbf{P}\f$
* \param[in] remainder_antidiffusion_matrix matrix of remainder antidiffusion
* fluxes \f$\Delta\mathbf{P}\f$
* \param[out] limiter_matrix matrix of limiting coeffients \f$\mathbf{L}\f$
*/
template <int dim>
void MultipassLimiter<dim>::compute_total_limiter_matrix(
const SparseMatrix<double> & antidiffusion_matrix,
const SparseMatrix<double> & remainder_antidiffusion_matrix,
SparseMatrix<double> & limiter_matrix) const
{
// loop over degrees of freedom
for (unsigned int i = 0; i < this->n_dofs; ++i)
{
// create sparse matrix iterators
SparseMatrix<double>::iterator it_lim = limiter_matrix.begin(i);
SparseMatrix<double>::iterator it_end = limiter_matrix.end(i);
SparseMatrix<double>::const_iterator it_flux = antidiffusion_matrix.begin(i);
SparseMatrix<double>::const_iterator it_remainder =
remainder_antidiffusion_matrix.begin(i);
// loop over entries in row
for (; it_lim != it_end; ++it_lim, ++it_flux, ++it_remainder)
{
const double Pij = it_flux->value();
const double DPij = it_remainder->value();
if (Pij == 0.0)
it_lim->value() = 1.0;
else
it_lim->value() = 1.0 - DPij / Pij;
}
}
}
| true |
093b5b35b6379620750bc04c851a4abfd2d79d31 | C++ | ypizarroza1990/ACM | /Online Judges/TJU/3507.cpp | UTF-8 | 1,132 | 2.625 | 3 | [] | no_license | //============================================================================
// Name : Grundy_Cup.cpp
// Author : BeCrazy
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <bits/stdc++.h>
#define ifc(x)(flag[x>>6]&(1<<((x>>1)&31)))
#define isc(x)(flag[x>>6]|=(1<<((x>>1)&31)))
using namespace std;
typedef long long i64;
struct Date{
int y,m,d;
};
bool bisiesto(int year){
if((year%4==0 && (year%100!=0))||(year%100==0 && (year%400==0)))
return true;
return false;
}
int Day(Date D){
int mes[]{0,31,28,31,30,31,30,31,31,30,31,30,31};
i64 ans=0;
for(int i=999;i<D.y;i++){
if(bisiesto(i))ans+=366;
else ans+=365;
}
if(bisiesto(D.y))mes[2]=29;
for(int i=1;i<D.m;i++){
ans+=mes[i];
}
ans+=D.d;
return ans;
}
int cas,y,m,d;
Date one,two;
int main() {
scanf("%d",&cas);
while(cas--){
scanf("%d/%d/%d",&y,&m,&d);
one=Date{y,m,d};
scanf("%d/%d/%d",&y,&m,&d);
two=Date{y,m,d};
printf("%d\n",abs(Day(one)-Day(two)));
}
return 0;
}
| true |
846bbc457baedc9bbb2e8dbbcb0364adb31f0520 | C++ | Hy4zin/bslab-tutorium | /includes/smart_ptr_demo.h | UTF-8 | 659 | 3.140625 | 3 | [] | no_license | //
// Created by Kai Siemek on 14.04.21.
//
#ifndef MODERN_CPP_DEMO_SMART_PTR_DEMO_H
#define MODERN_CPP_DEMO_SMART_PTR_DEMO_H
#include <iostream>
int smart_ptr_main();
class VeryLargeObj {
public:
int aLotOfData;
VeryLargeObj() : aLotOfData(0) {};
explicit VeryLargeObj(int data) : aLotOfData(data) {};
~VeryLargeObj()
{
std::cout << "VLO 0x" << std::hex << std::uppercase
<< aLotOfData << " is being destructed." << std::endl;
};
void method() const
{
std::cout << "VLO content: 0x" << std::hex << std::uppercase
<< aLotOfData << std::endl;
};
};
#endif //MODERN_CPP_DEMO_SMART_PTR_DEMO_H
| true |
6f319c1fae9ca9fe922cff15bae574dc3a4c30bc | C++ | sihrc/Personal-Code-Bin | /project-euler/problem_244.cpp | UTF-8 | 991 | 3.5 | 4 | [
"Apache-2.0"
] | permissive | /*
Sliders
Problem 244
You probably know the game Fifteen Puzzle. Here, instead of numbered tiles, we have seven red tiles and eight blue tiles.
A move is denoted by the uppercase initial of the direction (Left, Right, Up, Down) in which the tile is slid, e.g. starting from configuration (S), by the sequence LULUR we reach the configuration (E):
(S), (E)
For each path, its checksum is calculated by (pseudocode):
checksum = 0
checksum = (checksum 243 + m1) mod 100 000 007
checksum = (checksum 243 + m2) mod 100 000 007
…
checksum = (checksum 243 + mn) mod 100 000 007
where mk is the ASCII value of the kth letter in the move sequence and the ASCII values for the moves are:
L76
R82
U85
D68
For the sequence LULUR given above, the checksum would be 19761398.
Now, starting from configuration (S),
find all shortest ways to reach configuration (T).
(S), (T)
What is the sum of all checksums for the paths having the minimal length?
*/ | true |
fdf02b238760b4520a54948592a1bb69a38e9801 | C++ | LuukSteeman/Themadevices-groep_7 | /src/project/applicationLogic/messageLogic.hpp | UTF-8 | 2,071 | 3.53125 | 4 | [] | no_license | #pragma once
/**
Message logic object. Used Troughout the system to comunicate messages
*/
class MessageLogic
{
private:
int _id; //0 = spelleider 1-31 = speler
int _data;
unsigned int _error = 0;
bool checkChecksum(short data);
public:
/**
Create a message object
@param Player ID
@param data to be send.
*/
MessageLogic(int id, int data);
/**
Create a message object
@param message in bits, will decode it.
*/
MessageLogic(short input);
/**
Create a empty message object
*/
MessageLogic();
/**
Encode the MessageLogic object to its short representation
@return short representation(including checksum) of MessageLogic
*/
short encode();
/**
Decode a short to store in internal representation
@param short representation(with checksum) of message object
@return returns true if a error occured
*/
bool decode(short input);
/**
Return error value.
You can check for a specific error by or-ing with
@return error value
*/
int getError();
/**
Set the internal id of MessageLogic Object
@param id
*/
void setId(int id);
/**
Get the internal id
@return internal id
*/
int getId();
/**
Set the internal data of MessageLogic Object
@param data
*/
void setData(int data);
/**
Get internal data
@return internal data
*/
int getData();
/**
Value to be used for checking for start bit error (no startbit found)
*/
static const unsigned int STARTBITERROR = 1;
/**
Value to be used for checking for out of range
*/
static const unsigned int OUTOFRANGE = 2;
/**
Value to be used for checking for checksum error
*/
static const unsigned int CHECKSUMERROR = 4;
friend bool operator==(MessageLogic& lhs, MessageLogic& rhs){
return lhs._id == rhs._id && lhs._data == rhs._data;
}
}; | true |
ce00aef1baa21780dd4a03e64282dd894935b735 | C++ | NinoKudava/OOP-C- | /Token.cpp | UTF-8 | 866 | 3.3125 | 3 | [] | no_license | #include "std_lib_facilities.h"
class Token{
public:
char kind;
double value;
};
Token get_token();
vector<Token> tokens;
int main(){
for(Token t = get_token(); t.kind != 'q';t = get_token()){
tokens.push_back(t);}
for (Token tok:tokens){
if(tok.kind == '8')
cout << "A number of val " << tok.value << "\n";
else
cout <<"Token of kind " << tok.kind <<"\n";
}
}
Token get_token(){
char ch;
cin >> ch;
switch(ch){
case ';': case 'q': case '(': case ')': case'+': case'-': case'*': case'/': case'%':
return Token{ch};
case'0': case'1': case'2': case'3': case'4': case'5': case'6': case'7': case'8': case'9':
{
cin.putback(ch);
double val;
cin >> val;
return Token{'8',val};
}
}
}
| true |
73d3ab03ce47de38301ba0a7498b953eb166da3a | C++ | chvishu87/2D-Game | /main.cpp | UTF-8 | 566 | 2.75 | 3 | [] | no_license | /************************************************************
* Author : Viswanath Chennuru
* Framework : Provided by Dr Brian Malloy
* *********************************************************/
#include "menuManager.h"
Gamedata* Gamedata::instance;
int main(int, char*[]) {
try {
MenuManager game_manager;
game_manager.play();
}
catch (const string& msg) { std::cout << msg << std::endl; }
catch (const char* st) { std::cout << st <<std::endl; }
catch (...) {
std::cout << "Oops, someone threw an exception!" << std::endl;
}
return 0;
}
| true |
a7bb587dbfe91477bae86f8591cd33443a1b7a99 | C++ | RobJenks/rj-engine | /RJ/Frustum.h | UTF-8 | 5,390 | 2.546875 | 3 | [] | no_license | #pragma once
#include "DX11_Core.h"
#include "FastMath.h"
class iObject;
class OrientedBoundingBox;
class Frustum
{
public:
// Static constant data
static const size_t NEAR_PLANE; // Index into the plane collection
static const size_t FAR_PLANE; // Index into the plane collection
static const size_t FIRST_SIDE; // Index into the plane collection
// Construct a new frustum with the specified number of sides (not including the near- & far-planes)
Frustum(const size_t frustum_side_count);
// Construct a new frustum with the specified number of sides (not including the near- & far-planes)
// Pass the near- and far-planes in during construction since they do not need to be calculated again
Frustum(const size_t frustum_side_count, const FXMVECTOR near_plane, const FXMVECTOR far_plane);
// Should be run each time the projection/viewport settings change, to recalcuate cached information on the view frustrum
// Generally only applicable for the primary view frustum
Result RJ_XM_CALLCONV InitialiseAsViewFrustum(const FXMMATRIX projection, const float far_plane_distance,
const float FOV, const float aspect);
// Copies view frustum data from an existing frustum
void CopyViewFrustumData(const Frustum & view_frustum);
// Builds a new view frustrum based on the current view & inverse view matrices. Generally only applicable for the primary view frustum
// Note frustum must have either been initialised as a view frustum via InitialiseAsViewFrustum, or must have copied relevant data from
// a valid view frustum via CopyViewFrustumData, before it can construct a valid frustum from view data
void RJ_XM_CALLCONV ConstructViewFrustrum(const FXMMATRIX view, const CXMMATRIX invview);
// Add a new side to the frustum, based upon a viewer position and two further points in the world
// Result will be a triangular plane from the viewer with far edge between the two world vertices,
// forming one side of the eventual frustum pyramid
void SetPlane(size_t plane, const FXMVECTOR view_position, const FXMVECTOR p0, const FXMVECTOR p1);
// Add a new side to the frustum by providing the plane coefficients directly
void SetPlane(size_t plane, const FXMVECTOR plane_coeff);
// Retrieve data on the planes that make up this frustum
CMPINLINE size_t GetPlaneCount(void) const { return m_planecount; }
CMPINLINE size_t GetSideCount(void) const { return (m_planecount - 2U); }
CMPINLINE const XMVECTOR * GetPlanes(void) const { return m_planes; }
CMPINLINE const XMVECTOR & GetPlane(size_t plane) const { return m_planes[plane]; }
CMPINLINE const XMVECTOR & GetNearPlane(void) const { return m_planes[Frustum::NEAR_PLANE]; }
CMPINLINE const XMVECTOR & GetFarPlane(void) const { return m_planes[Frustum::FAR_PLANE]; }
// Transform the frustum by the given matrix
void Transform(const FXMMATRIX transform);
// Sets this frustum to a transformed version of the given frustum. This can only
// be performed between frustums of the same cardinatlity
void SetTransformed(const Frustum & frustum, const FXMMATRIX transform);
/*** Intersection testing methods ***/
// Test whether the given bounding sphere lies within the frustum
bool CheckSphere(const FXMVECTOR sphere_centre, float sphere_radius) const;
// Check whether a point lies within the frustum
bool CheckPoint(const FXMVECTOR pt) const;
// Check whether an object lies within the frustum, based upon its collision sphere
bool TestObjectVisibility(const iObject *obj) const;
// Check whether the given cuboid lies within the frustum
bool CheckCuboid(const FXMVECTOR centre, const FXMVECTOR size) const;
// Check whether the given OBB lies within the frustum
bool CheckOBB(const OrientedBoundingBox & obb) const;
// Determine the world-space coordinates of the frustum corners. Relevant ONLY for a view frustum
void DetermineWorldSpaceCorners(XMVECTOR(&pOutVertices)[8]) const;
// Return auxilliary data on the view frustum
CMPINLINE float GetNearClipPlaneDistance(void) const { return m_clip_near; }
CMPINLINE float GetFarClipPlaneDistance(void) const { return m_clip_far; }
CMPINLINE XMMATRIX GetFrustumProjectionMatrix(void) const { return m_proj; }
CMPINLINE XMMATRIX GetFrustumViewProjectionMatrix(void) const { return m_viewproj; }
// Destructor
~Frustum(void);
private:
// Collection of planes that make up the frustum; [0] is always near plane
// and [1] is the far plane. Plane count will be N+2 for an N-sided frustum
AXMVECTOR * m_planes;
size_t m_planecount;
// Checks for the intersection of a centre point and negative-vectorised-radius with
// the frustum. Internal method used as the basis for many public method above
bool CheckSphereInternal(const FXMVECTOR centre_point, const FXMVECTOR negated_radius_v) const;
// Other auxilliary frustum data
float m_clip_near, m_clip_far;
AXMMATRIX m_proj; // Frustrum-specific proj matrix, preacalculated at initialisation
AXMMATRIX m_viewproj; // View-projection for the frustum, calculated on each ConstructFrustum
// Temporary storage for construction of cuboid vertices during visibility testing
static AXMVECTOR_P m_working_cuboidvertices[8];
}; | true |
c98d779908dcf801f3aced8e8cbc0a688fc40b40 | C++ | MysticAdi/code.for.fun | /DP Practice/min_cost_to_n.cpp | UTF-8 | 657 | 3.796875 | 4 | [] | no_license | //Given a number N. Find minimal cost distance from 0 to N with the following conditions.
// 1 . P is the cost for X+1 operations
// 2 . Q is the cost for 2*X operations
#include<iostream>
using namespace std;
int minCost(int n, int p, int q)
{
int end_cost = 0;
while(n>0){
if(n&1){ end_cost+=p; n--;}
else{
int half = n/2;
if(half*p > q) {end_cost+=q;} //checking if p+p+....(n/2 times) is better than a single q cost
else { end_cost+=p*half;}
n/=2;
} }
return end_cost;
}
int main()
{
std::ios_base::sync_with_stdio(false); //To make cin input faster
cin.tie(NULL);
int n = 9 , p = 5, q=1;
int x = minCost(n,p,q);
cout<<x<<endl;
}
| true |
6d5453269e5cad389a83d09d6f2614d711f0751f | C++ | davidc1/BasicShowerReco | /Pi0Ana/Selection/SelectionAlg.cxx | UTF-8 | 1,421 | 2.515625 | 3 | [] | no_license | #ifndef SELECTION_SELECTIONALG_CXX
#define SELECTION_SELECTIONALG_CXX
#include "SelectionAlg.h"
#include <algorithm>
namespace selection {
SelectionAlg::SelectionAlg()
{
}
selection::PI0 SelectionAlg::ApplySelection(const art::ValidHandle<std::vector<recob::Shower> >& shr_h) {
if (shr_h->size() < 2)
return selection::PI0();
// find two most energetic showers
recob::Shower shr1, shr2;
size_t idx1 = 0;
size_t idx2 = 0;
double e1, e2;
e1 = 0.;
e2 = 0.;
// find largest energy shower
for (size_t s=0; s < shr_h->size(); s++) {
auto const& shr = shr_h->at(s);
if (shr.Energy()[2] > e1) {
e1 = shr.Energy()[2];
idx1 = s;
shr1 = shr;
}
}// for all showers
// find second largest energy shower
for (size_t s=0; s < shr_h->size(); s++) {
if (s == idx1) continue;
auto const& shr = shr_h->at(s);
if ( shr.Energy()[2] > e2) {
e2 = shr.Energy()[2];
idx2 = s;
shr2 = shr;
}
}// for all showers
selection::PI0 result;
result.e1 = e1;
result.e2 = e2;
result.idx1 = idx1;
result.idx2 = idx2;
result.dedx1 = shr1.dEdx()[2];
result.dedx2 = shr2.dEdx()[2];
result.angle = shr1.Direction().Angle(shr2.Direction());
result.mass = sqrt( 2 * result.e1 * result.e2 * ( 1 - cos(result.angle) ) );
return result;
}
}// namespace
#endif
| true |