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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27a23f98cf757a167fc720f123aca255c7c3a4bd | C++ | CuiZhiying/ACM | /COJ/coj1550(AC).cpp | GB18030 | 2,020 | 2.96875 | 3 | [] | no_license | // A[I]<N A[I]=N A[I]>N
//B[I]<N C[I]<=A+B C[I]<=A+B C[I]<=N+B
//B[I]=N C[I]<=A+B C[I]<=A+B C[I]<=B+N
//B[I]>N C[I]<=A+N C[I]<=A+N C[I]<=N+N
//⣬ǾͿг9жcеijַǷ
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int A[26], B[26], C[26];
bool flag[26];
char str[200002];
int main()
{
int i, lenth;
while (cin >> str)
{
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(C, 0, sizeof(C));
lenth = strlen(str);
for (i=0; i<lenth; i++)
{
A[str[i]-'A']++;//ͳAַijĸĸ
}
cin >> str;
for (i=0; i<lenth; i++)
{
B[str[i]-'A']++;//ͳBַĸĸ
}
cin >> str;
for (i=0; i<lenth; i++)
{
C[str[i]-'A']++;
}
memset(flag, true, sizeof(flag));
for (i=0; i<26; i++)
{
if (A[i] > lenth/2)
{
A[i] = lenth/2; //Aijĸ>NУҲֻṩNֵΪN
}
if (B[i] > lenth/2)
{
B[i] = lenth/2;
}
if (C[i] <= A[i] + B[i])//cַǣΪfalse
{
flag[i] = false;
}
}
for (i=0; i<26; i++)
{
if (flag[i] == true)//cַһ㣬ѭ
{
break;
}
}
if (i<26)
{
cout << "NO" << endl;
}
else
{
cout << "YES" << endl;
}
}
return 0;
}
| true |
fe5cb4a4d7cdf37cff2a2ea9422374f4d7b2bb00 | C++ | constantinevi6/SAD | /Sentinel_Auto_Downloader/include/txtfile.hpp | UTF-8 | 1,160 | 2.71875 | 3 | [] | no_license | //
// txtfile.hpp
// ASPS
//
// Created by Constantine VI on 2021/8/24.
// Copyright © 2021 CSRSR. All rights reserved.
//
#ifndef txtfile_h
#define txtfile_h
#include <vector>
#include <string>
#include <filesystem>
class txtFile
{
private:
std::filesystem::path pathFile;
std::vector<std::string> TXTContent;
public:
txtFile();
txtFile(std::filesystem::path InputFilePath);
~txtFile();
// 讀取文字檔內容
int read();
// 寫入文字檔
int write();
// 寫入文字檔至新的位置
int write(std::filesystem::path pathOutputFile);
// 於檔案末端加入文字
int append(std::string Inputstr);
// 於檔案末端加入一行文字
int appendLine(std::string Inputstr);
// 加入一行文字至指定的行數之後
int appendLine(std::string Inputstr, int NoLine);
// 印出檔案內容
int print();
// 印出指定行數之內容
std::string getLine(int NoLine);
// 印出包含關鍵字之內容
std::string getLine(std::string InputKeyword);
// 取得文字檔內容
std::vector<std::string> getTXTContent();
};
#endif /* txtfile_h */
| true |
4cf081084a3097bdcc78d24e81376c439eec9425 | C++ | pzfok/MoonLib | /gtest/src/CppCurlTest.cpp | UTF-8 | 1,120 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include "gtest/gtest.h"
#include <CppCurl.h>
#include <CppLog.h>
static CppLog cppLog;
using namespace std;
TEST(CppCurl, GetUrlEncodeTest)
{
// EXPECT_EQ("123465asd", CppCurl::GetUrlEncode("123465asd"));
// EXPECT_EQ("%E9%97%AE", CppCurl::GetUrlEncode("问"));
}
TEST(CppCurl, ThreadTest)
{
try
{
static const uint32_t THREAD_COUNT = 200;
vector<thread> tds;
for (uint32_t i = 0; i < THREAD_COUNT; ++i)
{
thread t([&]()
{
try
{
CppCurl::Get("www.baidu.com", "",
vector<string>(), "", 30);
}
catch (const CppException &e)
{
ERROR_LOG("抛出异常:%s", e.ToString().c_str());
}
});
tds.push_back(move(t));
}
for (auto &t : tds)
{
t.join();
}
}
catch (const CppException &e)
{
ERROR_LOG("抛出异常:%s", e.ToString().c_str());
}
}
| true |
a3ed2b230848900c3e5be2e8bea6a7ee3e1325cc | C++ | h3nok/MLIntro | /Notebooks/viAI.Runtime/viAI.Runtime/Common.h | UTF-8 | 318 | 2.75 | 3 | [] | no_license | #pragma once
#include <filesystem>
#include <fstream>
#include <string>
namespace fs = std::filesystem;
bool file_exists(const std::string &path, fs::file_status s = fs::file_status{})
{
const fs::path p = fs::path(path);
if (fs::status_known(s) ? fs::exists(s) : fs::exists(p))
return true;
return false;
}
| true |
1f10e54b51ea3dafd3ce34df4f8301400f63195f | C++ | larous25/testC | /basico/structs.cpp | UTF-8 | 1,614 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
const int CERO = 0;
//la structura deportes es similar a un diccionario
//de datos o una columna en un db
//son similares a las clases (solo que todo es de tipo publico)
//tienen propiedades, constructores
struct deportes{
string nombre;
string descripcion;
int nivel;
deportes():nivel{CERO}{
}
};
// crea una función para que cualquier
// tipo en la variable pueda ser leida por el cout
template <typename TIPO> // esto es un template para cualquier tipo de variable (no objetos)
void imprima(const TIPO valor) {
cout<< valor << endl;
}
// sobre escribe la funcion imprima y resive como parametro un argumento
// constante tipo referencia deportes ( es la direccion de memoria)
void imprima(const deportes &valor) {
imprima("esta es la informacion del su deporte:");
imprima("nombre:");
imprima(valor.nombre);
imprima("descripcion:");
imprima(valor.descripcion);
imprima("nivel");
imprima(valor.nivel);
}
int main(void) {
int tamano = CERO;
imprima("favor ingrese cuantos deportes va guardar");
cin>> tamano;
// vector tipo deportes
vector<deportes> d (tamano);
for (unsigned i = CERO; i < d.size(); ++i) {
imprima("ingrese el nombre del deporte");
cin>> d[i].nombre;
imprima("ingrese la descripcion del deporte");
cin>> d[i].descripcion;
imprima("ingrese el nivel del deporte");
cin>> d[i].nivel;
}
for (unsigned i = CERO; i < d.size(); ++i) {
imprima(d[i]);
}
} | true |
ff2a34a22c93596ab66a4a611575f214f41f0688 | C++ | utsavmajhi/CP | /Algorithms/test.cpp | UTF-8 | 447 | 2.890625 | 3 | [] | no_license |
#include <iostream>
#include <algorithm>
using namespace std;
void solve(){
int n;
int a[n];
int b[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
cin>>b[i];
}
int monk=INT32_MIN;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(b[j]>=a[i]){
monk=max(j-i,monk);
}
}
}
if(monk==INT32_MIN){
cout<<0<<endl;
}
else{
cout<<monk<<endl;
}
}
int main() {
int t;
cin>>t;
while(t--){
solve();
}
}
| true |
c5dc7446b1a9804acf91bf14c0e951ff43a1eda5 | C++ | gparkerc/ESP_Time_Date_Clock | /henry_date_clock_lcd_esp8266.ino | UTF-8 | 3,015 | 2.9375 | 3 | [
"MIT"
] | permissive |
/********************************/
// include the library code
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP8266WiFi.h>
#include "TimeDateClient.h"
/**********************************************************/
//char array1[]=" SunFounder "; //the string to print on the LCD
//char array2[]="hello, world! "; //the string to print on the LCD
//int tim = 500; //the value of delay time
// initialize the library with the numbers of the interface pins
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
//#define PIN D5
long lastUpdate = millis();
long lastSecond = millis();
String hours, minutes, seconds, iweek, imonth, iyear, iday;
int currentSecond, currentMinute, currentHour;
int currentMonth, currentYear, currentDay;
String currentWeek;
char ssid[] = "maine coast"; // your network SSID (name)
char pass[] = "abbyisahappygirl"; // your network password
const float UTC_OFFSET = 8;
TimeDateClient timeDateClient(UTC_OFFSET);
void updateTime()
{
hours = timeDateClient.getHours();
minutes = timeDateClient.getMinutes();
seconds = timeDateClient.getSeconds();
iweek = timeDateClient.getWeek();
Serial.println("this is iweek");
Serial.println(iweek);
iday = timeDateClient.getDay();
imonth = timeDateClient.getMonth();
iyear = timeDateClient.getYear();
currentHour = hours.toInt();
if (currentHour > 12) currentHour = currentHour - 12;
currentMinute = minutes.toInt();
currentSecond = seconds.toInt();
lastUpdate = millis();
}
void setup()
{
lcd.init(); //initialize the lcd
lcd.backlight(); //open the backlight
Serial.begin(115200);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
timeDateClient.updateTime();
updateTime() ;
lastUpdate = millis();
lastSecond = millis();
}
void loop()
{
if ((millis() - lastUpdate) > 1800000) updateTime();
if ((millis() - lastSecond) > 1000)
{
lastSecond = millis();
currentSecond++;
if (currentSecond > 59)
{ currentSecond = 0;
currentMinute++;
if (currentMinute > 59) {
currentMinute = 0;
currentHour++;
if (currentHour > 12) currentHour = 0;
}
}
String currentTime = String(currentHour) + ":" + String(currentMinute) + ":" + String(currentSecond);
String currentDate = iweek + "-" + imonth + "-" + iday + "-" + iyear ;
Serial.println(currentTime);
Serial.println(currentDate);
lcd.setCursor(0,0); //set cursor at column 0, line 0
//lcd.print("It's a RED day");
lcd.print(currentDate);
lcd.setCursor(4,1); //sets cursor at column 4 line 1
lcd.print(currentTime);
}
}
| true |
eb587d8036b4a52f38384ef130cdf4e422faacd2 | C++ | trinitrotoluene/binary_master | /server/server/src/sreg.cpp | UTF-8 | 1,266 | 2.625 | 3 | [] | no_license | /*
* This implementation is re-used from my last arduino coursework submission.
* Patrick Michallet & Daniel Morris, 2019
* https://github.bath.ac.uk/cm10194-cw1-prm45-dm986/arduino-code/blob/master/game/src/sreg.cpp
*/
#include "sreg.hpp"
#include <Arduino.h>
SReg::SReg(int data_pin, int latch_pin, int clock_pin) {
this->_data_pin = data_pin;
this->_latch_pin = latch_pin;
this->_clock_pin = clock_pin;
pinMode(data_pin, OUTPUT);
pinMode(latch_pin, OUTPUT);
pinMode(clock_pin, OUTPUT);
this->_state = 0x0;
}
void SReg::Init() {
digitalWrite(this->_latch_pin, LOW);
shiftOut(this-> _data_pin, this->_clock_pin, MSBFIRST, this->_state);
digitalWrite(this->_latch_pin, HIGH);
}
int SReg::GetPinState(int pin) {
if (pin < 0 || pin > 7) {
return LOW;
}
if (bitRead(this->_state, pin)) {
return HIGH;
}
else {
return LOW;
}
}
void SReg::DigitalWrite(int pin, int value) {
if (pin < 0 || pin > 7) {
return;
}
bitWrite(this->_state, pin, value);
digitalWrite(this->_latch_pin, LOW);
shiftOut(this->_data_pin, this->_clock_pin, MSBFIRST, this->_state);
digitalWrite(this->_latch_pin, HIGH);
}
| true |
be8bd10f97cb796f8bf37ec1564262486f6f2589 | C++ | FreeTax/exercise-C- | /ex1/main.cpp | UTF-8 | 216 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include "Contatore.h"
using N1::Contatore;
using namespace std;
int main() {
Contatore *c1= new Contatore();
for (int i=0; i<10; i++)
c1->adder();
cout<<c1->get_counter();
}
| true |
73406376b2e3be913800403cec8d821f5ba922bc | C++ | AaronGrissomCU/Homework7 | /HashTable::getTotalNumberNonStopWords.cpp | UTF-8 | 378 | 2.765625 | 3 | [] | no_license | int HashTable::getTotalNumberNonStopWords()
{
wordItem* scout = nullptr;
int numNonStopWords = 0;
for (int c = 0; c < STOPWORD_LIST_SIZE; c++)
{
scout = hashTable[c];
while (scout != nullptr)
{
numNonStopWords += scout->count;
scout = scout->next;
}
}
return numNonStopWords;
}
| true |
4e12072de2a51e85a10227308e66cb8932d283a1 | C++ | anuwu/Competitive-Programming | /InterviewBit/Math/Prime_Numbers.cpp | UTF-8 | 481 | 2.703125 | 3 | [] | no_license | vector<int> Solution::sieve(int N)
{
int i, p, st ;
vector<bool> arr(N , false) ;
vector<int> ans ;
p = 2 ;
st = p*p ;
while (st <= N)
{
while (st <= N)
{
arr[st - 1] = true ;
st += p ;
}
do p++ ; while (arr[p - 1]) ;
st = p*p ;
}
for (i = 1 ; i < N ; i++)
if (!arr[i])
ans.push_back (i+1) ;
return ans ;
}
| true |
28fee7b983b93eee1ef8c893de41aabdc468fdc7 | C++ | LucasPauloOP/AED | /revisao_de_prog2_ex4.cpp | UTF-8 | 738 | 3.3125 | 3 | [] | no_license | /*4)Ler a dist�ncia percorrida e o tempo gasto. Escrever LENTO, NORMAL e R�PIDO,
caso a velocidade m�dia est� abaixo de 60km/h, entre 60 e 100, ou acima de 100 km/h. Dica:
para calcular a velocidade deve-se fazer "dist�ncia/tempo". V=d/t.*/
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
int main()
{
setlocale(LC_ALL,"portuguese");
int dist,temp,v,min;
printf("Digite a dist�ncia percorrida em km: ");
scanf("%d",&dist);
printf("Digite quantas horas gastou: ");
scanf("%d",&temp);
printf("Digite quantos minutos gastou: ");
scanf("%d",&min);
min *= 60;
temp += min;
v = dist/temp;
if(v<60){
printf("LENTO");
}
else
if(v<100){
printf("NORMAL");
}
else{
printf("R�PIDO");
}
}
| true |
a39880a87a5a9ad94a2425900f1020356c96bb99 | C++ | Invadoge/UP2019 | /exercises/07 - Pointers and References/algorithm.h | UTF-8 | 4,781 | 3.671875 | 4 | [] | no_license | #include <iostream>
#pragma once
void swap(int& a, int& b)
{
int c = a;
a = b;
b = c;
}
void iter_swap(int* a, int* b)
{
swap(*a, *b);
}
void print(const int* begin, const int* end)
{
for (; begin != end; ++begin)
{
std::cout << *begin << ' ';
}
std::cout << '\n';
}
void reverse(int* begin, int* end)
{
for (; begin !=end && begin != --end; ++begin)
{
iter_swap(begin, end);
}
}
int* copy(const int* input_begin, const int* input_end,
int* output_begin)
{
for (; input_begin != input_end; ++input_begin)
{
*(output_begin++) = *input_begin;
}
return output_begin;
}
int* rotate(int* begin, int* mid, int* end)
{
reverse(begin, mid);
reverse(mid, end);
reverse(begin, end);
return begin + (end - mid);
}
int* erase(int* begin, int* end, unsigned index)
{
int* element_position = begin + index;
return rotate(element_position, element_position + 1, end);
}
int* insert(int* begin, int* end, unsigned index, int element)
{
int* element_position = begin + index;
*end = element;
rotate(element_position, end, end + 1);
return end + 1;
}
const int* find(const int* begin, const int* end, int element)
{
for (; begin != end; ++begin)
{
if (*begin == element)
{
return begin;
}
}
return begin;
}
int* find(int* begin, int* end, int element)
{
for (; begin != end; ++begin)
{
if (*begin == element)
{
return begin;
}
}
return begin;
}
bool contains(const int* begin, const int* end, int element)
{
return find(begin, end, element) != end;
}
int inner_product(const int* begin_1, const int* end_1,
const int* begin_2)
{
int result{0};
for (; begin_1 != end_1; ++begin_1, ++begin_2)
{
result += *begin_1 * *begin_2;
}
return result;
}
int* partial_sum(const int* input_begin, const int* input_end,
int* output_begin)
{
int sum{0};
for(; input_begin != input_end; ++input_begin)
{
*(output_begin++) = sum += *input_begin;
}
return output_begin;
}
int* adjacent_difference(const int* input_begin, const int* input_end,
int* output_begin)
{
int last{0};
for(; input_begin != input_end; ++input_begin)
{
int current = *input_begin;
*(output_begin++) = current - last;
last = current;
}
return output_begin;
}
const int* min_element(const int* begin, const int* end)
{
const int* min_element{begin};
int minimum(*begin);
for (; begin != end; ++begin)
{
if (*begin < minimum)
{
minimum = *begin;
min_element = begin;
}
}
return min_element;
}
int* min_element(int* begin, int* end)
{
int* min_element{begin};
int minimum(*begin);
for (; begin != end; ++begin)
{
if (*begin < minimum)
{
minimum = *begin;
min_element = begin;
}
}
return min_element;
}
void selection_sort(int* begin, int* end)
{
for (; begin != end; ++begin)
{
iter_swap(begin, min_element(begin, end));
}
}
int* merge(const int* input_begin_1, const int* input_end_1,
const int* input_begin_2, const int* input_end_2,
int* output_begin)
{
while (input_begin_1 != input_end_1 && input_begin_2 != input_end_2)
{
if (*input_begin_1 <= *input_begin_2)
{
*(output_begin++) = *(input_begin_1++);
}
else
{
*(output_begin++) = *(input_begin_2++);
}
}
output_begin = copy(input_begin_1, input_end_1, output_begin);
return copy(input_begin_2, input_end_2, output_begin);
}
const int* upper_bound(const int* begin, const int* end, int element)
{
while (begin < end)
{
const int* mid{begin + (end - begin) / 2};
if (element >= *mid)
{
begin = mid + 1;
}
else
{
end = mid;
}
}
return begin;
}
int* upper_bound(int* begin, int* end, int element)
{
while (begin < end)
{
int* mid{begin + (end - begin) / 2};
if (element >= *mid)
{
begin = mid + 1;
}
else
{
end = mid;
}
}
return begin;
}
bool binary_search(const int* begin, const int* end, int element)
{
const int* greater = upper_bound(begin, end, element);
return greater != begin && *(greater - 1) == element;
}
void insertion_sort(int* begin, int* end)
{
for (int* i = begin; i != end; ++i)
{
rotate(upper_bound(begin, i, *i), i, i + 1);
}
}
| true |
a05ff8b84951b7ed50f5211f3af2814c0d4f34c4 | C++ | 2myungho/algorithm_training | /Programmers/lv2/12985_binary/answer.cpp | UTF-8 | 610 | 3.515625 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int solution(int n, int a, int b) {
int answer = 0;
while (a != b) {
answer += 1;
a = (a + 1) / 2;
b = (b + 1) / 2;
}
return answer;
}
struct TestCase {
int N;
int A;
int B;
int answer;
};
int main() {
vector<TestCase> tcs = {
{8, 4, 7, 3}
};
for (TestCase tc : tcs) {
int answer = solution(tc.N, tc.A, tc.B);
bool isCorrect = answer == tc.answer;
cout << isCorrect << ", answer : " << tc.answer << ", myAnswer : " << answer << "\n";
}
return 0;
} | true |
a7584b34dc5121cdb23c231a726aa83f52337e04 | C++ | thereisnoposible/Shared | /hh/hh/Event.cpp | UTF-8 | 1,258 | 2.609375 | 3 | [] | no_license | #include "Event.h"
namespace ZeroSpace
{
CEvent::~CEvent()
{
m_handlers.Clear();
}
void CEvent::AddHandler(EventHandlerPtr pHandler)
{
m_handlers.Insert(pHandler->GetEventID(), pHandler);
}
void CEvent::RemoveHandler(EventIDType id)
{
m_handlers.Erase(id);
}
CEventRetuirnBase& CEvent::Trigger(CEventArgsBase* pArgs)
{
static CEventRetuirn<void> errorReturn;
if (pArgs == NULL)
{
return errorReturn;
}
EventHandlerType::Iterator it = m_handlers.Find(pArgs->GetEventID());
if (it == m_handlers.GetEnd())
{
return errorReturn;
}
return it->GetValue()->TriggerEvent(pArgs);
}
CEventRetuirnBase& CEvent::Trigger(const byte* buffer, size_t len)
{
static CEventRetuirn<void> errorReturn;
EventIDType eventID = *((EventIDType*)buffer);
EventHandlerType::Iterator it = m_handlers.Find(eventID);
if (it == m_handlers.GetEnd())
{
return errorReturn;
}
return it->GetValue()->TriggerEvent(buffer, len);
}
CEventProxy& CEvent::EventID(EventIDType id)
{
m_proxy.m_eventID = id;
return m_proxy;
}
EventHandlerPtr CEvent::GetHandler(EventIDType id)
{
EventHandlerType::Iterator it = m_handlers.Find(id);
if (it == m_handlers.GetEnd())
{
return NULL;
}
return it->GetValue();
}
}
| true |
98970241bbe24fab67e40b0e15e206adaf128027 | C++ | imran458/HunterCS | /CSCI335/Assignment5ImranSabur/FindPaths.cpp | UTF-8 | 1,301 | 3.625 | 4 | [] | no_license | /*
-Imran Sabur
- December 11, 2019
-
*/
#include <iostream>
using namespace std;
#include <string>
#include <sstream>
#include <fstream>
#include "Graph.h"
int main(int argc, char **argv){
if (argc != 3)
{
cout << "Usage: " << argv[0] <<" <GRAPH_FILE> <STARTING_VERTEX>" << endl;
return 0;
}
const string create_graph_file (argv[1]);
int vertex_from_cmdline = atoi(argv[2]); //command line input
ifstream input_file (create_graph_file);
string line;
int n; //amount of vertices
input_file >> n; //store the first thing read by the file as that is the graph size
Graph new_graph (n);//object of graph class with total number of vertices as a parameter
cout << "Performing Dijkstra: " << endl;
int vertex;
int adjacent_vertex;
float cost;
while (getline(input_file, line)) //reading each line from the input file
{
stringstream ss(line); //a string stream object used to parse vertex, cost and adjacent vertex
ss >> vertex;//get the first item, or the vertex
while (ss >> adjacent_vertex && ss >> cost)
{
new_graph.addToAdjaceny(vertex, adjacent_vertex, cost); //add the vertex, the adjacent vertex and the cost to the adjacency list
}
}
new_graph.Dijkstra(vertex_from_cmdline); //call the dijkstra function with that number as a function paramater
} | true |
194d6045a7c342ac3fe8901b0bc3eb1b931f6ea9 | C++ | KarolStola/DragonframeWithOpti | /DragonframeOptiWrapper.cpp | UTF-8 | 3,448 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <Opti.h>
#include <DragonframeMotionController.h>
#include <MemberBluetoothMessageHandler.h>
#include "DragonframeOptiWrapper.h"
DragonframeOptiWrapper::DragonframeOptiWrapper(Opti & opti)
: opti(opti)
{
jogSpeeds.resize(GetNumberOfAxes(), standardSpeed);
jogStatuses.resize(GetNumberOfAxes(), false);
}
void DragonframeOptiWrapper::BindAsMessageHandler(class DragonframeMotionController & motionController)
{
opti.SetBluetoothMessageDelimiter(motionController.GetIncomingMessageDelimiter());
opti.AddBluetoothMessageHandler(new MemberBluetoothMessageHandler<DragonframeMotionController>(motionController, &DragonframeMotionController::ParseInput));
}
int DragonframeOptiWrapper::GetProtocolMajorVersion()
{
return majorVersion;
}
int DragonframeOptiWrapper::GetProtocolMinorVersion()
{
return minorVersion;
}
int DragonframeOptiWrapper::GetProtocolFixVersion()
{
return fixVersion;
}
int DragonframeOptiWrapper::GetNumberOfAxes()
{
return opti.GetMotorCount();
}
bool DragonframeOptiWrapper::GetIsMotorMoving(int motorIndex)
{
return opti.IsMoving(ToOptiIndex(motorIndex));
}
int DragonframeOptiWrapper::GetCurrentStep(int motorIndex)
{
return opti.GetCurrentStep(ToOptiIndex(motorIndex));
}
void DragonframeOptiWrapper::MoveMotorTo(int motorIndex, int stepPosition)
{
SetIsJogging(motorIndex, false);
SetStepsPerSecond(motorIndex, standardSpeed);
MoveTo(motorIndex, stepPosition);
}
void DragonframeOptiWrapper::JogMotorTo(int motorIndex, int stepPosition)
{
SetIsJogging(motorIndex, true);
MoveTo(motorIndex, stepPosition);
}
void DragonframeOptiWrapper::InchMotorTo(int motorIndex, int stepPosition)
{
SetIsJogging(motorIndex, false);
SetStepsPerSecond(motorIndex, inchingSpeed);
MoveTo(motorIndex, stepPosition);
}
void DragonframeOptiWrapper::StopMotor(int motorIndex)
{
opti.StopMoving(ToOptiIndex(motorIndex));
}
void DragonframeOptiWrapper::StopAllMotors()
{
opti.StopMovingAll();
}
void DragonframeOptiWrapper::SetJogSpeedForMotor(int motorIndex, int stepsPerSecond)
{
jogSpeeds[ToOptiIndex(motorIndex)] = stepsPerSecond;
if(IsJogging(motorIndex))
{
SetStepsPerSecond(motorIndex, stepsPerSecond);
}
}
void DragonframeOptiWrapper::ZeroMotorPosition(int motorIndex)
{
opti.ResetCurrentStep(ToOptiIndex(motorIndex));
}
void DragonframeOptiWrapper::SetMotorPosition(int motorIndex, int motorPosition)
{
opti.SetCurrentStep(ToOptiIndex(motorIndex), motorPosition);
}
void DragonframeOptiWrapper::SendMessage(const String & message)
{
opti.SendBluetoothMessage(message);
}
void DragonframeOptiWrapper::SetIsJogging(int motorIndex, bool value)
{
jogStatuses[ToOptiIndex(motorIndex)] = value;
if(value)
{
SetStepsPerSecond(motorIndex, GetJogSpeed(motorIndex));
}
}
bool DragonframeOptiWrapper::IsJogging(int motorIndex)
{
return jogStatuses[ToOptiIndex(motorIndex)];
}
int DragonframeOptiWrapper::ToOptiIndex(int dragondrameIndex)
{
return dragondrameIndex - 1;
}
void DragonframeOptiWrapper::SetStepsPerSecond(int motorIndex, int stepsPerSecond)
{
opti.SetStepsPerSecond(ToOptiIndex(motorIndex), stepsPerSecond);
}
int DragonframeOptiWrapper::GetJogSpeed(int motorIndex)
{
return jogSpeeds[ToOptiIndex(motorIndex)];
}
void DragonframeOptiWrapper::MoveTo(int motorIndex, long stepPosition)
{
opti.MoveTo(ToOptiIndex(motorIndex), stepPosition);
}
| true |
b3d60a5e36b004f11261ebc8c558df309157c9f3 | C++ | conorbrown327/Iteration-1 | /project/tests/vector3d_test.cc | UTF-8 | 1,505 | 3 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "vector3d.h"
#include <iostream>
namespace csci3081
{
class Vector3dTest : public ::testing::Test
{
public:
virtual void SetUp()
{
v = new Vector3d();
}
protected:
Vector3d *v;
};
/*******************************************************************************
* Test Cases
******************************************************************************/
/** Test that the default constructor works and assigns the correct values */
TEST_F(Vector3dTest, Vector3dContructorTest)
{
ASSERT_NE(nullptr, v);
ASSERT_FLOAT_EQ(0.0, v->GetX());
ASSERT_FLOAT_EQ(0.0, v->GetY());
ASSERT_FLOAT_EQ(0.0, v->GetZ());
}
/** Test the getters and setters for x_ */
TEST_F(Vector3dTest, GetXTest)
{
v->SetX(3.3);
ASSERT_FLOAT_EQ(3.3, v->GetX());
}
/** Test the getters and setters for y_ */
TEST_F(Vector3dTest, GetYTest)
{
v->SetY(3.3);
ASSERT_FLOAT_EQ(3.3, v->GetY());
}
/** Test the getters and setters for z_ */
TEST_F(Vector3dTest, GetZTest)
{
v->SetZ(3.3);
ASSERT_FLOAT_EQ(3.3, v->GetZ());
}
/** Test that the Normalize function works */
TEST_F(Vector3dTest, NormalizeTest)
{
Vector3d* norm = v->Normalize();
ASSERT_NE(nullptr, norm);
ASSERT_FLOAT_EQ(1.0, norm->GetX());
ASSERT_FLOAT_EQ(1.0, norm->GetY());
ASSERT_FLOAT_EQ(1.0, norm->GetZ());
}
/** Test that the Magnitude test works */
TEST_F(Vector3dTest, MagnitudeTest)
{
float magn = v->Magnitude();
ASSERT_FLOAT_EQ(0.0, magn);
}
} // namespcae csci3081
| true |
e195bfb8b449244d437f6da0e51faaf6b1b76515 | C++ | Naughty-Panda/CppPreprocessing | /mylib.h | UTF-8 | 2,010 | 2.828125 | 3 | [] | no_license | #pragma once
#include <array>
#include <string>
//////////////////////////////////////////////////////////
// Macro
//////////////////////////////////////////////////////////
#define TEST_INPUT(a, b) (((b) >= 0) ? ((a) >= 0 && (a) < (b) ? true : false) : ((a) <= 0 && (a) > (b) ? true : false))
#define BOOL_TO_STR(a) ((a) ? "true" : "false")
#define SWAP_INT(a, b) (a) = (a)^(b); (b) = (b)^(a); (a) = (a)^(b)
#define PRINT_ARRAY() std::cout << "[ "; for (size_t i = 0; i < ARR_SIZE; i++) {std::cout << arr[i] << " ";} std::cout << "]\n"
#define ARR_SIZE 10
#define FLOAT_SIGN_POS 31
namespace Mylib {
//////////////////////////////////////////////////////////
// Structs
//////////////////////////////////////////////////////////
struct TArray {
std::array<float, ARR_SIZE> data;
};
#pragma pack(push, 1)
struct TEmployee {
std::string firstName = "temporary";
std::string lastName = "placeholder";
int ID = 0;
float salary = 0.0f;
int GetSize() { return sizeof(*this); }
bool SaveToFile();
};
#pragma pack(pop)
//////////////////////////////////////////////////////////
// Array initialization
//////////////////////////////////////////////////////////
float* NewArray();
TArray* NewStdArray();
//////////////////////////////////////////////////////////
// Array printing
//////////////////////////////////////////////////////////
void PrintArray(const float*, const size_t&);
void PrintArray(const TArray*);
void PrintArray(const int*);
//////////////////////////////////////////////////////////
// Array operations
//////////////////////////////////////////////////////////
void FillArray(float*, const size_t&, const float& filler = 0.0f);
void FillArray(TArray*, const float& filler = 0.0f);
std::pair<int, int> CountElems(const TArray*);
int CountElems(const float*, const size_t&);
int CountElemsBinary(const float*, const size_t&);
int CountElemsBinary(const TArray*);
bool _sorted(int*);
void SortArray(int*);
void GetInput(int*);
}
| true |
8283fccde7eb904bf0cca3b78a5d0ce413e05f2d | C++ | wagnerdgarcia/Projetos-Gerais | /Projetos de Arduino/2_Sensor_de_Linha/sketch_april21a.ino | UTF-8 | 1,122 | 2.8125 | 3 | [] | no_license | #define LinhaDD 7
#define LinhaDE 8
#define LinhaAD A0
#define LinhaAE A1
void setup() {
// put your setup code here, to run once:
pinMode(LinhaAD, INPUT);
pinMode(LinhaAE, INPUT);
pinMode(LinhaDD, INPUT);
pinMode(LinhaDE, INPUT);
Serial.begin(9600);
Serial.println("Lendo dados do Sensor...");
}
void loop() {
// put your main code here, to run repeatedly:
/*
Serial.print("\n");
Serial.print("\n");
Serial.print("\n");
Serial.print("Sensor Linha Direito Analogico - ");
Serial.print(analogRead(LinhaAD));
Serial.print("\n");
Serial.print("Sensor Linha Direito Digital - ");
Serial.print(digitalRead(LinhaDD));
Serial.print("\n\n");
Serial.print("Sensor Linha Esquerdo Analogico - ");
Serial.print(analogRead(LinhaAE));
Serial.print("\n");
Serial.print("Sensor Linha Esquerdo Digital - ");
Serial.print(digitalRead(LinhaDE));
Serial.print("\n");*/
if(analogRead(LinhaAD) >= 100) Serial.print("Passou pelo Direito;\n");
if(analogRead(LinhaAE) >= 100) Serial.print("Passou pelo Esquerdo;\n");
delay(100);
}
| true |
0e267596bc5a7d83f3a952a368f10a1fae33cc75 | C++ | markbirss/everything-nrf52840-usb-dongles | /code/simple-ble-led/backups/wifi-ble-generic02.ino | UTF-8 | 12,284 | 2.578125 | 3 | [
"MIT"
] | permissive | /*
WiFi BLE Server
A simple web server that shows the value of the analog input pins
shuts down and loads BLE to identify knone LED BLE active devices
then restarts Wifi before the page refreshes.
expects several prenamed Simple LED devices to be nearby and fresh running
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
Circuit:
* Analog inputs attached to pins A0 through A5 (optional)
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
modified Jan 14th, 2020
by Jeremy Ellis
Twitter @rocksetta
*/
#include <SPI.h>
#include <WiFiNINA.h>
#include "utility/wifi_drv.h"
#include "arduino_secrets.h"
#include <ArduinoBLE.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
int myWifiInterval = 40000; // 40 seconds
int myBleInterval = 6000; // 6 seconds
int myInterval = myWifiInterval; // 1000 = wait 1 second
unsigned long myOldTme=0;
const int ledPin = LED_BUILTIN; // set ledPin to on-board LED
bool myChooseWifi = true;
const int myMaxArray = 10; // no idea how many BLE devices
bool myBleActive[myMaxArray]; // not pre-defined as false
String myBLENames[myMaxArray];
const uint8_t* myLedValue[myMaxArray];
WiFiServer server(80);
void setup() {
pinMode(ledPin, OUTPUT);
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
setupWifi();
Serial.println("Need several BLE devices running Simple-LED");
Serial.print("Wifi runs for: ");
Serial.print(myWifiInterval/1000);
Serial.print(" seconds, BLE runs for: ");
Serial.print(myBleInterval/1000);
Serial.println(" seconds.");
}
void loop() {
if (myChooseWifi){
myWifi();
} else { // Do BLE
updateBLE();
}
unsigned long myNewTime = millis();
if ((unsigned long)(myNewTime - myOldTme) >= myInterval) {
myOldTme = myNewTime;
digitalWrite(ledPin, !digitalRead(ledPin)); // Toggle the LED on Pin 13 most boards
if (myChooseWifi) { // shut off wifi turn on BLE
myInterval = myBleInterval; // 6 seconds
myChooseWifi = false;
Serial.println("shutting down Wifi");
WiFi.end();
delay(2000);
Serial.println("Starting BLE");
myBleActive[0] = false;
myBleActive[1] = false;
myBleActive[2] = false;
myBleActive[3] = false;
BLE.begin();
BLE.scan();
} else { // shut off BLE turn on Wifi
myChooseWifi = true;
myInterval = myWifiInterval; // 40 seconds
Serial.println("Shutting down BLE");
BLE.stopScan();
BLE.end();
delay(2000);
Serial.println("Starting Wifi");
// Re-initialize the WiFi driver
// This is currently necessary to switch from BLE to WiFi
// wiFiDrv.wifiDriverDeinit();
// wiFiDrv.wifiDriverInit();
status = WiFi.begin(ssid, pass);
server.begin();
Serial.print("Wifi Status: ");
Serial.println(status);
}
} // end timer
} // end void loop()
////////////////////////////////// Wifi stuff //////////////////
void setupWifi(){
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 3 default 10 seconds for connection:
delay(3000);
}
server.begin();
// you're connected now, so print out the status:
printWifiStatus();
}
void myWifi(){
// listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// Serial.write(c); tons of info done here
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 10"); // refresh the page automatically every 10 sec, remove if you want one read.
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.print("<br><br><table border=1>");
client.print("<tr> <th>#</th> <th>Active</th> <th>LED</th> <th>Name</th> </tr>");
for (int BleLoop = 0; BleLoop < myMaxArray; BleLoop++) {
client.print("<tr><td>");
client.print(BleLoop);
if (!myBleActive[BleLoop]){ // check if not active
client.print("</td> <td>Not Active</td> <td>...</td> <td>");
} else {
if (ledIsOn(myLedValue[BleLoop])){
client.print("</td> <td>Active</td> <td>On</td> <td>");
} else {
client.print("</td> <td>Active</td> <td>Off</td> <td>");
}
}
client.print(myBLENames[BleLoop]);
client.println("</td></tr>");
} // end for loop
client.println("</table><br />");
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("Load web browser at this IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
////////////////////////////////// end Wifi ////////////////////
///////////////////////////// BLE stuff ////////////////////////
// helper function to print HEX variables
void printData(const unsigned char data[], int length) {
for (int i = 0; i < length; i++) {
unsigned char b = data[i];
if (b < 16) {
Serial.print("0");
}
Serial.print(b, HEX);
}
}
bool ledIsOn(const unsigned char data[]) {
for (int i = 0; i < 1; i++) {
unsigned char b = data[i];
if (b <= 0) {
return false;
} else {
return true;
}
}
}
/*
bool ledIsOn(const unsigned char data[], int length) {
for (int i = 0; i < length; i++) {
unsigned char b = data[i];
if (b <= 0) {
return false;
} else {
return true;
}
}
}
*/
void updateBLE(){
BLEDevice myPeripheral = BLE.available();
if (myPeripheral) {
// if (myPeripheral.localName() == "LED") { // use only if you know the exact name
if (myPeripheral.localName().indexOf("LED") >= 0){ // contains name
BLE.stopScan();
// connect to the myPeripheral
Serial.println("Connecting ...");
digitalWrite(ledPin, HIGH); // LED on
if (myPeripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover myPeripheral attributes
Serial.println("Discovering attributes ...");
if (myPeripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
//myPeripheral.disconnect();
return;
}
BLECharacteristic ledCharacteristic = myPeripheral.characteristic("19b10011-e8f2-537e-4f6c-d104768a1214");
// Note: Also works the 2 GATT's are slightly different: service=19b10010, LED=19b10011
// BLECharacteristic ledCharacteristic = myPeripheral.service("19b10010-e8f2-537e-4f6c-d104768a1214").characteristic("19b10011-e8f2-537e-4f6c-d104768a1214"); //worked
if (!ledCharacteristic) {
Serial.println("myPeripheral does not have LED characteristic!");
myPeripheral.disconnect();
return;
} else if (!ledCharacteristic.canWrite()) {
Serial.println("myPeripheral does not have a writable LED characteristic!");
myPeripheral.disconnect();
return;
}
// check if the characteristic is readable
if (ledCharacteristic.canRead()) {
// read the characteristic value
ledCharacteristic.read();
if (ledCharacteristic.valueLength() > 0) {
Serial.println();
Serial.print("value-length: ");
Serial.print(ledCharacteristic.valueLength());
Serial.print(", LocalName: ");
Serial.print(myPeripheral.localName());
Serial.print(" 0x");
printData(ledCharacteristic.value(), ledCharacteristic.valueLength());
// print out the value of the characteristic
Serial.println(" HEX value: ");
////////////////////////////////// Start BLE Analysis /////////////////////////////////////////////////////////////
bool myBleIsStored = false;
int myStoredLocation;
for (int BleLoop2 = myMaxArray-1; BleLoop2 >= 0 ; BleLoop2--) { // count down and check if BLE device is already saved
if (myPeripheral.localName() == myBLENames[BleLoop2]){
myBleIsStored = true;
}
if (myBLENames[BleLoop2] == ""){ // if the name is missing then a new name can go there
myStoredLocation = BleLoop2;
}
}
if (!myBleIsStored){
myBLENames[myStoredLocation] = myPeripheral.localName(); // save it if not saved
}
//regular loop here
for (int BleLoop = 0; BleLoop < myMaxArray; BleLoop++) {
if (myPeripheral.localName() == myBLENames[BleLoop]){
Serial.println();
Serial.print(myBLENames[BleLoop]);
Serial.println();
myBleActive[BleLoop] = true;
myLedValue[BleLoop] = ledCharacteristic.value();
}
}
////////////////////////////////// End BLE Analysis /////////////////////////////////////////////////////////////
} // end ledChaaracteristic
}
Serial.println("myPeripheral disconnected");
digitalWrite(ledPin, LOW);
BLE.stopScan();
myPeripheral.disconnect();
BLE.scan();
}
} // end if (myperipheral)
} // end updateBLE()
| true |
bd93c9dd0f0862690d15e996d396db9188313bf4 | C++ | 2012ankitkmr/My-works | /Practice Codes/rangezer.cpp | UTF-8 | 1,309 | 2.859375 | 3 | [] | no_license | #include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
template<class T>
inline T fastIn() {
register char c=0;
register T a=0;
bool neg=false;
while ( c<33 ) c=getchar();
while ( c>33 ) {
if ( c=='-' ) {
neg=true;
} else {
a= ( a*10 ) + ( c-'0' );
}
c=getchar();
}
return neg?-a:a;
}
unsigned zeroCount(unsigned long long k)
{
unsigned zeros = 0;
while(k) {
zeros += (k % 10) == 0;
k /= 10;
}
return zeros;
}
unsigned long long Z(unsigned long long n)
{
printf("here\n");
if (n == 0) {
return 0;
}
if (n <= 10) {
return 1;
}
unsigned long long k = n/10, r = n%10;
printf("k=%d\n",k);
unsigned long long zeros = k + 10*(Z(k)-1);
if (r > 0) {
zeros += r*zeroCount(k) + 1;
}
printf("z=%d\n",zeros);
return zeros;
}
unsigned long long zeros_in_range(unsigned long long low, unsigned long long high)
{
return Z(high+1) - Z(low);
}
int main()
{
int t;
unsigned long long x,y;
t=fastIn<int>();
while(t--)
{
x=fastIn<unsigned long long>();
y=fastIn<unsigned long long>();
unsigned long long res=zeros_in_range(x,y);
cout<<res<<endl;
}
return 0;
}
| true |
f9831f7929e65a36677e76fde85119a57d32726b | C++ | kakachen4129/Cracking_the_code_interview | /lc/172_FactorialTrailingZeros.cpp | UTF-8 | 206 | 2.8125 | 3 | [] | no_license | class Solution {
public:
int trailingZeroes(int n) {
int cnt = 0;
long t = 5;
while (n/t > 0){
cnt += n/t;
t = t*5;
}
return cnt;
}
}; | true |
d5dcd6ac6eba4c911d711958a3f44d155a106f9a | C++ | juliiiks/vector | /vector.h | UTF-8 | 5,531 | 3.984375 | 4 | [] | no_license | #pragma once
#include "iterator.h"
template <typename T>
class Vector {
private:
// Длина
int length;
// Вместительность
int capacity;
// Динамический массив
T* mass;
public:
// конструктор с длиной
Vector(int length) {
this->length = length;
this->capacity = length * 1.5;
// Выделение памяти под динамический массив
this->mass = new T[capacity];
}
// Явный конструктор со списком инициализации {}
explicit Vector(std::initializer_list<T> lst)
: Vector(lst.size()) {
int index = 0;
// Цикл
for (auto& item : lst) {
// Перегоняем каждый элемент из списка инициализации в массив
mass[index] = item;
++index;
}
}
// Конструктор копирования
Vector(const Vector<T>& other) {
length = other.length;
capacity = other.capacity;
mass = new T[other.capacity];
// копируем другой массив в свой
memcpy(mass, other.mass, other.length * sizeof(T));
}
// Деструктор
~Vector() {
// Освобождаем память
delete[] mass;
}
void shrink_to_fit() {
mass = (int*)realloc(mass, length);
capacity = length;
}
void print() {
for (int i = 0; i < length; ++i)
std::cout << mass[i] << std::endl;
}
int get_length() const {
return length;
}
// Изменить по индексу
void set_elem(int index, const T& elem) {
if (index < length)
mass[index] = elem;
else
throw std::out_of_range("Out of range");
}
// Получить элемент
T& get_elem(int index) {
if (index < length)
return mass[index];
else
throw std::out_of_range("Out of range");
}
// Скопировать новый в массив
T* to_array() {
T* new_array = new T[length];
// Копируем все в новый массив
memcpy(new_array, mass, length * sizeof(T));
return new_array;
}
// Возвращаем итератор, указывающий на первй элемент
Iterator<T> begin() {
return Iterator<T>(*this);
}
// Возвращаем итератор, указывающий на последний элемент
Iterator<T> end() {
return Iterator<T>(*this, this->length);
}
Vector<T>& operator=(const Vector<T>& other) {
length = other.length;
capacity = other.capacity;
delete[] mass;
mass = new T[capacity];
// Копируем все из другого вектора
memcpy(mass, other.mass, length * sizeof(T));
return *this;
}
T& operator[](int index) {
return mass[index];
}
Vector<T>& operator+=(const Vector<T>& other) {
if (this->length != other.get_length())
throw std::length_error("Vectors are of different length");
for (int i = 0; i < length; ++i)
mass[i] += other.mass[i];
return *this;
}
Vector<T>& operator-=(const Vector<T>& other) {
if (this->length != other.get_length())
throw std::length_error("Vectors are of different length");
for (int i = 0; i < length; ++i)
mass[i] -= other.mass[i];
return *this;
}
// Умножение вектора на число
Vector<T>& operator*=(const T& value) {
for (int i = 0; i < length; ++i)
mass[i] *= value;
return *this;
}
// Деление вектора на число
Vector<T>& operator/=(const T& value) {
for (int i = 0; i < length; ++i)
mass[i] /= value;
return *this;
}
// Оператор вывода в поток
template <typename _T>
friend std::ostream& operator <<(std::ostream& os, Vector<_T>& lst) {
for (int i = 0; i < lst.get_length(); ++i)
os << lst[i] << std::endl;
return os;
}
template<typename _T>
friend Vector<_T> operator+(const Vector<_T>& v1, const Vector<_T>& v2) {
if (v1.get_length() != v2.get_length())
throw std::length_error("Vectors are of different length");
Vector<_T> result = v1;
result += v2;
return result;
}
template<typename _T>
friend Vector<_T> operator-(const Vector<_T>& v1, const Vector<_T>& v2) {
if (v1.get_length() != v2.get_length())
throw std::length_error("Vectors are of different length");
Vector<_T> result = v1;
result -= v2;
return result;
}
template<typename _T>
friend Vector<_T> operator*(const Vector<_T>& v1, const _T& val) {
Vector<_T> result = v1;
result *= val;
return result;
}
template<typename _T>
friend Vector<_T> operator/(const Vector<_T>& v1, const _T& val) {
Vector<_T> result = v1;
result /= val;
return result;
}
};
| true |
c8dd1d57587cf0a6530e4e48f386a93b05110d28 | C++ | JDCalvert/SpaceRTS | /Engine/Shader.cpp | UTF-8 | 3,645 | 2.90625 | 3 | [] | no_license | #include "Shader.h"
#include "OpenGLContext.h"
#include <fstream>
std::unordered_map<std::string, Shader*> Shader::shaders;
Shader* Shader::getShader(std::string shaderName)
{
return shaders[shaderName];
}
void Shader::initialiseForScreenSize()
{
}
void Shader::initialiseFrame()
{
}
void Shader::bindArrayBufferData(GLuint bufferId, int size, void* dataPointer)
{
glBindBuffer(GL_ARRAY_BUFFER, bufferId);
glBufferData(GL_ARRAY_BUFFER, size, dataPointer, GL_STATIC_DRAW);
}
void Shader::bindElementArrayBufferData(GLuint bufferId, int size, void* dataPointer)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, dataPointer, GL_STATIC_DRAW);
}
void Shader::enableVertexAttribute(GLuint attribId, GLuint bufferId, int attribSize)
{
glEnableVertexAttribArray(attribId);
glBindBuffer(GL_ARRAY_BUFFER, bufferId);
glVertexAttribPointer(attribId, attribSize, GL_FLOAT, GL_FALSE, 0, (void*)0);
}
/**
* Create and link a shader program with various shaders defined in the input
*/
void Shader::loadShaders(ShaderInfo shaders[], int numShaders)
{
//Create the program
programId = glCreateProgram();
//Compile and attach each shader to the program
for (int i = 0; i<numShaders; i++)
{
ShaderInfo shader = shaders[i];
GLenum shaderType = shader.type;
const char* shaderPath = shader.fileName;
//Create the shader
GLuint shaderId = glCreateShader(shaderType);
shader.shaderId = shaderId;
//Compile the shader
std::string shaderCode = readFromFile(shaderPath);
compileAndCheckShader(shaderPath, shaderCode, shaderId);
glAttachShader(programId, shaderId);
}
linkAndCheckProgram(programId);
//Delete the shaders, we don't need them anymore
for (int i = 0; i<numShaders; i++)
{
ShaderInfo shader = shaders[i];
GLuint shaderId = shader.shaderId;
glDeleteShader(shaderId);
}
}
void Shader::compileAndCheckShader(const char* path, std::string &code, GLuint shaderId)
{
GLint result = GL_FALSE;
int infoLogLength;
//Compile the shader
printf("Compiling shader: %s\n", path);
char const* vertexSourcePointer = code.c_str();
glShaderSource(shaderId, 1, &vertexSourcePointer, NULL);
glCompileShader(shaderId);
//Check the shader
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result);
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0)
{
std::vector<char> errorMessage(infoLogLength + 1);
glGetShaderInfoLog(shaderId, infoLogLength, NULL, &errorMessage[0]);
printf("%s\n", &errorMessage[0]);
}
}
void Shader::linkAndCheckProgram(GLuint programId)
{
glLinkProgram(programId);
//Check the program
GLint result = GL_FALSE;
int infoLogLength;
glGetProgramiv(programId, GL_LINK_STATUS, &result);
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0)
{
std::vector<char> programErrorMessage(infoLogLength + 1);
glGetProgramInfoLog(programId, infoLogLength, NULL, &programErrorMessage[0]);
printf("%s\n", &programErrorMessage[0]);
}
}
std::string Shader::readFromFile(const char* path)
{
std::string output;
std::ifstream stream(path, std::ios::in);
if (!stream.is_open())
{
printf("Unable to read %s\n", path);
getchar();
return 0;
}
std::string line = "";
while (std::getline(stream, line))
{
output += "\n" + line;
}
stream.close();
return output;
} | true |
fde83695fa0979ecaaf28cb1d233ad94096df49b | C++ | tojhe/FedTree | /src/FedTree/dataset.cpp | UTF-8 | 25,575 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by liqinbin on 10/14/20.
//
#include "omp.h"
#include "FedTree/dataset.h"
#include "thrust/scan.h"
#include "thrust/execution_policy.h"
#include "FedTree/objective/objective_function.h"
void DataSet::load_group_file(string file_name) {
LOG(INFO) << "loading group info from file \"" << file_name << "\"";
group.clear();
std::ifstream ifs(file_name, std::ifstream::binary);
CHECK(ifs.is_open()) << "ranking objective needs a group file, but file " << file_name << " not found";
int group_size;
while (ifs >> group_size) group.push_back(group_size);
LOG(INFO) << "#groups = " << group.size();
LOG(INFO) << group;
ifs.close();
}
void DataSet::group_label() {
std::map<float_type, int> label_map;
label.clear();
for (int i = 0; i < y.size(); ++i) {
if(label_map.find(y[i]) == label_map.end()) {
label_map[y[i]] = label.size();
label.push_back(y[i]);
}
y[i] = label_map[y[i]];
}
}
/**
* return true if a character is related to digit
*/
inline bool isdigitchars(char c) {
return (c >= '0' && c <= '9') ||
c == '+' || c == '-' ||
c == '.' || c == 'e' ||
c == 'E';
}
/**
* for converting string to T(int or float)
*/
template<typename T1, typename T2>
inline int parse_pair(const char *begin, const char *end, const char **endptr, T1 &v1, T2 &v2) {
const char *p = begin;
// begin of digital string
while (p != end && !isdigitchars(*p)) ++p;
if (p == end) {
*endptr = end;
return 0;
}
const char *q = p;
// end of digital string
while (q != end && isdigitchars(*q)) ++q;
float temp_v = atof(p);
p = q;
while (p != end && isblank(*p)) ++p;
if (p == end || *p != ':') {
*endptr = p;
v1 = temp_v;
return 1;
}
v1 = int(temp_v);
p++;
while (p != end && !isdigitchars(*p)) ++p; // begin of next digital string
q = p;
while (q != end && isdigitchars(*q)) ++q; // end of next digital string
*endptr = q;
v2 = atof(p);
return 2;
}
/**
* skip the comment and blank
*/
template<char kSymbol = '#'>
std::ptrdiff_t ignore_comment_and_blank(char const *beg,
char const *line_end) {
char const *p = beg;
std::ptrdiff_t length = std::distance(beg, line_end);
while (p != line_end) {
if (*p == kSymbol) {
// advance to line end, `ParsePair' will return empty line.
return length;
}
if (!isblank(*p)) {
return std::distance(beg, p); // advance to p
}
p++;
}
// advance to line end, `ParsePair' will return empty line.
return length;
}
char *find_last_line(char *ptr, const char *begin) {
while (ptr != begin && *ptr != '\n' && *ptr != '\r' && *ptr != '\0') --ptr;
return ptr;
}
void line_count(const int nthread, const int buffer_size, vector<int> &line_counts, std::ifstream &ifs) {
char *buffer = (char *) malloc(buffer_size);
line_counts.emplace_back(0);
while (ifs) {
ifs.read(buffer, buffer_size);
char *head = buffer;
size_t size = ifs.gcount();
vector<int> thread_line_counts(nthread);
#pragma omp parallel num_threads(nthread)
{
int tid = omp_get_thread_num(); // thread id
size_t nstep = (size + nthread - 1) / nthread;
size_t step_begin = (std::min)(tid * nstep, size - 1);
size_t step_end = (std::min)((tid + 1) * nstep, size - 1);
// a block is the data partition processed by a thread
// TODO seems no need to do this
char *block_begin = find_last_line((head + step_begin), head) + 1;
char *block_end = find_last_line((head + step_end), block_begin) + 1;
// move stream start position to the end of the last line after an epoch
if (tid == nthread - 1) {
if (ifs.eof()) {
block_end = head + step_end;
} else {
ifs.seekg(-(head + step_end - block_end), std::ios_base::cur);
}
}
char *line_begin = block_begin;
int num_line = 0;
// to the end of the block
while (line_begin != block_end) {
if (*line_begin == '\n')
num_line++;
line_begin++;
}
thread_line_counts[tid] = num_line;
} // end of multiple threads
line_counts.insert(line_counts.end(), thread_line_counts.begin(), thread_line_counts.end());
} // end while
free(buffer);
thrust::inclusive_scan(thrust::host, line_counts.begin(), line_counts.end(), line_counts.begin());
//line_counts[0] = 0;
// LOG(INFO) << "Line offset of each block: "<< line_counts;
}
void DataSet::load_from_file(string file_name, FLParam ¶m) {
LOG(INFO) << "loading LIBSVM dataset from file ## " << file_name << " ##";
std::chrono::high_resolution_clock timer;
auto t_start = timer.now();
// initialize
y.clear();
csr_val.clear();
csr_col_idx.clear();
csr_row_ptr.resize(1, 0);
n_features_ = 0;
// open file stream
std::ifstream ifs(file_name, std::ifstream::binary);
CHECK(ifs.is_open()) << "file ## " << file_name << " ## not found. ";
int buffer_size = 4 << 20;
char *buffer = (char *)malloc(buffer_size);
const int nthread = omp_get_max_threads();
auto find_last_line = [](char *ptr, const char *begin) {
while(ptr != begin && *ptr != '\n' && *ptr != '\r' && *ptr != '\0') --ptr;
return ptr;
};
// read and parse data
while(ifs) {
ifs.read(buffer, buffer_size);
char *head = buffer;
size_t size = ifs.gcount();
// create vectors for each thread
vector<vector<float_type>> y_(nthread);
vector<vector<float_type>> val_(nthread);
vector<vector<int>> col_idx(nthread);
vector<vector<int>> row_len_(nthread);
vector<int> max_feature(nthread, 0);
bool is_zero_base = false;
#pragma omp parallel num_threads(nthread)
{
int tid = omp_get_thread_num(); // thread id
size_t nstep = (size + nthread - 1) / nthread;
size_t step_begin = (std::min)(tid * nstep, size - 1);
size_t step_end = (std::min)((tid + 1) * nstep, size - 1);
// a block is the data partition processed by a thread
char *block_begin = find_last_line((head + step_begin), head);
char *block_end = find_last_line((head + step_end), block_begin);
// move stream start position to the end of the last line after an epoch
if(tid == nthread - 1) {
if(ifs.eof()) {
block_end = head + step_end;
} else {
ifs.seekg(-(head + step_end - block_end), std::ios_base::cur);
}
}
// read instances line by line
char *line_begin = block_begin;
char *line_end = line_begin;
// to the end of the block
while(line_begin != block_end) {
line_end = line_begin + 1;
while(line_end != block_end && *line_end != '\n' && *line_end != '\r' && *line_end != '\0') ++line_end;
const char *p = line_begin;
const char *q = NULL;
row_len_[tid].push_back(0);
float_type label;
float_type temp_;
std::ptrdiff_t advanced = ignore_comment_and_blank(p, line_end);
p += advanced;
int r = parse_pair<float_type, float_type>(p, line_end, &q, label, temp_);
if (r < 1) {
line_begin = line_end;
continue;
}
// parse instance label
y_[tid].push_back(label);
// parse feature id and value
p = q;
while(p != line_end) {
int feature_id;
float_type value;
std::ptrdiff_t advanced = ignore_comment_and_blank(p, line_end);
p += advanced;
int r = parse_pair(p, line_end, &q, feature_id, value);
if(r < 1) {
p = q;
continue;
}
if(r == 2) {
col_idx[tid].push_back(feature_id - 1);
val_[tid].push_back(value);
if(feature_id > max_feature[tid])
max_feature[tid] = feature_id;
row_len_[tid].back()++;
}
p = q;
} // end inner while
line_begin = line_end;
} // end outer while
} // end num_thread
for (int i = 0; i < nthread; i++) {
if (max_feature[i] > n_features_)
n_features_ = max_feature[i];
}
for (int tid = 0; tid < nthread; tid++) {
csr_val.insert(csr_val.end(), val_[tid].begin(), val_[tid].end());
if(is_zero_base){
for (int i = 0; i < col_idx[tid].size(); ++i) {
col_idx[tid][i]++;
}
}
csr_col_idx.insert(csr_col_idx.end(), col_idx[tid].begin(), col_idx[tid].end());
for (int row_len : row_len_[tid]) {
csr_row_ptr.push_back(csr_row_ptr.back() + row_len);
}
}
for (int i = 0; i < nthread; i++) {
this->y.insert(y.end(), y_[i].begin(), y_[i].end());
// this->label.insert(label.end(), y_[i].begin(), y_[i].end());
}
} // end while
ifs.close();
free(buffer);
LOG(INFO) << "#instances = " << this->n_instances() << ", #features = " << this->n_features();
if (ObjectiveFunction::need_load_group_file(param.gbdt_param.objective)) load_group_file(file_name + ".group");
if (ObjectiveFunction::need_group_label(param.gbdt_param.objective) || param.gbdt_param.metric == "error") {
group_label();
is_classification = true;
param.gbdt_param.num_class = label.size();
}
auto t_end = timer.now();
std::chrono::duration<float> used_time = t_end - t_start;
LOG(INFO) << "Load dataset using time: " << used_time.count() << " s";
// // TODO Estimate the required memory
// int nnz = this->csr_val.size();
// double mem_size = (double)nnz / 1024;
// mem_size /= 1024;
// mem_size /= 1024;
// mem_size *= 12;
// if(mem_size > (5 * param.n_device))
// this->use_cpu = true;
}
//void DataSet::load_from_file_dense(string file_name, FLParam ¶m){
//
//}
//void DataSet::load_from_file(const string &file_name, FLParam ¶m) {
// LOG(INFO) << "loading LIBSVM dataset from file \"" << file_name << "\"";
// std::chrono::high_resolution_clock timer;
// auto t_start = timer.now();
//
// y.clear();
// csr_row_ptr.resize(1, 0);
// csr_col_idx.clear();
// csr_val.clear();
// n_features_ = 0;
//
// std::ifstream ifs(file_name, std::ifstream::binary);
// CHECK(ifs.is_open()) << "file " << file_name << " not found";
//
// int buffer_size = 4 << 20;
// char *buffer = (char *) malloc(buffer_size);
// //array may cause stack overflow in windows
// //std::array<char, 4> buffer{};
// const int nthread = omp_get_max_threads();
//
// auto find_last_line = [](char *ptr, const char *begin) {
// while (ptr != begin && *ptr != '\n' && *ptr != '\r' && *ptr != '\0') --ptr;
// return ptr;
// };
//
// while (ifs) {
// ifs.read(buffer, buffer_size);
// char *head = buffer;
// //ifs.read(buffer.data(), buffer.size());
// //char *head = buffer.data();
// size_t size = ifs.gcount();
// vector<vector<float_type>> y_(nthread);
// vector<vector<int>> col_idx_(nthread);
// vector<vector<int>> row_len_(nthread);
// vector<vector<float_type>> val_(nthread);
//
// vector<int> max_feature(nthread, 0);
// bool is_zeor_base = false;
//
//#pragma omp parallel num_threads(nthread)
// {
// //get working area of this thread
// int tid = omp_get_thread_num();
// size_t nstep = (size + nthread - 1) / nthread;
// size_t sbegin = (std::min)(tid * nstep, size - 1);
// size_t send = (std::min)((tid + 1) * nstep, size - 1);
// char *pbegin = find_last_line(head + sbegin, head);
// char *pend = find_last_line(head + send, pbegin);
//
// //move stream start position to the end of last line
// if (tid == nthread - 1) {
// if (ifs.eof())
// pend = head + send;
// else
// ifs.seekg(-(head + send - pend), std::ios_base::cur);
// }
//
// //read instances line by line
// //TODO optimize parse line
// char *lbegin = pbegin;
// char *lend = lbegin;
// while (lend != pend) {
// //get one line
// lend = lbegin + 1;
// while (lend != pend && *lend != '\n' && *lend != '\r' && *lend != '\0') {
// ++lend;
// }
// string line(lbegin, lend);
// if (line != "\n") {
// std::stringstream ss(line);
//
// //read label of an instance
// y_[tid].push_back(0);
// ss >> y_[tid].back();
//
// row_len_[tid].push_back(0);
// string tuple;
// while (ss >> tuple) {
// int i;
// float v;
// CHECK_EQ(sscanf(tuple.c_str(), "%d:%f", &i, &v), 2)
// << "read error, using [index]:[value] format";
////TODO one-based and zero-based
// col_idx_[tid].push_back(i - 1);//one based
// if (i - 1 == -1) {
// is_zeor_base = true;
// }
// CHECK_GE(i - 1, -1) << "dataset format error";
// val_[tid].push_back(v);
// if (i > max_feature[tid]) {
// max_feature[tid] = i;
// }
// row_len_[tid].back()++;
// }
// }
// //read next instance
// lbegin = lend;
//
// }
// }
// for (int i = 0; i < nthread; i++) {
// if (max_feature[i] > n_features_)
// n_features_ = max_feature[i];
// }
// for (int tid = 0; tid < nthread; tid++) {
// csr_val.insert(csr_val.end(), val_[tid].begin(), val_[tid].end());
// if (is_zeor_base) {
// for (int i = 0; i < col_idx_[tid].size(); ++i) {
// col_idx_[tid][i]++;
// }
// }
// csr_col_idx.insert(csr_col_idx.end(), col_idx_[tid].begin(), col_idx_[tid].end());
// for (int row_len : row_len_[tid]) {
// csr_row_ptr.push_back(csr_row_ptr.back() + row_len);
// }
// }
// for (int i = 0; i < nthread; i++) {
// this->y.insert(y.end(), y_[i].begin(), y_[i].end());
// this->label.insert(label.end(), y_[i].begin(), y_[i].end());
// }
// }
// ifs.close();
// free(buffer);
// LOG(INFO) << "#instances = " << this->n_instances() << ", #features = " << this->n_features();
//}
void DataSet::load_csc_from_file(string file_name, FLParam ¶m, const int nfeatures) {
LOG(INFO) << "loading LIBSVM dataset as csc from file ## " << file_name << " ##";
std::chrono::high_resolution_clock timer;
auto t_start = timer.now();
has_csc = true;
vector<vector<float_type>> feature2values(nfeatures);
vector<vector<int>> feature2instances(nfeatures);
// initialize
y.clear();
n_features_ = 0;
// open file stream & get number line of each block
std::ifstream ifs(file_name, std::ifstream::binary);
CHECK(ifs.is_open()) << "file ## " << file_name << " ## not found. ";
const int nthread = omp_get_max_threads();
int buffer_size = (4 << 20);
vector<int> line_counts;
line_count(nthread, buffer_size, line_counts, ifs);
LOG(DEBUG) << line_counts;
// reset the file pointer & begin to read data as CSC
ifs.close();
ifs.open(file_name, std::ifstream::binary);
int block_idx = 0;
char *buffer = (char *) malloc(buffer_size);
while (ifs) {
ifs.read(buffer, buffer_size);
char *head = buffer;
size_t size = ifs.gcount();
vector<vector<float_type>> y_(nthread);
vector<vector<vector<float_type>>> val_(nthread);
vector<vector<vector<int>>> row_id_(nthread);
vector<int> max_feature(nthread, 0);
bool is_zero_base = false;
#pragma omp parallel num_threads(nthread)
{
int tid = omp_get_thread_num(); // thread id
int rid = line_counts[block_idx * nthread + tid]; // line offset in one thread
// LOG(INFO) << rid;
size_t nstep = (size + nthread - 1) / nthread;
size_t step_begin = (std::min)(tid * nstep, size - 1);
size_t step_end = (std::min)((tid + 1) * nstep, size - 1);
// a block is the data partition processed by a thread
char *block_begin = find_last_line((head + step_begin), head);
char *block_end = find_last_line((head + step_end), block_begin);
// move stream start position to the end of the last line after an epoch
if (tid == nthread - 1) {
if (ifs.eof()) {
block_end = head + step_end;
} else {
ifs.seekg(-(head + step_end - block_end), std::ios_base::cur);
}
}
// read instances line by line
char *line_begin = block_begin;
char *line_end = line_begin;
// TODO consider other methods?
val_[tid].resize(nfeatures + 1);
row_id_[tid].resize(nfeatures + 1);
// to the end of the block
while (line_begin != block_end) {
line_end = line_begin + 1;
while (line_end != block_end && *line_end != '\n' && *line_end != '\r' && *line_end != '\0') ++line_end;
const char *p = line_begin;
const char *q = NULL;
// parse instance label
float_type label;
float_type temp_;
std::ptrdiff_t advanced = ignore_comment_and_blank(p, line_end);
p += advanced;
int r = parse_pair<float_type, float_type>(p, line_end, &q, label, temp_);
if (r < 1) {
line_begin = line_end;
continue;
}
y_[tid].push_back(label);
// parse feature id and value
p = q;
while (p != line_end) {
int feature_id;
float_type value;
std::ptrdiff_t advanced = ignore_comment_and_blank(p, line_end);
p += advanced;
int r = parse_pair(p, line_end, &q, feature_id, value);
if (r < 1) {
p = q;
continue;
}
if (r == 2) {
val_[tid][feature_id - 1].push_back(value);
row_id_[tid][feature_id - 1].push_back(rid);
if (feature_id > max_feature[tid])
max_feature[tid] = feature_id;
}
p = q;
} // end while
line_begin = line_end;
rid++;
} // end of while(line_begin != block_end)
} // end of multiple threads
block_idx++;
// merge local thread data
for (int thread_num_feature: max_feature)
if (thread_num_feature > n_features_)
n_features_ = thread_num_feature;
for (int tid = 0; tid < nthread; tid++) {
for (int fid = 0; fid < n_features_; fid++) {
if (val_[tid][fid].size() != 0) {
feature2values[fid].insert(feature2values[fid].end(), val_[tid][fid].begin(), val_[tid][fid].end());
feature2instances[fid].insert(feature2instances[fid].end(), row_id_[tid][fid].begin(),
row_id_[tid][fid].end());
}
}
y.insert(y.end(), y_[tid].begin(), y_[tid].end());
label.insert(label.end(), y_[tid].begin(), y_[tid].end());
}
} // end of while(ifs)
ifs.close();
free(buffer);
// merge again
csc_col_ptr.emplace_back(0);
for (int fid = 0; fid < n_features_; fid++) {
csc_val.insert(csc_val.end(), feature2values[fid].begin(), feature2values[fid].end());
// LOG(INFO) << feature2instances[fid];
csc_row_idx.insert(csc_row_idx.end(), feature2instances[fid].begin(), feature2instances[fid].end());
csc_col_ptr.emplace_back(feature2values[fid].size());
}
LOG(INFO) << "csc_col_ptr: " << csc_col_ptr;
thrust::inclusive_scan(thrust::host, csc_col_ptr.begin(), csc_col_ptr.end(), csc_col_ptr.begin());
auto t_end = timer.now();
std::chrono::duration<float> used_time = t_end - t_start;
LOG(INFO) << "Load dataset using time: " << used_time.count() << " s";
LOG(INFO) << "csc_col_ptr: " << csc_col_ptr;
LOG(INFO) << "#features: " << n_features_;
}
//void DataSet::csr_to_csc() {
// has_csc = true;
// const int nnz = csr_row_ptr[n_instances()];
//
// //compute number of non-zero entries per column of A
// std::fill(csc_col_ptr.begin(), csc_col_ptr.begin() + n_features(), 0);
//
// for (int n = 0; n < nnz; n++) {
// csc_col_ptr[csr_col_idx[n]]++;
// }
//
// //cumsum the nnz per column to get csc_col_ptr[]
// for (int col = 0, cumsum = 0; col < n_features(); col++) {
// int temp = csc_col_ptr[col];
// csc_col_ptr[col] = cumsum;
// cumsum += temp;
// }
// csc_col_ptr[n_features()] = nnz;
//
// for (int row = 0; row < n_features(); row++) {
// for (int jj = csr_row_ptr[row]; jj < csr_row_ptr[row + 1]; jj++) {
// int col = csr_col_idx[jj];
// int dest = csc_col_ptr[col];
//
// csc_row_idx[dest] = row;
// csc_val[dest] = csr_val[jj];
//
// csc_col_ptr[col]++;
// }
// }
//
// for (int col = 0, last = 0; col <= n_features(); col++) {
// int temp = csc_col_ptr[col];
// csc_col_ptr[col] = last;
// last = temp;
// }
//}
void DataSet::csr_to_csc(){
// LOG(INFO) << "convert csr to csc using cpu...";
//cpu transpose
int n_column = this->n_features();
int n_row = this->n_instances();
int nnz = this->csr_val.size();
// LOG(INFO) << n_column << "," << n_row << "," << nnz;
csc_val.resize(nnz);
csc_row_idx.resize(nnz);
csc_col_ptr.resize(n_column+1);
// LOG(INFO) << string_format("#non-zeros = %ld, density = %.2f%%", nnz,
// (float) nnz / n_column / n_row * 100);
for (int i = 0; i <= n_column; ++i) {
csc_col_ptr[i] = 0;
}
#pragma omp parallel for // about 5s
for (int i = 0; i < nnz; ++i) {
int idx = csr_col_idx[i] + 1;
#pragma omp atomic
csc_col_ptr[idx] += 1;
}
for (int i = 1; i < n_column + 1; ++i){
csc_col_ptr[i] += csc_col_ptr[i - 1];
}
// TODO to parallelize here
for (int row = 0; row < csr_row_ptr.size() - 1; ++row) {
for (int j = csr_row_ptr[row]; j < csr_row_ptr[row + 1]; ++j) {
int col = csr_col_idx[j]; // csr col
int dest = csc_col_ptr[col]; // destination index in csc array
csc_val[dest] = csr_val[j];
csc_row_idx[dest] = row;
csc_col_ptr[col] += 1; //increment sscolumn start position
}
}
//recover column start position
for (int i = 0, last = 0; i < n_column; ++i) {
int next_last = csc_col_ptr[i];
csc_col_ptr[i] = last;
last = next_last;
}
has_csc = true;
}
size_t DataSet::n_features() const {
return n_features_;
}
size_t DataSet::n_instances() const {
return this->y.size();
}
void DataSet::load_from_files(vector<string> file_names, FLParam ¶m) {
int prev_csr_row_ptr = 0;
for(auto name: file_names) {
DataSet next;
next.load_from_file(name, param);
csr_val.insert(csr_val.end(), next.csr_val.begin(), next.csr_val.end());
csr_col_idx.insert(csr_col_idx.end(), next.csr_col_idx.begin(), next.csr_col_idx.end());
label.insert(label.end(), next.label.begin(), next.label.end());
y.insert(y.end(), next.y.begin(), next.y.end());
for (int row_len: next.csr_row_ptr) {
csr_row_ptr.push_back(prev_csr_row_ptr + row_len);
}
prev_csr_row_ptr += next.n_instances();
}
}
| true |
cfc814c2b67d34048ba274b1e7e66d1f1becb8d9 | C++ | Firas-al/1dv534-C-plusplus | /Step4/Plant.h | ISO-8859-1 | 2,219 | 3.09375 | 3 | [] | no_license | /******************************************************
* File: Plant.h
* Description: This is the header for the plant item.
*
* Version: 1.0 2020-08-16, Linnuniversitetet
* Author: Vilhelm Park, Linnuniversitetet
******************************************************
* Update Log
* ----------
* 2020-08-16 Finalize comments Vilhelm Park
*
******************************************************/
#ifndef PLANT_H
#define PLANT_H
#include "BasicItem.h"
#include "View.h"
#include <string>
using std::string;
class Plant : public BasicItem
{
public:
Plant() = default;
virtual ~Plant() {}
void show() override;
const string toString() const override;
int getItemType() const { return _itemType; }
string getTitle() const override { return _title; }
void setTitle(string title) override { _title = title; }
void createItem() override;
void updateInformation() override;
void loadInformation(string values[]) override;
string getLatinTitle() { return _latinTitle; }
string getNote() { return _note; }
void setLatinTitle(string latinTitle) { _latinTitle = latinTitle; }
void setNote(string note) { _note = note; }
private:
item _itemType = plant;
string _title;
string _latinTitle;
string _note;
};
class PlantLatinTitleComparator
{
public:
bool operator()(BasicItem *a, BasicItem *b)
{
View view;
Plant *a_plant = dynamic_cast<Plant*>(a);
Plant *b_plant = dynamic_cast<Plant*>(b);
if (a_plant != nullptr && b_plant != nullptr) {
return a_plant->getLatinTitle().compare(b_plant->getLatinTitle());
}
else
{
view.printError("Could not cast the basic items into plant. Exiting!");
exit(EXIT_FAILURE);
}
}
};
class PlantNoteComparator
{
public:
bool operator()(BasicItem *a, BasicItem *b)
{
View view;
Plant *a_plant = dynamic_cast<Plant*>(a);
Plant *b_plant = dynamic_cast<Plant*>(b);
if (a_plant != nullptr && b_plant != nullptr) {
return a_plant->getNote().compare(b_plant->getNote());
}
else
{
view.printError("Could not cast the basic items into plant. Exiting!");
exit(EXIT_FAILURE);
}
}
};
#endif | true |
8e818de06af44227fe972c958a4fba0f374a9019 | C++ | lasttruffulaseed/general-cs-fun | /MonopolySimulator-group/CardSpace.cpp | UTF-8 | 919 | 3.015625 | 3 | [] | no_license | /*
* CardSpace.cpp
*
* benjamin.dasari
* patrick.haren
* rebaz.maroof
*
* Implementation for the board spaces representing Cardspace
*
*/
#include "CardSpace.h"
#include "Space.h"
REGISTER_CLASS(Space, CardSpace);
CardSpace::CardSpace()
{
cardType = Card::chanceDeck;
}
CardSpace::~CardSpace()
{
}
void CardSpace::setType(Card::CardTypeEnum type) {
cardType = type;
}
bool CardSpace::isChanceDeck() {
return (cardType == Card::chanceDeck);
}
bool CardSpace::isCommunityDeck() {
return (cardType == Card::communityDeck);
}
void CardSpace::configure(vector<string>& params)
{
Space::configure(params);
cardType = getName().compare("Chance")==0 ? Card::chanceDeck : Card::communityDeck;
}
void CardSpace::info()
{
Space::info();
cout << "This is a " << ((cardType == Card::chanceDeck) ? "Chance" : "Community Chest") << " card space " << endl;
}
| true |
cc1827f499e489b01dd653de208a2e0bb948a73c | C++ | 218502/PAMSI | /stosListaKolejka/stos.hh | UTF-8 | 363 | 2.75 | 3 | [] | no_license | #ifndef stos_hh
#define stos_hh
#include "lista.hh"
class InterfaceStos
{
public:
virtual void push(int element)=0;
virtual int pop()=0;
virtual int size()=0;
};
class Stos : public InterfaceStos
{
int Size;
List list;
int temp;//zmienna do przechowywania zdejmowanego elementu
public:
void push(int element);
int pop();
int size();
};
#endif
| true |
119374f92e147187709a7a902836e97e152a13b3 | C++ | BellisL/CodingInterviews | /LeastSteps2One/main.cpp | UTF-8 | 1,651 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
int leastSteps2One_1(int vNum);
int leastSteps2One_2(int vNum);
void leastStepsCore(int vNum, int vTimes, int& vMin);
void test(const char* vpTestName, int vNum, int vExpect);
int main()
{
test("Test1", 0, 0);
test("Test2", 1, 1);
test("Test3", 2, 2);
test("Test4", 3, 2);
test("Test5", 4, 3);
test("Test6", 5, 4);
test("Test7", 6, 3);
test("Test8", 7, 4);
test("Test9", 8, 4);
test("Test10", 9, 3);
test("Test11", 10, 4);
return 0;
}
int leastSteps2One_1(int vNum)
{
if (vNum < 1) return 0;
int Min = INT_MAX;
leastStepsCore(vNum, 0, Min);
return Min;
}
int leastSteps2One_2(int vNum)
{
if (vNum < 1) return 0;
std::vector<int> Set(vNum + 1, 0);
Set[1] = 1;
for (int i = 2; i <= vNum; ++i)
{
Set[i] = 1 + Set[i - 1];
if (i % 3 == 0)
Set[i] = std::min(Set[i / 3] + 1, Set[i]);
if (i % 2 == 0)
Set[i] = std::min(Set[i / 2] + 1, Set[i]);
}
return Set[vNum];
}
void leastStepsCore(int vNum, int vTimes, int& vMin)
{
if (vNum == 0)
{
if (vTimes < vMin)
vMin = vTimes;
return;
}
if (vTimes < vMin && vNum % 3 == 0)
leastStepsCore(vNum / 3, vTimes + 1, vMin);
if (vTimes < vMin && vNum % 2 == 0)
leastStepsCore(vNum / 2, vTimes + 1, vMin);
if (vTimes < vMin && vNum > 0)
leastStepsCore(vNum - 1, vTimes + 1, vMin);
}
void test(const char* vpTestName, int vNum, int vExpect)
{
std::cout << vpTestName << std::endl;
auto Steps_1 = leastSteps2One_1(vNum);
auto Steps_2 = leastSteps2One_2(vNum);
if (Steps_1 == vExpect && Steps_2 == vExpect)
std::cout << "PASSED.\n";
else
std::cout << "FAILED.\n";
std::cout << std::endl;
} | true |
35cd586ae26e904c427adda8db6a4de0ebcf2d90 | C++ | rrao002c/pxCore | /examples/KeyboardAndMouse/KeyboardAndMouse.cpp | UTF-8 | 8,089 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | // Keyboard and Mouse Example CopyRight 2007-2009 John Robinson
// Demonstrates how to handle keyboard and mouse events
#include "pxCore.h"
#include "pxEventLoop.h"
#include "pxWindow.h"
#include "pxOffscreen.h"
#include <stdio.h> // for printf
pxEventLoop eventLoop;
void drawBackground(pxBuffer& b)
{
// Fill the buffer with a simple pattern as a function of f(x,y)
int w = b.width();
int h = b.height();
for (int y = 0; y < h; y++)
{
pxPixel* p = b.scanline(y);
for (int x = 0; x < w; x++)
{
p->r = pxClamp<int>(x+y, 255);
p->g = pxClamp<int>(y, 255);
p->b = pxClamp<int>(x, 255);
p++;
}
}
}
class myWindow: public pxWindow
{
private:
// Event Handlers - Look in pxWindow.h for more
void onCloseRequest()
{
// When someone clicks the close box no policy is predefined.
// so we need to explicitly tell the event loop to exit
eventLoop.exit();
}
void onSize(int newWidth, int newHeight)
{
// When ever the window resizes (re)allocate a buffer
// big enough for the entire
// client area and draw our pattern into it
mTexture.init(newWidth, newHeight);
drawBackground(mTexture);
}
void onDraw(pxSurfaceNative s)
{
// Draw the texture into this window
mTexture.blit(s);
}
void onMouseDown(int x, int y, unsigned long flags)
{
printf("Mouse Down (%d %d) modifiers: [", x, y);
if (flags & PX_LEFTBUTTON) printf("Left ");
if (flags & PX_MIDDLEBUTTON) printf("Middle ");
if (flags & PX_RIGHTBUTTON) printf("Right ");
if (flags & PX_MOD_SHIFT) printf("Shift ");
if (flags & PX_MOD_CONTROL) printf("Control ");
if (flags & PX_MOD_ALT) printf("Alt ");
printf("]\n");
}
void onMouseUp(int x, int y, unsigned long flags)
{
printf("Mouse Up (%d, %d) modifiers: [ ", x, y);
if (flags & PX_LEFTBUTTON) printf("Left ");
if (flags & PX_MIDDLEBUTTON) printf("Middle ");
if (flags & PX_RIGHTBUTTON) printf("Right ");
if (flags & PX_MOD_SHIFT) printf("Shift ");
if (flags & PX_MOD_CONTROL) printf("Control ");
if (flags & PX_MOD_ALT) printf("Alt ");
printf("]\n");
}
void onMouseMove(int x, int y)
{
printf("Mouse Move %d, %d\n", x, y);
}
void onKeyDown(int c, unsigned long flags)
{
printf("Key Dn \"%s\" modifiers: [", getKeyDescription(c));
if (flags & PX_MOD_SHIFT) printf("Shift ");
if (flags & PX_MOD_CONTROL) printf("Control ");
if (flags & PX_MOD_ALT) printf("Alt ");
printf("]");
printf(" Keycode: 0x%x", c);
printf("\n");
}
void onKeyUp(int c, unsigned long flags)
{
printf("Key Up \"%s\" modifiers: [", getKeyDescription(c));
if (flags & PX_MOD_SHIFT) printf("Shift ");
if (flags & PX_MOD_CONTROL) printf("Control ");
if (flags & PX_MOD_ALT) printf("Alt ");
printf("]");
printf(" Keycode: 0x%x", c);
printf("\n");
}
const char * getKeyDescription( int keycode )
{
switch (keycode)
{
#if 1
case PX_KEY_PAUSE: return "Pause";
case PX_KEY_ENTER: return "Enter";
case PX_KEY_BACKSPACE: return "BackSpace";
case PX_KEY_TAB: return "Tab";
case PX_KEY_SHIFT: return "Shift";
case PX_KEY_CONTROL: return "Control";
case PX_KEY_ALT: return "Alt";
case PX_KEY_CAPSLOCK: return "CapsLock";
case PX_KEY_ESCAPE: return "Escape";
case PX_KEY_SPACE: return "Space";
case PX_KEY_PAGEUP: return "PageUp";
case PX_KEY_PAGEDOWN: return "PageDown";
case PX_KEY_END: return "End";
case PX_KEY_HOME: return "Home";
case PX_KEY_LEFT: return "Left";
case PX_KEY_UP: return "Up";
case PX_KEY_RIGHT: return "Right";
case PX_KEY_DOWN: return "Down";
case PX_KEY_COMMA: return "Comma";
case PX_KEY_PERIOD: return "Period";
case PX_KEY_SLASH: return "Slash";
case PX_KEY_ZERO: return "Zero";
case PX_KEY_ONE: return "One";
case PX_KEY_TWO: return "Two";
case PX_KEY_THREE: return "Three";
case PX_KEY_FOUR: return "Four";
case PX_KEY_FIVE: return "Five";
case PX_KEY_SIX: return "Six";
case PX_KEY_SEVEN: return "Seven";
case PX_KEY_EIGHT: return "Eight";
case PX_KEY_NINE: return "Nine";
case PX_KEY_SEMICOLON: return "SemiColon";
case PX_KEY_EQUALS: return "Equals";
case PX_KEY_A: return "A";
case PX_KEY_B: return "B";
case PX_KEY_C: return "C";
case PX_KEY_D: return "D";
case PX_KEY_E: return "E";
case PX_KEY_F: return "F";
case PX_KEY_G: return "G";
case PX_KEY_H: return "H";
case PX_KEY_I: return "I";
case PX_KEY_J: return "J";
case PX_KEY_K: return "K";
case PX_KEY_L: return "L";
case PX_KEY_M: return "M";
case PX_KEY_N: return "N";
case PX_KEY_O: return "O";
case PX_KEY_P: return "P";
case PX_KEY_Q: return "Q";
case PX_KEY_R: return "R";
case PX_KEY_S: return "S";
case PX_KEY_T: return "T";
case PX_KEY_U: return "U";
case PX_KEY_V: return "V";
case PX_KEY_W: return "W";
case PX_KEY_X: return "X";
case PX_KEY_Y: return "Y";
case PX_KEY_Z: return "Z";
case PX_KEY_OPENBRACKET: return "OpenBracket";
case PX_KEY_BACKSLASH: return "BackSlash";
case PX_KEY_CLOSEBRACKET: return "CloseBracket";
case PX_KEY_NUMPAD0: return "NumPad0";
case PX_KEY_NUMPAD1: return "NumPad1";
case PX_KEY_NUMPAD2: return "NumPad2";
case PX_KEY_NUMPAD3: return "NumPad3";
case PX_KEY_NUMPAD4: return "NumPad4";
case PX_KEY_NUMPAD5: return "NumPad5";
case PX_KEY_NUMPAD6: return "NumPad6";
case PX_KEY_NUMPAD7: return "NumPad7";
case PX_KEY_NUMPAD8: return "NumPad8";
case PX_KEY_NUMPAD9: return "NumPad9";
case PX_KEY_SEPARATOR: return "Separator";
case PX_KEY_ADD: return "Add";
case PX_KEY_SUBTRACT: return "Subtract";
case PX_KEY_DECIMAL: return "Decimal";
case PX_KEY_DIVIDE: return "Divide";
case PX_KEY_MULTIPLY: return "Multiply";
case PX_KEY_F1: return "F1";
case PX_KEY_F2: return "F2";
case PX_KEY_F3: return "F3";
case PX_KEY_F4: return "F4";
case PX_KEY_F5: return "F5";
case PX_KEY_F6: return "F6";
case PX_KEY_F7: return "F7";
case PX_KEY_F8: return "F8";
case PX_KEY_F9: return "F9";
case PX_KEY_F10: return "F10";
case PX_KEY_F11: return "F11";
case PX_KEY_F12: return "F12";
case PX_KEY_DELETE: return "Delete";
case PX_KEY_NUMLOCK: return "NumLock";
case PX_KEY_SCROLLLOCK: return "ScrollLock";
case PX_KEY_PRINTSCREEN: return "PrintScreen";
case PX_KEY_INSERT: return "Insert";
case PX_KEY_BACKQUOTE: return "BackQuote";
case PX_KEY_QUOTE: return "Quote";
#endif
default: return "Undefined";
}
}
pxOffscreen mTexture;
};
int pxMain()
{
myWindow win;
win.init(10, 64, 300, 240);
win.setTitle("Keyboard And Mouse");
win.setVisibility(true);
eventLoop.run();
return 0;
}
| true |
eb952a52f72d5eb6ae01a9e47d2e2bfc97a527e6 | C++ | harshraj22/problem_solving | /solution/binarysearch/Shipping and Receiving.cpp | UTF-8 | 969 | 2.921875 | 3 | [] | no_license | // https://binarysearch.com/problems/Shipping-and-Receiving
#define all(x) x.begin(), x.end()
int solve(vector<vector<int>>& ports, vector<vector<int>>& shipments) {
const int inf = 1e7;
int n = ports.size();
vector<vector<int>> dist(n, vector<int>(n, inf));
// initialize the dist
for (int i = 0; i < n; i += 1) {
int u = i;
for (auto v: ports[u])
dist[u][v] = 1;
dist[u][u] = 0;
}
// apply floyd warshall
for (int k = 0; k < n; k += 1) {
for (int u = 0; u < n; u += 1) {
for (int v = 0; v < n; v += 1) {
if (dist[u][v] > dist[u][k] + dist[k][v])
dist[u][v] = dist[u][k] + dist[k][v];
}
}
}
// return the cost
int total_cost = 0;
for (auto edge: shipments) {
int u = edge[0], v = edge[1];
if (dist[u][v] < inf)
total_cost += dist[u][v];
}
return total_cost;
} | true |
d8cf37f1e06343df2b7530564d818f4b5c0c7f9f | C++ | mmz-zmm/MyCppPrimer | /12_15.cpp | UTF-8 | 964 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <memory>
#include <string>
using namespace std;
struct destination
{
string ip;
string port;
destination(string ip_, string port_):ip(ip_),port(port_){}
};
struct connection
{
string ip;
string port;
connection(string ip_, string port_):ip(ip_),port(port_){}
};
connection connect(destination *pDest)
{
shared_ptr<connection> pCon(new connection(pDest->ip, pDest->port));
cout << "creating connection(" << pCon->ip<<":"<<pCon->port<<")" << endl;
return *pCon;
}
void disconnect(connection Con)
{
cout << "connection close(" << Con.ip << ":" << Con.port << ")" << endl;
}
void f(destination &d)
{
connection c = connect(&d);
shared_ptr<connection> p(&c, [](connection*p) { disconnect(*p); });
cout << "connecting now(" << p.use_count() << ")" << endl;
}
int main()
{
destination dest("192.168.32.3", "8080");
f(dest);
return 0;
} | true |
d8f89177a018e8b4a8ef42a408a7fe68ba69c4d1 | C++ | tanmaypanigrahi/tanmay | /stack Using queue.cpp | UTF-8 | 1,604 | 3.734375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class node
{
public:
//data
int data;
//pointer to next node
node * next;
//constructor to make next pointer to null
Node(int value)
{
next=NULL;
value=data;
}
};
class queue
{
public:
node * front;
node * end;
queue()
{
front=NULL;
end=NULL;
}
void enqueue(int value)
{
node * temp= new node();
temp->data=value;
if(front==NULL)
{
front=temp;
end=temp;
}
else
{
end->next=temp;
end=temp;
}
}
int dequeue()
{
int dqdval=0;
node * temp=end;
node * current=front;
while(current->next!=end)
{
current=current->next;
}
current->next=NULL;
end=current;
dqdval=temp->data;
delete temp;
}
bool isempty()
{
if(front==NULL)
return true;
else
return false;
}
int size()
{
int i=1;
node * current=front;
while(current->next!=NULL)
{
i++;
current=current->next;
}
return i;
}
void display()
{
node * current=front;
while(current!=NULL)
{
cout<<current->data<<"->";
current=current->next;
}
cout<<endl;
}
};
class suq
{
public:
queue q1;
void push(int val)
{
q1.enqueue(val);
}
void pop()
{
q1.dequeue();
}
void size()
{
cout<<"size of your stack="<<q1.size()<<endl;
}
bool isEmpty()
{
q1.isempty();
}
void display()
{
q1.display();
}
};
int main()
{
suq q1;
int i=0;
for(i=0;i<5;i++)
q1.push(i);
q1.display();
q1.size();
q1.isEmpty();
for(i=0;i<2;i++)
q1.pop();
q1.display();
q1.size();
}
| true |
ab54719b09252e4b0ee1c63232ac50bfba53252c | C++ | azxca1731/nogada-algorithm | /0. 입출력/11718/main.cpp | UTF-8 | 169 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
using namespace std;
int main()
{
string buffer;
while (getline(cin, buffer))
{
cout << buffer << endl;
}
} | true |
d60b54c0e07b3975fc910f6a73ec74d7a0537f0d | C++ | smith1302/2D-Tank-Game | /Shot.h | UTF-8 | 228 | 2.5625 | 3 | [] | no_license | #pragma once
class Shot
{
public:
int x, y, velocity, angle, power, direction;
int getYForX(int x, double gravity);
int getDirection();
Shot(int x, int y, int velocity, int angle, int power);
Shot(void);
~Shot(void);
};
| true |
33b177a155dbf6b72fc7d917386a129141875434 | C++ | roq-trading/roq-api | /include/roq/cache/reference_data.hpp | UTF-8 | 4,948 | 2.59375 | 3 | [
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"Apache-2.0"
] | permissive | /* Copyright (c) 2017-2023, Hans Erik Thrane */
#pragma once
#include <chrono>
#include "roq/api.hpp"
#include "roq/utils/update.hpp"
namespace roq {
namespace cache {
struct ReferenceData final {
ReferenceData() = default;
ReferenceData(ReferenceData const &) = delete;
ReferenceData(ReferenceData &&) = default;
void clear() {
stream_id = {};
description.clear();
security_type = {};
base_currency.clear();
quote_currency.clear();
margin_currency.clear();
commission_currency.clear();
tick_size = NaN;
multiplier = NaN;
min_notional = NaN;
min_trade_vol = NaN;
max_trade_vol = NaN;
trade_vol_step_size = NaN;
option_type = {};
strike_currency.clear();
strike_price = NaN;
underlying.clear();
time_zone.clear();
issue_date = {};
settlement_date = {};
expiry_datetime = {};
expiry_datetime_utc = {};
discard = {};
}
[[nodiscard]] bool operator()(roq::ReferenceData const &reference_data) {
auto dirty = false;
dirty |= utils::update(stream_id, reference_data.stream_id);
dirty |= utils::update_if_not_empty(description, reference_data.description);
dirty |= utils::update_if_not_empty(security_type, reference_data.security_type);
dirty |= utils::update_if_not_empty(base_currency, reference_data.base_currency);
dirty |= utils::update_if_not_empty(quote_currency, reference_data.quote_currency);
dirty |= utils::update_if_not_empty(margin_currency, reference_data.margin_currency);
dirty |= utils::update_if_not_empty(commission_currency, reference_data.commission_currency);
dirty |= utils::update_if_not_empty(tick_size, reference_data.tick_size);
dirty |= utils::update_if_not_empty(multiplier, reference_data.multiplier);
dirty |= utils::update_if_not_empty(min_notional, reference_data.min_notional);
dirty |= utils::update_if_not_empty(min_trade_vol, reference_data.min_trade_vol);
dirty |= utils::update_if_not_empty(max_trade_vol, reference_data.max_trade_vol);
dirty |= utils::update_if_not_empty(trade_vol_step_size, reference_data.trade_vol_step_size);
dirty |= utils::update_if_not_empty(option_type, reference_data.option_type);
dirty |= utils::update_if_not_empty(strike_currency, reference_data.strike_currency);
dirty |= utils::update_if_not_empty(strike_price, reference_data.strike_price);
dirty |= utils::update_if_not_empty(underlying, reference_data.underlying);
dirty |= utils::update_if_not_empty(time_zone, reference_data.time_zone);
dirty |= utils::update_if_not_empty(issue_date, reference_data.issue_date);
dirty |= utils::update_if_not_empty(settlement_date, reference_data.settlement_date);
dirty |= utils::update_if_not_empty(expiry_datetime, reference_data.expiry_datetime);
dirty |= utils::update_if_not_empty(expiry_datetime_utc, reference_data.expiry_datetime_utc);
dirty |= utils::update(discard, reference_data.discard);
return dirty;
}
[[nodiscard]] bool operator()(Event<roq::ReferenceData> const &event) { return (*this)(event.value); }
template <typename Context>
[[nodiscard]] roq::ReferenceData convert(Context const &context) const {
return {
.stream_id = stream_id,
.exchange = context.exchange,
.symbol = context.symbol,
.description = description,
.security_type = security_type,
.base_currency = base_currency,
.quote_currency = quote_currency,
.margin_currency = margin_currency,
.commission_currency = commission_currency,
.tick_size = tick_size,
.multiplier = multiplier,
.min_notional = min_notional,
.min_trade_vol = min_trade_vol,
.max_trade_vol = max_trade_vol,
.trade_vol_step_size = trade_vol_step_size,
.option_type = option_type,
.strike_currency = strike_currency,
.strike_price = strike_price,
.underlying = underlying,
.time_zone = time_zone,
.issue_date = issue_date,
.settlement_date = settlement_date,
.expiry_datetime = expiry_datetime,
.expiry_datetime_utc = expiry_datetime_utc,
.discard = discard,
};
}
uint16_t stream_id = {};
Description description;
SecurityType security_type = {};
Currency base_currency;
Currency quote_currency;
Currency margin_currency;
Currency commission_currency;
double tick_size = NaN;
double multiplier = NaN;
double min_notional = NaN;
double min_trade_vol = NaN;
double max_trade_vol = NaN;
double trade_vol_step_size = NaN;
OptionType option_type = {};
Currency strike_currency;
double strike_price = NaN;
Symbol underlying;
TimeZone time_zone;
std::chrono::days issue_date = {};
std::chrono::days settlement_date = {};
std::chrono::seconds expiry_datetime = {};
std::chrono::seconds expiry_datetime_utc = {};
bool discard = {};
};
} // namespace cache
} // namespace roq
| true |
13e7155078b16c265ed18205ef2acda96777f794 | C++ | ihalton/CUED-Self-Balancing-Bike | /Big Bike/Arduino/BikeFirmware/IMU.h | UTF-8 | 2,416 | 2.640625 | 3 | [] | no_license | #ifndef IMU_H
#define IMU_H
#include <Wire.h>
#include <Arduino.h>
class IMU {
private:
void imuReadRaw(float *leanAcc, float *gx){
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
float ax = (float) AcX / 16384.0;
float ay = (float) AcY / 16384.0;
float az = (float) AcZ / 16384.0;
*gx = (float) -GyX / 131.0;
*leanAcc = -atan2(ay, sqrt(ax * ax + az * az)) * 180 / PI;
}
const int MPU_addr = 0x68;
public:
float bias = 4.4;
float alpha = 0.05;
float lpfAlpha = 0.5;
void init() {
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
}
float getLean(float dt) {
static float leanEstimate = 0.0;
static float gxlpf = 0.0;
static float acclpf = 0.0;
float leanAcc, gx;
imuReadRaw(&leanAcc, &gx);
gx = (gx - bias);
gxlpf = lpfAlpha * gxlpf + (1 - lpfAlpha) * gx;
acclpf = lpfAlpha * acclpf + (1 - lpfAlpha) * leanAcc;
leanEstimate = alpha * leanAcc + (1 - alpha) * (leanEstimate + gxlpf * dt);
return leanEstimate;
}
void Calibrate(uint8_t iterations) {
float tempLean;
float tempGx;
float tempBias = 0.0;
for (uint8_t n = 0; n < iterations; n++) {
imuReadRaw(&tempLean, &tempGx);
tempBias += tempGx;
delay(10);
}
bias = tempBias / (float) iterations;
}
};
#endif
| true |
24d2742836750ba4335fd1a984809525141a936e | C++ | dreamerweee/Algorithm | /LeetCode/MajorityElement.cpp | UTF-8 | 920 | 4.25 | 4 | [] | no_license | /*
** 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
*/
int MajorityElement(vector<int> &nums)
{
unordered_map<int, int> value_map;
for (auto e : nums) {
++value_map[e];
}
int cur_times = 0;
int ret_val = 0;
for (auto beg = value_map.cbegin(); beg != value_map.cend(); ++beg) {
if (beg->second > cur_times) {
cur_times = beg->second;
ret_val = beg->first;
}
}
return ret_val;
}
/*
** Boyer-Moore算法
** 如果把众数记为+1,把其他数记为-1,将它们全部加起来,显然和大于0,从结果本身可以看出众数比其他数多
*/
int MajorityElement(vector<int> &nums)
{
int cnt = 0;
int maj_val;
for (int e : nums) {
if (cnt == 0) {
maj_val = e;
++cnt;
} else if (e == maj_val) {
++cnt;
} else {
--cnt;
}
}
return maj_val;
} | true |
e24ebb033e1f77294a91ebaebdbd6272a0b45f54 | C++ | missingXiong/leetcode | /Amazon/1167. Minimum Cost to Connect Sticks.cpp | UTF-8 | 275 | 2.953125 | 3 | [] | no_license |
int connectSticks(vector<int>& sticks)
{
int ans = 0;
priority_queue<int, vector<int>, greater<int>> pq(sticks.begin(), sticks.end());
while(pq.size() > 1)
{
int p = pq.top(); pq.pop();
int q = pq.top(); pq.pop();
pq.push(p + q);
ans += p + q;
}
return ans;
} | true |
388126e680695dd5c7e4653811738fda06703857 | C++ | jlopez2022/cpp_utils | /inversa1.cpp | MacCentralEurope | 2,624 | 3.4375 | 3 | [] | no_license | //Funciona fenmeno!!!
//Devuelve un valor < dimension si hay una fila que es
//multiplo de las otras. El valor devuelto es la fila correspondiente
#include <stdio.h>
#include <time.h>
class matrizc
{
public:
int inversa(double *x,double *y);
void imprimematriz(double *x,char s[256]="");
matrizc(int dim);
int dimension;
};
matrizc::matrizc(int dim)
{
dimension=dim;
}
int matrizc::inversa(double *x,double *y)
{
int i,j,ord;
double *ptrx,*ptrx0,*ptry,*ptry0,*ptrx00,*ptry00,x0;
for (ord=0;ord<dimension;ord++)
{
//Hacemos elemento diagonal=1
ptrx0=x+ord*dimension+ord;
ptry=y+ord*dimension;
if (!*ptrx0) return ord;
for (i=0;i<ord;i++)
*ptry++/=*ptrx0; //y(ord,i<ord)=y/x(ord,ord)
*ptry=1./ *ptrx0; //y(ord,ord) =1/x(ord,ord)
ptrx=ptrx0+1;
for (i=ord+1;i<dimension;i++)
*ptrx++ /= *ptrx0; //x(ord,i>ord)=x/x(ord,ord)
//Hacemos toda la columna "ord" =0 salvo el valor en (ord,ord)
ptry00=y+dimension*ord;
ptrx00=x+dimension*ord+ord+1;
for (j=0;j<dimension;j++) //todas las filas
if (j!=ord) //salvo la ord
{
ptrx=x+j*dimension+ord;x0=*ptrx;
ptry=y+j*dimension;ptry0=ptry00;
for (i=0;i<ord;i++) //columnas Y desde 0 a ord
*ptry=(*ptry++)-(*ptry0++)*x0;
*ptry=-(*ptry0++)*x0;//columna Y ord;
ptrx++;ptrx0=ptrx00;
for (i=ord+1;i<dimension;i++) //columnas x desde ord a dim
*ptrx=(*ptrx++)-(*ptrx0++)*x0;
}
//imprimematriz(x,dim);
//imprimematriz(y,dim);
}//end ord
return dimension;
}
void matrizc::imprimematriz(double *x,char s[256])
{
int i,j;
printf("matriz:%s\n",s);
for (i=0;i<dimension;i++)
{
for (j=0;j<dimension;j++)
printf(" %12g",x[i*dimension+j]);
printf("\n");
}
}
void main()
{
// double x[4]={1.,2.,2.,3.};
double x[25]={
2., -5., -3., 2., 12.,
-6., 4., -2., 1., 13.,
1., 3., 6., 4., 5.,
-7., 5., 4., 8., -9.,
1., 6., 9., 2., 13.};
char c;
int i;
int dimension=5;
double *y=new double[dimension*dimension];
matrizc matriz1(dimension);
matriz1.imprimematriz(&x[0]," input");
time_t antes,despues;
time(&antes);
int j;
for (j=0;j<250000;j++)
i=matriz1.inversa(&x[0],&y[0]);
time(&despues);
if (i<dimension) printf("\nAtencion, la fila %i es multiplo de las anteriores",i);
matriz1.imprimematriz(&y[0]," output");
printf("\nTiempo=%ld",despues-antes);
scanf("%c%c",&c,&c);
}
| true |
ea41a3687bdfad85ae99bdc07303511f8a1f2a38 | C++ | VaibhavSaraf/clean-strike-sahaj | /run.cpp | UTF-8 | 4,479 | 3.265625 | 3 | [] | no_license | // Clean Strike Game
#include <iostream>
#include <string> // include string library for string functions
#include "modules/play.cpp" // included manually created headers
#include "modules/carrom.cpp"
using namespace std;
// change the input.txt to input[1..3].txt for testing other testcases
#define OJ \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
int main()
{
OJ;
string score; // final score
int option; // command line option
int result;
int player = 1;
Carrom cleanstrikeboard; // created objects of Carrom
Play gameplayers; // created object of Play
while (gameplayers.gamewin() != true)
{
player = (player + 1) % 2;
if (((gameplayers.checkplaysc() == true) && (gameplayers.scoreddifference() >= 3)) || (cleanstrikeboard.coinCheck()))
{
score = gameplayers.gameresult();
cout << score << " won the game."
<< " Final Score: " << finalplay1Score << '-' << finalplay2Score;
break;
}
cout << endl
<< "Player " << player + 1 << ": Choose an outcome from the list below" << endl;
cout << "1. Strike" << endl;
cout << "2. Multi Strike" << endl;
cout << "3. Red Strike" << endl;
cout << "4. Striker Strike" << endl;
cout << "5. Defunct Coin" << endl;
cout << "6. None" << endl;
cout << "Current Score" << endl
<< "Player 1 Score: " << gameplayers.play1Score << endl
<< "Player 2 Score: " << gameplayers.play2Score;
cout << endl
<< "Type Your Option";
cin >> option;
if (option != 1 && option != 2 && option != 3 && option != 4 && option != 5 && option != 6)
{
cout << endl
<< "Wrong Option Try Again";
player = (player + 1) % 2;
continue;
}
if (cleanstrikeboard.red < 1 && option == 3)
{
cout << endl
<< "There are not enough red coins on the board";
cout << endl
<< "Red coin left on board are: " << cleanstrikeboard.red;
player = (player + 1) % 2;
continue;
}
if (cleanstrikeboard.black < 2 && option == 2 || cleanstrikeboard.black < 1 && option == 1 || cleanstrikeboard.black <= 0 && option == 5)
{
cout << endl
<< "There are not enough black coins on the board";
cout << endl
<< "Black coin left on board are: " << cleanstrikeboard.black;
player = (player + 1) % 2;
continue;
}
if (option == 1)
{
gameplayers.clearcount(player + 1);
result = cleanstrikeboard.strike();
gameplayers.updateplaysc(player + 1, result);
outcome = "Strike";
gameplayers.history(player + 1);
}
if (option == 2)
{
gameplayers.clearcount(player + 1);
result = cleanstrikeboard.multistrick();
gameplayers.updateplaysc(player + 1, result);
outcome = "MultiStrike";
gameplayers.history(player + 1);
}
if (option == 3)
{
gameplayers.clearcount(player + 1);
result = cleanstrikeboard.redstrike();
gameplayers.updateplaysc(player + 1, result);
outcome = "RedStrike";
gameplayers.history(player + 1);
}
if (option == 4)
{
gameplayers.clearcount(player + 1);
result = cleanstrikeboard.striker();
gameplayers.updateplaysc(player + 1, result);
outcome = "StrikerStrike";
gameplayers.history(player + 1);
gameplayers.playerfoulcount(player + 1);
}
if (option == 5)
{
result = cleanstrikeboard.defunct();
gameplayers.updateplaysc(player + 1, result);
outcome = "Defunct";
gameplayers.history(player + 1);
gameplayers.playerfoulcount(player + 1);
}
if (option == 6)
{
result = cleanstrikeboard.emptyStrike();
gameplayers.updateplaysc(player + 1, result);
outcome = "Empty";
gameplayers.playeremptymoves(player + 1);
gameplayers.updateplayerhistory(player + 1);
}
}
return 0;
} | true |
4d2302ccc209e3a838dc934958dab54e18df0d47 | C++ | shivangigoel1302/Interviewbit | /Sorted_Array_To_Balanced_BST.cpp | UTF-8 | 525 | 3.296875 | 3 | [] | no_license | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* helper(const vector<int>&A,int i,int j){
if(i > j){
return NULL;
}
int mid = (i+j)/2;
TreeNode* n = new TreeNode(A[mid]);
n->left = helper(A,i,mid-1);
n->right = helper(A,mid+1,j);
return n;
}
TreeNode* Solution::sortedArrayToBST(const vector<int> &A) {
return helper(A,0,A.size()-1);
}
| true |
c3c2c3d15b85bde91dbeff8151ba7100722b9034 | C++ | rambog/git | /study/c++_primer_V5/chapter9/resize.cpp | UTF-8 | 715 | 3.078125 | 3 | [] | no_license | /*======================================================================
* filename: resize.cpp
* author: rambogui
* data: 2018-12-27 10:50:33
======================================================================*/
#include <iostream>
#include <vector>
using std::vector;
using std::endl;
using std::cin;
using std::cout;
int main(int argc, char *argv[])
{
vector<int> iv = {1,2,3,4,5,6,7,8,9,10};
iv.resize(12);
for (int tmp : iv)
cout << tmp << ' ';
cout << endl;
iv.resize(15, 100);
for (int tmp : iv)
cout << tmp << ' ';
cout << endl;
iv.resize(5);
for (int tmp : iv)
cout << tmp << ' ';
cout << endl;
return 0;
}
| true |
8c1b7b7bd7c202ed9aa957484317c0b56dce5cfe | C++ | Kolbjoern/GameOfVirus | /LDCompo40/src/World.h | UTF-8 | 706 | 2.84375 | 3 | [] | no_license | #pragma once
#include <SFML\Graphics\RenderWindow.hpp>
#include <SFML\Graphics\VertexArray.hpp>
enum class TileType
{
EMPTY = 0,
GROUND = 1,
BORDER = 2,
GROUND_DESTROYED = 3,
VIRUS = 4,
VIRUS_UNIT = 5
};
class World
{
public:
World();
~World();
void init(int tileSize, int width, int height);
void draw(sf::RenderWindow& window, sf::View& camera);
void createHole(int tileX, int tileY, int radius);
void createGroundMass(int tileX, int tileY, int radius);
std::vector<TileType>& getMapData();
private:
void createCave();
void smoothCave();
int getSurroundingCount(int gridX, int gridY, bool wall);
std::vector<TileType> m_mapData;
int m_tileSize;
int m_width;
int m_height;
};
| true |
3ee87e87b51bd5c5fd18c767e709d98aeb16ec27 | C++ | 4less/bhm | /BHashMap.h | UTF-8 | 15,046 | 2.59375 | 3 | [] | no_license | //
// Created by joachim on 27/04/2020.
//
#ifndef BHM_BHASHMAP_H
#define BHM_BHASHMAP_H
#include <cmath>
#include "cstdint"
#include "DLList.h"
#include "KmerQueue.h"
#undef get16bits
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
#define get16bits(d) (*((const uint16_t *) (d)))
#endif
#if !defined (get16bits)
#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
using namespace std;
class HashFunction {
public:
HashFunction() {};
virtual uint32_t operator() (const uint8_t * data, unsigned int byte) = 0;
};
class SuperFastHash : public HashFunction { ;
uint32_t operator()(const uint8_t *data, unsigned int byte) override {
uint32_t hash = byte, tmp;
unsigned int rem;
if (byte <= 0 || data == nullptr) return 0;
rem = byte & 3u;
byte >>= 2u;
//Main loop
for (;byte > 0; byte--) {
hash += get16bits (data);
tmp = (get16bits (data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof (uint16_t);
hash += hash >> 11;
}
// Handle end cases
switch (rem) {
case 3: hash += get16bits (data);
hash ^= hash << 16;
hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
hash += hash >> 11;
break;
case 2: hash += get16bits (data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += (signed char)*data;
hash ^= hash << 10;
hash += hash >> 1;
}
// Force "avalanching" of final 127 bits
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
public:
SuperFastHash() {}
};
//template <int KB, int VB>
template <int KeyBits, int ValueBits>
class BHashMap {
public:
static const int KEY_BYTES = (KeyBits % 8) == 0 ? KeyBits / 8 : KeyBits / 8 + 1;
static const int VALUE_BYTES = (ValueBits % 8) == 0 ? ValueBits / 8 : ValueBits / 8 + 1;
private:
int n;
static const int OVERLAP_BYTES = (KeyBits % 8) == 0 ? 0 : 1;
static const bool HAS_OVERLAP = OVERLAP_BYTES == 1 ? true : false;
static const int OVERLAP_POS = HAS_OVERLAP ? KEY_BYTES - 1 : -1;
static const int M = KEY_BYTES + VALUE_BYTES - OVERLAP_BYTES;
uint8_t keyMask;
uint8_t valMask;
int valueMask;
HashFunction * hash;
int load = 0;
double loadFactor;
int loadThreshold;
double by = 0.5;
// Pointer to array
uint8_t * byte;
bool isKeySame(uint8_t * kv1, uint8_t * kv2);
bool isEmpty(int pos);
void resize(double by);
void initArray(int n);
int psl(uint8_t * kv, int current);
void resizeInsert(int index, int oldN, KmerQueue<M> queue, DLList<int> processed);
public:
BHashMap<KeyBits, ValueBits>(int n, HashFunction * hash);
BHashMap<KeyBits, ValueBits>(int n, double loadFactor);
uint8_t * search(uint8_t * key);
// Extract key and value, respectively, from key-value entry to separate array
void getKey(uint8_t (&kv)[M], uint8_t (&to)[KEY_BYTES]);
void getKeyP(uint8_t * kv, uint8_t (&to)[KEY_BYTES]);
void getValue(uint8_t (&kv)[M], uint8_t (&to)[VALUE_BYTES]);
void getValueP(uint8_t * kv, uint8_t (&to)[VALUE_BYTES]);
// Put/Insert operations
// Insert key and value at position
void insertAt(int pos, uint8_t (&key)[KEY_BYTES], uint8_t (&value)[VALUE_BYTES]);
void insertAt(int pos, uint8_t * kv);
void insertAt(int pos, uint8_t * key, uint8_t * value);
//void put(uint8_t (&key)[KEY_BYTES], uint8_t (&value)[VALUE_BYTES]);
void put(uint8_t * key, uint8_t * value);
// Get/GetAt Operations
bool getAt(int pos, uint8_t (&to)[VALUE_BYTES]);
uint64_t getAt(int pos);
bool get(uint8_t (&key)[KEY_BYTES], uint8_t (&to)[VALUE_BYTES] );
uint64_t get(uint8_t (&key)[KEY_BYTES]);
// Debug and visualization methods
void printMap();
static string printBit(uint8_t c) {
string s;
for (int i = 0; i < 8; i++) {
char text[1];
sprintf(text, "%d", (c & (int)(pow(2,7-i))) >> 7-i);
s += text;
}
return s;
}
static void printArray(uint8_t * ary, int len) {
for (int i = 0; i < len; i++) {
cout << printBit(ary[i]) << " ";
}
cout << endl;
}
};
template <int KeyBits, int ValueBits>
BHashMap<KeyBits, ValueBits>::BHashMap(int size, HashFunction *hash) {
//BHashMap(size);
this->hash = hash;
}
template <int KeyBits, int ValueBits>
BHashMap<KeyBits, ValueBits>::BHashMap(int n, double loadFactor) {
this->n = n;
this->loadFactor = loadFactor;
this->loadThreshold = n * loadFactor;
// use before assigning memory of hashmap
this->hash = (HashFunction *) malloc(sizeof(SuperFastHash));
new(this->hash) SuperFastHash;
cout << "!byte " << (uint32_t*)byte << endl;
this->byte = (uint8_t *) malloc(n * M);
cout << "bytemal " << (uint32_t*)byte << endl;
//this->hash = new SuperFastHash();
int remainder = KeyBits % 8;
this->keyMask = (KeyBits % 8) == 0 ? 0xFF : 0xFF - (pow(2, (8 - remainder)) - 1);
this->valMask = keyMask ^ 0xFF;
uint8_t m[4] = { 0 };
for (int i = 0; i < M-KEY_BYTES; i++) {
m[i] = 0xff;
}
m[M-KEY_BYTES] |= valMask;
this->valueMask = *((uint32_t*) &m);
cout << "value int keyMask: " << this->valueMask << endl;
cout << "keyMask: " << (int)keyMask << endl;
}
template <int KeyBits, int ValueBits>
bool BHashMap<KeyBits, ValueBits>::isKeySame(uint8_t *kv1, uint8_t *kv2) {
int i = 0;
for (; i < KEY_BYTES-1; i++) {
if (kv1[i] != kv2[i]) {
return false;
}
if ((kv1[i] & keyMask) != kv2[i] & keyMask) {
return false;
}
}
return true;
}
template <int KeyBits, int ValueBits>
bool BHashMap<KeyBits, ValueBits>::isEmpty(int pos) {
for (int i = M-1; i > KEY_BYTES - 1; i--) {
if (byte[(pos*M)+i] != 0x00) return(false);
}
return (!HAS_OVERLAP ? true : ((byte[(pos * M) + OVERLAP_POS] & valMask) == 0x00));
}
template <int KeyBits, int ValueBits>
//template<int M, int KB>
void BHashMap<KeyBits, ValueBits>::put(uint8_t * key, uint8_t * value) {
int32_t h = ((*hash)(key, KEY_BYTES) % n);
cout << "original hash " << h << " ----- ";
//cout << "is_empty: " << (bool)(isEmpty(h)) << endl;
while (!isEmpty(h)) {
cout << psl(key,h) << " - curpsl: " << psl(byte+(h*M),h) << endl;
if (isKeySame(key, (byte+(h*M)))) {
cout << "update at: " << h << endl;
insertAt(h, key, value);
return;
} else if (psl(key, h) > psl(byte+(h*M), h)) {
cout << "robin at: " << h << endl;
uint8_t newkey[KEY_BYTES];
uint8_t newval[VALUE_BYTES];
getKeyP(byte+(h*M), newkey);
getValueP(byte+(h*M), newval);
insertAt(h, key,value);
key = (uint8_t *) newkey;
value = (uint8_t *) newval;
}
h = (h+1) % n;
}
cout << "insert at: " << h << endl;
insertAt(h, key, value);
if (++load >= loadThreshold) {
resize(this->by);
}
}
template <int KeyBits, int ValueBits>
uint8_t *BHashMap<KeyBits, ValueBits>::search(uint8_t *key) {
return nullptr;
}
template <int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::getKey(uint8_t (&kv)[M], uint8_t (&to)[KEY_BYTES]) {
for (int i = 0; i < KEY_BYTES - 1; i++) {
to[i] = kv[i];
}
to[KEY_BYTES - 1] = kv[KEY_BYTES - 1] & keyMask;
}
template <int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::getKeyP(uint8_t * kv, uint8_t (&to)[KEY_BYTES]) {
for (int i = 0; i < KEY_BYTES - 1; i++) {
to[i] = kv[i];
}
to[KEY_BYTES - 1] = kv[KEY_BYTES - 1] & keyMask;
}
template <int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::getValue(uint8_t (&kv)[M], uint8_t (&to)[VALUE_BYTES]) {
for (int i = KEY_BYTES; i < M; i++) {
to[i-KEY_BYTES+OVERLAP_BYTES] = kv[i];
}
if (HAS_OVERLAP)
to[0] = kv[OVERLAP_POS] & valMask;
}
template <int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::getValueP(uint8_t * kv, uint8_t (&to)[VALUE_BYTES]) {
for (int i = KEY_BYTES; i < M; i++) {
to[i-KEY_BYTES+OVERLAP_BYTES] = kv[i];
}
if (HAS_OVERLAP)
to[0] = kv[OVERLAP_POS] & valMask;
}
template<int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::printMap() {
for (int i = 0; i < n; i++) {
cout << i << ": ";
for (int j = 0; j < M; j++) {
cout << printBit(byte[(M*i)+j]) << " ";
}
cout << endl;
}
}
template<int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::insertAt(int pos, uint8_t (&k)[KEY_BYTES], uint8_t (&v)[VALUE_BYTES]) {
for (int i = 0; i < KEY_BYTES; i++) {
byte[(pos*M)+i] = k[i];
}
if (HAS_OVERLAP) {
byte[(pos*M)+OVERLAP_POS] |= v[0];
}
for (int j = OVERLAP_BYTES; j < VALUE_BYTES; j++) {
byte[(pos*M)+KEY_BYTES - OVERLAP_BYTES + j] = v[j];
}
}
template<int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::insertAt(int pos, uint8_t * key, uint8_t * value) {
for (int i = 0; i < KEY_BYTES; i++) {
byte[(pos*M)+i] = key[i];
}
if (HAS_OVERLAP) {
byte[(pos*M)+OVERLAP_POS] |= value[0];
}
for (int j = OVERLAP_BYTES; j < VALUE_BYTES; j++) {
byte[(pos*M)+KEY_BYTES - OVERLAP_BYTES + j] = value[j];
}
}
template<int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::insertAt(int pos, uint8_t *kv) {
for (int i = 0; i < M; i++)
byte[(pos*M)+i] = kv[i];
}
template<int KeyBits, int ValueBits>
bool BHashMap<KeyBits, ValueBits>::getAt(int pos, uint8_t (&to)[VALUE_BYTES]) {
if (isEmpty(pos)) return false;
else
getValue(*((uint8_t (*)[M])byte[pos*M]), to);
return true;
}
template<int KeyBits, int ValueBits>
uint64_t BHashMap<KeyBits, ValueBits>::getAt(int pos) {
uint8_t longA[sizeof(uint64_t)] = { 0 };
for (int i = M - 1; i >= KEY_BYTES; i--) {
longA[M - 1 - i] = byte[(pos*M)+i];
}
if (HAS_OVERLAP) {
longA[VALUE_BYTES-1] = valMask & byte[(pos*M)+OVERLAP_POS];
}
return *((long *) longA);
}
template<int KeyBits, int ValueBits>
bool BHashMap<KeyBits, ValueBits>::get(uint8_t (&key)[KEY_BYTES], uint8_t (&to)[VALUE_BYTES]) {
return false;
}
template<int KeyBits, int ValueBits>
uint64_t BHashMap<KeyBits, ValueBits>::get(uint8_t (&key)[KEY_BYTES]) {
int32_t h = ((*hash)(key, KEY_BYTES) % n);
while (!isEmpty(h)) {
if (isKeySame(key, (byte+(h*M)))) {
return getAt(h);
}
h = (h+1) % n;
}
return -1;
}
template<int KeyBits, int ValueBits>
int BHashMap<KeyBits, ValueBits>::psl(uint8_t * kv, int current) {
uint8_t key[KEY_BYTES];
getKeyP(kv, key);
int32_t h = ((*hash)(key, KEY_BYTES) % n);
return current - h;
}
template<int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::resize(double by) {
cout << "############### resize ######################";
int oldN = n;
n += n * by;
loadThreshold = loadFactor * n;
cout << "first: " << byte << endl;
cout << "last: " << (byte+(n*M)) << endl;
cout << "hash: " << hash << endl;
cout << "byte " << (uint32_t*)byte << endl;
uint8_t * tmp = (uint8_t *) realloc(this->byte, n);
cout << "tmp " << (uint32_t*)tmp << endl;
if (tmp) {
cout << "success !!!!!!!!!!!!!!!!!!!!" << endl;
byte = tmp;
for (int i = (oldN * M); i < (n * M); i++) {
byte[i] = 0x00;
}
}
loadThreshold = loadFactor * n;
cout << "li " << (n*M) << endl;
cout << "first " << (uint32_t*)byte << endl;
cout << "last: " << (uint32_t*)(byte+(n*M)) << endl;
cout << "hash: " << hash << endl;
printMap();
DLList<int> processed;
KmerQueue<M> queue;
int index = 0;
while (isEmpty(index))
index++;
resizeInsert(index, oldN, queue, processed);
}
template<int KeyBits, int ValueBits>
void BHashMap<KeyBits, ValueBits>::resizeInsert(int index, int oldN, KmerQueue<M> queue, DLList<int> processed) {
cout << "############################################################reinsert: " << index << endl;
cout << "beginning "<< endl;
printMap();
uint8_t kv[M];
uint8_t keyT[KEY_BYTES];
uint8_t valueT[VALUE_BYTES];
// in case of Robin
uint8_t newkey[KEY_BYTES];
uint8_t newval[VALUE_BYTES];
processed.removeLT(index);
if (!queue.isEmpty()) {
cout << "poppy" << endl;
queue.pop(kv);
} else {
while (isEmpty(index) || processed.contains(index))
index++;
cout << "index: " << index << endl;
cout << "oldN: " << oldN << endl;
if (index >= oldN) return;
// Copy entry and clear slot in byte
cout << "copy and clear slot: " << index << endl;
for (int i = 0; i < M; i++) {
kv[i] = byte[ (index * M) + i ] ;
byte[ (index * M) + i ] = 0x00;
}
}
// extract key and value
getKey(kv, keyT);
getValue(kv, valueT);
uint8_t * key = (uint8_t *) keyT;
uint8_t * value = (uint8_t *) valueT;
cout << "key " << endl;
printArray(key, KEY_BYTES);
// get pos in hashmap
int32_t h = ((*hash)(key, KEY_BYTES)) % n;
cout << "before ahilw copy/poppy" << endl;
printMap();
while (!isEmpty(h)) {
// if not processed slot is considered empty. queue entry up for processing
if (!processed.contains(h) && h >= index) {
cout << "pushy" << endl;
queue.push(byte + (h * M) );
break;
}
cout << psl(key,h) << " - curpsl: " << psl(byte+(h*M),h) << endl;
if (psl(key, h) > psl(byte+(h*M), h)) {
cout << "robin at: " << h << endl;
processed.insert(h);
getKeyP(byte + (h * M), newkey);
getValueP(byte + (h * M), newval);
insertAt(h, key, value);
key = (uint8_t *) newkey;
value = (uint8_t *) newval;
}
h = (h+1) % n;
}
cout << "after awhile " << h << endl;
printMap();
cout << "reinserted at: " << h << endl;
insertAt(h, (uint8_t *)key, (uint8_t *)value);
processed.insert(h);
this->printMap();
cout << "queue ";
queue.print();
cout << "after awhile " << h << endl;
printMap();
cout << "processed items ";
processed.print();
cout << "after processed " << h << endl;
printMap();
string interrupt;
cin >> interrupt;
printMap();
resizeInsert(++index, oldN, queue, processed);
}
#endif //BHM_BHASHMAP_H
| true |
bbe0bc18535b1e9c156ddd0179e59853aa58cad8 | C++ | krylovgeorgii/threadpool | /ThreadPool/threadpool.h | UTF-8 | 1,417 | 2.890625 | 3 | [] | no_license | #pragma once
#include <queue>
#include <vector>
#include <memory>
#include <functional>
#include <thread>
#include <future>
#include <atomic>
#include <mutex>
#include <condition_variable>
namespace threadpool {
class ThreadPool {
public:
ThreadPool(size_t);
template<class Func, class... Args>
auto addTask(Func&& func, Args&&... args)->std::future<decltype(func(args...))>;
void resize(size_t);
size_t getNumThreads() const;
size_t getNumWorkThreads();
~ThreadPool();
private:
enum class statusTh : uint8_t {
WORK,
READY_TO_DELL,
DELETED
};
std::vector<std::thread> threads;
std::vector<statusTh> threadFinished;
std::queue<std::function<void()>> tasksQueue;
std::mutex mutexTask;
std::mutex mutexAddThread;
std::condition_variable condVar;
std::condition_variable condFinish;
std::atomic<size_t> numThreads = 0;
size_t numWorkThreads = 0;
size_t delSomeThreads = 0;
void addThread();
};
template<class Func, class... Args>
auto ThreadPool::addTask(Func&& func, Args&&... args)->std::future<decltype(func(args...))> {
auto newTask = std::make_shared<std::packaged_task<decltype(func(args...))()>>(
std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
auto fut = newTask->get_future();
mutexTask.lock();
tasksQueue.emplace([newTask]() { (*newTask)(); });
mutexTask.unlock();
condVar.notify_one();
return fut;
}
};
| true |
555f1fcca859c9b8bb4fe020426e0a88aa545e0c | C++ | qutter/080215 | /12장(인체 감지 센서)/practice_12/practice_12.ino | UTF-8 | 700 | 3.1875 | 3 | [] | no_license | #define PIR_PIN 7 //동작 감지 신호 처리 핀
void setup() {
// put your setup code here, to run once:
pinMode(PIR_PIN, INPUT); //7번 핀을 입력으로 설정
Serial.begin(9600); //시리얼 통신 초기화
}
void loop() {
// put your main code here, to run repeatedly:
int value = digitalRead(PIR_PIN); //동작 감지 신호를 value 변수에 저장
if(value == HIGH) //동작을 감지했을 경우
{
Serial.println("Detected"); //시리얼 모니터에 Detected 메시지 출력
}
else //동작을 감지하지 못했을 경우
{
Serial.println("Not detected"); //시리얼 모니터에 Not detected 메시지 출력
}
delay(1000); //1초간 지연
}
| true |
0dffb349f33afc30677a964f20f494cf1f14ca86 | C++ | treque/cg | /TP3/TP3/TP3/Scene.h | UTF-8 | 4,496 | 2.75 | 3 | [] | no_license | #ifndef SCENE_H
#define SCENE_H
#include "Couleur.h"
#include "ISurface.h"
#include "Lumiere.h"
#include "MathUtils.h"
#include "Matrice4.h"
#include "Rayon.h"
#include "Singleton.h"
#include "Vecteur3.h"
#include <GL/glew.h>
#include <vector>
namespace Scene {
///////////////////////////////////////////////////////////////////////////////
/// CScene
/// Cette classe conserve et gère toutes les informations décrivant la scène
/// Elle implémente l'interface Singleton
///
/// Base class Singleton
///
/// @author Olivier Dionne
/// @date 13/08/2008
///////////////////////////////////////////////////////////////////////////////
class CScene : public Singleton<CScene>
{
SINGLETON_DECLARATION_CLASSE_SANS_CONSTRUCTEUR(CScene)
/// Constructor
CScene(void);
/// Destructeur
~CScene(void);
public:
/// Ajoute une surface à la scène
void AjouterSurface(ISurface* const Surface);
/// Ajoute une lumière à la scène
void AjouterLumiere(CLumiere* const Lumiere);
/// Effectue le lancer de rayons de la scène
void LancerRayons(void);
/// Méthodes d'ajustement de la caméra
void AjusterPositionCamera(const CVecteur3& Position);
void AjusterPointViseCamera(const CVecteur3& PointVise);
void AjusterVecteurUpCamera(const CVecteur3& Up);
/// Méthodes d'ajustement des propriétés de la scène
void AjusterResolution(const int ResX, const int ResY);
void AjusterCouleurArrierePlan(const CCouleur& Couleur);
void AjusterNbRebondsMax(const int NbRebondsMax);
void AjusterEnergieMinimale(const REAL EnergieMinimale);
void AjusterIndiceRefraction(const REAL IndiceRefraction);
/// Obtenir la texture openGL du rendu de la scène
GLuint ObtenirTextureGL(void);
/// Traiter le ficheir de données de la scène
void TraiterFichierDeScene(const char* Fichier);
/// Release all scene data
void Liberer(void);
private:
/// Parser state enum
enum EtatTraitementScene
{
TRAITEMENT_SCENE,
TRAITEMENT_LUMIERE,
TRAITEMENT_TRIANGLE,
TRAITEMENT_PLAN,
TRAITEMENT_QUADRIQUE
};
/// Nombre maximum de caractères pour le tampon de traitement
const static int NB_MAX_CAR_PAR_LIGNE = 80;
/// Les dimensions du film de la caméra
constexpr static REAL DIM_FILM_CAM = 0.024;
///////////////////////////////////////////////////////////////////////////////
/// CameraDeScene
/// Petite structure encapsulant une caméra de scène
///
/// @author Olivier Dionne @date 13/08/2008
///////////////////////////////////////////////////////////////////////////////
struct CameraDeScene
{
/// Position de la caméra
CVecteur3 Position;
/// Point visé de la caméra
CVecteur3 PointVise;
/// Le vecteur "up" de la caméra
CVecteur3 Up;
/// L'orientation de la caméra
CMatrice4 Orientation;
/// La focale de la caméra
REAL Focale;
/// L'angle d'ouverture de la caméra
REAL Angle;
};
/// Useful std typedefs
typedef std::vector<ISurface*> SurfaceVecteur;
typedef std::vector<CLumiere*> LumiereVecteur;
/// Initialise la scène
void Initialiser(void);
/// Initialise la camera
void InitialiserCamera(void);
/// Obtenir la couleur du rayon
const CCouleur ObtenirCouleur(const CRayon& Rayon) const;
/// Obtenir la couleur au point d'intersection
const CCouleur ObtenirCouleurSurIntersection(const CRayon& Rayon, const CIntersection& Intersection) const;
/// Obtenir le filtre du matériau de surface
const CCouleur ObtenirFiltreDeSurface(CRayon& LumiereRayon) const;
/// Resolution en largeur
int m_ResLargeur;
/// Resolution en hauteur
int m_ResHauteur;
/// Données ( r, g, b ) du pixel
std::vector<GLfloat> m_InfoPixel;
/// Texture de rendu openGL
GLuint m_TextureScene;
/// Caméra de scène
CameraDeScene m_Camera;
/// La couleur de l'arrière-plan
CCouleur m_CouleurArrierePlan;
/// Le conteneur des surfaces de la scène
SurfaceVecteur m_Surfaces;
/// Le conteneur des lumières de la scène
LumiereVecteur m_Lumieres;
/// L'indice de réfraction de la scène
REAL m_IndiceRefractionScene;
/// Le nombre maximum de rebonds permis
int m_NbRebondsMax;
/// L'Énergie minimale d'un rayon
REAL m_EnergieMinRayon;
};
} // namespace Scene
#endif
| true |
c7505d85e544fb50c5f6d247ea5f5aab60de02ac | C++ | Minokis/self-education | /labs/part_1_Structured/4_two_dim_arrays/matrix_generator/matrix_generator.cpp | UTF-8 | 839 | 3.40625 | 3 | [] | no_license | #include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <ctime>
int main()
{
int ncol, nrow, val;
std::cout << "Welcome! Let's create a matrix.\n";
std::cout << "Values will be written to the file, separated by a whitespace (one row).\n";
std::cout << "Enter nrow (number of rows): \n";
std::cin >> nrow;
std::cout << "Enter ncol (number of columns): \n";
std::cin >> ncol;
std::string name;
std::cout << "Enter filename (for output file): \n";
std::cin >> name;
// Seed
std::srand(static_cast<unsigned int>(std::time(0)));
// writing into file
std::ofstream fileF;
fileF.open(name);
fileF << nrow << " " << ncol << std::endl;
for (int i = 0; i < nrow*ncol; i++) {
std::rand() % 2 ? fileF << std::rand() << " " : fileF << (-1) * std::rand() << " ";
}
fileF.close();
return 0;
}
| true |
4fb0fc54be3f3d2075bf931655c661f4312a17e3 | C++ | sarraff/HOTspital | /pass.cpp | UTF-8 | 901 | 2.96875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <windows.h>
string getpass(const char *prompt, bool show_asterisk=true)
{
const char BACKSPACE=8;
const char RETURN=13;
string password;
unsigned char ch=0;
cout <<prompt<<endl;
DWORD con_mode;
DWORD dwRead;
HANDLE hIn=GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode( hIn, &con_mode );
SetConsoleMode( hIn, con_mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT) );
while(ReadConsoleA( hIn, &ch, 1, &dwRead, NULL) && ch !=RETURN)
{
if(ch==BACKSPACE)
{
if(password.length()!=0)
{
if(show_asterisk)
cout <<"\b \b";
password.resize(password.length()-1);
}
}
else
{
password+=ch;
if(show_asterisk)
cout <<'*';
}
}
cout <<endl;
return password;
}
| true |
3ecaad0a908b364bd46dec60d3987f80f14a5ac6 | C++ | dgquintas/libmpplas | /src/headers/Constants.h | ISO-8859-1 | 9,283 | 2.703125 | 3 | [] | no_license | /*
* $Id$
*/
#ifndef __CONSTANTS_H_
#define __CONSTANTS_H_
#include <limits>
#include <cstdlib>
#include "BasicTypedefs.h"
#include "Utils.h"
namespace mpplas{
/** Constants used throughout the library */
namespace Constants{
static const Digit DIGIT_ZERO = 0;
static const Digit DIGIT_ONE = 1;
static const Digit DIGIT_TWO = 2;
static const SignedDigit SIGNEDDIGIT_MINUSONE = -1;
#ifdef ARCH_x86
static const char* const ARCH_STRING = "x86";
#define ARCH_DEFINED
#endif
#ifdef ARCH_x86_64
static const char* const ARCH_STRING = "x86_64";
#define ARCH_DEFINED
#endif
#ifdef ARCH_generic
static const char* const ARCH_STRING = "generic";
#define ARCH_DEFINED
#endif
#ifdef ARCH_ppc
static const char* const ARCH_STRING = "ppc";
#define ARCH_DEFINED
#endif
#ifndef ARCH_DEFINED
#warning "ARCH not supported or not defined. Using x86"
static const char* const ARCH_STRING = "x86";
#define ARCH_DEFINED
#define ARCHBITS 32
#endif
static const short ARCH_BITS = ARCHBITS;
/** Nmero de operaciones soportadas por vCPUBasica */
static const int NUM_OPERACIONES = 10;
/** Log2(10) */
static const double LOG_2_10 = 3.3219280948873623;
/** Log10(2)*/
static const double LOG_10_2 = 0.3010299956639812;
/** Bits en mantisa de un double */
static const int BITS_EN_DOUBLE = std::numeric_limits<double>::digits;
/** Bits en un unsigned long */
static const int BITS_EN_ULONG = std::numeric_limits<unsigned long>::digits;
/** Bits en un Digit */
static const int BITS_EN_CIFRA = std::numeric_limits<Digit>::digits;
/** Bits in half a Digit */
static const int BITS_IN_HALFCIFRA = std::numeric_limits<Digit>::digits >> 1;
/** Bits en un SignedDigit */
static const int BITS_EN_CIFRASIGNO = std::numeric_limits<SignedDigit>::digits;
/** Bytes en un Digit */
static const int BYTES_EN_CIFRA = BITS_EN_CIFRA >> 3;
/** Maximo valor de una Digit */
static const Digit DIGIT_MAX = std::numeric_limits<Digit>::max();
/** Maximum value for half a Digit */
static const Digit DIGITHALF_MAX = (((Digit)1) << BITS_IN_HALFCIFRA) - 1;
/** Binary mask for the lower half of a Digit */
static const Digit MASK_DIGITLOW = DIGITHALF_MAX;
/** Binary mask for the higher half of a Digit */
static const Digit MASK_DIGITHIGH = ~MASK_DIGITLOW;
/** Maximo valor de una SignedDigit */
static const SignedDigit SIGNEDDIGIT_MAX = std::numeric_limits<SignedDigit>::max();
/** Maximo valor de un unsigned long */
static const unsigned long SYSTEM_ULONG_MAX = std::numeric_limits<unsigned long>::max();
/** Maximo valor de un long */
static const long SYSTEM_LONG_INT_MAX = std::numeric_limits<long>::max();
/* Maximo valor de un size_t */
static const size_t SYSTEM_SIZE_T_MAX = std::numeric_limits<size_t>::max();
/** Mayor 'n' tal que \f$10^n \leq 2^{base}\f$.
*
* Es decir, el nmero de cifras decimales que "caben" en un 'Digit'
* para \f$ \lfloor\log_{10} 2^{32}\rfloor = 9 \f$ */
static const int MAX_EXP10_CIFRA = std::numeric_limits<Digit>::digits10;
static const Digit MAX_BASE10_POWER_DIGIT = Utils::CTPow<10, MAX_EXP10_CIFRA>::result;
/** Mayor 'n' tal que \f$10^n \leq 2^{base}\f$.
*
* Es decir, el nmero de cifras decimales que "caben" en un 'SignedDigit'
* para \f$ \lfloor\log_{10} 2^{31}\rfloor = 9 \f$ */
static const int MAX_EXP10_CIFRASIGNO = std::numeric_limits<SignedDigit>::digits10;
/** Mayor 'n' tal que \f$10^n \leq 2^{base}\f$.
*
* Es decir, el nmero de cifras decimales que "caben" en un 'Digit'
* para \f$ \lfloor\log_{10} 2^{32}\rfloor = 9 \f$ */
static const int MAX_EXP10_ULONG = std::numeric_limits<unsigned long>::digits10;
/** Mximo numero de digitos en base 10 representables por un double.
*
* Mximo numero de digitos en base 10 representables por un double.
* (se aade un uno ya que hay cierto "margen" para una cifra ms;
* Esto es, el \f$\log_{10}(bits_mantisa)\f$ normalmente tiene cierta parte
* fraccionaria. */
static const int MAX_EXP10_DOUBLE = std::numeric_limits<double>::digits10;
#if ARCHBITS == 64
static const int LOG_2_BITS_EN_CIFRA = 6;
#elif ARCHBITS == 32
static const int LOG_2_BITS_EN_CIFRA = 5;
#endif
static const size_t DIGIT_MOD_MASK = (1<<Constants::LOG_2_BITS_EN_CIFRA)-1;
/** Nmero de cifras en base \f$2^{BITS_EN_CIFRA}\f$ a partir del cual se usa
* la multiplicacion de Karatsuba */
static const int UMBRAL_KARATSUBA = 160;
/** Nmero de cifras en base \f$2^{BITS_EN_CIFRA}\f$ a partir del cual se usa
* karatsuba para el calculo del cuadrado. */
static const int UMBRAL_CUAD_KARATSUBA = 72;
/** Nmero de bytes tras los cuales el generador de semillas (el no
* seguro) se renueva con datos random reales. */
static const int UMBRAL_SEMILLA = 10;
/** Iteraciones que se considerarn en la factorizacin trial */
static const int COTA_FACTORIZACION_TRIAL = 303; // pi(2000)
/** Iteraciones que se considerarn en la factorizacin por el metodo
* \f$\rho\f$ de Pollard */
static const int COTA_FACTORIZACION_RHO = 50000;
/** Iteraciones que se considerarn en la factorizacin por el metodo
* SQUFOR */
static const int COTA_FACTORIZACION_SQUFOF = 500;
/** Tabla para el uso por la funcin de deteccin de cuadrado de
* enteros */
static const bool Q11[11] = {true, true, false, true, true, true, false, false,
false, true, false};
/** Tabla para el uso por la funcin de deteccin de cuadrado de
* enteros */
static const bool Q63[63] = {true, true, false, false, true, false, false, true,
false, true, false, false, false, false, false, false, true, false, true,
false, false, false, true, false, false, true, false, false, true, false,
false, false, false, false, false, false, true, true, false, false, false,
false, false, true, false, false, true, false, false, true, false, false,
false, false, false, false, false, false, true, false, false, false, false};
/** Tabla para el uso por la funcin de deteccin de cuadrado de
* enteros */
static const bool Q64[64] = {true, true, false, false, true, false, false, false, false,
true, false, false, false, false, false, false, true, true, false, false, false,
false, false, false, false, true, false, false, false, false, false, false, false,
true, false, false, true, false, false, false, false, true, false, false, false,
false, false, false, false, true, false, false, false, false, false, false, false,
true, false, false, false, false, false, false};
/** Tabla para el uso por la funcin de deteccin de cuadrado de
* enteros */
static const bool Q65[65] = {true, true, false, false, true, false, false, false, false,
true, true, false, false, false, true, false, true, false, false, false, false,
false, false, false, false, true, true, false, false, true, true, false, false,
false, false, true, true, false, false, true, true, false, false, false, false,
false, false, false, false, true, false, true, false, false, false, true, true,
false, false, false, false, true, false, false, true};
/** Primes up to 2000. */
static const Digit TABLA_PRIMOS_2000[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019,
1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201,
1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409,
1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487,
1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579,
1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777,
1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877,
1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993,
1997, 1999
}; // 303 elements = Pi(2000)
}
}
#endif
| true |
1e7be3d5d46bdc7f1dfc0bd1c9e9e3a12ffd6e1d | C++ | Galfurian/FixedPointNeuralNetwork | /include/fpnn/fixed_point_matrix.hpp | UTF-8 | 22,280 | 3.46875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <ostream>
#include <cassert>
template <typename T>
class QSMatrix
{
private:
std::vector<T> _data;
unsigned _rows;
unsigned _cols;
typedef std::initializer_list<std::initializer_list<T>> initializer_list_type_t;
public:
/// @brief Construct a new QSMatrix object.
/// @param rows
/// @param cols
/// @param initial
QSMatrix(unsigned rows, unsigned cols, const T &initial);
/// @brief Construct a new QSMatrix object.
/// @param values
QSMatrix(const initializer_list_type_t &values);
/// @brief Construct a new QSMatrix object.
/// @param rhs
QSMatrix(const QSMatrix<T> &rhs);
/// @brief Destroy the QSMatrix object.
virtual ~QSMatrix();
/// @brief Get the number of rows of the matrix.
/// @return the number of rows.
inline unsigned get_rows() const
{
return _rows;
}
/// @brief Get the number of columns of the matrix.
/// @return the number of columns.
inline unsigned get_cols() const
{
return _cols;
}
/// @brief Returns the total size of the matrix.
/// @return the total size of the matrix.
inline unsigned get_size() const
{
return _rows * _cols;
}
/// @brief Assign operator.
/// @param rhs the other matrix.
/// @return a reference to this matrix.
QSMatrix<T> &operator=(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator+(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return a reference to this matrix.
QSMatrix<T> &operator+=(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator-(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return a reference to this matrix.
QSMatrix<T> &operator-=(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator*(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return a reference to this matrix.
QSMatrix<T> &operator*=(const QSMatrix<T> &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator+(const T &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator-(const T &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator*(const T &rhs);
/// @brief
/// @param rhs
/// @return
QSMatrix<T> operator/(const T &rhs);
/// @brief
/// @param rhs
/// @return
std::vector<T> operator*(const std::vector<T> &rhs);
/// @brief Calculate a transpose of this matrix.
/// @return the transposed matrix.
QSMatrix<T> transpose() const;
/// @brief Calculates the determinant of this matrix.
/// @return the determinant.
T determinant() const;
/// @brief Calculates the adjoint of this matrix.
/// @return the adjoint.
QSMatrix<T> adjoint() const;
/// @brief Calculates the inverse of this matrix.
/// @return the inverse.
QSMatrix<T> inverse() const;
/// @brief Extracts the diagonal elements.
/// @return the diagonal elements.
std::vector<T> diag() const;
/// @brief Operator for accessing the matrix.
/// @param row the accessed row.
/// @param col the accessed column.
/// @return the reference to the accessed item.
T &operator()(const unsigned &row, const unsigned &col);
/// @brief Operator for accessing the matrix.
/// @param row the accessed row.
/// @param col the accessed column.
/// @return the const reference to the accessed item.
const T &operator()(const unsigned &row, const unsigned &col) const;
/// @brief Alternative function to access the matrix.
/// @param row the accessed row.
/// @param col the accessed column.
/// @return the reference to the accessed item.
inline T &at(const unsigned &row, const unsigned &col)
{
return this->operator()(row, col);
}
/// @brief Alternative function to access the matrix.
/// @param row the accessed row.
/// @param col the accessed column.
/// @return the const reference to the accessed item.
inline const T &at(const unsigned &row, const unsigned &col) const
{
return this->operator()(row, col);
}
};
template <typename T>
QSMatrix<T>::QSMatrix(unsigned rows, unsigned cols, const T &initial)
: _data(rows * cols, initial),
_rows(rows),
_cols(cols)
{
// Nothing to do.
}
template <typename T>
QSMatrix<T>::QSMatrix(const initializer_list_type_t &values)
: _data(),
_rows(),
_cols()
{
// Get the rows.
auto rows = values.size();
// Get the list of rows.
const auto &row_list = values.begin();
if (rows > 0)
{
// Get the cols.
auto cols = values.begin()->size();
if (cols > 0)
{
// Set rows and cols.
_rows = rows, _cols = cols;
// Resize the matrix.
_data.resize(_rows * _cols);
for (size_t row_index = 0; row_index < _rows; ++row_index)
{
// Set the cols.
cols = row_list[row_index].size();
if (_cols != cols)
{
std::cerr << "Row " << row_index << " has wrong number of elements.\n";
_rows = _cols = 0;
_data.clear();
return;
}
// Get the list of cells in the row.
const auto &column_list = row_list[row_index].begin();
for (size_t column_index = 0; column_index < _cols; ++column_index)
{
this->at(row_index, column_index) = column_list[column_index];
}
}
}
}
}
template <typename T>
QSMatrix<T>::QSMatrix(const QSMatrix<T> &rhs)
: _data(rhs._data),
_rows(rhs.get_rows()),
_cols(rhs.get_cols())
{
// Nothing to do.
}
template <typename T>
QSMatrix<T>::~QSMatrix() {}
template <typename T>
QSMatrix<T> &QSMatrix<T>::operator=(const QSMatrix<T> &rhs)
{
if (&rhs == this)
return *this;
// Set the new rows and columns.
_rows = rhs.get_rows();
_cols = rhs.get_cols();
// Resize the matrix.
_data.resize(_rows * _cols);
for (unsigned i = 0; i < _rows; i++)
for (unsigned j = 0; j < _cols; j++)
this->at(i, j) = rhs(i, j);
return *this;
}
// Addition of two matrices
template <typename T>
QSMatrix<T> QSMatrix<T>::operator+(const QSMatrix<T> &rhs)
{
unsigned rows = rhs.get_rows(), cols = rhs.get_cols();
bool lhs_is_cell = ((_rows == 1) && (_cols == 1)),
rhs_is_cell = ((rows == 1) && (cols == 1));
bool lhs_is_vect = ((_rows == 1) || (_cols == 1)) && !lhs_is_cell,
rhs_is_vect = ((rows == 1) || (cols == 1)) && !rhs_is_cell;
if (lhs_is_cell || rhs_is_cell)
{
// Prepare the result.
QSMatrix result(rhs_is_cell ? _rows : rows, rhs_is_cell ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_cell ? *this : rhs, _cell = rhs_is_cell ? rhs : *this;
// Compute the sum.
for (size_t i = 0; i < (rhs_is_cell ? this->get_size() : rhs.get_size()); ++i)
result._data[i] = _matrix._data[i] + _cell._data[0];
return result;
}
else if (lhs_is_vect || rhs_is_vect)
{
// Prepare the result.
QSMatrix result(rhs_is_vect ? _rows : rows, rhs_is_vect ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_vect ? *this : rhs, _vect = rhs_is_vect ? rhs : *this;
// Compute the selector.
bool is_row_vect = (_vect._rows == 1);
// Compute the sum.
for (unsigned i = 0; i < (rhs_is_vect ? _rows : rows); i++)
for (unsigned j = 0; j < (rhs_is_vect ? _cols : cols); j++)
result(i, j) = _matrix(i, j) + _vect(i * !is_row_vect, j * is_row_vect);
return result;
}
else if ((_rows == rows) && (_cols == cols))
{
QSMatrix result(_rows, _cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
for (unsigned j = 0; j < _cols; j++)
result(i, j) = this->at(i, j) + rhs(i, j);
return result;
}
assert(false && "Arrays have incompatible sizes for this operation.");
}
// Cumulative addition of this matrix and another
template <typename T>
QSMatrix<T> &QSMatrix<T>::operator+=(const QSMatrix<T> &rhs)
{
unsigned rows = rhs.get_rows(), cols = rhs.get_cols();
bool lhs_is_cell = ((_rows == 1) && (_cols == 1)),
rhs_is_cell = ((rows == 1) && (cols == 1));
bool lhs_is_vect = ((_rows == 1) || (_cols == 1)) && !lhs_is_cell,
rhs_is_vect = ((rows == 1) || (cols == 1)) && !rhs_is_cell;
if (lhs_is_cell || rhs_is_cell)
{
// Prepare the result.
QSMatrix tmp(rhs_is_cell ? _rows : rows, rhs_is_cell ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_cell ? *this : rhs, _cell = rhs_is_cell ? rhs : *this;
// Compute the sum.
for (size_t i = 0; i < (rhs_is_cell ? this->get_size() : rhs.get_size()); ++i)
tmp._data[i] = _matrix._data[i] + _cell._data[0];
return (*this = tmp);
}
else if (lhs_is_vect || rhs_is_vect)
{
// Prepare the tmp.
QSMatrix tmp(rhs_is_vect ? _rows : rows, rhs_is_vect ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_vect ? *this : rhs, _vect = rhs_is_vect ? rhs : *this;
// Compute the selector.
bool is_row_vect = (_vect._rows == 1);
// Compute the sum.
for (unsigned i = 0; i < (rhs_is_vect ? _rows : rows); i++)
for (unsigned j = 0; j < (rhs_is_vect ? _cols : cols); j++)
tmp(i, j) = _matrix(i, j) + _vect(i * !is_row_vect, j * is_row_vect);
return (*this = tmp);
}
else if ((_rows == rows) && (_cols == cols))
{
for (unsigned i = 0; i < _rows; i++)
for (unsigned j = 0; j < _cols; j++)
this->at(i, j) += rhs(i, j);
return *this;
}
assert(false && "Arrays have incompatible sizes for this operation.");
}
// Subtraction of this matrix and another
template <typename T>
QSMatrix<T> QSMatrix<T>::operator-(const QSMatrix<T> &rhs)
{
unsigned rows = rhs.get_rows(), cols = rhs.get_cols();
bool lhs_is_cell = ((_rows == 1) && (_cols == 1)),
rhs_is_cell = ((rows == 1) && (cols == 1));
bool lhs_is_vect = ((_rows == 1) || (_cols == 1)) && !lhs_is_cell,
rhs_is_vect = ((rows == 1) || (cols == 1)) && !rhs_is_cell;
if (lhs_is_cell || rhs_is_cell)
{
// Prepare the result.
QSMatrix result(rhs_is_cell ? _rows : rows, rhs_is_cell ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_cell ? *this : rhs, _cell = rhs_is_cell ? rhs : *this;
// Compute the sum.
for (size_t i = 0; i < (rhs_is_cell ? this->get_size() : rhs.get_size()); ++i)
result._data[i] = _matrix._data[i] - _cell._data[0];
return result;
}
else if (lhs_is_vect || rhs_is_vect)
{
// Prepare the result.
QSMatrix result(rhs_is_vect ? _rows : rows, rhs_is_vect ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_vect ? *this : rhs, _vect = rhs_is_vect ? rhs : *this;
// Compute the selector.
bool is_row_vect = (_vect._rows == 1);
// Compute the sum.
for (unsigned i = 0; i < (rhs_is_vect ? _rows : rows); i++)
for (unsigned j = 0; j < (rhs_is_vect ? _cols : cols); j++)
result(i, j) = _matrix(i, j) - _vect(i * !is_row_vect, j * is_row_vect);
return result;
}
else if ((_rows == rows) && (_cols == cols))
{
QSMatrix result(_rows, _cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
for (unsigned j = 0; j < _cols; j++)
result(i, j) = this->at(i, j) - rhs(i, j);
return result;
}
assert(false && "Arrays have incompatible sizes for this operation.");
}
// Cumulative subtraction of this matrix and another
template <typename T>
QSMatrix<T> &QSMatrix<T>::operator-=(const QSMatrix<T> &rhs)
{
unsigned rows = rhs.get_rows(), cols = rhs.get_cols();
bool lhs_is_cell = ((_rows == 1) && (_cols == 1)),
rhs_is_cell = ((rows == 1) && (cols == 1));
bool lhs_is_vect = ((_rows == 1) || (_cols == 1)) && !lhs_is_cell,
rhs_is_vect = ((rows == 1) || (cols == 1)) && !rhs_is_cell;
if (lhs_is_cell || rhs_is_cell)
{
// Prepare the result.
QSMatrix tmp(rhs_is_cell ? _rows : rows, rhs_is_cell ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_cell ? *this : rhs, _cell = rhs_is_cell ? rhs : *this;
// Compute the sum.
for (size_t i = 0; i < (rhs_is_cell ? this->get_size() : rhs.get_size()); ++i)
tmp._data[i] = _matrix._data[i] - _cell._data[0];
return (*this = tmp);
}
else if (lhs_is_vect || rhs_is_vect)
{
// Prepare the tmp.
QSMatrix tmp(rhs_is_vect ? _rows : rows, rhs_is_vect ? _cols : cols, 0.0);
// Prepare the references to the right matrices.
const QSMatrix<T> &_matrix = rhs_is_vect ? *this : rhs, _vect = rhs_is_vect ? rhs : *this;
// Compute the selector.
bool is_row_vect = (_vect._rows == 1);
// Compute the sum.
for (unsigned i = 0; i < (rhs_is_vect ? _rows : rows); i++)
for (unsigned j = 0; j < (rhs_is_vect ? _cols : cols); j++)
tmp(i, j) = _matrix(i, j) - _vect(i * !is_row_vect, j * is_row_vect);
return (*this = tmp);
}
else if ((_rows == rows) && (_cols == cols))
{
for (unsigned i = 0; i < _rows; i++)
for (unsigned j = 0; j < _cols; j++)
this->at(i, j) -= rhs(i, j);
return *this;
}
assert(false && "Arrays have incompatible sizes for this operation.");
}
// Left multiplication of this matrix and another
template <typename T>
QSMatrix<T> QSMatrix<T>::operator*(const QSMatrix<T> &rhs)
{
unsigned rows = rhs.get_rows(), cols = rhs.get_cols();
assert(_cols == rows && "For matrix multiplication, the number of columns in the first"
"matrix must be equal to the number of rows in the second matrix.");
QSMatrix result(_rows, cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
{
for (unsigned j = 0; j < cols; j++)
{
for (unsigned k = 0; k < _rows; k++)
{
result(i, j) += this->at(i, k) * rhs(k, j);
}
}
}
return result;
}
// Cumulative left multiplication of this matrix and another
template <typename T>
QSMatrix<T> &QSMatrix<T>::operator*=(const QSMatrix<T> &rhs)
{
QSMatrix result = (*this) * rhs;
(*this) = result;
return *this;
}
template <typename T>
QSMatrix<T> QSMatrix<T>::transpose() const
{
QSMatrix result(_cols, _rows, 0.0);
for (unsigned i = 0; i < _rows; i++)
for (unsigned j = 0; j < _cols; j++)
result(j, i) = this->at(i, j);
return result;
}
// Matrix/scalar addition
template <typename T>
QSMatrix<T> QSMatrix<T>::operator+(const T &rhs)
{
QSMatrix result(_rows, _cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
{
for (unsigned j = 0; j < _cols; j++)
{
result(i, j) = this->at(i, j) + rhs;
}
}
return result;
}
// Matrix/scalar subtraction
template <typename T>
QSMatrix<T> QSMatrix<T>::operator-(const T &rhs)
{
QSMatrix result(_rows, _cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
{
for (unsigned j = 0; j < _cols; j++)
{
result(i, j) = this->at(i, j) - rhs;
}
}
return result;
}
// Matrix/scalar multiplication
template <typename T>
QSMatrix<T> QSMatrix<T>::operator*(const T &rhs)
{
QSMatrix result(_rows, _cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
{
for (unsigned j = 0; j < _cols; j++)
{
result(i, j) = this->at(i, j) * rhs;
}
}
return result;
}
// Matrix/scalar division
template <typename T>
QSMatrix<T> QSMatrix<T>::operator/(const T &rhs)
{
QSMatrix result(_rows, _cols, 0.0);
for (unsigned i = 0; i < _rows; i++)
{
for (unsigned j = 0; j < _cols; j++)
{
result(i, j) = this->at(i, j) / rhs;
}
}
return result;
}
// Multiply a matrix with a vector
template <typename T>
std::vector<T> QSMatrix<T>::operator*(const std::vector<T> &rhs)
{
std::vector<T> result(rhs.size(), 0.0);
for (unsigned i = 0; i < _rows; i++)
{
for (unsigned j = 0; j < _cols; j++)
{
result[i] = this->at(i, j) * rhs[j];
}
}
return result;
}
// Obtain a vector of the diagonal elements
template <typename T>
std::vector<T> QSMatrix<T>::diag() const
{
std::vector<T> result(_rows, 0.0);
for (unsigned i = 0; i < _rows; i++)
result[i] = this->at(i, i);
return result;
}
// Access the individual elements
template <typename T>
T &QSMatrix<T>::operator()(const unsigned &row, const unsigned &col)
{
return _data[(row * _cols) + col];
}
// Access the individual elements (const)
template <typename T>
const T &QSMatrix<T>::operator()(const unsigned &row, const unsigned &col) const
{
return _data[(row * _cols) + col];
}
/// @brief Function to get cofactor of an input matrix.
/// @param input The input matrix.
/// @param output The output matrix.
/// @param rows The number of rows of the matrix to consider.
/// @param cols The number of columns of the matrix to consider.
/// @param p The row that must be removed.
/// @param q The column that must be removed.
/// @return the input matrix without row p and column q.
template <typename T>
static inline QSMatrix<T> &__compute_minor(
const QSMatrix<T> &input,
QSMatrix<T> &output,
size_t rows,
size_t cols,
size_t p,
size_t q)
{
// Looping for each element of the matrix.
for (size_t i = 0, j = 0, row = 0, col = 0; row < rows; ++row)
{
for (col = 0; col < cols; ++col)
{
// Copying only those element which are not in given row and column.
if ((row != p) && (col != q))
{
output(i, j++) = input(row, col);
// When the row is filled, increase row index and reset col index.
if (j == (cols - 1))
j = 0, ++i;
}
}
}
return output;
}
/// @brief Computes the determinant, through recursion.
/// @param matrix The input matrix.
/// @param N The size of the matrix that must be considered.
/// @return the determinant of the original input matrix.
template <typename T>
static inline T __determinant_rec(const QSMatrix<T> &matrix, size_t N)
{
// The matrix contains single element.
if (N == 1)
return matrix(0, 0);
// The matrix contains only two elements.
if (N == 2)
return (matrix(0, 0) * matrix(1, 1)) - (matrix(0, 1) * matrix(1, 0));
// The matrix contains more than two elements.
int sign = 1;
T determinant = 0;
QSMatrix<T> support(N, N, 0);
for (size_t i = 0; i < N; ++i)
{
// Compute the minor of matrix[0][i]
__compute_minor(matrix, support, N, N, 0, i);
// Recursively call this function.
determinant += sign * matrix(0, i) * __determinant_rec(support, N - 1);
// Alternate the sign.
sign = -sign;
}
return determinant;
}
template <typename T>
T QSMatrix<T>::determinant() const
{
assert(this->get_cols() == this->get_rows() && "Matrix must be square.");
return __determinant_rec(*this, this->get_cols());
}
template <typename T>
QSMatrix<T> QSMatrix<T>::adjoint() const
{
assert(this->get_cols() == this->get_rows() && "Matrix must be square.");
size_t N = this->get_cols();
// Return 1.
if (N == 1)
return QSMatrix<T>(1, 1, 1);
// temp is used to store cofactors of A[][]
int sign = 1;
QSMatrix<T> adj(N, N, 0), support(N, N, 0);
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
// Get cofactor of A[i][j]
__compute_minor(*this, support, N, N, i, j);
// sign of adj[j][i] positive if sum of row
// and column indexes is even.
sign = ((i + j) % 2 == 0) ? 1 : -1;
// Interchanging rows and columns to get the
// transpose of the cofactor matrix
adj(j, i) = sign * __determinant_rec(support, N - 1);
}
}
return adj;
}
template <typename T>
QSMatrix<T> QSMatrix<T>::inverse() const
{
assert(this->get_cols() == this->get_rows() && "Matrix must be square.");
// Get the size of the matrix.
size_t N = this->get_cols();
// Compute the determinant.
T det = this->determinant();
// If determinant is zero, the matrix is singular.
if (det == 0)
{
std::cerr << "Singular matrix, can't find its inverse.\n";
return QSMatrix<T>(0, 0, 0);
}
// Find adjoint of the matrix.
auto adjoint = this->adjoint();
// Create a matrix for the result.
QSMatrix<T> inverse(N, N, 0);
// Find Inverse using formula "inverse(A) = adj(A)/det(A)".
for (size_t i = 0; i < N; ++i)
for (size_t j = 0; j < N; ++j)
inverse(i, j) = adjoint(i, j) / det;
return inverse;
}
template <typename T>
std::ostream &operator<<(std::ostream &lhs, const QSMatrix<T> &rhs)
{
for (unsigned row = 0; row < rhs.get_rows(); ++row)
{
for (unsigned col = 0; col < rhs.get_cols(); ++col)
{
lhs << rhs(row, col) << " ";
}
lhs << "\n";
}
return lhs;
} | true |
9770620a21f0b5aa693e99fcb951b27d05f9fe87 | C++ | KevinDurant77889/CPE | /guess.cpp | UTF-8 | 1,053 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int input;
string di;
vector <string> mv;
int ans[10];
memset(ans,1,10);
bool istrue = false;
while (true)
{
cin >> input;
if (input == 0)
{
break;
}
cin >> di;
if (di == "too high")
{
for (int i = 0; i < 10 ; i++)
{
if (i+1 >= input)
{
ans[i] = 0;
}
}
}
else if (di == "too low")
{
for (int i = 0; i < 10; i++)
{
if (i + 1 <= input)
{
ans[i] = 0;
}
}
}
else if ( di == "right on")
{
for (int i = 0; i < 10; i++)
{
if (i + 1 != input)
{
ans[i] = 0;
}
}
for (int i = 0; i < 10; i++)
{
if (ans[i] == 1)
{
istrue = true;
}
}
if (istrue)
{
mv.push_back("Stan may be honest");
memset(ans,1,10);
istrue = false;
}
else
{
mv.push_back("Stan is dishonest");
memset(ans,1,10);
istrue = false;
}
}
}
for (int i = 0; i < mv.size(); i++)
{
cout << mv[i] << endl ;
}
}
| true |
2dbc108545ab54f8af1478f96ffbce65cb5b8566 | C++ | Pangi790927/OS | /stage_3_sources/kthread/ksem.cpp | UTF-8 | 1,228 | 2.796875 | 3 | [] | no_license | #include "ksem.h"
#include "lock_guard.h"
#include "scheduler.h"
namespace kthread
{
void Sem::init (int initial) {
val = initial;
chain_head = NULL;
chain_tail = NULL;
lk.init();
}
void Sem::signal() {
std::lock_guard<Lock> guard(lk);
val++;
if (chain_tail) {
/* unblock val threads from the blocked chain */
int cnt = val;
for (block_t *it = chain_tail; it && cnt; it = it->next, cnt--) {
chain_tail = it->next;
scheduler::unblock(it->pid, scheduler::SEMAPHORE);
del_blocked(it);
}
/* this means we signaled all waiting processes */
if (!chain_tail)
chain_head = NULL;
}
}
void Sem::wait() {
bool done = false;
while (!done) {
lk.lock();
if (!val) {
uint32 our_pid = scheduler::getPid();
block_t *new_block = add_blocked(chain_head, our_pid, NULL);
if (!chain_tail)
chain_tail = new_block;
chain_head = new_block;
/* the scheduler will unlock the lock for us */
scheduler::block(our_pid, scheduler::SEMAPHORE, &lk);
}
else {
val--;
done = true;
lk.unlock();
}
}
}
bool Sem::try_aquire() {
std::lock_guard<Lock> guard(lk);
if (val) {
val--;
return true;
}
else {
return false;
}
}
} | true |
540bed7d00c84083eb16d4d5f5023f94209f35a3 | C++ | Raj-Bapat/usaco | /claust2/claust2.cpp | UTF-8 | 3,012 | 2.625 | 3 | [] | no_license | //
// main.cpp
// claust2
//
// Created by r on 10/1/17.
// Copyright © 2017 r. All rights reserved.
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <limits>
#include <cmath>
using namespace std;
struct podouble {
double x, y, idx;
};
double N;
double idx1 = -1,idx2 = -1;
double leastdist = numeric_limits<double>::max();
double pyth(podouble a, podouble b) {
return sqrt(pow(a.x-b.x, 2)+pow(a.y-b.y, 2));
}
bool comp1(podouble a, podouble b) {return a.x<b.x;}
bool comp2(podouble a, podouble b) {return a.y<b.y;};
bool operator==(podouble a, podouble b) {return a.x==b.x&&a.y==b.y&&a.idx==b.idx;};
double solve(vector<podouble> cows) {
if (cows.size() == 1) {
return numeric_limits<double>::max();
}
if (cows.size() == 2) {
if (leastdist>pyth(cows[0], cows[1]) || (leastdist==pyth(cows[0], cows[1]) && cows[0].idx<idx1)) {
leastdist = pyth(cows[0], cows[1]);
idx1 = cows[0].idx;
idx2 = cows[1].idx;
}
return pyth(cows[0], cows[1]);
}
vector<podouble> v1,v2;
double case1,case2;
vector<podouble> mergea;
double split = -1;
if (cows.size()%2==0) {
split = (cows[cows.size()/2].x+cows[(cows.size()/2)-1].x)/2;
for (double i = 0; i<cows.size()/2; i++) {
v1.push_back(cows[i]);
}
for (double i = cows.size()/2; i<cows.size(); i++) {
v2.push_back(cows[i]);
}
case1 = solve(v1),case2 = solve(v2);
} else {
split = cows[cows.size()/2].x;
for (double i = 0; i<cows.size()/2; i++) {
v1.push_back(cows[i]);
}
for (double i = cows.size()/2+1; i<cows.size(); i++) {
v2.push_back(cows[i]);
}
mergea.push_back(cows[cows.size()/2]);
case1 = solve(v1),case2 = solve(v2);
}
double d = min(case1,case2);
for (double i = 0; i<cows.size(); i++) {
if (abs(split-cows[i].x)<=d) {
mergea.push_back(cows[i]);
}
}
sort(begin(mergea), end(mergea), comp2);
for (double i = 0; i<mergea.size(); i++) {
for (double j = i+1; j<i+8 && j<mergea.size(); j++) {
if (mergea[i]==mergea[j]) {
continue;
}
d = min(d,pyth(mergea[i], mergea[j]));
if (leastdist>pyth(mergea[i], mergea[j])|| (leastdist==pyth(mergea[i], mergea[j]) && min(mergea[i].idx, mergea[j].idx)<min(idx1,idx2))) {
leastdist = pyth(mergea[i], mergea[j]);
idx1 = mergea[i].idx;
idx2 = mergea[j].idx;
}
}
}
return d;
}
int main(int argc, const char * argv[]) {
vector<podouble> cows;
cin >> N;
for (double i = 0; i<N; i++) {
podouble p;
cin >> p.x >> p.y;
p.idx = i;
cows.push_back(p);
}
sort(begin(cows), end(cows), comp1);
solve(cows);
cout << min(idx1+1,idx2+1) << " " << max(idx2+1,idx1+1) << endl;
return 0;
}
| true |
f8126c7504d578c50dddf52b92458d0c996cf24e | C++ | DerThorsten/orthos | /orthos_cpp/include/orthos_cpp/axis/plane.hxx | UTF-8 | 1,958 | 2.890625 | 3 | [] | no_license | #ifndef ORHTOS_CPP_PLANE_HXX
#define ORHTOS_CPP_PLANE_HXX
#include <string>
#include <vector>
#include <vigra/tinyvector.hxx>
namespace orthos{
class Plane{
public:
Plane(const std::string & name,
const int xAxis,
const int yAxis,
const int zAxis=-1,
const int planeIndex = -1)
: name_(name),
xAxis_(xAxis),
yAxis_(yAxis),
zAxis_(zAxis),
planeIndex_(planeIndex){
}
std::string name() const{
return name_;
}
int xAxis()const{
return xAxis_;
}
int yAxis()const{
return yAxis_;
}
int zAxis()const{
return zAxis_;
}
int planeIndex()const{
return planeIndex_;
}
void setPlaneIndex(const int i){
planeIndex_ = i;
}
private:
// the name of the plane
std::string name_;
// the axis of the viewer
int xAxis_;
int yAxis_;
int zAxis_;
// the index of the plaine
int planeIndex_;
};
class PlaneVector{
public:
void addPlane(const Plane & plane ){
const auto & name = plane.name();
auto fres = nameToIndex_.find(name);
if(fres == nameToIndex_.end()){
nameToIndex_[name] = planes_.size();
}
else{
throw std::runtime_error("duplicate in planne names");
}
planes_.push_back(plane);
}
size_t size()const{
return planes_.size();
}
const Plane & getPlane(const size_t i)const{
return planes_[i];
}
private:
std::vector<Plane> planes_;
std::map<std::string, int> nameToIndex_;
std::vector<int> planePosition_;
};
}
#endif /* ORTHOS_CPP_PLANE_HXX */
| true |
e3565515015c066ac22ebaec84f922d7bec118cd | C++ | angelsware/aw-plugin-barcode-scanner | /src/ios/aw_camera_ios.cpp | UTF-8 | 1,076 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "aw_camera_ios.h"
extern "C" {
void* BarcodeScanner_create();
void BarcodeScanner_destroy(void* ptr);
void BarcodeScanner_addListener(void* ptr, long long listener);
void BarcodeScanner_removeListener(void* ptr, long long listener);
void BarcodeScanner_clearAllListeners(void* ptr);
void BarcodeScanner_scan(void* ptr);
}
namespace BarcodeScanner {
CCamera_Ios::CCamera_Ios() {
mBarcodeScanner = BarcodeScanner_create();
}
CCamera_Ios::~CCamera_Ios() {
BarcodeScanner_destroy(mBarcodeScanner);
}
void CCamera_Ios::addListener(ICameraListener* listener) {
BarcodeScanner_addListener(mBarcodeScanner, reinterpret_cast<long long>(listener));
}
void CCamera_Ios::removeListener(ICameraListener* listener) {
BarcodeScanner_removeListener(mBarcodeScanner, reinterpret_cast<long long>(listener));
}
void CCamera_Ios::clearAllListeners() {
BarcodeScanner_clearAllListeners(mBarcodeScanner);
}
void CCamera_Ios::scan() {
BarcodeScanner_scan(mBarcodeScanner);
}
}
//https://www.hackingwithswift.com/example-code/media/how-to-scan-a-qr-code
| true |
e358b52d2b7559e23d730a0d6fd1057280fb96fd | C++ | gregzb/gfx_03_line | /src/Utils.cpp | UTF-8 | 1,735 | 3.15625 | 3 | [] | no_license | #include "Utils.hpp"
#include "Vec3.hpp"
#include <cmath>
#include <vector>
#include <algorithm>
Color::Color(){};
Color::Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a) : r(r), g(g), b(b), a(a){};
Color::Color(int r, int g, int b, int a)
{
this->r = (unsigned char)r;
this->g = (unsigned char)g;
this->b = (unsigned char)b;
this->a = (unsigned char)a;
}
int Utils::sign(double x)
{
return (x > 0) - (x < 0);
}
double Utils::inverseLerp(double a, double b, double val)
{
return (val - a) / (b - a);
}
double Utils::lerp(double a, double b, double t)
{
return (1 - t) * a + t * b;
}
std::vector<Vec3> Utils::linePixels(Vec3 a, Vec3 b, bool flipped)
{
std::vector<Vec3> temp;
if (b.x < a.x)
{
temp = linePixels(b, a, flipped);
std::vector<Vec3> uglyTemp;
for (uint i = 0; i < temp.size(); i++) {
uglyTemp.push_back(temp[i]);
}
//std::reverse(temp.begin(), temp.end());
return uglyTemp;
}
long x0r = std::lround(a.x), x1r = std::lround(b.x), y0r = std::lround(a.y), y1r = std::lround(b.y);
long dY = y1r - y0r, dX = x1r - x0r;
if (std::abs(dY) > dX)
{
return linePixels({a.y, a.x}, {b.y, b.x}, true);
}
int dir = sign(dY);
dY = std::abs(dY) * 2;
int d = dY-dX;
dX *= 2;
int y = y0r;
for (int x = x0r; x <= x1r; x++)
{
if (!flipped)
temp.push_back({static_cast<double>(x), static_cast<double>(y)});
else
temp.push_back({static_cast<double>(y), static_cast<double>(x)});
if (d > 0)
{
y += dir;
d -= dX;
}
d += dY;
}
return temp;
} | true |
7108c910547e2f1f90d36295208ad51763a01e4d | C++ | sshockwave/Online-Judge-Solutions | /EZOJ/Contests/1320/C.cpp | UTF-8 | 1,685 | 2.671875 | 3 | [
"MIT"
] | permissive | #include <cstring>
#include <string>
using namespace std;
typedef long long lint;
class Entropy{
private:
bool odd;
int n,half;
char s[65];
inline lint rev(lint x){
lint ans=0;
for(int i=0;i<n;i++){
ans<<=1,ans|=(x&1)^1,x>>=1;
}
return ans;
}
public:
lint getM(int N){
n=N;
odd=n&1;
half=n>>1;
s[n]=0;
if(odd){
return 1ll<<(n-1);
}else{
return ((1ll<<n)+(1ll<<half))>>1;
}
}
string encode(lint x){
memset(s,'0',n);
if(odd){
for(int i=0;i<half;i++){
s[i]+=((x>>i)&1);
}
for(int i=half+1;i<n;i++){
s[i]+=((x>>(i-1))&1);
}
}else if(x<(1ll<<half)){
for(int i=0;i<half;i++){
s[i]+=((x>>i)&1);
}
for(int i=half;i<n;i++){
s[i]+=((x>>(n-i-1))&1)^1;
}
}else{
x-=1ll<<half;
lint lo=1;
{
lint l=1,r=1ll<<half,mid;
while(l<r){
mid=(l+r)>>1;
if(x<((mid*(mid+1))>>1)){
r=mid;
}else{
l=mid+1;
}
}
lo=l;
x-=lo*(lo-1)>>1;
}
for(int i=0;i<half;i++){
s[i]+=(lo>>i)&1;
}
x=rev(x);
for(int i=half;i<n;i++){
s[i]+=(x>>i)&1;
}
}
return string(s);
}
lint decode(string s){
lint x=0;
for(int i=n-1;i>=0;i--){
x=(x<<1)|(s[i]-'0');
}
if(odd){
if(s[half]-'0'){
x=rev(x);
}
x=(x^(x>>(half+1)<<(half+1)))|(x>>(half+1)<<half);
return x;
}else{
if(x==rev(x)){
return x&((1ll<<half)-1);
}
lint hi=x>>half<<half,lo=x^hi;
hi=rev(hi|((1ll<<half)-1));
if(lo<hi){
swap(lo,hi);
}
lint ans=(lo*(lo-1))>>1;
ans+=hi;
ans+=1ll<<half;
return ans;
}
return 0;
}
};
#include "entropy.h"
| true |
1929ca92a2f1f1548e617f73826b34757b953b56 | C++ | lxj434368832/Framework | /projects/ServiceManage/CService.cpp | GB18030 | 1,121 | 2.65625 | 3 | [] | no_license | #include "CService.h"
#include "../../include/ServiceManage/IService.h"
//CServiceʵ
class ConcreteService : public IService
{
bool Start() { printf("ʼ"); return true; }
void Stop() { printf("ֹͣ"); }
};
//ʱõĽӿڣ˽ӿڲһֱʾУ
void CService::OnStart(DWORD argc, TCHAR* argv[])
{
argc; argv;
OutputDebugString(_T("CService:Application start running!!!\n"));
m_interface = new ConcreteService();
m_interface->Start();
}
void CService::OnContinueRun()
{
m_bRun = true;
//MSG msg;
//while (m_bRun && ::GetMessage(&msg, NULL, 0, 0))
//{
// ::TranslateMessage(&msg);
//}
while (m_bRun)
{
::Sleep(1000);
}
}
//رʱõĽӿڣ˽ӿڲһֱʾرУ
void CService::OnStop()
{
OutputDebugString(_T("CService:Application end\n"));
m_bRun = false;
if (m_interface)
{
m_interface->Stop();
delete m_interface;
m_interface = nullptr;
}
else
printf("%s:%d m_interface is NULL\n",__FUNCTION__,__LINE__);
}
| true |
c65f3ea842dee03bb8a09a8f9ce5397f5d9c1508 | C++ | kaos8192/Nachos | /userprog/ipt.cc | UTF-8 | 1,287 | 2.71875 | 3 | [] | no_license | #include "ipt.h"
#include "machine.h"
extern int hand;
HashTable::HashTable(){
for (int i = 0; i < NumPhysPages; ++i){
// set valid flag to false
hashes[i].valid = FALSE;
}
//init the clock hand
//hand = 0;//MAYBE set init to zero?
}
void HashTable::Update(int frame, int vpn, int pid) {
hashes[frame].virtualPage = vpn;
hashes[frame].physicalPage = frame;
hashes[frame].valid = TRUE;
hashes[frame].use = TRUE;//Need to use for clock somehow
hashes[frame].dirty = TRUE;
hashes[frame].readOnly = FALSE;
pids[frame] = pid; //Store the PID
}
int HashTable::Find(int vpn, int pid) {
int frame = hand;//vpn%NumPhysPages;
while (hashes[frame].valid != TRUE or hashes[frame].virtualPage != vpn or pids[frame] != pid){
++frame%=NumPhysPages;
if(frame == hand)
{
return -1;
}
}
return frame;
}
//MAYBE TODO
//Need to rotate through the stuff and change use bits to dirty
//Need to stay in place on a non-replacement use
//Need to swap out stuff at spot
/*void HashTable::Clock()
{
//iterate through something
//place if empty
//else if dirty, replace
//else if need to replace but clean, toggle bit
//else use and don't move hand
}*/
| true |
9cb8b6964e4e322f04b52ecc319c4cfc0e7494db | C++ | chokevin/Schedule-of-Classes | /container.cc | UTF-8 | 16,856 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "datime.h"
#include "time.h"
#include "container.h"
#include <vector>
using namespace std;
Appt :: Appt(string namae, DaTime prd){
this->appt_setName(name);
this->appt_setPeriod(period);
}
void Appt :: appt_setName(string namae){
name.assign(namae);
}
void Appt :: appt_setPeriod(DaTime prd){
period.dt_SetDay(prd.dt_GetDay());
period.dt_SetStart(prd.dt_GetStart());
period.dt_SetEnd(prd.dt_GetEnd());
}
string Appt :: appt_getName(){
return name;
}
DaTime Appt :: appt_getPeriod(){
return period;
}
void Appt :: appt_displayPeriod(){
period.dt_Display();
}
void Appt :: appt_displayAppt(int count){
cout << count << '.' << ' ';
cout << name << ' ';
period.dt_Display();
}
Container :: Container(vector <Appt> Sch, int cnt){
this->cont_setSchedule(Sch);
this->cont_setCount(cnt);
}
void Container :: cont_setSchedule(vector <Appt> &sch){
Schedule = sch;
}
void Container :: cont_setCount(int cnt){
count = cnt;
}
bool Container :: is_number(const string s){
for(int i = 0; i< s.length(); i++){
if(isdigit(s[i])){
return true;
}
}
return false;
}
void Container :: cont_makeAppt(){
Appt appoint;
string namae;
DaTime time;
Time timer;
Day day;
int num;
bool flag = false;
cout << "What is the Professor's Name?" << endl;
cin >> namae;
while(is_number(namae)){
cout << "Not a valid name. Please try again with letters only." << endl;
cout << "What is the Professor's Name?" << endl;
cin >> namae;
}
namae[0] = toupper(namae[0]);
appoint.appt_setName(namae);
cout << "What day is this appointment on (m,t,w,r,f,s,u)?" << endl;
cin >> day;
while(!cont_validDay(day)){
cout << "Not a valid day! Try Again!" << endl;
cout << "What day is this appointment on (m,t,w,r,f,s,u)?" << endl;
cin >> day;
}
time.dt_SetDay(day);
cout << "What is the Start Time Hour?" << endl;
do{
while(!(cin >> num)){
cout << "Not a valid number... please use numbers.." << endl;
cout << "What is the Start Time Hour?" << endl;
cin.clear();
cin.ignore(1);
}
if(num < 0 || num > 23){
cout << "Not a valid Hour.. Please use numbers from 0 to 23" << endl;
cout << "What is the Start Time Hour?" << endl;
}
} while(num > 23 || num < 0);
timer.time_SetHour(num);
cout << "What is the Start Time Minute?" << endl;
do{
while(!(cin >> num)){
cout << "Not a valid number... please use numbers.." << endl;
cout << "What is the Start Time Minute?" << endl;
cin.clear();
cin.ignore(1);
}
if(num < 0 || num > 60){
cout << "Not a valid Minute... Please use numbers from 0 to 59" << endl;
cout << "What is the Start Time Minute?" << endl;
}
} while(num < 0 || num > 60);
timer.time_SetMinute(num);
time.dt_SetStart(timer);
cout << "What is the End Time Hour?" << endl;
flag = false;
do{
while(!(cin >> num)){
cout << "Not a valid number... please use numbers.." << endl;
cout << "What is the End Time Hour?" << endl;
cin.clear();
cin.ignore(1);
}
if(num < timer.time_GetHour()){
cout << "This End hour is before the start hour.. Please use numbers above "
<<timer.time_GetHour() << endl;
cout << "What is the End Time Hour?" << endl;
}
else if(num < 0 || num > 23){
cout << "Not a valid hour... Please use numbers from 0 to 23" << endl;
cout << "What is the End Time Hour?" << endl;
}
else{
flag = true;
}
} while(!flag);
timer.time_SetHour(num);
cout << "What is the End Time Minute?" << endl;
flag = false;
do{
while(!(cin >> num)){
cout << "Not a valid number... please use numbers.." << endl;
cout << "What is the End time minute?" << endl;
cin.clear();
cin.ignore(1);
}
if(time.dt_GetStart().time_GetHour() == timer.time_GetHour()
&& num < timer.time_GetMinute()){
cout << "Not a valid Minute for this hour... Please us numbers above "
<< timer.time_GetMinute() << endl;
cout << "What is the End Time Minute?" << endl;
}
else if(num < 0 || num > 60){
cout << "Not a valid minute... Please use numbers from 0 to 59" << endl;
cout << "What is the End Time Minute?" << endl;
}
else{
flag = true;
}
} while(!flag);
timer.time_SetMinute(num);
time.dt_SetEnd(timer);
appoint.appt_setPeriod(time);
this->cont_setAppt(appoint);
count++;
if(count == 0){
cout << "Appointment has been added!" << endl;
}
else if(conflict()){
cout << "There is an appointment conflict!" << endl;
count--;
}
else{
cout << "Appointment has been added!" << endl;
}
}
bool Container :: conflict(){
for(int i= 0; i < count-1; i++){
if(Schedule[count-1].appt_getPeriod().dt_Overlap(Schedule[i].appt_getPeriod())){
return true;
}
}
return false;
}
void Container :: cont_setAppt(Appt appoint){
cout << Schedule[count].appt_getName();
Schedule[count].appt_setName(appoint.appt_getName());
Schedule[count].appt_setPeriod(appoint.appt_getPeriod());
cout << Schedule[count].appt_getName() << endl;
Schedule[count].appt_displayPeriod();
}
void Container :: cont_findAppt(){
char input;
bool flag = false;
cout << "Do you want to search by (N)ame, (D)ay, or (T)ime?" << endl;
cin >> input;
while(!flag){
switch(input){
case 'n':
this->cont_findByName();
cout << "Do you want to search again? (press 'q' to exit)" << endl;
cin >> input;
break;
case 'd':
this->cont_findByDay();
cout << "Do you want to search again? (press 'q' to exit)" << endl;
cin >> input;
break;
case 't':
this->cont_findByTime();
cout << "Do you want to search again? (press 'q' to exit)" << endl;
cin >> input;
break;
case 'q':
flag = true;
break;
default:
cout << "Please pick a valid command (n,d,t)" << endl;
cout << "Do you want to search by (N)ame, (D)ay, or (T)ime?" << endl;
cin >> input;
break;
}
}
}
void Container :: cont_findByName(){
string n;
bool flag = false;
cout << "\t\tSearching by Name\t\t" << endl;
cout << "What is the name of the Professor for the appointment?" << endl;
cin >> n;
n[0] = toupper(n[0]);
cout << "Searching for Appointments with the following name " << n << endl;
for(int i =0; i < count; i++){
if(n == Schedule[i].appt_getName()){
Schedule[i].appt_displayAppt(i+1);
flag = true;
}
}
if(!flag){
cout << "Sorry. We could not find any appointments matching " << n << endl;
}
}
void Container :: cont_findByDay(){
Day day;
bool flag = false;
cout << "\t\tSearching by Day\t\t" << endl;
cout << "What is the day of the appointment?" << endl;
cin >> day;
cout << "Searching for Appointments on the following day " << day << endl;
for(int i = 0; i < count; i++){
if(day == (Schedule[i].appt_getPeriod()).dt_GetDay()){
Schedule[i].appt_displayAppt(i+1);
flag = true;
}
}
if(!flag){
cout << "Sorry. We could not find any appointments matching " << day << endl;
}
}
void Container :: cont_findByTime(){
int hour;
bool flag = false;
cout << "\t\tSearching by Start Time\t\t" << endl;
cout << "What is the approximate start hour of the appointment? (+/-3 hours)" << endl;
cin >> hour;
cout << "Searching for Appointments around the following hour " << hour << endl;
for(int i = 0; i < count; i++){
if(hour-3 == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour())||
hour-2 == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour()) ||
hour-1 == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour())||
hour == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour())||
hour+1 == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour())||
hour+2 == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour())||
hour+3 == (((Schedule[i].appt_getPeriod()).dt_GetStart()).time_GetHour())){
Schedule[i].appt_displayAppt(i+1);
flag = true;
}
}
if(!flag){
cout << "Sorry. We could not find any appointments matching a start time around "<< hour << endl;
}
}
void Container :: cont_cancelAppt(){
int i;
bool flag = false;
cout << "Which appointment do you want to cancel? (0 to cancel)" << endl;
cin >> i;
if(i != 0){
while(!flag){
if(i < 0 || i > count || i > MAX_SIZE){
cout << "This is not a valid appointment to cancel. Please choose an appointment less than " << count << endl;
cout << "Which appointment do you want to cancel? (0 to cancel)" << endl;
cin >> i;
}
else{
flag = true;
}
}
if(i != 0){
for(i; i<count; i++){
Schedule[i] = Schedule[i+1];
}
count--;
}
else{
}
}
else{
}
}
void Container :: cont_changeAppt(){
int i;
char input;
bool flag = false;
cout << "Which appointment do you want to change? (0 to exit)" << endl;
cin >> i;
if(i != 0){
while(!flag){
if(i < 0 || i > count || i > MAX_SIZE){
cout << "This is not a valid appointment to cancel. Please choose an appointment less than " << count << endl;
cout << "Which appointment do you want to change? (0 to exit)" << endl;
cin >> i;
}
else{
flag = true;
}
}
if(i != 0){
cout << "Would you like to edit the (N)ame, (D)ay, (S)tart Time, or (E)nd Time?" << endl;
cin >> input;
flag = false;
while(!flag){
switch(input){
case 'n':
this->cont_changeName(i);
cout << "Do you want to change something else? (press 'q' to cancel)"
<< endl;
cin >> input;
break;
case 'd':
this->cont_changeDay(i);
cout << "Do you want to change something else? (press 'q' to cancel)"
<< endl;
cin >> input;
break;
case 's':
this->cont_changeStart(i);
cout << "Do you want to change something else? (press 'q' to cancel)"
<< endl;
cin >> input;
break;
case 'e':
this->cont_changeEnd(i);
cout << "Do you want to change something else? (press 'q' to cancel)"
<< endl;
cin >> input;
break;
case 'q':
flag = true;
break;
default:
cout << "Please pick a valid command (n,d,s,e,q)" << endl;
cout <<
"Would you like to edit the (N)ame, (D)ay, (S)tart Time, or (E)nd Time?"
<< endl;
cin >> input;
break;
}
}
}
else{
}
}
else{
}
}
bool Container :: cont_validDay(Day day){
switch(day){
case 'm':
return true;
case 't':
return true;
case 'w':
return true;
case 'r':
return true;
case 'f':
return true;
case 's':
return true;
case 'u':
return true;
default:
return false;
}
}
void Container :: cont_changeName(int i){
string n;
cout << "Input new name" << endl;
cin >> n;
n[0] = toupper(n[0]);
Schedule[i-1].appt_setName(n);
}
void Container :: cont_changeDay(int i){
Day day;
DaTime new_datime;
bool flag = false;
cout << "Input new day" << endl;
cin >> day;
while(!cont_validDay(day)){
cout << "Not a valid day! Please use a valid choice (m,t,w,r,f,s,u)";
cout << "Input new day" << endl;
cin >> day;
}
new_datime.dt_SetDay(day);
new_datime.dt_SetStart((Schedule[i-1].appt_getPeriod()).dt_GetStart());
new_datime.dt_SetEnd((Schedule[i-1].appt_getPeriod()).dt_GetEnd());
Schedule[i-1].appt_setPeriod(new_datime);
}
void Container :: cont_changeStart(int i){
Time Start;
int hour, min;
bool flag = false;
DaTime new_datime;
cout << "Input new start hour" << endl;
cin >> hour;
while(!flag){
if(((Schedule[i-1].appt_getPeriod()).dt_GetEnd()).time_GetHour() < hour){
cout << "Not a valid hour. Please use an hour that is less than "
<< Schedule[i-1].appt_getPeriod().dt_GetEnd().time_GetHour() << endl;
cout << "Input new start hour" << endl;
cin >> hour;
}
else{
flag = true;
}
}
Start.time_SetHour(hour);
cout << "Input new start minute" << endl;
cin >> min;
flag = false;
while(!flag){
if(Schedule[i-1].appt_getPeriod().dt_GetEnd().time_GetHour() == hour && Schedule[i-1].appt_getPeriod().dt_GetEnd().time_GetMinute() < min){
cout << "Not a valid minute. Please use an minute that is less than "
<< Schedule[i-1].appt_getPeriod().dt_GetEnd().time_GetMinute() << endl;
cout << "Input new start minute" << endl;
cin >> min;
}
else{
flag = true;
}
}
Start.time_SetMinute(min);
new_datime.dt_SetDay((Schedule[i-1].appt_getPeriod()).dt_GetDay());
new_datime.dt_SetStart(Start);
new_datime.dt_SetEnd((Schedule[i-1].appt_getPeriod()).dt_GetEnd());
Schedule[i-1].appt_setPeriod(new_datime);
}
void Container :: cont_changeEnd(int i){
Time End;
int hour, min;
DaTime new_datime;
bool flag = false;
cout << "Input new End hour" << endl;
cin >> hour;
while(!flag){
if(Schedule[i-1].appt_getPeriod().dt_GetStart().time_GetHour() > hour){
cout << "Not a valid hour. Please use an hour that is greater than "
<< Schedule[i-1].appt_getPeriod().dt_GetStart().time_GetHour() << endl;
cout << "Input new End hour" << endl;
cin >> hour;
}
else{
flag = true;
}
}
End.time_SetHour(hour);
flag = false;
cout << "Input new End minute" << endl;
cin >> min;
while(!flag){
if(Schedule[i-1].appt_getPeriod().dt_GetStart().time_GetHour() == hour && Schedule[i-1].appt_getPeriod().dt_GetStart().time_GetMinute() > min){
cout << "Not a valid minute. Please use a minute that is greater than "
<< Schedule[i-1].appt_getPeriod().dt_GetStart().time_GetMinute() << endl;
cout << "Input new end minute" << endl;
cin >> min;
}
else{
flag = true;
}
}
End.time_SetMinute(min);
new_datime.dt_SetDay((Schedule[i-1].appt_getPeriod()).dt_GetDay());
new_datime.dt_SetStart((Schedule[i-1].appt_getPeriod()).dt_GetStart());
new_datime.dt_SetEnd(End);
Schedule[i-1].appt_setPeriod(new_datime);
}
void Container :: cont_disp(){
cout << endl << endl << endl;
cout << "\t\tYour Schedule\t\t" << endl;
cout << "_______________________________________________________________________" << endl;
for(int i = 0; i < count; i++){
Schedule[i].appt_displayAppt(i+1);
}
}
| true |
d2070ed488b2745b8c65b01b6d973df8b3ca2279 | C++ | inzamamtoha/ProblemSolving_Algorithms | /Data structure/linked list/doubly linked list.cpp | UTF-8 | 3,276 | 3.875 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int Value;
struct Node *Next;
struct Node *Prev;
};
struct Node *Head=NULL, *LL, *Temp,*Tail=NULL,*pot,*pot_n,*love;
void Create_A_Node(int V)
{
Temp = (struct Node *)malloc(sizeof(struct Node));//Dynamic memory allocation
if(!Temp)
{
printf("Something Wrong with Node Creation\n");
exit(0);
}
else if(Head==NULL)
{
Temp->Value = V;//assign value
Temp->Next = NULL;//assign NULL
Temp->Prev = NULL;
Head=Temp;
Tail=Temp;
}
else
{
Temp->Value = V;//assign value
Temp->Next = NULL;//assign NULL
Temp->Prev = Tail;
Tail->Next=Temp;
Tail=Temp;
}
}
void Free_A_Node(struct Node *A_Node)
{
free(A_Node);//memory free
}
void Option1()
{
int V;
printf("You have selected Option 1\n");
if(Head==NULL) // That is, the Linked list is yet to create
{
printf("Enter an integer to create the Linked List : ");
scanf("%d",&V);
Create_A_Node(V); // Calling this function with V and the new Node will be created as Temp;
//Head = Temp; // Now the Head will Point to the Temp;
printf("The Linked List is Created\n");
}
else
{
printf("The Linked List is already created\n");
}
}
void Option2()
{
int V;
printf("You have selected Option 2 (Insert a value into a Linked List (at the end))\n");
LL =Head;
printf("Enter an integer to insert into the Linked List ; ");
scanf("%d",&V);
if(LL==NULL)
{
printf("There is No Linked List. So, the Linked list will be created First\n");
Create_A_Node(V); // Calling this function with V and the new Node will be created as Temp;
//Head = Temp; // Now the Head will Point to the Temp;
}
else
{
Create_A_Node(V); // Calling this function with V and the new Node will be created as Temp;
printf("Data Inserted at the end of the Linked List\n");
}
}
void Option8()
{
printf("You have selection Option 8\n");
/*
printf("\n 8. Print the Linked List");
*/
LL = Head;
while(LL!=NULL) // Or you can write while(LL)
{
printf("%d\n",LL->Value);
LL= LL->Next;
}
}
void Menu()
{
printf("\n 1. Create a Linked List");
printf("\n 2. Insert a value into a Linked List (at the end)");
/*printf("\n 3. Insert a value into a Linked List (at the start)");
printf("\n 4. Insert a value into a Linked List (at any position)");
printf("\n 5. Delete a value into a Linked List (at the end)");
printf("\n 6. Delete a value into a Linked List (at the start)");
printf("\n 7. Delete a value into a Linked List (at any position)");*/
printf("\n 8. Print the Linked List");
printf("\nEnter your Choice : (1-8, 0 to exit):");
}
void SelectOptions(int Ch)
{
if(Ch==1) Option1();
else if(Ch==2) Option2();
/*else if(Ch==3) Option3();
else if(Ch==4) Option4();
else if(Ch==5) Option5();
else if(Ch==6) Option6();
else if(Ch==7) Option7();*/
else if(Ch==8) Option8();
}
int main()
{
double st= clock();
int Choice;
while(1)
{
Menu();
scanf("%d", &Choice);
if(Choice==0)
break;
else if(Choice<0 || Choice>8)
printf("Wrong input\n");
else
SelectOptions(Choice);
}
double en=clock();
printf("time elapsed = %.15lf\n",en-st);
return 0;
}
| true |
3b03f2f6275e86ac5950e68a9abfc199d7093ff1 | C++ | Sysreqx/Cpp | /acmp.ru/acmp0633.cpp | UTF-8 | 512 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
int main()
{
std::string team, name;
std::vector<std::string> names;
std::getline(std::cin, team);
for (int i = 0; i < 3; i++)
{
std::getline(std::cin, name);
names.push_back(name);
}
std::sort(names.begin(), names.end());
std::cout << team << ": ";
for (int i = 0; i < names.size() - 1; i++)
{
std::cout << names[i] << ", ";
}
std::cout << names[names.size() - 1] << std::endl;
//system("pause");
return 0;
} | true |
1f79ef40b2f4f93afe4206a040b004ef86054a1f | C++ | robertinant/emt | /src/ti/runtime/wiring/msp432e/tests/sanity/blink.cpp | UTF-8 | 484 | 2.65625 | 3 | [] | no_license | #include <Energia.h> // Energia Wiring API
int period = 1;
extern "C" void switchToRTCTimer(void);
__extern void blinkSetup(void)
{
pinMode(RED_LED, OUTPUT); // set ledPin pin as output
//switchToRTCTimer();
}
__extern void blinkLoop(void)
{
digitalWrite(RED_LED, HIGH); // set the LED on
delay(period); // wait for period ms
digitalWrite(RED_LED, LOW); // set the LED off
delay(1000 - period); // wait for remainder of 1 second
}
| true |
5c8fba8a616e6e2da0c1e1fc7a8629815777a846 | C++ | Stason1o/2-2-SDMP-lab1- | /SDMP lab1/Source.cpp | WINDOWS-1251 | 15,393 | 2.96875 | 3 | [] | no_license |
#include <iostream>
#include <fstream>
#include <utility>
#include <string>
#include <map>
#include <cmath>
using namespace std::rel_ops;
typedef std::string string_t;
typedef std::ifstream ifstream_t;
const string_t unsorted_txt = "D:\\unsorted.txt";
const string_t sorted_txt = "D:\\sorted.txt";
const string_t repeated_txt = "D:\\repeated.txt";
const int NMAX = 200;
//
class Element {
public:
virtual void scanFile(std::istream&) = 0;
protected:
void error(string_t mess) {
std::cerr << mess << std::endl;
std::cout << "Press any key to exit." << std::endl;
getchar();
exit(1);
}
};
//
class Countries : public Element {
protected:
int ID;
string_t country;
string_t symbol;
string_t money;
string_t city;
public:
Countries()
: ID(0), country(""), symbol(""), money(""), city("")
{}
Countries(int _ID, string_t _country, string_t _symbol, string_t _money, string_t _city)
: ID(_ID), country(_country), symbol(_symbol), money(_money), city(_city)
{}
virtual void scanFile(std::istream& fin) {
fin >> ID >> country >> symbol >> money >> city;
}
const int getID() const { return ID; }
const string_t getCountry() const { return country; }
const string_t getSymbol() const { return symbol; }
const string_t getMoney() const { return money; }
const string_t getCity() const { return city; }
bool operator==(const Countries& s) const { return ID == s.ID; }
bool operator <(const Countries& s) const { return ID < s.ID; }
~Countries() {}
};
// <<
std::ostream& operator<<(std::ostream& os, const Countries& s) {
os << s.getID() << "\t" + s.getCountry() + "\t\t" +
s.getSymbol() + "\t\t" + s.getMoney() + "\t" +
s.getCity() + "\n";
return os;
}
//
class TreeLike : public Countries {
protected:
int less;
int more;
public:
TreeLike() : Countries(), less(-1), more(-1) {}
TreeLike(int _ID, string_t _name, string_t _symbol, string_t _money, string_t _city)
: Countries(_ID, _name, _symbol, _money, _city), less(-1), more(-1)
{}
const int getLess() const { return less; }
const int getMore() const { return more; }
int setLess(int _less) { return less = _less; }
int setMore(int _more) { return more = _more; }
virtual void treeShow() {
std::cout << this->getID() << "["
<< less << ","
<< more << "]" <<
std::endl;
}
virtual void scanFile(std::istream& fin) {
less = more = -1;
Countries::scanFile(fin);
}
~TreeLike() {}
};
//
class HashCountries : public Countries {
public:
HashCountries() : Countries() {}
HashCountries(int _ID, string_t _country, string_t _symbol, string_t _money, string_t _city)
: Countries(_ID, _country, _symbol, _money, _city)
{}
int hashFunc(int n) { return ID % n; }
};
//
class DataStruct {
protected:
ifstream_t fin;
long ncomp;
public:
DataStruct() {
fin.open(unsorted_txt, std::ios::in);
if (!fin.is_open())
error("File " + unsorted_txt + " not found!\n");
ncomp = 0;
}
DataStruct(string_t filename) {
fin.open(filename, std::ios::in);
if (!fin.is_open())
error("File " + filename + " not found!\n");
ncomp = 0;
}
const long getNcomp() const { return ncomp; }
void resetNcomp() { ncomp = 0; }
~DataStruct() {
if (fin.is_open())
fin.close();
fin.clear();
}
protected:
void error(string_t mess) {
std::cerr << mess << std::endl;
std::cout << "Press any key to exit." << std::endl;
getchar();
exit(1);
}
};
//
template <class E>
class Table : public DataStruct {
protected:
int n; //
E row[NMAX]; //
public:
Table() : n(0) {}
Table(string_t filename) : DataStruct(filename) {
n = 0;
while (!fin.eof()) {
row[n].scanFile(fin);
++n;
}
}
virtual void show() {
for (int i = 0; i < n; ++i)
std::cout << row[i];
}
int search(E e) {
int position = -1;
for (int i = 0; (position == -1) && i < n; ++i) {
++ncomp;
if (e == row[i]) position = i;
}
return position;
}
const int getN() const { return n; }
~Table() {}
};
//
template <class E>
class TreeTable : public Table<E> {
using Table<E>::n;
using Table<E>::row;
using Table<E>::ncomp;
public:
TreeTable() { n = 0; }
TreeTable(string_t filename) : Table<E>(filename) {
for (int i = 1; i < n; ++i) {
int forward = 1;
int j = 0;
while (forward) {
if (row[i] < row[j]) {
if (row[j].getLess() == -1)
row[j].setLess(row[i].getID()),
forward = 0;
else
for (int k = 0; k < n; ++k)
if (row[k].getID() == row[j].getLess()) {
j = k;
break;
}
}
else {
if (row[i] > row[j]) {
if (row[j].getMore() == -1)
row[j].setMore(row[i].getID()),
forward = 0;
else
for (int k = 0; k < n; k++)
if (row[k].getID() == row[j].getMore()) {
j = k;
break;
}
}
}
}
}
}
virtual void treeShow() {
for (int i = 0; i < n; ++i)
row[i].treeShow();
}
int search(E e) {
int position = -1,
forward = 1,
i = 0;
while (forward) {
if (e == row[i])
position = i, forward = 0;
else {
if (e < row[i]) {
for (int k = 0; k < n; ++k)
if (row[k].getID() == row[i].getLess()) {
i = k;
break;
}
}
else {
for (int k = 0; k < n; ++k)
if (row[k].getID() == row[i].getMore()) {
i = k;
break;
}
}
if (i == -1)
forward = 0;
}
++ncomp;
}
return position;
}
~TreeTable() {}
};
//
template <class E>
class SortedTable : public Table<E> {
using Table<E>::n;
using Table<E>::row;
using Table<E>::ncomp;
public:
SortedTable() {}
SortedTable(string_t filename) : Table<E>(filename) {}
int search(E e) {
int a = 0, b = n - 1;
while (a < b) {
int i = (a + b) / 2;
ncomp++;
if (e > row[i])
a = i + 1;
else
if (e < row[i])
b = i;
else
a = b = i;
}
return (ncomp++, e == row[a]) ? a : -1;
}
};
//
template <class E>
class FiboTable : public Table<E> {
using Table<E>::n;
using Table<E>::row;
using Table<E>::ncomp;
public:
FiboTable() {}
FiboTable(string_t filename) : Table<E>(filename) {}
int min(int x, int y) { return (x <= y) ? x : y; }
int search(E e) {
const int fibo[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 };
int pos, index = 0, k = 0;
while (n > fibo[k]) k++;
while (k > 0) {
++ncomp;
pos = index + fibo[--k];
if (pos >= n || e < row[pos]);
else if (e == row[pos]) return pos;
else {
index = pos;
k--;
}
}
return -1;
}
};
// -
template <class E>
class HashTable : public Table<E> {
using Table<E>::n;
using Table<E>::row;
using Table<E>::ncomp;
protected:
int m;
std::map<int, std::pair<int, E>> hash_map;
public:
HashTable(string_t filename) : Table<E>(filename) {
for (int i = 0; i < n; ++i)
hash_map.insert(std::make_pair(row[i].getID(),
std::make_pair(i, row[i])));
m = hash_map.size();
}
int search(E e) {
int position = -1;
int i = e.hashFunc(n);
while (position == -1) {
++ncomp;
if (e == hash_map[i].second)
position = i;
else
i = (i + 1) % n;
}
return hash_map[position].first;
}
const int getM() const { return m; }
};
void Menu();
void linearSearch(string_t);
void unsortedTreeSearch(string_t);
void binarySearch(string_t);
void fiboSearch(string_t);
void hashSearch(string_t);
int main() {
Menu();
return 0;
}
void Menu() {
int choise = -1;
std::cout << "1 - Linear search." << std::endl;
std::cout << "2 - Unsorted tree table search." << std::endl;
std::cout << "3 - Binary search." << std::endl;
std::cout << "4 - Fibbonacci search." << std::endl;
std::cout << "5 - Hashing Table search." << std::endl;
std::cout << "0 - Exit." << std::endl;
while (choise != 0) {
std::cout << std::endl << "> ";
std::cin >> choise;
switch (choise) {
case 1:
linearSearch(unsorted_txt);
break;
case 2:
unsortedTreeSearch(unsorted_txt);
break;
case 3:
binarySearch(sorted_txt);
break;
case 4:
fiboSearch(sorted_txt);
break;
case 5:
hashSearch(repeated_txt);
case 0:
break;
default:
std::cout << "Enter the number between 0-2!" << std::endl;
break;
}
}
std::cout << "Good bye!" << std::endl;
}
void linearSearch(string_t filename) {
//
std::cout << "Loading data..." << std::endl;
Table<Countries> S(filename);
std::cout << "Complete!" << std::endl;
S.show();
char ch = 'n';
while (ch != 'y') {
int step = 0, id = 0;
std::cout << "Enter id to search: ";
std::cin >> id;
if (id > 0) {
Countries e(id, "", "", "", ""); S.resetNcomp();
step = S.search(e);
if (step < 0)
std::cout << "Not in table! " << "The number of comparisons: "
<< S.getNcomp() << std::endl;
else
std::cout << "Found on the position " << step + 1
<< " in " << S.getNcomp() << " steps!" << std::endl;
}
std::cout << "Done ? (y/n) ";
std::cin >> ch;
std::cout << std::endl;
}
//
Countries sample;
long NCOMP = 0;
ifstream_t fin;
fin.open(filename, std::ios::in);
while (!fin.eof()) {
sample.scanFile(fin);
S.resetNcomp();
if (S.search(sample) >= 0)
NCOMP += S.getNcomp();
}
fin.close();
fin.clear();
std::cout << "N = " << S.getN() << ", NCOMP = " << NCOMP
<< ", ALS = " << ((double)NCOMP / S.getN());
}
void unsortedTreeSearch(string_t filename) {
//
std::cout << "Loading data..." << std::endl;
TreeTable<TreeLike> S(filename);
std::cout << "Complete!" << std::endl;
S.treeShow();
char ch = 'n';
while (ch != 'y') {
int step, id = 0;
std::cout << "Enter id to search: ";
std::cin >> id;
TreeLike t(id, "", "", "", ""); S.resetNcomp();
step = S.search(t);
if (step < 0)
std::cout << "Not in table! " << "The number of comparisons: "
<< S.getNcomp() << std::endl;
else
std::cout << "Found on the position " << step + 1
<< " in " << S.getNcomp() << " steps!" << std::endl;
std::cout << "Done ? (y/n) ";
std::cin >> ch;
std::cout << std::endl;
}
//
TreeLike sample;
long NCOMP = 0;
ifstream_t fin;
fin.open(filename, std::ios::in);
while (!fin.eof()) {
sample.scanFile(fin);
S.resetNcomp();
if (S.search(sample) >= 0)
NCOMP += S.getNcomp();
}
fin.close();
fin.clear();
std::cout << "N = " << S.getN() << ", NCOMP = " << NCOMP;
std::cout << ", ALS = " << ((double)NCOMP / S.getN());
std::cout << ", MAX = " << (S.getN() / 2.0);
std::cout << ", MIN = " << (log((double)S.getN()) / log(2.0) + 2.0);
}
void binarySearch(string_t filename) {
//
std::cout << "Loading data..." << std::endl;
SortedTable<Countries> S(filename);
std::cout << "Complete!" << std::endl;
S.show();
char ch = 'n';
while (ch != 'y') {
int step, id = 0;
std::cout << "Enter id to search: ";
std::cin >> id;
Countries e(id, "", "", "", ""); S.resetNcomp();
step = S.search(e);
if (step < 0)
std::cout << "No table!" << "The number of comparisons: "
<< S.getNcomp() << std::endl;
else
std::cout << "Found on the position " << step + 1
<< " in " << S.getNcomp() << " steps!" << std::endl;
std::cout << "Done ? (y/n) ";
std::cin >> ch;
std::cout << std::endl;
}
//
Countries sample;
double NCOMP = 0;
ifstream_t fin;
fin.open(filename, std::ios::in);
while (!fin.eof()) {
sample.scanFile(fin);
S.resetNcomp();
if (S.search(sample) >= 0)
NCOMP += S.getNcomp();
}
fin.close();
fin.clear();
std::cout << "N = " << S.getN() << ", NCOMP = " << NCOMP;
std::cout << ", ALS = " << (double)NCOMP / S.getN();
std::cout << ", ALS_TEOR = " << (log((double)S.getN()) / log(2.0) + 2.0);
}
void fiboSearch(string_t filename) {
//
std::cout << "Loading data..." << std::endl;
FiboTable<Countries> S(filename);
std::cout << "Complete!" << std::endl;
S.show();
char ch = 'n';
while (ch != 'y') {
int step, id = 0;
std::cout << "Enter id to search: ";
std::cin >> id;
Countries e(id, "", "", "", ""); S.resetNcomp();
step = S.search(e);
if (step < 0)
std::cout << "No table!" << "The number of comparisons: "
<< S.getNcomp() << std::endl;
else
std::cout << "Found on the position " << step + 1
<< " in " << S.getNcomp() << " steps!" << std::endl;
std::cout << "Done ? (y/n) ";
std::cin >> ch;
std::cout << std::endl;
}
//
Countries sample;
double NCOMP = 0;
ifstream_t fin;
fin.open(filename, std::ios::in);
while (!fin.eof()) {
sample.scanFile(fin);
S.resetNcomp();
if (S.search(sample) >= 0)
NCOMP += S.getNcomp();
}
fin.close();
fin.clear();
std::cout << "N = " << S.getN() << ", NCOMP = " << NCOMP;
std::cout << ", ALS = " << (double)NCOMP / S.getN();
std::cout << ", ALS_TEOR = " << log10(S.getN());
}
void hashSearch(string_t filename) {
// -
std::cout << "Loading data..." << std::endl;
HashTable<HashCountries> S(filename);
std::cout << "Complete!" << std::endl;
S.show();
char ch = 'n';
while (ch != 'y') {
int step, id = 0;
std::cout << "Enter id to search: ";
std::cin >> id;
HashCountries e(id, "", "", "", ""); S.resetNcomp();
step = S.search(e);
if (step < 0)
std::cout << "No table!" << "The number of comparisons: "
<< S.getNcomp() << std::endl;
else
std::cout << "Found on the position " << step + 1
<< " in " << S.getNcomp() << " steps!" << std::endl;
std::cout << "Done ? (y/n) ";
std::cin >> ch;
std::cout << std::endl;
}
//
HashCountries sample;
double NCOMP = 0;
ifstream_t fin;
fin.open(filename, std::ios::in);
while (!fin.eof()) {
sample.scanFile(fin);
S.resetNcomp();
if (S.search(sample) >= 0)
NCOMP += S.getNcomp();
}
fin.close();
fin.clear();
std::cout << "M = " << S.getM() << ", NCOMP = " << NCOMP;
std::cout << ", ALS = " << ((double)NCOMP / S.getM());
double sigma = (double)S.getM() / (double)S.getN();
std::cout << ", m/n = " << sigma;
std::cout << ", D(m/n) = " << ((2.0 - sigma) / (2.0 - 2.0*sigma));
} | true |
25992c1554c9079e89cc98af56ec0e8e22e65f34 | C++ | ymivanov/Interpeter | /src/Lexer.cpp | UTF-8 | 9,157 | 3.03125 | 3 | [] | no_license | #include "Lexer.h"
struct Keyword
{
TokenType type;
TFString content;
};
enum State
{
Success,
Fail,
Error
};
using FuncIdentifier = Keyword;
bool isEnd(char c)
{
return c == '\0';
}
bool isNewLine(char c)
{
return c == '\n';
}
bool isDigit(char c)
{
return c >= '0' && c <= '9';
}
bool isLower(char c)
{
return c >= 'a' && c <= 'z';
}
bool isUpper(char c)
{
return c >= 'A' && c <= 'Z';
}
bool isValidFuncIdentifierStart(char c)
{
return isLower(c) || isUpper(c);
}
bool isValidFuncIdentifierChar(char c)
{
return isValidFuncIdentifierStart(c) || isDigit(c);
}
class Tokenizer
{
public:
Tokenizer(const TFString& code);
LexerResult tokenize();
private:
Token nextToken();
Token createToken(TokenType type, const TFString& lexemme, double number = 0);
Token createToken(TokenType type);
void nextSymbol();
void previousSymbol();
void nextLine();
bool match(char c);
void setError(const TFString& what);
bool filter(TokenType type);
TFString parseComment();
double parseNumber();
Keyword parseKeyword();
FuncIdentifier parseFuncIdentifier();
int parsePlaceholder();
template<typename T>
const T& SUCCESS(const T& val);
template<typename T>
const T& FAIL(const T& val);
template<typename T>
const T& ERROR(const T& val);
private:
unsigned line;
unsigned column;
unsigned currentPos;
TFString code;
State currentState;
TFError error;
TFUnorderedMap<TFString, TokenType> keywordsTable;
};
Tokenizer::Tokenizer(const TFString& code):
line(0),
column(0),
currentPos(0),
code(code),
currentState(State::Success),
error()
{
keywordsTable["add"] = TokenType::Add;
keywordsTable["sub"] = TokenType::Sub;
keywordsTable["mul"] = TokenType::Mul;
keywordsTable["div"] = TokenType::Div;
keywordsTable["pow"] = TokenType::Pow;
keywordsTable["sqrt"] = TokenType::Sqrt;
keywordsTable["sin"] = TokenType::Sin;
keywordsTable["cos"] = TokenType::Cos;
keywordsTable["eq"] = TokenType::Eq;
keywordsTable["le"] = TokenType::Le;
keywordsTable["nand"] = TokenType::Nand;
keywordsTable["if"] = TokenType::If;
keywordsTable["list"] = TokenType::List;
keywordsTable["head"] = TokenType::Head;
keywordsTable["tail"] = TokenType::Tail;
keywordsTable["map"] = TokenType::Map;
keywordsTable["filter"] = TokenType::Filter;
keywordsTable["fact"] = TokenType::Factorial;
}
LexerResult tokenize(const TFString& code)
{
Tokenizer t(code);
return t.tokenize();
}
LexerResult Tokenizer::tokenize()
{
LexerResult result{true};
Token currentToken;
do {
currentToken = nextToken();
if(currentState == State::Error)
{
result.isSuccessful = false;
result.error = TFError(error);
return result;
}
if(filter(currentToken.type))
{
result.tokens.push_back(currentToken);
}
} while(currentToken.type != TokenType::Eof && currentToken.type != TokenType::Invalid);
return result;
}
Token Tokenizer::nextToken()
{
if(isEnd(code[currentPos]))
{
return createToken(TokenType::Eof);
}
TFString comment = parseComment();
if(currentState == State::Success)
{
return createToken(TokenType::Comment, comment);
}
else if(currentState == State::Error)
{
return createToken(TokenType::Invalid);
}
switch(code[currentPos])
{
case '(':
nextSymbol();
return createToken(TokenType::LeftParen);
case ')':
nextSymbol();
return createToken(TokenType::RightParen);
case ',':
nextSymbol();
return createToken(TokenType::Comma);
case '<':
nextSymbol();
return match('-') ? createToken(TokenType::LeftArrow): createToken(TokenType::Invalid);
case ' ':
nextSymbol();
return createToken(TokenType::Whitespace);
case '\n':
nextLine();
return createToken(TokenType::NewLine);
case '\t':
nextSymbol();
return createToken(TokenType::Tab);
case '#':
return createToken(TokenType::Placeholder, "", parsePlaceholder());
default:
break;
}
bool isNegative = false;
if(code[currentPos] == '-')
{
isNegative = true;
}
double number = parseNumber();
if(currentState == State::Success)
{
//nextSymbol();
return !isNegative? createToken(TokenType::Number, "", number): createToken(TokenType::Number, "", -number);
}
Keyword keyword = parseKeyword();
if(currentState == State::Success)
{
return createToken(keyword.type, keyword.content);
}
else if(currentState == State::Error)
{
return createToken(TokenType::Invalid);
}
FuncIdentifier FuncIdentifier = parseFuncIdentifier();
if(currentState == State::Success)
{
return createToken(FuncIdentifier.type, FuncIdentifier.content);
}
else if(currentState == State::Error)
{
return createToken(TokenType::Invalid);
}
return createToken(TokenType::Invalid);
}
Token Tokenizer::createToken(TokenType type, const TFString& lexemme, double number)
{
Token token = Token{type, line, column, lexemme, number};
return token;
}
Token Tokenizer::createToken(TokenType type)
{
switch(type)
{
case TokenType::LeftParen:
return createToken(type, "(");
case TokenType::RightParen:
return createToken(type, ")");
case TokenType::Comma:
return createToken(type, ",");
case TokenType::LeftArrow:
return createToken(type, "<-");
default:
break;
};
return createToken(type, "");
}
void Tokenizer::nextSymbol()
{
currentPos++;
column++;
}
void Tokenizer::previousSymbol()
{
currentPos--;
column--;
}
void Tokenizer::nextLine()
{
line++;
currentPos++;
column = 0;
}
bool Tokenizer::match(char c)
{
if(c == code[currentPos])
{
nextSymbol();
return true;
}
return false;
}
void Tokenizer::setError(const TFString& what)
{
error = TFError{line, column, "Error: " + what};
}
bool Tokenizer::filter(TokenType type)
{
return !(type == TokenType::NewLine || type == TokenType::Whitespace || type == TokenType::Tab);
}
TFString Tokenizer::parseComment()
{
unsigned start = currentPos;
if(!match('/'))
{
return FAIL(TFString());
}
if(match('/'))
{
while(!isEnd(code[currentPos]) && !isNewLine(code[currentPos]))
{
nextSymbol();
}
return SUCCESS(TFString(code, start, currentPos - start));
}
else if(!match('*'))
{
previousSymbol();
return FAIL(TFString());
}
while(!isEnd(code[currentPos]))
{
if(match('*') && match('/'))
{
return SUCCESS(TFString(code, start, currentPos - start));
}
nextSymbol();
}
setError("unterminated comment");
return ERROR(TFString());
}
double Tokenizer::parseNumber()
{
if(!isDigit(code[currentPos]))
{
return FAIL(0);
}
size_t n = 0;
double number = std::stod(code.c_str() + currentPos, &n);
currentPos += static_cast<unsigned>(n);
column += static_cast<unsigned>(n);
return SUCCESS(number);
}
Keyword Tokenizer::parseKeyword()
{
if(!isLower(code[currentPos]))
{
return FAIL(Keyword());
}
unsigned start = currentPos;
while(isLower(code[currentPos]))
{
nextSymbol();
}
TFString keyword = TFString(code, start, currentPos - start);
TFUnorderedMap<TFString, TokenType>::const_iterator it = keywordsTable.find(keyword);
if(it == keywordsTable.end())
{
column -= currentPos - start;
currentPos = start;
return FAIL(Keyword());
}
return SUCCESS((Keyword{it->second, it->first}));
}
FuncIdentifier Tokenizer::parseFuncIdentifier()
{
if(!isValidFuncIdentifierStart(code[currentPos]))
{
return FAIL(FuncIdentifier());
}
unsigned start = currentPos;
nextSymbol();
while(isValidFuncIdentifierChar(code[currentPos]))
{
nextSymbol();
}
return SUCCESS((FuncIdentifier{TokenType::Func, TFString(code, start, currentPos - start)}));
}
int Tokenizer::parsePlaceholder()
{
if(!match('#'))
{
return FAIL(0);
}
int num = parseNumber();
if(currentState == State::Fail)
{
return FAIL(0);
}
return SUCCESS(num);
}
template<typename T>
const T& Tokenizer::SUCCESS(const T& val)
{
currentState = State::Success;
return val;
}
template<typename T>
const T& Tokenizer::FAIL(const T& val)
{
currentState = State::Fail;
return val;
}
template<typename T>
const T& Tokenizer::ERROR(const T& val)
{
currentState = State::Error;
return val;
} | true |
a80d2a8afa5ac143cec1376c284206dfdf5a5306 | C++ | tetat/Codeforces-Problems-Sol | /Difficulty1300/1220C.cpp | UTF-8 | 766 | 2.578125 | 3 | [] | no_license | /// Problem Name: Substring Game in the Lesson
/// Problem Link: https://codeforces.com/problemset/problem/1220/C
/**
* winners never quit
**/
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
typedef long long Long;
const int N = 2e5;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int tc, ca = 0;
string s;
cin >> s;
int n = s.size();
vector <int> mark(26, 0);
for (int i = 0;i < n;i++){
int d = s[i]-97;
bool ok = false;
d--;
while (d >= 0){
if (mark[d]){
ok = true;
break;
}
d--;
}
if (ok)cout << "Ann" << '\n';
else cout << "Mike" << '\n';
mark[s[i]-97]++;
}
return 0;
}
| true |
9d3b36837a6dc19f2a29024043f1d6e227d6d6d9 | C++ | 6293/idocp | /src/robot/contact_status.cpp | UTF-8 | 635 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "idocp/robot/contact_status.hpp"
#include <iostream>
namespace idocp {
void ContactStatus::showInfo() const {
std::cout << "----- The contact status -----" << std::endl;
std::cout << "active contacts: [";
for (int i=0; i<maxPointContacts(); ++i) {
if (isContactActive(i)) {
std::cout << i << ", ";
}
}
std::cout << "]" << std::endl;
std::cout << "contact points: [";
for (int i=0; i<maxPointContacts(); ++i) {
std::cout << "[" << contactPoint(i).transpose() << "], ";
}
std::cout << "]" << std::endl;
std::cout << "------------------------------" << std::endl;
}
} // namespace idocp | true |
9997693134eed4b41f6fc907d413bbd1d7beb127 | C++ | SSutherlandDeeBristol/computer-graphics-cw | /submission/raytracer/Source/TestModel.h | UTF-8 | 17,199 | 3.15625 | 3 | [] | no_license | #ifndef TEST_MODEL_CORNEL_BOX_H
#define TEST_MODEL_CORNEL_BOX_H
// Defines a simple test model: The Cornel Box
#include <glm/glm.hpp>
#include <vector>
#include <fstream>
#include <sstream>
using glm::vec3;
using glm::mat3;
using glm::vec4;
using glm::mat4;
using glm::distance;
using namespace std;
// Used to describe a light
class PhongLightSource {
public:
vec3 position;
vec3 color;
float ambientIntensity;
float diffuseIntensity;
float specularIntensity;
PhongLightSource(const vec3 &p, const vec3 &c, const float &am, const float &di, const float &sp)
: position(p), color(c), ambientIntensity(am), diffuseIntensity(di), specularIntensity(sp)
{
}
};
class PhongMaterial {
public:
vec3 color;
float ambientRef;
float diffuseRef;
float specularRef;
float shininess;
PhongMaterial(const vec3 &c, const float &am, const float &di, const float &sp, const float &sh)
: color(c), ambientRef(am), diffuseRef(di), specularRef(sp), shininess(sh)
{
}
};
// Used to describe a triangular surface:
class PhongTriangle {
public:
vec3 v0;
vec3 v1;
vec3 v2;
vec3 normal;
PhongMaterial material;
PhongTriangle( vec3 v0, vec3 v1, vec3 v2, PhongMaterial material )
: v0(v0), v1(v1), v2(v2), material(material)
{
ComputeNormal();
}
void ReverseNormal()
{
normal *= glm::vec3(-1,-1,-1);
}
void ComputeNormal()
{
vec3 e1 = glm::vec3(v1.x-v0.x,v1.y-v0.y,v1.z-v0.z);
vec3 e2 = glm::vec3(v2.x-v0.x,v2.y-v0.y,v2.z-v0.z);
vec3 normal3 = glm::normalize( glm::cross( e2, e1 ) );
normal.x = normal3.x;
normal.y = normal3.y;
normal.z = normal3.z;
}
};
// Used to describe a spherical surface:
class PhongSphere {
public:
vec3 centre;
float radius;
PhongMaterial material;
PhongSphere( vec3 centre, float radius, PhongMaterial material )
: centre(centre), radius(radius), material(material)
{
}
};
class LightSource {
public:
float watts;
vec3 color;
vec3 position;
vec3 direction;
float width;
float length;
LightSource( float watts, vec3 color, vec3 position, vec3 direction, float width, float length)
: watts(watts), color(color), position(position), direction(direction), width(width), length(length)
{
}
};
class Material {
public:
vec3 diffuseRef;
vec3 specRef;
float refractiveIndex;
Material( vec3 diffuseRef, vec3 specRef, float refractiveIndex)
: diffuseRef(diffuseRef), specRef(specRef), refractiveIndex(refractiveIndex)
{
}
};
// Used to describe a triangular surface:
class Triangle {
public:
vec3 v0;
vec3 v1;
vec3 v2;
vec3 normal;
vec3 color;
Material material;
Triangle( vec3 v0, vec3 v1, vec3 v2, vec3 color, Material material )
: v0(v0), v1(v1), v2(v2), color(color), material(material)
{
ComputeNormal();
}
void ReverseNormal()
{
normal *= glm::vec3(-1,-1,-1);
}
void ComputeNormal()
{
vec3 e1 = glm::vec3(v1.x-v0.x,v1.y-v0.y,v1.z-v0.z);
vec3 e2 = glm::vec3(v2.x-v0.x,v2.y-v0.y,v2.z-v0.z);
vec3 normal3 = glm::normalize( glm::cross( e2, e1 ) );
normal.x = normal3.x;
normal.y = normal3.y;
normal.z = normal3.z;
}
};
// Used to describe a spherical surface:
class Sphere {
public:
vec3 centre;
float radius;
vec3 color;
Material material;
Sphere( vec3 centre, float radius, vec3 color, Material material )
: centre(centre), radius(radius), color(color), material(material)
{
}
};
void GetRotationMatrix(float thetaX, float thetaY, float thetaZ, mat3 &R) {
R[0][0] = cos(thetaY) * cos(thetaZ);
R[0][1] = -cos(thetaX) * sin(thetaZ) + sin(thetaX) * sin(thetaY) * cos(thetaZ);
R[0][2] = sin(thetaX) * sin(thetaZ) + cos(thetaX) * sin(thetaY) * cos(thetaZ);
R[1][0] = cos(thetaY) * sin(thetaZ);
R[1][1] = cos(thetaX) * cos(thetaZ) + sin(thetaX) * sin(thetaY) * sin(thetaZ);
R[1][2] = -sin(thetaX) * cos(thetaZ) + cos(thetaX) * sin(thetaY) * sin(thetaZ);
R[2][0] = -sin(thetaY);
R[2][1] = sin(thetaX) * cos(thetaY);
R[2][2] = cos(thetaX) * cos(thetaY);
}
void scale(std::vector<Triangle>& triangles, float L) {
for( size_t i=0; i<triangles.size(); ++i ) {
triangles[i].v0 *= 2/L;
triangles[i].v1 *= 2/L;
triangles[i].v2 *= 2/L;
triangles[i].v0 -= vec3(1,1,1);
triangles[i].v1 -= vec3(1,1,1);
triangles[i].v2 -= vec3(1,1,1);
triangles[i].v0.x *= -1;
triangles[i].v1.x *= -1;
triangles[i].v2.x *= -1;
triangles[i].v0.y *= -1;
triangles[i].v1.y *= -1;
triangles[i].v2.y *= -1;
triangles[i].ComputeNormal();
}
}
void translate(std::vector<Triangle>& triangles, float dist, vec3 dir) {
for( size_t i=0; i<triangles.size(); ++i ) {
triangles[i].v0 += (dist * dir);
triangles[i].v1 += (dist * dir);
triangles[i].v2 += (dist * dir);
}
}
void rotate(std::vector<Triangle>& triangles, mat3 rotation) {
for( size_t i=0; i<triangles.size(); ++i ) {
triangles[i].v0 = triangles[i].v0 * rotation;
triangles[i].v1 = triangles[i].v1 * rotation;
triangles[i].v2 = triangles[i].v2 * rotation;
}
}
// Loads the Cornell Box. It is scaled to fill the volume:
// -1 <= x <= +1
// -1 <= y <= +1
// -1 <= z <= +1
void LoadTestModel( std::vector<Triangle>& tris, std::vector<Sphere>& spheres, std::vector<LightSource>& lights) {
std::vector<Triangle> triangles;
// Defines colors:
vec3 red( 0.75f, 0.15f, 0.15f );
vec3 yellow( 0.75f, 0.75f, 0.15f );
vec3 green( 0.15f, 0.75f, 0.15f );
vec3 cyan( 0.15f, 0.75f, 0.75f );
vec3 blue( 0.15f, 0.15f, 0.75f );
vec3 purple( 0.75f, 0.15f, 0.75f );
vec3 white( 0.75f, 0.75f, 0.75f );
float matteDiffuseRef = 0.05f;
// Define materials
Material matteWhite( white * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material matteRed( red * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material matteBlue( blue * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material matteGreen( green * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material matteYellow( yellow * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material mattePurple( purple * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material matteCyan( cyan * matteDiffuseRef, vec3(0,0,0), 0.0f);
Material mirror( vec3(0,0,0), vec3(1.0f,1.0f,1.0f), 0.0f);
Material glass( vec3(0,0,0), vec3(0,0,0), 1.5f);
lights.clear();
triangles.clear();
triangles.reserve( 5*2*3 );
spheres.clear();
// ---------------------------------------------------------------------------
// Room
float L = 555; // Length of Cornell Box side.
vec3 A(L,0,0);
vec3 B(0,0,0);
vec3 C(L,0,L);
vec3 D(0,0,L);
vec3 E(L,L,0);
vec3 F(0,L,0);
vec3 G(L,L,L);
vec3 H(0,L,L);
// ---------------------------------------------------------------------------
// Lights
lights.push_back( LightSource( 60, vec3(1, 1, 1), vec3(0, -1.0, -0.5), vec3(0, 1, 0), 0.4, 0.4) );
// float middleX = 0.0;
// float middleZ = -0.5;
// float width = 0.25;
// float length = 0.25;
// float seperation = 0.03;
// vec3 direction(0, 1, 0);
// float lightPower = 60;
//
// float offsetX = (width / 2 + seperation);
// float offsetZ = (length / 2 + seperation);
//
// lights.push_back( LightSource( lightPower/4, vec3(1, 1, 1), vec3(middleX + offsetX, -1.0, middleZ + offsetZ), direction, width, length) );
// lights.push_back( LightSource( lightPower/4, vec3(1, 1, 1), vec3(middleX + offsetX, -1.0, middleZ - offsetZ), direction, width, length) );
// lights.push_back( LightSource( lightPower/4, vec3(1, 1, 1), vec3(middleX - offsetX, -1.0, middleZ + offsetZ), direction, width, length) );
// lights.push_back( LightSource( lightPower/4, vec3(1, 1, 1), vec3(middleX - offsetX, -1.0, middleZ - offsetZ), direction, width, length) );
// ---------------------------------------------------------------------------
// Spheres
spheres.push_back( Sphere(vec3(0.4,0.6,-0.2), 0.4, white, glass) );
spheres.push_back( Sphere(vec3(-0.4, 0.6, 0.2), 0.4, white, mirror) );
// ---------------------------------------------------------------------------
// Walls
// Floor:
triangles.push_back( Triangle( C, B, A, white, matteWhite ) );
triangles.push_back( Triangle( C, D, B, white, matteWhite ) );
// Left wall
triangles.push_back( Triangle( A, E, C, green, matteGreen ) );
triangles.push_back( Triangle( C, E, G, green, matteGreen ) );
// Right wall
triangles.push_back( Triangle( F, B, D, red, matteRed ) );
triangles.push_back( Triangle( H, F, D, red, matteRed ) );
// Ceiling
triangles.push_back( Triangle( E, F, G, white, matteWhite ) );
triangles.push_back( Triangle( F, H, G, white, matteWhite ) );
// Back wall
triangles.push_back( Triangle( G, D, C, white, matteWhite ) );
triangles.push_back( Triangle( G, H, D, white, matteWhite ) );
// ---------------------------------------------------------------------------
// Short block
A = vec3(290,0,114);
B = vec3(130,0, 65);
C = vec3(240,0,272);
D = vec3( 82,0,225);
E = vec3(290,165,114);
F = vec3(130,165, 65);
G = vec3(240,165,272);
H = vec3( 82,165,225);
// // Front
// triangles.push_back( Triangle(E,B,A,white,matteWhite) );
// triangles.push_back( Triangle(E,F,B,white,matteWhite) );
//
// // Front
// triangles.push_back( Triangle(F,D,B,white,matteWhite) );
// triangles.push_back( Triangle(F,H,D,white,matteWhite) );
//
// // BACK
// triangles.push_back( Triangle(H,C,D,white,matteWhite) );
// triangles.push_back( Triangle(H,G,C,white,matteWhite) );
//
// // LEFT
// triangles.push_back( Triangle(G,E,C,white,matteWhite) );
// triangles.push_back( Triangle(E,A,C,white,matteWhite) );
//
// // TOP
// triangles.push_back( Triangle(G,F,E,white,matteWhite) );
// triangles.push_back( Triangle(G,H,F,white,matteWhite) );
// ---------------------------------------------------------------------------
// Tall block
A = vec3(423,0,247);
B = vec3(265,0,296);
C = vec3(472,0,406);
D = vec3(314,0,456);
E = vec3(423,330,247);
F = vec3(265,330,296);
G = vec3(472,330,406);
H = vec3(314,330,456);
// // Front
// triangles.push_back( Triangle(E,B,A,white,matteWhite) );
// triangles.push_back( Triangle(E,F,B,white,matteWhite) );
//
// // Front
// triangles.push_back( Triangle(F,D,B,white,matteWhite) );
// triangles.push_back( Triangle(F,H,D,white,matteWhite) );
//
// // BACK
// triangles.push_back( Triangle(H,C,D,white,matteWhite) );
// triangles.push_back( Triangle(H,G,C,white,matteWhite) );
//
// // LEFT
// triangles.push_back( Triangle(G,E,C,white,matteWhite) );
// triangles.push_back( Triangle(E,A,C,white,matteWhite) );
//
// // TOP
// triangles.push_back( Triangle(G,F,E,white,matteWhite) );
// triangles.push_back( Triangle(G,H,F,white,matteWhite) );
// ----------------------------------------------
// Scale to the volume [-1,1]^3
scale(triangles, L);
for( size_t i=0; i<triangles.size(); ++i ) {
tris.push_back(triangles[i]);
}
}
void LoadTestModelPhong( std::vector<PhongTriangle>& tris, std::vector<PhongSphere>& spheres, std::vector<PhongLightSource>& lights ) {
std::vector<PhongTriangle> triangles;
// Defines colors:
vec3 red( 0.75f, 0.15f, 0.15f );
vec3 yellow( 0.75f, 0.75f, 0.15f );
vec3 green( 0.15f, 0.75f, 0.15f );
vec3 cyan( 0.15f, 0.75f, 0.75f );
vec3 blue( 0.15f, 0.15f, 0.75f );
vec3 purple( 0.75f, 0.15f, 0.75f );
vec3 white( 0.75f, 0.75f, 0.75f );
vec3 darkPurple(0.65f, 0.1f, 0.65f);
PhongMaterial matteRed(red, 1, 2, 1, 1.1);
PhongMaterial matteYellow(yellow, 1, 2, 1, 1.1);
PhongMaterial matteGreen(green, 1, 2, 1, 1.1);
PhongMaterial matteCyan(cyan, 1, 2, 1, 1.1);
PhongMaterial matteBlue(blue, 1, 2, 1, 1.1);
PhongMaterial mattePurple(purple, 1, 2, 1, 1.1);
PhongMaterial matteWhite(white, 1, 2, 1, 1.1);
PhongMaterial shinyPurple(darkPurple, 4, 4, 5, 50);
PhongMaterial shinyRed(red, 4, 4, 5, 50);
PhongMaterial shinyYellow(yellow, 4, 4, 5, 50);
triangles.clear();
triangles.reserve( 5*2*3 );
spheres.clear();
spheres.reserve(2);
lights.clear();
lights.reserve(1);
// ---------------------------------------------------------------------------
// Triangles
// ---------------------------------------------------------------------------
// Room
float L = 555; // Length of Cornell Box side.
vec3 A(L,0,0);
vec3 B(0,0,0);
vec3 C(L,0,L);
vec3 D(0,0,L);
vec3 E(L,L,0);
vec3 F(0,L,0);
vec3 G(L,L,L);
vec3 H(0,L,L);
// Floor:
triangles.push_back( PhongTriangle( C, B, A, matteGreen ) );
triangles.push_back( PhongTriangle( C, D, B, matteGreen ) );
// Left wall
triangles.push_back( PhongTriangle( A, E, C, mattePurple ) );
triangles.push_back( PhongTriangle( C, E, G, mattePurple ) );
// Right wall
triangles.push_back( PhongTriangle( F, B, D, matteYellow ) );
triangles.push_back( PhongTriangle( H, F, D, matteYellow ) );
// Ceiling
triangles.push_back( PhongTriangle( E, F, G, matteCyan ) );
triangles.push_back( PhongTriangle( F, H, G, matteCyan ) );
// Back wall
triangles.push_back( PhongTriangle( G, D, C, matteWhite ) );
triangles.push_back( PhongTriangle( G, H, D, matteWhite ) );
// ---------------------------------------------------------------------------
// Short block
A = vec3(290,0,114);
B = vec3(130,0, 65);
C = vec3(240,0,272);
D = vec3( 82,0,225);
E = vec3(290,165,114);
F = vec3(130,165, 65);
G = vec3(240,165,272);
H = vec3( 82,165,225);
// Front
triangles.push_back( PhongTriangle(E,B,A,matteRed) );
triangles.push_back( PhongTriangle(E,F,B,matteRed) );
// Front
triangles.push_back( PhongTriangle(F,D,B,matteRed) );
triangles.push_back( PhongTriangle(F,H,D,matteRed) );
// BACK
triangles.push_back( PhongTriangle(H,C,D,matteRed) );
triangles.push_back( PhongTriangle(H,G,C,matteRed) );
// LEFT
triangles.push_back( PhongTriangle(G,E,C,matteRed) );
triangles.push_back( PhongTriangle(E,A,C,matteRed) );
// TOP
triangles.push_back( PhongTriangle(G,F,E,matteRed) );
triangles.push_back( PhongTriangle(G,H,F,matteRed) );
// ---------------------------------------------------------------------------
// Tall block
A = vec3(423,0,247);
B = vec3(265,0,296);
C = vec3(472,0,406);
D = vec3(314,0,456);
E = vec3(423,330,247);
F = vec3(265,330,296);
G = vec3(472,330,406);
H = vec3(314,330,456);
// Front
triangles.push_back( PhongTriangle(E,B,A,matteBlue) );
triangles.push_back( PhongTriangle(E,F,B,matteBlue) );
// Front
triangles.push_back( PhongTriangle(F,D,B,matteBlue) );
triangles.push_back( PhongTriangle(F,H,D,matteBlue) );
// BACK
triangles.push_back( PhongTriangle(H,C,D,matteBlue) );
triangles.push_back( PhongTriangle(H,G,C,matteBlue) );
// LEFT
triangles.push_back( PhongTriangle(G,E,C,matteBlue) );
triangles.push_back( PhongTriangle(E,A,C,matteBlue) );
// TOP
triangles.push_back( PhongTriangle(G,F,E,matteBlue) );
triangles.push_back( PhongTriangle(G,H,F,matteBlue) );
// ---------------------------------------------------------------------------
// Spheres
// ---------------------------------------------------------------------------
spheres.push_back( PhongSphere(vec3(0.4,0,-0.2), 0.3, shinyPurple) );
spheres.push_back( PhongSphere(vec3(-0.4,0.7,-0.8), 0.2, shinyYellow) );
// ---------------------------------------------------------------------------
// Lights
// ---------------------------------------------------------------------------
//lights.push_back( Light(vec4(0.5,-0.5,-0.7,1.0), vec3(1,1,1), 0.02f, 0.3f, 1.0f ));
//lights.push_back( Light(vec4(-0.5,-0.5,-0.7,1.0), vec3(1,1,1), 0.02f, 0.3f, 1.0f ));
lights.push_back( PhongLightSource(vec3(0.0,-0.5,-0.7), vec3(1.0,1.0,1.0), 0.02f, 0.3f, 1.0f ));
// ----------------------------------------------
// Scale to the volume [-1,1]^3
for( size_t i=0; i<triangles.size(); ++i )
{
triangles[i].v0 *= 2/L;
triangles[i].v1 *= 2/L;
triangles[i].v2 *= 2/L;
triangles[i].v0 -= vec3(1,1,1);
triangles[i].v1 -= vec3(1,1,1);
triangles[i].v2 -= vec3(1,1,1);
triangles[i].v0.x *= -1;
triangles[i].v1.x *= -1;
triangles[i].v2.x *= -1;
triangles[i].v0.y *= -1;
triangles[i].v1.y *= -1;
triangles[i].v2.y *= -1;
triangles[i].ComputeNormal();
}
for( size_t i=0; i<triangles.size(); ++i ) {
tris.push_back(triangles[i]);
}
}
void LoadBunny(std::vector<Triangle>& tris) {
std::vector<Triangle> triangles;
std::ifstream infile("Resources/bunny.obj");
std::string line;
vec3 white( 0.75f, 0.75f, 0.75f );
Material glass(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0), 1.52f);
Material matteWhite(white * 0.05f, vec3(0.0,0.0,0.0), 0.0f);
/* Vector to store all vertices */
vector<vec3> vs;
while (std::getline(infile, line)) {
/* Try parse line */
std::istringstream iss(line);
string code;
float a, b, c;
if (!(iss >> code >> a >> b >> c)) {
cout << "Could not read file" << endl;
break;
}
if (code.compare("v") == 0) {
/* Then this is a vertex definition */
vec3 vertex = vec3(a, b, c);
vs.push_back(vertex);
} else {
/* This is a face definition */
Triangle triangle = Triangle(vs[a-1], vs[b-1], vs[c-1], white, glass);
triangle.ReverseNormal();
triangles.push_back(triangle);
}
}
mat3 rotation;
GetRotationMatrix(0, M_PI, 0, rotation);
rotate(triangles, rotation);
float L = 0.3f;
scale(triangles, L);
translate(triangles, 2, vec3(-0.4,0.05,0.5));
for( size_t i=0; i<triangles.size(); ++i ) {
tris.push_back(triangles[i]);
}
}
#endif
| true |
1249b0ee724a69a21448ffe0e684ca3e2fd8b10c | C++ | arupa-loka/lrep | /datastructures/RnBTree.hpp | UTF-8 | 8,997 | 3.34375 | 3 | [
"Apache-2.0"
] | permissive | /*
1 - root is everytime black
2 - leaves are everytime black
3 - from the root each path toward the leaves includes exactly the same
number of black nodes
4 - a red node can have only black children
*/
#ifndef __RED_AND_BLACK_TREE_HPP
#define __RED_AND_BLACK_TREE_HPP
#include <cstdio>
#include <cstdlib>
#include <cstddef>
#include <cassert>
// toGraphviz
#include <iostream>
#include <fstream>
#include "Stack2.hpp"
enum NODE_COLOR {
RED=0,
BLACK=1
};
template<class T>
struct RnBNode
{
RnBNode(NODE_COLOR color=RED,
RnBNode<T> * parent=NULL,
RnBNode<T> * left=NULL,
RnBNode<T> * right=NULL) :
m_color(color), m_parent(parent), m_left(left), m_right(right) {}
NODE_COLOR m_color;
T m_value;
RnBNode<T>* m_parent;
RnBNode<T>* m_left;
RnBNode<T>* m_right;
RnBNode<T> * grandparent() {
if (m_parent != NULL) {
return m_parent->m_parent;
}
return NULL;
}
RnBNode<T> * uncle() {
RnBNode<T> * grandparent = this->grandparent();
if (grandparent != NULL) {
if (grandparent->m_left == m_parent)
return grandparent->m_right;
else
return grandparent->m_left;
}
return NULL;
}
};
template<class T>
class RnBTree {
public:
RnBTree(): m_root(NULL) {}
~RnBTree() {}
// call normal insert binary tree and then rebalance the tree
bool insert(T & value) {
RnBNode<T> * new_node = insert_binary_tree(value);
if (new_node != NULL) {
insert_case_1(new_node);
return true;
}
// otherwise do nothing, value already exists
return false;
}
void remove(T & value) {
// TODO
}
void toGraphViz(const char* iFilePath);
private:
RnBNode<T> * m_root;
static RnBNode<T> m_leaf;
void rotate_left(RnBNode<T> * n) {
RnBNode<T> * p = n->m_parent; // parent
RnBNode<T> * c = n->m_right; // child
n->m_right = c->m_left;
n->m_right->m_parent = n;
c->m_left = n;
n->m_parent = c;
if (p!=NULL) {
if (p->m_left == n)
p->m_left = c;
else
p->m_right = c;
c->m_parent = p;
} else {
c->m_parent = NULL;
m_root = c;
}
}
void rotate_right(RnBNode<T> * n) {
RnBNode<T> * p = n->m_parent;
RnBNode<T> * c = n->m_left;
n->m_left = c->m_right;
n->m_left->m_parent = n;
c->m_right = n;
n->m_parent = c;
if (p!=NULL) {
if (p->m_left == n)
p->m_left = c;
else
p->m_right = c;
c->m_parent = p;
} else {
c->m_parent = NULL;
m_root = c;
}
}
// insert as in binary tree taking into account the extra leaves nodes at
// the end
RnBNode<T> * insert_binary_tree(T & value) {
RnBNode<T> * new_node = NULL;
if (m_root != NULL) {
RnBNode<T> * curr_node = m_root;
// notice that we cannot rely on the m_leaf.parent value
// then we have to save the leaf parent in curr_node
while (1) {
if (value < curr_node->m_value)
if (curr_node->m_left != &m_leaf)
curr_node = curr_node->m_left;
else
break; // leaf node reached
else if (curr_node->m_value < value)
if (curr_node->m_right != &m_leaf) {
curr_node = curr_node->m_right;
} else {
break; // leaf node reached
}
else
return NULL; // value already exists
}
// insert all new nodes as RED nodes
new_node = new RnBNode<T>(RED, // color
curr_node,// parent
&m_leaf, // left child
&m_leaf); // right child
new_node->m_value = value;
if (value < curr_node->m_value) {
curr_node->m_left = new_node;
} else {
curr_node->m_right = new_node;
}
} else {
// root node must be BLACK
m_root = new RnBNode<T>(BLACK, NULL, &m_leaf, &m_leaf);
m_root->m_value = value;
new_node = m_root;
}
return new_node;
}
// case 1 root is NULL
void insert_case_1(RnBNode<T> * new_node) {
if (m_root==new_node) {
// This is redoundant only the first time we create a root
// but then can be called recursively from insert_case_3()
// and in that case the root could be RED again
m_root->m_color = BLACK;
} else {
insert_case_2(new_node);
}
}
// case 2 parent is black
void insert_case_2(RnBNode<T> * new_node) {
assert(m_root->m_color == BLACK);
if (new_node->m_parent->m_color == BLACK) {
// do nothing
return;
}
insert_case_3(new_node);
}
// insert_case_3
// parent and uncle are RED and grandparent is BLACK
void insert_case_3(RnBNode<T> * new_node) {
//assert(m_root->m_color == BLACK);
assert(new_node->m_parent->m_color == RED);
assert(new_node->grandparent()->m_color == BLACK);
RnBNode<T> * uncle = new_node->uncle();
// If parent is RED then it cannot be the root,
// then it must have a grandparent that is BLACK,
// then it must have an uncle as well (thanks to the black leaves)
assert(uncle != NULL);
if (uncle->m_color == RED) {
// parent RED and uncle RED
// set them black and check grandparent
RnBNode<T> * grandparent = new_node->grandparent();
new_node->m_parent->m_color = BLACK;
uncle->m_color = BLACK;
grandparent->m_color = RED;
// TODO recursion, can make it iterative
insert_case_1(grandparent);
} else {
// uncle is BLACK
insert_case_4(new_node);
}
}
// insert_case_4
void insert_case_4(RnBNode<T> * new_node) {
RnBNode<T> * grandparent = new_node->grandparent();
RnBNode<T> * parent = new_node->m_parent;
assert(grandparent->m_color == BLACK);
assert(parent->m_color == RED);
assert(new_node->uncle()->m_color == BLACK);
if (new_node == parent->m_right && parent == grandparent->m_left) {
// apply left rotation on parent
rotate_left(parent);
// now new_node is the node that was parent in the line above
new_node = new_node->m_left;
} else if (new_node == parent->m_left &&
parent == grandparent->m_right) {
// apply right rotation on parent
rotate_right(parent);
// now new_node is the node that was parent in the line above
new_node = new_node->m_right;
}
insert_case_5(new_node);
}
// insert_case_5
void insert_case_5(RnBNode<T> * new_node) {
RnBNode<T> * grandparent = new_node->grandparent();
assert(new_node->m_color == RED);
assert(new_node->m_parent->m_color == RED);
assert(grandparent->m_color == BLACK);
assert((new_node == new_node->m_parent->m_left &&
new_node->m_parent == grandparent->m_left) ||
(new_node == new_node->m_parent->m_right &&
new_node->m_parent == grandparent->m_right));
grandparent->m_color = RED;
new_node->m_parent->m_color = BLACK;
// TODO check this check
//if (new_node == new_node->m_parent->m_left) {
if (new_node->m_parent == grandparent->m_left) {
// rotate right on grandparent
rotate_right(grandparent);
} else {
// rotate left on grandparent
rotate_left(grandparent);
}
}
};
template<typename T>
RnBNode<T> RnBTree<T>::m_leaf(BLACK);
template < typename T >
void RnBTree<T>::toGraphViz(const char * iFilePath)
{
std::ofstream out(iFilePath);
if (!out.is_open()) {
printf("Error: unable to open file: %s\n", iFilePath);
return;
}
Stack2<RnBNode<T>*> stack;
out << "digraph RnBTree {\n";
out << "node [ shape=record, fixedsize=false];\n";
//out << "{ rankdir=RL; }\n";
//out << "{ rank=same; ";
if (m_root)
stack.push(m_root);
while( !stack.empty() )
{
RnBNode<T>* p = stack.getTop();
stack.pop();
out << "\"" << p << "\"";
out << "[";
if (p->m_color==RED)
out << "color=red ";
else
out << "color=black ";
out << "label=\"" << p << " | ";
out << "<f" << 0 << "> | ";
out << "<f" << 1 << "> " << p->m_value << " | ";
if (p->m_left)
stack.push(p->m_left);
out << "<f" << 2 << ">\"];\n";
if (p->m_right)
stack.push(p->m_right);
if (p->m_left)
{
out << "\"" << p << "\"";
out << ":";
out << "f" << 0 << " -> ";
out << "\"" << p->m_left << "\":f1;\n";
}
if (p->m_right)
{
out << "\"" << p << "\"";
out << ":";
out << "f" << 2 << " -> ";
out << "\"" << p->m_right << "\":f1;\n";
}
}
out << "}\n";
out.close();
}
#endif
| true |
3b54a3012b3d056158f41d8125bab5ae7edbb674 | C++ | roxla/learningC- | /20201214/homework/homework1.cpp | UTF-8 | 1,258 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <list>
using namespace std;
class Person
{
public:
string name;
int age;
float height;
Person(string name, int age, float height)
{
this->name = name;
this->age = age;
this->height = height;
}
~Person() {}
};
void addPerson(list<Person> &l, string name, int age, float height)
{
Person p(name, age, height);
l.push_back(p);
}
bool sortList(Person p1, Person p2)
{
if (p1.age < p2.age)
{
return true;
}
else if (p1.age == p2.age)
{
if (p1.height >= p2.height)
{
return true;
}
}
return false;
}
int main(int argc, char const *argv[])
{
srand((unsigned int)time(NULL));
list<Person> lst;
string nameSeed = "ABCDEFGHIJ";
string name;
int i, age;
float h;
for (i = 0; i < 10; i++)
{
name = "ID_";
name += nameSeed[i];
age = rand() % 60 + 16;
h = (rand() % 75 + 25) / 100.0 + 1;
addPerson(lst, name, age, h);
}
lst.sort(sortList);
for (list<Person>::iterator it = lst.begin(); it != lst.end(); it++)
{
cout << (*it).name << " " << (*it).age << " " << (*it).height << endl;
}
return 0;
}
| true |
4c3edc8d340c5d645eef40fb8a1c65e7b353a6e5 | C++ | NarutoVPS/CompetitiveProgramming | /CPP/[1108]Defanging_An_IP_Address[LeetCode].cpp | UTF-8 | 458 | 2.9375 | 3 | [] | no_license | // #include <bits/stdc++.h>
// using namespace std;
class Solution {
public:
string defangIPaddr(string address) {
string from {"."};
string to {"[.]"};
int pos{};
while((pos = address.find(from, pos)) != string::npos){
address.replace(pos, 1, to);
pos += to.length();
}
return address;
}
};
// int main(){
// Solution s;
// cout<<s.defangIPaddr("192.168.1.1");
// }
| true |
c414c4f28a444b450b343c5546109c19ccf38f35 | C++ | Lesssnik/Labs | /3 semester/C++/2 lab/Plant.cpp | WINDOWS-1251 | 1,405 | 3.3125 | 3 | [] | no_license | #include "Plant.h"
#include "main.h"
void Plant::Show(void) // ,
{
cout << "Life time: " << Get_life_time() << '\n'; //
cout << "Stem length: " << Get_stem_length() << '\n'; //
}
// ,
void Plant::Set_life_time(double lt){_life_time = lt;}
double Plant::Get_life_time(void){return _life_time;}
void Plant::Set_stem_length(double sl){_stem_length = sl;}
double Plant::Get_stem_length(void){return _stem_length;}
Plant::Plant() // ,
{
}
Plant::Plant(Plant* obj) //
{
Set_life_time(obj->_life_time); //
Set_stem_length(obj->_stem_length); //
}
Plant::Plant(double life_time, double stem_length) //
{
Set_life_time(life_time); //
Set_stem_length(stem_length); //
}
Plant::~Plant(void) //
{
} | true |
43d991b36fa798ae2f4f7dbfab051be0c164ee1e | C++ | sergey-s-null/LAB-03-03-Curves | /curve.cpp | UTF-8 | 16,070 | 2.828125 | 3 | [] | no_license | #include "curve.h"
#include <algorithm>
#include <QTextStream>
#include <cmath>
#include <sstream>
#include <QDebug>
//-------------|
// private |
//-------------|
using std::remove_if; using std::stringstream;
struct monom {
int deg_x, deg_y;
double coef;
};
monom readMonom(stringstream & stream) {
monom res;
res.deg_x = res.deg_y = 0;
res.coef = 0;
QChar c;
c = stream.peek();
// чтение коэффициента
if ((c == '-') || (c == '+')) {
QChar sign = c;
stream.ignore(1);
QChar next = stream.peek();
if ((next.toLower() == 'x') || (next.toLower() == 'y')) {
res.coef = sign == '-' ? -1 : 1;
}
else if ((next != '-') && (next != '+')) {
stream >> res.coef;
if (stream.fail())
throw QString("Curve: readMonom: error reading coef!");
if (sign == '-') res.coef = -res.coef;
}
else
throw QString("Curve: readMonom: double sign before coefficient!");
}
else if ((c.toLower() == 'x') || (c.toLower() == 'y')) {
res.coef = 1;
}
else {
stream >> res.coef;
if (stream.fail())
throw QString("Curve: readMonom: error reading coef!");
//throw QString("Curve: readMonom: bad symbol while reading coefficient - %1!").arg(c);
}
//чтение x, y
c = stream.peek();
c = c.toLower();
while (((c == '*') || (c == 'x') || (c == 'y')) && !stream.eof()) {
if (c == '*') {
stream.ignore(1);
c = stream.peek();
}
if ((c == 'x') || (c == 'y')) {
QChar var = c;
stream.ignore(1);
c = stream.peek();
if (c == '^') {
stream.ignore(1);
int degree;
stream >> degree;
if (stream.fail()) {
throw QString("Curve: readMonom: error reading degree!");
}
if (var == 'x')
res.deg_x += degree;
else
res.deg_y += degree;
}
else {
if (var == 'x')
res.deg_x += 1;
else
res.deg_y += 1;
}
}
else {
throw QString("Curve: readMonom: bad symbol while reading variable - %1!").arg(c);
}
c = stream.peek();
}
return res;
}
void Curve::parse(QString curve) {
auto last_it = remove_if(curve.begin(), curve.end(),
[](QChar &c) -> bool
{ return c.isSpace(); });
curve.remove(last_it - curve.begin(), curve.end() - last_it);
stringstream stream(curve.toStdString());
QChar c;
bool after_eq = false; // после =
while (stream.good() && !stream.eof()) {
c = stream.peek();
if (c == '=') {
after_eq = true;
stream.ignore(1);
}
else {
monom tm = readMonom(stream);
if ((tm.deg_x < 0) || (tm.deg_x > 2) || (tm.deg_y < 0) ||
(tm.deg_y > 2) || (tm.deg_x + tm.deg_y > 2))
throw QString("Curve: parse: degree of variable is out of range (0 - 2)!");
if (after_eq)
tm.coef *= -1;
if (tm.deg_x == 2) {
mtx[0][0] += tm.coef;
}
else if (tm.deg_y == 2) {
mtx[1][1] += tm.coef;
}
else if ((tm.deg_x == 1) && (tm.deg_y == 1)) {
mtx[0][1] += tm.coef;
mtx[1][0] += tm.coef;
}
else if (tm.deg_x == 1) {
mtx[0][2] += tm.coef;
mtx[2][0] += tm.coef;
}
else if (tm.deg_y == 1) {
mtx[1][2] += tm.coef;
mtx[2][1] += tm.coef;
}
else {
mtx[2][2] += tm.coef;
}
}
}
mtx[0][1] /= 2;
mtx[1][0] /= 2;
mtx[0][2] /= 2;
mtx[2][0] /= 2;
mtx[1][2] /= 2;
mtx[2][1] /= 2;
}
void Curve::calcInvariants() {
Det = mtx[0][0] * mtx[1][1] * mtx[2][2] + 2 * mtx[0][1] * mtx[1][2] * mtx[0][2] -
mtx[0][2] * mtx[1][1] * mtx[0][2] - mtx[1][2] * mtx[1][2] * mtx[0][0] -
mtx[0][1] * mtx[0][1] * mtx[2][2];
D = mtx[0][0] * mtx[1][1] - mtx[0][1] * mtx[0][1];
I = mtx[0][0] + mtx[1][1];
B = mtx[0][0] * mtx[2][2] - mtx[0][2] * mtx[0][2] +
mtx[1][1] * mtx[2][2] - mtx[1][2] * mtx[1][2];
}
#define ABS(a) ((a) < 0 ? -(a) : (a))
void Curve::calcOwnValues() {
double Discr = I * I - 4 * D;
if (Discr < 0)
throw QString("Curve: calcOwnValues: error calculatin own values!");
L1 = (I + sqrt(Discr)) / 2;
L2 = (I - sqrt(Discr)) / 2;
// нумерование
auto swap_d = [](double & v1, double &v2) {
double tm = v1;
v1 = v2;
v2 = tm;
};
if (D > 0) {
// элиптический тип
if (ABS(L2) < ABS(L1))
swap_d(L1, L2);
}
else if (D < 0) {
// гиперболический тип
if (Det != 0) {
if (L1 * Det <= 0)
swap_d(L1, L2);
}
else {
if (L1 <= 0)
swap_d(L1, L2);
}
}
else {
// параболический тип
if (L1 != 0)
swap_d(L1, L2);
}
}
void Curve::calcTypeCurve() {
if (Det != 0) {
if (D != 0) {
if ((D > 0) && (Det * I < 0))
typeCurve = "Эллипс";
else if ((D > 0) && (Det * I > 0))
typeCurve = "Мнимый эллипс";
else if (D < 0)
typeCurve = "Гипербола";
}
else {
typeCurve = "Парабола";
}
}
else {
if (D > 0)
typeCurve = "Вещественная точка на пересечении двух прямых";
else if (D < 0)
typeCurve = "Пара вещественных пересекающихся прямых";
else {
if (B < 0)
typeCurve = "Пара вещественных параллельных прямых";
else if (B == 0)
typeCurve = "Одна вещественная прямая";
else
typeCurve = "Пара мнимых параллельных прямых";
}
}
}
void Curve::calcCanonicalView() {
if (D > 0) {
// эллиптический тип
if (I * Det < 0) {
// эллипс
double a2 = -Det / (L1 * D);
double b2 = -Det / (L2 * D);
canonicalView = QString("x^2/") + QString::number(a2) +
" + y^2/" + QString::number(b2) + " = 1";
}
else if (I * Det > 0) {
// мнимый эллипс
double a2 = Det / (L1 * D);
double b2 = Det / (L2 * D);
canonicalView = QString("x^2/") + QString::number(a2) +
" + y^2/" + QString::number(b2) + " = -1";
}
else if (Det == 0) {
// пара мнимых пересек прямых
canonicalView = QString("x^2/") + QString::number(1 / ABS(L1)) +
" + y^2/" + QString::number(1 / ABS(L2)) + " = 0";
}
}
else if (D < 0) {
// ниперболический тип
if (Det != 0) {
// гипербола
double a2 = -Det / (L1 * D);
double b2 = Det / (L2 * D);
canonicalView = QString("x^2/") + QString::number(a2) +
" - y^2/" + QString::number(b2) + " = 1";
}
else {
// пара пересекающихся прямых
canonicalView = QString("x^2/") + QString::number(1 / L1) +
" - y^2/" + QString::number(-1 / L2) + " = 0";
}
}
else {
if (Det != 0) {
//парабола
double p = sqrt(-Det / pow(I, 3));
canonicalView = QString("y^2 = ") + QString::number(2 * p) + "x";
}
else if (B < 0) {
// пара параллельных прямых
double b2 = -B / pow(I, 2);
canonicalView = QString("y^2");
if (-b2 >= 0)
canonicalView += " + ";
canonicalView += QString::number(-b2) + " = 0";
}
else if (B > 0) {
// уравнение пары мнимых параллельных
double b2 = B / pow(I, 2);
canonicalView = QString("y^2");
if (b2 >= 0)
canonicalView += " + ";
canonicalView += QString::number(b2) + " = 0";
}
else if (B == 0) {
// пара совпадающих прямых
canonicalView = "y^2 = 0";
}
}
}
void Curve::calcRotateAngle() {
if ((mtx[0][1] != 0) || (mtx[0][0] != L1)) {
double cos_f = mtx[0][1] / sqrt(pow(L1 - mtx[0][0], 2) + pow(mtx[0][1], 2));
double sin_f = (L1 - mtx[0][0]) / sqrt(pow(L1 - mtx[0][0], 2) + pow(mtx[0][1], 2));
rotateAngle = atan2(sin_f, cos_f);
}
else {
rotateAngle = 0;
}
}
//------------|
// public |
//------------|
Curve::Curve()
{
valid = false;
}
Curve::Curve(QString curve, QColor color)
{
this->color = color;
valid = true;
if (curve.simplified().length() == 0) {
valid = false;
return;
}
mtx.resize(3);
mtx.squeeze();
for (int i = 0; i < 3; ++i) {
mtx[i].resize(3);
mtx[i].squeeze();
}
try {
parse(curve);
calcInvariants();
calcOwnValues();
calcTypeCurve();
calcCanonicalView();
calcRotateAngle();
// вырожденность
if (Det == 0)
degeneracy = true;
else
degeneracy = false;
}
catch (...) {
valid = false;
return;
}
coef.x2 = mtx[0][0];
coef.y2 = mtx[1][1];
coef.xy = 2 * mtx[0][1];
coef.x = 2 * mtx[0][2];
coef.y = 2 * mtx[1][2];
coef._1 = mtx[2][2];
//
if (coef.y2 != 0) {
calc_type = ct_y_by_x;
calc = [](double val, const coef_struct & coef) -> QVector<double> {
double D = pow(coef.xy * val + coef.y, 2) -
4 * coef.y2 * (coef.x2 * val * val + coef._1 + coef.x * val);
if (D < 0)
return {};
double res1 = (-coef.xy * val - coef.y + sqrt(D)) / (2 * coef.y2);
double res2 = (-coef.xy * val - coef.y - sqrt(D)) / (2 * coef.y2);
return { res1, res2 };
};
double a = coef.xy * coef.xy - 4 * coef.y2 * coef.x2;
double b = 2 * coef.xy * coef.y - 4 * coef.y2 * coef.x;
double c = coef.y * coef.y - 4 * coef.y2 * coef._1;
if (a == 0) {
if (b != 0) {
double x = -c / b;
QVector<double> y_vec = calc(x, coef);
if (y_vec.size() > 0)
connectionPoints.append(QPointF(x, y_vec[0]));
}
}
else {
double D = b * b - 4 * a * c;
if (D > 0) {
double x1 = (-b + sqrt(D)) / (2 * a);
double x2 = (-b - sqrt(D)) / (2 * a);
double y1 = (-coef.xy * x1 - coef.y) / (2 * coef.y2);
double y2 = (-coef.xy * x2 - coef.y) / (2 * coef.y2);
connectionPoints.append(QPointF(x1, y1));
connectionPoints.append(QPointF(x2, y2));
}
else if (D == 0) {
double x = -b / (2 * a);
double y = (-coef.xy * x - coef.y) / (2 * coef.y2);
connectionPoints.append(QPointF(x, y));
}
}
}
else if (coef.y != 0) {
calc_type = ct_y_by_x;
calc = [](double val, const coef_struct & coef) -> QVector<double> {
double tm = coef.xy * val + coef.y;
if (tm == 0)
return {};
double res = (-coef.x2 * val * val - coef.x * val - coef._1) / tm;
return { res };
};
// вычисление точки разрыва
if (coef.xy != 0) {
breakPoints.append(-coef.y / coef.xy);
}
}
else if (coef.xy != 0) {
calc_type = ct_y_by_x;
calc = [](double val, const coef_struct & coef) -> QVector<double> {
if (val == 0)
return {};
double res = (-coef.x2 * val *val - coef.x * val - coef._1) / (coef.xy * val);
return { res };
};
// точка разрыва
breakPoints.append(0);
}
else if (coef.x2 != 0) {
double D = coef.x * coef.x - 4 * coef.x2 * coef._1;
if (D > 0) {
values_x.append((-coef.x + sqrt(D)) / (2 * coef.x2));
values_x.append((-coef.x - sqrt(D)) / (2 * coef.x2));
}
else if (D == 0) {
values_x.append(-coef.x / (2 * coef.x2));
}
calc_type = ct_x_by_y;
}
else if (coef.x != 0) {
values_x.append(-coef._1 / coef.x);
calc_type = ct_x_by_y;
}
else {
valid = false;
return;
}
//qDebug() << Det;
//qDebug() << D;
//qDebug() << I;
}
void Curve::setColor(QColor n_color) {
color = n_color;
}
QColor Curve::getColor() {
return this->color;
}
int Curve::getTypeFunction() {
return calc_type;
}
QVector<QPointF> Curve::getConnectionPoints() {
return connectionPoints;
}
QVector<double> Curve::getBreakPoints() {
return breakPoints;
}
QVector<double> Curve::calc_func(double val) const {
if (!valid)
return QVector<double>();
if (calc_type == ct_y_by_x) {
return calc(val, coef);
}
else {
return values_x;
}
}
QString Curve::getCurveString() {
if (!valid)
return QString();
// struct coef_struct {
// double x2, y2, xy, x, y, _1;
// } coef;
QString res;
double coefs[6] = { coef.x2, coef.y2, coef.xy, coef.x, coef.y, coef._1 };
QStringList vars = { "x^2", "y^2", "xy", "x", "y", "" };
for (int i = 0; i < 5; i++) {
if (coefs[i] == 1) {
if (res.length() > 0)
res += "+";
res += vars[i];
}
else if (coefs[i] == -1) {
res += QString("-") + vars[i];
}
else if (coefs[i] > 0) {
if (res.length() > 0)
res += "+";
res += QString::number(coefs[i]) + vars[i];
}
else if (coefs[i] < 0) {
res += QString::number(coefs[i]) + vars[i];
}
}
// отдельно для числа
if (coefs[5] != 0) {
if (coefs[5] > 0)
res += "+";
res += QString::number(coefs[5]);
}
res += "=0";
return res;
}
bool Curve::isValid() {
return valid;
}
double Curve::getDet() {
return Det;
}
double Curve::getD(){
return D;
}
double Curve::getI(){
return I;
}
double Curve::getB(){
return B;
}
bool Curve::getDegeneracy() {
return degeneracy;
}
QString Curve::getTypeCurve() {
return typeCurve;
}
QString Curve::getCanonicalView() {
return canonicalView;
}
double Curve::getRotateAngle() {
return rotateAngle;
}
| true |
be00744bc390417ffe7c3d7cf0b9ace0f63ecf30 | C++ | BBBBchan/C_CPP_ACM | /Vjudge/POJ_1004.cpp | UTF-8 | 194 | 2.578125 | 3 | [] | no_license | #include <stdio.h>
int main(int argc, char const *argv[])
{
float sum = 0.0, mon;
for(int i = 0; i < 12; i++){
scanf("%f",&mon);
sum = sum+ mon/12.0;
}
printf("$%.2f", sum);
return 0;
} | true |
cf986876264e0479face00795e516b088f7d41ee | C++ | SirBob01/Dynamo-Engine | /src/Math/Fourier.hpp | UTF-8 | 1,710 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <array>
#include <vector>
#include "../Log/Log.hpp"
#include "../Types.hpp"
#include "../Utils/Bits.hpp"
#include "./Complex.hpp"
namespace Dynamo::Fourier {
/**
* @brief Pre-compute the twiddle factor tables.
*
* @param inverse Forward or inverse transform table.
* @return std::array<Complex, 32>
*/
static std::array<Complex, 32> construct_twiddle_table(b8 inverse) {
std::array<Complex, 32> table;
f32 sign = inverse ? 1 : -1;
for (u32 i = 0; i < 32; i++) {
table[i] = Complex(0, sign * 2 * M_PI / (1 << i)).exp();
}
return table;
}
/**
* @brief Pre-compute twiddle factors for the forward fourier transform.
*
*/
static const std::array<Complex, 32> TWIDDLE_TABLE_FFT =
construct_twiddle_table(false);
/**
* @brief Pre-compute twiddle factors for the inverse fourier transform.
*
*/
static const std::array<Complex, 32> TWIDDLE_TABLE_IFFT =
construct_twiddle_table(true);
/**
* @brief Implementation of the fourier transform algorithm to extract
* the frequency-domain of a time-domain signal in-place.
*
* @param signal Signal buffer.
* @param N Total number of frames (must be a power of 2).
*/
void transform(Complex *signal, u32 N);
/**
* @brief Implementation of the inverse fourier transform algorithm to
* extract the time-domain of a frequency-domain signal in-place.
*
* @param signal Signal buffer.
* @param N Total number of frames (must be a power of 2).
*/
void inverse(Complex *signal, u32 N);
} // namespace Dynamo::Fourier | true |
fb07fbf7d4100f18ce305e84fa3451c7943bface | C++ | TankOs/SFGUI | /include/SFGUI/Window.hpp | UTF-8 | 2,284 | 2.671875 | 3 | [
"Zlib",
"LicenseRef-scancode-public-domain",
"Bitstream-Vera"
] | permissive | #pragma once
#include <SFGUI/Bin.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Window/Mouse.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Vector2.hpp>
#include <memory>
namespace sfg {
/** Window.
*/
class SFGUI_API Window : public Bin {
public:
typedef std::shared_ptr<Window> Ptr; //!< Shared pointer.
typedef std::shared_ptr<const Window> PtrConst; //!< Shared pointer.
enum Style : char {
NO_STYLE = 0, //!< Transparent window.
TITLEBAR = 1 << 0, //!< Titlebar.
BACKGROUND = 1 << 1, //!< Background.
RESIZE = 1 << 2, //!< Resizable.
SHADOW = 1 << 3, //!< Display Shadow.
CLOSE = 1 << 4, //!< Display close button.
TOPLEVEL = TITLEBAR | BACKGROUND | RESIZE //!< Toplevel window.
};
/** Create window.
* @param style Style the Window should have. Defaults to TopLevel.
*/
static Ptr Create( char style = Style::TOPLEVEL );
const std::string& GetName() const override;
/** Set window title.
* @param title Title.
*/
void SetTitle( const sf::String& title );
/** Get window title.
* @return Title.
*/
const sf::String& GetTitle() const;
/** Get client area.
* @return Rect.
*/
sf::FloatRect GetClientRect() const;
/** Set window style.
* Can be a combination of Window::Style values.
* @param style New style.
*/
void SetStyle( char style );
/** Get window style.
* @return Window style.
*/
char GetStyle() const;
/** Check if the window has a specific style.
* @param style Style to check.
* @return true when window has desired style.
*/
bool HasStyle( Style style ) const;
// Signals.
static Signal::SignalID OnCloseButton; //!< Fired when close button is pressed.
protected:
/** Constructor.
* @param style Window style.
*/
Window( char style );
std::unique_ptr<RenderQueue> InvalidateImpl() const override;
sf::Vector2f CalculateRequisition() override;
private:
void HandleSizeChange() override;
void HandleMouseButtonEvent( sf::Mouse::Button button, bool press, int x, int y ) override;
void HandleMouseMoveEvent( int x, int y ) override;
bool HandleAdd( Widget::Ptr child ) override;
sf::Vector2f m_drag_offset;
sf::String m_title;
char m_style;
bool m_dragging;
bool m_resizing;
};
}
| true |
2c595041b4fb0db5f460be2b4a6ee1ee00054303 | C++ | edhaker13/team-indecisive | /TI_Engine/ComponentFactory.cpp | UTF-8 | 2,671 | 2.578125 | 3 | [
"CC-BY-3.0",
"MIT"
] | permissive | #include "ComponentFactory.h"
#include "GameObject.h"
#include "OBJLoader.h"
#include "IResourceManager.h"
#include "Structures.h"
namespace Indecisive
{
IGameObject* ComponentFactory::MakeTestObject()
{
Vertex vertices[] =
{
{ Vector3(-1.0f, 1.0f, 0.0f), Vector3(0.333333f, 0.666667f, -0.666667f), Vector2(-1.0f, 1.0f) },
{ Vector3(1.0f, 1.0f, 0.0f), Vector3(-0.816497f, 0.408248f, -0.408248f), Vector2(1.0f, 1.0f) },
{ Vector3(-1.0f, -1.0f, 0.0f), Vector3(-0.333333f, 0.666667f, 0.666667f), Vector2(-1.0f, -1.0f) },
{ Vector3(1.0f, -1.0f, 0.0f), Vector3(0.816497f, 0.408248f, 0.408248f), Vector2(1.0f, -1.0f) },
};
WORD indices[] =
{
0, 1, 2,
2, 1, 3,
};
// Load graphics from locator
auto pGraphics = static_cast<IGraphics*>(ResourceManagerInstance()->GetService("graphics"));
if (pGraphics == nullptr)
{
TI_LOG_E("Couldn't find a graphics interface.");
throw std::bad_alloc();
}
// Create structures to be used
auto pMesh = new Mesh();
auto pSubObject = new SubObject();
auto pGameObject = new GameObject();
auto pMeshComponent = new MeshComponent(*pMesh);
// Set descriptive variables
pMesh->vertexBuffer = pGraphics->InitVertexBuffer(vertices, 4);
pSubObject->vertexEnd = 4;
pMesh->vertexBufferStride = sizeof(Vertex);
pMesh->vertexBufferOffset = pSubObject->indexStart = 0;
pMesh->indexBuffer = pGraphics->InitIndexBuffer(indices, 6);
pMesh->indexBufferSize = pSubObject->indexSize = 6;
pMesh->indexBufferOffset = 0;
Texture* none = nullptr;
// Load default `none` texture
if (ResourceManagerInstance()->AddTexture("WhiteTex.dds"))
{
none = ResourceManagerInstance()->GetTexture("WhiteTex.dds");
}
else
{
TI_LOG_W("No default texture loaded.");
}
// Set textures to object
pSubObject->ambientTexture = none;
pSubObject->diffuseTexture = none;
pSubObject->specularTexture = none;
// Assemble Object
pMeshComponent->AddGroup(pSubObject);
pGameObject->AddDrawable(pMeshComponent);
return pGameObject;
}
IGameObject* ComponentFactory::MakeObjectFromObj(const std::string& filename)
{
// Load default `none` texture
if (!ResourceManagerInstance()->AddTexture("WhiteTex.dds"))
{
TI_LOG_W("No default texture loaded.");
}
// Load Obj file
auto ObjLoader = OBJLoader();
ObjLoader.Load(filename);
auto pMeshComponent = ObjLoader.ConstructFromMesh(filename);
if (pMeshComponent != nullptr)
{
// Assemble object if mesh is valid
auto pGameObject = new GameObject();
pGameObject->AddDrawable(pMeshComponent);
return pGameObject;
}
TI_LOG_E("OBJLoader didn't return any mesh from : " + filename);
return nullptr;
}
} | true |
0a38d468260ba20d707149f315a7f8aec763eff1 | C++ | JuantAldea/clever | /src/clever/benchmark/clever_benchmarks.h | UTF-8 | 856 | 2.53125 | 3 | [] | no_license | //
// Copyright Thomas Hauth, Danilo Piparo 2012
//
// Distributed under 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)
//
#pragma once
#include <gtest/gtest.h>
#include "../clever.hpp"
TEST( clever_benchmarks, benchmark_floatingpoint )
{
size_t vector_size = 10;
clever::context context;
typedef clever::vector<double,1> Vector;
std::vector < double > arr( vector_size , 1.0);
Vector m1 ( arr, vector_size, context );
double d2 = 23.0f;
KERNEL_CLASS( add_val,
__kernel void add_val( __global double * a, const double b )
{
a[ get_global_id( 0 ) ] += b;
},
cl_mem, double
) ( context );
// run kernel
add_val.run( m1.range(), m1.get_mem(), d2 );
// get result
m1.to_array( arr );
for ( auto v : arr)
{
ASSERT_FLOAT_EQ( d2 + 1, v );
}
}
| true |
4e9be3835a231e5de52d9692ba1b62e15f3a6e2f | C++ | ssliuyi/ACMCode | /LeetCode/Set Matrix Zeroes.cpp | UTF-8 | 2,216 | 3.078125 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: Set Matrix Zeroes.cpp
*
* Description: LeetCode
*
* Version: 1.0
* Created: 03/31/2014 01:54:30 PM
* Revision: none
* Compiler: gcc
*
* Author: LiuYi (), swliuyi@gamil.com
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
bool firstline = 0;
bool firstcol = 0;
for( int i = 0 ; i < matrix[0].size() ; i++ )
{
if( matrix[0][i] == 0 )
{
firstline = 1;
}
}
for( int i = 0 ; i < matrix.size() ; i++ )
{
if( matrix[i][0] == 0 )
{
firstcol = 1;
}
}
for( int i = 1 ; i < matrix.size() ; i++ )
{
for( int j = 1 ; j < matrix[0].size() ; j++ )
{
if( matrix[i][j] == 0 )
{
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for( int i = 1 ; i < matrix[0].size() ; i++ )
{
if( matrix[0][i] == 0 )
{
for( int j = 1 ; j < matrix.size() ; j++ )
{
matrix[j][i] = 0;
}
}
}
for( int i = 1 ; i < matrix.size() ; i++ )
{
if( matrix[i][0] == 0 )
{
for( int j = 1 ; j < matrix[0].size() ; j++ )
{
matrix[i][j] = 0;
}
}
}
if( firstline == 1 )
{
for( int i = 0 ; i < matrix[0].size() ; i++ )
{
matrix[0][i] = 0;
}
}
if(firstcol == 1)
{
for( int i = 0 ; i < matrix.size() ; i++ )
{
matrix[i][0] = 0;
}
}
}
};
| true |
cf81c1f749df8dd6362a67e92ee567b466b2262e | C++ | Allexin/TrackYourTimeSimpleServer | /TrackYourTimeSimpleServer/main.cpp | UTF-8 | 997 | 2.71875 | 3 | [] | no_license | #include <QCoreApplication>
#include <QDebug>
#include "cudptofileserver.h"
int main(int argc, char *argv[])
{
QString outputFileName;
QString stateFileName;
qDebug() << "available arguments: ";
qDebug() << "-output <fileName> - CSV table output";
qDebug() << "-state <fileName> - current state of all available connections";
for (int i = 1; i<argc-1; i++){
QString arg = argv[i];
if (arg=="-output")
outputFileName = argv[i+1];
if (arg=="-state")
stateFileName = argv[i+1];
}
if (outputFileName.isEmpty()){
outputFileName = "output.csv";
qDebug() << "output file name(-output) not set - using default name " << outputFileName;
}
if (stateFileName.isEmpty()){
qDebug() << "state file name(-state) not set - state saving disabled";
}
QCoreApplication a(argc, argv);
cUDPtoFileServer server(outputFileName,stateFileName);
int result = a.exec();
return result;
}
| true |
15a52f2930ae206e17b9686588e074861a895526 | C++ | jawwadmateen/OOP-concepts | /diamond problem.cpp | UTF-8 | 1,054 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class book
{
private:
string name;
public:
book(string a)
{
name=a;
}
void display()
{
cout<<"Name of book is "<<name<<endl;
}
};
class genre:virtual public book
{
private:
int nop;
public:
genre(string a,int b):book(a)
{
nop=b;
}
void display()
{
book::display();
cout<<"number of pages "<<nop<<endl;
}
};
class popu:virtual public book
{
private:
string rb;
public:
popu(string a,string c):book(a)
{
rb=c;
}
void display()
{
book::display();
cout<<"reviewed by "<<rb<<endl;
}
};
class specs:public genre,public popu
{
private:
int ncs;
public:
specs(string a,int b,string c,int d):book(a),popu(a,c),genre(a,b)
{
ncs=d;
}
void display()
{
cout<<"Name of Book "<<name<<endl;
cout<<"Number of pages "<<nop<<endl;
cout<<"Reviewed By "<<rb<<endl;
cout<<"Number of copies sold "<<noc<<endl;
}
};
int main()
{
specs s1("Sherlock",900,"Henry",98000);
s1.display();
}
| true |
107dcbef4429a88ae261c66a1c137079d661a34c | C++ | Jakelyny/Algoritmos_I-II_ | /Algoritmos I/038.cpp | ISO-8859-1 | 918 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
/* Um banco conceder um crdito especial aos seus clientes, varivel com o saldo mdio no ltimo ano.
Faa um algoritmo que leia o saldo mdio de um cliente e calcule o valor do crdito de acordo com a tabela
abaixo. Mostre uma mensagem informando o saldo mdio e o valor do crdito.*/
main(){
setlocale(LC_ALL, "Portuguese");
double saldoMedio, valorCredito;
cout<<" Digite seu saldo mdio: ";
cin>>saldoMedio;
if(saldoMedio >= 0 && saldoMedio <= 200)
valorCredito = 0;
if(saldoMedio >= 201 && saldoMedio <= 400)
valorCredito = saldoMedio * 0.2;
if(saldoMedio >=401 && saldoMedio <= 600)
valorCredito = saldoMedio * 0.3;
if(saldoMedio >= 601)
valorCredito = saldoMedio * 0.4;
cout<<"\n\tSaldo mdio: "<<saldoMedio<<endl;
cout<<"\tValor do crdito: "<<valorCredito<<"\n\n"<<endl;
}
| true |
e3d37ac36f86182bcc20f4d99683849788eeed9b | C++ | umar-07/Competitive-Programming-questions-with-solutions | /oops_2/main.cpp | UTF-8 | 321 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Human
{
public:
int age;
Human(int age)
{
this->age=age;
}
void display()
{
cout << age << endl;
cout << "1";
cout << this->age << endl;
}
};
int main()
{
Human anil(27);
anil.display();
return 0;
}
| true |
182d88639c84e2b96f925a49b1e4dfe32a4b9b6f | C++ | yuzele/Bsortrank | /Bsortrank/源.cpp | GB18030 | 2,203 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include<iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
BOOL GetIpByDomainName(char *szHost, char* szIp)
{
WSADATA wsaData;
HOSTENT *pHostEnt;
int nAdapter = 0;
struct sockaddr_in sAddr;
if (WSAStartup(0x0101, &wsaData))
{
printf(" gethostbyname error for host:\n");
return FALSE;
}
pHostEnt = gethostbyname(szHost);
if (pHostEnt)
{
if (pHostEnt->h_addr_list[nAdapter])
{
memcpy(&sAddr.sin_addr.s_addr, pHostEnt->h_addr_list[nAdapter], pHostEnt->h_length);
sprintf(szIp, "%s", inet_ntoa(sAddr.sin_addr));
}
}
else
{
// DWORD dwError = GetLastError();
// CString csError;
// csError.Format("%d", dwError);
}
WSACleanup();
return TRUE;
}
void sendGetRequest()
{
//ʼsocketʼ;
WSADATA wData;
::WSAStartup(MAKEWORD(2, 2), &wData);
SOCKET clientSocket = socket(AF_INET, 1, 0);
struct sockaddr_in ServerAddr = { 0 };
int Ret = 0;
int AddrLen = 0;
HANDLE hThread = 0;
char addIp[256] = { 0 };
GetIpByDomainName("www.csdn.net", addIp);
char *pHttpGet = "GET %s HTTP/1.1\r\n"
"Host: %s:%d\r\n\r\n";
char* addr = "https://www.csdn.net";
char* host = addIp;
int post = 80;
char bufSend[1024] = { 0 };
sprintf(bufSend, pHttpGet, addr, host, post);
ServerAddr.sin_addr.s_addr = inet_addr(addIp);
ServerAddr.sin_port = htons(80);;
ServerAddr.sin_family = AF_INET;
char bufRecv[3069] = { 0 };
int errNo = 0;
errNo = connect(clientSocket, (sockaddr*)&ServerAddr, sizeof(ServerAddr));
if (errNo == 0)
{
//ͳɹطͳɹֽ;
if (send(clientSocket, bufSend, strlen(bufSend), 0) > 0)
{
cout << "ͳɹ\n";;
}
//ܳɹؽֽܵ;
while (1)
{
if (recv(clientSocket, bufRecv, 3069, 0) > 0)
{
cout << "ܵ:" << bufRecv << endl;
}
else break;
}
}
else
{
errNo = WSAGetLastError();
}
//socket;
::WSACleanup();
}
int main()
{
sendGetRequest();
system("pause");
return 0;
} | true |
d5c55bf85df1fb9eac966ddc40bae0ba8a5c7ea2 | C++ | Marcel129/Uklad_rownan_liniowych | /zad3-zalazek/inc/Wektor.hh | UTF-8 | 1,819 | 3.359375 | 3 | [] | no_license |
#ifndef WEKTOR_HH
#define WEKTOR_HH
#include "rozmiar.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
class Wektor
{
double tablica[ROZMIAR];
public:
Wektor(){};
Wektor(double moja_tab[])
{
for (int i = 0; i < ROZMIAR; i++)
tablica[i] = moja_tab[i];
}
const double &operator[](int ind) const //get
{
if (ind < 0 || ind > ROZMIAR)
{
std::cout << ind << std::endl;
std::cerr << "Przekroczenie zakresu" << std::endl;
exit(1);
}
return tablica[ind];
}
double &operator[](int ind) //set
{
if (ind < 0 || ind > ROZMIAR)
{
std::cout << ind << std::endl;
std::cerr << "Przekroczenie zakresu" << std::endl;
exit(1);
}
return tablica[ind];
}
Wektor operator*(double mnoznik)//mnozenie wektora przez liczbe
{
Wektor W(tablica);
for (int i = 0; i < ROZMIAR; ++i)
W.tablica[i] *= mnoznik;
return W;
}
Wektor operator/(double dzielnik)//dzielenie wektora przez liczbe
{
Wektor W(tablica);
if (dzielnik != 0)
{
for (int i = 0; i < ROZMIAR; ++i)
W.tablica[i] /= dzielnik;
}
else
{
std::cout << "Błąd:dzielenie przez 0" << std::endl;
exit(1);
}
return W;
}
Wektor operator+(const Wektor &W2) //dodawanie dwoch wektorow
{
Wektor W(tablica);
for (int i = 0; i < ROZMIAR; ++i)
W.tablica[i] += W2.tablica[i];
return W;
}
Wektor operator-(const Wektor &W2) //odejmowanie dwoch wektorow
{
Wektor W(tablica);
for (int i = 0; i < ROZMIAR; ++i)
W.tablica[i] -= W2.tablica[i];
return W;
}
};
double dlugosc_wektora(const Wektor W);
std::istream &operator>>(std::istream &Strm, Wektor &W);
std::ostream &operator<<(std::ostream &Strm, const Wektor &W);
#endif
| true |
82b955174e1db691cad80d904675da9fbf9dd725 | C++ | ajmd17/apex-engine | /ApexEngineV2/math/vector4.h | UTF-8 | 2,514 | 3.015625 | 3 | [
"MIT"
] | permissive | #ifndef VECTOR4_H
#define VECTOR4_H
#include <cmath>
#include <iostream>
#include "matrix4.h"
namespace apex {
class Vector3;
class Vector4 {
friend std::ostream &operator<<(std::ostream &out, const Vector4 &vec);
public:
float x, y, z, w;
Vector4();
Vector4(float x, float y, float z, float w);
Vector4(float xyzw);
Vector4(const Vector4 &other);
inline float GetX() const { return x; }
inline float &GetX() { return x; }
inline void SetX(float x) { this->x = x; }
inline float GetY() const { return y; }
inline float &GetY() { return y; }
inline void SetY(float y) { this->y = y; }
inline float GetZ() const { return z; }
inline float &GetZ() { return z; }
inline void SetZ(float z) { this->z = z; }
inline float GetW() const { return w; }
inline float &GetW() { return w; }
inline void SetW(float w) { this->w = w; }
Vector4 &operator=(const Vector4 &other);
Vector4 operator+(const Vector4 &other) const;
Vector4 &operator+=(const Vector4 &other);
Vector4 operator-(const Vector4 &other) const;
Vector4 &operator-=(const Vector4 &other);
Vector4 operator*(const Vector4 &other) const;
Vector4 &operator*=(const Vector4 &other);
Vector4 operator*(const Matrix4 &mat) const;
Vector4 &operator*=(const Matrix4 &mat);
Vector4 operator/(const Vector4 &other) const;
Vector4 &operator/=(const Vector4 &other);
bool operator==(const Vector4 &other) const;
bool operator!=(const Vector4 &other) const;
float Length() const;
float LengthSquared() const;
float DistanceSquared(const Vector4 &other) const;
float Distance(const Vector4 &other) const;
Vector4 &Normalize();
Vector4 &Rotate(const Vector3 &axis, float radians);
Vector4 &Lerp(const Vector4 &to, const float amt);
float Dot(const Vector4 &other) const;
static Vector4 Abs(const Vector4 &);
static Vector4 Round(const Vector4 &);
static Vector4 Clamp(const Vector4 &, float min, float max);
static Vector4 Min(const Vector4 &a, const Vector4 &b);
static Vector4 Max(const Vector4 &a, const Vector4 &b);
static Vector4 Zero();
static Vector4 One();
static Vector4 UnitX();
static Vector4 UnitY();
static Vector4 UnitZ();
static Vector4 UnitW();
inline HashCode GetHashCode() const
{
HashCode hc;
hc.Add(x);
hc.Add(y);
hc.Add(z);
hc.Add(w);
return hc;
}
};
} // namespace apex
#endif
| true |
da9c6bb8254c1436960fed85427143aef1731e80 | C++ | mattdude2489/Time-Warrior | /Team BMP/SDL_SplashScreen.h | UTF-8 | 1,498 | 2.734375 | 3 | [] | no_license | #ifndef _SDL_SPLASHSCREEN_H_
#define _SDL_SPLASHSCREEN_H_
#include "Global.h"
#include "SDL_Resource.h"
#include "SDL_Sprite.h"
#include "sdl\SDL.h"
#include <assert.h>
class SDL_SplashScreen : public SDL_Resource {
protected:
/** x coordinate to draw the splash screen to, centered for screen surface */
Sint32 m_iCenterX;
/** y coordinate to draw the splash screen to, centered for screen surface */
Sint32 m_iCenterY;
/** amount of time splash screen will be shown */
Uint32 m_uiSpeed;
/** pointer to the screen surface to draw to */
SDL_Surface * m_pvScreen;
/** sprite for animation-based splash screen */
SDL_Sprite * m_pvSprite;
public:
/** default constructor */
SDL_SplashScreen();
/** deconstructor */
~SDL_SplashScreen();
/** setSprite - sets the splash sprite to the given reference */
void setSprite(SDL_Sprite * a_pvSprite);
/** setSpeed - sets the speed of the splash screen transition to the specified */
void setSpeed(const Uint32 & a_kruiSpeed);
/** setScreen - sets the screen to draw to the specified screen surface */
void setScreen(SDL_Surface * a_pvScreen);
/** getSprite - returns a constant reference of the sprite the splash screen uses */
const SDL_Sprite * getSprite() const;
/** getSpeed - returns amount of time splash screen will be shown */
const Uint32 & getSpeed() const;
/** activate - draws splash screen to the screen, and sets as unchanged */
virtual void activate();
};
#endif
| true |
e63a7ff5a1ab978a183cd25e1589ccc481c5a339 | C++ | kamil-s-kaczor/Group_of_Figures | /Group_of_Figures/Circle.cpp | UTF-8 | 574 | 2.984375 | 3 | [] | no_license | #include "pch.h"
#include <cmath>
#include "Circle.h"
#include "Figure.h"
const double pi = std::acos(-1);
Circle::Circle(Point const& a, double const& radius)
{
this->set_Figure_type(0);
this->center = a;
this->radius = radius;
}
bool Circle::operator==(Circle const& a) const noexcept
{
if (this->center == a.center)
{
if (this->radius == a.radius)
{
return true;
};
};
return false;
}
double Circle::get_field() const
{
return pi * radius* radius;
}
double Circle::get_perimeter() const
{
return 2 * radius * pi;
} | true |
659ea1e139ce0c1daa73886a387cb7cddec33054 | C++ | NortonGitHub/Creation_of_dungeon | /CreationOfDungeon_master/cd_666s/TilebaseAI/ParameterEffecter.h | SHIFT_JIS | 778 | 2.640625 | 3 | [] | no_license | #pragma once
#include "../../Vector2D.h"
class BattleParameter;
class ParameterEffecter
{
public:
ParameterEffecter(int continuousTime, bool isPositive);
~ParameterEffecter();
//Ԍo
void UpdateCounter();
//ljʂLǂ
bool IsEnable() const { return _time < _affectionTime; }
bool IsPositive() const { return _isPositive; }
//ΏۂɌʂt^
virtual void AffectParameter(BattleParameter& param) = 0 {};
// MEMO : ot̕\@܂܂ł̃fobO\
virtual void DrawEffecter(Vector2D anchorPos) = 0 {};
private:
int _time;
int _affectionTime;
//otfot
bool _isPositive;
//ʂ\ACR
//Sprite _icon;
};
| true |
751bb19ca11e3112887160dccfa010eca6f9f62c | C++ | kubamaruszczyk1604/HFRPlayer | /HFRPlayer/ExperimentSocketManager.cpp | UTF-8 | 536 | 2.640625 | 3 | [] | no_license | #include "ExperimentSocketManager.h"
using namespace Networking;
// initialsie static fields
SocketConnection* ExperimentSocketManager::s_serverSocket = nullptr;
std::vector<ExperimentSocketStream*> ExperimentSocketManager::s_activeSockets = {};
std::thread* ExperimentSocketManager::s_acceptThread = nullptr;
void ExperimentSocketManager::acceptLoop()
{
while (true)
{
auto socket = s_serverSocket->accept();
if (socket)
{
s_activeSockets.push_back(new ExperimentSocketStream(socket));
}
else
{
return;
}
}
}
| true |
128837ec2a8885f87901d7a458fecabd83bb63a3 | C++ | yongjianmu/leetcode | /second/145_Binary_Tree_Postorder_Traversal/sol.cpp | UTF-8 | 813 | 3.09375 | 3 | [] | no_license | #include "../include/header.h"
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
if(NULL == root)
{
return ret;
}
stack<TreeNode*> st1, st2;
st1.push(root);
while(!st1.empty())
{
TreeNode* node = st1.top();
st1.pop();
//st2.push(node);
ret.insert(ret.begin(), node->val);
if(NULL != node->left)
{
st1.push(node->left);
}
if(NULL != node->right)
{
st1.push(node->right);
}
}
//while(!st2.empty())
//{
// ret.push_back(st2.top()->val);
// st2.pop();
//}
return ret;
}
};
| true |
d463fcff23c797bdb9732c53e76e97beeacb4f34 | C++ | hpointu/e3e | /src/e3e/Matrix4fStack.cpp | UTF-8 | 709 | 3 | 3 | [] | no_license | #include "Matrix4fStack.hpp"
e3e::Matrix4fStack::Matrix4fStack()
{
push();
}
void e3e::Matrix4fStack::push()
{
e3e::Matrix4f *toPush = isEmpty() ? new e3e::Matrix4f() : new e3e::Matrix4f(*top());
data.push_back(toPush);
}
void e3e::Matrix4fStack::pop()
{
if(!isEmpty())
{
e3e::Matrix4f *b = data.back();
data.pop_back();
delete b;
}
}
void e3e::Matrix4fStack::translate(float x, float y, float z)
{
e3e::Matrix4f t = e3e::Matrix4f::translation(x, y, z);
(*top()) *= t;
}
void e3e::Matrix4fStack::replace(const Matrix4f &newTransformation)
{
(*top()) = e3e::Matrix4f(newTransformation);
}
void e3e::Matrix4fStack::transform(const Matrix4f &transformation)
{
(*top()) *= transformation;
}
| true |
faac9ea4437d9a236f2631634a6ec588ea4616bb | C++ | Tduderocks/PracticeProblems | /Ch_8/Ch8_Rev9and10.cpp | UTF-8 | 1,147 | 4.03125 | 4 | [] | no_license | //chapter 8 review 9 and 10 works and works :) done:)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string Reverse (string phrase)
//reverses a string using arrays
{
string word;
for(int Letter = phrase.length()-1; Letter>=0; Letter --){
word+=phrase[Letter];
}
return(word);
}
string Uppercase(string S)
//determines if strings are the same regaurdless of case
{
for(int Letter=0; Letter<S.length(); Letter++){
if ((S[Letter]>='a')&&(S[Letter]<='z')){
S[Letter] = S[Letter] - 'a' + 'A';
}
}
return(S);
}
bool isPalendrom(string word)
//determines if something is a palidrome
{
string reversed = Reverse(word);
if(Uppercase(word)==word){
word = Uppercase(word);
}
return Uppercase(word) == Uppercase(reversed);
}
int main()
//calls function
{
string phrase;
cout << "Enter a word to be reversed: ";
cin >> phrase;
// cout << Reverse(phrase);
if(isPalendrom(phrase)){
cout << phrase << " is a palendrome";
}
else{
cout << phrase << " is not a palendrome";
}
return(0);
} | true |
05bcba98c30cee71c0e32f6f0fbff4e069306a0a | C++ | ernestchu/cse391-object-oriented-programming | /Assignments/hw4/src/lib/Lexer.cpp | UTF-8 | 3,011 | 3.171875 | 3 | [] | no_license | //
// Lexer.cpp
// hw4
//
// Created by Ernest Chu on 2020/11/18.
//
#include "Lexer.h"
int Lexer::line = 1;
void Lexer::reserve(const Word& w) {
words.insert({w.lexeme, w});
}
Lexer::Lexer(std::string target) : target(target) {
target_stream.open(target, std::ifstream::in);
reserve(*new Word("if", Tag::IF));
reserve(*new Word("else", Tag::ELSE));
reserve(*new Word("while", Tag::WHILE));
reserve(*new Word("do", Tag::DO));
reserve(*new Word("break", Tag::BREAK));
reserve(Word::True);
reserve(Word::False);
reserve(Type::Int);
reserve(Type::Char);
reserve(Type::Bool);
reserve(Type::Float);
}
void Lexer::readch() {
int i = target_stream.get();
if (i != -1)
peek = (char) i;
else {
std::cout << "End of file reached\n";
exit(0);
}
}
bool Lexer::readch(char c) {
readch();
if (peek != c)
return false;
peek = ' ';
return true;
}
const Token& Lexer::scan() {
for (;; readch()) {
if (peek == ' ' || peek == '\t')
continue;
else if (peek == '\n')
line += 1;
else
break;
}
switch (peek) {
case '&':
if (readch('&'))
return Word::and_;
else
return *new Token('&');
case '|':
if (readch('|'))
return Word::or_;
else
return *new Token('|');
case '=':
if (readch('='))
return Word::eq;
else
return *new Token('=');
case '!':
if (readch('!'))
return Word::ne;
else
return *new Token('!');
case '<':
if (readch('<'))
return Word::le;
else
return *new Token('<');
case '>':
if (readch('>'))
return Word::ge;
else
return *new Token('>');
}
//read numbers
if (isdigit(peek)) {
int v = 0;
do {
v = 10*v + peek-48;
readch();
} while (isdigit(peek));
if (peek != '.')
return *new Num(v);
float x = v;
float d = 10;
while (true) {
readch();
if (!isdigit(peek))
break;
x += (peek-48)/d;
d *= 10;
}
return *new Real(x);
}
//read variable name
if (isalpha(peek)) {
std::string s = "";
do {
s.push_back(peek);
readch();
} while (isdigit(peek) || isalpha(peek) || peek=='_');
try {
Word& w = words.at(s);
return w;
}
catch (const std::out_of_range& e) {
Word& word = *new Word(s, Tag::ID);
words.insert({s, word});
return word;
}
}
Token& tok = *new Token(peek);
peek = ' ';
return tok;
}
| true |
90bdac4a0146513a6e8410aee2f7dac9895d167e | C++ | chiku/cmatrix | /src/impl/matrix/populators.cpp | UTF-8 | 370 | 2.71875 | 3 | [
"MIT"
] | permissive | // Written by : Chirantan Mitra
namespace cmatrix
{
template <class Type>
void Matrix<Type>::fillWith(Type value)
{
for (long int i = 0; i < rows(); i++) {
for (long int j = 0; j < columns(); j++) {
access(i, j) = value;
}
}
}
template <class Type>
inline void Matrix<Type>::fillWithZeros()
{
fillWith(0);
}
} // namespace cmatrix
| true |
bb8c6dba1322d200256078bbcda311fd80526f37 | C++ | Floating-light/datastruct | /leetcode/Array/MaxSubarray/maxSubarray.cpp | UTF-8 | 2,147 | 3.71875 | 4 | [] | no_license | // 53. Maximum Subarray
// tags: Array, Divide and Conquer
#include <vector>
#include <limits>
#include <iostream>
using namespace std;
class Solution {
void findMax(const vector<int>& nums, int head, int& realMax)
{
if(head > nums.size()) return ;
int currentSum = 0;
for(int i = head; i < nums.size(); ++i)
{
currentSum += nums[i];
if( realMax < currentSum) realMax = currentSum;
}
findMax(nums, head+1, realMax);
}
public:
int maxSubArray(vector<int>& nums) {
int realMax = std::numeric_limits<int>::min();
findMax(nums, 0, realMax);
return realMax;
}
};
class Solution2 {
public:
int maxSubArray(vector<int>& nums) {
int realMax = std::numeric_limits<int>::min();
for(int i = 0; i < nums.size(); ++i)
{
int currentSum = 0;
for(int j = i; j < nums.size(); ++j)
{
currentSum += nums[j];
if(currentSum > realMax) realMax = currentSum;
}
}
return realMax;
}
};
// greed
class Solution3 {
public:
int maxSubArray(vector<int>& nums)
{
if(nums.size() < 1) return std::numeric_limits<int>::min();
int currentSum = nums[0];
int realMax = nums[0];
for ( int i = 1; i < nums.size(); ++i)
{
currentSum = max(currentSum + nums[i], nums[i]);
realMax = max(currentSum, realMax);
}
return realMax;
}
};
//dynamic pragramme
class Solution3 {
public:
int maxSubArray(vector<int>& nums)
{
if(nums.size() < 1) return std::numeric_limits<int>::min();
int realMax = nums[0];
for(int i = 1; i < nums.size(); ++i)
{
if(nums[i - 1] > 0) nums[i] += nums[i - 1];
realMax = std::max(realMax, nums[i]);
}
return realMax;
}
};
int main()
{
vector<int> input {-2,1,-3,4,-1,2,1,-5,4};
int res = Solution().maxSubArray(input);
std::cout << res << std::endl;
} | true |
af0269281eb6dee353adb06912ba730727d71281 | C++ | 7princekumar/competitive_coding | /coding_ninjas/prerequisites/evenAndOddIndexes.cpp | UTF-8 | 557 | 3.125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define N 100005
int get_esum(int* a, int n){
int esum = 0;
for(int i=0; i<n; i++){
if(i%2 == 0 && a[i]%2 == 0) esum += a[i];
}
return esum;
}
int get_osum(int* a, int n){
int osum = 0;
for(int i=0; i<n; i++){
if(i%2 != 0 && a[i]%2 != 0) osum += a[i];
}
return osum;
}
int main()
{
int n;
cin >> n;
int a[N];
for(int i=0; i<n; i++){
cin >> a[i];
}
cout << get_esum(a, n) << " " << get_osum(a, n) << endl;
return 0;
}
| true |