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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
56f0f4f3438ac4c52d9144560467538652689af1 | C++ | Maxim658/lab01 | /maks_lab01c++.cpp | UTF-8 | 1,689 | 3.34375 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include "Complex.h"
#include <fstream>
#include <math.h>
using namespace std;
void Task1()
{
Complex d1 = Input();
Complex d2 = Input();
Complex res;
char act;
bool flag = true;
while (flag)
{
cout << "Input action (+-*/): ";
cin >> act;
switch (act)
{
case '+':
res = Plus(d1, d2);
flag = false;
break;
case '-':
res = Minus(d1, d2);
flag = false;
break;
case '*':
res = Multiply(d1, d2);
flag = false;
break;
case '/':
res = Divide(d1, d2);
flag = false;
break;
default:
cout << "Wrong action! Try again!" << endl;
}
}
cout << "Result: ";
Print(res);
cout << endl;
}
void Task2()
{
int n = 0, a = 0, b = 0;
ifstream f;
f.open("complex.txt");
f >> n;
Complex *p = new Complex[5];
Complex pMax;
int max = -1;
cout << "Complex digits from file: " << endl;
for (int i = 0; i < n; i++)
{
f >> a;
f >> b;
p[i].a = a;
p[i].b = b;
double mod = sqrt(p[i].a * p[i].a + p[i].b * p[i].b);
Print(p[i]);
cout << "Module: " << mod << endl << endl;
if (mod > max)
{
max = mod;
pMax = p[i];
}
}
cout << "Max Complex digit is: \n";
Print(pMax);
cout << "Module: " << max << endl << endl;
}
int Menu()
{
int c;
cout << "1. Task1" << endl;
cout << "2. Task2" << endl;
cout << "0. Exit" << endl;
cin >> c;
return c;
}
int main()
{
int c = 1;
while (c)
{
c = Menu();
switch (c)
{
case 1:
Task1();
break;
case 2:
Task2();
break;
define:
cout << "Wrong input! Try again!" << endl << endl;
}
}
}
| true |
1ea812333ed482acad2411a1f44e02110534c4c8 | C++ | O-Beya/Comp280Assignment1Solution | /main.cpp | UTF-8 | 2,890 | 3.640625 | 4 | [] | no_license | //
// main.cpp
// Comp280Assignment1Solution
//
// Created by Olivier on 5/27/16.
// Copyright © 2016 OlivierBeya(Beyasoft). All rights reserved.
//
#include <iostream>
#include "List.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
//testing constructor, creating an empty List
List intList;
//will use this variable to take user input for menu choice
int userInput = 0;
//testing if the list is empty or not
if (intList.Empty())
{
cout << "The List is created and is empty at the moment" << endl;
}
//loop to keep the program runing until user wants to exit (choosing option 6 from the menu)
while (userInput != 6)
{
//printing the menu option
cout << endl;
intList.Menu();
//taking user input for the choise of the menu option
cin >> userInput;
//testing the insert method
if (userInput == 1)
{
int x;
cout << endl;
cout << "enter the number you would like to insert into the List: " << endl;
cin >> x;
cout << "inserting..." << endl;
intList.InsertAtEnd(x);
}
//testing the delete method
else if (userInput == 2)
{
cout << endl;
cout << "enter the number you would like to delete from the List: " << endl;
int x;
cin >> x;
cout << "Deleting..." << endl;
intList.Delete(x);
}
//testing the display method
else if (userInput == 3)
{
//if user select 3 before anything is inserted tell the user the list is still empty
if (intList.Empty())
{
cout << endl;
cout << "The list is empty, try option 1 to insert a value in the List" << endl;
}
//display the list
else if (!intList.Empty())
{
cout << endl;
cout << "Your List is : " << endl;
intList.Display();
}
}
//testing the sum method
else if(userInput == 4)
{
cout << endl;
cout << "The sum of the list is: " << intList.Sum() << endl;
}
//testing the average method
else if (userInput == 5)
{
cout << endl;
cout << "The Average of the list is: " << intList.Average() << endl;
}
//catching user error. if user enter a number that isn't on the menu option we let the user know
//it is an invalid option
else if (userInput != 6)
{
cout << "You have entered an invalid option, please try again" << endl;
}
}
return 0;
}
| true |
479075ff7a88444199b835b1bfe30b9fca73e1f9 | C++ | XNerv/mlib | /include/mlib/wtimer.h | UTF-8 | 655 | 2.65625 | 3 | [
"MIT"
] | permissive | /*!
\file wtimer.h definition of waitable timer class
(c) Mircea Neacsu 1999
*/
#pragma once
#include "syncbase.h"
namespace mlib {
class wtimer : public syncbase
{
public:
///Timer mode
enum mode { manual, automatic };
wtimer (mode m=automatic, const char *name=NULL, bool use_apc=false);
void start (DWORD interval_ms, DWORD period_ms=0);
void at (FILETIME& utctime, DWORD period_ms=0);
void stop ();
protected:
/*!
Function called for timers that use the APC feature.
*/
virtual void at_timer (DWORD loval, DWORD hival) {};
private:
bool apc_;
static void CALLBACK timerProc (wtimer *obj, DWORD loval, DWORD hival);
};
}
| true |
15ad52760666befac54e1c770939c121d86f0243 | C++ | PSCLab-ASU/multi-agent-accelerator-platform | /utils/include/pending_msg_reg.h | UTF-8 | 6,291 | 2.6875 | 3 | [] | no_license | #include <string>
#include <utility>
#include <variant>
#include <map>
#include <tuple>
#include <mutex>
#include <list>
#include <iostream>
#include "payloads.h"
#include <boost/range/algorithm.hpp>
#ifndef PENDMSGS_REG
#define PENDMSGS_REG
template <typename ... Ts>
class pending_msg_registry{
using pending_message_t = typename std::variant<Ts...>;
using registry_t = typename std::vector< std::pair<std::string, pending_message_t> >;
using registry_vt = typename registry_t::value_type;
public:
template< typename V>
struct find_element_t
{
////////////////////////////////////////////////////
//typedefs
///////////////////////////////////////////////////
using Func = typename std::function<bool(const V &)>;
////////////////////////////////////////////////////
//member variables
///////////////////////////////////////////////////
std::optional<std::string> _key;
Func _pred;
////////////////////////////////////////////////////
//member methods
///////////////////////////////////////////////////
find_element_t( std::optional<std::string> key = {})
: _key(key)
{
_pred = []( const V& obj ){ return true; };
}
find_element_t( Func && pred, std::optional<std::string> key={})
{
_key = key;
_pred = std::forward<Func>(pred);
}
bool operator()( const registry_vt & reg_entry)
{
bool out =false;
auto&[ key, pmsg] = reg_entry;
if(std::holds_alternative<V>(pmsg) )
{
//run the predicate
out = _pred( std::get<V>(pmsg) );
//finally compare optinal key
if( _key ) { out = out && ( _key == key ); };
}
return out;
}
};
std::pair<std::string, std::string> get_ids( std::string AccId )
{
std::string LibId, ReqId;
auto var_pair = boost::find_if( _pending_msgs,
[&](auto& vp){ return (AccId == vp.first); } );
if( var_pair == std::end(_pending_msgs ) )
{
std::cout << "No Ids Found" << std::endl;
return std::make_pair("", "");
}
auto& var_item = var_pair->second;
std::visit( [&](auto& arg)
{
auto [LibId1, ReqId1 ] = arg.get_ids();
LibId = LibId1;
ReqId = ReqId1;
}, var_item );
return std::make_pair(LibId, ReqId);
}
template <typename T>
std::optional<std::reference_wrapper<const T> >
get_pending_message(std::string id)
{
return read_pending_message<T>( find_element_t<T>(id) );
}
template <typename T>
std::optional<T>&& move_pending_message_out(std::string id)
{
std::optional<T> out;
return std::move( move_pending_message_out<T>( find_element_t<T>(id)) );
}
template<typename T, typename U = find_element_t<T> >
std::optional< std::reference_wrapper<T> >
edit_pending_message( U&& lookup )
{
return _edit_pending_msg<T>( std::forward<U>(lookup) );
}
template<typename T, typename U=find_element_t<T> >
std::optional<std::reference_wrapper<const T> >
read_pending_message( U&& lookup )
{
return _edit_pending_msg<T>( std::forward<U>(lookup) );
}
template<typename T, typename U=find_element_t<T> >
std::optional<T>
move_pending_message_out( U&& lookup )
{
U lk = lookup;
auto ref_data = _edit_pending_msg<T>( std::forward<U>(lookup));
if( ref_data )
{
auto data = std::move( ref_data->get() );
remove_pending_message<T>( std::move(lk) );
return std::move(data);
}
else std::cout << "No message to move!!" << std::endl;
return {};
}
template<typename T, typename U=find_element_t<T> >
void remove_pending_message( U&& lookup)
{
//remove element from registry
boost::remove_if( _pending_msgs, std::forward<U>(lookup) );
}
void add_pending_message( std::string AccId, pending_message_t&& pmsg)
{
_pending_msgs.emplace_back(AccId, std::forward<pending_message_t>(pmsg) );
}
void add_generic_message( std::string AccId, std::string LibId, std::string ReqId )
{
other_pending_msg opm( LibId, ReqId );
//AccId is created by this processa for downstream id
//LibId is the Id given by the library
//requester_id zmq given by the ZMQ subsys
_pending_msgs.emplace_back(AccId, opm );
}
void remove_message( std::string id)
{
boost::remove_if( _pending_msgs,
[&](auto& entry){ return (id == entry.first); } );
}
template<typename T>
std::list<T> _get_all_msgs_by_type( bool remove)
{
std::list<T> out;
std::list<std::string> removal_list;
//get all messages
for(auto vmsg : _pending_msgs )
{
if(auto pval = std::get_if<T>(&(vmsg.second)))
{
out.push_back( *pval );
removal_list.push_back( vmsg.first );
}
}
if( remove )
for(auto key : removal_list )
remove_message( key );
return out;
}
void lock() { _pmsg_mu.lock(); }
void unlock() { _pmsg_mu.unlock(); }
private:
template< typename T, typename U = find_element_t<T> >
std::optional<std::reference_wrapper<T> >
_edit_pending_msg (U&& lookup )
{
std::optional<std::reference_wrapper<T> > out;
try
{
//look for a variant of type T and pred
auto var_pair = boost::find_if( _pending_msgs, std::forward<U>(lookup) );
//if it found an entry then return the reference
if( var_pair != std::end(_pending_msgs ) )
{
//return reference by copy
out = std::ref( std::get<T>(var_pair->second ) );
} else std::cout << "Could not find pmsg... _edit_pending_msg" << std::endl;
}
catch (const std::bad_variant_access&)
{
std::cout << "Inoorrect/no message type" << std::endl;
out = {};
}
return out;
}
//nex_key message
registry_t _pending_msgs;
std::mutex _pmsg_mu;
};
#endif
| true |
e74e15970bf4eca07b35c73624b8c5b45d5c3297 | C++ | RageHyperNOVA/Project-Solar-Tracking-System-Tessolve-Training | /Tessolve_SolarTrackingSystem.ino | UTF-8 | 5,470 | 2.71875 | 3 | [] | no_license | #ifndef __CC3200R1M1RGC__
#include <SPI.h>
#endif
#include <WiFi.h>
#include <Wire.h>
#include "Adafruit_TMP006.h"
#include <stdlib.h>
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "S5CEPJUL7KFTHSES";
const int updateThingSpeakInterval = 16 * 1000;
char buffer[25];
char ssid[] = "R2C";
char password[] = "r2cudt@2021";
WiFiClient client;
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 10*1000;
int failedCounter = 0;
void setup() {
Serial.begin(115200);
pinMode(2,INPUT); // LDR Sensor-1 placed along EAST
pinMode(6,INPUT); // LDR Sensor-2 placed along WEST
pinMode(23,INPUT); // LDR Sensor-3 attached with Solar Panels
pinMode(9, OUTPUT); // Yellow LED
pinMode(10, OUTPUT); // Green LED
pinMode(29, OUTPUT); // Red LED
pinMode(3, OUTPUT); // Buzzer
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println("\nYou're connected to the network");
Serial.println("Waiting for an ip address");
while (WiFi.localIP() == INADDR_NONE) {
Serial.print(".");
delay(300);
}
Serial.println("\nIP Address obtained");
printWifiStatus();
}
void loop() {
while (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
int maxIntensity = 4095; // A THRESHOLD to determine the need of altering the DIRECTION of solar PANEL.
if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
//float objt = tmp006.readObjTempC();
float LDR_EAST = analogRead(2);
float LDR_WEST = analogRead(6);
float LDR_PANEL = analogRead(23);
int dirInd = 0; // This is the value to sent to thingspeak INDICATING required change in DIRECTION.
// Checking if current position of panel is ideal based on the threshold value "maxIntensity"
if(LDR_PANEL<0.75*maxIntensity) {
Serial.print("Current Direction LDR value: ");
Serial.print(LDR_PANEL);
Serial.println("");
// BUZZER set HIGH to indicate that change of DIRECTION is required.
digitalWrite(3, HIGH);
// Checking in which direction panels must be moved based on LDR SENSOR values placed along EAST & WEST
if(LDR_EAST > LDR_WEST) {
Serial.print("LDR Value EAST "); Serial.print(LDR_EAST);
Serial.print("LDR Value WEST "); Serial.print(LDR_WEST);
Serial.println("--ALERT--\nMOVE THE PANELS TOWARDS EAST");
dirInd = -100; // -100 indicating TOWARDS EAST
digitalWrite(10, HIGH); // GREEN LED indicating TOWARDS EAST
digitalWrite(9, LOW);
digitalWrite(29, LOW);
}
else {
Serial.print("LDR Value EAST "); Serial.print(LDR_EAST);
Serial.print("LDR Value WEST "); Serial.print(LDR_WEST);
Serial.println("--ALERT--\nMOVE THE PANELS TOWARDS WEST");
dirInd = 100; // +100 indicating TOWARDS WEST
digitalWrite(29, HIGH); // RED LED indicating TOWARDS WEST
digitalWrite(10, LOW);
digitalWrite(9, LOW);
}
}
else {
// Buzzer is turned off as the current direction of panels are ideal enough.
digitalWrite(3, LOW);
digitalWrite(9, HIGH); // YELLOW LED indicates halt state i.e panels are well placed for optimum sunlight
Serial.println("PANELS are placed along OPTIMUM DIRECTION");
dirInd = 0;
}
String sLDR_PANEL = dtostrf(LDR_PANEL,3,3,buffer);
String sLDR_EAST = dtostrf(LDR_EAST,3,3,buffer);
String sLDR_WEST = dtostrf(LDR_WEST,3,3,buffer);
String sdirInd = dtostrf(dirInd,3,3,buffer);
updateThingSpeak("field1=" + sdirInd+"&field2=" + sLDR_PANEL+"&field3=" + sLDR_EAST + "&field4=" + sLDR_WEST);
}
lastConnected = client.connected();
}
void updateThingSpeak(String tsData)
{
if (client.connect(thingSpeakAddress, 80))
{
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
Serial.println(">>TSDATALength=" + tsData.length());
client.print("\n\n");
client.print(tsData);
Serial.println(">>TSDATA=" + tsData);
lastConnectionTime = millis();
if (client.connected())
{
Serial.println("Connecting to ThingSpeak...");
Serial.println();
failedCounter = 0;
}
else
{
failedCounter++;
Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");
Serial.println();
}
}
else
{
failedCounter++;
Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
Serial.println();
lastConnectionTime = millis();
}
}
int getLength(int someValue) {
int digits = 1;
int dividend = someValue / 10;
while (dividend > 0) {
dividend = dividend / 10;
digits++;
}
return digits;
}
void printWifiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
| true |
cc54216137665077133bff539e8bfec5f6d3e63c | C++ | SteBry/competitive_programming | /IMPA/2020_Round_2/Week_1/wff_n_proof.cpp | UTF-8 | 1,671 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
std::string line;
while (cin >> line && line != "0")
{
string aString, lString, nString;
int tempPos;
sort(line.begin(), line.end());
/*
The string is split into 3 strings
one contains all characters of type "qprst",
one contains all characters of type "KACE",
one contains all characters of type "N"
*/
// Create string of all "qprst"
tempPos = line.find_first_of("qprst");
if (tempPos != string::npos)
{
aString = line.substr(tempPos);
}
//create string of all "KACE"
tempPos = line.find_first_of("KACE");
if (tempPos != string::npos)
{
lString = line.substr(tempPos, line.find_last_of("KACE") - tempPos + 1);
}
// Create string of all "N"
tempPos = line.find_first_of("N");
if (tempPos != string::npos)
{
nString = line.substr(tempPos, line.find_last_of("N") - tempPos + 1);
}
if (aString == "")
{
// if there are no string of "qprst" there can be no WFF
cout << "no WFF possible" << endl;
}
else
{
/*
Add all characters of type "N" to the WFF since they always create a WFF if the rest of the formula is a WFF
Add one more character of type "KACE" then of type "qprst"
*/
cout << nString << lString.substr(0, aString.length() - 1) << aString.substr(0, lString.length() + 1) << endl;
}
}
}
| true |
0a46a622215d32d0a65dc1e34364387893fda92a | C++ | peperontino39/AirRide_Gameshoow | /src/Scene/SceneManager/CreateScene.h | UTF-8 | 284 | 2.75 | 3 | [] | no_license | #pragma once
#include "SceneBase.h"
#include <memory>
class Scene
{
public:
template<typename T>
static void createScene(T* _scene) {
scene = std::make_shared<T>(*_scene);
};
static SceneBase& get() {
return *scene;
}
private:
static std::shared_ptr<SceneBase> scene;
};
| true |
169af366887a30b19efca8f937557662dbd72c3b | C++ | Pecneb/CodingStudies | /8_het/min_rendez.cpp | UTF-8 | 693 | 3.203125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void rendez(int* t, int size) {
int i,j,k;
for(i=0; i<size; i++) {
k = i;
for(j=i; j<size; j++) {
if(*(t+k) > *(t+j)) {
k = j;
}
}
if(k > i) {
int cs = *(t+k);
*(t+k) = *(t+i);
*(t+i) = cs;
}
}
}
int main() {
int* tomb = new int[5];
int be;
for(int i=0; i < 5; i++) {
cin >> be;
*(tomb+i) = be;
cout << i+1 << " = " << *(tomb+i) << '\n';
}
rendez(tomb, 5);
cout << '\n';
for(int i=0; i < 5; i++) {
cout << i+1 << " = " << *(tomb+i) << '\n';
}
return 0;
} | true |
18c9c6060a4755bc76532321322ba6b8965be1f9 | C++ | gtomasini/neuronal-network-3 | /generador.cpp | UTF-8 | 1,296 | 2.6875 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <math.h>
using namespace std;
const float radio_=20;
const float x0_(20), y0_(25);
const float pi=3.14159265358979323846433832;
int
main( int argc, char *argv[] ) {
if (argc <3 ){
cout<<"escriba "<<argv[0]<<" archivo #muestras"<<endl;
return -1;
}
ofstream myfile;
myfile.open ( argv[1] );
srand ((unsigned int) time(0) );
//const float x0(20), y0(25);
int ang=0;
for (int i=0; i<atoi( argv[2] ); i++){
float x=(float)rand()/float(RAND_MAX)*100;
float y=(float)rand()/float(RAND_MAX)*100;
float xx(x-x0_), yy(y-y0_);
float d( sqrt(xx*xx+yy*yy));
bool out(true);
if ( d>radio_) out=false;
myfile<<x<<","<<y<<","<<out<<endl;
cout<<i<<") "<<x<<" "<<y<<" "<<d<<" "<<out<<endl;
//angulo
float radianes=ang*2*pi/360;
d=radio_-2 +(float)rand()/float(RAND_MAX)*4;
x=d*cos(radianes)+x0_;
y=d*sin(radianes)+y0_;
//float xx(x-x0), yy(y-y0);
//float d( sqrt(xx*xx+yy*yy));
//cout<<x<<" "<<y<<" "<<d<<endl;
out=true;
if ( d>radio_) out=false;
cout<<"d:"<<d<<" x:"<<x<<" y:"<<y<<", out:"<<out<<endl;
myfile<<x<<","<<y<<","<<out<<endl;
ang++;
}
myfile.close();
}
| true |
2d7db7107c7266f6277afcd728ba27865b8f725c | C++ | Inero1999/Catalog-Song-lirics | /24.03_Catalog song lyrics.cpp | UTF-8 | 3,991 | 2.953125 | 3 | [] | no_license | // 24.03_Catalog song lyrics.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include<string.h>
#include<string>
#include<Windows.h>
#include <fstream>
using namespace std;
struct catalog_song //создание структуры Каталога
{
string name_song;
string author_song;
string text_song;
int year_song;
};
catalog_song* Catalog; // объявляю указатель на массив для Каталога
void create_catalog(catalog_song A[]) {
int a, y; // а - первоначальное количество песен в каталоге; y - переменная для окончания ввода
string x; // х - переменная для ввода информации
cout << " How many songs do you want to add to the catalog ? Enter nomber \n";
cin >> a;
ofstream in("Catalog.txt", ios::app);
catalog_song* temp= new catalog_song [a]; // создаем массив с нужным количеством элементов
for (int i = 0;i < a;i++) {
{
do {
cout << "Enter NAME Song. At the end, put the symbol '>'. For END Enter 'q'.";
getline(cin, x);
in << x;
y = getchar();
} while (y != 113);
///* cout << endl;
// cout << "Enter AUTHOR Song. For END Enter '>'. ";
// cin >> A[i].author_song;
// cout << endl;
// cout << "Enter YEAR of Song Writing : ";
// cin >> A[i].year_song;
}
}
}
int main()
{
ofstream in("Catalog.txt", ios::app); // поток для записи
if (in.is_open()) {
int z = 0;
do {
cout << "Menu for working with the catalog: \n";
cout << " '0' - Create Catalog of Songs; \n";
cout << " '1' - Add Song lyrics; \n";
cout << " '2' - Delete Song lyrics; \n";
cout << " '3' - Edit Song lyrics; \n";
cout << " '4' - Show Song lyrics; \n";
cout << " '5' - Save Song Lyrics for File; \n";
cout << " '6' - Search for all songs by the author; \n";
cout << " '6' - Search for all songs by word; \n";
cout << " 'q' - EXIT the Catalog; \n";
z = getchar();
if (z == 48) {
create_catalog(Catalog);
}
} while (z != 113);
}
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
| true |
86c04c7f785a5fef3f84d2afd1e52c8b0bde18eb | C++ | LJK150030/AntAI | /code/Math/MathUtils.cpp | UTF-8 | 25,272 | 3.21875 | 3 | [] | no_license | #include"Math/MathUtils.hpp"
#include <cmath>
#include "Math/Vec2.hpp"
#include <vector>
typedef union {float f; int i;} IntOrFloat;
//Angle utilities
//--------------------------------------------------------------------------------------------------
float ConvertRadiansToDegrees(const float radians)
{
return radians * RADIANS_TO_DEGREES;
}
//--------------------------------------------------------------------------------------------------
float ConvertDegreesToRadians(const float degrees)
{
return degrees * DEGREES_TO_RADIANS;
}
//--------------------------------------------------------------------------------------------------
float CosDegrees(const float degrees)
{
return cos(ConvertDegreesToRadians(degrees));
}
//--------------------------------------------------------------------------------------------------
float SinDegrees(const float degrees)
{
return sin(ConvertDegreesToRadians(degrees));
}
float TanDegrees(const float radians)
{
return tan(ConvertDegreesToRadians(radians));
}
float CosRadians(const float radians)
{
return cos(radians);
}
float SinRadians(const float radians)
{
return sin(radians);
}
float TanRadians(const float radians)
{
return tan(radians);
}
//--------------------------------------------------------------------------------------------------
float Atan2Degrees(const float y, const float x)
{
return ConvertRadiansToDegrees(atan2f(y, x));
}
float GetAngularDisplacement(const float start_degrees, const float end_degrees)
{
float ang_disp = end_degrees - start_degrees;
while (ang_disp > 180.f)
ang_disp -= 360.f;
while (ang_disp < -180.f)
ang_disp += 360.f;
return ang_disp;
}
float GetTurnedToward(const float current_degrees, const float goal_degrees, const float max_positive_delta_degrees)
{
const float ang_disp = GetAngularDisplacement(current_degrees, goal_degrees);
const float turn_degrees = ClampFloat(ang_disp, -max_positive_delta_degrees, max_positive_delta_degrees);
return turn_degrees;
}
//Geometric utilities
//--------------------------------------------------------------------------------------------------
float GetDistance(const Vec2& position_a, const Vec2& position_b)
{
const Vec2 direction = position_b - position_a;
return direction.GetLength();
}
//-------------------------------------------------------------------------------------------------
float GetDistanceSquared(const Vec2& position_a, const Vec2& position_b)
{
const Vec2 direction = position_b - position_a;
return direction.GetLengthSquared();
}
//--------------------------------------------------------------------------------------------------
bool DoDiscsOverlap(const Vec2& center_a, const float radius_a, const Vec2& center_b, const float radius_b)
{
const float i = GetDistanceSquared(center_a, center_b);
const float j = (radius_a + radius_b) * (radius_a + radius_b);
return i <= j;
}
bool DoesDiscOverlapLine2D(const Vec2& disc_center, float disc_radius, const Vec2& point_on_line,
const Vec2& another_point_on_line)
{
const Vec2 line = another_point_on_line - point_on_line;
const Vec2 i_axis = line.GetNormalized();
const Vec2 j_axis = i_axis.GetRotated90Degrees();
const Vec2 displacement = disc_center - point_on_line;
const Vec2 displacement_onto_j = GetProjectedVectorAlongAxis2D(displacement, j_axis);
return displacement_onto_j.GetLengthSquared() < disc_radius * disc_radius;
}
bool DoesDiscOverlapLineSegment2D(const Vec2& disc_center, float disc_radius, const Vec2& line_start,
const Vec2& line_end)
{
const Vec2 start_to_end = line_end - line_start;
const Vec2 start_to_center = disc_center - line_start;
if (DotProduct(start_to_end, start_to_center) < 0.0f)
return IsPointInDisc2D(line_start, disc_center, disc_radius);
const Vec2 end_to_start = line_start - line_end;
const Vec2 end_to_center = disc_center - line_end;
if (DotProduct(end_to_start, end_to_center) < 0.0f)
return IsPointInDisc2D(line_end, disc_center, disc_radius);
const Vec2 i_axis = start_to_end.GetNormalized();
const Vec2 displacement_onto_i = DotProduct(i_axis, start_to_center) * i_axis;
return IsPointInDisc2D(line_start + displacement_onto_i, disc_center, disc_radius);
}
bool DoesDiscOverlapCapsule2D(const Vec2& disc_center, float disc_radius, const Vec2& capsule_start,
const Vec2& capsule_end, float capsule_radius)
{
const float disc_new_radius = disc_radius + capsule_radius;
return DoesDiscOverlapLineSegment2D(disc_center, disc_new_radius, capsule_start, capsule_end);
}
//--------------------------------------------------------------------------------------------------
bool IsPointInSector(const Vec2& point, const Vec2& origin, const float orientation_degrees, const float max_dist,
const float aperture_degrees)
{
if (!IsPointInDisc2D(point, origin, max_dist)) return false;
Vec2 displacement_to_point = point - origin;
const float angle_to_point_degrees = displacement_to_point.GetAngleDegrees();
const float angular_displacement_to_point = GetAngularDisplacement(orientation_degrees, angle_to_point_degrees);
return (fabsf(angular_displacement_to_point) <= aperture_degrees * 0.5f);
}
Vec2 GetLocalVectorFromWorld(const Vec2& world_vector, const Vec2& i_basis, const Vec2& j_basis)
{
const float world_project_i = DotProduct(world_vector, i_basis);
const float world_project_j = DotProduct(world_vector, j_basis);
return Vec2(world_project_i, world_project_j);
}
Vec2 GetLocalPositionFromWorld(const Vec2& world_position, const Vec2& i_basis, const Vec2& j_basis,
const Vec2& t_basis)
{
const Vec2 t_to_p = world_position - t_basis;
const float displacement_project_i = DotProduct(t_to_p, i_basis);
const float displacement_project_j = DotProduct(t_to_p, j_basis);
return Vec2(displacement_project_i, displacement_project_j);
}
Vec2 GetWorldVectorFromLocal(const Vec2& local_vector, const Vec2& i_basis, const Vec2& j_basis)
{
Vec2 world_vector = local_vector.x * i_basis + local_vector.y * j_basis;
return world_vector;
}
Vec2 GetWorldPositionFromLocal(const Vec2& local_position, const Vec2& i_basis, const Vec2& j_basis,
const Vec2& t_basis)
{
Vec2 world_position = t_basis + local_position.x * i_basis + local_position.y * j_basis;
return world_position;
}
float SmoothStart2(const float input_zero_to_one)
{
return input_zero_to_one * input_zero_to_one;
}
float SmoothStart3(const float input_zero_to_one)
{
return input_zero_to_one * input_zero_to_one * input_zero_to_one;
}
float SmoothStart4(const float input_zero_to_one)
{
return input_zero_to_one * input_zero_to_one * input_zero_to_one * input_zero_to_one;
}
float SmoothStart5(const float input_zero_to_one)
{
return input_zero_to_one * input_zero_to_one * input_zero_to_one * input_zero_to_one * input_zero_to_one;
}
float SmoothStop2(const float input_zero_to_one)
{
return (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) + 1.0f;
}
float SmoothStop3(const float input_zero_to_one)
{
return (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) + 1.0f;
}
float SmoothStop4(const float input_zero_to_one)
{
return (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) * (input_zero_to_one -
1.0f) + 1.0f;
}
float SmoothStop5(const float input_zero_to_one)
{
return (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) * (input_zero_to_one - 1.0f) * (input_zero_to_one -
1.0f) * (input_zero_to_one - 1.0f) + 1.0f;
}
float SmoothStep3(const float input_zero_to_one)
{
const float& t = input_zero_to_one;
return t * t * (3.f - (2.f * t));
}
float SmoothStep5(const float input_zero_to_one)
{
const float& t = input_zero_to_one;
return t * t * t * (t * ((t * 6) - 15) + 10);
}
//--------------------------------------------------------------------------------------------------
// The order of the composite transformation is first scale, then rotate, then translate
Vec2 TransformPosition(const Vec2& position, const float uniform_scale, const float rotation_degree_about_z,
const Vec2& translation_xy)
{
Vec2 new_position = position * uniform_scale;
new_position.RotateDegrees(rotation_degree_about_z);
new_position += translation_xy;
return new_position;
}
//--------------------------------------------------------------------------------------------------
Vec2 MaxVec2(const Vec2& a, const Vec2& b)
{
const float max_x = (a.x > b.x) ? a.x : b.x;
const float max_y = (a.y > b.y) ? a.y : b.y;
return Vec2(max_x, max_y);
}
Vec2 MinVec2(const Vec2& a, const Vec2& b)
{
const float min_x = (a.x < b.x) ? a.x : b.x;
const float min_y = (a.y < b.y) ? a.y : b.y;
return Vec2(min_x, min_y);
}
float RangeMapLinearFloat(const float in_value, const float in_start, const float in_end, const float out_start,
const float out_end)
{
if (in_end == in_start) return 0.5f * (out_start + out_end);
const float in_range = in_end - in_start;
const float out_range = out_end - out_start;
const float in_distance = in_value - in_start;
const float in_fraction = in_distance / in_range;
const float out_distance = in_fraction * out_range;
const float out_value = out_start + out_distance;
return out_value;
}
Vec2 RangeMapLinearVec2(const Vec2& in_value, const Vec2& in_start, const Vec2& in_end, const Vec2& out_start,
const Vec2& out_end)
{
const float x_val = RangeMapLinearFloat(in_value.x, in_start.x, in_end.x, out_start.x, out_end.x);
const float y_val = RangeMapLinearFloat(in_value.y, in_start.y, in_end.y, out_start.y, out_end.y);
return Vec2(x_val, y_val);
}
float LinearInterpolationFloat(const float start_value, const float end_value, const float fraction)
{
const float range = end_value - start_value;
const float mapped_value = fraction * range;
return (start_value + mapped_value);
}
Vec2 LinearInterpolationVec2(const Vec2& start_value, const Vec2& end_value, float fraction)
{
const float range_x = end_value.x - start_value.x;
const float mapped_value_x = fraction * range_x;
const float result_x = start_value.x + mapped_value_x;
const float range_y = end_value.y - start_value.y;
const float mapped_value_y = fraction * range_y;
const float result_y = start_value.y + mapped_value_y;
return Vec2(result_x, result_y);
}
float GetFractionInRange(const float start_value, const float end_value, const float value)
{
const float range = end_value - start_value;
const float distance = value - start_value;
return distance / range;
}
float Sign(const float value)
{
return (value <= 0.0f) ? 1.0f : -1.0f;
}
bool IsBitFlagSet(const unsigned short bits, const unsigned short bit_flag)
{
return (bits & bit_flag);
}
void SetBitFlag(unsigned short& bits, const unsigned short bit_flag)
{
bits |= bit_flag;
}
unsigned short GetBitFlag(unsigned short& bits, const unsigned short bit_flag)
{
const unsigned short set = bits;
return set & bit_flag;
}
void ClearBitFlag(unsigned short& bits, const unsigned short bit_flag)
{
bits &= ~bit_flag;
}
void ToggleBitFlag(unsigned short& bits, const unsigned short bit_flag)
{
bits = bits ^ bit_flag;
}
bool IsBitFlagSet(const unsigned bits, const unsigned bit_flag)
{
return (bits & bit_flag);
}
void SetBitFlag(unsigned& bits, const unsigned bit_flag)
{
bits |= bit_flag;
}
unsigned GetBitFlag(unsigned& bits, const unsigned bit_flag)
{
const unsigned int set = bits;
return set & bit_flag;
}
void ClearBitFlag(unsigned& bits, const unsigned bit_flag)
{
bits &= ~bit_flag;
}
float ClampFloat(const float value, const float min_value, const float max_value)
{
if (value < min_value)
return min_value;
if (value > max_value)
return max_value;
return value;
}
double ClampDouble(const double value, const double min_value, const double max_value)
{
if (value < min_value)
return min_value;
if (value > max_value)
return max_value;
return value;
}
float ClampFloatPositive(const float value, const float max_value)
{
const float clamped_vale = ClampFloat(value, 0.0f, max_value);
return clamped_vale;
}
float ClampFloatPositive(const float value)
{
if( value < 0.f )
return 0.f;
else
return value;
}
Vec2 ClampVec2(const Vec2& value, const Vec2& min_value, const Vec2& max_value)
{
const float x_val = ClampFloat(value.x, min_value.x, max_value.x);
const float y_val = ClampFloat(value.y, min_value.y, max_value.y);
return Vec2(x_val, y_val);
}
int RoundToNearestInt(const float value)
{
return static_cast<int>(floorf(value + 0.5f));
}
int RoundDownToNearestInt(const float value)
{
return static_cast<int>(floorf(value));
}
int RoundUpToNearestInt(const float value)
{
return static_cast<int>(ceilf(value));
}
int ModPositive(const int value, const int mod_by)
{
int mod_value = value % mod_by;
if (mod_value < 0)
mod_value += mod_by;
return mod_value;
}
float ModFloatPositive(float value, float mod_by)
{
float mod_value = value;
while(mod_value >= mod_by)
mod_value -= mod_by;
while(mod_value < 0.0f)
mod_value += mod_by;
return mod_value;
}
float ClampZeroToOne(const float value)
{
return ClampFloat(value, 0.0f, 1.0f);
}
int ClampInt(const int value, const int min_value, const int max_value)
{
if (value < min_value)
return min_value;
if (value > max_value)
return max_value;
return value;
}
int ClampIntPositive(const int value, const int max_value)
{
const int clamped_vale = ClampInt(value, 0, max_value);
return clamped_vale;
}
float Sqrt(const float value)
{
/*ASSERT_RECOVERABLE(value >= 0, "Attempting to Sqrt a zero value");*/
if(value <= 0.0f) return 0.0f;
return sqrtf( value );
}
float RecipSqrt(const float value)
{
/*ASSERT_RECOVERABLE(value >= 0, "Attempting to Sqrt a zero value");*/
if(value <= 0.0f) return 0.0f;
return 1.0f/sqrtf( value );
}
float Abs(const float f)
{
return fabsf(f);
}
int Abs(const int i)
{
return abs(i);
}
float Min(float a, float b)
{
return a < b ? a : b;
}
float Max(float a, float b)
{
return a > b ? a : b;
}
int Min(int a, int b)
{
return a < b ? a : b;
}
int Max(int a, int b)
{
return a > b ? a : b;
}
float DotProduct(const Vec2& a, const Vec2& b)
{
return (a.x * b.x) + (a.y * b.y);
}
float GetProjectedLengthAlongAxis2D(const Vec2& source, const Vec2& normalized_axis)
{
return DotProduct(source, normalized_axis);
}
Vec2 GetProjectedVectorAlongAxis2D(const Vec2& source, const Vec2& axis)
{
// const float projected_length = GetProjectedLengthAlongAxis2D(source, normalized_axis);
// return normalized_axis * projected_length;
const float dot_axis = DotProduct(axis, axis);
const Vec2 normalized_axis = axis / dot_axis;
const float dot_product = DotProduct(source, axis);
return normalized_axis * dot_product;
}
Vec2 GetReflectedVector(const Vec2& reflect_this, const Vec2& point_normal)
{
const Vec2 projected_vector_against_normal = GetProjectedVectorAlongAxis2D(reflect_this, point_normal);
const Vec2 projected_vector_against_wall = reflect_this - projected_vector_against_normal;
return projected_vector_against_wall + (-1 * projected_vector_against_normal);
}
Vec2 ReflectVectorOffSurfaceNormal(const Vec2& incoming_vector, const Vec2& surface_normal)
{
const Vec2 incoming_vector_n = GetProjectedVectorAlongAxis2D(incoming_vector, surface_normal);
const Vec2 incoming_vector_t = incoming_vector - incoming_vector_n;
return incoming_vector_t + (-1.0f * incoming_vector_n);
}
Vec2 GetClosestPointOnDisc(const Vec2& position, const Vec2& disc_center, const float disc_radius)
{
Vec2 pc = position - disc_center;
pc.ClampLength(disc_radius);
return disc_center + pc;
}
bool IsPointInDisc2D(const Vec2& position, const Vec2& origin, float disc_radius)
{
Vec2 displacement = origin - position;
const float length_squared = displacement.GetLengthSquared();
const float disc_radius_squared = disc_radius * disc_radius;
return length_squared <= disc_radius_squared;
}
void PushDiscOutOfDisc(const Vec2& stationary_disc_center, const float stationary_disc_radius, Vec2& mobile_disc_center,
const float mobile_disc_radius)
{
if(DoDiscsOverlap(stationary_disc_center, stationary_disc_radius, mobile_disc_center, mobile_disc_radius))
{
Vec2 displacment = mobile_disc_center - stationary_disc_center;
displacment.SetLength((mobile_disc_radius + stationary_disc_radius) - displacment.GetLength());
mobile_disc_center += displacment;
}
}
// assuming they have already overlapped
void PushDiscsOutOfEachOther(Vec2& disc_1_center, const float disc_1_radius, Vec2& disc_2_center,
const float disc_2_radius)
{
Vec2 displacement = Vec2(disc_2_center - disc_1_center);
const float length_from_discs = displacement.GetLength();
const float summation_of_disc_radii = disc_1_radius + disc_2_radius;
const float overlap = summation_of_disc_radii - length_from_discs;
if (overlap <= 0) return;
displacement.Normalize();
disc_1_center += displacement * (-0.5f * overlap);
disc_2_center += displacement * (0.5f * overlap);
}
Vec2 GetClosestPointOnLine2D(const Vec2& reference_pos, const Vec2& point_on_line, const Vec2& another_point_on_line)
{
// Guildhall MP1
// const Vec2 line = another_point_on_line - point_on_line;
// const Vec2 i = line.GetNormalized();
// const Vec2 sp = reference_pos - point_on_line;
// const Vec2 p_i = DotProduct(i, sp) * i;
// return point_on_line + p_i;
//essential mathematics 3rd ed
const Vec2 w = reference_pos - point_on_line;
const Vec2 line_direction = another_point_on_line - point_on_line;
const float line_mag_sq = DotProduct(line_direction, line_direction);
const float project = DotProduct(w, line_direction);
return point_on_line + (project/line_mag_sq)*line_direction;
}
float GetDistanceSquaredFromLine2D(const Vec2& reference_pos, const Vec2& point_on_line, const Vec2& another_point_on_line)
{
//essential mathematics 3rd ed
const Vec2 origin_to_point = reference_pos - point_on_line;
const Vec2 line_direction = another_point_on_line - point_on_line;
const float line_mag_sq = DotProduct(line_direction, line_direction);
const float o2p_line_mag_sq = DotProduct(origin_to_point, origin_to_point);
const float projection = DotProduct(origin_to_point, line_direction);
return o2p_line_mag_sq - projection * projection / line_mag_sq;
}
Vec2 GetClosestPointOnLineSegment2D(const Vec2& reference_pos, const Vec2& line_start, const Vec2& line_end)
{
// essential mathematics 3rd ed
const Vec2 origin_to_point = reference_pos - line_start;
const Vec2 line_direction = line_end - line_start;
const float projection = DotProduct(origin_to_point, line_direction);
if( projection <= 0.0f )
{
return line_start;
}
const float line_mag_sq = DotProduct(line_direction, line_direction);
if(projection >= line_mag_sq)
{
return line_end;
}
return line_start + (projection/line_mag_sq) * line_direction;
}
float GetDistanceSquaredFromLineSegment2D(const Vec2& reference_pos, const Vec2& line_start, const Vec2& line_end)
{
// essential mathematics 3rd ed
const Vec2 origin_to_point = reference_pos - line_start;
const Vec2 line_direction = line_end - line_start;
float projection = DotProduct(origin_to_point, line_direction);
if( projection <= 0.0f )
{
return DotProduct(origin_to_point, origin_to_point);
}
const float line_mag_sq = DotProduct(line_direction, line_direction);
if(projection >= line_mag_sq)
{
return DotProduct(origin_to_point, origin_to_point) - 2.0f * projection + line_mag_sq;
}
return DotProduct(origin_to_point, origin_to_point) - projection * projection / line_mag_sq;
}
void GetClosestPointsFromTwo2DLines(Vec2& point_1, Vec2& point_2, const Vec2& line_1_start,
const Vec2& line_1_end, const Vec2& line_2_start, const Vec2& line_2_end)
{
// essential mathematics 3rd ed
const Vec2 w_0 = line_1_start - line_2_start;
const Vec2 line_1_direction = line_1_end - line_1_start;
const Vec2 line_2_direction = line_2_end - line_2_start;
const float a = DotProduct(line_1_direction, line_1_direction);
const float b = DotProduct(line_1_direction, line_2_direction);
const float c = DotProduct(line_2_direction, line_2_direction);
const float d = DotProduct(line_1_direction, w_0);
const float e = DotProduct(line_2_direction, w_0);
const float denom = a*c - b*b;
if(denom == 0.0f)
{
point_1 = line_1_start;
point_2 = line_2_start + (e/c) * line_2_direction;
}
else
{
point_1 = line_1_start + ((b*e - c*d)/denom)*line_1_direction;
point_2 = line_2_start + ((a*e - b*d)/denom)*line_2_direction;
}
}
void GetClosestPointsFromTwo2DLineSegments(Vec2& point_1, Vec2& point_2, const Vec2& line_1_start,
const Vec2& line_1_end, const Vec2& line_2_start, const Vec2& line_2_end)
{
// compute intermediate parameters
Vec2 w_0 = line_1_start - line_2_start;
const Vec2 line_1_direction = line_1_end - line_1_start;
const Vec2 line_2_direction = line_2_end - line_2_start;
const float a = DotProduct(line_1_direction, line_1_direction);
const float b = DotProduct(line_1_direction, line_2_direction);
const float c = DotProduct(line_2_direction, line_2_direction);
const float d = DotProduct(line_1_direction, w_0);
const float e = DotProduct(line_2_direction, w_0);
const float denom = a*c - b*b;
// parameters to compute s_c, t_c
float s_c, t_c;
float sn, sd, tn, td;
// if denom is zero, try finding closest point on segment1 to origin0
if ( denom == 0.0f )
{
// clamp s_c to 0
sd = td = c;
sn = 0.0f;
tn = e;
}
else
{
// clamp s_c within [0,1]
sd = td = denom;
sn = b*e - c*d;
tn = a*e - b*d;
// clamp s_c to 0
if (sn < 0.0f)
{
sn = 0.0f;
tn = e;
td = c;
}
// clamp s_c to 1
else if (sn > sd)
{
sn = sd;
tn = e + b;
td = c;
}
}
// clamp t_c within [0,1]
// clamp t_c to 0
if (tn < 0.0f)
{
t_c = 0.0f;
// clamp s_c to 0
if ( -d < 0.0f )
{
s_c = 0.0f;
}
// clamp s_c to 1
else if ( -d > a )
{
s_c = 1.0f;
}
else
{
s_c = -d/a;
}
}
// clamp t_c to 1
else if (tn > td)
{
t_c = 1.0f;
// clamp s_c to 0
if ( (-d+b) < 0.0f )
{
s_c = 0.0f;
}
// clamp s_c to 1
else if ( (-d+b) > a )
{
s_c = 1.0f;
}
else
{
s_c = (-d+b)/a;
}
}
else
{
t_c = tn/td;
s_c = sn/sd;
}
// compute closest points
point_1 = line_1_start + s_c*line_1_direction;
point_2 = line_2_start + t_c*line_2_direction;
}
float GetDistanceSquaredFromTwo2DLineSegments(float& length_sq_from_l1_start, float& length_sq_from_l2_start,
const Vec2& line_1_start, const Vec2& line_1_end, const Vec2& line_2_start, const Vec2& line_2_end)
{
// compute intermediate parameters
const Vec2 w_0 = line_1_start - line_2_start;
const Vec2 line_1_direction = line_1_end - line_1_start;
const Vec2 line_2_direction = line_2_end - line_2_start;
const float a = DotProduct(line_1_direction, line_1_direction);
const float b = DotProduct(line_1_direction, line_2_direction);
const float c = DotProduct(line_2_direction, line_2_direction);
const float d = DotProduct(line_1_direction, w_0);
const float e = DotProduct(line_2_direction, w_0);
const float denom = a*c - b*b;
// parameters to compute s_c, t_c
float sn, sd, tn, td;
// if denom is zero, try finding closest point on segment1 to origin0
if ( denom == 0.0f )
{
// clamp s_c to 0
sd = td = c;
sn = 0.0f;
tn = e;
}
else
{
// clamp s_c within [0,1]
sd = td = denom;
sn = b*e - c*d;
tn = a*e - b*d;
// clamp s_c to 0
if (sn < 0.0f)
{
sn = 0.0f;
tn = e;
td = c;
}
// clamp s_c to 1
else if (sn > sd)
{
sn = sd;
tn = e + b;
td = c;
}
}
// clamp t_c within [0,1]
// clamp t_c to 0
if (tn < 0.0f)
{
length_sq_from_l2_start = 0.0f;
// clamp s_c to 0
if ( -d < 0.0f )
{
length_sq_from_l1_start = 0.0f;
}
// clamp s_c to 1
else if ( -d > a )
{
length_sq_from_l1_start = 1.0f;
}
else
{
length_sq_from_l1_start = -d/a;
}
}
// clamp t_c to 1
else if (tn > td)
{
length_sq_from_l2_start = 1.0f;
// clamp s_c to 0
if ( (-d+b) < 0.0f )
{
length_sq_from_l1_start = 0.0f;
}
// clamp s_c to 1
else if ( (-d+b) > a )
{
length_sq_from_l1_start = 1.0f;
}
else
{
length_sq_from_l1_start = (-d+b)/a;
}
}
else
{
length_sq_from_l2_start = tn/td;
length_sq_from_l1_start = sn/sd;
}
// compute difference vector and distance squared
const Vec2 wc = w_0 + length_sq_from_l1_start*line_1_direction - length_sq_from_l2_start*line_2_direction;
return DotProduct(wc,wc);
}
float GetDistanceSquaredFromTwo2DLines(const Vec2& line_1_start, const Vec2& line_1_end,
const Vec2& line_2_start, const Vec2& line_2_end)
{
const Vec2 w_0 = line_1_start - line_2_start;
const Vec2 line_1_direction = line_1_end - line_1_start;
const Vec2 line_2_direction = line_2_end - line_2_start;
const float a = DotProduct(line_1_direction, line_1_direction);
const float b = DotProduct(line_1_direction, line_2_direction);
const float c = DotProduct(line_2_direction, line_2_direction);
const float d = DotProduct(line_1_direction, w_0);
const float e = DotProduct(line_2_direction, w_0);
const float denom = a*c - b*b;
if( denom == 0.0f )
{
const Vec2 w_c = w_0 - (e/c) * line_2_direction;
return DotProduct(w_c, w_c);
}
const Vec2 w_c = w_0 + ((b*e - c*d)/denom) * line_1_direction - ((a*e - b*d)/denom)*line_2_direction;
return DotProduct(w_c, w_c);
}
//////////////////////////////////////////////////////////////////////////////////////////// | true |
d324f01ca15156fc320605e1453fd00ba307ecc8 | C++ | Soma247/ubuntu_projects | /cppprojects/concepts.cpp | UTF-8 | 294 | 3.203125 | 3 | [] | no_license | #include <concepts>
#include <iostream>
template<typename T>
concept my_integral=std::integral<T>;
template <my_integral I>
void fn(const I& data){
std::cout<<data<<" is integral"<<std::endl;
}
int main(int argc, char**argv){
int i{2};
fn(i);
//fn(std::string{});
return 0;
}
| true |
05e74e5449747d88c0a9bf46c3f6e526a752cfff | C++ | Sun-CX/reactor | /netc/EpollPoller.cpp | UTF-8 | 3,214 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by suncx on 2020/8/17.
//
#include "EpollPoller.h"
#include "Channel.h"
#include "Ext.h"
#include "ConsoleStream.h"
#include <sys/epoll.h>
#include <unistd.h>
#include <cassert>
#include <cstring>
using reactor::core::Timestamp;
using reactor::net::EpollPoller;
using std::chrono::system_clock;
const int EpollPoller::NEW = -1;
const int EpollPoller::ADD = 0;
EpollPoller::EpollPoller(EventLoop *loop) :
Poller(loop),
epoll_fd(epoll_open()),
events() {
events.reserve(16);
}
EpollPoller::~EpollPoller() {
epoll_close(epoll_fd);
}
Timestamp EpollPoller::poll(Channels &active_channels, int milliseconds) {
int ready_events = ::epoll_wait(epoll_fd, events.data(), events.capacity(), milliseconds);
Timestamp ts = system_clock::now();
if (unlikely(ready_events < 0)) {
if (errno != EINTR)
RC_FATAL << "epoll(" << epoll_fd << ") wait error: " << ::strerror(errno);
} else if (ready_events == 0) {
RC_WARN << "epoll(" << epoll_fd << ") wait timeout, nothing happened";
} else {
fill_active_channels(active_channels, ready_events);
// FIXME: optimize enlarge capacity strategy.
if (ready_events == events.capacity())
events.reserve(events.capacity() << 1u);
}
return ts;
}
void EpollPoller::fill_active_channels(Channels &active_channels, int num_events) const {
for (int i = 0; i < num_events; ++i) {
auto channel = static_cast<Channel *>(events[i].data.ptr);
channel->set_revents(events[i].events);
active_channels.push_back(channel);
}
}
void EpollPoller::update(Channel *channel, int operation) {
epoll_event evt;
evt.events = channel->get_events();
evt.data.ptr = channel;
int fd = channel->get_fd();
if (unlikely(::epoll_ctl(epoll_fd, operation, fd, &evt) < 0))
RC_FATAL << "epoll(" << epoll_fd << ") ctl error: " << ::strerror(errno);
}
void EpollPoller::update_channel(Channel *channel) {
Poller::assert_in_loop_thread();
int idx = channel->get_index();
int fd = channel->get_fd();
switch (idx) {
case NEW:
assert(channel_map.find(fd) == channel_map.cend());
channel_map[fd] = channel;
update(channel, EPOLL_CTL_ADD);
channel->set_index(ADD);
break;
case ADD:
assert(channel_map.find(fd) != channel_map.cend());
update(channel, EPOLL_CTL_MOD);
break;
default:
RC_FATAL << "invalid channel state";
}
}
void EpollPoller::remove_channel(Channel *channel) {
Poller::assert_in_loop_thread();
assert(channel->get_index() == ADD);
update(channel, EPOLL_CTL_DEL);
int fd = channel->get_fd();
auto n = channel_map.erase(fd);
assert(n == 1);
channel->set_index(NEW);
}
int EpollPoller::epoll_open() const {
int fd;
if (unlikely((fd = ::epoll_create1(EPOLL_CLOEXEC)) < 0))
RC_FATAL << "epoll create error: " << ::strerror(errno);
return fd;
}
void EpollPoller::epoll_close(int fd) const {
if (unlikely(::close(fd) < 0))
RC_FATAL << "close epoll(" << fd << ") error: " << ::strerror(errno);
}
| true |
c9668183e0777cb3844b981aadc7fa61daeb22be | C++ | beefeather/clean-sources-cpp | /examples/GeneralNumberSystems/Graph/roger/MATH/Graphs/LinkedNode.cpp | UTF-8 | 4,103 | 2.90625 | 3 | [] | no_license | namespace MATH::Graphs;
/**
* @brief Node linked representaion
* @details Evry Node join to eachother by edges.
*
* @tparam Weight_t the weight type of the graph
* @tparam Label_t the Label type of the graph
* @tparam Tag_t the tag type of the graph
*
* @see MATH::Graphs::Node
* @see MATH::Graphs::Edge
*
* @todo refactor, every function are inlnine
*/
template<class Weight_t, class Label_t = Weight_t, class Tag_t = Weight_t>
class LinkedNode: public Node<Weight_t, Label_t, Tag_t> {
protected:
/**
* @brief connected edges
*/
std::vector<Edge<Weight_t, Label_t, Tag_t>*> _edges;
public:
/**
* @brief simple constructor
* @param label the label
* @param weight the weight of the node
* @param tag sepcial information for the node
*/
explicit LinkedNode(Label_t label, Weight_t weight = Weight_t(), Tag_t tag =
Tag_t()) :
Node<Weight_t, Label_t, Tag_t>(label, weight, tag) {
}
/**
* @brief copy constructor
* @param other the other nod
*/
LinkedNode(const LinkedNode& other) :
Node<Weight_t, Label_t, Tag_t>(other) {
for (unsigned i = 0; i < other._edges.size(); ++i) {
_edges.push_back(new Edge<Weight_t, Label_t, Tag_t>(*other._edges[i]));
}
}
/**
* @brief Destructor
* @warning this function delete the all of edges, which,
* go from here
*/
virtual ~LinkedNode() {
for (unsigned i = 0; i < _edges.size(); ++i) {
_edges[i]->setBegin((Node<Weight_t, Label_t, Tag_t>*) 0);
delete _edges[i];
}
_edges.clear();
}
/**
* @brief getter for edges of the node
* @return the outgoing edges
*/
std::vector<Edge<Weight_t, Label_t, Tag_t>*>* getEdges() {
return &_edges;
}
/**
* @brief Getter for a specific edge
* @param nodeLabel the label of the node, which
* is connected by edge
* @return the connected edge, or 0 if it not exists
*/
Edge<Weight_t, Label_t, Tag_t>* getEdge(const Label_t& nodeLabel) {
for (unsigned i = 0; i < _edges.size(); ++i) {
if (_edges[i]->getEnd()->getLabel() == nodeLabel)
return _edges[i];
}
return 0;
}
/**
* @brief the outgoing degree of this node
* @return the degree
*/
unsigned getEdgesCount() const {
return _edges.size();
}
/**
* @brief the outgoing degree of this node
* @return the degree
*/
unsigned getDegree() const {
return _edges.size();
}
/**
* @brief getter for a spcific neightborn
* @param i the id of edge
* @return the i-th edges end node
*/
const LinkedNode<Weight_t, Label_t, Tag_t>* getNeigthborn(unsigned i) const {
const LinkedNode<Weight_t, Label_t, Tag_t>* ret =
dynamic_cast<const LinkedNode<Weight_t, Label_t, Tag_t>*>(_edges[i]->getEnd());
return ret;
}
/**
* @brief getter for a spcific neightborn
* @param i the id of edge
* @return the i-th edges end node
*/
LinkedNode<Weight_t, Label_t, Tag_t>* getNeigthborn(unsigned i) {
return dynamic_cast<LinkedNode<Weight_t, Label_t, Tag_t>*>(_edges[i]->getEnd());
}
/**
* @brief connect a new node
* @param node the new node
* @param weight the weight of the edge
*/
void addNode(LinkedNode<Weight_t, Label_t, Tag_t>* node,
const Weight_t& weight = Weight_t()) {
_edges.push_back(new Edge<Weight_t, Label_t, Tag_t>(this, node, weight));
}
/**
* @brief print function
* @param os output stream
* @param node the node
* @return the output stream for chainging
*/
friend std::ostream& operator<<(std::ostream& os,
const LinkedNode<Weight_t, Label_t, Tag_t> node) {
node.print(os);
return os;
}
protected:
/**
* @brief print function
* @param os the stream
*/
virtual void print(std::ostream& os) const {
Node<Weight_t, Label_t, Tag_t>::print(os);
os << "\tNeightborns:" << std::endl;
for (unsigned i = 0; i < _edges.size(); ++i) {
os << "\t\t" << _edges[i]->getEnd()->getLabel() << ", "
<< _edges[i]->getWeight() << ", " << _edges[i]->getTag() << std::endl;
}
}
};
| true |
d0ad25e5d99ab333445b02fdef455311166b8bff | C++ | ls-cwi/heinz | /src/preprocessing/posedge.h | UTF-8 | 2,874 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
* posedge.h
*
* Created on: 14-jan-2013
* Author: M. El-Kebir
*/
#ifndef POSEDGE_H
#define POSEDGE_H
#include <lemon/core.h>
#include <string>
#include <vector>
#include <set>
#include "rule.h"
namespace nina {
namespace mwcs {
template<typename GR,
typename WGHT = typename GR::template NodeMap<double> >
class PosEdge : public Rule<GR, WGHT>
{
public:
typedef GR Graph;
typedef WGHT WeightNodeMap;
typedef Rule<GR, WGHT> Parent;
typedef typename Parent::NodeMap NodeMap;
typedef typename Parent::NodeSet NodeSet;
typedef typename Parent::NodeSetIt NodeSetIt;
typedef typename Parent::NodeSetMap NodeSetMap;
typedef typename Parent::DegreeNodeMap DegreeNodeMap;
typedef typename Parent::DegreeNodeSetVector DegreeNodeSetVector;
typedef typename Parent::LabelNodeMap LabelNodeMap;
TEMPLATE_GRAPH_TYPEDEFS(Graph);
using Parent::remove;
using Parent::merge;
PosEdge();
virtual ~PosEdge() {}
virtual int apply(Graph& g,
const NodeSet& rootNodes,
LabelNodeMap& label,
WeightNodeMap& score,
NodeSetMap& mapToPre,
NodeSetMap& preOrigNodes,
NodeSetMap& neighbors,
int& nNodes,
int& nArcs,
int& nEdges,
DegreeNodeMap& degree,
DegreeNodeSetVector& degreeVector,
double& LB);
virtual std::string name() const { return "PosEdge"; }
};
template<typename GR, typename WGHT>
inline PosEdge<GR, WGHT>::PosEdge()
: Parent()
{
}
template<typename GR, typename WGHT>
inline int PosEdge<GR, WGHT>::apply(Graph& g,
const NodeSet& rootNodes,
LabelNodeMap& label,
WeightNodeMap& score,
NodeSetMap& mapToPre,
NodeSetMap& preOrigNodes,
NodeSetMap& neighbors,
int& nNodes,
int& nArcs,
int& nEdges,
DegreeNodeMap& degree,
DegreeNodeSetVector& degreeVector,
double& LB)
{
for (EdgeIt e(g); e != lemon::INVALID; ++e)
{
Node u = g.u(e);
Node v = g.v(e);
if (score[u] >= 0 && score[v] >= 0
&& rootNodes.find(u) == rootNodes.end()
&& rootNodes.find(v) == rootNodes.end())
{
merge(g, label, score,
mapToPre, preOrigNodes, neighbors,
nNodes, nArcs, nEdges,
degree, degreeVector, u, v, LB);
return 1;
}
}
return 0;
}
} // namespace mwcs
} // namespace nina
#endif // POSEDGE_H
| true |
e96c1ccca92001e4c25d8382f8a883a0b58aa638 | C++ | matarms/LibCDS4 | /DS4.cpp | UTF-8 | 2,857 | 2.625 | 3 | [] | no_license | #include "DS4.h"
DS4::DS4(){
rc.open("/dev/input/js0");
if(rc == NULL)
cerr << "Erro ao abrir evento do controle\n";
but = new Buttons [11]; //Cria os botões a serem usados
}
DS4::DS4(string local){
rc.open(local.c_str());
if(rc == NULL)
cerr << "Erro ao abrir evento do controle\n";
}
int DS4::buttonPos(int button){
switch(button){
case SQUARE: return SQUAREPOS;
case CROSS: return CROSSPOS;
case CIRCLE: return CIRCLEPOS;
case TRIANGLE: return TRIANGLEPOS;
case UP: return UPPOS;
case DOWN: return DOWNPOS;
case LEFT: return LEFTPOS;
case RIGHT: return RIGHTPOS;
case SHARE: return SHAREPOS;
case OPTIONS: return OPTIONSPOS;
case PSN: return PSNPOS;
}
}
bool DS4::DS4UpdateState(){
if(!(rc.read(buff, sizeof(buff)))) //Lê os dados do controle
return 0;
//////DEBUG/////
/*for(int i=0; i<8; i++)
cout << (int)buff[i] << " ";
cout << endl;*/
int type = buff[6];
int value = buff[7];
int status = buff[4];
if(type == 1){ //Botões Comuns
but[buttonPos(value)].setStatus(status);
}
else if(type == 2){ //D-PAD
if(value == 6){ //D-PAD horizontal
if((int)buff[4] == 1 && (int)buff[5] == -128)
but[buttonPos(LEFT)].setStatus(PRESSED);
else if((int)buff[4] == -1 && (int)buff[5] == 127)
but[buttonPos(RIGHT)].setStatus(PRESSED);
else{
but[buttonPos(LEFT)].setStatus(NOTPRESSED);
but[buttonPos(RIGHT)].setStatus(NOTPRESSED);
}
}
else if(value == 7){ //D-PAD vertical
if((int)buff[4] == 1 && (int)buff[5] == -128)
but[buttonPos(UP)].setStatus(PRESSED);
else if((int)buff[4] == -1 && (int)buff[5] == 127)
but[buttonPos(DOWN)].setStatus(PRESSED);
else{
but[buttonPos(UP)].setStatus(NOTPRESSED);
but[buttonPos(DOWN)].setStatus(NOTPRESSED);
}
}
}
return 1;
}
bool DS4::checkIfPressed(int button){
switch(button){
case SQUARE: return but[SQUAREPOS].getStatus();
case CROSS: return but[CROSSPOS].getStatus();
case CIRCLE: return but[CIRCLEPOS].getStatus();
case TRIANGLE: return but[TRIANGLEPOS].getStatus();
case UP: return but[UPPOS].getStatus();
case DOWN: return but[DOWNPOS].getStatus();
case LEFT: return but[LEFTPOS].getStatus();
case RIGHT: return but[RIGHTPOS].getStatus();
case SHARE: return but[SHAREPOS].getStatus();
case OPTIONS: return but[OPTIONSPOS].getStatus();
case PSN: return but[PSNPOS].getStatus();
}
return 0;
}
DS4::~DS4(){
delete [] but;
rc.close();
} | true |
78ff002002baa6c18535e7dacd1605d668e306cb | C++ | Chao-Jiang/fiberCodes | /R/blocks.cpp | UTF-8 | 1,092 | 2.953125 | 3 | [] | no_license | /* Author: Ian Leifer <ianleifer93@gmail.com> */
#include "blocks.h"
#include <iostream>
#include <fstream>
bool BuildingBlock::addNode(int id, int color) {
for(int i = 0; i < nodes.size(); i++) {
if(nodes[i] == id) {return 0;}
}
nodes.push_back(id);
if(color != -1) {
if(color >= colors.size()) {
colors.resize(color + 1);
}
colors[color]++;
}
return 1;
}
bool BuildingBlock::isAddableColor(int color) {
if(color >= colors.size()) {
return 0;
}
if(colors[color] > 1) {
return 1;
} else {
return 0;
}
}
void BuildingBlock::print(string filename) {
ofstream buildingBlockFile;
buildingBlockFile.open(filename, ofstream::out | ofstream::app);
/*for(int i = 0; i < groupoidIds.size(); i++) {
fiberFile << i << "\t" << groupoidIds[i] << endl;
}*/
buildingBlockFile << id << ":\t";
for(int i = 0; i < nodes.size() - 1; i++) {
buildingBlockFile << nodes[i] << ", ";
}
buildingBlockFile << nodes[nodes.size() - 1] << endl;
buildingBlockFile.close();
/*cout << "Colors:" << endl;
for(int i = 0; i < colors.size(); i++) {
cout << i << ":\t" << colors[i] << endl;
}*/
}
| true |
c906cb92d68d00f24972ab97bb0586be99bf38f4 | C++ | sdycxx2279/myAlgorithm | /357.cpp | UTF-8 | 502 | 3.140625 | 3 | [] | no_license | //
//@author Xiao Xu
//@create 2018-12-05 21:10
//Count Numbers with Unique Digits
//
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(!n)
return 1;
int a = 1, b = 10, c = 9;
for(int i = 1; i < n; i++){
int temp = b;
b = (b - a) * c + b;
c--;
a = temp;
}
return b;
}
};
int main(){
Solution s;
return 0;
} | true |
96a8b962cdfcf24dd86e5cbb9eaefeabd8c50343 | C++ | aqing1987/s-lang-cpp | /beginning-c++-through-game-programming-4th/chapter1/game_over2.cpp | UTF-8 | 175 | 2.875 | 3 | [] | no_license | // Game over 2.0
// Demonstrates a using directive
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
cout << "Game Over!" << endl;
return 0;
}
| true |
3ae16cb430076c8d63cf2315506cd30050aae0d3 | C++ | jaybrecht/ros_collection_robot | /test/polygon_test.cpp | UTF-8 | 1,255 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <gtest/gtest.h>
#include "../include/polygon.h"
TEST(calculateCentroid,simpleCentroidTest) {
std::vector <geometry_msgs::Point> vertices;
geometry_msgs::Point point1;
point1.x = 0;
point1.y = 0;
geometry_msgs::Point point2;
point2.x = 2;
point2.y = 0;
geometry_msgs::Point point3;
point3.x = 1;
point3.y = 2;
vertices.push_back(point1);
vertices.push_back(point2);
vertices.push_back(point3);
Polygon polygon(vertices);
EXPECT_NEAR(polygon.getCentroid().x,1,0.01);
EXPECT_NEAR(polygon.getCentroid().y,0.66,0.05);
}
TEST(insideObject,testPointEnclosure) {
std::vector <geometry_msgs::Point> vertices;
geometry_msgs::Point point1;
point1.x = 0;
point1.y = 0;
geometry_msgs::Point point2;
point2.x = 2;
point2.y = 0;
geometry_msgs::Point point3;
point3.x = 1;
point3.y = 2;
vertices.push_back(point1);
vertices.push_back(point2);
vertices.push_back(point3);
Polygon polygon(vertices);
geometry_msgs::Point check_point;
check_point.x = 1;
check_point.y = 0.1;
EXPECT_TRUE(polygon.insideObject(check_point));
check_point.x = 3;
check_point.y = 2;
EXPECT_FALSE(polygon.insideObject(check_point));
} | true |
d271858a739b00af8a878a5a7330b971fc312d24 | C++ | souchea/snippets | /cpp/multiple_template.cpp | UTF-8 | 205 | 2.75 | 3 | [] | no_license | template<typename T>
struct Pair1 {
Pair1(T aa, T bb)
: a(aa), b(bb) {}
T a;
T b;
};
template<typename T, typename U>
struct Pair2 {
Pair2(T aa, U bb)
: a(aa), b(bb) {}
T a;
U b;
};
| true |
b2522c0a71881602a1e529a0243773d76a37af61 | C++ | fofcn/vip | /common/Thread.h | UTF-8 | 731 | 2.578125 | 3 | [] | no_license | //
// Created by jiquanxi on 17-9-20.
//
#ifndef VIP_THREAD_H
#define VIP_THREAD_H
#include <iostream>
#include <pthread.h>
#include "Runnable.h"
class IThread
{
public:
virtual bool start() = 0;
virtual void stop() = 0;
virtual void stop(bool force) = 0;
virtual void join() = 0;
virtual void join(long milliSecs) = 0;
};
class Thread : public IThread
{
public:
Thread();
Thread(IRunnable *target);
virtual bool start();
virtual void stop();
virtual void stop(bool force);
virtual void join();
virtual void join(long milliSecs);
private:
static void *callback(void *arg);
private:
IRunnable *target;
pthread_t handle;
bool started;
};
#endif //VIP_THREAD_H
| true |
a705f1d9449d34578b2ac95bf9c24fbc8245df6c | C++ | spatel98/Project1 | /sectiontoken.cpp | UTF-8 | 379 | 2.765625 | 3 | [] | no_license | /*
* sectiontoken.cpp
*
* Created on: Sep 19, 2018
* Author: sawan
*/
#include "sectiontoken.h"
#include <string>
using namespace std;
SectionToken::SectionToken(string str, secType_t tempType){
section = str;
type = tempType;
}
secType_t SectionToken:: getType() const{
return type;
}
string SectionToken:: getText(){
return section;
}
| true |
f82301283394fa4ff32124e170b80985c0a862d3 | C++ | HallWoodZhang/Compiler | /C-Compiler/compile.cpp | UTF-8 | 95,045 | 2.578125 | 3 | [] | no_license | #include "compile.h"
vector<string> check_list;//给出原来四元式的位置即可找到应该跳转的标记
vector<arr_list>Arr_list;
extern vector<ainfl> AINFL;
extern vector<rinfl> RINFL;
targe data;//汇编语言序列
targe code;
targe cout_code;
targe* data_pointer;
targe* data_end;//链表最后一个元素的指针
stack<targe*> backfilling;
int jump_label = 0;
int cout_label = 0;//打印函数标记
int func_label = 0;//子程序标记
int inter_pro_pointer;//中间代码
string the_first_data_label;
//保存子程序名称
vector<string>functionName;
void data_new_node(targe* temp){
data_end->next = temp;
data_end = temp;
}
string itos(int num){
ostringstream ss;
ss << num;
string result(ss.str());
return result;
}
void DSEG(){
int int_num, float_num, char_num,arr_num,struct_num;
struct_num=0;
arr_num=0;
int_num = 0;
float_num = 0;
char_num = 0;
for (int i = 0; i < SYNBL.size(); i++){
switch (SYNBL[i].type){
case 0:{char_num++; break; }
case 1:{int_num++; break; }
case 2:{float_num++; break; }
default:break;
}
switch (SYNBL[i].cat){
case 5:{
arr_list temp;
temp.name=Id[SYNBL[i].name.value];
temp.size=AINFL[arr_num].up-AINFL[arr_num].low+1;
arr_num++;
Arr_list.push_back(temp);
break;
}
case 7:{
arr_list temp;
temp.name=Id[SYNBL[i].name.value];
for(int i=0;i<RINFL.size();i++)
{
if(RINFL[i].num==SYNBL[i].addr)
struct_num++;
if(RINFL[i].num>SYNBL[i].addr)
break;
}
temp.size=struct_num;
struct_num=0;
Arr_list.push_back(temp);
break;
}
case 8:{
arr_list temp;
temp.name=Id[SYNBL[i].name.value];
for(int i=0;i<RINFL.size();i++)
{
if(RINFL[i].num==AINFL[arr_num].ctp)
struct_num++;
if(RINFL[i].num>AINFL[arr_num].ctp)
break;
}
temp.size=struct_num;
arr_num++;
struct_num=0;
Arr_list.push_back(temp);
break;
}
default:break;
}
// cout<<i<<endl;
}
targe* last_data;
last_data = &data;
for(int i=0;i<Arr_list.size();i++){
data_pointer = new targe;
data_pointer->cw = Arr_list[i].name;
data_pointer->arg1 = "DW";
data_pointer->arg2 =itos (Arr_list[i].size) + " DUP(0)";
data_pointer->flag = 2;
data_pointer->next = NULL;
last_data->next = data_pointer;
last_data = data_pointer;
}
for (int i = 0;i < TYPEL.size(); i++){
if(TYPEL[i].lenth==0)
continue;
else{
data_pointer = new targe;
data_pointer->cw = TYPEL[i].name;
switch (TYPEL[i].lenth){
case 1:data_pointer->arg1 = "DB"; break;
case 2:data_pointer->arg1 = "DW"; break;
}
switch (i){
case 0:data_pointer->arg2 = itos(char_num) + " DUP(0)"; break;
case 1:data_pointer->arg2 = itos(int_num) + " DUP(0)"; break;
case 2:data_pointer->arg2 = itos(float_num) + " DUP(0)"; break;
}
if (i == 0){
the_first_data_label = data_pointer->cw;
}
data_pointer->flag = 2;
data_pointer->next = NULL;
last_data->next = data_pointer;
last_data = data_pointer;
}
}
data_pointer = new targe;
data_pointer->cw = "TEMP";
data_pointer->arg1 = "DW";
data_pointer->arg2 = itos(temp_num) + " DUP(0)";
data_pointer->flag = 2;
data_pointer->next = NULL;
last_data->next = data_pointer;
last_data = data_pointer;
data_pointer = new targe;
data_pointer->cw = "CONST";
data_pointer->arg1 = "DW";
data_pointer->arg2 = ConstNum[0];
for (int i = 1; i < ConstNum.size(); i++){
data_pointer->arg2 = data_pointer->arg2 + "," + ConstNum[i];
}
data_pointer->flag = 2;
data_pointer->next = NULL;
last_data->next = data_pointer;
last_data = data_pointer;
}
void cout_compile(){
targe* code_pointer;
targe* code_last;
code_last = &cout_code;
code_pointer = new targe;
code_pointer->cw = "MOV";
code_pointer->arg1 = "SI";
code_pointer->arg2 = "10";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "MOV";
code_pointer->arg1 = "CX";
code_pointer->arg2 = "0";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->label="next1";
code_pointer->cw = "MOV";
code_pointer->arg1 = "DX";
code_pointer->arg2 = "0";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "DIV";
code_pointer->arg1 = "SI";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "PUSH";
code_pointer->arg1 = "DX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "INC";
code_pointer->arg1 = "CX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "CMP";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "0";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "JNZ";
code_pointer->arg1 = "next1";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->label="next2";
code_pointer->cw = "POP";
code_pointer->arg1 = "DX";
code_pointer->arg2 = "0";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "ADD";
code_pointer->arg1 = "DL";
code_pointer->arg2 = "30H";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "MOV";
code_pointer->arg1 = "AH";
code_pointer->arg2 = "02H";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "INT";
code_pointer->arg1 = "21H";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "LOOP";
code_pointer->arg1 = "next2";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "RET";
code_pointer->arg1 = "";
code_pointer->arg2 = "";
code_pointer->flag = 0;
code_pointer->next = &code;
code_last->next = code_pointer;
code_last = code_pointer;
}
void getFunctionName(){
for(int i=0;i<SYNBL.size();i++)
{
if(SYNBL[i].cat==1)
{
string funcStr=Id[SYNBL[i].name.value];
transform(funcStr.begin(),funcStr.end(),funcStr.begin(),::toupper);
functionName.push_back(funcStr);
}
}
}
targe* creatFunction(targe* code_last){
targe* code_pointer;
int funcArea=1;
for (;inter_pro_pointer < mainStartId; inter_pro_pointer++){
if(funcArea==1)
{
if (inter_pro[inter_pro_pointer].label != -1){
if (inter_pro[inter_pro_pointer].op.code == 11 || //是算术运算
inter_pro[inter_pro_pointer].op.code == 12 ||
inter_pro[inter_pro_pointer].op.code == 13 ||
inter_pro[inter_pro_pointer].op.code == 14 ||
inter_pro[inter_pro_pointer].op.code == 67 ||
inter_pro[inter_pro_pointer].op.code == 69
){
//读入第一个操作数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//读入第二个操作数
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].arg2.code){
case 0:{
code_pointer->cw = "MOV"; //mov Bx,int|char|float[i]
code_pointer->arg1 = "BX";
//TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].name
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg2.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov bx,const[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov bx,temp[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//进行计算
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].op.code){
case 11:{
code_pointer->cw = "ADD";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 12:{
code_pointer->cw = "SUB";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 13:{
code_pointer->cw = "MUL";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 14:{
code_pointer->cw = "XOR";
code_pointer->arg1 = "DX";
code_pointer->arg2 = "DX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "DIV";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 67:{
code_pointer->cw = "CMP";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 69:{
code_pointer->cw = "CMP";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
}
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
//赋值表达式
if (inter_pro[inter_pro_pointer].op.code == 17){
//读出到AX
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
//四元式是if
if (inter_pro[inter_pro_pointer].op.code == 6){
//读出到AX
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "AND";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "AX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "JZ";
code_pointer->arg1 = check_list[inter_pro[inter_pro_pointer].pointer];
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
//四元式是while
if (inter_pro[inter_pro_pointer].op.code == 5){
if (inter_pro[inter_pro_pointer].arg1.code != -1){//条件跳出部分
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "AND";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "AX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "JZ";
code_pointer->arg1 = check_list[inter_pro[inter_pro_pointer].pointer];
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
else {
code_pointer = new targe;
code_pointer->cw = "JMP";
code_pointer->arg1 = check_list[inter_pro[inter_pro_pointer].pointer];
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
}
//四元式cout
if (inter_pro[inter_pro_pointer].op.code == 34){
code_pointer = new targe; //取操作数
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
cout_label=1;
code_pointer = new targe;
code_pointer->cw = "CALL";
code_pointer->arg1 = "COUT";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//显示十进制数
}
if(inter_pro[inter_pro_pointer].op.code>=78&&inter_pro[inter_pro_pointer].op.code<=83){ //双目运算
//读入第一个操作数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//读入第二个操作数
switch (inter_pro[inter_pro_pointer].arg2.code){
case 0:{
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov Bx,int|char|float[i]
code_pointer->arg1 = "BX";
//TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].name
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg2.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].lenth) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 3:{
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov bx,const[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case -2:{
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov bx,temp[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
}
//进行计算
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].op.code){
case 78:{
code_pointer->cw = "INC";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 79:{
code_pointer->cw = "DEC";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 80:{
code_pointer->cw = "ADD";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 81:{
code_pointer->cw = "SUB";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 82:{
code_pointer->cw = "MUL";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 83:{
code_pointer->cw = "DIV";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
}
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{ //不应该有
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 71){ //数组取数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
code_pointer->cw = "MOV"; //mov ax,**[]
code_pointer->arg1 = "AX";
code_pointer->arg2 = Id[inter_pro[inter_pro_pointer].arg1.value] + "[" +
itos(stoi(ConstNum[inter_pro[inter_pro_pointer].arg2.value])*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 72){ //数组存数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos((inter_pro[inter_pro_pointer].arg1.value) * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = Id[inter_pro[inter_pro_pointer].res.value] + "[" +
itos(stoi(ConstNum[inter_pro[inter_pro_pointer].arg2.value])*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 75){ //数组取数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
int tp;
tp=0;
for(int i=0;i<i < SYNBL.size(); i++){
if(SYNBL[i].cat==7&&Id[SYNBL[i].name.value]==Id[inter_pro[inter_pro_pointer].arg1.value]){
for(int j=0;j<RINFL.size();j++)
{
if(RINFL[j].num==SYNBL[i].addr)
{
if(Id[RINFL[j].name.value]==Id[inter_pro[inter_pro_pointer].arg2.value])
break;
else
tp++;
}
if(RINFL[j].num>SYNBL[i].addr)
break;
}
break;
}
}
code_pointer->cw = "MOV"; //mov ax,**[]
code_pointer->arg1 = "AX";
code_pointer->arg2 = Id[inter_pro[inter_pro_pointer].arg1.value] + "[" +
itos(tp*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 74){ //数组存数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
int rtp;
rtp=0;
for(int i=0;i<i < SYNBL.size(); i++){
if(SYNBL[i].cat==7&&Id[SYNBL[i].name.value]==Id[inter_pro[inter_pro_pointer].res.value]){
for(int j=0;j<RINFL.size();j++)
{
if(RINFL[j].num==SYNBL[i].addr)
{
if(Id[RINFL[j].name.value]==Id[inter_pro[inter_pro_pointer].arg2.value])
break;
else
rtp++;
}
if(RINFL[j].num>SYNBL[i].addr)
break;
}
break;
}
}
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = Id[inter_pro[inter_pro_pointer].res.value] + "[" +
itos(rtp*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 76 ){ //函数 call
code_pointer = new targe;
code_pointer->cw = "CALL";
string funcStr=Id[inter_pro[inter_pro_pointer].res.value];
transform(funcStr.begin(),funcStr.end(),funcStr.begin(),::toupper);
code_pointer->arg1 = funcStr;
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 77){ //函数 ret
code_pointer = new targe;
code_pointer->cw = "RET";
code_pointer->arg1 = "";
code_pointer->arg2 = "";
code_pointer->flag = 0;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
funcArea=0;
inter_pro_pointer++;
break;
}
}
}
}
return code_last;
}
void CSEG(){
targe* code_pointer;
targe* code_last;
int inter_pro_pointer;//中间代码
inter_pro_pointer = mainStartId;
code_last = &code;
for(int i=0;i<mainStartId;i++){//宏定义目标代码生成
if(inter_pro[i].op.code==85){
code_pointer = new targe;
if (inter_pro[i].label == 2){
code_pointer->label = check_list[i];
}
switch (inter_pro[i].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[i].arg1.value * TYPEL[SYNBL[inter_pro[i].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[i].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[i].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[i].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[i].res.value * TYPEL[SYNBL[inter_pro[i].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[i].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[i].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
}
for (;inter_pro_pointer < inter_pro.size(); inter_pro_pointer++){
if (inter_pro[inter_pro_pointer].label != -1){
if (inter_pro[inter_pro_pointer].op.code == 11 || //是算术运算
inter_pro[inter_pro_pointer].op.code == 12 ||
inter_pro[inter_pro_pointer].op.code == 13 ||
inter_pro[inter_pro_pointer].op.code == 14 ||
inter_pro[inter_pro_pointer].op.code == 67 ||
inter_pro[inter_pro_pointer].op.code == 69
){
//读入第一个操作数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//读入第二个操作数
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].arg2.code){
case 0:{
code_pointer->cw = "MOV"; //mov Bx,int|char|float[i]
code_pointer->arg1 = "BX";
//TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].name
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg2.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov bx,const[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov bx,temp[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//进行计算
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].op.code){
case 11:{
code_pointer->cw = "ADD";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 12:{
code_pointer->cw = "SUB";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 13:{
code_pointer->cw = "MUL";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 14:{
code_pointer->cw = "XOR";
code_pointer->arg1 = "DX";
code_pointer->arg2 = "DX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "DIV";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 67:{
code_pointer->cw = "CMP";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 69:{
code_pointer->cw = "CMP";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
}
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
//赋值表达式
if (inter_pro[inter_pro_pointer].op.code == 17){
//读出到AX
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
//四元式是if
if (inter_pro[inter_pro_pointer].op.code == 6){
//读出到AX
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "AND";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "AX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "JZ";
code_pointer->arg1 = check_list[inter_pro[inter_pro_pointer].pointer];
cout<<"test:"<<check_list[inter_pro[inter_pro_pointer].pointer]<<endl;
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
//四元式是while
if (inter_pro[inter_pro_pointer].op.code == 5){
if (inter_pro[inter_pro_pointer].arg1.code != -1){//条件跳出部分
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "AND";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "AX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
code_pointer = new targe;
code_pointer->cw = "JZ";
code_pointer->arg1 = check_list[inter_pro[inter_pro_pointer].pointer];
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
else {
code_pointer = new targe;
code_pointer->cw = "JMP";
code_pointer->arg1 = check_list[inter_pro[inter_pro_pointer].pointer];
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
}
//四元式cout
if (inter_pro[inter_pro_pointer].op.code == 34){
code_pointer = new targe; //取操作数
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
cout_label=1;
code_pointer = new targe;
code_pointer->cw = "CALL";
code_pointer->arg1 = "COUT";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//显示十进制数
}
if(inter_pro[inter_pro_pointer].op.code == 71){ //数组取数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
code_pointer->cw = "MOV"; //mov ax,**[]
code_pointer->arg1 = "AX";
code_pointer->arg2 = Id[inter_pro[inter_pro_pointer].arg1.value] + "[" +
itos(stoi(ConstNum[inter_pro[inter_pro_pointer].arg2.value])*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 72){ //数组存数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = Id[inter_pro[inter_pro_pointer].res.value] + "[" +
itos(stoi(ConstNum[inter_pro[inter_pro_pointer].arg2.value])*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
<<<<<<< HEAD
=======
>>>>>>> 4e4bd0df6d4666beae81f3b5aab29e636ca75084
//读入第一个操作数
if(inter_pro[inter_pro_pointer].op.code == 75){ //数组取数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
int tp;
tp=0;
for(int i=0;i<i < SYNBL.size(); i++){
if(SYNBL[i].cat==7&&Id[SYNBL[i].name.value]==Id[inter_pro[inter_pro_pointer].arg1.value]){
for(int j=0;j<RINFL.size();j++)
{
if(RINFL[j].num==SYNBL[i].addr)
{
if(Id[RINFL[j].name.value]==Id[inter_pro[inter_pro_pointer].arg2.value])
break;
else
tp++;
}
if(RINFL[j].num>SYNBL[i].addr)
break;
}
break;
}
}
code_pointer->cw = "MOV"; //mov ax,**[]
code_pointer->arg1 = "AX";
code_pointer->arg2 = Id[inter_pro[inter_pro_pointer].arg1.value] + "[" +
itos(tp*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 74){ //数组存数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//结果存到res
int rtp;
rtp=0;
for(int i=0;i<i < SYNBL.size(); i++){
if(SYNBL[i].cat==7&&Id[SYNBL[i].name.value]==Id[inter_pro[inter_pro_pointer].res.value]){
for(int j=0;j<RINFL.size();j++)
{
if(RINFL[j].num==SYNBL[i].addr)
{
if(Id[RINFL[j].name.value]==Id[inter_pro[inter_pro_pointer].arg2.value])
break;
else
rtp++;
}
if(RINFL[j].num>SYNBL[i].addr)
break;
}
break;
}
}
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = Id[inter_pro[inter_pro_pointer].res.value] + "[" +
itos(rtp*2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code>=78&&inter_pro[inter_pro_pointer].op.code<=83){ //双目运算
//读入第一个操作数
code_pointer = new targe;
if (inter_pro[inter_pro_pointer].label == 2){
code_pointer->label = check_list[inter_pro_pointer];
}
switch (inter_pro[inter_pro_pointer].arg1.code){
case 0:{
code_pointer->cw = "MOV"; //mov ax,int|char|float[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg1.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg1.value].type].lenth) + "]";
break;
}
case 3:{
code_pointer->cw = "MOV"; //mov ax,const[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
case -2:{
code_pointer->cw = "MOV"; //mov ax,temp[i]
code_pointer->arg1 = "AX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg1.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
//读入第二个操作数
switch (inter_pro[inter_pro_pointer].arg2.code){
case 0:{
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov Bx,int|char|float[i]
code_pointer->arg1 = "BX";
//TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].name
code_pointer->arg2 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].arg2.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].arg2.value].type].lenth) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 3:{
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov bx,const[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "CONST[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case -2:{
code_pointer = new targe;
code_pointer->cw = "MOV"; //mov bx,temp[i]
code_pointer->arg1 = "BX";
code_pointer->arg2 = "TEMP[" + itos(inter_pro[inter_pro_pointer].arg2.value * 2) + "]";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
}
//进行计算
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].op.code){
case 78:{
code_pointer->cw = "INC";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 79:{
code_pointer->cw = "DEC";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 80:{
code_pointer->cw = "ADD";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 81:{
code_pointer->cw = "SUB";
code_pointer->arg1 = "AX";
code_pointer->arg2 = "BX";
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 82:{
code_pointer->cw = "MUL";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
case 83:{
code_pointer->cw = "DIV";
code_pointer->arg1 = "BX";
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
break;
}
}
//结果存到res
code_pointer = new targe;
switch (inter_pro[inter_pro_pointer].res.code){
case 0:{
code_pointer->cw = "MOV"; //mov int|char|float[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = the_first_data_label + "[" +
itos(inter_pro[inter_pro_pointer].res.value * TYPEL[SYNBL[inter_pro[inter_pro_pointer].res.value].type].lenth) + "]";
break;
}
case 3:{ //不应该有
code_pointer->cw = "MOV"; //mov const[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "CONST[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
case -2:{ //反正也不应该有
code_pointer->cw = "MOV"; //mov temp[i],ax
code_pointer->arg2 = "AX";
code_pointer->arg1 = "TEMP[" + itos(inter_pro[inter_pro_pointer].res.value * 2) + "]";
break;
}
}
code_pointer->flag = 2;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 76 ){ //函数 call
code_pointer = new targe;
code_pointer->cw = "CALL";
string funcStr=Id[inter_pro[inter_pro_pointer].res.value];
transform(funcStr.begin(),funcStr.end(),funcStr.begin(),::toupper);
code_pointer->arg1 = funcStr;
code_pointer->arg2 = "";
code_pointer->flag = 1;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
if(inter_pro[inter_pro_pointer].op.code == 77&& inter_pro[inter_pro_pointer].res.code!=(-1) ){ //函数 ret
code_pointer = new targe;
code_pointer->cw = "RET";
code_pointer->arg1 = "";
code_pointer->arg2 = "";
code_pointer->flag = 0;
code_pointer->next = NULL;
code_last->next = code_pointer;
code_last = code_pointer;
}
}
}
<<<<<<< HEAD
}
=======
}
>>>>>>> 4e4bd0df6d4666beae81f3b5aab29e636ca75084
void compilization(){
check_list.resize(inter_pro.size());
for (int i = 0; i < inter_pro.size(); i++){
if (inter_pro[i].label == 2){
check_list[i] = "t" + itos(jump_label);
jump_label++;
}
}
DSEG();
if(mainStartId!=0){
func_label=1;
}
CSEG();
ofstream ofile("D:\\QT/code/Compiler/C-Compiler/test.asm",ios::out);
targe * front,* back;
ofile << "DSEG\tSEGMENT" << endl;
back = &data;
while (back->next != NULL){
back = back->next;
ofile << "\t" + back->cw + "\t" + back->arg1 + "\t" + back->arg2 << endl;
}
ofile << "DSEG\tENDS" << endl;
ofile << "CSEG\tSEGMENT\n\tASSUME\tCS:CSEG,DS:DSEG" << endl;
if(func_label==1){
inter_pro_pointer = 0;
getFunctionName();
for(int i=0;i<functionName.size();i++)
{
ofile<<functionName[i]<<"\tPROC\tNEAR"<<endl;
targe func_code;
front=&func_code;
back=creatFunction(&func_code);
while (front->next != NULL){
front = front->next;
if (front->label.size() != 0){
ofile << front->label << ":";
}
switch (front->flag){
case 0:ofile << "\t" + front->cw << endl; break;
case 1:ofile << "\t" + front->cw + "\t" + front->arg1 << endl; break;
case 2:ofile << "\t" + front->cw + "\t" + front->arg1 << "," << front->arg2 << endl; break;
}
}
ofile<<functionName[i]<<"\tENDP"<<endl;
}
}
if(cout_label==1){
ofile << "COUT\tPROC\tNEAR"<<endl;
cout_compile();
front=&cout_code;
back=&code;
while (front->next != back){
front = front->next;
if (front->label.size() != 0){
ofile << front->label << ":";
}
switch (front->flag){
case 0:ofile << "\t" + front->cw << endl; break;
case 1:ofile << "\t" + front->cw + "\t" + front->arg1 << endl; break;
case 2:ofile << "\t" + front->cw + "\t" + front->arg1 << "," << front->arg2 << endl; break;
}
}
ofile << "COUT\tENDP"<<endl;
front=&code;
}
else
front = &code;
ofile << "start:\tMOV\tAX,DSEG\n\tMOV\tDS,AX" << endl;
while (front->next != NULL){
front = front->next;
if (front->label.size() != 0){
ofile << front->label << ":";
}
switch (front->flag){
case 0:ofile << "\t" + front->cw << endl; break;
case 1:ofile << "\t" + front->cw + "\t" + front->arg1 << endl; break;
case 2:ofile << "\t" + front->cw + "\t" + front->arg1 << "," << front->arg2 << endl; break;
}
}
ofile << "CSEG\tENDS\n\tEND\tSTART" << endl;
}
| true |
3c585ac5a71bd87dc5c677bead5feea0982e38b6 | C++ | jpennington222/KU_EECS_Labs | /EECS_268/Lab02/WebBrowser.cpp | UTF-8 | 1,927 | 3.359375 | 3 | [] | no_license | /*
* @Author: Joseph Pennington
* @File Name: WebBrowser.cpp
* @Assignment: EECS 268 Lab 02
* @Date: 09/17/2018
* @Brief: This program is the cpp file for the WebBrowser Class. It contains the constructor, navigateTo, forward, back, currentURL, copyCurrentHistory, and the descructor functions.
*/
#include "WebBrowser.h"
#include "LinkedList.h"
#include "ListInterface.h"
#include "WebBrowserInterface.h"
#include "Node.h"
#include <string>
#include <stdexcept>
#include <iostream>
WebBrowser::WebBrowser()
{
history = new LinkedList<std::string>();
m_current = 0;
}
void WebBrowser::navigateTo(std::string url)
{
if(m_current == history -> getLength())
{
try
{
history -> insert(m_current+1, url);
}
catch(std::runtime_error error)
{
std::cout<<error.what()<<'\n';
}
m_current++;
}
else
{
for(int i=history -> getLength(); i>m_current; i--)
{
try
{
history -> remove(i);
}
catch(std::runtime_error error)
{
std::cout<<error.what()<<'\n';
}
}
try
{
history -> insert(m_current+1, url);
}
catch(std::runtime_error error)
{
std::cout<<error.what()<<'\n';
}
m_current++;
}
}
void WebBrowser::forward()
{
if(m_current != history -> getLength())
{
m_current++;
}
}
void WebBrowser::back()
{
if(m_current != 1)
{
m_current--;
}
}
std::string WebBrowser::currentURL()const
{
try
{
return(history -> getEntry(m_current));
}
catch(std::runtime_error error)
{
std::cout<<error.what()<<'\n';
}
}
void WebBrowser::copyCurrentHistory(ListInterface<std::string>& destination)
{
for(int i=1; i<=(history -> getLength()); i++)
{
try
{
destination.insert(i, history -> getEntry(i));
}
catch(std::runtime_error error)
{
std::cout<<error.what()<<'\n';
}
}
}
WebBrowser::~WebBrowser()
{
delete history;
}
| true |
771f1609d454b286e45f8382282792a61838a3f8 | C++ | alexandraback/datacollection | /solutions_1485488_1/C++/MrRoach/main.cpp | UTF-8 | 2,299 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <list>
#include <deque>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <queue>
using namespace std;
const int MAXN = 120;
const int INFTY = 100000000;
const double EPS = 1e-6;
const int dx[] = {-1,0,1,0};
const int dy[] = {0,1,0,-1};
struct node {
bool friend operator < (const node &a, const node &b){
return (a.t > b.t);
}
int y;
int x;
int t;
};
int T;
int H,N,M;
int f[MAXN][MAXN];
int c[MAXN][MAXN];
int t[MAXN][MAXN];
bool det[MAXN][MAXN];
priority_queue<node, vector<node>, less<node>> q;
int earliest_time(int y1, int x1, int y2, int x2){
if (c[y1][x1] - f[y1][x1] < 50) return INFTY;
if (c[y2][x2] - f[y2][x2] < 50) return INFTY;
if (c[y1][x1] - f[y2][x2] < 50) return INFTY;
if (c[y2][x2] - f[y1][x1] < 50) return INFTY;
int t = H - (c[y1][x1] - 50);
if (t < H - (c[y2][x2] - 50)) {
t = H - (c[y2][x2] - 50);
}
if (t < 0) t = 0;
return t;
}
int travel_cost(int y, int x, int t){
if (t == 0) return 0;
if (H-t-f[y][x] >= 20) return 10;
else return 100;
}
int main(){
cin >>T;
for (int times = 0; times < T; ++times){
cin >> H >> N >> M;
for (int i = 0; i < N; ++i){
for (int j = 0; j < M; ++j){
cin >> c[i][j];
t[i][j] = INFTY;
}
}
for (int i = 0; i < N; ++i){
for (int j = 0; j < M; ++j){
cin >> f[i][j];
}
}
memset(det, false, sizeof(det));
while (!q.empty()) q.pop();
t[0][0] = 0;
node n;
n.y = 0;
n.x = 0;
n.t = 0;
q.push(n);
while (!q.empty()){
node n = q.top();
q.pop();
int y = n.y;
int x = n.x;
if (det[y][x]) continue;
det[y][x] = true;
if (det[N-1][M-1]) break;
for (int i = 0; i < 4; ++i){
int ny = y + dy[i];
int nx = x + dx[i];
if (ny >= 0 && nx >= 0 && ny < N && nx < M && !det[ny][nx]){
int nt = earliest_time(y, x, ny,nx);
if (nt < n.t) nt = n.t;
nt += travel_cost(y, x, nt);
if (nt < t[ny][nx]){
t[ny][nx] = nt;
node nn;
nn.x = nx;
nn.y = ny;
nn.t = nt;
q.push(nn);
}
}
}
}
cout <<"Case #" << times + 1 <<": "<<t[N-1][M-1]/10.0<<endl;
}
return 0;
} | true |
b584cd52c9db7e4c8707a5d6dfecaf4ef92d7653 | C++ | jukemal/MARX-XIX-Arduino | /src/main.cpp | UTF-8 | 895 | 2.859375 | 3 | [] | no_license | #include <Arduino.h>
#include <Wire.h>
#define ADDRESS 8
bool isProcessing = false;
void receiveEvent(int howMany)
{
String str;
while (Wire.available())
{
char c = Wire.read();
str += c;
}
Serial.println(str);
isProcessing = true;
Serial.println("Progress Started.");
}
void sendEvent()
{
if (isProcessing)
{
Wire.write("proc");
}else
{
Wire.write("done");
}
}
void setup()
{
Wire.begin(ADDRESS);
Wire.onReceive(receiveEvent);
Wire.onRequest(sendEvent);
Serial.begin(115200);
Serial.println("Started...");
}
int i = 0;
void loop()
{
if (isProcessing && i == 10)
{
isProcessing = false;
i = 0;
Serial.println("Progress Done");
}
if (isProcessing)
{
i++;
}
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("Arduino is Running...");
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
| true |
9842533de4894879daa331b00ce43f707583bac7 | C++ | rk946/cpp | /Recursion/power.cpp | UTF-8 | 211 | 2.953125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int sol(int a,int b)
{
if(b==1)
return a;
return a*sol(a,--b);
}
int main()
{
int a,b;
cin>>a>>b;
cout <<a<<endl;
cout <<b<<endl;
cout << sol(a,b) <<endl;
} | true |
04703f9de88430456113c9cc2b96ee3eba6663df | C++ | b0rista/cpp-karate | /WhiteBelt/Week2/Anagram/Anagram/main.cpp | UTF-8 | 636 | 3.421875 | 3 | [] | no_license | //
// main.cpp
// Anagram
//
// Created by Boris Tarovik on 20.06.2021.
//
#include <iostream>
#include <map>
using namespace std;
map<char, int> BuildCharCounters(const string& s) {
map<char, int> charCounters;
for (auto c : s) {
++charCounters[c];
}
return charCounters;
}
int main(int argc, const char * argv[]) {
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string s1, s2;
cin >> s1 >> s2;
if (BuildCharCounters(s1) == BuildCharCounters(s2)) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
return 0;
}
| true |
00fb560f89ccfbe25d18a2bba589a51df90299fc | C++ | MarcoGeraldi/Homework_2019 | /HomeworkAC_2019/HomeworkAC_2019/gate.h | UTF-8 | 972 | 2.78125 | 3 | [] | no_license | #pragma once
#include "signal.h"
//Generic Gate
class gate{
protected:
//Each Gate has many input signal and only 1 output signal
std::vector<signal_input> signal_in;
signal_output signal_out;
public:
gate();
bool Read();
};
//AND Gate
class AND : public gate {
public:
AND(const std::vector<signal_input> & _signal_in);
};
//NAND GATE
class NAND : public gate {
public:
NAND(const std::vector<signal_input> & _signal_in);
};
//OR Gate
class OR : public gate {
public:
OR(const std::vector<signal_input> & _signal_in);
};
//XOR GATE
class XOR : public gate {
public:
XOR (const std::vector<signal_input> & _signal_in);
};
//NOR GATE
class NOR : public gate {
public:
NOR(const std::vector<signal_input> & _signal_in);
};
//XNOR GATE
class XNOR : public gate {
public:
XNOR(const std::vector<signal_input> & _signal_in);
};
//NOT Gate
class NOT : public gate {
private:
signal_input signal_in;
public:
NOT(const signal_input &_signal_in);
};
| true |
9aad7893a5e4e51530c079b30439959a7dcf9b92 | C++ | jiteshsingla1999/Competitive_code | /stl/quick_sort.cpp | UTF-8 | 1,053 | 3.046875 | 3 | [] | no_license |
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp = a;
a=b;
b=temp;
}
int partition(int input[], int start, int stop)
{
int pivot = input[start];
int i=start+1;
int j=i;
while(j<=stop)
{
if(input[j]<pivot)
{
j++;
}
else
{
swap(input[i],input[j]);
i++;j++;
}
}
swap(input[start],input[i-1]);
return i-1;
}
void quickSortUtil(int input[], int start, int stop)
{
if(start<stop)
{
cout << "huh\n";
int pi = partition(input,start,stop);
quickSortUtil(input,start,pi-1);
quickSortUtil(input,pi+1,stop);
}
return;
}
void quickSort(int input[], int size) {
quickSortUtil(input,0,size-1);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
quickSort(input, n);
for(int i = 0; i < n; i++) {
cout << input[i] << " ";
}
delete [] input;
}
| true |
fc447613aa10dcf4c25b14905d9cb91427af4f81 | C++ | ducthangbui/Learning | /C++/BaiTap/baitaplan1/12.cpp | UTF-8 | 319 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int Amstrong(int n)
{
int tmp=n,a;
int s=0;
while(n!=0)
{
a=n%10;
s=s+a*a*a;
n=n/10;
}
if(s==tmp) return 1;
return 0;
}
main()
{
int dem=0;
for(int i=100;i<=999;i++)
if(Amstrong(i))
{
dem++;
cout<<i<<" ";
}
cout<<endl<<"Co tat ca "<<dem<<" so"<<endl;
}
| true |
d1e62df148a41af9d14be3d43315dcc71c369061 | C++ | CartoDB/mobile-sdk | /all/native/utils/GeneralUtils.h | UTF-8 | 1,395 | 2.703125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (c) 2016 CartoDB. All rights reserved.
* Copying and using this code is allowed only according
* to license terms, as given in https://cartodb.com/terms/
*/
#ifndef _CARTO_GENERALUTILS_H_
#define _CARTO_GENERALUTILS_H_
#include <string>
#include <vector>
#include <map>
namespace carto {
class GeneralUtils {
public:
template <typename T>
static T Clamp(const T& value, const T& low, const T& high) {
return value < low ? low : (value > high ? high : value);
}
static long long IntPow(int x, unsigned int p);
static unsigned int UpperPow2(unsigned int n);
static bool IsPow2(unsigned int n);
static void ReplaceSubstrings(std::string& base, const std::string& search, const std::string& replace);
static std::string ReplaceTags(const std::string& base, const std::map<std::string, std::string>& tagValues, const std::string& startTag = "{", const std::string& endTag = "}", bool keepUnknownTags = false);
static std::vector<std::string>& Split(const std::string& str, char delim, std::vector<std::string>& elems);
static std::vector<std::string> Split(const std::string& str, char delim);
static std::string Join(const std::vector<std::string>& strs, char delim);
private:
GeneralUtils();
};
}
#endif
| true |
20b00ea2926f0d4fbe1738e23801191e7b11b7aa | C++ | wesley-stone/leetcode | /hiho43/cnmhiho.h | UTF-8 | 1,817 | 2.71875 | 3 | [] | no_license | //
// Created by wesley shi on 2018/1/7.
//
#ifndef HIHO43_CNMHIHO_H
#define HIHO43_CNMHIHO_H
#include <vector>
using namespace std;
vector<vector<vector<int>>> dp(100, vector<vector<int>>(3, vector<int>(4, 0)));
void init(int max){
// h
dp[0][0][0] = 1;
// i
dp[0][1][1] = 1;
// o
dp[0][2][2] = 1;
// total
dp[0][0][3] = 1;
dp[0][1][3] = 1;
dp[0][2][3] = 1;
for (int i=1; i<max; i++){
for (int j=0; j<3; j++){
dp[i][j][0] = dp[i-1][j][3];
dp[i][j][1] = dp[i-1][j][0]+dp[i-1][j][1];
dp[i][j][2] = dp[i-1][j][0]+dp[i-1][j][2];
dp[i][j][3] = dp[i][j][0]+dp[i][j][1]+dp[i][j][2];
}
}
}
int intervals(int cnt[], int &K){
for (int i=0; i<3; i++){
if (K <= cnt[i]){
return i;
}
K -= cnt[i];
}
return 0;
}
char search(int N, char c, int K){
if (N == 0)
return c;
int cnt[3] = {0};
int index = 0;
switch (c){
case 'h':
cnt[0] = dp[N-1][0][3];
cnt[1] = dp[N-1][1][3];
cnt[2] = dp[N-1][2][3];
index = intervals(cnt, K);
if (index == 0) return search(N-1, 'h', K);
else if (index == 1) return search(N-1, 'i', K);
else return search(N-1, 'o', K);
case 'i':
cnt[0] = dp[N-1][0][3];
cnt[1] = dp[N-1][1][3];
index = intervals(cnt, K);
if (index == 0) return search(N-1, 'h', K);
else return search(N-1, 'i', K);
default: // 'o'
cnt[0] = dp[N-1][0][3];
cnt[1] = dp[N-1][2][3];
index = intervals(cnt, K);
if (index == 0) return search(N-1, 'h', K);
else return search(N-1, 'o', K);
}
}
#endif //HIHO43_CNMHIHO_H
| true |
1ea83088f89f29659425f47866da650fd673e93d | C++ | yjglab/cpp_programming_study | /B1_40/Source6.cpp | UHC | 629 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
// *** Ҹ ***
class Base1 {
public:
virtual ~Base1()
{
cout << "~Base1() " << endl;
}
};
class Derived1 : public Base1 {
private:
int* _arr;
public:
Derived1(int length)
{
_arr = new int[length];
}
virtual ~Derived1() override
{
cout << "~Derived1() " << endl;
delete[] _arr;
}
};
int main() {
// Ҹ ȣ : ڽ -> θ ( ݴ)
Derived1 d1(5);
//
Derived1* drv = new Derived1(5);
Base1* bse = drv;
delete bse; // memory leak Base1 Ҹڸ virtual
return 0;
} | true |
e431d21055a36c4308fb8afa9e9700d803502c4b | C++ | seanande/hearing-aid | /main.cpp | UTF-8 | 2,255 | 2.5625 | 3 | [] | permissive | //#include "frost.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_FILE_SIZE 1000000
#define BLOCK_SIZE 256
#define CHANNELS 4
int main(int argc, char const *argv[]) {
unsigned char buffer[MAX_FILE_SIZE];
int i, j, k, n, num_blocks;
char *filenames[4];
filenames[0] = (char*)"test.raw";
filenames[1] = (char*)"test.raw";
filenames[2] = (char*)"test.raw";
filenames[3] = (char*)"test.raw";
FILE *f = fopen(filenames[0], "r");
if(!f) {
printf("oh no\n");
return -1;
}
n = fread(buffer, 1, MAX_FILE_SIZE, f);
fclose(f);
num_blocks = n/BLOCK_SIZE + 1;
printf("num = %d\n", num_blocks);
char blocks[CHANNELS][num_blocks][BLOCK_SIZE];
printf("channels: %d, numbloks: %d, blocksize: %d\n", CHANNELS, num_blocks, BLOCK_SIZE);
for(k=0; k < CHANNELS; k++) {
f = fopen(filenames[k], "rb");
n = fread(buffer, 1, MAX_FILE_SIZE, f);
printf("%d\n", k);
fclose(f);
num_blocks = n/BLOCK_SIZE;
for(i = 0; i < num_blocks; i++) {
for (j = 0; j < BLOCK_SIZE; j++) {
//printf("%d, %d, %d\n", k, i, j);
blocks[k][i][j] = buffer[i*BLOCK_SIZE + j];
if(blocks[k][i][j] != 0) {
//printf("%d, %d, %d: %d\n", k, i, j, blocks[k][i][j]);
}
}
}
}
printf("donezo\n");
// test that new breaking up into blocks didn't mess up the file
FILE* newfile = fopen("new.raw", "w");
size_t s = fwrite(blocks, num_blocks, BLOCK_SIZE, newfile);
for(k=0; k < CHANNELS; k++) {
char num[10];
sprintf(num, "%d", k);
char *filename = (char*)calloc(sizeof(char), 2);
strcpy(filename, "new");
filename = strncat(filename, num, 1);
filename = strncat(filename, ".csv", 4);
printf("%s\n", filename);
FILE *fp = fopen(filename, "w+");
for(i=0; i<num_blocks; i++) {
for(j=0; j<BLOCK_SIZE; j++) {
fprintf(fp, ",%d ", blocks[k][i][j]);
}
}
fclose(fp);
}
return 0;
}
| true |
68383f7c18313e6e447f20a0160d43e291599bd1 | C++ | provo/dataStructures | /arrayStack/arrayStack.cpp | UTF-8 | 3,408 | 4.09375 | 4 | [] | no_license | /*
* July 8, 2017
* Stack implemented with an array. The stack holds string objects.
*/
// Included files
#include <iostream>
#include <string>
#include "arrayStack.hpp"
// Using declarations
using std::cout;
using std::endl;
using std::string;
// Check if the stack is empty
inline bool ArrayStack::isEmpty() const { return (top == &stackArray[0]); }
// Check if the stack array is filled
inline bool ArrayStack::isFull() const { return (stackElements >= STACK_SIZE); }
// Default constructor
ArrayStack::ArrayStack()
{
top = stackArray;
stackElements = 0;
}
// Constructor with string object as argument
ArrayStack::ArrayStack(const string &str)
{
top = stackArray;
*top = str;
top++;
stackElements = 1;
}
// Constructor with pointer to string as argument
ArrayStack::ArrayStack(const char *str)
{
top = stackArray;
*top = str;
top++;
stackElements = 1;
}
// Copy constructor
ArrayStack::ArrayStack(const ArrayStack &obj)
{
if (this == &obj)
; // Do nothing
else
{
top = stackArray;
for(int i = 0; i < obj.stackElements; i++)
{
stackArray[i] = obj.stackArray[i];
top++;
}
stackElements = obj.stackElements;
}
}
// Have not created a destructor
ArrayStack::~ArrayStack() { /* Do nothing */ }
// Print the stack
void ArrayStack::printStack() const
{
if (isEmpty())
{
cout << "The stack is empty" << endl;
return;
}
const string *ptr;
if (isFull())
ptr = &(stackArray[STACK_SIZE - 1]);
else
ptr = top - 1;
cout << "TOP ";
while(ptr != &stackArray[0])
{
cout << *ptr << " ";
ptr--;
}
cout << *ptr << " BOTTOM" << endl;
}
// View top of the stack
void ArrayStack::peek() const { cout << "Top element of stack: " << *(top - 1) << endl; }
// Push string object onto the stack
void ArrayStack::push(const string &str)
{
if (isFull())
{
cout << "The stack is full" << endl;
return;
}
stackElements++;
*top = str;
if (top == &stackArray[STACK_SIZE - 1])
top = nullptr;
else
top++;
}
// Push pointer to string onto the stack
void ArrayStack::push(const char *str)
{
if (isFull())
{
cout << "The stack is full" << endl;
return;
}
stackElements++;
*top = str;
if (top == &stackArray[STACK_SIZE - 1])
top = nullptr;
else
top++;
}
// Pop and return top of the stack
string ArrayStack::pop()
{
if (isEmpty())
{
cout << "The stack is empty. Pop operation aborted." << endl;
return "STACK EMPTY ERROR";
}
string tmp = *(top - 1);
cout << "Popping " << tmp << " off the stack." << endl;
top--; // Next push operation will override the current top element
stackElements--;
return tmp;
}
// Overload cout << operator to print the stack
std::ostream & operator<<(std::ostream &os, const ArrayStack &obj)
{
if (obj.isEmpty())
{
os << "The stack is empty" << endl;
return os;
}
const string *ptr;
if (obj.isFull())
ptr = &(obj.stackArray[obj.STACK_SIZE - 1]);
else
ptr = obj.top - 1;
os << "TOP ";
while(ptr != &obj.stackArray[0])
{
os << *ptr << " ";
ptr--;
}
os << *ptr << " BOTTOM" << endl;
return os;
}
| true |
00438d09c9403792930d2f3a1fda8ffca311619e | C++ | developersbk/Universal_Code_Snippets | /Codes/C++ Programs/Others/Convert a number into words.cpp | UTF-8 | 3,112 | 3.46875 | 3 | [] | no_license | Convert a number into words
#include <conio.h> // For getch() function only
#include <iostream>
using namespace std;
void numword1(int);
void numword2(int);
int main()
{
long unsigned int number,temp;
int mult,i,digit,digits,last_two,hundred,thousand,lakh,crore;
digits=last_two=hundred=thousand=lakh=crore=0;
cout<<"Enter a number(lesser than 99,99,99,999)
";
cin>>number;
if(number>999999999)
{
cout<<"Number out of range!";
getch();
exit(0);
}
if(number==0)
{
cout<<"Zero";
getch();
exit(0);
}
temp=number;
digit=number%10; // Extracting last two digts
last_two=digit;
number=number/10;
digit=number%10;
last_two=(digit*10)+last_two;
number=number/10; // Extract hundreds
digit=number%10;
hundred=digit;
number=number/10; // Extract thousands
digit=number%10;
thousand=digit;
number=number/10;
digit=number%10;
thousand=(digit*10)+thousand;
number=number/10; // Extract lakhs
digit=number%10;
lakh=digit;
number=number/10;
digit=number%10;
lakh=(digit*10)+lakh;
number=number/10; // Extract crores
digit=number%10;
crore=digit;
number=number/10;
digit=number%10;
crore=(digit*10)+crore;
while(temp!=0) // Calculate number of digits in the number
{
temp=temp/10;
digits++;
}
cout<<"The number in words is:
";
// Printing the number in words
if(digits>=8)
{
numword2(crore);
cout<<"crores ";
}
if(digits>=6)
{
if(lakh!=0)
{
numword2(lakh);
cout<<"lakh ";
}
}
if(digits>=4)
{
if(thousand!=0)
{
numword2(thousand);
cout<<"Thousand ";
}
}
if(digits>=3)
{
if(hundred!=0)
{
numword2(hundred);
cout<<"Hundred ";
}
}
numword2(last_two);
getch();
return 0;
}
void numword1(int num)
{
switch(num)
{
case 0: break;
case 1: cout<<"One ";
break;
case 2: cout<<"Two ";
break;
case 3: cout<<"Three ";
break;
case 4: cout<<"Four ";
break;
case 5: cout<<"Five ";
break;
case 6: cout<<"Six ";
break;
case 7: cout<<"Seven ";
break;
case 8: cout<<"Eight ";
break;
case 9: cout<<"Nine ";
break;
case 10: cout<<"Ten ";
break;
case 11: cout<<"Eleven ";
break;
case 12: cout<<"Twelve ";
break;
case 13: cout<<"Thirteen ";
break;
case 14: cout<<"Fourteen ";
break;
case 15: cout<<"Fifteen ";
break;
case 16: cout<<"Sixteen ";
break;
case 17: cout<<"Seventeen ";
break;
case 18: cout<<"Eighteen ";
break;
case 19: cout<<"Nineteen ";
break;
}
return;
}
void numword2(int num)
{
if(num>=90)
{
cout<<"Ninety ";
numword1(num-90);
}
else if(num>=80)
{
cout<<"Eighty ";
numword1(num-80);
}
else if(num>=70)
{
cout<<"Seventy ";
numword1(num-70);
}
else if(num>=60)
{
cout<<"Sixty ";
numword1(num-60);
}
else if(num>=50)
{
cout<<"Fifty ";
numword1(num-50);
}
else if(num>=40)
{
cout<<"Fourty ";
numword1(num-40);
}
else if(num>=30)
{
cout<<"Thirty ";
numword1(num-30);
}
else if(num>=20)
{
cout<<"Twenty ";
numword1(num-20);
}
else
numword1(num);
return;
}
| true |
2b1845e7ff09a0bbebedbc9d6edbd9b5f784f135 | C++ | dendisuhubdy/osfix | /FixEngine/source/common/message/BasicMessage.h | UTF-8 | 1,401 | 2.734375 | 3 | [
"BSL-1.0"
] | permissive | /*
* BasicMessage.h
*
* Created on: 1 Jan 2013
* Author: Wei Liew [wei.liew@outlook.com]
*
* Copyright Wei Liew 2012 - 2013.
* Distributed under the Boost Software License, Version 1.0.
* (See http://www.boost.org/LICENSE_1_0.txt)
*
*/
#ifndef BASICMESSAGE_H_
#define BASICMESSAGE_H_
namespace osf_common
{
class BasicMessage
{
public:
BasicMessage()
: _buffer(NULL)
, _len(0)
{
}
BasicMessage(const BasicMessage& copy)
: _buffer(NULL)
, _len(0)
{
_payload.assign((const char *)copy._buffer, copy._len);
_buffer = (unsigned char *)_payload.data();
_len = copy._len;
}
virtual ~BasicMessage()
{
}
virtual unsigned int set(unsigned char * buffer, unsigned int len, bool deepCopy = false)
{
if(deepCopy)
{
_payload.assign((const char *) buffer, len);
_buffer = (unsigned char *) _payload.data();
_len = len;
}
else
{
_buffer = buffer;
_len = len;
}
return _len;
}
virtual unsigned char * getMessage()
{
return _buffer;
}
virtual unsigned int getMessageLen()
{
return _len;
}
protected:
std::string _payload;
unsigned char * _buffer;
unsigned int _len;
};
} // namespace osf_common
#endif /* BASICMESSAGE_H_ */
| true |
aee31f061c4b99d02e98ba103b78f620876ae83f | C++ | sysu-itl/FinalProject | /code/Classes/map.cpp | UTF-8 | 3,019 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "map.h"
vector<string> MapClass::mapTexture = vector<string>();
MapClass::MapClass()
{
if (mapTexture.size() == 0) {
init();
}
}
Sprite* MapClass::createSprite(int texture)
{
//精灵
auto sprite = Sprite::create(mapTexture[texture].c_str());
Texture2D::TexParams texParams = { GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT };
sprite->setTag(texture);
sprite->getTexture()->setTexParameters(texParams);
sprite->setAnchorPoint(Vec2::ZERO);
return sprite;
}
void MapClass::setPhysic(Sprite* sprite)
{
//物理body
auto playerBody1 = PhysicsBody::createBox(sprite->getContentSize(), PhysicsMaterial(100.0f, 0.0f, 1.0f));
playerBody1->setCategoryBitmask(0xFFFFFFFF);
playerBody1->setCollisionBitmask(0xFFFFFFFF);
playerBody1->setContactTestBitmask(0xFFFFFFFF);
playerBody1->setDynamic(false);
sprite->setPhysicsBody(playerBody1);
}
void MapClass::saveMap(string filename)
{
if (mapElement.size()) {
origin = mapElement.front()->getPosition();
auto path = FileUtils::getInstance()->getWritablePath();
ofstream file(path + filename);
for (auto const &element : mapElement) {
auto position = element->getPosition() - mapElement.front()->getPosition() + origin;
file << position.x << " " << position.y << " " <<
element->getContentSize().width << " " << element->getContentSize().height << " " << element->getTag() << endl;
}
}
}
bool MapClass::loadMap(string filename)
{
auto path = FileUtils::getInstance()->getWritablePath();
ifstream file(path + filename);
if (file) {
CCLOG("mapelement");
mapElement.clear();
while (!file.eof()) {
float x, y, w, h;
int tag;
file >> x >> y >> w >> h >> tag;
auto sprite = createSprite(tag);
sprite->setTextureRect(Rect(0, 0, w, h));
setPhysic(sprite);
sprite->setPosition(x, y);
mapElement.emplace_back(sprite);
if (mapElement.size())
origin = mapElement.front()->getPosition();
}
return true;
}
return false;
}
void MapClass::push(Sprite * element)
{
mapElement.push_back(element);
origin = mapElement.front()->getPosition();
}
void MapClass::remove(Sprite * element)
{
mapElement.remove(element);
if (mapElement.size()) {
origin = mapElement.front()->getPosition();
}
}
void MapClass::clear()
{
mapElement.clear();
}
void MapClass::init()
{
mapTexture = vector<string>({ "block1.png", "block2.png" });
}
//重置
void MapClass::reset()
{
if (mapElement.size()) {
auto tran = origin - mapElement.front()->getPosition();
for (auto & element : mapElement) {
element->getPhysicsBody()->setVelocity(Vec2::ZERO);
element->setPosition(element->getPosition() + tran);
}
}
}
//移动
void MapClass::move()
{
if (mapElement.size()) {
for (auto & element : mapElement) {
element->getPhysicsBody()->setVelocity(Vec2(-GameMinSpeed, 0));
}
}
}
void MapClass::stop()
{
if (mapElement.size()) {
CCLOG("test");
for (auto & element : mapElement) {
element->getPhysicsBody()->setVelocity(Vec2::ZERO);
}
}
}
| true |
7961b09523c7a9edfb02f3978dea690484cd9580 | C++ | GevArakelyan/OpenCv | /Source.cpp | UTF-8 | 776 | 2.546875 | 3 | [] | no_license | #include <boost/gil.hpp>
#include <boost/gil/extension/dynamic_image/any_image.hpp>
#include <boost/gil/extension/io/jpeg.hpp>
#include <boost/gil/extension/io/png.hpp>
#include <boost/mpl/vector.hpp>
#include <iostream>
#include <algorithm>
int main()
{
namespace bg = boost::gil;
using my_images_t = boost::mpl::vector<bg::gray8_image_t, bg::rgb8_image_t, bg::gray16_image_t, bg::rgb16_image_t>;
bg::any_image<my_images_t> dynamic_image;
bg::rgb8_image_t image;
bg::read_image("image.png", image, bg::png_tag());
// Save the image upside down, preserving its native color space and channel depth
bg::rgb8_pixel_t pixel;
auto view = bg::flipped_up_down_view(bg::const_view(dynamic_image));
bg::write_view("out-dynamic_image.jpg", view, bg::jpeg_tag());
}
| true |
19882e71896395be43a1c0d065928829a777a876 | C++ | Chinkyu/CXXExercise | /MyAlgorithmPractice/MyAlgorithmPractice/43.MultiplyStrings1.cpp | UTF-8 | 1,828 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
string add(string num1, string num2) {
int s1 = num1.size()-1;
int s2 = num2.size()-1;
int len = (s1 > s2) ? s1 : s2;
string ans;
int carry = 0;
int sum;
do {
if(s1 >= 0 && s2 >= 0) sum = num1[s1] + num2[s2] + carry - '0';
else if (s1 >= 0 && s2 < 0) sum = num1[s1] + carry;
else sum = num2[s2] + carry;
if (sum > '9') {
carry = 1;
sum -= 10;
}
else {
carry = 0;
}
ans.push_back(sum);
if (s1 >= 0) s1--;
if (s2 >= 0) s2--;
} while (s1 >= 0 || s2 >= 0);
if (carry >= 1) ans.push_back('1');
reverse(ans.begin(), ans.end());
return ans;
}
string oneDigitMultiply(string num1, int c) {
int s1 = num1.size() - 1;
string ans;
if (c == 0) return "0";
int carry = 0;
for (int i = s1; i >= 0; --i) {
int d = (num1[i] - '0') * c + carry;
if (d > 9) {
carry = d / 10;
ans.push_back(d % 10 + '0');
}
else {
carry = 0;
ans.push_back(d + '0');
}
}
if (carry > 0) ans.push_back(carry + '0');
reverse(ans.begin(), ans.end());
return ans;
}
string multiply(string num1, string num2) {
int s1 = num1.size();
int s2 = num2.size();
string ans;
string l, s;
if (s1 > s2) {
l = num1; s = num2;
}
else {
l = num2; s = num1;
}
//ans = l;
for (int i = s.size() - 1; i >= 0; --i) {
string temp = oneDigitMultiply(l, s[i]-'0');
for (int j = 0; s.size()- 1 - i > j; ++j) {
temp.push_back('0');
}
ans = add(ans, temp);
}
return ans;
}
};
int main() {
Solution sol;
char c;
string n1 = "9999"; // "123";// = "22222";
string n2 = "9"; // "456";
// cout << sol.add(n1, n2).c_str();
cout << sol.oneDigitMultiply(n1, 0).c_str();
// cout << sol.multiply(n1, n2).c_str();
cin >> c;
} | true |
70bc8771b230b1df93e24cb2f12253f6e3e50090 | C++ | ljmihalik/OPL-Kono | /Board.cpp | UTF-8 | 13,320 | 3.578125 | 4 | [] | no_license | #include "Board.h"
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
Board::Board(){
}
Board::~Board(){
}
void Board::setBoard(int row, int col, string newElement){
mBoard[row][col]=newElement;
}
/* *********************************************************************
Function Name: createBoard
Purpose: to create the intial board
Parameters:
no parameters
Return Value: no value returned
Local Variables:
row, and col to print board
Algorithm:
1) get the size of board
2) loop over to place in the B O and W's in correct spot
3) account for the 4 pieces in the second and second to last row
Assistance Received: none
********************************************************************* */
void Board::createBoard(int gridSize){
mGridsize=gridSize;
mBoard.resize(gridSize);
string piece;
//make dynamic
for(int row=0; row<gridSize; row++){
if(row==0){
piece="B";
}
else if(row==mGridsize-1){
piece="W";
}
else{
piece="O";
}
mBoard[row].resize(gridSize);
for(int col=0; col<gridSize; col++){
mBoard[row][col]=piece;
}
}
mBoard[1][0]="B";
mBoard[1][mGridsize-1]="B";
mBoard[mGridsize-2][0]="W";
mBoard[mGridsize-2][mGridsize-1]="W";
}
/* *********************************************************************
Function Name: devOption
Purpose: To hold a winning game board for comparision
Parameters:
gridSize
Return Value: no value
Local Variables:
pieces --> holding the B W or O
row --> for looping rows
col --> for looping columns
Algorithm:
1) show a "winning board"
Assistance Received: none
********************************************************************* */
void Board::devOption(int gridSize){
mGridsize=gridSize;
mBoard.resize(gridSize);
string piece;
//make dynamic
for(int row=0; row<gridSize; row++){
if(row==0){
piece="W";
}
else if(row==mGridsize-1){
piece="B";
}
else{
piece="O";
}
mBoard[row].resize(gridSize);
for(int col=0; col<gridSize; col++){
mBoard[row][col]=piece;
}
}
mBoard[1][0]="W";
mBoard[0][2]="O";
mBoard[2][2]="W";
mBoard[1][mGridsize-1]="O";
mBoard[mGridsize-2][0]="B";
mBoard[mGridsize-2][mGridsize-1]="B";
}
/* *********************************************************************
Function Name: movePiece
Purpose: To move a piece on the board
Parameters:
row and column of piece that user wants to move
coordinate of the piece
Return Value: no value
Local Variables:
piece --> store the color of the piece getting moved
newRow --> row of pieces new position
newCol --> column of pieces new position
Cpiece --> BB/WW if piece can capture
Algorithm:
1) account of each move user can make (4 options)
2) move the piece into the new row and column according to the option
Assistance Received: none
********************************************************************* */
void Board::movePiece(int row, int column, string coordinate){
string piece=mBoard[row][column];
mBoard[row][column]="O";
int newRow=0;
int newCol=0;
string Cpiece=piece;
if(piece.length() == 1){
Cpiece=piece+piece;
}
if(coordinate=="northeast"){
newRow=row-1;
newCol=column+1;
mBoard[row-1][column+1]=piece;
}
else if (coordinate=="northwest"){
newRow=row-1;
newCol=column-1;
mBoard[row-1][column-1]=piece;
}
else if (coordinate=="southeast"){
newRow=row+1;
newCol=column+1;
mBoard[row+1][column+1]=piece;
}
else if(coordinate=="southwest"){
newRow=row+1;
newCol=column-1;
mBoard[row+1][column-1]=piece;
}
if(newRow == 0 || newRow == mGridsize-1){
//home position
mBoard[newRow][newCol]=Cpiece;
}
if((newRow == 1 && newCol == 0) || (newRow == 1 && newCol == mGridsize-1)){
mBoard[newRow][newCol]=Cpiece;
}
if((newRow == mGridsize-2 && newCol == 0 ) || (newRow == mGridsize-2 && newCol == mGridsize-1)){
mBoard[newRow][newCol]=Cpiece;
}
}
/* *********************************************************************
Function Name: validateMove
Purpose: Error handling for the board
Parameters:
row --> row position of current piece
column --> column position of current piece
coordinate --> direction of the pieces move
color --> what color the user picked
Return Value: false is something goes wrong otherwise true
Local Variables:
Upiece --> B or W
Cpiece --> is BB if it is a piece that can capture
piece --> letter(s) in current positoin
newRow --> row where piece is getting moved
newCol --> column where piece is getting moved
Algorithm:
1) valid starting position
2) out of bounds
3) open position
4) capture
Assistance Received: none
********************************************************************* */
bool Board::validateMove(int row, int column, string coordinate, string color){
bool isValid=true;
string Upiece;
string Cpiece;
if(color == "black"){
Upiece="B";
Cpiece="BB";
}
else{
Upiece="W";
Cpiece="Ww";
}
//valid starting position by color and gridsize
if(row < 0 || row > mGridsize || column < 0 || column > mGridsize){
cout<<"Starting position not on board!"<<endl;
return false;
}
string piece=mBoard[row][column];
//color
if(piece != Upiece){
if(piece != Cpiece){
cout<<"Piece selected is not your color!"<<endl;
return false;
}
}
string newPiece;
int newRow;
int newCol;
//if move is out of bounds
if(coordinate=="northeast"){
newRow=row-1;
newCol=column+1;
}
else if (coordinate=="northwest"){
newRow=row-1;
newCol=column-1;
}
else if (coordinate=="southeast"){
newRow=row+1;
newCol=column+1;
}
else if(coordinate=="southwest"){
newRow=row+1;
newCol=column-1;
}
if(newRow < 0 || newRow > mGridsize || newCol < 0 || newCol > mGridsize){
cout<<"Moving piece out of bounds!"<<endl;
return false;
}
//if positions open
if(coordinate=="northeast"){
newPiece=mBoard[row-1][column+1];
}
else if (coordinate=="northwest"){
newPiece=mBoard[row-1][column-1];
}
else if (coordinate=="southeast"){
newPiece=mBoard[row+1][column+1];
}
else if(coordinate=="southwest"){
newPiece=mBoard[row+1][column-1];
}
//can capture?
if(newPiece == Upiece || newPiece == Cpiece){
cout<<"You have a piece in that position!"<<endl;
return false;
}
if(piece == Upiece && newPiece != "O"){
cout<<"Not an open spot!"<<endl;
return false;
}
return true;
}
/* *********************************************************************
Function Name: viewBoard
Purpose: print the board
Parameters:
no parameters
Return Value: no return value
Local Variables:
row --> print rows
col --> print columns
Algorithm:
1) nested loops to print the board
Assistance Received: none
********************************************************************* */
void Board::viewBoard(){
int count=1;
cout<<"N"<<endl;
for(int row=0; row<mGridsize; row++){
cout<<count;
cout<<" ";
count++;
for(int col=0; col<mGridsize; col++){
cout<<mBoard[row][col];
cout<<"\t";
}
cout<<endl;
}
cout<<"S"<<endl;
cout<<"W ";
for(int horizontalNum=1; horizontalNum<=5; horizontalNum++){
cout<<horizontalNum;
cout<<"\t";
}
cout<<"E";
cout<<"\n";
}
/* *********************************************************************
Function Name: checkWinner
Purpose: checks if winner
Parameters:
no parameters
Return Value: returns true if winner otherwise false
Local Variables:
Algorithm:
1) nested loops to print the board
Assistance Received: none
********************************************************************* */
bool Board::checkWinner(){
int bPieces=0;
int wPieces=0;
int totalB=0;
int totalW=0;
string piece;
//count up all the current white and black pieces on the board in winning spots
//check the first and last row --> then the 4 other points
//if all available pieces are in winning position then theres a winner
for(int row=0; row<mGridsize; row++){
for(int col=0; col<mGridsize; col++){
piece=mBoard[row][col];
//looking at winning positions and counting
if( piece == "B" && row == mGridsize-1){
bPieces++;
}
else if( piece == "BB" && row == mGridsize-1){
bPieces++;
}
else if( piece == "W" && row == 0 ){
wPieces++;
}
else if( piece == "WW" && row == 0){
wPieces++;
}
//looking at the whole board --> counting total pieces
if(piece =="W" || piece =="WW"){
totalW++;
}
else if(piece =="B" ||piece =="BB"){
totalB++;
}
}
}
//looking at 2nd row and 2nd to last row's
if(mBoard[mGridsize-2][0] == "B" || mBoard[mGridsize-2][0] == "BB"){
bPieces++;
}
else if(mBoard[mGridsize-2][mGridsize-1] == "B" || mBoard[mGridsize-2][mGridsize-1] == "BB"){
bPieces++;
}
if(mBoard[1][0] == "W" || mBoard[1][0] == "WW"){
wPieces++;
}
else if(mBoard[1][mGridsize-1] == "W" || mBoard[1][mGridsize-1] == "WW"){
wPieces++;
}
if(totalW == wPieces){
return true;
}
else if(totalB == bPieces){
return true;
}
return false;
}
/* *********************************************************************
Function Name: score
Purpose: adds up score of winner.
Parameters:
no parameters
Return Value: returns score
Local Variables: piece --> holds the B, BB, W, WW
Pscore/Cscore --> holds score
row/col --> used for looping in for loop
Algorithm:
1) home pieces 3 1 5 1 3
2) add up all the pieces in home positions
3) count number of remaining peices +5 for player who captured
5) -5 for player who quits
Assistance Received: none
********************************************************************* */
int Board::score(string color){
string piece;
int Pscore=0;
string ScorePiece;
string ScoreCapture;
int Scorerow=0;
int OppPieces=0;
int SecondScoreRow=0;
if(color =="black"){
ScorePiece="B";
ScoreCapture="BB";
Scorerow=mGridsize-1;
SecondScoreRow=mGridsize-2;
}
else if(color =="white"){
ScorePiece="W";
ScoreCapture="WW";
Scorerow=0;
SecondScoreRow=1;
}
for(int row=0; row<mGridsize; row++){
for(int col=0; col<mGridsize; col++){
piece=mBoard[row][col];
//adding scores
if((piece == ScorePiece && row==Scorerow) || (piece == ScoreCapture && row ==Scorerow)){
//adding 3's
if(col==0 || col==mGridsize-1){
Pscore+=3;
}
//adding 1's
if(col==1 || col==mGridsize-2){
Pscore++;
}
//adding 5's
if(col==2 || col==mGridsize-3){
Pscore+=5;
}
//adding 7's
if(mGridsize>5){
if(col==3 || col==mGridsize-4 ){
Pscore+=7;
}
//adding 9's
if(mGridsize==9 && col==4){
Pscore+=9;
}
}
}
//count up oppentent pieces on board
if(piece != ScorePiece && piece != ScoreCapture && piece != "O"){
OppPieces++;
}
}
}
//calc captured score
int PieceDiff=0;
if(OppPieces < mGridsize+2){
PieceDiff=mGridsize-OppPieces;
Pscore+=PieceDiff*5;
}
//adding inner one's
if(mBoard[SecondScoreRow][0] == ScorePiece || mBoard[SecondScoreRow][0] == ScoreCapture){
Pscore++;
}
else if(mBoard[SecondScoreRow][mGridsize-1] == ScorePiece || mBoard[SecondScoreRow][mGridsize-1] == ScoreCapture){
Pscore++;
}
return Pscore;
}
| true |
c1cc4de347bb6da6f94a03978bcfae96ff491f23 | C++ | professor9999/DSA | /Practice Problems/Array/01_Reverse_The_Array_STL.cpp | UTF-8 | 313 | 3.40625 | 3 | [] | no_license | // Reverse the array
// Time Complexity = O(n)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[] = {1, 21, 8, 9, 3, 1, 19, 55, 15, 45, 23};
int n = sizeof(a) / sizeof(int);
reverse(a, a + n);
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
return 0;
} | true |
d3dc44ebda68331297473f5c46e7d8db4e38e82e | C++ | BaeJongHo/Algorithm | /Guess_2/Guess_2.cpp | UTF-8 | 815 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
int n;
char a[10][10];
vector<int> v;
void dfs(int idx);
bool possible(int idx);
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
cin >> a[i][j];
}
}
dfs(0);
return 0;
}
void dfs(int idx) {
if (idx == n) {
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
exit(0);
}
for (int i = -10; i < 11; i++) {
v.push_back(i);
if (possible(idx))
dfs(idx + 1);
v.pop_back();
}
}
bool possible(int idx) {
int sum = 0;
for (int i = idx; i >= 0; i--) {
sum += v[i];
if (a[i][idx] == '+' && sum <= 0)
return false;
if (a[i][idx] == '0' && sum != 0)
return false;
if (a[i][idx] == '-' && sum >= 0)
return false;
}
return true;
} | true |
db825fee7a94f30c6262a86dbf151af60df9af39 | C++ | mka-sieg/Domino | /func_game.cpp | UTF-8 | 6,770 | 2.6875 | 3 | [] | no_license | #include "libraries.h"
void koniec_ruchu(){
string next;
while(next!="n"){
cout<<"By zakonczyc ruch wpisz litere n"<<endl;
cin>>next;
if(next=="n"){
break;
}
}
system("cls");
}
int dokladanie_kostki(int kolejka[],int **gracz_kostki,int ostatnia,int **tab,int talon[],int liczba_talon,int **do_dodania,int ii,int liczba_do_dodania[]){
int aa=0;
int jjj=0;
int kostka;
int **nowa_kostka;
nowa_kostka = new int *[1];
for(int i=0;i<1;i++){
nowa_kostka[i] = new int[1];
}
int temp[liczba_talon];
int losowa_liczba;
while(aa!=1){
cin>>kostka;
if (kostka==-1){
do{
cout<<"Dobieram kostke z talonu!"<<endl;
losowa_liczba=rand()%liczba_talon;
do_dodania[ii][jjj]=talon[losowa_liczba];
for(int t=0;t<liczba_talon;t++){
if(t!=losowa_liczba){
temp[jjj]=talon[t];
jjj++;
}
}
nowa_kostka[0][0]=gracz_kostki[talon[0]][0];
nowa_kostka[0][1]=gracz_kostki[talon[0]][1];
rysuj_kostka(1,nowa_kostka);
}while(gracz_kostki[kostka][0]!=tab[kolejka[ostatnia]][1]);
aa=1;
liczba_talon--;
for (int iiii=0;iiii<liczba_talon;iiii++){
talon[iiii]=temp[iiii];
}
liczba_do_dodania[ii]=jjj;
}else{
if(gracz_kostki[kostka][0]!=tab[kolejka[ostatnia]][1]){
cout<<"Wybierz inna kostke!"<<endl;
}else{
aa=1;
}
}
}
cout<<"Wybrano kostke nr "<<kostka<<endl;
//sprawdzenie czy koniec
return kostka;
}
int dokladanie_kostki_komputer(int kolejka[],int **gracz_kostki,int ostatnia,int **tab,int liczba,int talon[],int liczba_talon,int **do_dodania, int ii,int liczba_do_dodania[]){
int kostka=0;
int jjj=0;
int **nowa_kostka;
nowa_kostka = new int *[1];
for(int i=0;i<1;i++){
nowa_kostka[i] = new int[1];
}
int temp[liczba_talon];
int losowa_liczba;
for(int i=0;i<liczba;i++){
if(gracz_kostki[i][0]==tab[kolejka[ostatnia]][1]){
kostka=kolejka[ostatnia];
}else{
do{
cout<<"Dobieram kostke z talonu!"<<endl;
losowa_liczba=rand()%liczba_talon;
do_dodania[ii][jjj]=talon[losowa_liczba];
for(int t=0;t<liczba_talon;t++){
if(t!=losowa_liczba){
temp[jjj]=talon[t];
jjj++;
}
}
nowa_kostka[0][0]=gracz_kostki[talon[0]][0];
nowa_kostka[0][1]=gracz_kostki[talon[0]][1];
rysuj_kostka(1,nowa_kostka);
}while(gracz_kostki[kostka][0]!=tab[kolejka[ostatnia]][1]);
liczba_talon--;
for (int iiii=0;iiii<liczba_talon;iiii++){
talon[iiii]=temp[iiii];
}
}
}
liczba_do_dodania[ii]=jjj;
//sprawdzenie czy koniec
return kostka;
}
void ustawienie_kolejnosci(int ilosc_graczy,int pierwszy_gracz, int kolejnosc_graczy[]){
int kolejnosc_04[]={0,1,2,3};
int kolejnosc_14[]={1,2,3,0};
int kolejnosc_24[]={2,3,0,1};
int kolejnosc_34[]={3,0,1,2};
int kolejnosc_03[]={0,1,2};
int kolejnosc_13[]={1,2,0};
int kolejnosc_23[]={2,0,1};
int kolejnosc_02[]={0,1};
int kolejnosc_12[]={1,0};
if(ilosc_graczy==2){
for (int i=0;i<ilosc_graczy;i++){
if (pierwszy_gracz==0){
kolejnosc_graczy[i]=kolejnosc_02[i];
}if (pierwszy_gracz==1){
kolejnosc_graczy[i]=kolejnosc_12[i];
}
}
}else if(ilosc_graczy==3){
for (int i=0;i<ilosc_graczy;i++){
if (pierwszy_gracz==0){
kolejnosc_graczy[i]=kolejnosc_03[i];
}if (pierwszy_gracz==1){
kolejnosc_graczy[i]=kolejnosc_13[i];
}if (pierwszy_gracz==2){
kolejnosc_graczy[i]=kolejnosc_23[i];
}
}
}else{
for (int i=0;i<ilosc_graczy;i++){
if (pierwszy_gracz==0){
kolejnosc_graczy[i]=kolejnosc_04[i];
}if (pierwszy_gracz==1){
kolejnosc_graczy[i]=kolejnosc_14[i];
}if (pierwszy_gracz==2){
kolejnosc_graczy[i]=kolejnosc_24[i];
}if (pierwszy_gracz==3){
kolejnosc_graczy[i]=kolejnosc_34[i];
}
}
}
}
int rozpoczecie_gry(int liczba,int **gracze_losowanie,int pierwszy_gracz,int kolejka[],int **tab,int kostka,int liczba_elem){
int **gracz_kostki;
gracz_kostki = new int *[liczba];
for(int i=0;i<liczba;i++){
gracz_kostki[i] = new int[1];
}
for (int j=0;j<liczba;j++){
gracz_kostki[j][0]=tab[gracze_losowanie[pierwszy_gracz][j]][0];
gracz_kostki[j][1]=tab[gracze_losowanie[pierwszy_gracz][j]][1];
}
rysuj_kostka(liczba,gracz_kostki);
cin>>kostka;
cout<<"Wybrano kostke nr "<<kostka<<endl;
koniec_ruchu();
kolejka[liczba_elem]=gracze_losowanie[pierwszy_gracz][kostka];
liczba_elem+=1;
int **kolejka_rys;
kolejka_rys = new int *[liczba_elem];
for(int i=0;i<liczba_elem;i++){
kolejka_rys[i] = new int[1];
}
for(int l=0;l<liczba_elem;l++){
kolejka_rys[l][0]=tab[kolejka[l]][0];
kolejka_rys[l][1]=tab[kolejka[l]][1];
}
rysuj_kostka(liczba_elem,kolejka_rys);
delete [] kolejka_rys;
delete [] gracz_kostki;
return kostka;
}
int rozpoczecie_gry_komputer(int liczba,int **gracze_losowanie,int pierwszy_gracz,int kolejka[],int **tab,int kostka,int liczba_elem){
int **gracz_kostki;
gracz_kostki = new int *[liczba];
for(int i=0;i<liczba;i++){
gracz_kostki[i] = new int[1];
}
for (int j=0;j<liczba;j++){
gracz_kostki[j][0]=tab[gracze_losowanie[pierwszy_gracz][j]][0];
gracz_kostki[j][1]=tab[gracze_losowanie[pierwszy_gracz][j]][1];
}
kostka=rand()%liczba;
kolejka[liczba_elem]=gracze_losowanie[pierwszy_gracz][kostka];;
liczba_elem+=1;
int **kolejka_rys;
kolejka_rys = new int *[liczba_elem];
for(int i=0;i<liczba_elem;i++){
kolejka_rys[i] = new int[1];
}
for(int l=0;l<liczba_elem;l++){
kolejka_rys[l][0]=tab[kolejka[l]][0];
kolejka_rys[l][1]=tab[kolejka[l]][1];
}
rysuj_kostka(liczba_elem,kolejka_rys);
delete [] kolejka_rys;
delete [] gracz_kostki;
return kostka;
}
| true |
591b09ab838b6c0a55a34440e69ce144cab8fa4a | C++ | zahellcode/hydroponics_control | /hydroponics_control.ino | UTF-8 | 5,478 | 2.5625 | 3 | [] | no_license |
#include "vars.h"
// RTC_DS1307 rtc;
RTC_DS3231 rtc;
char t[32];
bool evento_inicio = true; //variable de control para inicio de evento con valor true
bool evento_fin = true; // variable de control para finalización de evento con valor true
# define RELE 7
// constante RELE con valor 12 que corresponde a pin digital 7
# define bombaAguaRele1 0 // Bomba de agua
# define peltier1Rele2 1
# define peltier2Rele3 2
//#define rele4 3
//Sensores de temperatura
int pinTempSensor1 = A0;
int pinTempSensor2 = A1;
OneWire ourWire1(pinTempSensor1);
OneWire ourWire2(pinTempSensor2);
DallasTemperature sensors1(&ourWire1);
DallasTemperature sensors2(&ourWire2);
int temp1;
int temp2;
int umbralTemp1 = 25;
int umbralTemp2 = 27;
// Variables para el uso de la bomba de agua
int horaEjecutada = 0;
int minutosStartBomba = 0; // Minutos de la hora en la que se enciende, que se enciende la bomba (intentar que el inicio + tiempo encendido no sean 60
int tiempoEncendidoBomba = 5; // minutos
// Nivel del agua
int pinNivelAgua = 4;
void setup() {
Serial.begin(9600); // Iniciializa comunicación serie a 9600 bps
Wire.begin();
pinMode(bombaAguaRele1, OUTPUT);
pinMode(peltier1Rele2, OUTPUT) ;
pinMode(peltier2Rele3, OUTPUT);
//pinMode(rele4, OUTPUT);
pinMode(pinNivelAgua, OUTPUT);
// Las variables tienen un funcionamiento al reves, LOW apaga HIGH enciende
digitalWrite(bombaAguaRele1, HIGH); // Este rele se enciendo en LOW y se apaga en HIGH
digitalWrite(peltier1Rele2, HIGH); // Este rele se enciendo en LOW y se apaga en HIGH
digitalWrite(peltier2Rele3, HIGH); // Este rele se enciendo en LOW y se apaga en HIGH
//digitalWrite(rele4, HIGH); // Este rele se enciendo en LOW y se apaga en HIGH
digitalWrite(pinNivelAgua, HIGH); // Este rele se enciendo en LOW y se apaga en HIGH
//Begin sensores temp
sensors1.begin();
sensors2.begin();
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
// Configuracion de la hora si se apaga la bateria
if (rtc.lostPower()) {
Serial.println("RTC lost power, lets set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
//rtc.begin()
//setSyncProvider(rtc.now);
}
void loop() {
//El codigo solo funciona si el sensor de nivel esta a 1
Serial.print(digitalRead(pinNivelAgua) + "\n");
if (digitalRead(pinNivelAgua) == LOW){
DateTime now = rtc.now(); //captura la Hora
sprintf(t, "%02d:%02d:%02d %02d/%02d/%02d", now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());
Serial.print(F("Date/Time: "));
Serial.println(t);
//cojemos la temperatura
temp1 = getTemperatura(sensors1);
temp2 = getTemperatura(sensors2);
Serial.print("Temperatura1=");
Serial.print(temp1);
Serial.print("\nTemperatura2=");
Serial.print(temp2);
Serial.print("\n");
//Funcionamiento normal del sistema, peltiers apagados y bomba funcionamiento normal
if (temp1 < umbralTemp1 && temp2 < umbralTemp1){
//Esta variable la vamos a utilizar como control de uso de las excepciones de la temperatura, cuando salta la temperatura ponemos el valor a 0 para aqui poder apagarla al volver a la
// temperatura optima
if (horaEjecutada == 0){
apagarBomba();
}
checkEncenderBomba();
if (digitalRead(bombaAguaRele1) == LOW){
checkApagarBomba();
}
if (digitalRead(peltier1Rele2) == LOW){
digitalWrite(peltier1Rele2, HIGH);
}
if (digitalRead(peltier2Rele3) == LOW){
digitalWrite(peltier2Rele3, HIGH);
}
}
if (temp1 >= umbralTemp1 || temp2 >= umbralTemp1){
//Funcionamiento normal (hay excepciones de uso segun el resto de los reles)
encenderBomba();
horaEjecutada = 0;
if (digitalRead(peltier1Rele2) == HIGH){
digitalWrite(peltier1Rele2, LOW);
}
if (digitalRead(peltier2Rele3) == LOW){
digitalWrite(peltier2Rele3, HIGH);
}
}
if (temp1 >= umbralTemp2 || temp2 >= umbralTemp2){
//Funcionamiento normal (hay excepciones de uso segun el resto de los reles)
encenderBomba();
horaEjecutada = 0;
if (digitalRead(peltier1Rele2) == HIGH){
digitalWrite(peltier1Rele2, LOW);
}
if (digitalRead(peltier2Rele3) == HIGH){
digitalWrite(peltier2Rele3, LOW);
}
}
}else{
Serial.print("Deposito vacio\n");
apagarBomba();
digitalWrite(peltier1Rele2, HIGH);
digitalWrite(peltier2Rele3, HIGH);
}
delay(1000);
}
int getTemperatura(DallasTemperature sensors){
sensors.requestTemperatures();
float temp = sensors.getTempCByIndex(0);
return temp;
}
void checkEncenderBomba(){
for (int elem = 0; elem < sizeof(HOURS_PUMP_ON); elem++) {
if (HOURS_PUMP_ON[elem] == rtc.now().hour() && minutosStartBomba == rtc.now().minute() && HOURS_PUMP_ON[elem] != horaEjecutada){
encenderBomba();
horaEjecutada = HOURS_PUMP_ON[elem];
}
}
}
void checkApagarBomba(){
if (rtc.now().minute() >= minutosStartBomba + tiempoEncendidoBomba){
Serial.print("\nApagar Bomba SUMA:");
Serial.print(minutosStartBomba + tiempoEncendidoBomba);
apagarBomba();
}
}
void encenderBomba(){
digitalWrite(bombaAguaRele1, LOW);
//Serial.print("encender Bomba\n");
}
void apagarBomba(){
digitalWrite(bombaAguaRele1, HIGH);
//Serial.print("Apagar Bomba\n");
}
| true |
8e574bbdb02bd23f9c16b1539a6e7feada7a07a7 | C++ | olegseledets/theTask17-4 | /main.cpp | UTF-8 | 1,682 | 3.859375 | 4 | [] | no_license | #include <iostream>
void arrFilling(int arr[][4]){
int newArr[4][4];
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 4; ++j){
std::cout<< "[" << i << "][" << j << "] = ";
std::cin >> arr[i][j];
}
}
}
bool comparisonArr(int arrOne[][4], int arrTwo[][4]){
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 4; ++j){
if(arrOne[i][j] != arrTwo[i][j]){
std::cout << "Ошибка!!!!\n";
return false;
}
}
}
std::cout << "Успех!!! \n";
return true;
}
int main() {
int arrOne[4][4], arrTwo[4][4];
std::cout << "Заполнение массива 1" << std::endl;
arrFilling(arrOne);
std::cout << "Заполнение массива 2" << std::endl;
arrFilling(arrTwo);
comparisonArr(arrOne, arrTwo) ? std::cout << "Массивы равны \n" : std::cout << "Массивы не равны \n";
}
/*
Задача 4. Равенство матриц
Требуется реализовать небольшую программу для сравнения двух двумерных матриц размерами 4х4 на предмет их полного равенства. Программа принимает на вход две целочисленные матрицы A и B, которые вводятся с помощью std::cin и сравнивает их на предмет полного равенства. Если матрицы равны, то об этом сообщается в стандартном выводе. Алгоритм должен быть по возможности оптимальным и не проводить лишних операций.
*/ | true |
5edbd79409e9822b6df153e85b14839e5811ab0a | C++ | leon-anavi/eduArdu | /SOFTWARE/Challenges for kids who study the demo codes/ch_Makey_Servo/ch_Makey_Servo.ino | UTF-8 | 3,924 | 2.734375 | 3 | [
"Apache-2.0",
"CC-BY-SA-3.0",
"GPL-3.0-only"
] | permissive | /**********************************************************************
Demo example for Olimex board eduArdu
Tested with Arduino 1.8.12
Date: 2020/02/19
Description: Capacitive sense MakeyMakey implementation
Demo sketch using the default Arduino library "Keyboard"
**********************************************************************/
#include <Servo.h>
#include "Keyboard.h"
#include "pins_arduino.h" // Arduino pre-1.0 needs this
#include "Buzzer.h"
Servo Servo1;
Buzzer Buzz (6);
// readCapacitivePin
// Input: Arduino pin number
// Output: A number, from 0 to 30 expressing
// how much capacitance is on the pin
// When you touch the pin, or whatever you have
// attached to it, the number will get higher
uint8_t readCapacitivePin(int pinToMeasure) {
// Variables used to translate from Arduino to AVR pin naming
volatile uint8_t* port;
volatile uint8_t* ddr;
volatile uint8_t* pin;
// Here we translate the input pin number from the
// Arduino pin number to the AVR PORT, PIN, DDR,
// and we care about which bit of those registers.
byte bitmask;
port = portOutputRegister(digitalPinToPort(pinToMeasure));
ddr = portModeRegister(digitalPinToPort(pinToMeasure));
bitmask = digitalPinToBitMask(pinToMeasure);
pin = portInputRegister(digitalPinToPort(pinToMeasure));
// Discharge the pin first by setting it low and output
*port &= ~(bitmask);
*ddr |= bitmask;
delay(1);
uint8_t SREG_old = SREG; //back up the AVR Status Register
// Prevent the timer IRQ from disturbing our measurement
noInterrupts();
// Make the pin an input with the internal pull-up on
*ddr &= ~(bitmask);
*port |= bitmask;
// Now see how long it takes for the pin to get pulled up. This manual unrolling of the loop
// decreases the number of hardware cycles between each reading of the pin,
// thus increasing sensitivity.
uint8_t cycles = 20;
if (*pin & bitmask) { cycles = 0;}
else if (*pin & bitmask) { cycles = 1;}
else if (*pin & bitmask) { cycles = 2;}
else if (*pin & bitmask) { cycles = 3;}
else if (*pin & bitmask) { cycles = 4;}
else if (*pin & bitmask) { cycles = 5;}
else if (*pin & bitmask) { cycles = 6;}
else if (*pin & bitmask) { cycles = 7;}
else if (*pin & bitmask) { cycles = 8;}
else if (*pin & bitmask) { cycles = 9;}
else if (*pin & bitmask) { cycles = 10;}
else if (*pin & bitmask) { cycles = 11;}
else if (*pin & bitmask) { cycles = 12;}
else if (*pin & bitmask) { cycles = 13;}
else if (*pin & bitmask) { cycles = 14;}
else if (*pin & bitmask) { cycles = 15;}
else if (*pin & bitmask) { cycles = 16;}
else if (*pin & bitmask) { cycles = 17;}
else if (*pin & bitmask) { cycles = 18;}
else if (*pin & bitmask) { cycles = 19;}
else if (*pin & bitmask) { cycles = 20;}
else if (*pin & bitmask) { cycles = 21;}
else if (*pin & bitmask) { cycles = 22;}
else if (*pin & bitmask) { cycles = 23;}
else if (*pin & bitmask) { cycles = 24;}
else if (*pin & bitmask) { cycles = 25;}
else if (*pin & bitmask) { cycles = 26;}
else if (*pin & bitmask) { cycles = 27;}
else if (*pin & bitmask) { cycles = 28;}
else if (*pin & bitmask) { cycles = 29;}
else if (*pin & bitmask) { cycles = 30;}
// End of timing-critical section; turn interrupts back on if they were on before, or leave them off if they were off before
SREG = SREG_old;
// Discharge the pin again by setting it to low and to output
// It's important to leave the pins low if you want to
// be able to touch more than 1 sensor at a time - if
// the sensor is left pulled high, when you touch
// two sensors, your body will transfer the charge between
// sensors.
*port &= ~(bitmask);
*ddr |= bitmask;
return cycles;
}
void setup()
{
Servo1.attach(9);
Serial.begin (115200);
Keyboard.begin();
}
void loop ()
{
int pin14 = readCapacitivePin(14);
Servo1.write ((pin14 - 2)*8);
}
| true |
09b28ff76d126f04074d9d8f656e44945f52e963 | C++ | avasyutkin/term_1 | /My labs/Lab_11explicit/Lab_11explicit.cpp | UTF-8 | 730 | 3.09375 | 3 | [] | no_license | // Lab_11explicit - неявное подключение динамической библиотеки
#include "pch.h"
#include <iostream>
#include <windows.h>
using namespace std;
//Инициализация функции
double(*fun)(double, double);
int main(int argc, char* argv[])
{
// Загрузка dll
HMODULE h = LoadLibrary(L"Lab_11dll.dll");
(FARPROC &)fun = GetProcAddress(h, "ADD");
//Обращаемся к библиотеке, чтоб посчитать
cout << "Calculated value: " << fun(100, 194) << endl;
getchar();
//Выгружаем библиотеку из системной памяти
FreeLibrary(h);
cout << "Press any key for exit!" << endl;
getchar();
return 0;
} | true |
47064506eca2ab05a8740463fd563b59dc8c6707 | C++ | hamko/sample | /tbb/parallel_pipeline.cpp | UTF-8 | 5,837 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <tbb/tbb.h>
#include <utility>
#include "tbb/task_scheduler_init.h"
using namespace std;
using namespace tbb;
typedef tbb::mutex::scoped_lock lock_t;
typedef vector<string>::iterator iterator_t;
// 1st-stage : おサシミを引く
class osashimi : public tbb::filter {
iterator_t first_;
iterator_t last_;
public:
osashimi(iterator_t f, iterator_t l)
: tbb::filter(tbb::filter::serial_in_order), first_(f), last_(l) {}
void* operator()(void*) { // 初段なので引数は無視
if ( first_ == last_ ) { // おサカナがなくなったら終了
return 0;
}
string* result = new string(*first_ + "のおサシミ");
++first_;
return result;
}
};
// 2nd-stage : 皿に盛る
class moritsuke : public tbb::filter {
public:
moritsuke() : tbb::filter(tbb::filter::serial_in_order) {}
void* operator()(void* p) {
string* sp = static_cast<string*>(p);
sp->append("を皿に盛り");
return sp;
}
};
// 3rd-stage : ツマを添える
class tsuma : public tbb::filter {
public:
tsuma() : tbb::filter(tbb::filter::serial_in_order) {}
void* operator()(void* p) {
string* sp = static_cast<string*>(p);
sp->append("ツマを添えて");
return sp;
}
};
// 4th-stage : タンポポを乗せる
class tampopo : public tbb::filter {
public:
tampopo() : tbb::filter(tbb::filter::serial_in_order) {}
void* operator()(void* p) {
string* sp = static_cast<string*>(p);
sp->append("タンポポ乗せる");
return sp;
}
};
// last-stage : ショーケースに並べる
class showcase : public tbb::filter {
public:
showcase() : tbb::filter(tbb::filter::serial_in_order) {}
void* operator()(void* p) {
string* sp = static_cast<string*>(p);
cout << *sp << endl;
delete sp;
return 0;
}
};
int main() {
task_scheduler_init init;
const char* table[] = { "マグロ", "ハマチ", "サワラ", "ホタテ" };
vector<string> fish(table, table+4);
// C++11の表記
vector<string>::iterator first = fish.begin();
vector<string>::iterator last = fish.end();
tbb::parallel_pipeline(1,
// ---- 1st filter
tbb::make_filter<void,string>(
tbb::filter::serial_in_order,
[&](tbb::flow_control& fc) -> string {
if ( first == last ) {
fc.stop();
return ""; // dummy value
}
return *first++ + "のおサシミ";
})
&
// ---- 2nd filter
tbb::make_filter<string,string>(
tbb::filter::serial_in_order,
[](const string& s) -> string {
return s + "を皿に盛り";
})
&
// ---- 3rd filter
tbb::make_filter<string,string>(
tbb::filter::serial_in_order,
[](const string& s) -> string {
return s + "ツマを添えて";
})
&
// ---- 4th filter
tbb::make_filter<string,string>(
tbb::filter::serial_in_order,
[](const string& s) -> string {
return s + "タンポポ乗せる\n";
})
&
// ---- last filter
tbb::make_filter<string,void>(
tbb::filter::serial_in_order,
[](const string& s) -> void {
cout << s;
})
);
// C++11の表記
tbb::mutex mtx;
int count = 1;
int limit = 20;
tbb::parallel_pipeline(6, // ココを書き換えて遊んでみよう!
// ---- 1st filter
tbb::make_filter<void,int>(
tbb::filter::serial_in_order,
[&](tbb::flow_control& fc) -> int { // void(はじめはflow_control) -> int
if ( count == limit ) {
fc.stop();
return -1; // dummy value
}
lock_t lock(mtx); // ブロック抜けるまでロック?
cout << string(count,' ') << "1st(" << count << ")\n";
return count++;
})
&
// ---- 2nd filter
tbb::make_filter<int,pair<int,double>>(
tbb::filter::serial_in_order,
[&](int n) -> pair<int,double> { // int -> pair
lock_t lock(mtx);
cout << string(n,' ') << "2nd(" << n << ")\n";
return pair<int,double>(n, 1.0/n);
})
&
// ---- 3rd filter
tbb::make_filter<pair<int,double>,void>(
tbb::filter::serial_in_order,
[&](pair<int,double> p) -> void { // pair -> void
lock_t lock(mtx);
cout << string(p.first,' ') << "3rd(" << p.first << ") : " << p.second << endl;
})
);
// C++99の表記
// 入力系列とパイプラインを生成
tbb::pipeline pipeline;
// 各stageをパイプラインに接続
osashimi first_body(fish.begin(), fish.end());
moritsuke second_body;
tsuma third_body;
tampopo fourth_body;
showcase last_body;
pipeline.add_filter(first_body);
pipeline.add_filter(second_body);
pipeline.add_filter(third_body);
pipeline.add_filter(fourth_body);
pipeline.add_filter(last_body);
pipeline.run(3);
pipeline.clear();
init.terminate();
return 0;
}
| true |
f1b379e437017b1edef3a3ed10cd0469452ecf69 | C++ | vsrikrishna/cplusplus | /Miscellaneous/checkRegexExp.cpp | UTF-8 | 1,655 | 3.703125 | 4 | [] | no_license | basic Regex engine implementing the "." (any character) and "*" (previous rule, 0 to many).
* The function receives a string (letters only, no need for escaping) and a string pattern.
* It returns a bool whether the string matches the pattern. For example, the pattern "AB.*E" should match both "ABCDE" and "ABEEE".
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <climits>
using namespace std;
bool checkRegex(string pattern,string str){
int si=0;
for(int i=0;i<pattern.length();i++){
if(pattern[i] != '.' && pattern[i] != '*' && pattern[i] != str[si]){
return false;
}else if(pattern[i] == '.' && pattern[i+1] == '*'){
int pat_rem = pattern.length()-1-(i+1); //remaining length in pattern
int str_rem = str.length()-1-i; //remaining length in string
if(str_rem >pat_rem){
si+=(str_rem-pat_rem)+1; //skip over one extra character for '.' substitution
}else if(str_rem<pat_rem){
//do nothing, since there is no pattern match to be done
}
else{
si++;
}
cout<<"pat_rem:"<<pat_rem<<",str_rem:"<<str_rem<<",si:"<<si<<endl;
i++;
}else{
si++;
}
}
return true;
}
int main()
{
string str,pattern;
cout<<"Enter the regex pattern"<<endl;
cin>>pattern;
cout<<"Enter the string to be checked"<<endl;
cin>>str;
if(checkRegex(pattern,str)){
cout<<"String "<<str<<" matches pattern "<<pattern<<endl;
}else{
cout<<"Pattern does not match the string"<<str<<endl;
}
return 0;
}
| true |
bf585195be819ed0e1312367c1c9df9c6950e9c0 | C++ | SweetheartSquad/S-Tengine2 | /S-Tengine2/Source/S-Tengine2/src/CommandProcessor.cpp | UTF-8 | 3,058 | 3 | 3 | [] | no_license | #pragma once
#include <typeinfo>
#include "CommandProcessor.h"
#include "Command.h"
#include "CompressedCommand.h"
#include "Log.h"
CommandProcessor::CommandProcessor(void) :
currentCompressedCommand(nullptr)
{
}
bool CommandProcessor::executeCommand(Command * c){
if(currentCompressedCommand != nullptr){
if(!currentCompressedCommand->subCmdProc.executeCommand(c)){
Log::error("Compression command failed: sub-command error bubbled up");
currentCompressedCommand->subCmdProc.undoAll();
currentCompressedCommand->firstRun = false;
endCompressing();
return false;
}else{
currentCompressedCommand->firstRun = true;
}
}else{
redoStack.push_back(c);
if(!redo()){
return false;
}else{
c->firstRun = false;
}
}
// Executing a new command will always clear the redoStack
while(redoStack.size() > 0){
delete redoStack.back();
redoStack.pop_back();
}
return true;
}
void CommandProcessor::startCompressing(){
if(currentCompressedCommand == nullptr){
CompressedCommand * c = new CompressedCommand();
currentCompressedCommand = c;
}else{
// Error: already compressing
}
}
void CommandProcessor::endCompressing(){
if(currentCompressedCommand != nullptr){
if(currentCompressedCommand->firstRun){
undoStack.push_back(currentCompressedCommand);
}else{
delete currentCompressedCommand;
}
currentCompressedCommand = nullptr;
}
}
bool CommandProcessor::undo(){
//log("undo");
if (undoStack.size() > 0){
Command * c = undoStack.back();
bool success = c->unexecute();
undoStack.pop_back();
// Log command's entries
for(unsigned long int i = 0; i < c->subCmdProc.consoleEntries.size(); ++i){
consoleEntries.push_back(c->subCmdProc.consoleEntries.at(i));
}
c->subCmdProc.consoleEntries.clear();
//consoleEntries.insert(consoleEntries.end(), c->subCmdProc.consoleEntries.begin(), c->subCmdProc.consoleEntries.end());
if(success){
c->executed = false;
redoStack.push_back(c);
}else{
delete c;
}
return success;
}
return true;
}
bool CommandProcessor::redo(){
//log("redo");
if (redoStack.size() > 0){
Command * c = redoStack.back();
bool success = c->execute();
redoStack.pop_back();
// Log command's entries
for(unsigned long int i = 0; i < c->subCmdProc.consoleEntries.size(); ++i){
consoleEntries.push_back(c->subCmdProc.consoleEntries.at(i));
}
c->subCmdProc.consoleEntries.clear();
if(success){
c->executed = true;
undoStack.push_back(c);
}else{
delete c;
}
return success;
}
return true;
}
void CommandProcessor::undoAll(){
while (undoStack.size() != 0){
undo();
}
}
void CommandProcessor::redoAll(){
while (redoStack.size() != 0){
redo();
}
}
void CommandProcessor::reset(){
while(undoStack.size() > 0){
delete undoStack.back();
undoStack.pop_back();
}
while(redoStack.size() > 0){
delete redoStack.back();
redoStack.pop_back();
}
}
CommandProcessor::~CommandProcessor(void){
reset();
while(consoleEntries.size() > 0){
delete consoleEntries.back();
consoleEntries.pop_back();
}
} | true |
7dafafe7d42cdac8c1af10d50958ab0ad116efc9 | C++ | clach/Realtime-Vulkan-Hair | /src/Camera.cpp | UTF-8 | 3,270 | 2.703125 | 3 | [] | no_license | #include <iostream>
#define GLM_FORCE_RADIANS
// Use Vulkan depth range of 0.0 to 1.0 instead of OpenGL
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/gtc/matrix_transform.hpp>
#include "Camera.h"
#include "BufferUtils.h"
Camera::Camera(Device* device, float aspectRatio) : device(device), eye(glm::vec3(0.0f, 1.f, 10.f)) {
r = 10.0f;
theta = 0.0f;
phi = 0.0f;
cameraBufferObject.viewMatrix = glm::lookAt(eye, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
cameraBufferObject.projectionMatrix = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 50.0f);
cameraBufferObject.projectionMatrix[1][1] *= -1; // y-coordinate is flipped
BufferUtils::CreateBuffer(device, sizeof(CameraBufferObject), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, buffer, bufferMemory);
vkMapMemory(device->GetVkDevice(), bufferMemory, 0, sizeof(CameraBufferObject), 0, &mappedData);
memcpy(mappedData, &cameraBufferObject, sizeof(CameraBufferObject));
}
Camera::Camera(Device* device, float aspectRatio, glm::vec3 eye, float nearPlane, float farPlane) : device(device), eye(eye) {
r = 10.0f;
theta = 0.0f;
phi = 0.0f;
glm::vec3 normal = normalize(this->eye - glm::vec3(0.f, 1.f, 0.f));
cameraBufferObject.viewMatrix = glm::lookAt(6.5f * normal, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
cameraBufferObject.projectionMatrix = glm::perspective(glm::radians(60.0f), aspectRatio, nearPlane, farPlane);
cameraBufferObject.projectionMatrix[1][1] *= -1; // y-coordinate is flipped
BufferUtils::CreateBuffer(device, sizeof(CameraBufferObject), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, buffer, bufferMemory);
vkMapMemory(device->GetVkDevice(), bufferMemory, 0, sizeof(CameraBufferObject), 0, &mappedData);
memcpy(mappedData, &cameraBufferObject, sizeof(CameraBufferObject));
}
VkBuffer Camera::GetBuffer() const {
return buffer;
}
void Camera::UpdateOrbit(float deltaX, float deltaY, float deltaZ) {
theta += deltaX;
phi += deltaY;
r = glm::clamp(r - deltaZ, 1.0f, 50.0f);
float radTheta = glm::radians(theta);
float radPhi = glm::radians(phi);
glm::mat4 rotation = glm::rotate(glm::mat4(1.0f), radTheta, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::rotate(glm::mat4(1.0f), radPhi, glm::vec3(1.0f, 0.0f, 0.0f));
glm::mat4 finalTransform = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f)) * rotation * glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 1.0f, r));
cameraBufferObject.viewMatrix = glm::inverse(finalTransform);
memcpy(mappedData, &cameraBufferObject, sizeof(CameraBufferObject));
}
void Camera::TranslateCamera(glm::vec3 translation) {
this->eye += translation;
glm::vec3 normal = normalize(this->eye - glm::vec3(0.f, 1.f, 0.0));
cameraBufferObject.viewMatrix = glm::lookAt(6.5f * normal, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
memcpy(mappedData, &cameraBufferObject, sizeof(CameraBufferObject));
}
Camera::~Camera() {
vkUnmapMemory(device->GetVkDevice(), bufferMemory);
vkDestroyBuffer(device->GetVkDevice(), buffer, nullptr);
vkFreeMemory(device->GetVkDevice(), bufferMemory, nullptr);
}
| true |
a0c5cdff6a09d3612fde857f3d907148c0b71aae | C++ | jackp1711/Basic_RayTracer | /camera.h | UTF-8 | 1,321 | 3.578125 | 4 | [] | no_license | /*
Class to store information about the camera in relation to the world coordinate system.
Includes implementation to set the lookAt point and the position of the camera, updating
the necessary vectors in the mean time.
*/
#pragma once
#include "vector.h"
#include "vertex.h"
class Camera{
public:
Vertex position;
Vector worldX = Vector(1,0,0);
Vector worldY = Vector(0,1,0);
Vector worldZ = Vector(0,0,1);
Vector up;
Vector left;
Vector down;
Vertex eye;
Vertex lookAt;
Vector lookAtVector;
float distance;
Camera()
{
position.x = 0;
position.y = 0;
position.z = 0;
position.w = 1;
}
Camera(float x, float y, float z)
{
position.x = x;
position.y = y;
position.z = z;
position.w = 1;
}
void setLookAt(float x, float y, float z)
{
lookAt.x = x;
lookAt.y = y;
lookAt.z = z;
lookAt.w = 1;
lookAtVector.x = x - position.x;
lookAtVector.y = y - position.y;
lookAtVector.z = z - position.z;
worldY.cross(lookAtVector, left);
left.cross(lookAtVector, up);
}
void setDistance(float d)
{
distance = d;
}
}; | true |
27d1f5d4dacd198328af0950c12538126e483ce9 | C++ | Kousuke-N/kyopuro | /20200711/20200711.cpp | UTF-8 | 184 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int L;
int R;
int d;
cin >> L >> R >> d;
int h = R / d;
int i = L / d + 1;
cout << R / d - (L - 1) / d << '\n';
} | true |
4b5a984492eed4af69a98cc714277a7ec695a37f | C++ | artur-kink/game | /GameEngine/Tile.hpp | UTF-8 | 617 | 2.828125 | 3 | [] | no_license | #ifndef _TILE_HPP
#define _TILE_HPP
#include <cstdint>
#define TILE_SIZE 32
#define NUM_LAYERS 3
class Tile{
private:
uint32_t attributes;
public:
enum TileAttributes{
Blocked = 0x01,
Arable = 0x02,
Plowed = 0x04,
Water = 0x08
};
uint16_t layers[NUM_LAYERS];
void setAttribute(uint32_t attr, bool val = true);
bool isBlocked();
void setBlocked(bool val = true);
bool isArable();
void setArable(bool val = true);
bool isPlowed();
void setPlowed(bool val = true);
bool isWater();
void setWater(bool val = true);
};
#endif
| true |
66e9021742b83cf7078473ad8f3aa06fe6e7c0e6 | C++ | SideDivisionCommander/AlgCoding | /Question/SlidingWindow/no_159/solution.cpp | UTF-8 | 1,134 | 2.96875 | 3 | [] | no_license | class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
if (Init(s) == 0) {
return 0;
}
return Process(s);
}
private:
unordered_map<char, int> helpMap;
int maxDis;
int Init(string& s)
{
maxDis = 2;
return s.size();
}
int Process(string& s)
{
int left = 0;
int right = 0;
int res = 0;
while(right < s.size()) {
if (helpMap.count(s[right]) > 0) {
helpMap[s[right]]++;
res = max(res, right - left + 1);
right++;
} else {
if (helpMap.size() < maxDis) {
helpMap.insert(pair<char, int>(s[right], 0));
} else if (helpMap.size() == maxDis) {
if (helpMap[s[left]] > 1) {
helpMap[s[left]]--;
} else if (helpMap[s[left]] == 1) {
helpMap.erase(s[left]);
}
left++;
}
}
}
return res;
}
}; | true |
f5bd44d15870ee1aa696f5f2c194c7dea9fc2352 | C++ | ysk24ok/leetcode-submissions | /0152/dp_constant_space.cpp | UTF-8 | 1,049 | 3.21875 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int maxProduct(vector<int>& nums) {
if (nums.size() == 0) { return 0; }
int prev_max = 1, prev_min = 1, curr_max = 0, curr_min = 0;
int ret = numeric_limits<int>::min();
for (size_t i = 0; i < nums.size(); i++) {
int val1 = prev_max * nums[i];
int val2 = prev_min * nums[i];
curr_max = max({nums[i], val1, val2});
curr_min = min({nums[i], val1, val2});
ret = max(curr_max, ret);
prev_max = curr_max;
prev_min = curr_min;
}
return ret;
}
};
int main() {
Solution sol;
vector<int> nums;
int expected;
nums = {2, 3, -2, 4};
expected = 6;
EXPECT_EQ(expected, sol.maxProduct(nums));
nums = {-2, 0, -1};
expected = 0;
EXPECT_EQ(expected, sol.maxProduct(nums));
nums = {-2};
expected = -2;
EXPECT_EQ(expected, sol.maxProduct(nums));
nums = {-4, -3, -2};
expected = 12;
EXPECT_EQ(expected, sol.maxProduct(nums));
exit(EXIT_SUCCESS);
}
| true |
3b4ba308221f763a39ee44cbbead3658ca8f6392 | C++ | eChadwick/Unguided_Search | /Project 1/main.cpp | UTF-8 | 3,216 | 3.6875 | 4 | [] | no_license | //
// main.cpp
// Project 1
//
// Created by Chadwick,Eric on 1/25/18.
// Copyright © 2018 Eric Chadwick. All rights reserved.
//
#include <iostream>
#include <iomanip>
#include <math.h>
#include <vector>
using namespace std;
// Calculates the probability of winning when presented with num_tokens on your turn and saves it to solutions array.
//
// @param num_tokens is the number of tokens for which the win probability will be calculated.
// @param solved is an array that will hold the solutions to probabilities already calculated.
// @return is a pair in which the second element is the number of possible outcomes from num_tokens and the first element is the number
// of those that are wins.
pair<double, double> win_prob(int num_tokens, pair<double, double> solved[]){
// If already solved for num_tokens, return cached solution value.
if(solved[num_tokens].second != 0)
return solved[num_tokens];
// Base case. With 1 token you are hosed.
else if(num_tokens == 1){
solved[num_tokens].first = 0;
solved[num_tokens].second = 1;
cout << "1 token - win probability: 0.0000%, best move: take 1, result 0.0000% win probability." << endl;
return solved[num_tokens];
// Do the calculation.
} else {
pair<double, double> temp_prob(0,0); // This will be used to hold the working win probability at this node.
pair<double, double> worst_opponent_prob(1,1); // Win probability of worst child node.
int take = 0; // Take this many to generate worst child node.
// Generate children of current node. These represent the possible states on opponent's turn.
for(int i = floor(num_tokens / 2); i > 0; i--){
// calcuate the win probability of child node (probability of opponent win).
pair<double, double> child_prob = win_prob(num_tokens - i, solved);
// If this child is the worst win probability, save the probability and the number of tokens taken to achieve it.
if(child_prob.first / child_prob.second <= worst_opponent_prob.first / worst_opponent_prob.second){
worst_opponent_prob = child_prob;
take = i;
}
// Sum total outcomes and losing outcomes of children (i.e. winning outcomes of parent node).
temp_prob.first += child_prob.second - child_prob.first;
temp_prob.second += child_prob.second;
}
// Cache solution for this node.
solved[num_tokens] = temp_prob;
// Print out relevent info.
cout << fixed << setprecision(4);
cout << num_tokens << " tokens - win probability: " << temp_prob.first / temp_prob.second * 100 << "%, best move: take " << take <<
" result " << (1 - (worst_opponent_prob.first / worst_opponent_prob.second)) * 100 << "%"<<
" win probability." << endl;
// Return probability with num_tokens
return temp_prob;
}
}
int main() {
pair<double, double> p_solutions[501];
cout << "If it is your turn with: " << endl;
win_prob(500, p_solutions);
return 0;
}
| true |
22684a3f6af5ae52973c03fb7ec2952da6b67462 | C++ | haeunyoung/algorithmStudy | /algorithm/algorithm/day31_1647.cpp | UTF-8 | 1,237 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int n, m;
int getParent(int set[], int x)
{
if (set[x] == x) return x;
return set[x] = getParent(set, set[x]);
}
void unionParent(int set[], int a, int b)
{
a = getParent(set, a);
b = getParent(set, b);
if (a < b) set[b] = a;
else set[a] = b;
}
int find(int set[], int a, int b)
{
a = getParent(set, a);
b = getParent(set, b);
if (a == b) return 1;
else return 0;
}
class Edge {
public:
int node[2];
int distance;
Edge(int a, int b, int distance) {
this->node[0] = a;
this->node[1] = b;
this->distance = distance;
}
bool operator<(Edge& edge)
{
return this->distance < edge.distance;
}
};
int main(void)
{
cin >> n >> m;
vector<Edge> v;
int h1, h2, k;
for (int i = 0; i < m; i++)
{
scanf("%d %d %d", &h1, &h2, &k);
v.push_back(Edge(h1, h2, k));
}
sort(v.begin(), v.end());
int set[n+1];
for (int i = 1; i <= n; i++)
{
set[i] = i;
}
int sum = 0;
int last_k;
for (int i = 0; i < v.size(); i++)
{
if (!find(set, v[i].node[0], v[i].node[1]))
{
sum += v[i].distance;
last_k = v[i].distance;
unionParent(set, v[i].node[0], v[i].node[1]);
}
}
printf("%d\n", sum-last_k);
} | true |
0bf5572f1780e2a5919c94e3f9bcec2c440adb61 | C++ | AnjolaTope/C_PLUS_PLUS_PRACTICE | /Resize_dynamic_array.cpp | UTF-8 | 1,546 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include<fstream>
#include<string>
using namespace std;
// this is the morespace function that increases the size of the array
int morespace(string* &p,int &size) {
int s=0;
s=size+10;
string* pointer;
pointer = new string[s];
for (int i = 0; i < size; i++)
{
pointer[i] = p[i] ;
}
delete[]p;
p = pointer;
return s;
}
int main()
{
ifstream file;
string* list;
int n = 10;
// this Initializes the original array. This array has ten elements
list = new string[n];
cout <<"The initial array contains: "<< n <<" elements"<<endl;
file.open("List.txt",ios::in);
//this opens the file and inserts the first ten elements in the file into the array
if (file.is_open())
{
for (int i = 0; i < n; i++)
{
file >> list[i];
cout << list[i] << endl;
}
}
// this dynamically increases the size of the array when there are still elements in the file
while(!file.eof() )
{
if (list[n - 1] != "")
{
// this is the morespace function that increases the size of the array
morespace(list, n);
}
// the morespace function returns the new size of the array
// the new size of the array is put into the variable n
cout <<"The new array contains: "<< n << " elements"<< endl;
n= morespace(list, n);
// The elemnts in the file are added to the new array
for (int i = n-10; i < n; i++)
{
file >> list[i];
cout << list[i] << endl;
}
}
delete[]list;
return 0;
}
| true |
1649c920efd5139f3b9239797c7675c9d4f24b54 | C++ | LichuHaung/Zero_Judge_CPP | /d186.cpp | UTF-8 | 288 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a,b,c=0,d,i;
while(cin>>a>>b)
{
c=0;
for(;a<=b;a++)
{
for(i=0;i<=b;i++)
{
d=i*i;
if(a==d)
{
c++;
}
}
}
if(a==10&&b==0)
{
break;
}
cout<<c<<endl;
}
}
| true |
7ac7bafa800ed0e9d6061359776eb0f7127a70e2 | C++ | david4u/ACSYSLab | /First Task/ACSYSMatMul/singleThread.cpp | UTF-8 | 2,351 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <time.h>
using namespace std;
// 더 빠르게 하는 방법.
// 월요일 온라인 1시반
int** makeMAT(int n) {
int** mat = new int*[n];
for (int i = 0 ;i < n; i++) {
mat[i] = new int[n];
}
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
mat[r][c] = rand() % 10 - 4;
}
}
return mat;
}
int** makeZero(int n) {
int** mat = new int*[n];
for (int i = 0; i < n ;i++) {
mat[i] = new int[n];
}
for (int r = 0; r < n; r++) {
for (int c = 0; c < n ; c++) {
mat[r][c] = 0;
}
}
return mat;
}
int** makeIdentity(int n) {
int** mat = new int*[n];
for (int i = 0; i< n; i++) {
mat[i] = new int[n];
}
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
mat[r][c] = 0;
}
mat[r][r] = 1;
}
return mat;
}
int** matmul1(int** m1, int** m2,int** ret, int n) { // n -> original size, m-> parted size
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
for (int i = 0; i < n ; i++) {
ret[r][c] += m1[r][i] * m2[i][c];
}
}
}
return ret;
}
int main() {
// initiallize
struct timespec begin, end ;
int** mat1 = makeMAT(2048);
int** mat2 = makeMAT(2048);
int** mat3 = makeZero(2048);
int** matI = makeIdentity(2048);
int** test1 = makeZero(2048);
int** test2 = makeZero(2048);
clock_gettime(CLOCK_MONOTONIC, &begin);
matmul1(mat1, mat2, mat3, 2048);
clock_gettime(CLOCK_MONOTONIC, &end);
cout << (end.tv_sec - begin.tv_sec) + (end.tv_nsec - begin.tv_nsec) / 1000000000.0 << endl;
matmul1(mat1, matI, test1, 2048);
matmul1(matI, mat1, test2, 2048);
for (int r = 0; r < 2048; r++) {
for (int c = 0; c < 2048; c++) {
if (!(mat1[r][c] == test1[r][c] && mat1[r][c] == test2[r][c] && test1[r][c] == test2[r][c])) {
cout << r << ", " << c << " takes wrong value [ mat ] vs [ test1 ] vs [ test2 ] : [ " << mat1[r][c] << " ] vs [ " <<
test1[r][c] << " ] vs [ " << test2[r][c] << " ]\n";
}
}
}
cout << "TEST DONE\n";
for (int i = 0; i < 2048; i++) delete[] mat1[i];
for (int i = 0; i < 2048; i++) delete[] mat2[i];
for (int i = 0; i < 2048; i++) delete[] mat3[i];
for (int i = 0; i < 2048; i++) delete[] matI[i];
for (int i = 0; i < 2048; i++) delete[] test1[i];
for (int i = 0; i < 2048; i++) delete[] test2[i];
delete[] mat1;
delete[] mat2;
delete[] mat3;
delete[] matI;
delete[] test1;
delete[] test2;
} | true |
c42e33594f5b21a531649a80bf8a4a749b549572 | C++ | tedsta/FissionPong | /src/PlayerControlSystem.cpp | UTF-8 | 2,020 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "PlayerControlSystem.h"
#include "Paddle.h"
#include "Velocity.h"
PlayerControlSystem::PlayerControlSystem(fsn::EntityManager& entityMgr) : fsn::ComponentSystem(entityMgr),
mKeyW(false), mKeyS(false), mKeyUp(false), mKeyDown(false)
{
all<Paddle, Velocity>();
}
PlayerControlSystem::~PlayerControlSystem()
{
//dtor
}
void PlayerControlSystem::processEntity(const fsn::EntityRef& entity, const float dt)
{
auto& vel = entity.getComponent<Velocity>();
auto& paddle = entity.getComponent<Paddle>();
if (paddle.deflectDir == 1)
{
if (mKeyW)
vel.y = -300;
else if (mKeyS)
vel.y = 300;
else
vel.y = 0;
}
else if (paddle.deflectDir == -1)
{
if (mKeyUp)
vel.y = -300;
else if (mKeyDown)
vel.y = 300;
else
vel.y = 0;
}
}
bool PlayerControlSystem::onKeyPressed(sf::Keyboard::Key key)
{
switch (key)
{
case sf::Keyboard::Key::W:
{
mKeyW = true;
break;
}
case sf::Keyboard::Key::S:
{
mKeyS = true;
break;
}
case sf::Keyboard::Key::Up:
{
mKeyUp = true;
break;
}
case sf::Keyboard::Key::Down:
{
mKeyDown = true;
break;
}
default:
break;
}
return false;
}
bool PlayerControlSystem::onKeyReleased(sf::Keyboard::Key key)
{
switch (key)
{
case sf::Keyboard::Key::W:
{
mKeyW = false;
break;
}
case sf::Keyboard::Key::S:
{
mKeyS = false;
break;
}
case sf::Keyboard::Key::Up:
{
mKeyUp = false;
break;
}
case sf::Keyboard::Key::Down:
{
mKeyDown = false;
break;
}
default:
break;
}
return false;
}
| true |
21cdf5b1a6f10e76e0348a4120c8fbc5158527fa | C++ | lilelr/LeecodeProblemsSolutionsByC- | /dp/PerfectSquares/Solution.h | UTF-8 | 2,698 | 3.015625 | 3 | [] | no_license | //
// Created by YuXiao on 7/19/16.
//
#ifndef LEECODEPROBLEMSSOLUTIONSBYC__SOLUTION_H
#define LEECODEPROBLEMSSOLUTIONSBYC__SOLUTION_H
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
//https://discuss.leetcode.com/topic/24255/summary-of-4-different-solutions-bfs-dp-static-dp-and-mathematics/2
using namespace std;
class Solution {
public:
int numSquares(int n) {
if (n <= 0) {
return 0;
}
vector<int> cntSqures(n + 1, INT_MAX);
cntSqures[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j * j <= i; j++) {
cntSqures[i] = min(cntSqures[i], cntSqures[i - j * j] + 1);
}
}
return cntSqures.back();
}
// 12ms static vector static is not used, it would cost 312ms.
int numSquares2(int n) {
if (n <= 0) {
return 0;
}
static vector<int> cntSqures({0});
while (cntSqures.size() <= n) {
int curSize = cntSqures.size();
int newSqures = INT_MAX;
for (int j = 1; j * j <= curSize; j++) {
newSqures = min(newSqures, cntSqures[curSize - j * j] + 1);
}
cntSqures.push_back(newSqures);
}
return cntSqures[n];
}
//BFS 80ms
int numSquares3(int n) {
if(n <=0){
return 0;
}
vector<int> perfectSquares;
vector<int> cntPerfectSquares(n);
for(int i=1;i*i<=n;i++){
perfectSquares.push_back(i*i);
cntPerfectSquares[i*i-1] = 1;
}
if(perfectSquares.back() == n){
return 1;
}
queue<int> searchQ;
for(auto& item: perfectSquares){
searchQ.push(item);
}
int currCntPerfectSquares = 1;
while (!searchQ.empty()){
currCntPerfectSquares++;
int searchQSize = searchQ.size();
for(int i=0;i< searchQSize;i++){
int frontItem = searchQ.front();
for(auto& j:perfectSquares){
if(frontItem+j == n){
return currCntPerfectSquares;
}
else if ((frontItem+j <n) && (cntPerfectSquares[frontItem+j-1] == 0)){
cntPerfectSquares[frontItem+j-1] = currCntPerfectSquares;
searchQ.push(frontItem+j);
}
else if(frontItem+j > n){
break;
}
}
searchQ.pop();
}
}
return 0;
}
};
#endif //LEECODEPROBLEMSSOLUTIONSBYC__SOLUTION_H
| true |
94798d3a90b7fec13c519ab694bb48068bfbfa14 | C++ | RafigRzayev/BasicCppCourseProjects | /HomeWork7/bubblesort.hpp | UTF-8 | 642 | 3.546875 | 4 | [] | no_license | // BUBBLE SORT FROM HW4
#pragma once
#include <functional>
#include <iostream>
using CompDouble = std::function<bool(double, double)>;
void bubble_sort(double *begin, const double *const end, CompDouble predicate) {
if (begin == nullptr || end == nullptr) {
std::cout << "bubble_sort() - Exception\n";
return;
}
while (true) {
double *it{begin};
size_t swap_counter{0};
while (it != end - 1) {
if (predicate(*it, *(it + 1))) {
double temp{*it};
*it = *(it + 1);
*(it + 1) = temp;
++swap_counter;
}
++it;
}
if (swap_counter == 0) {
break;
}
}
} | true |
4954a83f62dbb44b9c7e7b0351c3dbdf7352f28f | C++ | ethanjob98/solve-puzzle-8 | /main.cpp | UTF-8 | 1,180 | 3.125 | 3 | [] | no_license | #include"controller.hpp"
using namespace std;
void given();
void custom();
int main(){
int choice;
cout << "What type: \n" << "(1) CUSTOM\n(2) GIVEN\nANSWER: " ;
cin >> choice;
choice == 1 ? custom() : given();
return 0;
}
void custom(){
vector<int> row1;
vector<int> row2;
vector<int> row3;
int a;
for(int i = 0; i < 9; i++){
cin >> a;
if(i <= 2){
row1.push_back(a);
}
else if(i <= 5){
row2.push_back(a);
}
else{
row3.push_back(a);
}
}
Board b(row1,row2,row3);
Node n(b);
Controller c;
c.solve(n);
// cout << "FINISHED:\n";
// c.goal->printBoard();
// c.goal->parent->printBoard();
c.printSolution();
}
void given(){
vector<int> row1;
row1.push_back(7);
row1.push_back(2);
row1.push_back(4);
vector<int> row2;
row2.push_back(5);
row2.push_back(0);
row2.push_back(6);
vector<int> row3;
row3.push_back(8);
row3.push_back(3);
row3.push_back(1);
Board b(row1,row2,row3);
Node n(b);
Controller c;
c.solve(n);
c.printSolution();
} | true |
7aa558b43833210b17661b3fd46d4302340e7ed0 | C++ | WM-CS544/NACHOS3 | /threads/resmanager.cc | UTF-8 | 969 | 3.203125 | 3 | [
"MIT-Modern-Variant"
] | permissive | // resmanager.cc
//
// Implemented in "monitor"-style -- surround each procedure with a
// lock acquire and release pair, using condition signal and wait for
// synchronization.
//
#include "resmanager.h"
#include <new>
ResManager::ResManager()
{
lock = new(std::nothrow) Lock("resmanager lock");
gotsome = new(std::nothrow) Condition("gotsome");
inventory = NUMUNITS;
}
ResManager::~ResManager()
{
delete lock;
delete gotsome;
}
void
ResManager::Request(int num)
{
lock->Acquire(); // entering the "monitor" ... get mutex
while (num > inventory) gotsome->Wait(lock); // Keep trying until
// sufficient free units.
inventory -= num;
lock->Release();
}
void
ResManager::Release(int num)
{
lock->Acquire();
inventory += num;
gotsome->Broadcast(lock); // Let ALL sleepers retry.
lock->Release();
}
| true |
f3dc577a37a1799d796e9716d2e923538a62e229 | C++ | Aarth-Tandel/DataStructures | /competitive/Data Structure/Tree/insertingnode.cpp | UTF-8 | 1,006 | 3.6875 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct tnode {
int data;
struct tnode *left,*right;
};
struct tnode* newnode(int data)
{
struct tnode* new_node = new tnode();
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void inorder(struct tnode *root)
{
if(root==NULL) return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
struct tnode* insert(struct tnode *root, int key)
{
if(root==NULL)
{
root=newnode(key);
cout<<root->data;
return root;
}
if(root->data>key) return insert(root->left,key);
else return insert(root->right,key);
}
int main()
{
struct tnode *root = NULL;
int n;
cin>>n;
for(int i=0; i<n; i++)
insert(root,i);
inorder(root);
return 1;
}
| true |
3fa97672777a90ad677ab37f0475f97e85ae668d | C++ | letyletylety/ps2016 | /1035.cpp | UTF-8 | 2,511 | 2.59375 | 3 | [] | no_license | #include <cstdio>
#include <map>
#include <queue>
#include <memory.h>
using namespace std;
map<int, int> d;
map<int, int> b;
bool visited[25];
int cnt = 0;
int diff[4] = {-1,1,-5,5};
bool isCoordi(int oldpos, int pos)
{
if(pos < 0 || 25 <= pos) return false;
if(pos % 5 == 0)
{
if(oldpos == pos - 1)
return false;
}
if(oldpos % 5 == 0)
{
if(pos == oldpos - 1)
return false;
}
return true;
}
bool connected(vector<int> & v, int id)
{
// bfs
queue<int> q;
memset(visited, 0, sizeof(visited));
// for(int &i : v)printf("%d ", i);
q.push(v[0]);
visited[v[0]] = 1;
int cc = 0;
while(!q.empty())
{
int tt = q.front(); q.pop();
cc++;
int newpos;
for(int i = 0 ; i < 4 ; i++)
{
newpos = tt + diff[i];
if(isCoordi(tt, newpos) && !visited[newpos] && (id & (1<<newpos)))
{
q.push(newpos);
visited[newpos] = 1;
}
}
}
// printf("%d\n", cc);
return (cc == ::cnt);
}
int main()
{
char tt;
int ori = 0;
for(int i = 0 ; i < 25; i++)
{
scanf(" %c", &tt);
if(tt == '*')
{
ori |= (1<<i);
cnt++;
}
}
// vector<int> star;
// for(int i = 0; i < 25 ;i++)
// {
// if(ori & (1<<i))
// star.push_back(i);
// }
//
// for(int i : star)
// printf("%d ", i);
//
// if(connected(star, ori))
// {
// printf("GOOD");
// }
//
// return 0;
if(cnt <= 1){ puts("0"); return 0;}
d[ori] = 0;
queue<int> q;
q.push(ori);
d[ori] = 0;
while(!q.empty())
{
int tt = q.front();q.pop();
vector<int> star;
// for(int i = 0 ; i < 5; i++)
// {
// for(int j = 0; j < 5; j++)
// {
// printf("%d",((1<<(i*5+j)) == ( tt & (1<<(i*5 + j)))));
// }
// puts("");
// }
// puts("");
for(int i = 0; i < 25 ;i++)
{
if(tt & (1<<i))
star.push_back(i);
}
if(connected(star, tt))
{
// printf("GOOD");
printf("%d", d[tt]);
// while(tt != ori)
// {
// tt = b[tt];
// vector<int> star;
// for(int i = 0; i < 25 ;i++)
// {
// if(tt & (1<<i))
// star.push_back(i);
// }
// for(int &i : star) printf("%d ", i);
// puts("");
// }
break;
}
for(int i = 0 ; i < star.size(); i++)
{
for(int j = 0 ; j < 4; j++)
{
int newpos = star[i] + diff[j];
int newtt = tt;
if(isCoordi(star[i], newpos) && (tt & (1<<newpos)) == 0)
{
newtt -= (1<<star[i]);
newtt |= (1<<newpos);
if(d.count(newtt) == 0)
{
d[newtt] = d[tt] + 1;
b[newtt] = tt;
q.push(newtt);
}
}
else
{
continue;
}
}
}
}
return 0;
}
| true |
def3edd3fa56a340d526eba5963e4850c90a9f4b | C++ | ericniebler/coronet | /include/coronet/detail/noop_coroutine.hpp | UTF-8 | 2,281 | 2.546875 | 3 | [
"BSL-1.0"
] | permissive | // coronet - An experimental networking library that supports both the
// Universal Model of the Networking TS and the coroutines of
// the Coroutines TS.
//
// Copyright Eric Niebler 2017
// Copyright Lewis Baker 2017
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/coronet
//
#ifndef CORONET_DETAIL_NOOP_COROUTINE_HPP
#define CORONET_DETAIL_NOOP_COROUTINE_HPP
#include <experimental/coroutine>
namespace coronet
{
namespace detail
{
class _noop_coroutine_gen final
{
public:
struct promise_type final
{
_noop_coroutine_gen get_return_object() noexcept;
std::experimental::suspend_never initial_suspend() noexcept
{
return {};
}
std::experimental::suspend_never final_suspend() noexcept
{
return {};
}
void unhandled_exception() noexcept {}
void return_void() noexcept {}
};
static std::experimental::coroutine_handle<> value() noexcept
{
static const auto s_value = coroutine().coro_;
return s_value;
}
private:
explicit _noop_coroutine_gen(promise_type& p) noexcept
: coro_(std::experimental::coroutine_handle<
promise_type>::from_promise(p))
{}
static _noop_coroutine_gen coroutine()
{
for(;;)
{
co_await std::experimental::suspend_always{};
}
}
const std::experimental::coroutine_handle<> coro_;
};
inline _noop_coroutine_gen _noop_coroutine_gen::promise_type::
get_return_object() noexcept
{
return _noop_coroutine_gen{*this};
}
} // namespace detail
inline std::experimental::coroutine_handle<> noop_coroutine()
{
return detail::_noop_coroutine_gen::value();
}
}
#endif
| true |
a8fb3e936c2d432f98172eabbee532367a33cc97 | C++ | coderfamer/linuxstudy | /c++/c++primer_3/10/ex10_13.cpp | UTF-8 | 640 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool isfive(string str)
{
if (str.size() < 5)
{
return false;
}
return true;
}
auto print(vector<string> svec)
{
for (auto const &w : svec)
{
cout << w << " ";
}
cout << endl;
}
int main()
{
vector<string > svec;
for (string str; cout << "Enter a str:\n", cin >> str && str != "@q";)
{
svec.push_back(str);
}
print(svec);
auto true_end = partition(svec.begin(), svec.end(), isfive);
print(svec);
svec.erase(true_end, svec.end());
print(svec);
return 0;
}
| true |
a4f988efaa20da177b4102df3ff57cf970d5250d | C++ | mbkhan721/C-Plus-Plus | /ExprHW04.cpp | UTF-8 | 689 | 3.5625 | 4 | [] | no_license | #include<iostream>
using namespace std;
int expHw() {
/*
// 1.
int x, digit;
cout << "Enter a 3-digit integer: ";
cin >> x;
int y = x;
digit = x % 10;
cout << "Is " << digit << " a factor of " << y << "? " << (y % digit == 0) << endl;
x /= 10;
digit = x % 10;
cout << "Is " << digit << " a factor of " << y << "? " << (y % digit == 0) << endl;
x /= 10;
digit = x % 10;
cout << "Is " << digit << " a factor of " << y << "? " << (y % digit == 0) << endl << endl;
int dollars;
cout << "Enter a dollar amount as an integer: ";
cin >> dollars;
cout << dollars << endl;
dollars %= 25;
cout << "Optimal number of dimes: " << (dollars / 10) << endl;
*/
return 0;
} | true |
011709135cb6efbb99e35d4fdb4bbdadb49ee532 | C++ | DuongNguyenHai/C-Program | /C++/B-6.cpp | UTF-8 | 1,234 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h> // exit()
// n la so ky tu phair cat, m la tong so ky tu
char *trichphai(char s[], int n, int m){
int i=0;
char *str = (char *)malloc(128);
while( s[i]!='\0' ){
str[i] = s[m-n+i];
i++;
if(i>n) break;
}
str[i]='\0';
return str;
}
void doctep(char s[],int &m){
FILE *pfile;
pfile = fopen("file/B-6-read.txt","r");
// kiem tra xem co mo duoc file khong, neu khong thi se bao loi va ket thuc chuong trinh,
// gia tri tra ve qua ham exit() la -1
if(pfile==NULL){
perror("error opening file");
exit(-1);
}
// copy toan bo cac ky tu trong file ra s[], bao gom ca ky tu space, tab, newline ...
while( !feof(pfile) ){
s[m]=fgetc(pfile);
m++;
}
m--;
s[m]='\0';
}
int main(){
char s[128]; // chuoi trong file chi chua toi da 128 ky tu
int n=0;
int m=0; // bien cho tong so ky tu, tong ky tu bao gom ca space, tab, newline
doctep(s,m);
printf("chuoi : \"%s\"\nso luong ky tu la:%d\n",s,m);
printf("Trich phai n ky tu, ban hay nhap n:\n");
printf("n = ");scanf("%d",&n);
if( n>=m){
printf("n phai no hon so luong ky tu");
return 0;
}
printf("chuoi cat duoc : \"%s\"",trichphai(s,n,m));
return 1;
}
| true |
7eb436dbca3c9e786e533d8abb0d457eb4bfa28c | C++ | gregfeng08/linkedList | /main.cpp | UTF-8 | 2,015 | 4.15625 | 4 | [] | no_license | #include <iostream>
#include <cstring>
#include "Node.h"
#include "Student.h"
/*
Linked lists project
Written by: Gregory Feng
This program takes in the name and ID of a student and adds them to a linked list.
Problems: Working on fixing the segfault on the second node creation
*/
using namespace std;
Node* head = NULL; //Node creation
void print(Node* next); //Initial var definitions
void add(char* name, int id);
int main() {
char userInput[20];
bool running = true;
char name[20];
int id;
cout << "Welcome to student list: Linked lists!" << endl;
while(running) { //Loop until quit
cout << "What would you like to do? (ADD/PRINT/DELETE/QUIT)" << endl;
cin >> userInput;
if (strcmp(userInput, "ADD") == 0) {
cout << "Name?" << endl;
cin >> name;
cin.clear();
cin.ignore(999, '\n');
cout << "ID?" << endl;
cin >> id;
add(name, id); //Uses the add function to add the name and ID
cout << "Successfully added!" << endl;
}
else if (strcmp(userInput, "PRINT") == 0) { //Prints the linked list
print(head);
}
else if (strcmp(userInput, "QUIT") == 0) { //Stops the program
running = false;
}
}
}
void add(char* name, int id) { //Adds the inputted information into the linked node
Student* newvalue = new Student(name, id);
Node* current = head;
if (current == NULL) {
head = new Node();
head->setValue(newvalue); //Adds this to the very end of the list
} else {
while (current->getNext() != NULL) {
current = current->getNext();
}
current->setNext(new Node());
current->getNext()->setValue(newvalue);
}
}
void print(Node* next) { //Prints the linked list and all of the information
if (next == head) {
cout << "list:";
}
if (next != NULL) {
cout << next->getValue()->getName() << ", " << next->getValue()->getID() << " ";
print(next->getNext()); //Recalls the print function so that it keeps printing until it hits a NULL node
}
cout << endl;
}
| true |
66923957b39dfde8f7aad5b8c0ac826b2993aff7 | C++ | tashbeeh25/MiniProject | /ReadWords.h | UTF-8 | 917 | 3.171875 | 3 | [] | no_license | /**
ReadWords.h file
**/
#ifndef _READWORDS_H_
#define _READWORDS_H_
using namespace std;
#include <iostream>
#include <string>
#include <fstream>
class ReadWords
{
public:
//Constructor. Opens the file with the given file name.
//Prints an error message then terminates the program if file does not exist.
ReadWords(const char *filename);
//Closes the file.
void close();
//Returns a string, being the next word in the file. All letters are converted
//to lower case
//Leading and trailing punctuation marks are not included in the word
string getNextWord();
//Returns true if there is a further word in the file, false if we have reached the
//end of file.
bool isNextWord();
private:
string nxtW; //next words
ifstream fileofwords;
bool eoffound;
};
#endif
| true |
88b3de0361391ce85ee8d888c718091b2d0c34a4 | C++ | JHegelund/EDAF50 | /Lab2/dictionary.h | UTF-8 | 638 | 2.78125 | 3 | [] | no_license | #ifndef DICTIONARY_H
#define DICTIONARY_H
#include <string>
#include <vector>
#include <map>
#include "word.h"
class Dictionary {
public:
Dictionary();
Word wordify(const std::string& str);
bool contains(const std::string& word) const;
std::vector<std::string> get_suggestions(const std::string& word) const;
private:
std::map<int, std::vector<Word>> words;
void add_trigram_suggestions(std::vector<std::string>& suggestions, const std::string word) const;
void rank_suggestions(std::vector<std::string>& suggestions, const std::string word) const;
void trim_suggestions(std::vector<std::string>& suggestions) const;
};
#endif
| true |
cbd405e172745c7c66e102abafdfadab4bf6acca | C++ | mayankDhiman/cp | /codeforces/contests/1324/B.cpp | UTF-8 | 521 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll t; cin >> t;
while (t --)
{
ll n; cin >> n;
vector <ll> pos[5001];
for (ll i = 0; i < n; i ++){
ll x; cin >> x;
pos[x].push_back(i);
}
bool ok = 0;
for (ll m = 1; m <= 5000; m ++)
{
if (pos[m].size() > 2){
ok = 1;
break;
}
if (pos[m].size() == 2){
if (pos[m][1] - pos[m][0] > 1){
ok = 1;
break;
}
}
}
if (ok){
cout << "YES\n";
}
else{
cout << "NO\n";
}
}
} | true |
aa75205bb5ca9693a74797595ab20f1ebd33e5cd | C++ | Johndhawk2/PAM | /Main-Device-Code/BLEDataTransmission/BLEDataTransmission.ino | UTF-8 | 4,606 | 2.828125 | 3 | [] | no_license | #include <SoftwareSerial.h> // Include Libraries
#include <SPI.h>
#include <SD.h>
SoftwareSerial mySerial(7,8); // RX, TX // Setup BLE communication
#define SDChipSelect 6
#define datLengthMax 12
void setup() {
Serial.begin(57600); // Start Serial Communication
mySerial.begin(9600); // Start BLE communication
Serial.print(F("Initializing SD card...")); // Initialise SD card
if (!SD.begin(SDChipSelect)) {
Serial.println(F("initialization failed!"));
while (1);
}
Serial.println(F("initialization done."));
}
void loop() {
String fileNameTest = "TestFile.csv"; // Open Test File
if (mySerial.available()) { // If BLE request available
char buf = mySerial.read(); // Read request
static String readVal;
if(buf == 10){
if(readVal == "datReq"){ // If BLE requests data
Serial.println(F("Sending Data"));
dataRequest(fileNameTest); // Send data
}
else{
Serial.println(readVal);
readVal = "";
}
}
else{ // Read request
readVal += buf;
}
}
}
void dataRequest(String fileNameRecall){
File readFile = SD.open(fileNameRecall); // Open file to read data
if (readFile) {
while(readFile.available()){
delay(5); // Delay to make processing simpler
uint32_t datRead[datLengthMax] = {0}; // Setup buffer for reading
uint8_t datLength = lineRead(&datRead[0],datLengthMax,readFile); // Read a line of data
for(uint8_t i=0; i<datLength; i++){
Serial.print(datRead[i]);
if(i != datLength-1)Serial.print(F(","));
}
Serial.println();
mySerial.write(100); // Send Start bit
for(int j=0; j<datLength; j++){
for(int k=0; k<4; k++){
uint8_t sendBit = datRead[j]>>8*(3-k); // Assume data is 32-bit and send in 8-bit chunks
mySerial.write(sendBit); // Transmit data
}
}
}
Serial.println(F("Done Sending")); // End of file
delay(5); // Delay to make processing simpler
mySerial.write(200); // End of file marker
}
}
uint8_t lineRead(uint32_t *datRead, uint8_t datLength, File readFile){
uint8_t lengthRead = 0;
for(uint8_t i=0; i<=datLength; i++){
int64_t temp = numget(readFile); // Read a number from the file
if(temp!=-1){ // If a valid number, store it
datRead[i] = temp;
}
else{ // Otherwise set length of line
lengthRead = i;
i=datLength;
}
}
return lengthRead; // Return length of line
}
int64_t numget(File readFile){
byte readBit = readFile.read(); // Read byte as ASCII
uint8_t readInt = readBit - '0'; // Convert to integer
static bool endOfFile = 0;
static uint32_t readVal;
while(readBit != 44 && readBit != 13 && readBit != 10){ // If not end of line or end of file
readVal = readVal*10+readInt; // Read full integer from individual digits
readBit = readFile.read();
readInt = readBit - '0';
if(!readFile.available()){ // If end of file
if(endOfFile == 0){
endOfFile = 1;
readVal = readVal*10 +readInt; // Read last digit
uint32_t temp = readVal;
readVal = 0;
return temp; // Return value
}
if(endOfFile == 1){ // If an error occured
endOfFile = 0;
return -1; // Return error message
}
}
}
if(readBit == 10)return(-1); // If error, return error message
uint32_t temp = readVal;
readVal = 0;
if(readBit!=10)return temp;
return(-1); // If nothing occured, return error message
}
| true |
14abb7cab65e022c112dccc33279571ff9f38677 | C++ | pycpp/stl-test | /memory/shared_ptr.cc | UTF-8 | 7,485 | 3.109375 | 3 | [
"MIT"
] | permissive | // :copyright: (c) 2017-2018 Alex Huszagh.
// :license: MIT, see LICENSE.md for more details.
/*
* \addtogroup Tests
* \brief shared_ptr unittests.
*/
#include <pycpp/stl/memory/allocator.h>
#include <pycpp/stl/memory/shared_ptr.h>
#include <gtest/gtest.h>
PYCPP_USING_NAMESPACE
// DATA
// ----
template <bool ThreadSafe>
struct shared: enable_shared_from_this<shared<ThreadSafe>, ThreadSafe>
{
shared_ptr<shared, ThreadSafe> create()
{
return this->shared_from_this();
}
};
// HELPERS
// -------
template <typename T, bool ThreadSafe>
static
void
test_constructors()
{
using type = T;
using const_type = typename std::add_const<T>::type;
using shared_type = shared_ptr<type, ThreadSafe>;
using alias_type = shared_ptr<const_type, ThreadSafe>;
using deleter_type = std::default_delete<type>;
using allocator_type = std::allocator<type>;
type x = 5;
alias_type a1;
alias_type a2(new const_type(2));
// shared_ptr constructors
shared_type s1;
shared_type s2(nullptr);
alias_type s3(new type(3));
alias_type s4(new type(4), deleter_type());
shared_type s5(nullptr, deleter_type());
shared_type s6(new type(6), deleter_type(), allocator_type());
shared_type s7(nullptr, deleter_type(), allocator_type());
shared_type s8(s1, &x);
shared_type s9(s1);
alias_type s10(s2);
shared_type s11(std::move(s1));
alias_type s12(std::move(s2));
// weak constructors
typename shared_type::weak_type sw1(s6);
alias_type s13(sw1);
shared_type s14(sw1);
EXPECT_EQ(*s13, *s6);
EXPECT_EQ(sw1.use_count(), 3);
EXPECT_EQ(s13.use_count(), 3);
// unique_ptr constructors
std::unique_ptr<type> u(new type(4));
EXPECT_TRUE(u);
shared_type s15(std::move(u));
EXPECT_FALSE(u);
EXPECT_EQ(*s15, 4);
}
template <typename T, bool ThreadSafe>
static
void
test_assignment()
{
using type = T;
using const_type = typename std::add_const<T>::type;
using shared_type = shared_ptr<type, ThreadSafe>;
using alias_type = shared_ptr<const_type, ThreadSafe>;
// shared_ptr assignments
shared_type s1;
alias_type a1, a2;
a2 = s1;
a2 = a1;
a2 = std::move(s1);
a2 = std::move(a1);
// unique_ptr assignments
std::unique_ptr<type> u(new type(4));
EXPECT_TRUE(u);
s1 = std::move(u);
EXPECT_FALSE(u);
EXPECT_EQ(*s1, 4);
}
template <typename T, bool ThreadSafe>
static
void
test_observers()
{
using type = T;
using shared_type = shared_ptr<type, ThreadSafe>;
// don't delete, just used to check `get()`
type* p = new type(6);
// 1 reference
shared_type s1(p);
EXPECT_EQ(s1.get(), p);
EXPECT_EQ(s1.use_count(), 1);
EXPECT_TRUE(s1.unique());
EXPECT_TRUE(s1);
EXPECT_FALSE(s1.owner_before(s1));
// 2 references
shared_type s2(s1);
EXPECT_EQ(s1.get(), p);
EXPECT_EQ(s2.get(), p);
EXPECT_EQ(s1.use_count(), 2);
EXPECT_EQ(s2.use_count(), 2);
EXPECT_FALSE(s1.unique());
EXPECT_FALSE(s2.unique());
EXPECT_TRUE(s1);
EXPECT_TRUE(s2);
EXPECT_FALSE(s1.owner_before(s2));
EXPECT_FALSE(s2.owner_before(s1));
// 2 references, 1 invalid
shared_type s3(std::move(s1));
EXPECT_EQ(s1.get(), nullptr);
EXPECT_EQ(s2.get(), p);
EXPECT_EQ(s3.get(), p);
EXPECT_EQ(s1.use_count(), 0);
EXPECT_EQ(s2.use_count(), 2);
EXPECT_EQ(s3.use_count(), 2);
EXPECT_FALSE(s1.unique());
EXPECT_FALSE(s2.unique());
EXPECT_FALSE(s3.unique());
EXPECT_FALSE(s1);
EXPECT_TRUE(s2);
EXPECT_TRUE(s3);
EXPECT_TRUE(s1.owner_before(s2));
EXPECT_FALSE(s2.owner_before(s1));
// 1 reference, 2 invalid
s3.reset();
EXPECT_EQ(s1.get(), nullptr);
EXPECT_EQ(s2.get(), p);
EXPECT_EQ(s3.get(), nullptr);
EXPECT_EQ(s1.use_count(), 0);
EXPECT_EQ(s2.use_count(), 1);
EXPECT_EQ(s3.use_count(), 0);
EXPECT_FALSE(s1.unique());
EXPECT_TRUE(s2.unique());
EXPECT_FALSE(s3.unique());
EXPECT_FALSE(s1);
EXPECT_TRUE(s2);
EXPECT_FALSE(s3);
EXPECT_TRUE(s1.owner_before(s2));
EXPECT_TRUE(s3.owner_before(s2));
EXPECT_FALSE(s2.owner_before(s1));
EXPECT_FALSE(s2.owner_before(s3));
// test the remaining operators
constexpr size_t size = 5;
shared_type s4(new int[size]);
for (size_t i = 0; i < size; ++i) {
s4[i] = static_cast<int>(2*i);
}
EXPECT_EQ(s4[1], 2);
EXPECT_EQ(*s4, 0);
EXPECT_EQ(*(s4.operator->()), 0);
}
template <typename T, bool ThreadSafe>
static
void
test_modifiers()
{
using type = T;
using shared_type = shared_ptr<type, ThreadSafe>;
using deleter_type = std::default_delete<type>;
using allocator_type = std::allocator<type>;
shared_type s1(new int(2));
EXPECT_TRUE(s1);
EXPECT_EQ(*s1, 2);
// reset 0-args
s1.reset();
EXPECT_FALSE(s1);
// reset 1-arg
s1.reset(new int(3));
EXPECT_TRUE(s1);
EXPECT_EQ(*s1, 3);
// reset 2-args
s1.reset(new int(4), deleter_type());
EXPECT_TRUE(s1);
EXPECT_EQ(*s1, 4);
// reset 3-args
s1.reset(new int(5), deleter_type(), allocator_type());
EXPECT_TRUE(s1);
EXPECT_EQ(*s1, 5);
// swap
shared_type s2;
EXPECT_TRUE(s1);
EXPECT_FALSE(s2);
EXPECT_EQ(*s1, 5);
s1.swap(s2);
EXPECT_TRUE(s2);
EXPECT_FALSE(s1);
EXPECT_EQ(*s2, 5);
}
template <bool ThreadSafe>
static
void
test_shared_from_this()
{
using shared_type = shared<ThreadSafe>;
auto s1 = make_shared<shared_type, ThreadSafe>();
EXPECT_EQ(s1.use_count(), 1);
auto s2 = s1->create();
EXPECT_EQ(s1.use_count(), 2);
EXPECT_EQ(s2.use_count(), 2);
EXPECT_EQ(s1.get(), s2.get());
}
template <bool ThreadSafe>
static
void
test_make_shared()
{
auto p1 = make_shared<int>(5);
auto p2 = make_shared<int, ThreadSafe>(5);
EXPECT_EQ(*p1, *p2);
}
template <bool ThreadSafe>
static
void
test_make_shared_array()
{
// TODO: need to test all 4 constructors of make_shared...
}
template <bool ThreadSafe>
static
void
test_allocate_shared()
{
using allocator_type = allocator<int>;
allocator_type alloc;
// ADL is a pain, sometimes...
auto p1 = PYCPP_NAMESPACE::allocate_shared<int>(alloc, 5);
auto p2 = allocate_shared<int, ThreadSafe>(alloc, 5);
EXPECT_EQ(*p1, *p2);
}
template <bool ThreadSafe>
static
void
test_allocate_shared_array()
{
// TODO: need to test all 3 constructors of allocate_shared...
}
// TESTS
// -----
TEST(shared_ptr, constructors)
{
test_constructors<int, true>();
test_constructors<int, false>();
}
TEST(shared_ptr, assignment)
{
test_assignment<int, true>();
test_assignment<int, false>();
}
TEST(shared_ptr, observers)
{
test_observers<int, true>();
test_observers<int, false>();
}
TEST(shared_ptr, modifiers)
{
test_modifiers<int, true>();
test_modifiers<int, false>();
}
TEST(shared_ptr, enable_shared_from_this)
{
test_shared_from_this<true>();
test_shared_from_this<false>();
}
TEST(shared_ptr, make_shared)
{
test_make_shared<true>();
test_make_shared<false>();
}
TEST(shared_ptr, make_shared_array)
{
test_make_shared_array<true>();
test_make_shared_array<false>();
}
TEST(shared_ptr, allocate_shared)
{
test_allocate_shared<true>();
test_allocate_shared<false>();
}
TEST(shared_ptr, allocate_shared_array)
{
test_allocate_shared_array<true>();
test_allocate_shared_array<false>();
}
| true |
88c79bce8a3c24572f1ab6e3090f93d0656fe75b | C++ | chipsu/opengl-demo | /Mesh.h | UTF-8 | 1,882 | 2.703125 | 3 | [] | no_license | #pragma once
#include "Main.h"
#include "Vertex.h"
#include "AABB.h"
struct Mesh {
std::vector<Vertex> mVertices;
std::vector<uint32_t> mIndices;
GLuint mVertexBuffer = 0;
GLuint mIndexBuffer = 0;
GLuint mVertexArray = 0;
bool mVertexBufferDirty = true;
bool mHidden = false;
AABB mAABB;
GLuint mMode = GL_TRIANGLES;
Mesh(const Mesh&) = delete;
Mesh& operator=(const Mesh&) = delete;
Mesh() {}
~Mesh() {
if (mVertexBuffer) glDeleteBuffers(1, &mVertexBuffer);
if (mIndexBuffer) glDeleteBuffers(1, &mIndexBuffer);
if (mVertexArray) glDeleteVertexArrays(1, &mVertexArray);
}
void Bind() {
if (mVertexBufferDirty) {
UpdateVertexBuffer();
mVertexBufferDirty = false;
}
if (!mIndexBuffer) {
UpdateIndexBuffer();
}
if (!mVertexArray) {
UpdateVertexArray();
}
glBindVertexArray(mVertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
}
void UpdateVertexBuffer() {
if (!mVertexBuffer) glGenBuffers(1, &mVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, mVertices.size() * sizeof(Vertex), &mVertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void UpdateVertexArray() {
if (!mVertexArray) glGenVertexArrays(1, &mVertexArray);
glBindVertexArray(mVertexArray);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
Vertex::MapVertexArray();
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void UpdateIndexBuffer() {
if (!mIndexBuffer) glGenBuffers(1, &mIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mIndices.size() * sizeof(uint32_t), &mIndices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void UpdateAABB() {
mAABB = AABB::FromVertices(mVertices);
}
};
typedef std::shared_ptr<Mesh> Mesh_;
| true |
2ce8686ef6f0e5992adecd71c369fe2994aa2b5d | C++ | ps-group/cg_course_examples | /chapter_2/lesson_08/Bodies.h | UTF-8 | 837 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <glm/vec3.hpp>
#include <glm/fwd.hpp>
enum class CubeFace
{
Front = 0,
Back,
Top,
Bottom,
Left,
Right,
NumFaces
};
class CIdentityCube
{
public:
CIdentityCube();
void Update(float deltaTime);
void Draw()const;
void SetFaceColor(CubeFace face, const glm::vec3 &color);
private:
static const size_t COLORS_COUNT = static_cast<size_t>(CubeFace::NumFaces);
glm::vec3 m_colors[COLORS_COUNT];
};
class CAnimatedCube : public CIdentityCube
{
public:
void Update(float deltaTime);
void Draw()const;
private:
enum Animation
{
Rotating,
Pulse,
Bounce,
};
glm::mat4 GetAnimationTransform()const;
static const float ANIMATION_STEP_SECONDS;
Animation m_animation = Rotating;
float m_animationPhase = 0;
};
| true |
33b6512b3f0b63b5befe3e9098b91d6a7d3ac235 | C++ | rajswilochan1999/Hacktoberfest-2020 | /C++_Programs/BFS.cpp | UTF-8 | 1,194 | 2.734375 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
vector<int>dist;
void bfs(int s,vector<vector<int>>a,vector<bool>visited)
{
visited[s]=true;
queue<int>q;
q.push(s);
dist[s]=0;
while(!q.empty())
{
s=q.front();
//cout<<s<<" ";
q.pop();
for(int i:a[s])
{
if(!visited[i]&&dist[i]==-1)
{
dist[i]=dist[s]+1;
visited[i]=true;
q.push(i);
}
}
}
}
int main() {
int q;
cin>>q;
for(int t=0;t<q;t++)
{
int n,m;
cin>>n>>m;
vector<vector<int>>a(n);
for(int i=0;i<m;i++)
{
int x,y;
cin>>x>>y;
a[x-1].push_back(y-1);
a[y-1].push_back(x-1);
}
int s;
cin>>s;
vector<bool>visited(n+1,false);
dist.resize(n,-1);
bfs(s-1,a,visited);
for(int i=0;i<dist.size();i++)
if(dist[i]==-1)
cout<<dist[i]<<" ";
else if(dist[i]!=0)
cout<<dist[i]*6<<" ";
cout<<endl;
dist.clear();
}
return 0;
}
| true |
d93f812591a9e99a5d265aa6ca1165008ccc6ce6 | C++ | Ashwin-Ragupathy/R3-SoftwareTask1-AshwinRagupathy | /r3_software_task_1_ashwin_ragupathy1.ino | UTF-8 | 8,431 | 3.546875 | 4 | [] | no_license | // C++ code
// Ashwin Ragupathy
// R3 - Training Task 1 - Software
// Due: OCtober 10, 2021
//
// Map the input of a potentiometer of 0 - 1023 to 0 - 99 and
// display the values on two Seven Segment displays using CD4511
// seven segment decoders
//
int potentiometerPin = 0; // Initialize the analog input of the potentiometer to A0
int position = 0; // The obtained position of the potentiometer
int mappedPosition = 0; // The mapped position of the potentiometer
int mappedPositionTens = 0; // The tens place value of the mapped position
int mappedPositionOnes = 0; // The ones place value of the mapped position
int tensValueBit1 = 4; // Initialize the first binary bit (ordered right to left) of the tens place value to digital pin 4
int tensValueBit2 = 5; // Initialize the second binary bit of the tens place value to digital pin 5
int tensValueBit3 = 6; // Initialize the third binary bit of the tens place value to digital pin 6
int tensValueBit4 = 7; // Initialize the fourth binary bit of the tens place value to digital pin 7
int onesValueBit1 = 8; // Initialize the first binary bit (ordered right to left) of the ones place value to digital pin 8
int onesValueBit2 = 9; // Initialize the second binary bit of the ones place value to digital pin 9
int onesValueBit3 = 10; // Initialize the third binary bit of the ones place value to digital pin 10
int onesValueBit4 = 11; // Initialize the fourth binary bit of the ones place value to digital pin 11
void setup()
{
pinMode(4, OUTPUT); // Sets digital pin 4 as an output
pinMode(5, OUTPUT); // Sets digital pin 5 as an output
pinMode(6, OUTPUT); // Sets digital pin 6 as an output
pinMode(7, OUTPUT); // Sets digital pin 7 as an output
pinMode(8, OUTPUT); // Sets digital pin 8 as an output
pinMode(9, OUTPUT); // Sets digital pin 9 as an output
pinMode(10, OUTPUT); // Sets digital pin 10 as an output
pinMode(11, OUTPUT); // Sets digital pin 11 as an output
}
void loop()
{
position = analogRead(potentiometerPin); // Obtain the position of the potentiometer by reading the value from the potentiometer pin
mappedPosition = map(position, 0, 1023, 0, 99); // Map the position from 0-1023 to 0-99
mappedPositionTens = mappedPosition / 10; // Find the tens place value of the mapped position
mappedPositionOnes = mappedPosition % 10; // Find the ones place value of the mapped position
// Writing to the tens value seven segment display
if (mappedPositionTens == 1) { // If tens value is 1 then set binary tens value as 0001 by writing to the individual bits
digitalWrite(tensValueBit1, 1);
digitalWrite(tensValueBit2, 0);
digitalWrite(tensValueBit3, 0);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 2) { // If tens value is 2 then set binary tens value as 0010 by writing to the individual bits
digitalWrite(tensValueBit1, 0);
digitalWrite(tensValueBit2, 1);
digitalWrite(tensValueBit3, 0);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 3) { // If tens value is 3 then set binary tens value as 0011 by writing to the individual bits
digitalWrite(tensValueBit1, 1);
digitalWrite(tensValueBit2, 1);
digitalWrite(tensValueBit3, 0);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 4) { // If tens value is 4 then set binary tens value as 0100 by writing to the individual bits
digitalWrite(tensValueBit1, 0);
digitalWrite(tensValueBit2, 0);
digitalWrite(tensValueBit3, 1);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 5) { // If tens value is 5 then set binary tens value as 0101 by writing to the individual bits
digitalWrite(tensValueBit1, 1);
digitalWrite(tensValueBit2, 0);
digitalWrite(tensValueBit3, 1);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 6) { // If tens value is 6 then set binary tens value as 0110 by writing to the individual bits
digitalWrite(tensValueBit1, 0);
digitalWrite(tensValueBit2, 1);
digitalWrite(tensValueBit3, 1);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 7) { // If tens value is 7 then set binary tens value as 0111 by writing to the individual bits
digitalWrite(tensValueBit1, 1);
digitalWrite(tensValueBit2, 1);
digitalWrite(tensValueBit3, 1);
digitalWrite(tensValueBit4, 0);
}
if (mappedPositionTens == 8) { // If tens value is 8 then set binary tens value as 1000 by writing to the individual bits
digitalWrite(tensValueBit1, 0);
digitalWrite(tensValueBit2, 0);
digitalWrite(tensValueBit3, 0);
digitalWrite(tensValueBit4, 1);
}
if (mappedPositionTens == 9) { // If tens value is 9 then set binary tens value as 1001 by writing to the individual bits
digitalWrite(tensValueBit1, 1);
digitalWrite(tensValueBit2, 0);
digitalWrite(tensValueBit3, 0);
digitalWrite(tensValueBit4, 1);
}
if (mappedPositionTens == 0) { // If tens value is 0 then set binary tens value as 0000 by writing to the individual bits
digitalWrite(tensValueBit1, 0);
digitalWrite(tensValueBit2, 0);
digitalWrite(tensValueBit3, 0);
digitalWrite(tensValueBit4, 0);
}
// Writing to the ones value seven segment display
if (mappedPositionOnes == 1) { // If ones value is 1 then set binary tens value as 0001 by writing to the individual bits
digitalWrite(onesValueBit1, 1);
digitalWrite(onesValueBit2, 0);
digitalWrite(onesValueBit3, 0);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 2) { // If ones value is 2 then set binary tens value as 0010 by writing to the individual bits
digitalWrite(onesValueBit1, 0);
digitalWrite(onesValueBit2, 1);
digitalWrite(onesValueBit3, 0);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 3) { // If ones value is 3 then set binary tens value as 0011 by writing to the individual bits
digitalWrite(onesValueBit1, 1);
digitalWrite(onesValueBit2, 1);
digitalWrite(onesValueBit3, 0);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 4) { // If ones value is 4 then set binary tens value as 0100 by writing to the individual bits
digitalWrite(onesValueBit1, 0);
digitalWrite(onesValueBit2, 0);
digitalWrite(onesValueBit3, 1);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 5) { // If ones value is 5 then set binary tens value as 0101 by writing to the individual bits
digitalWrite(onesValueBit1, 1);
digitalWrite(onesValueBit2, 0);
digitalWrite(onesValueBit3, 1);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 6) { // If ones value is 6 then set binary tens value as 0110 by writing to the individual bits
digitalWrite(onesValueBit1, 0);
digitalWrite(onesValueBit2, 1);
digitalWrite(onesValueBit3, 1);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 7) { // If ones value is 7 then set binary tens value as 0111 by writing to the individual bits
digitalWrite(onesValueBit1, 1);
digitalWrite(onesValueBit2, 1);
digitalWrite(onesValueBit3, 1);
digitalWrite(onesValueBit4, 0);
}
if (mappedPositionOnes == 8) { // If ones value is 8 then set binary tens value as 1000 by writing to the individual bits
digitalWrite(onesValueBit1, 0);
digitalWrite(onesValueBit2, 0);
digitalWrite(onesValueBit3, 0);
digitalWrite(onesValueBit4, 1);
}
if (mappedPositionOnes == 9) { // If ones value is 9 then set binary tens value as 1001 by writing to the individual bits
digitalWrite(onesValueBit1, 1);
digitalWrite(onesValueBit2, 0);
digitalWrite(onesValueBit3, 0);
digitalWrite(onesValueBit4, 1);
}
if (mappedPositionOnes == 0) { // If ones value is 0 then set binary tens value as 0000 by writing to the individual bits
digitalWrite(onesValueBit1, 0);
digitalWrite(onesValueBit2, 0);
digitalWrite(onesValueBit3, 0);
digitalWrite(onesValueBit4, 0);
}
} | true |
1c3f9292c6251e5e5bf23fce3af35608a67b8981 | C++ | CodeRecode/Manticore | /Source/Texture.cpp | UTF-8 | 1,060 | 2.625 | 3 | [] | no_license | #include "Texture.h"
Texture::Texture(std::string fileName)
{
glGenTextures(1, &textureId);
// Load and convert the image with DevIL
ILuint imageID;
ilGenImages(1, &imageID);
ilBindImage(imageID);
ilLoadImage(fileName.c_str());
ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
//iluFlipImage();
textureWidth = ilGetInteger(IL_IMAGE_WIDTH);
textureHeight = ilGetInteger(IL_IMAGE_HEIGHT);
// Bind the texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_FORMAT), textureWidth, textureHeight,
0, GL_RGBA, GL_UNSIGNED_BYTE, ilGetData());
ilDeleteImage(imageID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, NULL);
}
Texture::~Texture()
{
glDeleteTextures(1, &textureId);
} | true |
c924b6cc7879f60548d2c2cfb88ba390d6c101b3 | C++ | pig0726/LeetCode | /problemset/Container_With_Most_Water.cpp | UTF-8 | 340 | 2.71875 | 3 | [] | no_license | class Solution {
public:
int maxArea(vector<int>& height) {
int lidx = 0, ridx = height.size() - 1;
int ret = 0;
while (lidx < ridx) {
ret = max(ret, min(height[lidx], height[ridx]) * abs(lidx - ridx));
if (height[lidx] <= height[ridx]) ++lidx;
else --ridx;
}
return ret;
}
};
| true |
b3e62c8f2560bfa7fb08d574f0ba418008c7264a | C++ | shenxn/minijava-compiler | /include/variable.cpp | UTF-8 | 1,241 | 2.5625 | 3 | [] | no_license | #include "variable.hpp"
#include "symboltable.hpp"
namespace AST {
Variable::Variable(Identifier *id) {
this->id = id;
}
Variable::~Variable() {
delete id;
delete type;
}
void Variable::execute() {}
void Variable::typecheck() {
// TODO: check if initialized
if (currentMethod != NULL) {
// Not main class
auto varItem = currentMethod->varTable.find(id->s);
if (varItem != currentMethod->varTable.end()) {
type = varItem->second->type;
return;
}
for (auto classItem = currentClass; classItem != NULL; classItem = classItem->parent) {
varItem = classItem->varTable.find(id->s);
if (varItem != classItem->varTable.end()) {
type = varItem->second->type;
return;
}
}
}
id->reportTypeCheckError("Undefined variable");
}
VarValue *Variable::find() {
auto it = methodStack->variableMap.find(id->s);
if (it == methodStack->variableMap.end()) {
it = classStack->variableMap.find(id->s);
}
return it->second;
}
}
| true |
f81508c567fcc42737080c03b8605a8950aa7b66 | C++ | jose-joaquim/Competitive-Programming | /URI/URI 1933 - Tri-du.cpp | UTF-8 | 308 | 2.515625 | 3 | [] | no_license | //Author/Autor: José Joaquim de Andrade Neto
//Link da questão: https://www.urionlinejudge.com.br/judge/pt/problems/view/1933
#include <iostream>
#include <cstdio>
using namespace std;
int main(int argc, char **argv)
{
int a, b;
cin >> a >> b;
if(a >= b){
printf("%d\n", a);
}else{
printf("%d\n", b);
}
return 0;
}
| true |
df06a141ba625fa02652becfa30047ba03572024 | C++ | SayaUrobuchi/uvachan | /Kattis/grandpabernie.cpp | UTF-8 | 787 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
using um = unordered_map<string, int>;
char s[32];
bool dirty[1048576];
vector<int> v[1048576];
int main()
{
int n, m, i, t, id;
um tbl;
while (scanf("%d", &n) == 1)
{
tbl.clear();
for (i=0; i<n; i++)
{
scanf("%s%d", s, &t);
um::iterator it = tbl.find(s);
if (it == tbl.end())
{
id = tbl.size();
tbl[s] = id;
v[id].clear();
dirty[id] = true;
}
else
{
id = it->second;
}
v[id].emplace_back(t);
}
scanf("%d", &m);
for (i=0; i<m; i++)
{
scanf("%s%d", s, &t);
id = tbl[s];
if (dirty[id])
{
dirty[id] = false;
sort(v[id].begin(), v[id].end());
}
printf("%d\n", v[id][t-1]);
}
}
return 0;
}
| true |
e673ae3569d4605881bdfdbe6bdc192ed480447d | C++ | ng210/cpp | /js/managed/base/String.h | UTF-8 | 2,003 | 2.640625 | 3 | [] | no_license | #ifndef __STRING_H
#define __STRING_H
#include "base/Object.h"
NAMESPACE_FRMWRK_BEGIN
/*****************************************************************************
* Object_ (structure)
*****************************************************************************/
class String;
class Array_;
class String_ : public Object_ {
friend class String;
friend class Array_;
String_(char *p);
String_(const char *p);
static const String_ emptyInstance_;
protected:
char *buffer_;
size_t length_;
String_(void);
virtual ~String_(void);
const char* getType();
String toString();
int compareTo(Object_* str);
void* valueOf();
};
/*****************************************************************************
* Object (reference)
*****************************************************************************/
class Null;
class Array;
class String : public Object {
friend class Object;
friend class Array_;
String(const String_*);
void empty_();
public:
//static const String emptyInstance_;
static const String Empty;
String(void);
String(String&);
String(const Null&);
String(char*);
String(const char*);
~String(void);
//String operator=(String&);
String operator=(const String&);
//String operator=(const Null&);
char operator[](int);
String operator+(String&);
String operator+(const char*);
bool startsWith(String&);
bool startsWith(char*);
long long indexOf(String&);
long long indexOf(const char*);
long long indexOf(const char*, size_t);
long long lastIndexOf(String&);
long long lastIndexOf(char*);
bool endsWith(String&);
bool endsWith(char*);
//? match(RegExp&);
String replace(String&, String&);
String replace(const char*, const char*);
//String replace(Array&, Array&);
String substr(long long, long long = 0);
String substring(long long, long long = 0);
Array split(String&);
Array split(const char*);
String toLowerCase();
String toUpperCase();
String trim();
const char* toCString();
//void empty();
};
NAMESPACE_FRMWRK_END
#endif
| true |
e530c3cd59a742739c30cd1e8cd2f81a80f72444 | C++ | Behrouz-Babaki/practice | /11953/11953.cpp | UTF-8 | 1,346 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using std::cin;
using std::endl;
using std::cout;
using std::vector;
using std::ws;
vector<vector<int> > grid;
vector<vector<int> > visited;
int N;
int num_ships;
void visit(int r, int c);
int main(void) {
int T;
cin >> T;
for (int case_cnt = 1; case_cnt <= T; case_cnt++){
cin >> N >> ws;
num_ships = 0;
grid.clear();
visited.clear();
grid.resize(N, vector<int>(N));
visited.resize(N, vector<int>(N));
char ch;
for (int r=0; r<N; r++) {
for(int c=0; c<N; c++) {
cin >> ch;
switch(ch) {
case '.':
grid[r][c] = 0;
break;
case 'x':
grid[r][c] = 1;
break;
case '@':
grid[r][c] = 2;
break;
}
}
cin >> ws;
}
for (int r=0; r<N; r++)
for (int c=0; c<N; c++)
if (grid[r][c] == 1 && !visited[r][c]){
num_ships++;
visit(r,c);
}
cout << "Case " << case_cnt << ": " << num_ships << endl;
}
return 0;
}
void visit(int r, int c) {
int h, v;
h = (((c-1) >= 0 && grid[r][c-1]) ||
((c+1) < N && grid[r][c+1]));
v = 1-h;
int col = c, row = r;
while (col >= 0 && row >= 0 && grid[row][col]) {
visited[row][col] = 1;
col -= h;
row -= v;
}
col = c, row = r;
while (col < N && row < N && grid[row][col]) {
visited[row][col] = 1;
col += h;
row += v;
}
}
| true |
4a114ef9c3d76fbc7db3103f98570d58ed26e035 | C++ | tianshihao/picop | /source/smoothmethod.cpp | UTF-8 | 15,651 | 2.875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "smoothmethod.h"
SmoothMethod::SmoothMethod()
{
}
SmoothMethod::~SmoothMethod()
{
}
QImage SmoothMethod::averageFiltering(QImage *originImage)
{
bool ok;
int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok);
if (ok)
{
if (filterRadius % 2 == 0)
filterRadius += 1;
qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":"
<< "图像平滑, 方式, 均值滤波"
<< "滤波器大小" << filterRadius;
int kernel[filterRadius][filterRadius];
for (int i = 0; i < filterRadius; i++)
for (int j = 0; j < filterRadius; j++)
kernel[i][j] = 1;
int len = filterRadius / 2;
int originWidth = originImage->width();
int originHeight = originImage->height();
QImage targetImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32);
// 添加边框
for (int i = 0; i < targetImage.width(); i++)
for (int j = 0; j < targetImage.height(); j++)
if (i >= len && i < targetImage.width() - len && j >= len && j < targetImage.height() - len)
{ // 不在边框中
QColor originImageColor = QColor(originImage->pixel(i - len, j - len));
targetImage.setPixelColor(i, j, originImageColor);
}
else // 在边框中
targetImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色
for (int i = len; i < targetImage.width() - len; i++)
for (int j = len; j < targetImage.height() - len; j++)
{
int r = 0;
int g = 0;
int b = 0;
for (int p = -len; p <= len; p++)
for (int q = -len; q <= len; q++)
{
r = targetImage.pixelColor(i + p, j + q).red() * kernel[len + p][len + q] + r;
g = targetImage.pixelColor(i + p, j + q).green() * kernel[len + p][len + q] + g;
b = targetImage.pixelColor(i + p, j + q).blue() * kernel[len + p][len + q] + b;
}
r /= (filterRadius * filterRadius);
g /= (filterRadius * filterRadius);
b /= (filterRadius * filterRadius);
if (((i - len) >= 0) && ((i - len) < originWidth) && ((j - len) >= 0) && ((j - len) < originHeight))
originImage->setPixel(i - len, j - len, qRgb(r, g, b));
}
}
return (*originImage);
} // averageFiltering
QImage SmoothMethod::medianFiltering(QImage *originImage)
{ // originImage 格式为 Format_RGB32
bool ok;
int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("中值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok);
if (ok)
{
if (filterRadius % 2 == 0)
filterRadius += 1;
qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":"
<< "图像平滑, 方式, 中值滤波"
<< "滤波器大小" << filterRadius;
int len = filterRadius / 2;
int threshold = filterRadius * filterRadius / 2 + 1;
int originWidth = originImage->width();
int originHeight = originImage->height();
QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32);
QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32);
// 初始化 middleImage
for (int i = 0; i < middleImage.width(); i++)
{
for (int j = 0; j < middleImage.height(); j++)
{
if ((i >= len) && (i < (middleImage.width() - len)) && (j >= len) && (j < (middleImage.height() - len)))
{ // 像素点不在边框中
middleImage.setPixelColor(i, j, QColor(originImage->pixel(i - len, j - len)));
}
else
{ // 像素点在边框中
middleImage.setPixelColor(i, j, Qt::white);
}
}
}
// 使用直方图记录窗口中出现的像素的出现次数
int redHist[256] = {0};
int greenHist[256] = {0};
int blueHist[256] = {0};
int grayHist[256] = {0};
for (int i = len; i < middleImage.width() - len; i++)
{
for (int j = len; j < middleImage.height() - len; j++)
{
// 设置窗口
if (j == len)
{ // 每到新的一列, 初始化直方图
memset(redHist, 0, sizeof(redHist));
memset(greenHist, 0, sizeof(greenHist));
memset(blueHist, 0, sizeof(blueHist));
memset(grayHist, 0, sizeof(grayHist));
for (int p = -len; p <= len; p++)
{
for (int q = -len; q <= len; q++)
{
int red = qRed(middleImage.pixel(i + p, j + q));
int green = qGreen(middleImage.pixel(i + p, j + q));
int blue = qBlue(middleImage.pixel(i + p, j + q));
int gray = qGray(middleImage.pixel(i + p, j + q));
redHist[red]++;
greenHist[green]++;
blueHist[blue]++;
grayHist[gray]++;
}
}
}
else
{ // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值
int oldWindowStartCol = j - len - 1;
int newWindowEndCol = j + len;
for (int p = -len; p <= len; p++)
{
// 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len]
int red = qRed(middleImage.pixel(i + p, oldWindowStartCol));
int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol));
int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol));
int gray = qGray(middleImage.pixel(i + p, oldWindowStartCol));
redHist[red]--;
greenHist[green]--;
blueHist[blue]--;
grayHist[gray]--;
red = qRed(middleImage.pixel(i + p, newWindowEndCol));
green = qGreen(middleImage.pixel(i + p, newWindowEndCol));
blue = qBlue(middleImage.pixel(i + p, newWindowEndCol));
gray = qGray(middleImage.pixel(i + p, newWindowEndCol));
redHist[red]++;
greenHist[green]++;
blueHist[blue]++;
grayHist[gray]++;
}
}
// 获取窗口内像素中值
int r = getMedianValue(redHist, threshold);
int g = getMedianValue(greenHist, threshold);
int b = getMedianValue(blueHist, threshold);
targetImage.setPixel(i - len, j - len, qRgb(r, g, b));
}
}
return targetImage;
}
} // medianFiltering
// 获取窗口中像素的中值
int SmoothMethod::getMedianValue(const int *histogram, int threshold)
{
int sum = 0;
for (int i = 0; i < 256; i++)
{
sum += histogram[i];
if (sum >= threshold)
return i;
}
return 255;
} // getMedianValue
QImage SmoothMethod::KNNF(QImage originImage)
{
bool ok1;
bool ok2;
int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok1);
int K = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值平滑"), "输入K值", 1, 1, 30, 1, &ok2);
if (ok1 & ok2)
{
if (filterRadius % 2 == 0)
filterRadius += 1;
qDebug().noquote().nospace() << "[Debug] " << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ": "
<< "图像平滑, 方式, K近邻均值滤波, "
<< "滤波器大小, " << filterRadius << ", "
<< "K值, " << K;
// int kernel[filterRadius][filterRadius];
// for (int i = 0; i < filterRadius; i++)
// for (int j = 0; j < filterRadius; j++)
// kernel[i][j] = 1;
int len = filterRadius / 2;
int originWidth = originImage.width();
int originHeight = originImage.height();
QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32);
QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32);
// 添加边框
for (int i = 0; i < middleImage.width(); i++)
for (int j = 0; j < middleImage.height(); j++)
if (i >= len && i < middleImage.width() - len && j >= len && j < middleImage.height() - len)
{ // 不在边框中
middleImage.setPixelColor(i, j, QColor(originImage.pixel(i - len, j - len)));
}
else
{ // 在边框中
middleImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色
}
int redHist[256] = {0};
int greenHist[256] = {0};
int blueHist[256] = {0};
for (int i = len; i < middleImage.width() - len; i++)
for (int j = len; j < middleImage.height() - len; j++)
{
// 设置窗口
if (j == len)
{ // 每到新的一列, 初始化直方图
memset(redHist, 0, sizeof(redHist));
memset(greenHist, 0, sizeof(greenHist));
memset(blueHist, 0, sizeof(blueHist));
for (int p = -len; p <= len; p++)
{
for (int q = -len; q <= len; q++)
{
int red = qRed(middleImage.pixel(i + p, j + q));
int green = qGreen(middleImage.pixel(i + p, j + q));
int blue = qBlue(middleImage.pixel(i + p, j + q));
redHist[red]++;
greenHist[green]++;
blueHist[blue]++;
}
}
}
else
{ // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值
int oldWindowStartCol = j - len - 1;
int newWindowEndCol = j + len;
for (int p = -len; p <= len; p++)
{
// 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len]
int red = qRed(middleImage.pixel(i + p, oldWindowStartCol));
int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol));
int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol));
redHist[red]--;
greenHist[green]--;
blueHist[blue]--;
red = qRed(middleImage.pixel(i + p, newWindowEndCol));
green = qGreen(middleImage.pixel(i + p, newWindowEndCol));
blue = qBlue(middleImage.pixel(i + p, newWindowEndCol));
redHist[red]++;
greenHist[green]++;
blueHist[blue]++;
}
}
int r = getKValue(redHist, qRed(middleImage.pixel(i, j)), K);
int g = getKValue(greenHist, qGreen(middleImage.pixel(i, j)), K);
int b = getKValue(blueHist, qBlue(middleImage.pixel(i, j)), K);
// int r = getAverage(rKNNValue);
// int g = getAverage(gKNNValue);
// int b = getAverage(bKNNValue);
targetImage.setPixel(i - len, j - len, qRgb(r, g, b));
}
return targetImage;
}
return originImage;
} // KNNF
int SmoothMethod::getKValue(const int *histogram, int key, int K)
{
// 计算距离 key 的 K 近邻的方法也是桶排序
// 记录各点到 key 距离的数组长度不超过 255-key
// bucket[255-key][0] => 像素值大于 key 的点其像素值与 key 的差值
// bucket[255-key][1] => 像素值小于 key 的点其像素值与 key 的差值
int bucket[255][2];
for (int i = 0; i <= 255; i++)
{
bucket[i][0] = 0;
bucket[i][1] = 0;
}
for (int i = 0; i <= 255; i++)
{
if (histogram[i] > 0)
{
if (i - key >= 0)
{
bucket[i - key][0] = histogram[i];
}
else
{
bucket[key - i][1] = histogram[i];
}
}
}
int max = K + 1;
int KNNValue[max] = {0};
K = K - 1; // 所有的 K 近邻点中 key 本身是第一个
KNNValue[0] = key;
bucket[0][0]--;
if (K <= 0)
return key;
// j 是 KNNValue 索引
for (int i = 0, j = 1; i <= 255; i++)
{
if (bucket[i][0] > 0)
{ // TODO 可优化
// 大于 key 的像素值
qDebug() << ">";
if (bucket[i][0] >= K)
{
for (int k = 0; k < K; j++, k++)
{
KNNValue[j] = i + key;
}
K = 0;
}
else
{
for (int k = 0; k < bucket[i][0]; j++, k++)
{ // 将所有像素值为 i 的点全部加入
KNNValue[j] = i + key; // 还原原始像素值
}
K -= bucket[i][0];
}
}
if (K <= 0)
break;
if (bucket[i][1] > 0)
{ // 小于 key 的像素值
qDebug() << "<";
if (bucket[i][1] >= K)
{
for (int k = 0; k < K; j++, k++)
{
KNNValue[j] = key - i;
}
K = 0;
}
else
{
for (int k = 0; k < bucket[i][1]; j++, k++)
{ // 将所有像素值为 i 的点全部加入
KNNValue[j] = key - i; // 还原原始像素值
}
K -= bucket[i][1];
}
}
if (K <= 0)
break;
}
for (int i = 0; i < max - 1; i++)
qDebug() << KNNValue[i];
// return KNNValue;
int res = getAverage(KNNValue, max - 1);
return res;
} // getKValue
int SmoothMethod::getAverage(const int *arr, int len)
{
int average = 0;
for (int i = 0; i < len; i++)
average += arr[i];
int res = average / len;
return res;
} // getAverage
| true |
66860e43ed1a239e231fbac600e2ec1937c9ba5d | C++ | JoyPoint/CPP-Library-Headers | /CircleBin.hpp | UTF-8 | 2,123 | 2.921875 | 3 | [] | no_license | #ifndef ASU_CIRCLEBIN
#define ASU_CIRCLEBIN
#include<iostream>
#include<vector>
#include<GcpDistance.hpp>
/*********************************************************
* This C++ template compute circle geographic binning
* results. Update the bin center to the average position.
*
* input(s):
* const vector<pair<T1,T2>> &p ---- Sampling lon/lat.
* const vector<pair<T3,T4>> &b ---- Bin center lon/lat.
* const vector<T5> &r ---- Bin radius (in deg).
*
* return(s):
* pair<vector<pair<double,double>>,vector<vector<bool>>> ans ---- make_pair(B,ans)
* B : Updated bin centers. (b.size())
* ans: Bin result matrix. (p.size()*b.size())
*
* Shule Yu
* Dec 26 2017
*
* Note: original bin center locations destroyed.
* Key words: geographic bin, circle, update.
***********************************************************/
template <typename T1, typename T2, typename T3, typename T4, typename T5>
std::pair<std::vector<std::pair<double,double>>,std::vector<std::vector<bool>>> CircleBin(
const std::vector<std::pair<T1,T2>> &p,
const std::vector<std::pair<T3,T4>> &b,
const std::vector<T5> &r){
// Check array size.
if (b.size()!=r.size()) {
std::cerr << "Error in " << __func__ << ": bins and radius size don't match ..." << std::endl;
return {};
}
// Prepare output.
std::size_t Np=p.size(),Nb=b.size();
std::vector<std::pair<double,double>> B(Nb);
std::vector<std::vector<bool>> ans(Np,std::vector<bool>(Nb,false));
// For each bin, search which points are inside them.
// Then update the bin center.
for (std::size_t i=0;i<Nb;++i){
T2 NewLon=0,NewLat=0;
int Cnt=0;
for (std::size_t j=0;j<Np;++j){
if (GcpDistance(b[i].first,b[i].second,p[j].first,p[j].second)<=r[i]){
ans[j][i]=true;
NewLon+=p[j].first;
NewLat+=p[j].second;
++Cnt;
}
}
B[i].first=NewLon/Cnt;
B[i].second=NewLat/Cnt;
}
return {B,ans};
}
#endif
| true |
aa302bb98c8b3384a3e47ca4473a4a5f7e628ba8 | C++ | adityaramesh/ndmath | /include/ndmath/index/composite_index.hpp | UTF-8 | 2,654 | 2.65625 | 3 | [] | no_license | /*
** File Name: composite_index.hpp
** Author: Aditya Ramesh
** Date: 01/09/2015
** Contact: _@adityaramesh.com
*/
#ifndef Z8F87A6F3_74EA_4A09_A3CD_6DCFFB754A07
#define Z8F87A6F3_74EA_4A09_A3CD_6DCFFB754A07
#include <ndmath/index/index_wrapper.hpp>
namespace nd {
namespace detail {
template <unsigned N, unsigned Dims1, bool UseFirstIndex>
struct composite_index_helper;
template <unsigned N, unsigned Dims1>
struct composite_index_helper<N, Dims1, true>
{
template <class I1, class I2>
CC_ALWAYS_INLINE
static decltype(auto) get(I1& i1, I2) noexcept
{ return i1.at_c(sc_coord<N>); }
template <class I1, class I2>
CC_ALWAYS_INLINE constexpr
static decltype(auto) get_const(I1& i1, I2) noexcept
{ return i1.at_c(sc_coord<N>); }
};
template <unsigned N, unsigned Dims1>
struct composite_index_helper<N, Dims1, false>
{
template <class I1, class I2>
CC_ALWAYS_INLINE
static decltype(auto) get(I1, I2& i2) noexcept
{ return i2.at_c(sc_coord<N - Dims1>); }
template <class I1, class I2>
CC_ALWAYS_INLINE constexpr
static decltype(auto) get_const(I1, I2& i2) noexcept
{ return i2.at_c(sc_coord<N - Dims1>); }
};
}
template <class Index1, class Index2>
class composite_index final
{
using i1 = std::decay_t<Index1>;
using i2 = std::decay_t<Index2>;
static constexpr auto dims1 = i1::dims();
static constexpr auto dims2 = i2::dims();
public:
static constexpr auto dims = dims1 + dims2;
private:
Index1& m_i1;
Index2& m_i2;
public:
CC_ALWAYS_INLINE constexpr
explicit composite_index(Index1& i1, Index2& i2)
noexcept : m_i1{i1}, m_i2{i2} {}
template <unsigned N>
CC_ALWAYS_INLINE
decltype(auto) get() noexcept
{
using helper = detail::composite_index_helper<N, dims1, N < dims1>;
return helper::get(m_i1, m_i2);
}
template <unsigned N>
CC_ALWAYS_INLINE constexpr
decltype(auto) get() const noexcept
{
using helper = detail::composite_index_helper<N, dims1, N < dims1>;
return helper::get_const(m_i1, m_i2);
}
};
template <class Index1, class Index2>
CC_ALWAYS_INLINE constexpr
auto operator,(index_wrapper<Index1>& i1, index_wrapper<Index2>& i2)
noexcept
{
using w1 = index_wrapper<Index1>;
using w2 = index_wrapper<Index2>;
using index_type = composite_index<w1, w2>;
using w3 = index_wrapper<index_type>;
return w3{in_place, i1, i2};
}
template <class Index1, class Index2>
CC_ALWAYS_INLINE constexpr
auto operator,(const index_wrapper<Index1>& i1, const index_wrapper<Index2>& i2)
noexcept
{
using w1 = const index_wrapper<Index1>;
using w2 = const index_wrapper<Index2>;
using index_type = composite_index<w1, w2>;
using w3 = index_wrapper<index_type>;
return w3{in_place, i1, i2};
}
}
#endif
| true |
4d3a87efd0e305bcd8419ba495ae7e25804129f1 | C++ | weslu1/cs24_Project1_final | /list.cpp | UTF-8 | 1,761 | 3.484375 | 3 | [] | no_license | #include "list.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
List:: List(){
}
Node* List::getHead()
{
return head;
}
void List::expressionToList(string exp){
Node* parent;
Node* current = new Node;
Node* n;
head = current; //access list with this head
for(int i = 1; i<exp.length(); i++){
if(exp[i] == '('){
parent = current;//create a parent node to access later
n = new Node();
if(current->getLeft() == NULL)
current->setLeft(n);
else
current->setRight(n);
current = n;
}
else if(exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/')
{
if(exp[i] == '+'){
current->setDataOP(PLUS);
current->setNodeType(EXPRESSION);
}
if(exp[i] == '-'){
current->setDataOP(MINUS);
current->setNodeType(EXPRESSION);
}
if(exp[i] == '*'){
current->setDataOP(MULT);
current->setNodeType(EXPRESSION);
}
if(exp[i] == '/'){
current->setDataOP(DIVIDE);
current->setNodeType(EXPRESSION);
}
}
else if(exp[i] == 'x')
{
Node*z = new Node('x');
z->setNodeType(VARIABLE);
current->setLeft(z);
}
else if(exp[i] == '0' ||exp[i] == '1' ||exp[i] == '2' ||exp[i] == '3' ||exp[i] == '4' ||exp[i] == '5' ||exp[i] == '6' ||exp[i] == '7' ||exp[i] == '8' ||exp[i] == '9')
{
int t = (exp[i] - '0');
Node*y = new Node(t);
y->setNodeType(INTEGER);
current->setRight(y);
}
else if(exp[i] == ')')
{
current = parent;
}
}
}
| true |
54a03a4a40559c5594c521bd7dcf9cdc1e070bd3 | C++ | JaeminShim/NCUAdvancedCPP | /Day4/1_this_call_6.cpp | UHC | 1,855 | 3.25 | 3 | [] | no_license | // 1. this call_6 - 9page
#include <iostream>
#include "ioacademy.h"
using namespace std;
using namespace ioacademy;
// C GUI Լ ü ô.
#include <map>
// ̺귯 Ŭ
class CWnd
{
int hwnd; // ȣ
public:
int GetHandle() const { return hwnd; }
public:
void Create()
{
hwnd = IoMakeWindow(foo);
this_map[hwnd] = this;
}
virtual void OnLButtonDown() {}
private:
// A. Ʒ Լ static ˾ƾ մϴ.
static int foo(int h, int msg, int a, int b)
{
// ȣ ڷᱸ this .
CWnd* const self = this_map[h];
switch (msg)
{
case WM_LBUTTONDOWN:
self->OnLButtonDown(); // ٽ Լ ȣ
break;
}
return 0;
}
static map<int, CWnd*> this_map; // ڵ(ȣ) Ű (this)
};
// Ŭ
class MyWindow : public CWnd
{
public:
virtual void OnLButtonDown()
{
cout << "[" << GetHandle() << "] " << "LButton" << endl;
}
};
int main()
{
MyWindow w;
w.Create(); // 찡 Ǿ մϴ.
// LBUTTON "LButton" Ǿ մϴ.
IoProcessMessage(); // óش.
}
/*
[this ϴ ]
1. callbackԼ ڷ this
2. ڷᱸ Ͽ this
^
2 API: C++ Ŭ static Լ => this ٴ
---------------------------------------------------------------------
1 API: C Լ Լȣ(ٸԼ̸(ּ)) - callback Լ
---------------------------------------------------------------------
OS: linux, Windows, MAC - C
*/
| true |
ec56886abdfd7ded579c6db6b6573f781624565a | C++ | Mentos15/PISP_1sem | /PiBSP(ШИМАН)/lab7/ServerMS/ServerMS/ServerMS.cpp | UTF-8 | 2,206 | 2.546875 | 3 | [] | no_license | // ServerMS.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <time.h>
#include <WS2tcpip.h>
#include <WS2tcpip.h>
#include "Winsock2.h"
#include "Windows.h"
#pragma comment(lib, "WS2_32.lib")
using namespace std;
string GetErrorMsgText(int code) // cформировать текст ошибки
{
string msgText;
switch (code) // проверка кода возврата
{
case WSAEINTR: msgText = "WSAEINTR"; break;
case WSAEACCES: msgText = "WSAEACCES"; break;
//..........коды WSAGetLastError ..........................
case WSASYSCALLFAILURE: msgText = "WSASYSCALLFAILURE"; break;
default: msgText = "***ERROR***"; break;
};
return msgText;
};
string SetErrorMsgText(string msgText, int code)
{
cout << code << endl;
return msgText + GetErrorMsgText(code);
};
string charToString(char mes[], int size) {
string finalMes;
for (int i = 0; i < size; i++) {
finalMes += mes[i];
}
return finalMes;
}
int main()
{
HANDLE sHandle; // дескриптор канала
WSADATA wsaData;
int waitTime = 1000 * 60 * 3;//0xFFFFFFFF
try
{
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
throw SetErrorMsgText("Startup:", WSAGetLastError());
//cout << "Server gonna wait " << waitTime / 1000 << " s until it thows an exception" << endl;
if ((sHandle = CreateMailslot(L"\\\\.\\mailslot\\myslot",
1500,
INFINITE, // ждать вечно
NULL)) == INVALID_HANDLE_VALUE)
throw SetErrorMsgText("CreateMailslot", WSAGetLastError());
while (1) {
char buf[300];
DWORD readCount;
if (!ReadFile(sHandle,
buf, // буфер
sizeof(buf), // размер буфера
&readCount, // прочитано
NULL))
throw SetErrorMsgText("ReadFile", WSAGetLastError());
buf[readCount] = '\0';
cout << buf << endl;
}
if (WSACleanup() == SOCKET_ERROR)
throw SetErrorMsgText("WSACleanup", WSAGetLastError());
}
catch (string s) {
cout << endl << s;
}
system("pause");
}
| true |
804def70a4c97910433ca81888abd83ab1944a82 | C++ | acimadamore/competitive-programming | /UVA Online Judge/iCanGuessThaDataStructure.cpp | UTF-8 | 1,351 | 3.15625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <stack>
#include <queue>
/*
* Author: Andrés Cimadamore(@acimadamore)
* Judge: Online Judge(Former UVA Online Judge)
* Problem: 11995 - I Can Guess the Data Structure!
* URL: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3146
* Topics: Ad Hoc,
*
*/
using namespace std;
int main(){
int n, c, x;
bool is_q, is_s, is_pq;
while(cin >> n){
is_q = is_s = is_pq = true;
stack<int> s;
queue<int> q;
priority_queue<int> pq;
for(; n > 0; n--){
cin >> c >> x;
if(c == 1){
q.push(x);
s.push(x);
pq.push(x);
}
else{
if(q.empty()){
is_q = is_s = is_pq = false;
}
else{
is_q = (q.front() == x) && is_q;
is_s = (s.top() == x) && is_s;
is_pq = (pq.top() == x) && is_pq;
q.pop();
s.pop();
pq.pop();
}
}
}
if(!is_s && !is_q && !is_pq){
cout << "impossible" << endl;
}
else{
if((is_s && is_q) || (is_s && is_pq) || (is_q && is_pq)){
cout << "not sure" << endl;
}
else{
if(is_s) cout << "stack" << endl;
if(is_q) cout << "queue" << endl;
if(is_pq) cout << "priority queue" << endl;
}
}
}
return 0;
}
| true |
5218c7d6c305697f42f1b9c97a24c5119152cb34 | C++ | rahul799/leetcode_problems | /Graphs/Bipartitie/Check if a graphs has a cycle of odd length.cpp | UTF-8 | 2,950 | 3.8125 | 4 | [] | no_license | https://www.geeksforgeeks.org/check-graphs-cycle-odd-length/
Check if a graphs has a cycle of odd length
Given a graph, the task is to find if it has a cycle of odd length or not.
It is obvious that if a graph has an odd length cycle then it cannot be Bipartite. In Bipartite graph there are two sets of vertices such that
no vertex in a set is connected with any other vertex of the same set). For a cycle of odd length, two vertices must of the same set be connected
which contradicts
Bipartite definition
Therefore we conclude that every graph with no odd cycles is bipartite. One can construct a bipartition as follows:
(1) Choose an arbitrary vertex x0 and set X0 = {x0}.
(2) Let Y0 be the set of all vertices adjacent to x0 and iterate steps 3-4.
(3) Let Xk be the set of vertices not chosen that are adjacent to a vertex of Yk-1.
(4) Let Yk be the set of vertices not chosen that are adjacent to a vertex of Xk-1.
(5) If all vertices of G have been chosen then
X = X0 ∪ X1 ∪ X2 ∪. . . and Y = Y0 ∪ Y1 ∪ Y2 ∪
// C++ program to find out whether a given graph is
// Bipartite or not
#include <bits/stdc++.h>
#define V 4
using namespace std;
// This function returns true if graph G[V][V] contains
// odd cycle, else false
bool containsOdd(int G[][V], int src)
{
// Create a color array to store colors assigned
// to all veritces. Vertex number is used as index
// in this array. The value '-1' of colorArr[i]
// is used to indicate that no color is assigned to
// vertex 'i'. The value 1 is used to indicate first
// color is assigned and value 0 indicates second
// color is assigned.
int colorArr[V];
for (int i = 0; i < V; ++i)
colorArr[i] = -1;
// Assign first color to source
colorArr[src] = 1;
// Create a queue (FIFO) of vertex numbers and
// enqueue source vertex for BFS traversal
queue <int> q;
q.push(src);
// Run while there are vertices in queue (Similar to BFS)
while (!q.empty())
{
// Dequeue a vertex from queue
int u = q.front();
q.pop();
// Return true if there is a self-loop
if (G[u][u] == 1)
return true;
// Find all non-colored adjacent vertices
for (int v = 0; v < V; ++v)
{
// An edge from u to v exists and destination
// v is not colored
if (G[u][v] && colorArr[v] == -1)
{
// Assign alternate color to this adjacent
// v of u
colorArr[v] = 1 - colorArr[u];
q.push(v);
}
// An edge from u to v exists and destination
// v is colored with same color as u
else if (G[u][v] && colorArr[v] == colorArr[u])
return true;
}
}
// If we reach here, then all adjacent
// vertices can be colored with alternate
// color
return false;
}
// Driver program to test above function
int main()
{
int G[][V] = {{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};
containsOdd(G, 0) ? cout << "Yes" : cout << "No";
return 0;
}
| true |