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
4b3f97696450e1c22a2e06c79d08e35da58d7d48
C++
LasseD/uva
/P143.cpp
UTF-8
4,407
3.1875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <cmath> #include <iomanip> struct Real; typedef std::pair<Real,Real> Point; typedef std::pair<Point,Point> Line; typedef long long ll; #define XX first #define YY second #define p1 first #define p2 second ll gcd(ll a, ll b) { ll c; while(a != 0) { c = a; a = b%a; b = c; } return b; } int sign(ll l) { if(l < 0) return -1; return 1; } struct Real { ll nom, denom; Real() : nom(0), denom(0) {} Real(ll i) : nom(i), denom(1) {} Real(ll nom, ll denom) : nom(sign(denom)*nom), denom(std::abs(denom)) {} Real(const std::string &rep) { nom = 0; denom = 1; char c; unsigned int i = 0; while(((c = rep[i]) != '.') && i < rep.size()) { nom = 10*nom + (c-'0'); ++i; } ++i; while(i < rep.size()) { nom = 10*nom + (rep[i]-'0'); denom*=10; ++i; } } Real operator*(const Real &b) const { return Real(nom*b.nom, denom*b.denom); } Real operator+(const Real &b) const { return Real(nom*b.denom+b.nom*denom, denom*b.denom); } Real operator-(const Real &b) const { return Real(nom*b.denom-b.nom*denom, denom*b.denom); } Real operator/(const Real &b) const { return Real(nom*b.denom, denom*b.nom); } bool operator==(const Real &b) const { return nom*b.denom == denom*b.nom; } bool operator<(const Real &b) const { return nom*b.denom < b.nom*denom; } bool operator>(const Real &b) const { return nom*b.denom > denom*b.nom; } bool operator<=(const Real &b) const { return nom*b.denom <= denom*b.nom; } bool operator>=(const Real &b) const { return nom*b.denom >= denom*b.nom; } bool operator<(const ll &b) const { return nom < denom*b; } bool operator>(const ll &b) const { return nom > denom*b; } bool operator<=(const ll &b) const { return nom <= denom*b; } bool operator>=(const ll &b) const { return nom >= denom*b; } bool operator==(const ll &b) const { return nom == b*denom; } Real shorten() const { Real ret(nom,denom); ll g = gcd(nom,denom); ret.nom /= g; ret.denom /= g; return ret; } }; std::ostream& operator<<(std::ostream& os, const Real& b) { os << b.nom << "/" << b.denom; //os << (b.nom/(double)b.denom); return os; } std::ostream& operator<<(std::ostream& os, const Point& b) { os << b.XX << "," << b.YY; return os; } std::ostream& operator<<(std::ostream& os, const Line& b) { os << b.p1 << "->" << b.p2; return os; } Real getX(const Line &l, int y) { if(l.p1.YY == y) return l.p1.XX; if(l.p2.YY == y) return l.p2.XX; Real a = ((l.p2.XX - l.p1.XX) / (l.p2.YY - l.p1.YY)).shorten(); return (l.p1.XX + a*y - a*l.p1.YY).shorten(); } int get(Line *lines) { int res = 0; for(int y = 1; y <= 99; ++y) { Real minX(100); Real maxX(0); for(int i = 0; i < 3; ++i) { Line &l = lines[i]; if(l.p1.YY <= y && l.p2.YY >= y) { if(l.p1.YY == l.p2.YY) { { Real x = l.p1.XX; if(x < minX) { minX = x; } if(x > maxX) { maxX = x; } } { Real x = l.p2.XX; if(x < minX) { minX = x; } if(x > maxX) { maxX = x; } } continue; } // get x Real x = getX(l, y); // update minX, maxX if(x < minX) { minX = x; } if(x > maxX) { maxX = x; } } } if(minX < 1) minX = Real(1); if(maxX > 99) maxX = Real(99); // update res if(maxX >= minX) { int max = maxX.nom / maxX.denom; int min = (minX.nom / minX.denom) + (minX.nom % minX.denom == 0 ? 0 : 1); int add = max-min+1; res += add; } } return res; } int main() { Point points[3]; Line lines[3]; while(true) { bool allZero = true; for(int i = 0; i < 3; ++i) { std::string s; std::cin >> s; points[i].XX = Real(s); if(points[i].XX.nom != 0) allZero = false; std::cin >> s; points[i].YY = Real(s); if(points[i].YY.nom != 0) allZero = false; } if(allZero) return 0; lines[0] = Line(points[0],points[1]); lines[1] = Line(points[1],points[2]); lines[2] = Line(points[2],points[0]); for(int i = 0; i < 3; ++i) { if(lines[i].p1.YY > lines[i].p2.YY) { std::swap(lines[i].p1, lines[i].p2); } } // compute trapped trees: printf("%4i\n", get(lines)); } }
true
4fc994f396182fcacb1ea02cbe7389e06c69eb2e
C++
Tardigrade-nx/Tatanga
/src/sdlutils.cpp
UTF-8
4,278
2.796875
3
[]
no_license
#include <iostream> #include <SDL2/SDL_image.h> #include "sdlutils.h" #include "def.h" #ifdef __SWITCH__ #include "switch.h" #endif //------------------------------------------------------------------------------ // Init SDL bool SDLUtils::Init() { INHIBIT(std::cout << "SDLUtils::Init()" << std::endl;) // Initialize romfs #ifdef __SWITCH__ romfsInit(); #endif // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl; return false; } // Intialize SDL_image int flags = IMG_INIT_PNG; if ((IMG_Init(flags) & flags) != flags) { std::cerr << "SDL_image could not initialize! IMG_GetError: " << IMG_GetError() << std::endl; return false; } // Initialize joystick INHIBIT(std::cout << "SDL_NumJoysticks: '" << SDL_NumJoysticks() << "'" << std::endl;) if (SDL_NumJoysticks() >= 1) { g_joystick = SDL_JoystickOpen(0); if (g_joystick == NULL) { std::cerr << "Unable to open joystick." << std::endl; return false; } INHIBIT(std::cout << "SDL_JoystickOpen OK" << std::endl;) } // Create window #ifdef __SWITCH__ g_window = SDL_CreateWindow(APP_NAME, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_FULLSCREEN); #else g_window = SDL_CreateWindow(APP_NAME, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); #endif if (g_window == NULL) { std::cerr << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl; return false; } // Create renderer g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (g_renderer == NULL) { std::cerr << "Renderer could not be created! SDL_Error: " << SDL_GetError() << std::endl; return false; } // Set draw color SDL_SetRenderDrawColor(g_renderer, 0xA0, 0xA0, 0xA0, 0xFF); return true; } //------------------------------------------------------------------------------ // Close SDL void SDLUtils::Close() { INHIBIT(std::cout << "SDLUtils::Close()" << std::endl;) // Textures for (std::map<std::string, SDL_Texture*>::iterator it = g_textures.begin(); it != g_textures.end(); ++it) SDL_DestroyTexture(it->second); // Renderer if (g_renderer != NULL) { SDL_DestroyRenderer(g_renderer); g_renderer = NULL; } // Window if (g_window != NULL) { SDL_DestroyWindow(g_window); g_window = NULL; } // Joystick if (g_joystick != NULL) { SDL_JoystickClose(g_joystick); g_joystick = NULL; } // SDL_image IMG_Quit(); // SDL SDL_Quit(); // romfs #ifdef __SWITCH__ romfsExit(); #endif } //------------------------------------------------------------------------------ // Load a texture SDL_Texture* SDLUtils::LoadTexture(const std::string &p_path) { INHIBIT(std::cout << "SDLUtils::LoadTexture(" << p_path << ")" << std::endl;) SDL_Texture* texture = NULL; SDL_Surface* surface = IMG_Load(p_path.c_str()); if (surface == NULL) { std::cerr << "Unable to load image '" << p_path << "'! SDL_Error: " << SDL_GetError() << std::endl; return NULL; } texture = SDL_CreateTextureFromSurface(g_renderer, surface); if (texture == NULL) { std::cerr << "Unable to create texture from '" << p_path << "'! SDL_Error: " << SDL_GetError() << std::endl; return NULL; } SDL_FreeSurface(surface); return texture; } //------------------------------------------------------------------------------ // Return a texture, load it if necessary SDL_Texture* SDLUtils::GetTexture(const std::string &p_path) { INHIBIT(std::cout << "SDLUtils::GetTexture(" << p_path << ")" << std::endl;) // Search texture std::map<std::string, SDL_Texture*>::iterator it = g_textures.find(p_path); if (it != g_textures.end()) return it->second; // First time asking for this texture => load it SDL_Texture *tex = LoadTexture(p_path); if (tex != NULL) g_textures.insert(std::pair<std::string, SDL_Texture*>(p_path, tex)); return tex; }
true
d4ab848dd51a692f6413577d5e31aa42d28e5a8f
C++
henrythasler/legendary-dashboard
/lib/text/wisdom.h
UTF-8
28,421
2.703125
3
[ "MIT" ]
permissive
#if defined(ESP8266) || defined(ESP32) #include <pgmspace.h> #else #include <avr/pgmspace.h> #endif // Latin-1 character codes // ä: "\xe4" // ü: "\xfc" // ö: "\xf6" // Ä: "\xc4" // Ö: "\xd6" // Ü: "\xdc" // ß: "\xdf" const std::vector<String> wisdomTexts PROGMEM = { // Bullshit Bingo "Bingo 1: It works on my Machine!", "Bingo 2: It worked yesterday!", "Bingo 3: I've never done that before.", "Bingo 4: That's weird.", "Bingo 5: Where were you when the program blew up?", "Bingo 6: Why do you want to do it that way?", "Bingo 7: You can't use that version on your System!", "Bingo 8: Even though it doesn't work how does it feel?", "Bingo 9: Did you check for a Virus on your System?", "Bingo 10: Somebody must have changed my code!", "Bingo 11: It works, but it hasn't been tested.", "Bingo 12: THIS can't be the source of that!", "Bingo 13: I can't test everything.", "Bingo 14: It's just some unlucky coincidence.", "Bingo 15: You must have the wrong version!", "Bingo 16: I haven't touched that module in weeks.", "Bingo 17: There is something funky in your data.", "Bingo 18: What did you Type in to get it to crash?", "Bingo 19: It must be a hardware problem.", "Bingo 20: How is that possible?", "Bingo 21: That's scheduled to be fixed in the next release.", "Bingo 22: Yes, we knew that would happen.", "Bingo 23: Maybe we just don't support that platform.", "Bingo 24: It's a Feature we just haven't updated the specs.", "Bingo 25: Surely Nobody is going to use the program like that.", // Julia "So m""\xfc""de wie heute, war ich bestimmt seit gestern nicht mehr.", "Geschenke einpacken. Das r""\xfc""ckw""\xe4""rts einparken der Frauen f""\xfc""r M""\xe4""nner.", "Je gr""\xf6""ßer der Dachschaden desto besser der Blick auf die Sterne.", "Ich kann doch nicht alle gl""\xfc""cklich machen oder sehe ich aus wie ein Glas Nutella?!", "Lass uns lachen, das Leben ist ernst genug.", "Ich f""\xfc""hle mich, als k""\xf6""nnte ich B""\xe4""ume ausreissen. Also, kleine B""\xe4""ume. Vielleicht Bambus. Oder Blumen. Na gut. Gras. Gras geht.", "Nat""\xfc""rlich mache ich gerne Sport. Deshalb auch so selten. Soll ja schließlich was Besonderes bleiben.", "Das Problem will ich nicht, zeig mir das N""\xe4""chste!", "Fr""\xfc""her war wirklich alles leichter. Zum Beispiel Ich.", "Als Gott mich schuf, grinste er und dachte: Keine Ahnung was passiert, aber lustig wirds bestimmt!", "Fahre nie schneller, als dein Schutzengel fliegen kann!", "Wer Ordnung h""\xe4""lt, ist nur zu faul zum Suchen.", "Gebildet ist, wer wei""\xdf"", wo er findet, was er nicht wei""\xdf"".", "I don't know where I'm going but I'm on my way.", "Humor ist versteckte Weisheit.", "Schokolade ist Gottes Entschuldigung f""\xfc""r Brokkoli.", "Wer schwankt hat mehr vom Weg!", "Da lernt man Dreisatz und Wahrscheinlichkeitsrechnung und steht trotzdem gr""\xfc""belnd vor dem Backofen, welche der vier Schienen nun die Mittlere ist.", "Ich schlafe im Sommer mit offenem Fenster. 1832 M""\xfc""cken gef""\xe4""llt das.", "Was ist ein Keks unter einem Baum? Ein schattiges Pl""\xe4""tzchen", "Nat""\xfc""rlich spreche ich mit mir selbst. Manchmal brauche ich eine kompetente Beratung.", "Wie, zu Fu""\xdf"" gehen? Hab doch vier gesunde Reifen!", // Postillon Newsticker "Z""\xe4""hlte bereits 60 Jahre: Amazon-Lagerist bei Inventur verstorben", "Mag er roh nie: Mann kocht Nudelgericht", "In G""\xe4""nsef""\xfc""""\xdf""chen gesetzt: Praktikant macht es sich bei 'Arbeit' im Schlachthof bequem", """\xe4""tsch, Iran: Versteckte Kamera schickt englischen S""\xe4""nger in den nahen Osten", "Multibl""\xe4""h-Pers""\xf6""nlichkeit: Psychisch Kranker kann als mehrere Menschen furzen", "Nur ein paar Brocken: Englisch-Kenntnisse nicht ausreichend um Arzt den Grad der ""\xfc""belkeit zu erkl""\xe4""ren", "Jahrelang Kohlgirl gewesen: Merkel spricht nicht gerne ""\xfc""ber ihre Anfangszeit", "Kann ich mal Ihren Stift haben?: Azubi-Leihvertrag steht kurz vor der Unterzeichnung", "Ersatzteil aus dem Second-Hand-Laden: Einarmiger Bandit repariert", """\xfc""ber Welt tickendes Angebot: Swatch plant kostenlose Riesen-Uhr auf dem Mond", "Wieder zu Hause aufgetaucht: H""\xe4""ftling gl""\xfc""ckt Flucht durch Kanalisation", "Das Bett h""\xe4""utet ihm sehr viel: Mann h""\xe4""lt trotz unruhiger N""\xe4""chte an Schlafst""\xe4""tte aus Schlangenleder fest", "Weltrekordhalter im Kraulen: Schwimmer verw""\xf6""hnt Katze", "Opa-Hammer-Gau: Rentner f""\xe4""llt bei Passionsspielen Werkzeug auf Fu""\xdf""", "Essenzzeit: Mann nimmt Gericht aus Konzentraten ein", "D""\xf6""ner Hebab: Turkish Airlines bietet an Bord nun auch Grillspezialit""\xe4""t an", "Na, Geld: Alternder Callboy wird gefragt, warum er ""\xfc""berhaupt noch arbeitet", "20 Pfund abgenommen: Dicke Britin hetzt Taschendieb durch die ganze Stadt", "Autorennlesung: Schriftsteller rezitiert sein Werk ""\xfc""ber Formel 1 Saison am N""\xfc""rburgring", "2G und SD: Veraltetes Handy h""\xe4""ngt in Baum", "Beim Bund: General weist Soldaten auf Riss in Hose hin", "Pfiff dezent: US Rapper bewies als Schiedsrichter kein Durchsetzungsverm""\xf6""gen", "Tubenarrest: Freche Zahnpasta muss drinnen bleiben", "Schlimmen R""\xfc""ckfall erlitten: Alkoholiker konnte nicht wieder stehen", "War nicht ohne: Mann von Safer Sex begeistert", "Will da auch gar nichts besch""\xf6""nigen: Plastischer Chirurg nimmt Patientin jede Hoffnung", "Zwei Dijons: Senfhersteller bringt Ex-Freundin Geschenk", "Helles Lager: Getr""\xe4""nkemarktmitarbeiter findet Bier schneller", "Erwischt: Frau beobachtet ihren Mann beim Tindern", "Aus dem Bauch heraus: Von Wal verspeister Mann verfasst spontan seine Memoiren", "Herdzinsangelegenheit: Kunde m""\xf6""chte Ofen liebend gern auf Raten zahlen", "Rotes Kreuz: Rettungssanit""\xe4""ter klagt ""\xfc""ber R""\xfc""ckenschmerzen nach S/M-Wochenende", "Tarte ""\xfc"", Tarte A: B""\xe4""cker wegen verr""\xfc""ckter Nummerierung in Psychiatrie eingeliefert", "Muss neuen aufsetzen: Mann sch""\xfc""ttet sich Kaffee ""\xfc""ber den Hut", "Springer Steve L.: Neonazi trug beim Suizid seine Lieblingsschuhe", "Hintergrund unklar: Maler zerst""\xf6""rt Stillleben", "Im Karsten: Schwulenporno endlich fertig", "Nur eine Kugel: Revolverheld erschie""\xdf""t knausrigen Eisdielenkunden", "War noch gr""\xfc""n hinter Tenoren: Fahranf""\xe4""nger rast auf Kreuzung in Tourbus-Heck", "Speichermedium: Auf Dachboden lebende Frau mit ""\xfc""bernat""\xfc""rlichen F""\xe4""higkeiten findet USB-Stick", "Thomas' Scotch-Alk: Whisky von Showmaster entwendet", "Alles au""\xdf""er Kontrolle: T""\xfc""rsteher nahm Job nicht ernst", "Mittags Sch""\xe4""fchen gehalten: Hirte macht Pause mit Lamm im Arm", "Tausend Zsa Zsa: Trickreicher Erfinder klont mehrfach Hollywoodlegende", "Sitzt gut: H""\xe4""ftling mit Kleidung und Schemel zufrieden", "S""\xe4""uchenschutzgesetz: Kleine Schweine m""\xfc""ssen bei Pandemie als erstes gerettet werden", "Beh""\xe4""lter f""\xfc""r sich: Betrunkener erkl""\xe4""rt auf Party nicht, warum er Eimer dabei hat", "Rasch aua: Autobahn""\xfc""berquerung zu Fuß endet im Krankenhaus", "Da kennt er nix: Vollidiot meldet sich zu Astrophysik-Quiz an", "Social Diss-Dancing: Waldorfsch""\xfc""ler postet beleidigende Videos auf Facebook", "Der totale Kn""\xfc""ller: Kopierer bricht Verkaufsrekorde trotz schlechten Papiereinzugs", "Qual-Lied-Hetz-Management: Nach ISO9001 ist es erlaubt, ""\xfc""ber 'Atemlos durch die Nacht' herzuziehen", "Steckt in Apache: Winnetou in flagranti mit Liebhaber erwischt", "Streit ""\xfc""ber fehlende Stra""\xdf""e eskaliert: B""\xfc""rgermeister schickt Erschlie""\xdf""ungskommando", "Schwamm: SpongeBob besteht Seepferdchen", "F""\xfc""hrt ein Schattendasein: Von Hand auf Leinwand projiziertes Krokodil", "Ernie Dirigent: Bert erlebt Berufung von Freund zum Orchesterleiter als Dem""\xfc""tigung", "Wegen Kontaktsperre: Batterie verweigert Dienst", "Nach dem Stunt teert Inge: Filmdouble muss voraussichtlich Zweitjob im Stra""\xdf""enbau annehmen", "Geh""\xf6""ren zur Riesigkotgruppe: Dicke leiden unter Klopapiermangel", "Bekam einen R""\xfc""ffel: Zahnloser muss sich zur Strafe als Elefant verkleiden", "Hahn-Twerker: Zimmermann macht Potanz-Video im Gockel-Kost""\xfc""m", "Unterschiedliche Vorstellungen: Kinobesitzerehepaar trennt sich", "Siel bereisen: Florian macht Deichtour", "Macht sich nichts vor: Pfleger wei""\xdf"" eigentlich, dass Ansteckungsrisiko ohne Mundschutz gr""\xf6""""\xdf""er ist", "K. Russell: Schauspieler nutzt Fahrgesch""\xe4""ft", "Zieht Schlussstrich: Mann trennt sich von Lieblingsstift", "Prinzessbohnen: K""\xf6""nig r""\xe4""t seinem Sohn zu mehr Gem""\xfc""se", "K""\xf6""nnte jeden treffen: Mann immun gegen Coronavirus", "In Skiflagge geraten: Insolventer Quizteilnehmer tr""\xe4""gt Riesenslalomzubeh""\xf6""r als Schal", "Wegen Best""\xe4""ubungsmitteln: Biene verhaftet", "Eilegeboten: Kundschafter mahnen H""\xfc""hner zu rechtzeitiger Steigerung der Produktion bis Ostern", "Verein-Zelt: Sch""\xfc""tzenfest-Pavillon darf nur noch von je einem Mitglied betreten werden", "Stoff vers""\xe4""umt: N""\xe4""herin muss nach Feierabend noch f""\xfc""r Kurs lernen", "Stand dort: Wanderer sah auf Umgebungsplan, wo er sich befand", "In Betrieb genommen: Sexroboter vor Auslieferung getestet", "Wertpapiere: Banker investiert in Toilettenrollen", "Musste dem Rechnung tragen: Frau akzeptiert, dass Freund nach Leistenbruch unm""\xf6""glich Kassenzettel heben kann", "Hat endlich eine Rolle ergattert: Erfolgloser Schauspieler bringt Klopapier nach Hause", "Stand kurz vor einer L""\xf6""sung: Impfstoffentwickler atmet hochgiftige D""\xe4""mpfe ein", "S. Raab bellt im Karton: Entertainer hat den Verstand verloren", "F""\xe4""llt leicht: Neymar auch in Verkleidung unschwer zu erkennen", "Total vervirt: Coronapatient l""\xe4""uft orientierungslos durch Fu""\xdf""g""\xe4""ngerzone", "'Wang, w""\xfc""rz mal Widder...richtig so...mehr!': Carrell empfand Hammelfleisch am China-Imbiss als zu fad", "Brachte nur noch Vieren nach Hause: Familie von schlechtem Sch""\xfc""ler in Quarant""\xe4""ne", "Dia mit Lungen aufgenommen: Polizei jagt Organfotografen", "Einrichtungshaus: IKEA mahnt Kunden zur Einhaltung der Laufroute", "Trampolin: Warschauerin nimmt H""\xfc""pfger""\xe4""t mit in die Stra""\xdf""enbahn", "Mustafa werden: Muslima will nach Geschlechtsumwandlung dominanter auftreten", "Das wird sich noch zeigen: Murmeltierexperte streitet mit entt""\xe4""uschten Touristen ""\xfc""ber seine Fachkompetenz", "'Husten! Wir haben ein Problem.': ISS meldet ersten Corona-Fall", "Macht jetzt in Antiquit""\xe4""ten: Vasenh""\xe4""ndler findet kein Klo", "F""\xfc""hrt Ananas-Serum: Arzt t""\xe4""uscht Patienten mit Impfstoff aus Fruchtsaft", "Immer nur Fish &amp;amp; Ships: Godzilla findet englische K""\xfc""che ""\xf6""de", "h.c. nicht alle: Uni-Rektor stellt fast nur Dozenten mit Ehrendoktorw""\xfc""rde ein", "Waren verdorben: Ordin""\xe4""re Marktfrauen boten faules Obst an", "Eine einzige Schikane: Formel-1-Fahrer ""\xfc""ber schlechten Kurs emp""\xf6""rt", "File geboten: Datei zu verkaufen", "Schnappt nach Luft: Hund dreht in Sauna durch", "'Kiek, Erik, ih!': Berlinerin zeigt ihrem Freund toten Hahn", "Nicht auszumalen: Kinderbuch mit 10.000 Seiten ver""\xf6""ffentlicht", "Schlafend gestellt: Einbrecher lag bei Zugriff noch im Bett", "finnish.net: Homepage in Helsinki f""\xfc""r Hessen unm""\xf6""glich zu erreichen", "Arbeitet fieberhaft: Immunsystem l""\xe4""uft auf Hochtouren", "Petryschale: Frauke z""\xfc""chtet Halsw""\xe4""rmer im Labor", "Hinter Heer ist man schlauer: Soldat will nicht an die Front", "Fellig losgel""\xf6""st: Major Tom startete unrasiert", "'Sch""\xfc""tt Senf herein!': Jugendlicher stiftet Kumpel an, Schie""\xdf""sport-Club einen Streich zu spielen", "Leckt ein bisschen: Chemiker untersucht unbekannte Substanz unter Silo", "Dieb rennt: Fl""\xfc""chtiger Taschenr""\xe4""uber z""\xfc""ndete Opfer an", "Muss zum K""\xe4""ferorthop""\xe4""den: Insekt hat ""\xfc""berbiss", "Punk kaut Tomaten: Linker Veganer hebt mehrfach Geld ab", "Spricht mit gespaltener Zunge: Indianer l""\xfc""gt ""\xfc""ber Unfall mit Jagdmesser", "Wiesloch: Frau aus Baden-W""\xfc""rttemberg s""\xe4""uft", "Patienten m""\xfc""ssen mit gr""\xf6""""\xdf""eren Einschnitten rechnen: Chirurgiepraxis spart an feinen Skalpellen", "Ein sch""\xf6""ner Zug von ihm: Modell-Eisenbahner verschenkt sein liebstes Exemplar", "Da gibts Gedr""\xe4""nge: Hohes Menschenaufkommen bei hessischem Spirituosenh""\xe4""ndler", "Arsch reckend: Immer mehr M""\xe4""nner gehen in Yoga-Kurs", "PDF: Geheimes Dokument offenbart verkehrte Politik der FDP", "H""\xe4""ufig in Elefantenporno zu sehen: Sto""\xdf""szene", "Ging ihm dann auch direkt auf: Mann h""\xe4""tte Hosenrei""\xdf""verschluss vor Vorstellungsgespr""\xe4""ch besser repariert", "Ein einmaliges Erlebnis:  Marodes Bungeeunternehmen versucht es mit ehrlicher Werbung", "Gold richtig: Quizshow-Teilnehmer beantwortet Frage nach Edelmetall", "Ein Fach nur, d""\xe4""mlich: Merkw""\xfc""rdiger Apothekerschrank floppt", "Die wichtigsten Wokgabeln: Asiatischer Koch paukt f""\xfc""r Pr""\xfc""fung in Besteckkunde", "Rote Arme Fraktion: Andreas Baader und Ulrike Meinhof haben Sonnenbrand", "Hat ihn dumm angemacht: Vegetarier von Salat verpr""\xfc""gelt", "Er ist jetzt an einem besseren Ort: Journalist springt aus dem Fenster der BILD-Redaktion", "War als erster an der Ziehlinie: Junkie gewinnt Wettrennen um Kokain", "Aphte: Nazi wegen Mundh""\xf6""hlenentz""\xfc""ndung unf""\xe4""hig, seine Lieblingspartei zu nennen", "Kann ein Liter Fond singen: Mann wei""\xdf"", wie es ist, beim Tr""\xe4""llern Bratensaft zu produzieren", "War eiskalt vor dem Tor: Platzwart findet erfrorenen St""\xfc""rmer", "Will nicht, dass jeder seinen Schwan zieht: Bekleideter Mann bindet Wasservogel an", "Ein Schlag ins Gesicht: Masochist von entt""\xe4""uschendem Domina-Angebot gekr""\xe4""nkt", "Serge ade: Bayernspieler muss trotz hervorragender Leistungen den Verein verlassen", """\xfc""ber Alf lecken: Masernpatient versucht Krankheit durch Lutschen an Au""\xdf""erirdischem zu lindern", "Wie die Lehm-Inge: Kinder beim T""\xf6""pfern von Klippe gesprungen", "'""\xe4""hm, Sie Hemmer!': Rapper als Spa""\xdf""bremse beschimpft", "Wageneber im Kofferraum: Franzose mit Reifenpanne hatte Schwein", "Steiffhundfest: Kind behauptet, sein Stofftier habe Geburtstag", "War am saugen: Ehefrau ""\xfc""berrascht ihren Mann mit neuer Haushaltshilfe", "Gingen um die Welt: Bilder von Extremdistanz-Wanderern in allen Nachrichten pr""\xe4""sent", "Bekommt lecker Li: Kampfhund wird mit Chinesen belohnt", "Ohne Witz: Mario Barth ist nicht lustig", "Freut sich auf 'at home-Pils': Nuklearphysiker hat Feierabend", "Zweibr""\xfc""cken: Zahn""\xe4""rztin aus der Pfalz erlebt ruhigen Vormittag", "Irre summen: Anwohner m""\xfc""ssen f""\xfc""r L""\xe4""rmschutzwand vor Psychiatrie zahlen", "H""\xf6""ren sich gegenseitig ab: Spionage-Azubis lernen f""\xfc""r ihre Abschlusspr""\xfc""fung", "Kaviar im Zeugnis: Bayerischer Lehrer belohnt rogens""\xfc""chtigen Sch""\xfc""ler", "Genfer: Zahnloser Schweizer gibt sich f""\xfc""r ehemaligen deutschen Au""\xdf""enminister aus", "Lange nicht Font""\xe4""nen geh""\xf6""rt: Meeresanwohner wundert sich, wo Wale geblieben sind" // Murphys law "If anything can go wrong, it will.", "If anything just cannot go wrong, it will anyway.", "If everything seems to be going well, you have obviously overlooked something", "Smile . . . tomorrow will be worse.", "Matter will be damaged in direct proportion to its value.", "Research supports a specific theory depending on the amount of funds dedicated to it.", "In nature, nothing is ever right. Therefore, if everything is going right ... something is wrong.", "It is impossible to make anything foolproof because fools are so ingenious.", "Everything takes longer than you think.", "Every solution breeds new problems.", "The legibility of a copy is inversely proportional to its importance.", "A falling object will always land where it can do the most damage.", "A shatterproof object will always fall on the only surface hard enough to crack or break it.", "The other line always moves faster.", "In order to get a personal loan, you must first prove you don't need it.", "Anything you try to fix will take longer and cost you more than you thought.", "Build a system that even a fool can use, and only a fool will use it.", "Everyone has a scheme for getting rich that will not work.", "In any hierarchy, each individual rises to his own level of incompetence, and then remains there.", "There's never time to do it right, but there's always time to do it over.", "When in doubt, mumble. When in trouble, delegate.", "Anything good in life is either illegal, immoral or fattening.", "Murphy's golden rule: whoever has the gold makes the rules.", "A Smith & Wesson beats four aces.", "In case of doubt, make it sound convincing.", "Never argue with a fool, people might not know the difference.", "Whatever hits the fan will not be evenly distributed.", "Where patience fails, force prevails.", "Just when you think things cannot get any worse, they will.", "Great ideas are never remembered and dumb statements are never forgotten.", "When you see light at the end of the tunnel, the tunnel will cave in.", "Traffic is inversely proportional to how late you are, or are going to be.", "The probability of being observed is in direct proportion to the stupidity of ones actions.", "Those who know the least will always know it the loudest.", "Just because you CAN do something doesn't mean you SHOULD.", "Chaos always wins, because it's better organized.", "If at first you don't succeed destroy all evidence that you ever tried.", "It takes forever to learn the rules and once you've learned them they change again", "You will find an easy way to do it, after you've finished doing it.", "Anyone who isn't paranoid simply isn't paying attention.", "A valuable falling in a hard to reach place will be exactly at the distance of the tip of your fingers.", "The probability of rain is inversely proportional to the size of the umbrella you carry around with you all day.", "Nothing is impossible for the man who doesn't have to do it himself.", "The likelihood of something happening is in inverse proportion to the desirability of it happening.", "Common Sense Is Not So Common.", "Power Is Taken... Not Given.", "Two wrongs don't make a right. It usually takes three or four.", "The difference between Stupidity and Genius is that Genius has its limits.", "Those who don't take decisions never make mistakes.", "Anything that seems right, is putting you into a false sense of security.", "Its never so bad it couldn't be worse.", "When saying that things can not possibly get any worse - they will.", "The person ahead of you in the queue, will have the most complex transaction possible.", "Logic is a systematic method of coming to the wrong conclusion with confidence.", "Technology is dominated by those who manage what they do not understand.", "The opulence of the front office decor varies inversely with the fundamental solvency of the firm.", "The attention span of a computer is only as long as it electrical cord.", "Nothing ever gets built on schedule or within budget.", "The first myth of management is that it exists.", "A failure will not appear till a unit has passed final inspection.", "To err is human, but to really foul things up requires a computer.", "Any sufficiently advanced technology is indistinguishable from magic.", "Nothing motivates a man more than to see his boss putting in an honest day's work.", "Some people manage by the book, even though they don't know who wrote the book or even what book.", "To spot the expert, pick the one who predicts the job will take the longest and cost the most.", "After all is said and done, a hell of a lot more is said than done.", "The only perfect science is hind-sight.", "If an experiment works, something has gone wrong.", "When all else fails, read the instructions.", "The degree of technical competence is inversely proportional to the level of management.", "The remaining work to finish in order to reach your goal increases as the deadline approaches.", "It is never wise to let a piece of electronic equipment know that you are in a hurry.", "If you are not thoroughly confused, you have not been thoroughly informed.", "Standard parts are not.", "The bolt that is in the most awkward place will always be the one with the tightest thread.", "In today's fast-moving tech environment, it is a requirement that we forget more than we learn.", "It is simple to make something complex, and complex to make it simple.", "If it works in theory, it won't work in practice. If it works in practice it won't work in theory.", "Any tool dropped will fall where it can cause the most damage.", "When you finally update to a new technology, is when everyone stop supporting it.", "If you think you understand science (or computers or women), you're clearly not an expert", "Technicians are the only ones that don't trust technology.", "The repairman will have never seen a model quite like yours before.", "In theory there is no difference between theory and practice, but in practice there is.", "Never underestimate incompetency.", "Any given program, when running, is obsolete.", "Any given program costs more and takes longer each time it is run.", "If a program is useful, it will have to be changed.", "If a program is useless, it will have to be documented.", "Any given program will expand to fill all the available memory.", "Program complexity grows until it exceeds the capability of the programmer who must maintain it.", "Adding manpower to a late software project makes it later.", "No matter how many resources you have, it is never enough.", "If a program has not crashed yet, it is waiting for a critical moment before it crashes.", "Software bugs are impossible to detect by anybody except the end user.", "A failure in a device will never appear until it has passed final inspection.", "An expert is someone brought in at the last minute to share the blame.", "A patch is a piece of software which replaces old bugs with new bugs.", "The chances of a program doing what it's supposed to do is inversely proportional to the number of lines of code used.", "The longer it takes to download a program the more likely it won't run.", "It's not a bug, it's an undocumented feature.", "Bugs mysteriously appear when you say, Watch this!", "The probability of bugs appearing is directly proportional to the number and importance of people watching.", "If a project is completed on schedule, it wasn't debugged properly.", "If it works, it's production. If it doesn't, it's a test.", "Real programmers don't comment their code. If it was hard to write, it should be hard to understand.", "A computer that has been on the market for 6 weeks is still usable as a boat anchor.", "Computers let you waste time efficiently.", "A pat on the back is only a few inches from a kick in the pants.", "Don't be irreplaceable, if you can't be replaced, you can't be promoted.", "It doesn't matter what you do, it only matters what you say you've done and what you say you're going to do.", "The more crap you put up with, the more crap you are going to get.", "When the bosses talk about improving productivity, they are never talking about themselves.", "Mother said there would be days like this, but she never said there would be so many.", "--> The last person that quit or was fired will be the one held responsible for everything that goes wrong. :-)", "If it wasn't for the last minute, nothing would get done.", "The longer the title, the less important the job.", "If you have a little extra money to blow, something will break, and cost more than that little extra.", "If the salesperson says, All you have to do is..., you know you're in trouble.", // general "When I was a kid my parents moved a lot, but I always found them.", "Life is short. Smile while you still have teeth.", "The best way to teach your kids about taxes is by eating 30 percent of their ice cream.", "I'm writing a book. I've got the page numbers done.", "I have always wanted to be somebody, but I see now I should have been more specific.", "Knowledge is like underwear. It is useful to have it, but not necessary to show it off.", "If a book about failures doesn't sell, is it a success?", "A lie gets halfway around the world before the truth has a chance to get its pants on.", "It's okay if you don't like me. Not everyone has good taste.", "Everything is changing. People are taking the comedians seriously and the politicians as a joke.", "I like long walks, especially when they are taken by people who annoy me.", "The only way to keep your health is to eat what you don't want, drink what you don't like, and do what you'd rather not.", "When nothing is going right, go left.", "Never miss a good chance to shut up.", "I'd like to live like a poor man – only with lots of money.", "My life feels like a test I didn't study for.", "I don't go crazy. I am crazy. I just go normal from time to time.", "My bed is a magical place where I suddenly remember everything I forgot to do.", "I'm actually not funny. I'm just really mean and people think I'm joking.", "Sometimes I want to go back in time and punch myself in the face.", "If you are lonely, dim all lights and put on a horror movie. After a while it won't feel like you are alone anymore.", "Fries or salad? sums up every adult decision you have to make.", "If we're not meant to have midnight snacks, why is there a light in the fridge.", "My doctor told me to watch my drinking. Now I drink in front of a mirror.", "I drive way too fast to worry about cholesterol.", "As your best friend I'll always pick you up when you fall, after I finish laughing.", "Some people are like clouds. When they disappear, it's a beautiful day.", "I'm not arguing. I'm simply explaining why I'm right.", "No wonder the teacher knows so much; she has the book.", "The most ineffective workers are systematically moved to the place where they can do the least damage: management.", "The best way to appreciate your job is to imagine yourself without one.", "If I had asked people what they wanted, they would have said faster horses. Henry Ford", "The closest a person ever comes to perfection is when he fills out a job application form.", "Don't yell at your kids! Lean in real close and whisper, it's much scarier.", "The quickest way for a parent to get a child's attention is to sit down and look comfortable.", "I don't know what's more exhausting about parenting: the getting up early, or the acting like you know what you're doing.", "It just occurred to me that the majority of my diet is made up of the foods that my kid didn't finish.", "When your children are teenagers, it's important to have a dog so that someone in the house is happy to see you.", "I never know what to say when people ask me what my hobbies are. I mean, I'm a dad.", "My wife and I were happy for twenty years. Then we met.", "Marriage... it's not a word, it's a sentence.", "Marry a man your own age; as your beauty fades, so will his eyesight.", "Marriage is the triumph of imagination over intelligence. Second marriage is the triumph of hope over experience.", "The most terrifying thing any woman can say to me is Notice anything different?", "When a man brings his wife flowers for no reason, there's a reason." };
true
31b130db6cfd8f0acc66ccd4cd3f4ec52147efc2
C++
pastman/arduino_examples
/Example_Analog.ino
UTF-8
716
2.734375
3
[]
no_license
#define ANALOG 0 #define DIGITAL0 0 #define DIGITAL1 1 #define DIGITAL2 2 void setup() { Serial.begin(9600); pinMode(ANALOG, INPUT); pinMode(DIGITAL0, OUTPUT); pinMode(DIGITAL1, OUTPUT); pinMode(DIGITAL2, OUTPUT); } void loop() { int light = analogRead(ANALOG); Serial.println(light); if (light < 650) { digitalWrite(DIGITAL0, HIGH); digitalWrite(DIGITAL1, LOW); digitalWrite(DIGITAL2, LOW); } else if (light < 200) { digitalWrite(DIGITAL0, LOW); digitalWrite(DIGITAL1, HIGH); digitalWrite(DIGITAL2, LOW); } else { digitalWrite(DIGITAL0, LOW); digitalWrite(DIGITAL1, LOW); digitalWrite(DIGITAL2, HIGH); } delay(1000); }
true
6e0e807376bf3d3f1fbc0f9fde4f39ab66ce272d
C++
alissastanderwick/OpenKODE-Framework
/01_Develop/libXMCocos2D/Source/kazmath/plane.cpp
UTF-8
5,612
2.5625
3
[ "MIT" ]
permissive
/* ----------------------------------------------------------------------------------- * * File plane.cpp * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * ----------------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft * Copyright (c) 2008 Luke Benstead. All rights reserved. * * ----------------------------------------------------------------------------------- * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ----------------------------------------------------------------------------------- */ #include "Precompiled.h" #include "kazmath/vec3.h" #include "kazmath/vec4.h" #include "kazmath/plane.h" const kmScalar kmPlaneDot(const kmPlane* pP, const kmVec4* pV) { //a*x + b*y + c*z + d*w return (pP->a * pV->x + pP->b * pV->y + pP->c * pV->z + pP->d * pV->w); } const kmScalar kmPlaneDotCoord(const kmPlane* pP, const kmVec3* pV) { return (pP->a * pV->x + pP->b * pV->y + pP->c * pV->z + pP->d); } const kmScalar kmPlaneDotNormal(const kmPlane* pP, const kmVec3* pV) { return (pP->a * pV->x + pP->b * pV->y + pP->c * pV->z); } kmPlane* const kmPlaneFromPointNormal(kmPlane* pOut, const kmVec3* pPoint, const kmVec3* pNormal) { /* Planea = Nx Planeb = Ny Planec = Nz Planed = −N⋅P */ pOut->a = pNormal->x; pOut->b = pNormal->y; pOut->c = pNormal->z; pOut->d = -kmVec3Dot(pNormal, pPoint); return pOut; } /** * Creates a plane from 3 points. The result is stored in pOut. * pOut is returned. */ kmPlane* const kmPlaneFromPoints(kmPlane* pOut, const kmVec3* p1, const kmVec3* p2, const kmVec3* p3) { /* v = (B − A) × (C − A) n = 1⁄|v| v Outa = nx Outb = ny Outc = nz Outd = −n⋅A */ kmVec3 n, v1, v2; kmVec3Subtract(&v1, p2, p1); //Create the vectors for the 2 sides of the triangle kmVec3Subtract(&v2, p3, p1); kmVec3Cross(&n, &v1, &v2); //Use the cross product to get the normal kmVec3Normalize(&n, &n); //Normalize it and assign to pOut->m_N pOut->a = n.x; pOut->b = n.y; pOut->c = n.z; pOut->d = kmVec3Dot(kmVec3Scale(&n, &n, -1.0), p1); return pOut; } kmVec3* const kmPlaneIntersectLine(kmVec3* pOut, const kmPlane* pP, const kmVec3* pV1, const kmVec3* pV2) { /* n = (Planea, Planeb, Planec) d = V − U Out = U − d⋅(Pd + n⋅U)⁄(d⋅n) [iff d⋅n ≠ 0] */ kmVec3 d; kdAssert(0 && "Not implemented"); kmVec3Subtract(&d, pV2, pV1); //Get the direction vector //TODO: Continue here! /*if (fabs(kmVec3Dot(&pP->m_N, &d)) > kmEpsilon) { //If we get here then the plane and line are parallel (i.e. no intersection) pOut = nullptr; //Set to nullptr return pOut; } */ return KD_NULL; } kmPlane* const kmPlaneNormalize(kmPlane* pOut, const kmPlane* pP) { kmVec3 n; kmScalar l = 0; n.x = pP->a; n.y = pP->b; n.z = pP->c; l = 1.0f / kmVec3Length(&n); //Get 1/length kmVec3Normalize(&n, &n); //Normalize the vector and assign to pOut pOut->a = n.x; pOut->b = n.y; pOut->c = n.z; pOut->d = pP->d * l; //Scale the D value and assign to pOut return pOut; } kmPlane* const kmPlaneScale(kmPlane* pOut, const kmPlane* pP, kmScalar s) { kdAssert(0 && "Not implemented"); return KD_NULL; } /** * Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn. Returns * POINT_BEHIND_PLANE if it is behind. Returns POINT_ON_PLANE otherwise */ const POINT_CLASSIFICATION kmPlaneClassifyPoint(const kmPlane* pIn, const kmVec3* pP) { // This function will determine if a point is on, in front of, or behind // the plane. First we store the dot product of the plane and the point. float distance = pIn->a * pP->x + pIn->b * pP->y + pIn->c * pP->z + pIn->d; // Simply put if the dot product is greater than 0 then it is infront of it. // If it is less than 0 then it is behind it. And if it is 0 then it is on it. if(distance > 0.001) return POINT_INFRONT_OF_PLANE; if(distance < -0.001) return POINT_BEHIND_PLANE; return POINT_ON_PLANE; }
true
e8e47c3ea811b3c399f45efd57e63da6dd847e7b
C++
shanta3220/Light-OJ
/1015 - Brush (I).cpp
UTF-8
447
2.609375
3
[]
no_license
#include <iostream> #include<math.h> using namespace std; int main() { int n,t,j=1, ng,s=0; cin>>t; while(t--){ cin>>n; int a[n]; for(int k=0; k<n;k++ ) { cin>>a[k]; if(a[k]<0){ a[k]=pow(a[k],2); a[k]=pow(a[k],0.5); s+=a[k]; ng+=a[k]; } else s+=a[k]; } cout<<"Case "<<j++<<": "<<s-ng<<"\n"; s=0; ng=0; } return 0; }
true
380579ed09e67097a066ed79cdf7ba93ac2a201a
C++
yaoReadingCode/VS2015project
/game/game/Minesweeper.cpp
GB18030
10,993
3.1875
3
[]
no_license
#include"Minesweeper.h" //ͷļ #include<cstdlib> #include<ctime> #include<iostream> #include<conio.h> #include <fstream> using namespace std; //״̬λ #define BOMB 9 //BOMBʾλը #define MARKED -2 //MARKEDʾλñ #define UNOPEN -1 //ʾλû #define WIN 1 //Ӯ #define ON 2 //Ϸڽ #define LOSE 0 // Minesweeper::Minesweeper(int X, int Y, int bombs) //캯 { gridNumOfX = X; //ֵ gridNumOfY = Y; bombNum = bombs; markNum = 0; gameON = true; Win_or_Lose = false; map = new int *[gridNumOfX+2]; //ռ䣬Ϊ˱ֵ߽⴦ھı߽һȦ for (int i = 0;i < gridNumOfX+2;i++) { map[i] = new int[gridNumOfY+2]; } for (int i = 0;i < gridNumOfX + 2;i++) //ڸ㸳ֵ for (int j = 0;j < gridNumOfY + 2;j++) map[i][j] = UNOPEN; srand(time(0)); // for (int i = 0;i < bombNum;) //ֲըλ { int x = rand() % gridNumOfX + 1; int y = rand() % gridNumOfY + 1; if (map[x][y] != BOMB) //λûըĻ͸ը { map[x][y] = BOMB; i++; } } } Minesweeper::Minesweeper(ifstream& in) //캯 { in >> gridNumOfX >> gridNumOfY >> bombNum >> markNum >> gameON >> Win_or_Lose; //ļж map = new int *[gridNumOfX + 2]; //ռ䣬Ϊ˱ֵ߽⴦ھı߽һȦ for (int i = 0;i < gridNumOfX + 2;i++) { map[i] = new int[gridNumOfY + 2]; } for (int j = 0;j < gridNumOfY + 2;j++) //ӵı߽縳ֵ { map[0][j] = UNOPEN; map[gridNumOfX + 1][j] = UNOPEN; } for (int i = 0;i < gridNumOfX + 2;i++) { map[i][0] = UNOPEN; map[i][gridNumOfY + 1] = UNOPEN; } for (int i = 1;i <= gridNumOfX;i++) //ļж for (int j = 1;j <= gridNumOfY;j++) in >> map[i][j]; in.close(); } Minesweeper::~Minesweeper() { for (int i = 0;i < gridNumOfX+2;i++) delete[] map[i]; delete map; } int Minesweeper::calculate(int x, int y) //һΧжٸը { int count = 0; for (int i = 0;i < 3;i++) //ѭ߱һΧ8 for (int j = 0;j < 3;j++) if (!(derection[i] == 0 && derection[j] == 0)) if (map[x + derection[i]][y + derection[j]] == BOMB|| map[x + derection[i]][y + derection[j]] == MARKED) //ǵҲը count++; return count; } void Minesweeper::setMap(int x, int y) //ڸֵ { int num = calculate(x, y); if (num == 0) //õΧ8ûըôԸ8ֱݹ鱾 { map[x][y] = 0; for (int i = 0;i < 3;i++) //ѭ߱һΧ8 { for (int j = 0;j < 3;j++) { if (!(derection[i] == 0 && derection[j] == 0)) //Լ8ŵݹ { int neighborX = x + derection[i]; //ڽӵ int neighborY = y + derection[j]; if (neighborX <= gridNumOfX && neighborY <= gridNumOfY && neighborX >= 1 && neighborY >= 1) if (map[neighborX][neighborY] == UNOPEN) setMap(neighborX, neighborY); //ݹڵĵ } } } } else map[x][y] = num; //Χըֱը } void Minesweeper::print(bool gameON) //ӡ { system("cls"); cout << "\t\tMinesweeper\t\t\t\n\n\n" << endl; //漸ǴӡʽĿƣϸ cout << "\tYou have " << bombNum - markNum << " bombs still to find\n\n" << endl; cout << " "; for (int i = 1;i <= gridNumOfY;i++) if(i<10) cout << " " << i << " "; else cout << " " << i << ""; cout << endl; cout << " "; for (int i = 1;i <= gridNumOfY;i++) cout << " " << '-' << " "; cout << endl; if (gameON == 0) //ϷѾӡըλ { for (int i = 1;i <= gridNumOfX;i++) { if(i<10) cout << i << " |"; else cout << i << " |"; for (int j = 1;j <= gridNumOfY;j++) { if (map[i][j] == BOMB||map[i][j]==MARKED) cout << " B |"; else if (map[i][j] == UNOPEN || map[i][j] == BOMB) cout << " |"; else cout << " " << map[i][j] << " |"; } cout << endl; cout << " "; for (int i = 1;i <= gridNumOfY;i++) cout << " " << '-' << " "; cout << endl; } if (Win_or_Lose) cout << "You Win!" << endl; else cout << "YOU LOSE!\nYou have revealed a bomb" << endl; } else //Ϸûݾ״̬´ӡ { for (int i = 1;i <= gridNumOfX;i++) { if (i<10) cout << i << " |"; else cout << i << " |"; for (int j = 1;j <= gridNumOfY;j++) { if (map[i][j] == MARKED) cout << " x |"; else if (map[i][j] == UNOPEN || map[i][j] == BOMB) cout << " |"; else cout << " " << map[i][j] << " |"; } cout << endl; cout << " "; for (int i = 1;i <= gridNumOfY;i++) cout << " " << '-' << " "; cout << endl; } } } bool Minesweeper::win() //жǷ˳թ֮иӵĺֻʤһ { int unOpenNum = 0; //ڼ¼ը֮δ򿪵ĸӵ for (int i = 1;i <= gridNumOfX;i++) //ͳƾϳը֮δ򿪵ĸӵ for (int j = 1;j <= gridNumOfY;j++) if (map[i][j] == UNOPEN) unOpenNum++; if (unOpenNum == 0) //ը֮δ򿪵ĸӵΪ㣬˵׳ɹ return true; else return false; } void Minesweeper::marked(int x, int y) //ǺֻиøըŻɹǣܱ { if (map[x][y] == BOMB) //õըԱ { map[x][y] = MARKED; //ը״̬л״̬ markNum++; //һ print(ON); //ϷڽУӡ if (markNum == bombNum) //ȷǵը׳ɹ { cout << "You Win\nYou have mark all of the bombs!" << endl; gameON = false; //Ϸѽ״̬λ Win_or_Lose = true; //ϷӮ˵״̬ cout << "Input any key to return menu" << endl; getch(); //ڱסĻ } else gameON = true; //Ϸ } else //õ㲻ըܱ { cout << "(" << x << "," << y << ")" << "Can't mark : there isn't a bomb!" << endl; gameON = true; } } void Minesweeper::revealed(int x, int y) //򿪸ӵĺ { if (map[x][y] == BOMB || map[x][y] == MARKED) //򿪵ĸһը߸øѱը { print(LOSE); //Ϸӡ gameON = false; //Ϸ־ cout << "Input any key to return menu"<<endl; getch(); } else //򿪸ûը { setMap(x, y); //øõ㼰Χֵ print(ON); if (win()) //ըиѾ򿪣׳ɹ { cout << "You Win\nYou have revealed all of the grid beside the bombs!" << endl; gameON=false; Win_or_Lose = true; cout << "Input any key to return menu" << endl; getch(); } else gameON = true; } } void Minesweeper::saveGame() //Ϸļ gameDate.txt { ofstream of("gameDate.txt"); if (of.is_open()) { of << gridNumOfX <<"\t"<< gridNumOfY << "\t" << bombNum << "\t" << markNum << "\t" << gameON << "\t" << Win_or_Lose<<endl; for (int i = 1;i <= gridNumOfX;i++) { for (int j = 1;j <= gridNumOfY;j++) of << map[i][j] << "\t"; of << "\n"; } of.close(); } } void Minesweeper::playing() //Ϸ { while (gameON) //Ϸ״̬ʱѭ { int select,x,y; cout << "1. Revealed a grid.\t\t2. Mark a grid" << endl; //1.򿪸 2.Ǹ cout << "3. save the game.\t\t4. return to menu\n" << endl; //3.Ϸ 4.ص˵ cout << "Please inpit [1/2/3/4] : "; cin >> select; if (select < 3) { cout << "Please input the row and column of the grid:" << endl; //У cin >> x >> y; if (select == 1) revealed(x, y); else marked(x, y); } else if (select == 3) { saveGame(); //Ϸ print(ON); cout << "The game have saved!\n" << endl; } else { break; //Ϸѭгȥ } } }
true
e44a16ba348ba9a8082981d6ac5e0a796f0c8d7a
C++
multifacs/Journal
/Journal/Source.cpp
UTF-8
461
3.4375
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Student { public: string name; int group; int grade[10]; }; void fillStud(int n, Student *&mas) { mas = new Student[n]; for (int i = 0; i < n; i++) { cin >> mas[i].name >> mas[i].group; } } int main() { string subject[5] = { "Math", "IT", "Eng", "Phys", "PE" }; int groups[5] = { 1, 2, 3, 4, 5 }; Student* mass; int n; cin >> n; fillStud(n, mass); cout << mass[1].name; }
true
c1c5ecd7366260975bdbce3375dc9c917506ea7b
C++
yyuanl/coding_exercise
/0001_剑指offer/0007_旋转数组的最小值/c++/main.cpp
UTF-8
580
3.640625
4
[]
no_license
#include<iostream> #include<vector> using namespace std; int minNumberInRotateArray(const vector<int> &rotateArray){ // 顺序查找 O(N) if(rotateArray.size() == 0) return 0; for(int index1 = 0, index2 = 1;index2 < rotateArray.size(); index2 ++ ){ if(rotateArray[index1] > rotateArray[index2]){ return rotateArray[index2]; } } } int main(){ int array[6] = {4,5,6,1,2,3}; vector<int>rotateArray(array, array + 6); cout << "min of rotateArray is :" << minNumberInRotateArray(rotateArray) << endl; return 0; }
true
b4b343bc91622bae92c2cf081ed0b26dfec8a3d0
C++
lsils/mockturtle
/lib/percy/percy/printer.hpp
UTF-8
3,112
2.796875
3
[ "MIT" ]
permissive
#pragma once #include <kitty/dynamic_truth_table.hpp> #include <fmt/format.h> #include <string> #include <utility> #include <unordered_map> #include <map> namespace percy { template<typename ResultType> class printer { public: explicit printer( chain const& c ); ResultType operator()() const; }; template<> class printer<std::string> { public: explicit printer( chain const& c ) : c( c ) { } std::string operator()() const { assert( c.get_nr_outputs() == 1u ); std::string result; auto const output_literal = c.get_outputs()[0u]; if ( output_literal & 1 ) result += "!"; auto const output_variable = output_literal >> 1u; if ( output_variable == 0u ) { /* special ase of constant 0 */ result += "0"; } else { result += step_to_expression( output_variable - 1u ); } return result; } std::string step_to_expression( uint32_t index ) const { auto const nr_in = c.get_nr_inputs(); if ( index < nr_in ) { return std::string( 1u, 'a' + index ); } const auto& step = c.get_step( index - nr_in ); auto const word = word_from_tt( c.get_operator( index - nr_in ) ); auto const it = masks.find( word ); if ( it == masks.end() ) { assert( false ); return "error"; } auto const mask = it->second; std::string result; switch ( c.get_fanin() ) { case 2u: return fmt::format( mask, step_to_expression( step.at( 0 ) ), step_to_expression( step.at( 1 ) ) ); case 3u: return fmt::format( mask, step_to_expression( step.at( 0 ) ), step_to_expression( step.at( 1 ) ), step_to_expression( step.at( 2 ) ) ); case 4u: return fmt::format( mask, step_to_expression( step.at( 0 ) ), step_to_expression( step.at( 1 ) ), step_to_expression( step.at( 2 ) ), step_to_expression( step.at( 3 ) ) ); case 5u: return fmt::format( mask, step_to_expression( step.at( 0 ) ), step_to_expression( step.at( 1 ) ), step_to_expression( step.at( 2 ) ), step_to_expression( step.at( 3 ) ), step_to_expression( step.at( 4 ) ) ); default: return mask; } } void add_function( kitty::dynamic_truth_table const& tt, std::string const& mask ) { masks[word_from_tt( tt )] = mask; } protected: static inline uint32_t word_from_tt( kitty::dynamic_truth_table const& tt ) { auto word = 0; for ( int i = 0; i < tt.num_vars(); ++i ) { if ( kitty::get_bit( tt, i ) ) word |= ( 1 << i ); } return word; } protected: chain const& c; /* maps the function to their string representation, e.g., 2 --> "(%s%s)" */ std::map<uint32_t,std::string> masks; }; /* printer */ } // namespace printer
true
4c3a2c74eabc9c730600fa6c2883a758fd1c66f5
C++
ttyang/sandbox
/sandbox/icl/libs/xplore/value_sem/TreeSync1/TreeSync1/Syncable/Syncable_Light.h
UTF-8
1,062
2.796875
3
[ "BSL-1.0" ]
permissive
#pragma once //#include <boost/utility/enable_if.hpp> //#include "Syncable/Syncable_ModeledBy.h" typedef int tUuid; typedef int tTime; template<class Model> tUuid uuid(Model const& object) { return object.uuid(); } template<class Model> tTime time(Model const& object) { return object.time(); } template<class Model> bool less_for_time(Model const& lhs, Model const& rhs) { return lhs.time() < rhs.time(); } template<class Model> bool less_for_uuid(Model const& lhs, Model const& rhs) { return lhs.uuid() < rhs.uuid(); } template<class Syncable> struct LessForUuid : std::binary_function<Syncable, Syncable, bool> { bool operator()(Syncable const& lhs, Syncable const& rhs) { return less_for_uuid(lhs, rhs); } }; template<class Syncable> struct LessForTime : std::binary_function<Syncable, Syncable, bool> { typedef Syncable first_argument_type; typedef Syncable second_argument_type; bool operator()(Syncable const& lhs, Syncable const& rhs) { return less_for_time(lhs, rhs); } };
true
e75457080c4b5d2898237d12abbdbe0d0f934336
C++
lintcoder/leetcode
/src/566.cpp
UTF-8
747
3
3
[]
no_license
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int row = nums.size(); if (row == 0) return nums; int col = nums[0].size(); if (row * col != r * c || (row == r && col == c)) return nums; vector<vector<int> > res; vector<int> rownum(c, 0); int m = 0, n = 0; for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (n == col) { m++; n = 0; } rownum[j] = nums[m][n]; n++; } res.push_back(rownum); } return res; }
true
fc888583ebdb08d08613082639d6ea74478c546b
C++
matthew-h-shaw/FollowMe
/FollowMe/FollowMe.cpp
UTF-8
9,014
2.578125
3
[]
no_license
#include "FollowMe.h" FollowMe::FollowMe() { srand((int)time(0)); setImmediateDrawMode(false); } FollowMe::~FollowMe() { } void FollowMe::onTimer(UINT nIDEvent) { if (nIDEvent == ANIMATION) { if (animationCounter < 51) { switch (animation) { case FollowMe::left: spriteX -= 1; break; case FollowMe::right: spriteX += 1; break; case FollowMe::up: spriteY -= 1; break; case FollowMe::down: spriteY += 1; break; default: break; } animationCounter += 1; onDraw(); } else killTimer(ANIMATION); } if (nIDEvent == MOVE) { generatePath(); } } void FollowMe::onDraw() { clearScreen(WHITE); drawBitmap(L"assets\\background.bmp",0, 0, 700, 700); drawBitmap(L"assets\\logo.bmp", 25, 25, 300, 75); setBackColour(GREEN); setPenColour(BLACK, 5); drawRectangle(50, 575, 200, 50, true); drawRectangle(300, 575, 200, 50, true); setTextColour(BLACK); setFont(25, L"Helvetica"); drawText("START", 95, 580); drawText("RESTART", 325, 580); drawText(message.c_str(), 250, 150); for (int i = 0; i < squares.size(); i++) { for (int j = 0; j < squares[i].size(); j++) { if (squares[i][j].visible == true) drawBitmap((squares[i][j].filepath).c_str(), (25 + i * 50), (125 + j * 50), 50, 50); } } drawBitmap(gameOver.c_str(), 150, 200, 400, 300); // GAME OVER IMAGE drawBitmap(sprite.c_str(), spriteX, spriteY, 40, 40); //SPRITE setPenColour(cheatColour, 5); if (userMovement == true && cheatMode) { for (int i = 0; i < ((programPath.size()) / 2); i++) { if (((i * 2) + 3) < programPath.size()) { int startX = programPath[i * 2]; int startY = programPath[(i * 2) + 1]; int endX = programPath[(i * 2) + 2]; int endY = programPath[(i * 2) + 3]; drawLine((25 + startX * 50)+25, (125 + startY * 50)+25, (25 + endX * 50)+25, (125 + endY * 50)+25); } } } ifstream inFile; inFile.open("assets\\highscore.txt"); string myText; inFile >> myText; inFile.close(); drawRectangle(50, 515, 300, 50, true); drawText("HIGH SCORE:", 60, 520); drawText(myText.c_str(), 285, 520); EasyGraphics::onDraw(); } void FollowMe::onMouseMove(UINT nFlags, int x, int y) { mx = x; my = y; onDraw(); } void FollowMe::onKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { keyPressed = nChar; if (userMovement == true && keyPressed != 67) { if (currentMove < level + 3) // WITHIN CORRECT NUMBER OF MOVES FOR THE LEVEL { bool validationCheck; if (keyPressed == 38) //UP { validationCheck = userMoveAndValidate(up); } else if (keyPressed == 40) //DOWN { validationCheck = userMoveAndValidate(down); } else if (keyPressed == 39) //RIGHT { validationCheck = userMoveAndValidate(right); } else if (keyPressed == 37) //LEFT { validationCheck = userMoveAndValidate(left); } if (!validationCheck) // INCORRECT MOVEMENT { incorretChoice(); } } else if (currentMove == level + 3)// REACHED LAST MOVE WITHOUT FAILURE { int temp = level; // STORES LEVEL DURING RESET restart(); level = temp + 1;// GIVES CORRECT LEVEL VALUE resetGrid(); showPath(); } } if (keyPressed == 67) if (cheatMode) cheatMode = false; else cheatMode = true; onDraw(); } void FollowMe::resetGrid() { if (level <5) { width = 4; height = 4; }else if (level < 10) { width = 5; height = 5; }else { width = 6; height = 6; } for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) squares[i][j].visible = false; //RESETS ALL SQUARES AS NON VISIBLE } for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { squares[i][j].visible = true; squares[i][j].filepath = L"assets\\darkSquare.bmp";//SETS REQUIRED SQUARES AS VISIBLE } } sprite = L""; } void FollowMe::onLButtonDown(UINT nFlags, int x, int y) { if (mx > 50 && mx < 250 && my>575 && my < 625 && start == false) { //START levelPlayer(); } else if (mx > 300 && mx < 500 && my>575 && my < 625) { //RESTART restart(); resetGrid(); } onDraw(); } void FollowMe::showPath() { previousMove = none; currentX = (rand() % width); currentY = (rand() % height); squares[currentX][currentY].filepath = L"assets\\lightSquare.bmp"; programPath.insert(programPath.end(), currentX); programPath.insert(programPath.end(), currentY); moves = level + 2; onDraw(); setTimer(MOVE, 1000); onDraw(); } void FollowMe::levelPlayer() { start = true; //LEVEL resetGrid(); showPath(); } void FollowMe::generatePath() { if (moves > 0) { moves -= 1; bool validMove = true; do { validMove = true; int pos = (rand() % 4); if (pos == 0) { // MOVE UP if (((currentY - 1) > -1) && (previousMove != down)) { //VALID MOVEMENT squares[currentX][(currentY - 1)].filepath = L"assets\\lightSquare.bmp"; moveSprite(currentX, currentY, up); currentY -= 1; previousMove = up; } else { //INVALID MOVEMENT validMove = false; } } else if (pos == 1) { // MOVE RIGHT if (((currentX + 1) < width) && (previousMove != left)) { //VALID MOVEMENT squares[currentX + 1][(currentY)].filepath = L"assets\\lightSquare.bmp"; moveSprite(currentX, currentY, right); currentX += 1; previousMove = right; } else { //INVALID MOVEMENT validMove = false; } } else if (pos == 2) { // MOVE DOWN if (((currentY + 1) < height) && (previousMove != up)) { //VALID MOVEMENT squares[currentX][(currentY)+1].filepath = L"assets\\lightSquare.bmp"; moveSprite(currentX, currentY, down); currentY += 1; previousMove = down; } else { //INVALID MOVEMENT validMove = false; } } else if (pos == 3) { // MOVE LEFT if (((currentX - 1) > -1) && previousMove != right) { //VALID MOVEMENT squares[currentX - 1][(currentY)].filepath = L"assets\\lightSquare.bmp"; moveSprite(currentX, currentY, left); currentX -= 1; previousMove = left; } else { //INVALID MOVEMENT validMove = false; } } } while (!validMove); programPath.insert(programPath.end(),currentX); programPath.insert(programPath.end(), currentY); } else { killTimer(ANIMATION); resetGrid(); killTimer(MOVE); onDraw(); inputPath(); } onDraw(); } void FollowMe::inputPath() { bool correctMovement = true; vectorX = currentMove * 2; vectorY = (currentMove * 2) + 1; xPos = programPath[vectorX]; yPos = programPath[vectorY]; squares[xPos][yPos].filepath = L"assets\\lightSquare.bmp"; spriteX = (25 + xPos * 50) + 5; spriteY = (125 + yPos * 50) + 5; sprite = L"assets\\sprite.bmp"; currentMove += 1; bool correct = true; userMovement = true; } bool FollowMe::userMoveAndValidate(direction direction) { bool myReturn; vectorX = currentMove * 2; vectorY = (currentMove * 2) + 1; xPos = programPath[vectorX]; yPos = programPath[vectorY]; switch (direction) { case FollowMe::left: if (xPos == (programPath[vectorX - 2] - 1)) { squares[xPos][yPos].filepath = L"assets\\lightSquare.bmp"; moveSprite((programPath[vectorX - 2]), yPos, left); currentMove += 1; myReturn = true; } else myReturn = false; break; case FollowMe::right: if (xPos == (programPath[vectorX - 2] +1)) { squares[xPos][yPos].filepath = L"assets\\lightSquare.bmp"; moveSprite((programPath[vectorX - 2]), yPos, right); currentMove += 1; myReturn = true; } else myReturn = false; break; case FollowMe::up: if (yPos == (programPath[vectorY - 2] - 1)) { squares[xPos][yPos].filepath = L"assets\\lightSquare.bmp"; moveSprite(xPos, (programPath[vectorY - 2] ), up); currentMove += 1; myReturn = true; } else myReturn = false; break; case FollowMe::down: if (yPos == (programPath[vectorY - 2] + 1)) { squares[xPos][yPos].filepath = L"assets\\lightSquare.bmp"; moveSprite(xPos, (programPath[vectorY - 2] ), down); currentMove += 1; myReturn = true; } else myReturn = false; break; default: break; } return myReturn; } void FollowMe::incorretChoice() { userMovement = false; start = false; gameOver = L"assets\\gameOver.bmp"; ofstream inFile; inFile.open("assets\\highscore.txt"); inFile << to_string(level); inFile.close(); } void FollowMe::restart() { userMovement = false; start = false; currentMove = 0; gameOver = L""; level = 1; width = 4; height = 4; userPath.erase(userPath.begin(), userPath.end()); programPath.erase(programPath.begin(), programPath.end()); killTimer(MOVE); sprite = L""; killTimer(ANIMATION); animationCounter = 0; } void FollowMe::moveSprite(int startX, int startY, direction direction) { spriteX = (25 + startX * 50)+5; spriteY = (125 + startY * 50)+5; sprite = L"assets\\sprite.bmp"; animation = direction; animationCounter = 0; setTimer(ANIMATION, 10); onDraw(); }
true
49d499c0afc0a6693013aa41025ba3b90347b498
C++
mja1110/Arduino-and-library
/Arduino/Arduino11_HW2_BT1_LeHuuTruong.ino/Arduino11_HW2_BT1_LeHuuTruong.ino.ino
UTF-8
401
2.90625
3
[]
no_license
int number; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { if (Serial.available()) { String data = Serial.readString(); number = data.toInt(); if (number > 0 && number < 49) { digitalWrite(13, LOW); Serial.println(number); } if(number>50 && number<100) { digitalWrite(13,HIGH); Serial.println(number); } } }
true
68b1b378c41bfd3259d86c2bda1bbddb2acb4a88
C++
pawelwojtowicz/ecuApp
/Src/CSM/ICSMBuilder.h
UTF-8
885
2.734375
3
[]
no_license
#ifndef CSM_ICSMBUILDER_H #define CSM_ICSMBUILDER_H #include <GlobalTypes.h> namespace CSM { class ICSMBuilder { protected: ICSMBuilder() {}; virtual ~ICSMBuilder() {}; public: virtual void AddState(const std::string& parent, const std::string& stateName, const std::string& enterActionName, const std::string& leafActionName, const std::string& exitActioName) = 0; virtual void AddTransition( const std::string& eventName, const std::string& sourceStateName, const std::string& destinationStateName, const std::string& conditionName, const std::string& actionName) = 0; virtual void SetInitialState( const std::string& initialState) = 0; private: ICSMBuilder(const ICSMBuilder&); ICSMBuilder& operator=( const ICSMBuilder&); }; } #endif
true
1402733f0000d9ff30c7b5e21970ee196e6c712c
C++
ChuckHalmond/qt-patients
/Model/ResourceType.cpp
UTF-8
404
2.75
3
[]
no_license
#include "ResourceType.h" /* Constructors & destructor */ ResourceType::ResourceType() { } ResourceType::~ResourceType() { } /* Getters */ int ResourceType::getId() const { return id; } QString ResourceType::getLabel() const { return label; } /* Setters */ void ResourceType::setId(int id) { this->id = id; } void ResourceType::setLabel(QString label) { this->label = label; }
true
1df9acdba2ef51d58dae4dc4f8133b2f2bac557b
C++
RioRocker97/DistractMyselfFrom_Crypto
/C++/Intermediate/Inheritance_Sub class_Type of class inheritance.cpp
UTF-8
377
2.75
3
[]
no_license
#include<iostream> #include"TankWithSub.h" int main() { Tank standard; heavy T29; std::cout<<T29.getTankName()<<std::endl; T29.setName("T29"); standard.setName("Default"); std::cout<<T29.getTankName()<<" "<<T29.showTypeTank()<<std::endl; std::cout<<standard.getTankName()<<" "<<standard.showTypeTank()<<std::endl; return 0; }
true
7ce4de306e4e240917a9a9608e2caeaa7778ae88
C++
ktekchan/Summer
/Recursion/knapsack.cpp
UTF-8
774
4.03125
4
[]
no_license
/* * Khushboo Tekchandani * Given weights and values of n items, put these items in a knapsack of * capacity W to get the maximum total value in the knapsack. * * Start from the back. If last item weight > w, then that cannot be included * else two cases, max (nth val included, nth value not included) */ #include <iostream> #include <cstdlib> using namespace std; int knapsack(int w, int wt[], int val[], int n){ if(n==0||w==0) return 0; if(wt[n-1]>w) return knapsack(w,wt,val,n-1); else return max(val[n-1]+knapsack(w-wt[n-1],wt,val,n-1) , knapsack(w,wt,val,n-1)); } int main(){ int val[] = {60,100,120}; int wt[] ={10,20,30}; int w = 50; int n = sizeof(val)/sizeof(val[0]); cout << knapsack(w,wt,val,n) << endl; return 0; }
true
47832aabb348580b26298a9b3d31972305314543
C++
blaneart/cpppool
/day08/ex01/span.cpp
UTF-8
1,718
3.375
3
[]
no_license
#include "span.hpp" span::span(unsigned int n) { this->n = n; this->length = 0; } span::span(const span& other) { this->n = other.n; this->length = other.length; this->vec = other.vec; } span& span::operator=(const span& other) { this->n = other.n; this->length = other.length; this->vec = other.vec; return *this; } span::~span() {} void span::addNumber(int number) { if (this->length < this->n) { this->vec.push_back(number); this->length++; } else throw TooManyNumbers(); } void span::addNumber(std::vector<int>::iterator begin, std::vector<int>::iterator end) { std::vector<int>::iterator old = this->vec.end(); int new_length = this->length + std::distance(begin, end); if (new_length > this->n) throw std::exception(); this->vec.insert(old, begin, end); this->length = new_length; } int span::shortestSpan(void) { if (this->length == 1 || this->length == 0) throw NotEnoughNumbers(); std::sort(this->vec.begin(), this->vec.end()); int short_span = INT_MAX; for (int i = 0; i < this->length - 1; i++) { if (vec[i + 1] - vec[i] < short_span) short_span = vec[i + 1] - vec[i]; } return (short_span); } const char* span::NotEnoughNumbers::what() const throw() { return "Not enough numbers to find span."; } const char* span::TooManyNumbers::what() const throw() { return "Impossible to add number."; } int span::longestSpan(void) { if (this->length == 1 || this->length == 0) throw NotEnoughNumbers(); int long_span = 0; int max_val = vec[0]; int min_val = vec[0]; for (int i = 1; i < this->length; i++) { if (max_val < vec[i]) max_val = vec[i]; if (min_val > vec[i]) min_val = vec[i]; } long_span = max_val - min_val; return (long_span); }
true
8f59ffa79e62d735f0ee37568c38452840e3562e
C++
RolloCriterion/Hangman-Game
/mainHungman.cpp
UTF-8
2,580
3.53125
4
[]
no_license
#include <iostream> #include <string> #include "headerHungman.h" void PrintIntro(); void PlayGame(); std::string GetValidGuess(); void PrintSummary(); bool AskToPlayAgain(); headerHungman Game; int main () { PrintIntro(); do { Game.Reset(); Game.GetSecretWord(); PlayGame(); } while (AskToPlayAgain()); } void PrintIntro() { std::cout << " _________\n" " | |\n" " | o\n" " | /|\\ \n" " | / \\ \n" " .|...........\n" " /|\\ /|\\ \n"; std::cout << "Welcome to the Hungman Game!\n"; std::cout << "Guess the secret word... you have five try for dont stay hung!\n\n"; } void PlayGame() { system("CLS"); //initialized and print the censored word Game.Gallows(); Game.InitializeCensoredWord(); while(!Game.IsGameWon() && Game.GetCurentTry() <= Game.GetMaxTries()) { std::string Guess = GetValidGuess(); system("CLS"); Game.SubmitValidGuess(Guess); Game.Gallows(); Game.WordLetters(Guess); Game.WrongLettersGuess(Guess); } PrintSummary(); } std::string GetValidGuess() { HungmanStatus Status = HungmanStatus::OnGallows; std::string Guess; do { //get first std::cout << "\nGuess the letters: "; getline(std::cin, Guess); Status = Game.CheckGuessValidity(Guess); switch(Status) { case HungmanStatus::NotLowercase: std::cout << "You have to type a lower case letter.\n"; break; case HungmanStatus::LetterTyped: std::cout << "You have already typed this letter!\n"; break; default: //Valid letter typed break; } }while(Status != HungmanStatus::OK); return Guess; } void PrintSummary() { if (Game.IsGameWon()) { std::cout << "Well Done! You are free now!\n\n"; } else { std::cout << "Game Over! You dead!"; } } bool AskToPlayAgain() { std::string Response; do { std::cout << "\nDo you want to play again (y/n)? "; getline(std::cin, Response); if ((Response[0] == 'y') || (Response[0] == 'Y')) { return true; } else if ((Response[0] == 'n') || (Response[0] == 'N')) { return false; } }while(Response[0] != 'y' || Response[0] != 'Y' || Response[0] != 'n' || Response[0] != 'N'); }
true
44476b9044256c58e8ed569ed793df527bd49d0c
C++
fenneishi/conPerfor
/sequPerfor/conTime.h
UTF-8
10,117
3.09375
3
[]
no_license
/* 模板参数有三种类型 偏特化的理解 不定长模板参数的偏特化方式 模板模板参数的偏特化方式 */ #if !defined(CONTime_H_) #define CONTime_H_ #include <fstream> #include <iostream> #include <string> #include <memory> //std::allocator() #include <ctime> //clock() #include <utility> //pair<key,T>(...) #include <functional> //std::less<int> #include <initializer_list> #include <vector> #include <deque> #include <list> #include <forward_list> #include <set> #include <map> #include <unordered_set> #include <unordered_map> using namespace std; namespace ConTimeSpace { template<typename _ConType> class _timeComputer { protected: _ConType con; long testNum; public: _timeComputer(long num):testNum(num),con(){} virtual size_t insertTime()=0; size_t copyConstructTime() { insertTime(); size_t start=clock(); _ConType temp(con); return clock()-start; } size_t copyAssignmentTime() { insertTime(); _ConType temp; size_t start=clock(); temp=con; return clock()-start; } }; template <typename _ConType,typename _EleType> class _seqConCom:public _timeComputer<_ConType> { private: typedef _timeComputer<_ConType> Father; public: _seqConCom(long num=10000):Father(num){}; virtual size_t insertTime() { size_t start=clock(); for(int i=0;i<Father::testNum;i++) { Father::con.push_back(_EleType()); } return clock()-start; } }; template <typename _ConType,typename _Key,typename _Data> class _mapCom:public _timeComputer<_ConType> { private: typedef _timeComputer<_ConType> Father; public: _mapCom(long num=10000):Father(num){}; virtual size_t insertTime() { size_t start=clock(); for(int i=0;i<Father::testNum;i++) { Father::con.insert(pair<_Key,_Data>( _Key(),_Data() ) ); } return clock()-start; } }; template <typename _ConType,typename _Key> class _setCom:public _timeComputer<_ConType> { private: typedef _timeComputer<_ConType> Father; public: _setCom(long num=10000):Father(num){}; virtual size_t insertTime() { size_t start=clock(); for(int i=0;i<Father::testNum;i++) { Father::con.insert(_Key()); } return clock()-start; } }; // 统一接口定义(泛化接口) template < template <typename... Tail > class con ,typename... Tail> class ConTime{}; // 定义各种sequence container接口(特化接口) // vector template < typename EleType> struct ConTime<vector,EleType> { typedef vector<EleType> conType; _seqConCom<conType,EleType> testor; ConTime(long num):testor(num){}; }; template < typename EleType,typename alloc> struct ConTime<vector,EleType,alloc> { typedef vector<EleType,alloc> conType; _seqConCom<conType,EleType> testor; ConTime(long num):testor(num){}; }; // list template < typename EleType> struct ConTime<list,EleType> { typedef list<EleType> conType; _seqConCom<conType,EleType> testor; ConTime(long num):testor(num){}; }; template < typename EleType,typename alloc> struct ConTime<list,EleType,alloc> { typedef list<EleType,alloc> conType; _seqConCom<conType,EleType> testor; ConTime(long num):testor(num){}; }; // deque template < typename EleType> struct ConTime<deque,EleType> { typedef deque<EleType> conType; _seqConCom<conType,EleType> testor; ConTime(long num):testor(num){}; }; template < typename EleType,typename alloc> struct ConTime<deque,EleType,alloc> { typedef deque<EleType,alloc> conType; _seqConCom<conType,EleType> testor; ConTime(long num):testor(num){}; }; // 定义各种set container接口(特化接口) // set template < class Key> struct ConTime<set,Key> { typedef set<Key> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Compare> struct ConTime<set,Key,Compare> { typedef set<Key,Compare> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Compare,class Allocator> struct ConTime<set,Key,Compare,Allocator> { typedef set<Key,Compare,Allocator> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; // multiset template < class Key> struct ConTime<multiset,Key> { typedef multiset<Key> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Compare> struct ConTime<multiset,Key,Compare> { typedef multiset<Key,Compare> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Compare,class Allocator> struct ConTime<multiset,Key,Compare,Allocator> { typedef multiset<Key,Compare,Allocator> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; // unordered_set template < class Key> struct ConTime<unordered_set,Key> { typedef unordered_set<Key> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Hash> struct ConTime<unordered_set,Key,Hash> { typedef unordered_set<Key,Hash> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Hash,class KeyEqual> struct ConTime<unordered_set,Key,Hash,KeyEqual> { typedef unordered_set<Key,Hash,KeyEqual> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Hash,class KeyEqual,class Allocator> struct ConTime<unordered_set,Key,Hash,KeyEqual,Allocator> { typedef unordered_set<Key,Hash,KeyEqual,Allocator> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; // unordered_multiset template < class Key> struct ConTime<unordered_multiset,Key> { typedef unordered_multiset<Key> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Hash> struct ConTime<unordered_multiset,Key,Hash> { typedef unordered_multiset<Key,Hash> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Hash,class KeyEqual> struct ConTime<unordered_multiset,Key,Hash,KeyEqual> { typedef unordered_multiset<Key,Hash,KeyEqual> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; template < class Key,class Hash,class KeyEqual,class Allocator> struct ConTime<unordered_multiset,Key,Hash,KeyEqual,Allocator> { typedef unordered_set<Key,Hash,KeyEqual,Allocator> conType; _setCom<conType,Key> testor; ConTime(long num):testor(num){}; }; // // 定义各种map container接口(特化接口) // map template < class Key,class Data> struct ConTime<map,Key,Data> { typedef map<Key,Data> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Compare> struct ConTime<map,Key,Data,Compare> { typedef map<Key,Data,Compare> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Compare,class Allocator> struct ConTime<map,Key,Data,Compare,Allocator> { typedef map<Key,Data,Compare,Allocator> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; // multimap template < class Key,class Data> struct ConTime<multimap,Key,Data> { typedef multimap<Key,Data> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Compare> struct ConTime<multimap,Key,Data,Compare> { typedef multimap<Key,Data,Compare> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Compare,class Allocator> struct ConTime<multimap,Key,Data,Compare,Allocator> { typedef multimap<Key,Data,Compare,Allocator> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; // unordered_map template < class Key,class Data> struct ConTime<unordered_map,Key,Data> { typedef unordered_map<Key,Data> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Hash> struct ConTime<unordered_map,Key,Data,Hash> { typedef unordered_map<Key,Data,Hash> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Hash,class KeyEqual> struct ConTime<unordered_map,Key,Data,Hash,KeyEqual> { typedef unordered_map<Key,Data,Hash,KeyEqual> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Hash,class KeyEqual,class Allocator> struct ConTime<unordered_map,Key,Data,Hash,KeyEqual,Allocator> { typedef unordered_map<Key,Data,Hash,KeyEqual,Allocator> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; // unordered_multimap template < class Key,class Data> struct ConTime<unordered_multimap,Key,Data> { typedef unordered_multimap<Key,Data> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Hash> struct ConTime<unordered_multimap,Key,Data,Hash> { typedef unordered_multimap<Key,Data,Hash> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Hash,class KeyEqual> struct ConTime<unordered_multimap,Key,Data,Hash,KeyEqual> { typedef unordered_multimap<Key,Data,Hash,KeyEqual> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; template < class Key,class Data,class Hash,class KeyEqual,class Allocator> struct ConTime<unordered_multimap,Key,Data,Hash,KeyEqual,Allocator> { typedef unordered_map<Key,Data,Hash,KeyEqual,Allocator> conType; _mapCom<conType,Key,Data> testor; ConTime(long num):testor(num){}; }; }//namespace ConTimeSpace #endif // CONTime_H_
true
20cee77468790781abc6dcde6504ecd229bee74e
C++
jefersonla/robozino
/utils/old_code/teste.ino
UTF-8
9,955
2.859375
3
[ "MIT" ]
permissive
/*Libraries*/ //#include <Ultrasonic.h> /* Define Matrix Grid */ #define n 3 #define a (n * 15) #define m (n + 2) int grid[m][m]; int heuristic[n][n]; /*Inserir uma interface gráfica para visualização do A-Star */ int processing[n][n]; int numerador = 0; int iD; /* MAKE IT STOP */ int fim = 0; int counter = 0; /* Define Goal */ int GoalRow = 1; int GoalCol = 3; /* Define Actual Point */ int ActualRow; int ActualCol; /* Define Next Point */ int NextRow; int NextCol; /* Define StartPoint */ int StartRow = 3; int StartCol = 1; /* Function g(n) - Cost */ int ort = 10; // Define ortogonal's(up, down, left, right) cost as 10 int obstacle = 1000; //Define obstacle /* Variables */ int i; int j; int z;//Indice utilizado nos vetores path int p; int pathRow[a]; int pathCol[a]; int finalRow[m]; int finalCol[m]; void intervencao(){ for(i = 0; i < m; i++){ for(j = 0; j < m; j++){ //serial.println(grid[i][j]); fim = 1; } } } void setup() { Serial.begin(9600); //serial.println("Estou no Setup!"); heuristicFunction(); ActualRow = StartRow; ActualCol = StartCol; //O caminho obviamente inicia pelo ponto inicial pathRow[0] = StartRow; pathCol[0] = StartCol; z = 1; // Setando todo o grid para 1000, isso irá auxiliar no momento da execução do A* for(i = 0; i < m; i++){ for(j = 0; j < m; j++){ grid[i][j] = 1000; } } grid[1][2] = 16; for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ processing[i][j] = numerador; numerador ++; } } iD = processing[StartRow - 1][StartCol - 1]; Serial.write(iD); //calibratemotors() } void loop() { //serial.println("Inicio do loop!"); delay(1000); if(!fim){ a_star(); delay(1000); findPath(); delay(1000); goAhead(); delay(1000); printgrid(); printheuristic(); delay(1000); if(isFim()){ defineWay(); delay(10000); } delay(2000); //intervencao(); } else{ //Don't do nothing... } //serial.println("Fim do loop!"); } void printpath(){ //serial.println("Este eh ao caminho percorrido ate aqui:"); for(i = 0; i < z; i++){ //serial.print(pathRow[i]); //serial.print(" "); //serial.println(pathCol[i]); } } void printheuristic(){ //serial.println("Este eh a heuristica do labirinto, resolvido por Manhanttan:"); for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ //serial.print(heuristic[i][j]); //serial.print(" "); } //serial.print("\n"); } } void printgrid(){ //serial.println("Este eh o grid do labirinto, resolvido por A*:"); for(i = 0; i < m; i++){ for(j = 0; j < m; j++){ //serial.print(grid[i][j]); //serial.print(" "); } //serial.print("\n"); } } boolean isFim(){ //serial.println("Verificando se eh o fim..."); //This funcion will see if we reach the goal //if ActualPoint is equal GoalPoint if(ActualRow == GoalRow && ActualCol == GoalCol){ fim = 1; return true; } else{ return false; } } /* PD Functions - Make the Robot drive straight*/ /* Obstacles Detector Functions */ boolean isObstacle(int x, int y){ //serial.println("Verificando obstaculos..."); //This funcion will see if there is a object on a point in the matrix that is a obstacles if (x == 0 or y == 0 or x == 4 or y == 4){ return true; } else{ return false; } } /* Robot Moviments Functions */ //This follows moviments has as function, besides move the robot aroud the grid, make the robo orientation be always to the North, this can make it easier to move the robot void goForward(){ //serial.println("Movendo para frente..."); //Move robot forward } void goBackward(){ //serial.println("Movendo para tras..."); //Move robot backward } void turnLeft(){ //serial.println("Movendo para esquerda..."); //Turn robot left *doesn't mean change matriz position, move robot 90º on his atual position //goForward() *go to other position on the grid //Turn robot right } void turnRight(){ //serial.println("Movendo para direita..."); //Turn robot right //goForward() //Turn robot left } //Just change the robot orientation void turnAround(){ //serial.println("Girando..."); //Turn robot right } /* A Star Functions */ int aux1; int aux2; /* Function h(n) - Define Heuristic using Manhattan Distance*/ void heuristicFunction(){ //serial.println("Calculando matriz heuristica..."); for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ aux1 = abs(i - (GoalRow-1)); aux2 = abs(j - (GoalCol-1)); aux1 = aux1 + aux2; heuristic[i][j] = aux1; //serial.print("heuristic["); //serial.print(i); //serial.print("]["); //serial.print(j); //serial.print("] = "); //serial.println(heuristic[i][j]); } } } /* Function f(n) = g(n) + h(n) */ void a_star(){ //serial.println("Aplicando A* em meus vizinhos..."); /* int StartRow = 3; int StartCol = 1; I need o check all around, but skip previous calculate... */ //Seta o grid como 2000 para evitar loop infinito grid[ActualRow][ActualCol] = 2000; //Fist test forward (forward is -1 of the ActualPosition Row) setGrid(ActualRow-1,ActualCol); //Then test right (right is +1 of the ActualPosition Col) turnAround(); setGrid(ActualRow,ActualCol+1); //Then test backward (backward is +1 of the ActualPosition Row) turnAround(); setGrid(ActualRow+1,ActualCol); //Then test left (left is -1 of the ActualPosition Col), turnAround(); setGrid(ActualRow,ActualCol-1); //Finally turn back to Origin orientation turnAround(); } void findPath(){ //serial.println("Definindo rota..."); p = z - 1; int padrao = 1000; for(i = 1; i < m; i++){ for(j = 1; j < m; j++){ if(grid[i][j] < padrao){ NextRow = i; NextCol = j; //serial.print(NextRow); //serial.println(NextCol); padrao = grid[i][j]; } } } } void setGrid(int x, int y){ //serial.println("Calculando heuristica mais custo..."); int q = x; int r = y; if (isObstacle(q, r)){ if (q >= 0 && r >= 0){ grid[x][y] = obstacle; return; } } if (grid[x][y] == 2000){ //(grid[x][y] == 2000) return; } if (grid[x][y] == 16){ //(grid[x][y] == 2000) return; } else{ grid[x][y] = 0; grid[x][y] = 10 + heuristic[x-1][y-1]; // NAO //int w = z; //while(pathRow[w] != StartRow && pathCol[w] != StartCol){ // grid[x][y] += heuristic[pathRow[w-1]][pathCol[w-1]]; // w -= 1; // } // NAO //serial.print("Este eh meu indice Z: "); //serial.println(z); p = z-1; int lock2 = 1; printpath(); while(lock2){ if(pathRow[p] == StartRow && pathCol[p] == StartCol){ lock2 = 0; } else{ //serial.print(pathRow[p]); //serial.print(" "); //serial.println(pathCol[p]); grid[x][y] += heuristic[pathRow[p]-1][pathCol[p]-1]; p-=1; } } } } void goAhead(){ //serial.println("Indo para proxima posicao..."); //serial.print("Linha: "); //serial.print(NextRow); //serial.print(" Coluna: "); //serial.println(NextCol); //É necessario se posicionar neste novo grid //Verifico se próxima posição é um vizinho if(ActualRow == NextRow){ //Se for, eles estão na mesma linha, devo left ou right while(ActualCol != NextCol){ if(ActualCol < NextCol){ turnRight(); ActualRow = NextRow; ActualCol +=1; } else{ turnLeft(); ActualRow = NextRow; ActualCol -= 1; } iD = processing[ActualRow - 1][ActualCol - 1]; Serial.write(iD); //serial.write("\n"); pathRow[z] = ActualRow; pathCol[z] = ActualCol; z += 1; } return; } if(ActualCol == NextCol){ //Se for, eles estão na mesma coluna, devo forward ou backward while(ActualRow != NextRow){ if(ActualRow < NextRow){// turn right goBackward(); ActualRow += 1; ActualCol = NextCol; } else{ goForward(); ActualRow -= 1; ActualCol = NextCol; } iD = processing[ActualRow - 1][ActualCol - 1]; Serial.write(iD); //serial.write("\n"); pathRow[z] = ActualRow; pathCol[z] = ActualCol; z += 1; } return; } //Caso não seja vizinho, devo regredir no grid, retrocendendo na lista percorrida até alcançar um vizinho, //serial.println("Nao e vizinho............................."); p -= 1; if(ActualRow == pathRow[p]){ //Se for, eles estão na mesma linha, devo left ou right if(ActualCol < pathCol[p]){ turnRight(); } else{ turnLeft(); } ActualRow = pathRow[p]; ActualCol = pathCol[p]; iD = processing[ActualRow - 1][ActualCol - 1]; Serial.write(iD); //serial.write("\n"); pathRow[z] = ActualRow; pathCol[z] = ActualCol; z += 1; goAhead(); } if(ActualCol == pathCol[p]){ //Se for, eles estão na mesma coluna, devo forward ou backward if(ActualRow < pathRow[p]){// turn right goBackward(); } else{ goForward(); } ActualRow = pathRow[p]; ActualCol = pathCol[p]; iD = processing[ActualRow - 1][ActualCol - 1]; Serial.write(iD); //serial.write("\n"); pathRow[z] = ActualRow; pathCol[z] = ActualCol; z += 1; goAhead(); } goAhead(); //? } void defineWay(){ p = z; int lock = 1; while(lock){ if(pathRow[p] == StartRow && pathCol[p] == StartCol){ lock = 0; } else{ counter++; p--; } } for(i = 0; i < counter; i++){ finalRow[i] = pathRow[p]; finalCol[i] = pathCol[p]; p++; } numerador = n*n; Serial.write(numerador); }
true
fdc63d06465d85d3fae42e072ff5d0698d7a5b31
C++
BlitzModder/dava.engine
/Modules/TArc/Sources/TArc/Qt/QtSize.h
UTF-8
232
2.640625
3
[]
permissive
#pragma once #include <Base/Any.h> #include <QSize> namespace DAVA { template <> struct AnyCompare<QSize> { static bool IsEqual(const Any& v1, const Any& v2) { return v1.Get<QSize>() == v2.Get<QSize>(); } }; }
true
ae01734f455d41d4e2e1b0f2ffb3c265c1c69bac
C++
chasejohnson3/Recent-Programming-Projects
/Spring 2017 Ventures/StringPractice/main.cpp
UTF-8
204
2.859375
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string words; cout << "Give me a few words, please." << endl; getline(cin, words); cout << words; return 0; }
true
710376e887b1ec799dcdd088d74dae8aba7385ab
C++
dhkim0821/Humanoid_2018
/RobotSystems/Valkyrie/Valkyrie_Definition.h
UTF-8
2,209
2.515625
3
[]
no_license
#ifndef VALKYRIE_DEFINITION #define VALKYRIE_DEFINITION namespace valkyrie_joint{ constexpr int virtual_X = 0; constexpr int virtual_Y = 1; constexpr int virtual_Z = 2; constexpr int virtual_Rx = 3; constexpr int virtual_Ry = 4; constexpr int virtual_Rz = 5; constexpr int leftHipYaw = 6; // 1st joint constexpr int leftHipRoll = 7; constexpr int leftHipPitch = 8; constexpr int leftKneePitch = 9; constexpr int leftAnklePitch = 10; constexpr int leftAnkleRoll = 11; constexpr int rightHipYaw = 12; constexpr int rightHipRoll = 13; constexpr int rightHipPitch = 14; constexpr int rightKneePitch = 15; constexpr int rightAnklePitch = 16; constexpr int rightAnkleRoll = 17; constexpr int torsoYaw = 18; constexpr int torsoPitch = 19; constexpr int torsoRoll = 20; constexpr int leftShoulderPitch = 21; constexpr int leftShoulderRoll = 22; constexpr int leftShoulderYaw = 23; constexpr int leftElbowPitch = 24; constexpr int leftForearmYaw = 25; constexpr int lowerNeckPitch = 26; constexpr int neckYaw = 27; constexpr int upperNeckPitch = 28; constexpr int rightShoulderPitch = 29; constexpr int rightShoulderRoll = 30; constexpr int rightShoulderYaw = 31; constexpr int rightElbowPitch = 32; constexpr int rightForearmYaw = 33; constexpr int virtual_Rw = 34; } namespace valkyrie{ // Simple version constexpr int num_q = 35; constexpr int num_qdot = 34; constexpr int num_act_joint = 28; constexpr int num_virtual = 6; constexpr double servo_rate = 0.001; constexpr int num_leg_joint = 6; constexpr int upper_body_start_jidx = valkyrie_joint::leftShoulderPitch; constexpr int num_upper_joint = valkyrie_joint::virtual_Rw - valkyrie_joint::leftShoulderPitch; }; namespace valkyrie_link{ constexpr int pelvis = 0; constexpr int torso = 1; constexpr int rightCOP_Frame = 2; constexpr int leftCOP_Frame = 3; constexpr int rightPalm = 4; constexpr int leftPalm = 5; constexpr int head = 6; constexpr int rightFoot = 7; constexpr int leftFoot = 8; } #endif
true
91ade7d2238ee4b090663dd91d7572cac4f2d133
C++
taggelos/JobExecutor
/fileUtil.cpp
UTF-8
3,840
3.34375
3
[]
no_license
//Function Definitions #include "fileUtil.h" void paramError(char * programName ,const char * reason){ //Display the problem cerr << reason << ", please try again." << endl; //Show the usage and exit. cerr << "Usage : " << programName << " -d <DOCUMENT> [-w <NUMBER OF WORKERS>]" << endl; exit(1); } //Print Format when problem with command occurs void commandError(){ cerr << "############################################################################"<<endl; cerr << "#Invalid command!" <<endl; cerr << "#Available commands :\t/search <q1> <q2> <q3> <q4> ... <q10> -d <INTEGER>" << endl; cerr << "#\t\t\t" << "/mincount <WORD>" << endl << "#\t\t\t" << "/maxcount <WORD>" << endl << "#\t\t\t" << "/wc" << endl << "#\t\t\t" << "/exit" << endl; cerr << "############################################################################"<<endl; } //Read input File char** readFile(char* myFile, int& lines, int& fileChars){ FILE * file; lines = 0; file = fopen (myFile, "r"); if (file == NULL){ cerr << "Error opening file" << endl; exit(2); } else { while(!feof(file)) if(fgetc(file) == '\n') lines++; char ** documents = new char*[lines]; rewind(file); //Lines char * mystring = NULL; size_t n = 0; for (int i=0; i<lines;i++){ ssize_t size = getline(&mystring, &n, file); fileChars+=(int)size; if(mystring[size-1]=='\n') mystring[size-1]='\0'; char *token = strtok(mystring," \t"); //For first character of first line we check without using atoi if (token==NULL || !numberCheck(token) || atoi(mystring)!=i ) { cerr <<"Invalid number close in line "<< i << " of file" <<endl; exit(4); } documents[i] = new char[size+1-strlen(token)]; strcpy(documents[i],mystring+strlen(token)+1); //cout << " " << documents[i] << " "<< endl; } if(mystring!=NULL) free(mystring); fclose (file); return documents; } } //Read input File char** readPathFile(char* myFile, int &lines){ FILE * file; lines = 0; file = fopen (myFile, "r"); if (file == NULL){ cerr << "Error opening file" << endl; exit(2); } else { while(!feof(file)) if(fgetc(file) == '\n') lines++; char ** documents = new char*[lines]; rewind(file); //Lines char * mystring = NULL; size_t n = 0; for (int i=0; i<lines;i++){ ssize_t size = getline(&mystring, &n, file); if(mystring[size-1]=='\n') mystring[size-1]='\0'; documents[i] = new char[size+1]; strcpy(documents[i],mystring); } if(mystring!=NULL) free(mystring); fclose (file); return documents; } } //Check the arguments given by the user void inputCheck(int argc, char* argv[], char*& inputFile, int& workersNum){ if (argc == 3){ if (strcmp(argv[1],"-d")) paramError(argv[0], "You need to provide input file"); inputFile = argv[2]; } else if (argc== 5) { if (!strcmp(argv[1],"-d") && !strcmp(argv[3],"-w")){ inputFile = argv[2]; if (numberCheck(argv[4])) workersNum = atoi(argv[4]); else workersNum = 0; //Invalid for negative or zero result if (workersNum <=0) paramError(argv[0], "This is not an appropriate number"); } else if (!strcmp(argv[3],"-d") && !strcmp(argv[1],"-w")){ inputFile = argv[4]; if (numberCheck(argv[2])) workersNum = atoi(argv[2]); else workersNum = 0; //Invalid for negative or zero result if (workersNum <=0) paramError(argv[0], "This is not an appropriate number"); } else { paramError(argv[0], "Invalid arguments"); } } else paramError(argv[0], "This is not an appropriate syntax"); cout << "Arguments taken : " << inputFile << " " << workersNum << endl; } void createLog(){ struct stat st = {}; if(stat("log", &st) == -1) mkdir("log", 0700); } //Free a 2D array knowing its size with lineNum void free2D(char ** paths, const int& lineNum){ for (int i=0; i < lineNum ; i++) { delete[] paths[i]; } delete[] paths; }
true
13ec633c69e03e8eb62997b72cd993b01234d17b
C++
realn/Trader
/kikiGui/GUIPanel.h
UTF-8
948
2.53125
3
[]
no_license
#pragma once #include <memory> #include "GUIRect.h" #include "GUIWidgetContainer.h" namespace gui { class CPanel : public CRect , public CWidgetContainer { protected: glm::vec2 mContentPos; public: CPanel(cb::string const& id, glm::vec4 const& backColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), glm::vec4 const& contentMargin = glm::vec4(0.0f), Align const contentAlign = Align::Default) : CRect(id, backColor), CWidgetContainer(contentMargin, contentAlign) {} CPanel(CPanel&&) = default; virtual ~CPanel() {} virtual void Update(float const timeDelta); virtual void UpdateWidget(CUpdateContext const& ctx, glm::vec2 const& spaceSize); virtual void Render(CRenderContext& ctx, glm::vec2 const& pos) const; virtual CWidget* FindWidgetById(cb::string const& id) override; virtual const CWidget* FindWidgetById(cb::string const& id) const override; }; }
true
bb74ed8163d6c800d74be4b9a6d60f79642aec98
C++
anoriar/MatrixEigenValues
/CharPolynomial/Matrix.h
UTF-8
288
2.546875
3
[]
no_license
#pragma once #include "FileReader.h" class Matrix { public: Matrix(int size); ~Matrix(); void Matrix::PutElem(int i, int j, double elem); double Matrix::GetElem(int i, int j); int Matrix::GetSize(); void Matrix::Print(); private: int size; vector<vector<double>> matrix; };
true
b183cdb7fe4a2690416e68025b3366086f0793c1
C++
lefunal/cursoProgramacionComputadores
/ejercicios/e12-funcionesRecursivas/factorial-exp.cpp
UTF-8
5,103
3.53125
4
[]
no_license
// Esqueleto de C++ # include <iostream> // Input/Output Stream: cin, cout etc. # include <fstream> // Para leer y escribir en archivos. # include <cmath> // math.h: pow(x,y), fabs(x), abs(x), cos(x), sin(x), acos(x), exp(x), log(x), log10(x) etc. # include <iomanip> // Input/output manipulators - formateo de salida: setw etc. # include <cstdio> // standard input-output : printf: %d ó %i: integer, %f: float, %lf: double, %e - %E: exponente, %c: char, %s:string # include <cstdlib> // stdlib.h: standard library; para: system ("pause") etc.; # include <sstream> using namespace std; // si no se usa --> usar extensión ".h" ej: # include <iostream.h> // ......................... int facotorial_0(); int facotorial_1(); int facotorial_2(); int facotorial_3(); int factorial(int n); int factorialCiclos(int n); int func_sumatoria_n_mas_uno_1(); int func_sumatoria_n_mas_uno_2(); int func_sumatoria_n_mas_uno_3(); int func_sumatoria_n_mas_uno(int n); int func_sumatoria_n_mas_uno_ciclos(int n); double func_exp_0(double x); double func_exp_1(double x); double func_exp_2(double x); double func_exp(double x, int n_terminos); double func_exp_ciclos(double x, int n_terminos); int main() { cout << "Factorial: " << endl; cout << "Usando una funcion por cada n " << endl; cout << "3! = " << facotorial_3() << endl; cout << endl; cout << "Usando una funcion recursiva" << endl; cout << "3! = " << factorial(3) << endl; cout << endl; cout << "Usando ciclos" << endl; cout << "3! = " << factorialCiclos(3) << endl; cout << endl; cout << "---------------------------------- " << endl; cout << "Sumatoria (n+1) de n = 1 hasta m: " << endl; cout << "Usando una funcion por cada n " << endl; cout << "sumatoria(n+1) = " << func_sumatoria_n_mas_uno_3() << endl; cout << endl; cout << "Usando una funcion recursiva" << endl; cout << "sumatoria(n+1) = " << func_sumatoria_n_mas_uno(3) << endl; cout << endl; cout << "Usando ciclos" << endl; cout << "sumatoria(n+1) = " << func_sumatoria_n_mas_uno_ciclos(3) << endl; cout << endl; cout << "---------------------------------- " << endl; cout << "e^x usando series de Taylor: " << endl; cout << "Usando una funcion por cada n " << endl; cout << "e^2 = " << func_exp_2(2) << endl; cout << endl; cout << "Usando una funcion recursiva" << endl; cout << "e^2 = " << func_exp(2, 10) << endl; cout << endl; cout << "Usando ciclos" << endl; cout << "e^2 = " << func_exp_ciclos(2, 10) << endl; cout << endl; system ("pause"); return 0; } int facotorial_0(){ return 1; } int facotorial_1(){ return 1 * facotorial_0(); } int facotorial_2(){ return 2 * facotorial_1(); } int facotorial_3(){ return 3 * facotorial_2(); } int factorial(int n){ if(n == 0){ return 1; } else{ return n * factorial(n - 1); } } int factorialCiclos(int n){ int factorialMMenosUno = 1; int factorialM = factorialMMenosUno; for(int m = 1; m <= n; m = m + 1){ factorialM = m * factorialMMenosUno; factorialMMenosUno = factorialM; // Se actualiza para la proxima iteracion } return factorialM; } int func_sumatoria_n_mas_uno_1(){ return 1 + 1; } int func_sumatoria_n_mas_uno_2(){ return (2 + 1) + func_sumatoria_n_mas_uno_1(); } int func_sumatoria_n_mas_uno_3(){ return (3 + 1) + func_sumatoria_n_mas_uno_2(); } int func_sumatoria_n_mas_uno(int n){ if(n == 1){ return 1 + 1; } else{ return (n + 1) + func_sumatoria_n_mas_uno(n - 1); } } int func_sumatoria_n_mas_uno_ciclos(int n){ int sumatoriaMMenosUno = 1 + 1; //inicializa a func_sumatoria_n_mas_uno_ciclos(1) int sumatoriaM = sumatoriaMMenosUno; for(int m = 2; m <= n; m = m + 1){ sumatoriaM = (m + 1) + sumatoriaMMenosUno; sumatoriaMMenosUno = sumatoriaM; // Se actualiza para la proxima iteracion } return sumatoriaM; } double func_exp_0(double x){ return pow(x, 0)/((double)factorial(0)); } double func_exp_1(double x){ return pow(x, 1)/((double)factorial(1)) + func_exp_0(x); } double func_exp_2(double x){ return pow(x, 2)/((double)factorial(2)) + func_exp_1(x); } double func_exp(double x, int n_terminos){ if(n_terminos == 0){ return pow(x, 0)/((double)factorial(0)); } else{ return pow(x, n_terminos)/((double)factorial(n_terminos)) + func_exp(x, n_terminos - 1); } } double func_exp_ciclos(double x, int n_terminos){ double sumaTerminosAnteriores = pow(x, 0)/((double)factorial(0)); double sumaTerminos = sumaTerminosAnteriores; for(int n = 1; n <= n_terminos; n = n + 1){ sumaTerminos = pow(x, n)/((double)factorial(n)) + sumaTerminosAnteriores; sumaTerminosAnteriores = sumaTerminos; // Se actualiza para la proxima iteracion } return sumaTerminos; } //....... FIN ...............
true
54ec3ba760213487dea854527c3bdb7db7e982ec
C++
Andrey246/POO-TEMA1
/TEMA2/Premiu.cpp
UTF-8
651
2.828125
3
[]
no_license
#include <Premiu.h> Premiu::Premiu(std::string nume, std::string data_acordarii) { this->nume_premiu = nume; this->data_acordarii = data_acordarii; } Premiu::Premiu(const Premiu& premiu) { this->nume_premiu = premiu.nume_premiu; this->data_acordarii = premiu.data_acordarii; } Premiu& Premiu::operator=(const Premiu& premiu) { this->nume_premiu = premiu.nume_premiu; this->data_acordarii = premiu.data_acordarii; return *this; } std::ostream& operator<<(std::ostream& out, Premiu& premiu) { out << "Premiu: " << premiu.nume_premiu << " Data acordarii: " << premiu.data_acordarii << '\n'; return out; }
true
0487b2848f0d88382e1a56af2ea23e90d9f02c6f
C++
TUM-I5/MolSim
/src/outputWriter/XYZWriter.cpp
UTF-8
1,001
2.546875
3
[]
no_license
/* * XYZWriter.cpp * * Created on: 01.03.2010 * Author: eckhardw */ #include "outputWriter/XYZWriter.h" #include <iomanip> #include <sstream> namespace outputWriter { XYZWriter::XYZWriter() = default; XYZWriter::~XYZWriter() = default; void XYZWriter::plotParticles(std::list<Particle> particles, const std::string &filename, int iteration) { std::ofstream file; std::stringstream strstr; strstr << filename << "_" << std::setfill('0') << std::setw(4) << iteration << ".xyz"; file.open(strstr.str().c_str()); file << particles.size() << std::endl; file << "Generated by MolSim. See http://openbabel.org/wiki/XYZ_(format) for " "file format doku." << std::endl; for (auto &p : particles) { std::array<double, 3> x = p.getX(); file << "Ar "; file.setf(std::ios_base::showpoint); for (auto &xi : x) { file << xi << " "; } file << std::endl; } file.close(); } } // namespace outputWriter
true
3ab46cb94a2298e30ac33e09af965c097329a214
C++
KratosMultiphysics/Kratos
/kratos/mpi/utilities/mpi_search_utilities.h
UTF-8
15,116
2.578125
3
[ "BSD-3-Clause" ]
permissive
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Vicente Mataix Ferrandiz // #pragma once // System includes #include <vector> #include <numeric> // External includes // Project includes #include "includes/data_communicator.h" namespace Kratos { /** * @class MPISearchUtilities * @ingroup KratosCore * @brief This class provides the utilities for MPI search * @author Vicente Mataix Ferrandiz */ class MPISearchUtilities { public: ///@name Type Definitions ///@{ /// Define zero tolerance as Epsilon static constexpr double ZeroTolerance = std::numeric_limits<double>::epsilon(); ///@} ///@name Operations ///@{ /** * @brief MPISynchronousPointSynchronization prepares synchronously the coordinates of the points for MPI search. * @param itPointBegin Iterator to the beginning of the points range * @param itPointEnd Iterator to the end of the points range * @param rAllPointsCoordinates vector where the computed coordinates will be stored * @param rDataCommunicator The data communicator * @tparam TPointIteratorType The type of the point iterator */ template<typename TPointIteratorType> static void MPISynchronousPointSynchronization( TPointIteratorType itPointBegin, TPointIteratorType itPointEnd, std::vector<double>& rAllPointsCoordinates, const DataCommunicator& rDataCommunicator ) { // First check that the points are the same in all processes int number_of_points, total_number_of_points; const bool all_points_are_the_same = CheckAllPointsAreTheSameAndCalculateNumberOfPoints(itPointBegin, itPointEnd, number_of_points, total_number_of_points, rDataCommunicator); KRATOS_DEBUG_ERROR_IF(number_of_points < 0) << "The number of points is negative" << std::endl; KRATOS_DEBUG_ERROR_IF(total_number_of_points < 0) << "The total number of points is negative" << std::endl; // We synchronize the points SynchronizePoints(itPointBegin, itPointEnd, rAllPointsCoordinates, rDataCommunicator, all_points_are_the_same, number_of_points, total_number_of_points); } /** * @brief MPISynchronousPointSynchronizationWithRecvSizes prepares synchronously the coordinates of the points for MPI search including the recv sizes * @details With recv sizes * @param itPointBegin Iterator to the beginning of the points range * @param itPointEnd Iterator to the end of the points range * @param rAllPointsCoordinates vector where the computed coordinates will be stored * @param rDataCommunicator The data communicator * @return The resulting whole radius vector * @tparam TPointIteratorType The type of the point iterator */ template<typename TPointIteratorType> static std::vector<int> MPISynchronousPointSynchronizationWithRecvSizes( TPointIteratorType itPointBegin, TPointIteratorType itPointEnd, std::vector<double>& rAllPointsCoordinates, const DataCommunicator& rDataCommunicator ) { // First check that the points are the same in all processes int number_of_points, total_number_of_points; const bool all_points_are_the_same = CheckAllPointsAreTheSameAndCalculateNumberOfPoints(itPointBegin, itPointEnd, number_of_points, total_number_of_points, rDataCommunicator); KRATOS_DEBUG_ERROR_IF(number_of_points < 0) << "The number of points is negative" << std::endl; KRATOS_DEBUG_ERROR_IF(total_number_of_points < 0) << "The total number of points is negative" << std::endl; // We synchronize the points SynchronizePoints(itPointBegin, itPointEnd, rAllPointsCoordinates, rDataCommunicator, all_points_are_the_same, number_of_points, total_number_of_points); // Get recv_sizes const auto recv_sizes = SynchronizeRecvSizes(number_of_points, all_points_are_the_same, rDataCommunicator); return recv_sizes; } /** * @brief MPISynchronousPointSynchronizationWithRadius prepares synchronously the coordinates of the points for MPI search including radius * @details With radius * @param itPointBegin Iterator to the beginning of the points range * @param itPointEnd Iterator to the end of the points range * @param rAllPointsCoordinates vector where the computed coordinates will be stored * @param rRadius The radius of the points * @param rDataCommunicator The data communicator * @return The resulting whole radius vector * @tparam TPointIteratorType The type of the point iterator */ template<typename TPointIteratorType> static std::vector<double> MPISynchronousPointSynchronizationWithRadius( TPointIteratorType itPointBegin, TPointIteratorType itPointEnd, std::vector<double>& rAllPointsCoordinates, const std::vector<double>& rRadius, const DataCommunicator& rDataCommunicator ) { // First check that the points are the same in all processes int number_of_points, total_number_of_points; const bool all_points_are_the_same = CheckAllPointsAreTheSameAndCalculateNumberOfPoints(itPointBegin, itPointEnd, number_of_points, total_number_of_points, rDataCommunicator); KRATOS_DEBUG_ERROR_IF(number_of_points < 0) << "The number of points is negative" << std::endl; KRATOS_DEBUG_ERROR_IF(total_number_of_points < 0) << "The total number of points is negative" << std::endl; // We synchronize the points SynchronizePoints(itPointBegin, itPointEnd, rAllPointsCoordinates, rDataCommunicator, all_points_are_the_same, number_of_points, total_number_of_points); // Get recv_sizes const auto recv_sizes = SynchronizeRecvSizes(number_of_points, all_points_are_the_same, rDataCommunicator); // Get radius const auto radius = SynchronizeRadius(recv_sizes, rRadius, rDataCommunicator); return radius; } ///@} private: ///@name Private Operations ///@{ /** * @details Synchronizes points between different processes. * @details Synchonously * @param itPointBegin Iterator pointing to the beginning of the range of points * @param itPointEnd Iterator pointing to the end of the range of points * @param rAllPointsCoordinates Vector to store the synchronized points' coordinates * @param rDataCommunicator Object for data communication between processes * @param AllPointsAreTheSame Flag indicating if all points are the same * @param NumberOfPoints Local number of points to be synchronized * @param TotalNumberOfPoints Total number of points across all processes * @tparam TPointIteratorType The type of the point iterator */ template<typename TPointIteratorType> static void SynchronizePoints( TPointIteratorType itPointBegin, TPointIteratorType itPointEnd, std::vector<double>& rAllPointsCoordinates, const DataCommunicator& rDataCommunicator, const bool AllPointsAreTheSame, const int NumberOfPoints, const int TotalNumberOfPoints ) { // Initialize local points coordinates std::size_t counter = 0; array_1d<double, 3> coordinates; unsigned int i_coord; std::vector<double> send_points_coordinates(NumberOfPoints * 3); for (auto it_point = itPointBegin ; it_point != itPointEnd ; ++it_point) { noalias(coordinates) = it_point->Coordinates(); for (i_coord = 0; i_coord < 3; ++i_coord) { send_points_coordinates[3 * counter + i_coord] = coordinates[i_coord]; } ++counter; } // If all points are the same if (AllPointsAreTheSame) { rAllPointsCoordinates = send_points_coordinates; } else { // If not // MPI information const int world_size = rDataCommunicator.Size(); // Getting global number of points std::vector<int> points_per_partition(world_size); std::vector<int> send_points_per_partition(1, NumberOfPoints); rDataCommunicator.AllGather(send_points_per_partition, points_per_partition); // Getting global coordinates rAllPointsCoordinates.resize(TotalNumberOfPoints * 3); // Generate vectors with sizes for AllGatherv std::vector<int> recv_sizes(world_size, 0); for (int i_rank = 0; i_rank < world_size; ++i_rank) { recv_sizes[i_rank] = 3 * points_per_partition[i_rank]; } std::vector<int> recv_offsets(world_size, 0); for (int i_rank = 1; i_rank < world_size; ++i_rank) { recv_offsets[i_rank] = recv_offsets[i_rank - 1] + recv_sizes[i_rank - 1]; } // Invoque AllGatherv rDataCommunicator.AllGatherv(send_points_coordinates, rAllPointsCoordinates, recv_sizes, recv_offsets); } } /** * @brief Synchronizes the sizes of data among multiple processes using MPI. * @param NumberOfPoints The number of local points in the data * @param AllPointsAreTheSame Flag indicating if all points are the same * @param rDataCommunicator The data communicator for MPI communication * @return A vector containing the sizes of data for each process */ static std::vector<int> SynchronizeRecvSizes( const int NumberOfPoints, const bool AllPointsAreTheSame, const DataCommunicator& rDataCommunicator ) { // MPI information const int world_size = rDataCommunicator.Size(); // Define recv_sizes std::vector<int> recv_sizes(world_size, 0); if (!AllPointsAreTheSame) { // If not all points are the same // Getting global number of points std::vector<int> points_per_partition(world_size); std::vector<int> send_points_per_partition(1, NumberOfPoints); rDataCommunicator.AllGather(send_points_per_partition, points_per_partition); // Generate vectors with sizes for AllGatherv for (int i_rank = 0; i_rank < world_size; ++i_rank) { recv_sizes[i_rank] = points_per_partition[i_rank]; } } else if (world_size == 1) { // In case only one process is used recv_sizes[0] = NumberOfPoints; } return recv_sizes; } /** * @brief Synchronizes the radius of all points in a distributed system. * @param rRecvSizes a vector containing the number of points to be received from each rank * @param rRadius a vector containing the radius of each point * @param rDataCommunicator the communication object used for data exchange * @return A vector containing the synchronized radius of all points */ static std::vector<double> SynchronizeRadius( const std::vector<int>& rRecvSizes, const std::vector<double>& rRadius, const DataCommunicator& rDataCommunicator ) { // First we calculate the total number of points to communicate const int total_number_of_points = std::accumulate(rRecvSizes.begin(), rRecvSizes.end(), 0); // Synchonize radius if (total_number_of_points == 0) { // If all points are the same return rRadius; } else { // If not // The resulting radius std::vector<double> all_points_radius(total_number_of_points); // MPI information const int world_size = rDataCommunicator.Size(); // Generate vectors with sizes for AllGatherv std::vector<int> recv_offsets(world_size, 0); for (int i_rank = 1; i_rank < world_size; ++i_rank) { recv_offsets[i_rank] = recv_offsets[i_rank - 1] + rRecvSizes[i_rank - 1]; } // Invoque AllGatherv rDataCommunicator.AllGatherv(rRadius, all_points_radius, rRecvSizes, recv_offsets); return all_points_radius; } } /** * @brief This method checks if all nodes are the same across all partitions * @param itPointBegin Iterator to the beginning of the points range * @param itPointEnd Iterator to the end of the points range * @param rNumberOfPoints Number of points in the range * @param rTotalNumberOfPoints Total number of points in all partitions * @return true if all points are the same in all partitions * @tparam TPointIteratorType The type of the point iterator */ template<typename TPointIteratorType> static bool CheckAllPointsAreTheSameAndCalculateNumberOfPoints( TPointIteratorType itPointBegin, TPointIteratorType itPointEnd, int& rNumberOfPoints, int& rTotalNumberOfPoints, const DataCommunicator& rDataCommunicator ) { // Get the World Size in MPI const int world_size = rDataCommunicator.Size(); // Getting local number of points rNumberOfPoints = std::distance(itPointBegin, itPointEnd); // First we check if all the partitions have the same number of points rTotalNumberOfPoints = rDataCommunicator.SumAll(rNumberOfPoints); if (rNumberOfPoints * world_size != rTotalNumberOfPoints) { return false; } // Now we check if all the points are the same (we are going to do a gross assumtion that the sum of coordinates in al partitions does not compensate between them) double x_sum, y_sum, z_sum; array_1d<double, 3> coordinates; bool all_points_are_the_same = true; for (auto it_point = itPointBegin ; it_point != itPointEnd ; it_point++) { noalias(coordinates) = it_point->Coordinates(); x_sum = rDataCommunicator.SumAll(coordinates[0]); if (std::abs(coordinates[0] - (x_sum/world_size)) > ZeroTolerance) all_points_are_the_same = false; all_points_are_the_same = rDataCommunicator.AndReduceAll(all_points_are_the_same); if (!all_points_are_the_same) break; y_sum = rDataCommunicator.SumAll(coordinates[1]); if (std::abs(coordinates[1] - (y_sum/world_size)) > ZeroTolerance) all_points_are_the_same = false; all_points_are_the_same = rDataCommunicator.AndReduceAll(all_points_are_the_same); if (!all_points_are_the_same) break; z_sum = rDataCommunicator.SumAll(coordinates[2]); if (std::abs(coordinates[2] - (z_sum/world_size)) > ZeroTolerance) all_points_are_the_same = false; all_points_are_the_same = rDataCommunicator.AndReduceAll(all_points_are_the_same); if (!all_points_are_the_same) break; } return all_points_are_the_same; } ///@} }; } // namespace Kratos
true
48e8849f6ef7a17117ac5bbae27c60376b7efe98
C++
adjasont/CS303_Project2
/Project2/Project2/Floor.h
UTF-8
1,000
3.71875
4
[]
no_license
#pragma once #include <iostream> #include "Person.h" #include <queue> using namespace std; class Floor { private: int floor_number; queue<Person> peeps; public: Floor() { ; } void setFloor(int floorNum) { floor_number = floorNum; } void push(Person peep) { peeps.push(peep); } int getFloorNum() const { return floor_number; } int size() const { return peeps.size(); } bool is_empty() const { return peeps.empty(); } Person front() { return peeps.front(); } void pop() { peeps.pop(); } void createFloor(int floorNum); }; void Floor::createFloor(int floorNum) { int numPeeps = (rand() % 10); //Creates a random number of people on each floor. setFloor(floorNum); for (int j = 0; j < numPeeps; j++) { Person person; person.current_floor = floorNum; int desiredFloor = ((rand() % 9) + 1); while (desiredFloor == floorNum) //While loop so desired floor isnt the same as current floor desiredFloor = ((rand() % 9) + 1); person.desired_floor = desiredFloor; push(person); } }
true
a60c3364f8ed5eda12e348c1b0fcf8156bb64435
C++
truongpt/warm_up
/practice/cpp/misc/smallest_integer_divisible_k.cpp
UTF-8
844
3.890625
4
[]
no_license
/* - Problem: https://leetcode.com/problems/smallest-integer-divisible-by-k/ - Solution: - K = 3 - 111 - 111 = 11 * 10 + 1 We only need to store remainders modulo K. */ #include <iostream> #include <unordered_set> using namespace std; int smallestIntDivByK(int K) { if (!(K % 2) || !(K % 5)) { return -1; } int cnt = 1; int num = 1; int remain = num % K; if (0 == remain) return num; unordered_set<int> s; while (s.find(remain) == s.end()) { s.insert(remain); cnt++; num = remain*10 + 1; remain = num % K; if (remain == 0) return cnt; } return -1; } int main(void) { cout << smallestIntDivByK(1) << endl; cout << smallestIntDivByK(3) << endl; cout << smallestIntDivByK(7) << endl; }
true
39d4e0595134443ef2f6d30e2e178fd53eb7e782
C++
lamarrr/STX
/include/stx/scheduler/timeline.h
UTF-8
9,903
2.6875
3
[ "MIT" ]
permissive
#pragma once #include <algorithm> #include <chrono> #include <iostream> #include <thread> #include <utility> #include "stx/async.h" #include "stx/config.h" #include "stx/scheduler/thread_slot.h" #include "stx/task/id.h" #include "stx/task/priority.h" #include "stx/vec.h" STX_BEGIN_NAMESPACE using TimePoint = std::chrono::steady_clock::time_point; using namespace std::chrono_literals; using std::chrono::nanoseconds; /// Scheduler Documentation /// - Tasks are added to the timeline once they become ready for execution /// - We first split tasks into timelines based on when they last ran /// - We then select the most starved tasks in a sliding window containing at /// least a certain amount of tasks /// - We then sort the sliding window using their priorities /// - We repeat these steps /// - if any of the selected tasks is in the thread slot then we need not /// suspend or cancel them /// - the task itself manages its own suspension, preemption, and cancelation, /// the timeline doesn't handle that, the task should use a request proxy to /// track requests. /// /// tasks in the timeline are ready-to-execute, preempted, or suspended tasks struct ScheduleTimeline { static constexpr nanoseconds STARVATION_PERIOD = 16ms * 4; struct Task { // task to execute RcFn<void()> fn = fn::rc::make_static([]() {}); // used for book-keeping and notification of state PromiseAny promise; // assigned id of the task TaskId id{}; // priority to use in evaluating CPU-time worthiness TaskPriority priority{NORMAL_PRIORITY}; // the timepoint the task became ready for execution. in the case of a // suspended task, it correlates with the timepoint the task became ready // for resumption TimePoint last_preempt_timepoint{}; // last known status of the task FutureStatus last_status_poll{FutureStatus::Preempted}; }; explicit ScheduleTimeline(Allocator allocator) : starvation_timeline{allocator}, thread_slots_capture{allocator} {} Result<Void, AllocError> add_task(RcFn<void()> fn, PromiseAny promise, TaskId id, TaskPriority priority, TimePoint present_timepoint) { // task is ready to execute but preempteed upon adding promise.notify_preempted(); TRY_OK(ok, starvation_timeline.push(Task{std::move(fn), std::move(promise), id, priority, present_timepoint, FutureStatus::Preempted})); (void) ok; return Ok(Void{}); } void poll_tasks(TimePoint present_timepoint) { // update all our record of the tasks' statuses // // NOTE: the task could still be running whilst cancelation was requested. // it just means we get to remove it from taking part in future scheduling. // // if the task is already running, it either has to attend to the // cancel request, attend to the suspend request, or complete. // if it makes modifications to the terminal state, after we have made // changes to it, its changes are ignored. and if it has reached a terminal // state before we attend to the request, our changes are ignored. // // for (Task &task : starvation_timeline.span()) { // the status could have been modified in another thread, so we need // to fetch the status FutureStatus new_status = task.promise.fetch_status(); // if preempt timepoint not already updated, update it if ((task.last_status_poll != FutureStatus::Preempted && new_status == FutureStatus::Preempted)) { task.last_preempt_timepoint = present_timepoint; } task.last_status_poll = new_status; } } void execute_resume_requests() { for (Task &task : starvation_timeline) { if (task.last_status_poll == FutureStatus::Suspended && task.promise.fetch_suspend_request() == SuspendState::Executing) { // make it ready for resumption/execution task.promise.notify_preempted(); } } } void remove_done_tasks() { Span done_tasks = starvation_timeline.span() .partition([](Task const &task) { return task.last_status_poll != FutureStatus::Completed && task.last_status_poll != FutureStatus::Canceled; }) .second; starvation_timeline.erase(done_tasks); } // returns number of selected tasks size_t select_tasks_for_slots(size_t num_slots) { Span starving = starvation_timeline.span() // ASSUMPTION(unproven): The tasks are mostly sorted so we are very // unlikely to pay much cost in sorting??? // // suspended tasks are not considered for execution // .partition([](Task const &task) { return task.last_status_poll == FutureStatus::Preempted || task.last_status_poll == FutureStatus::Executing; }) .first // sort hungry tasks by preemption/starvation duration (most starved // first). Hence the starved tasks would ideally be more likely // chosen for execution .sort([](Task const &a, Task const &b) { return a.last_preempt_timepoint < b.last_preempt_timepoint; }); auto *selection = starving.begin(); TimePoint const most_starved_task_timepoint = starving[0].last_preempt_timepoint; nanoseconds selection_period_span = STARVATION_PERIOD; while (selection < starving.end()) { if ((selection->last_preempt_timepoint - most_starved_task_timepoint) <= selection_period_span) { // add to timeline selection selection++; continue; } else if ((selection->last_preempt_timepoint - most_starved_task_timepoint) > selection_period_span && (static_cast<size_t>(selection - starving.begin()) < num_slots)) { // if there's not enough tasks within the current starvation period span // to fill up all the slots then extend the starvation period span // (multiple enough to cover this selection's timepoint) nanoseconds diff = selection->last_preempt_timepoint - most_starved_task_timepoint; // (STARVATION_PERIOD-1ns) added since division by STARVATION_PERIOD // ONLY will result in the remainder of the division operation being // trimmed off and hence not cover the required span int64_t multiplier = (diff + (STARVATION_PERIOD - nanoseconds{1})) / STARVATION_PERIOD; selection_period_span += STARVATION_PERIOD * multiplier; selection++; continue; } else { break; } } // sort selection span by priority std::sort(starving.begin(), selection, [](Task const &a, Task const &b) { return a.priority > b.priority; }); size_t num_selected = selection - starving.begin(); // the number of selected starving tasks might be more than the number of // available ones, so we select the top tasks (by priority) num_selected = std::min(num_slots, num_selected); return num_selected; } // slots uses Rc because we need a stable address void tick(Span<Rc<ThreadSlot *> const> slots, TimePoint present_timepoint) { // cancelation and suspension isn't handled in here, it doesn't really make // sense to handle here. if the task is fine-grained enough, it'll be // canceled as soon as its first phase finishes execution. this has the // advantage that we don't waste scheduling efforts. size_t const num_slots = slots.size(); thread_slots_capture.resize(num_slots, ThreadSlot::Query{}).unwrap(); // fetch the status of each thread slot slots.map([](Rc<ThreadSlot *> const &rc_slot) { return rc_slot.handle->slot.query(); }, thread_slots_capture.span()); poll_tasks(present_timepoint); execute_resume_requests(); remove_done_tasks(); if (starvation_timeline.is_empty()) { return; } size_t const num_selected = select_tasks_for_slots(num_slots); // request preemption of non-selected tasks since they might be running. // // we only do this if the task is not already force suspended since it could // be potentially expensive if the promises are very far apart in memory. // // we don't expect just-suspended tasks to suspend immediately, even if // they do we'll process them in the next tick. // for (Task const &task : starvation_timeline.span().slice(num_selected)) { task.promise.request_preempt(); } // push the tasks onto the task slots if the task is not already on any of // the slots. // // the selected tasks might not get slots assigned to them. i.e. if tasks // are still using some of the slots. tasks that don't get assigned to slots // here will get assigned in the next tick // // add tasks to slot if not already on the slots size_t next_slot = 0; for (Task const &task : starvation_timeline.span().slice(0, num_selected)) { bool has_slot = !thread_slots_capture.span().which([&task](ThreadSlot::Query const &query) { return query.executing_task.contains(task.id) || query.pending_task.contains(task.id); }).is_empty(); if (has_slot) { continue; } while (next_slot < num_slots && !has_slot) { if (thread_slots_capture[next_slot].can_push) { // possibly a preempted task. // tasks are expected to check their request states. // // we have to unpreempt the task // task.promise.clear_preempt_request(); slots[next_slot].handle->slot.push_task(ThreadSlot::Task{task.fn.share(), task.id}); has_slot = true; } next_slot++; } } } Vec<Task> starvation_timeline; Vec<ThreadSlot::Query> thread_slots_capture; }; STX_END_NAMESPACE
true
eae8edf75d6890de89a3a6ec2523b932dd176049
C++
Shree987/WinterOfCP
/Chapter 3 - March 2021/Day 23/3Sum With Multiplicity.cpp
UTF-8
1,201
3
3
[]
no_license
/* Author : Shreeraksha R Aithal Problem name : 3Sum With Multiplicity Problem link : https://leetcode.com/problems/3sum-with-multiplicity/ Difficulty : Medium Tags : Two Pointers */ #define mod 1000000007 class Solution { public: int threeSumMulti(vector<int>& arr, int target) { long long answer = 0; vector<pair<long, long>> vp; map<long, long> mp; for(auto k : arr){ mp[k]++; } for(auto p : mp){ vp.push_back(p); } long long i, j, k, n = vp.size(); if(target%3 == 0){ k = mp[target/3]; answer = (answer%mod + ((k*(k-1)*(k-2))/6)%mod)%mod; } for(i=0; i<n; i++){ k = target - 2*vp[i].first; if(k != vp[i].first){ k = mp[target - 2*vp[i].first]; answer = (answer%mod + ((k*(vp[i].second-1)*vp[i].second)/2)%mod)%mod; } for(j=i+1;j<n;j++){ k = target - vp[i].first - vp[j].first; if(k > vp[j].first){ answer = (answer%mod + (vp[i].second*vp[j].second*mp[k])%mod)%mod; } } } return answer; } };
true
683f2b4e3230b50634f054dd8506506eef8f64a7
C++
casperwang/OJproblems
/UVa judge/#10200_Prime Time.cpp
UTF-8
943
2.65625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <vector> #define N 10000 using namespace std; int a, b; bool not_prime[N+5]; bool make_prime[N+5]; vector <int> primes; int main() { for (int i = 2; i <= 100; i++) { if (!not_prime[i]) { for (int j = i*i; j <= N; j+=i) { not_prime[j] = 1; } } } for (int i = 2; i <= N; i++) { if (!not_prime[i]) primes.push_back(i); } for (int i = 0; i <= N; i++) { int tmp = i*i+i+41; bool tf = 1; for (int j = 0; j < primes.size(); j++) { if (tmp % primes[j] == 0) tf = 0; } if ((i*i+i+41 <= N && !not_prime[i*i+i+41]) || (tf)) { make_prime[i] = 1; } } while (cin >> a >> b) { int n = 0; for (int i = a; i <= b; i++) { if (make_prime[i]) n++; } double ans = (double)((double)n * 10000 / (double)(b-a+1)); ans = round(ans); ans /= 100; printf("%.2f\n", ans); } return 0; }
true
9a5c08b4432e63425db95dcf9c2450d34bf2fa69
C++
pokachopotun/everythingWrongWithPinocchio
/cpp_examples/shared_ptr_aliasing.cpp
UTF-8
421
3.234375
3
[]
no_license
#include <vector> #include <iostream> #include <memory> using namespace std; struct My { My(size_t size) : A(size) { for (size_t i = 0; i < size; ++i) { A[i] = static_cast<int>(i); } } vector<int> A; }; int main() { shared_ptr<int> a; { auto ptr = make_shared<My>(10); a = shared_ptr<int>(ptr, &ptr->A[5]); } cout << *a << endl; return 0; }
true
7bc74362205911978c857796f5c18bb5b20a5454
C++
sinianyutian/offer
/Offer/面试题35:第一个只出现一次的字符.cpp
GB18030
1,715
4.28125
4
[]
no_license
/* * * 35һֻһεַ * һַ(1<=ַ<=10000ȫĸ)ҵһֻһεַ,λ * */ #include <string> using namespace std; int FirstNotRepeatingChar(string str) { //ֵж if (!str.size()) { return 0; } //ַhash const int size = 256; unsigned int hash_table[256]; for (int i = 0; i < size; i++) { hash_table[i] = 0; } //ͳַַ for (auto ch : str) { hash_table[ch]++; } //ҳһַΪ1ַ for (int i = 0; i < str.size(); i++) { if (1 == hash_table[str[i]]) { return i; } } return 0; } //ַеһֻһεַ //ʵһҳַеһֻһεַ //磬ַֻǰַ"go"ʱһֻһεַ"g" //Ӹַжǰַgoogle"ʱһֻһεַ"l" class Solution { public: int idx; int occurrence[256]; Solution():idx(1) { for (int i = 0; i < 256; ++i) { occurrence[i] = 0; } } //һַhashַӦλ void Insert(char ch) { //һγhashֵΪ if (occurrence[ch] == 0) { occurrence[ch] = idx++; //ٴγhashֵΪ-1 }else if(occurrence[ch] > 0){ occurrence[ch] = -1; } } //ַеһַ char FirstAppearingOnce() { char ch; int min = INT_MAX; //ͳ±С for (int i = 0; i < 256; ++i) { if (occurrence[i]>0 && occurrence[i] < min) { ch = (char)i; min = occurrence[i]; } } return ch; } };
true
3cd323c82e650de06ebebf65f41197d0b3604cf1
C++
MensInvictaManet/superbingo_cocos
/Classes/LinkedList.cpp
UTF-8
1,520
3.484375
3
[ "MIT" ]
permissive
////#include "LinkedList.h" // //template<class T> //LinkedList<T>::LinkedList(void) //{ // pHead = NULL; // pTail = NULL; // nElements = 0; //} // //template<class T> //LinkedList<T>::~LinkedList(void) //{ // for(int i = 0; i < nElements; i++) // { // pop_back(); // } // // pHead = NULL; // pTail = NULL; //} // //template<class T> //void LinkedList<T>::push_back(T obj) //{ // if(pHead == NULL) // { // pHead = new Node<T>(obj); // pHead->pLastNode = pHead; // pTail = pHead; // nElements++; // } // else // { // pTail->pNextNode = new Node<T>(obj); // pTail->pNextNode->pLastNode = pTail; // pTail = pTail->pNextNode; // nElements++; // } //} // //template<class T> //void LinkedList<T>::pop_back() //{ // if((pTail != NULL) && (pTail != pHead)) // { // pTail = pTail->pLastNode; // delete pTail->pNextNode; // pTail->pNextNode = NULL; // nElements--; // } // else if((pTail != NULL) && (pTail == pHead)) // { // delete pHead; // pTail = NULL; // pHead = NULL; // nElements = 0; // } //} // //template<class T> //void LinkedList<T>::clear() //{ // while(pHead != NULL) // { // pop_back(); // } // // nElements = 0; //} // //template<class T> //int LinkedList<T>::size() //{ // return nElements; //} // //template<class T> //T LinkedList<T>::operator[](const unsigned int index) //{ // int i = 0; // Node<T>* pSeek = pHead; // // if(index < nElements) // { // while(i != index) // { // pSeek = pSeek->pNextNode; // i++; // } // // return pSeek; // } // else // { // return NULL; // } //}
true
fa7825707fda399fa740d3b50232460bccce099a
C++
Xnco/Data-Structures-and-Algorithms
/TitleProject_Cpp/0067_二进制求和.cpp
UTF-8
2,021
3.578125
4
[]
no_license
 #pragma region 67_二进制求和 /* 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-binary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ class Solution { public: // 一位一位算 //Runtime: 4 ms, faster than 80.07% of C++ online submissions for Add Binary. //Memory Usage : 9.3 MB, less than 49.09 % of C++ online submissions for Add Binary. string addBinary(string a, string b) { string res = ""; int indexA = a.length() - 1; int indexB = b.length() - 1; int isAdd = 0; while (indexA >= 0 && indexB >= 0) { int temp = a[indexA] - 48 + b[indexB] - 48 + isAdd; isAdd = temp > 1 ? 1 : 0; res = (temp % 2 == 0 ? "0" : "1") + res; --indexA; --indexB; } string target = (indexA < 0) ? b : a; int targetIdx = (indexA < 0) ? indexB : indexA; while (targetIdx >= 0) { int temp = target[targetIdx] - 48 + isAdd; isAdd = temp > 1 ? 1 : 0; res = (temp % 2 == 0 ? "0" : "1") + res; --targetIdx; } if (isAdd == 1) { res = "1" + res; } return res; } // 可以合并 // push_back好像更慢了?? //Runtime: 8 ms, faster than 26.96 % of C++ online submissions for Add Binary. //Memory Usage : 8.5 MB, less than 94.55 % of C++ online submissions for Add Binary. string addBinary(string a, string b) { string res = ""; int indexA = a.length() - 1; int indexB = b.length() - 1; int isAdd = 0; while (indexA >= 0 || indexB >= 0 || isAdd == 1) { int temp = (indexA < 0 ? 0 : a[indexA] - 48) + (indexB < 0 ? 0 : b[indexB] - 48) + isAdd; isAdd = temp > 1 ? 1 : 0; res.push_back(temp % 2 + '0'); --indexA; --indexB; } reverse(res.begin(), res.end()); return res; } }; #pragma endregion
true
53591eb63ded6510d6480a66e16ea230df126d5c
C++
justinm1093/paC-man
/Source/GameCode/GhostRed.cpp
UTF-8
4,337
2.515625
3
[]
no_license
#define GHOST_RED_CPP #include <stdio.h> #include <windows.h> // Header File For Windows #include <gl\gl.h> // Header File For The OpenGL32 Library #include <gl\glu.h> // Header File For The GLu32 Library #include <assert.h> #include "..\\Framework\\baseTypes.h" #include <map> #include "Utilities.h" #include "Tile.h" #include "Character.h" #include "Ghost.h" #include "GhostRed.h" #include "CharacterManager.h" #include "StatsManager.h" GhostRed::GhostRed(const Tile* spawnTile, const GameUtil::CharacterID id) : Ghost(spawnTile, id) { // BLINKY // SHADOW } //----------------------------------------------------------------------------------------- void GhostRed::reset() { // reset for the new level, then reset cruise elroy mode Ghost::reset(); mCruiseElroyMode = GameUtil::CruiseElroyMode::NONE; // save cruise elroy speed values from the stats manager so we don't spam request them const StatsManager* smInstance = StatsManager::ConstInstace(); mCruiseElroySpeed_1 = smInstance->getCruiseElroySpeed_1(); mCruiseElroySpeed_2 = smInstance->getCruiseElroySpeed_2(); } //----------------------------------------------------------------------------------------- void GhostRed::resetFromDeath() { // reset from pacman death, then reset cruise elroy mode Ghost::resetFromDeath(); mCruiseElroyMode = GameUtil::CruiseElroyMode::NONE; } //----------------------------------------------------------------------------------------- void GhostRed::targetPacman() { // targets pacman directly mTargetTile = CharacterManager::ConstInstance()->getCharacterCurrentTile(GameUtil::CharacterID::PACMAN); } //----------------------------------------------------------------------------------------- void GhostRed::updateSpeed() { // speed is affected by ghost targeting mode switch(mTargetState) { // if scared... case GhostTargetingState::SCARED: mSpeed = mBaseSpeed * mGhostSpeedScared; break; // chase or scatter has to take into account the tile type (except in cruise elroy mode) case GhostTargetingState::CHASE: case GhostTargetingState::SCATTER: switch(mCruiseElroyMode) { case GameUtil::CruiseElroyMode::NONE: if(mCurrTile->isTunnel()) { mSpeed = mBaseSpeed * mGhostSpeedTunnel; } else { mSpeed = mBaseSpeed * mGhostSpeed; } break; case GameUtil::CruiseElroyMode::CRUISE_1: mSpeed = mBaseSpeed * mCruiseElroySpeed_1; break; case GameUtil::CruiseElroyMode::CRUISE_2: mSpeed = mBaseSpeed * mCruiseElroySpeed_2; break; } break; // dead ghosts take into account if they're in the ghost hosue case GhostTargetingState::DEAD: if(mIsInGhostHome) { mSpeed = mBaseSpeed * mGhostSpeed; } else { mSpeed = mBaseSpeed * 1.5f; } break; default: break; } } //----------------------------------------------------------------------------------------- void GhostRed::setScatter() { // can only scatter when not in a cruise elroy mode if(mCruiseElroyMode == GameUtil::CruiseElroyMode::NONE) { Ghost::setScatter(); } } //----------------------------------------------------------------------------------------- void GhostRed::activateCruiseElroy() { GameUtil::CruiseElroyMode nextPhase = (GameUtil::CruiseElroyMode)(mCruiseElroyMode + 1); if(nextPhase != GameUtil::CruiseElroyMode::CRUISE_INVAL) { // can only experience a cruise elroy state change when all ghosts are spawned if(CharacterManager::ConstInstance()->areAllGhostsSpawned()) { mCruiseElroyMode = nextPhase; } } } //----------------------------------------------------------------------------------------- const GameUtil::CruiseElroyMode GhostRed::getCruiseElroyPhase() const { return mCruiseElroyMode; }
true
3ac0a190f6950102b51a474cd88f36f85c9cb16c
C++
PoojaRani24/Arena
/Backtacking/N-Queen, print all solutions.cpp
UTF-8
1,070
3.265625
3
[]
no_license
//N-Queen Problem, printing all the solutions #include<bits/stdc++.h> using namespace std; void printsol(bool b[][100],int n){ static int k=1; cout<<k<<":"; cout<<endl; k++; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<b[i][j]<<" "; } cout<<endl; } cout<<endl; } bool is_safe(bool b[][100],int n,int x,int y){ //check for row; for(int i=0;i<n;i++){ if(b[x][i]==true) return false; } //check for column for(int i=0;i<n;i++){ if(b[i][y]==true) return false; } //check for diagonal for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(b[i][j]==1 && ((i+j == x+y) || (i-j == x-y))) return false; } } return true; } bool queen(bool b[][100],int n,int col){ if(col==n){ printsol(b,n); return true; } bool res=false; for(int i=0;i<n;i++){ if(is_safe(b,n,i,col)){ b[i][col]=1; res=(queen(b,n,col+1)||res); b[i][col]=0; } } return res; } int main(){ int n; bool res; cin>>n; bool b[100][100]; memset(b,0,sizeof(b)); res= queen(b,n,0); if(res==false){ cout<<"NO"<<endl; } }
true
4b8858dd4a73c3dad3f747c8a11536827b5294b6
C++
joyce103/ITSA
/標準體重.cpp
UTF-8
309
2.765625
3
[]
no_license
#include<iostream> #include<cstdlib> #include<iomanip> using namespace std ; int main () { double tall ; double w ; int s ; while(cin >> tall >> s){ if(s==1){ w=(tall-80)*0.7 ; } else if (s==2) { w=(tall-70)*0.6 ; } cout << fixed << setprecision(1) << w << endl ; } return 0 ; }
true
3727c9f280df5158a59d18bef7f9f0e5775625c3
C++
lantian-fz/test_cpp
/test_156/test_156/main.cpp
GB18030
1,147
3.484375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 //-67. //ַǵĺͣöƱʾ //Ϊ ǿ ַֻ 1 0 //: a = "11", b = "1" //: "100" // //: a = "1010", b = "1011" //: "10101" //ʾ //ÿַַ '0' '1' ɡ //1 <= a.length, b.length <= 10^4 //ַ "0" Ͷǰ㡣 #include <iostream> #include <string> #include <algorithm> using namespace std; string addBinary(string a, string b) { reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); if (a.size() > b.size()) b.resize(a.size(), '0'); else a.resize(b.size(), '0'); string s; int count = 0;//λ for (size_t i = 0; i < a.size(); i++) { count += a[i] + b[i] - '0' - '0'; if (count >= 2) { s.push_back(count - 2 + '0'); count = 1; } else { s.push_back(count + '0'); count = 0; } } if (count > 0) s.push_back('1'); reverse(s.begin(), s.end()); return s; } int main() { string a, b; while (cin >> a >> b) cout << addBinary(a, b) << endl; return 0; }
true
b2a7cf39039f05ca44ce2c4f38cd374bf56abe14
C++
wiranegara777/dasprog
/contest4.cpp
UTF-8
347
2.78125
3
[]
no_license
#include <iostream> using namespace std; // int fpb(a,b) { // if (b==0) return a; // else return fpb(b, a%b); // } int main(){ int a,b,c; int count=0; cin>>a>>b>>c; while(a!=-99){ if( a > 0 && b > 0){ count++; } cin>>a; if(a == -99){break;} cin>>b>>c; } cout<<count++<<'\n'; }
true
cd8602cc542a430fd058b1008a90abac15e85357
C++
Lazik10/CPP-In-21-Days
/src/String.h
UTF-8
766
3.4375
3
[]
no_license
#pragma once #include <iostream> #include <string.h> class String { public: // Constructors String(); String(const char* const string); // Copy constr String(const String& string); // Destructor ~String(); // Overloaded operators char& operator[](unsigned short indentation); char operator[](unsigned short indentation) const; String operator+(const String& string); void operator+=(const String & string); String& operator=(const String & string); // Public methods unsigned short GetLength() const { return m_length; }; const char* GetString() const { return m_string; }; private: // Private constructor String(unsigned short lenght); char* m_string; unsigned short m_length; };
true
50a64dc6bf2da7c1a0f93b17c141cac77c61b152
C++
NoahBGriffin/LoanIt
/LoanIt/SaveLoad.cpp
UTF-8
3,731
3.25
3
[]
no_license
#include "SaveLoad.h" /** * Saves the LoanIt information to an external text file named "LoanItSaveData.txt" * @param itemList the list of all the items in LoanIt * @param loanList the list of all the loans in LoanIt */ void Save(vector<Item> itemList, vector<Loan> loanList) { string loaned; Item loanItem = Item("", ""); ofstream loanItFile("LoanItSaveData.txt"); if (loanItFile.is_open()) { loanItFile << "ITEMS:\n"; for (auto i : itemList) { loanItFile << i.GetName() << ": " << i.GetDescription() << "\n"; } loanItFile << "\nLOANS:"; for (auto i : loanList) { loanItem = i.GetLoanItem(); loanItFile << "\n" << i.GetLoanID() << ") " << loanItem.ToString() << " - " << i.GetLoanName() << ", " << i.GetDate(); } loanItFile.close(); cout << "LoanIt data successfully saved to \"LoanItSaveData.txt\"\n"; } else cout << "Unable to save\n"; Return(2); } /** * Loads items and loans to LoanIt from an external text document named "LoanItSaveData.txt" * @param itemList the item list which will have item data from the document loaded on to it * @param loanList the loan list which will have loan data from the document loaded on to it * @param saveFile the name of the file being loaded in */ void Load(vector <Item>& itemList, vector<Loan>& loanList, string saveFile) { ifstream readfile; bool item = true; //item variables string tmpItemName; string tmpItemDesc; //loan variables int tmpLoanID; string tmpLoanPName; string tmpLoanDate; Item tmpLoanItem = Item("", ""); readfile.open(saveFile); if (!readfile) { cout << "No previous save data found.\n"; } else { getline(readfile, tmpItemName, '\n'); if (tmpItemName == "ITEMS:") { while (!readfile.eof()) { while (item) //get all the items { getline(readfile, tmpItemName, ':'); //read item name if (tmpItemName == "\nLOANS") //check for break to loans { item = false; break; } getline(readfile, tmpItemDesc, '\n'); trim(tmpItemName); //trim whitespace from name trim(tmpItemDesc); //trim whitespace from desc itemList.push_back(Item(tmpItemName, tmpItemDesc)); //put in list } //now find all the loans if (!item && !readfile.eof()) { readfile >> tmpLoanID; readfile.ignore(); //ignore the : char getline(readfile, tmpItemName, ':'); getline(readfile, tmpItemDesc, '-'); getline(readfile, tmpLoanPName, ','); readfile >> tmpLoanDate; trim(tmpItemName); //trim whitespace from item name trim(tmpItemDesc); //trim whitespace from item description trim(tmpLoanPName); //trim whitespace from person's name tmpLoanItem = Item(tmpItemName, tmpItemDesc); //FIX THIS tmpLoanItem.ChangeStatus(); loanList.push_back(Loan(tmpLoanItem, tmpLoanPName, tmpLoanDate)); //put loan in the list } } cout << "Load complete.\n"; } else cout << "Error: Unable to read in LoanIt data.\n"; readfile.close(); } }
true
b4cd4803e3c862574169d08d432c0ccbf7db9159
C++
marcelloak/ball-breaker
/Main/main.cpp
UTF-8
21,889
2.640625
3
[]
no_license
//Assignment 2 //COMP 369 //Ball Breaker Game //By Marcello Kuenzler //3140074 //December 19, 2019 #include <string> #include <vector> #include "sprite.h" #include "datafile.h" #include <allegro.h> //Define basic stats #define WHITE makecol(255, 255, 255) #define BLACK makecol(0, 0, 0) #define RED makecol(255, 0, 0) #define SCREENW 800 #define SCREENH 600 #define BRICK_W 32 #define BRICK_H 12 #define ROW_W 23 #define NUMLIVES 3 #define PSPEED 2 #define PUPSPEED 0.3 #define STARTBSPEED 0.8 #define PLUSBSPEED 0.1 #define BGVOLUME 100 #define SEVOLUME 255 #define R_TIMER 10000 //Declare basic stats, bitmaps and sounds int score; int level; int lives; int numballs; int numbricks; int rpowerup; int rpoweruptimer; double bspeed; volatile int musiccounter = 0; volatile int counter = 0; std::vector<sprite*> sprites; DATAFILE* data; sprite* paddle; BITMAP* startimage; BITMAP* buffer; BITMAP* bg; BITMAP* help; BITMAP* again; MIDI* bmusic; SAMPLE* sample; int panning = 128; int pitch = 1000; int musicplaying = 1; //Function to generate a ball //It takes a location (x,y) and a speed(x,y) as two ints and two doubles void ball_generator(int x, int y, double vx, double vy) { //Only generate a ball if there isn't already three in play if (numballs < 3) numballs++; else return; sprite *ball = new sprite(); ball->image = (BITMAP*)data[RollingBall].dat; ball->x = x; ball->y = y; ball->width = 16; ball->height = 16; ball->animcolumns = 5; ball->velx = vx; ball->vely = vy; ball->totalframes = 28; ball->type = "ball"; sprites.push_back(ball); } //Function to generate a powerup //It takes a location (x,y) as two ints void powerup_generator(int x, int y) { sprite *powerup = new sprite(); //Randomly assign the powerup one of three benefits int r = (rand() % 3) + 1; if (rpowerup == 1) r = 1; if (r == 1) { powerup->image = (BITMAP*)data[BluePowerUp].dat; powerup->type = "bpowerup"; } else if (r == 2) { powerup->image = (BITMAP*)data[RedPowerUp].dat; powerup->type = "rpowerup"; } else if (r == 3) { powerup->image = (BITMAP*)data[YellowPowerUp].dat; powerup->type = "ypowerup"; } powerup->x = x; powerup->y = y; powerup->width = 32; powerup->height = 32; powerup->vely = PUPSPEED; powerup->animcolumns = 2; powerup->totalframes = 4; sprites.push_back(powerup); } //Function to bounce a ball against an object //It takes two sprites, the ball and the object it is bouncing against void ball_bounce(sprite* s1, sprite* s2) { //If the other object is a brick if (s2->type == "brick") { //Determine which side or corner the ball is coming from and bounce accordingly if (s1->inside(s1->x, s1->y, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { if (s1->inside(s1->x + 1, s1->y, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->vely *= -1; s1->y += 1; s1->animdir *= -1; } else if (s1->inside(s1->x, s1->y + 1, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->velx *= -1; s1->x += 1; s1->animdir *= -1; } else { s1->vely *= -1; s1->y += 1; s1->velx *= -1; s1->x += 1; s1->animdir *= -1; } } else if (s1->inside(s1->x + s1->width, s1->y + s1->height, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { if (s1->inside(s1->x + s1->width - 1, s1->y + s1->height, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->vely *= -1; s1->y -= 1; s1->animdir *= -1; } else if (s1->inside(s1->x + s1->width, s1->y + s1->height - 1, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->velx *= -1; s1->x -= 1; s1->animdir *= -1; } else { s1->vely *= -1; s1->y -= 1; s1->velx *= -1; s1->x -= 1; s1->animdir *= -1; } } else if (s1->inside(s1->x, s1->y + s1->height, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { if (s1->inside(s1->x - 1, s1->y + s1->height, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->vely *= -1; s1->y -= 1; s1->animdir *= -1; } else if (s1->inside(s1->x, s1->y + s1->height - 1, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->velx *= -1; s1->x += 1; s1->animdir *= -1; } else { s1->vely *= -1; s1->y -= 1; s1->velx *= -1; s1->x += 1; s1->animdir *= -1; } } else if (s1->inside(s1->x + s1->width, s1->y, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { if (s1->inside(s1->x + s1->width - 1, s1->y, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->vely *= -1; s1->y += 1; s1->animdir *= -1; } else if (s1->inside(s1->x + s1->width, s1->y - 1, s2->x, s2->y, s2->x + s2->width, s2->y + s2->height)) { s1->velx *= -1; s1->x -= 1; s1->animdir *= -1; } else { s1->vely *= -1; s1->y += 1; s1->velx *= -1; s1->x -= 1; s1->animdir *= -1; } } } //If the other object is a paddle else if (s2->type == "paddle") { //It will always be hitting from the top, so bounce back up, accounting for if the paddle is moving s1->vely *= -1; s1->y -= 1; double spd = 0; spd = (rand() % int(bspeed * 10)) + 1; spd /= 10; if (spd < 0.2) spd = 0.2; if (s2->velx > 0) s1->velx = spd; else if (s2->velx < 0) s1->velx = spd * -1; s1->animdir *= -1; } } //Function to collide two objects and determine the outcome //It takes two objects void collide(sprite* s1, sprite* s2) { //If the first object is a powerup if (s1->type == "bpowerup" || s1->type == "rpowerup" || s1->type == "ypowerup") { //And the second is as well, nothing happens if (s2->type == "bpowerup" || s2->type == "rpowerup" || s2->type == "ypowerup") return; //Same if the second is a ball else if (s2->type == "ball") return; //And if its a brick else if (s2->type == "brick") return; //If its a paddle, then the powerup is collected else if (s2->type == "paddle") { //If it's a blue powerup, a life is gained if (s1->type == "bpowerup") { lives++; sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s1))); } //If it's a red powerup, the double paddle width is activated else if (s1->type == "rpowerup" && rpowerup == 0) { rpowerup = 1; rpoweruptimer = R_TIMER; paddle = new sprite(); paddle->image = (BITMAP*)data[DoublePaddle].dat; paddle->x = s2->x - 16; paddle->y = s2->y; paddle->width = 128; paddle->height = 8; paddle->type = "paddle"; sprites.push_back(paddle); sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s2))); sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s1))); } //If it's a yellow powerup, a ball is generated above the paddle else if (s1->type == "ypowerup") { ball_generator(sprites.at(std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s2)))->x + 16, sprites.at(std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s2)))->y - 300, 0, bspeed); sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s1))); } } } //If the first object is a ball if (s1->type == "ball") { //And the second is a powerup, nothing happens if (s2->type == "bpowerup" || s2->type == "rpowerup" || s2->type == "ypowerup") return; //Same if it's another ball else if (s2->type == "ball") return; //If it's a paddle, bounce the ball else if (s2->type == "paddle") ball_bounce(s1, s2); //And if it's a brick, bounce the ball and break the brick else if (s2->type == "brick") { sample = (SAMPLE*)data[Shatter].dat; play_sample(sample, SEVOLUME, panning, pitch, FALSE); s2->animdir = 1; ball_bounce(s1, s2); } } //If the first object is a paddle if (s1->type == "paddle") { //And the second object is a ball, bounce the ball if (s2->type == "ball") ball_bounce(s2, s1); //Or if it's a powerup, collect it else if (s2->type == "bpowerup" || s2->type == "rpowerup" || s2->type == "ypowerup") { if (s2->type == "bpowerup") { lives++; sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s2))); } else if (s2->type == "rpowerup") { rpowerup = 1; rpoweruptimer = R_TIMER; paddle = new sprite(); paddle->image = (BITMAP*)data[DoublePaddle].dat; paddle->x = s1->x - 16; paddle->y = s1->y; paddle->width = 128; paddle->height = 8; paddle->type = "paddle"; sprites.push_back(paddle); sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s2))); sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s1))); } else if (s2->type == "ypowerup") { ball_generator(sprites.at(std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s1)))->x + 16, sprites.at(std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s1)))->y - 300, 0, bspeed); sprites.erase(sprites.begin() + std::distance(sprites.begin(), std::find(sprites.begin(), sprites.end(), s2))); } } } //If the first object is a brick if (s1->type == "brick") { //Ignore powerups if (s2->type == "bpowerup" || s2->type == "rpowerup" || s2->type == "ypowerup") return; //And bounce balls and then break else if (s2->type == "ball") { sample = (SAMPLE*)data[Shatter].dat; play_sample(sample, SEVOLUME, panning, pitch, FALSE); s1->animdir = 1; ball_bounce(s2, s1); } } } //Function to check collisions within the list of objects //It takes no parameters void checkcollisions() { //Loop through the list of objects for (int n1 = 0; n1 < static_cast<int>(sprites.size()); n1++) { //Loop through the list of objects for each object for (int n2 = 0; n2 < static_cast<int>(sprites.size()); n2++) { //If the objects are not the same object, and they are in collision, run the collision between them //If either are destroyed, lower the current count within that loop to account for them not being in it anymore if (n1 != n2 && sprites.at(n1)->collided(sprites.at(n2), -1)) { int m1 = 0; int m2 = 0; if (sprites.at(n1)->type == "bpowerup" || sprites.at(n1)->type == "rpowerup" || sprites.at(n1)->type == "ypowerup") { if (sprites.at(n2)->type == "paddle") m1 = 1; } if (sprites.at(n1)->type == "paddle") { if (sprites.at(n2)->type == "bpowerup" || sprites.at(n2)->type == "rpowerup" || sprites.at(n2)->type == "ypowerup") m2 = 1; } collide(sprites.at(n1), sprites.at(n2)); if (m1 == 1) n1--; if (m2 == 1) n2--; } } } //Then check for collisions between objects and walls //If an object hits either wall or the ceiling, bounce it //If an object hits the floor, destroy it for (int n = 0; n < static_cast<int>(sprites.size()); n++) { if (sprites.at(n)->x < 0) { sprites.at(n)->x = 0; sprites.at(n)->velx *= -1; sprites.at(n)->animdir *= -1; } else if (sprites.at(n)->x > SCREENW - sprites.at(n)->width) { sprites.at(n)->x = SCREENW - sprites.at(n)->width; sprites.at(n)->velx *= -1; sprites.at(n)->animdir *= -1; } if (sprites.at(n)->y < 0) { sprites.at(n)->y = 0; sprites.at(n)->vely *= -1; sprites.at(n)->animdir *= -1; } else if (sprites.at(n)->y > SCREENH - sprites.at(n)->height) { if (sprites.at(n)->type == "ball") { sprites.erase(sprites.begin() + n); n--; numballs--; } else if (sprites.at(n)->type == "bpowerup") { sprites.erase(sprites.begin() + n); n--; } else if (sprites.at(n)->type == "rpowerup") { sprites.erase(sprites.begin() + n); n--; } else if (sprites.at(n)->type == "ypowerup") { sprites.erase(sprites.begin() + n); n--; } else { sprites.at(n)->y = SCREENH - sprites.at(n)->height; sprites.at(n)->vely *= -1; sprites.at(n)->animdir *= -1; } } } } //Function to build a row of bricks //It takes a row number void build_row(int row) { sprite* br; //For each brick that makes up the row, determined by the row width basic stat //Create a brick at the appropriate spot and give it a random color for (int i = 0; i < ROW_W; i++) { br = new sprite(); int r = (rand() % 3) + 1; if (r == 1) br->image = (BITMAP*)data[BlueBrick].dat; else if (r == 2) br->image = (BITMAP*)data[GreenBrick].dat; else if (r == 3) br->image = (BITMAP*)data[RedBrick].dat; else if (r == 4) br->image = (BITMAP*)data[YellowBrick].dat; br->x = i * (BRICK_W + 2) + 8; br->y = (row + 1) * BRICK_H * 3; br->width = BRICK_W; br->height = BRICK_H; br->animcolumns = 2; br->animdir = 0; br->totalframes = 13; br->type = "brick"; sprites.push_back(br); numbricks++; } } //Function to build level 1 //It takes no parameters void level_1() { //Create one row for (int i = 0; i < 1; i++) { build_row(i); } } //Function to build level 2 //It takes no parameters void level_2() { //Create two rows for (int i = 0; i < 2; i++) { build_row(i); } } //Function to build level 3 //It takes no parameters void level_3() { //Create three rows for (int i = 0; i < 3; i++) { build_row(i); } } //Function to build level 4 //It takes no parameters void level_4() { //Create four rows for (int i = 0; i < 4; i++) { build_row(i); } } //Function to build level 5 //It takes no parameters void level_5() { //Create a random number of rows, between one and eight //Row one will always be created, otherwise it is random if a row is created for (int i = 0; i < 8; i++) { if (i == 0) build_row(i); else if (rand() % 2) build_row(i); } } //Function to draw the screen //It takes no parameters void draw_screen() { //Erase the buffer by drawing the background blit(bg, buffer, 0, 0, 0, 0, SCREENW, SCREENH); //If the double width powerup is active, decrease the timer //If the time is done, turn the powerup off if (rpoweruptimer > 0) { rpoweruptimer--; if (rpoweruptimer == 0) { rpowerup = 0; paddle = new sprite(); for (int n = 0; n < static_cast<int>(sprites.size()); n++) { if (sprites.at(n)->type == "paddle") { paddle->image = (BITMAP*)data[Paddle].dat; paddle->x = sprites.at(n)->x + 16; paddle->y = sprites.at(n)->y; paddle->width = 64; paddle->height = 8; paddle->type = "paddle"; sprites.erase(sprites.begin() + n); } } sprites.push_back(paddle); } } //For each object, update its position and animation //If the object is a brick at the end of its break animation, destroy it //And increase score, lower number of bricks and randomly drop a powerup for (int n = 0; n < static_cast<int>(sprites.size()); n++) { sprites.at(n)->updatePosition(); sprites.at(n)->updateAnimation(); if (sprites.at(n)->type == "brick" && sprites.at(n)->curframe == sprites.at(n)->totalframes - 1) { int pup = 0; pup = (rand() % (9 * level)); if (pup == 0) powerup_generator(sprites.at(n)->x, sprites.at(n)->y + 16); sprites.erase(sprites.begin() + n); numbricks--; score++; n--; } } //Check for collisions at new positions checkcollisions(); //For each object, draw them to the buffer for (int n = 0; n < static_cast<int>(sprites.size()); n++) { sprites.at(n)->drawframe(buffer); } //Draw the level information to the bottom of the buffer textprintf_ex(buffer, font, 10, 590, BLACK, -1, "Level: %d", level); textprintf_ex(buffer, font, 110, 590, BLACK, -1, "Score: %d", score); textprintf_ex(buffer, font, 210, 590, BLACK, -1, "Lives: %d", lives); textprintf_ex(buffer, font, 310, 590, BLACK, -1, "Bricks Left: %d", numbricks); if (rpowerup == 1) textout_ex(buffer, font, "DOUBLE PADDLE ACTIVE", 600, 590, RED, -1); //Draw the buffer to the screen acquire_screen(); masked_blit(buffer, screen, 0, 0, 0, 0, SCREENW, SCREENH); release_screen(); } //Function to display the help screen //It takes no parameters void gethelp() { //Draw the static help screen acquire_screen(); masked_blit(help, screen, 0, 0, 0, 0, SCREENW, SCREENH); release_screen(); //Wait the player to proceed or quit while (key[KEY_SPACE]); while (!key[KEY_SPACE]) if (key[KEY_ESC]) allegro_exit(); } //Function to create a level //It takes no parameters void create_level() { //Clear any previous objects sprites.clear(); //Create the bricks based on the current level if (level == 1) level_1(); else if (level == 2) level_2(); else if (level == 3) level_3(); else if (level == 4) level_4(); else if (level < 4) level_5(); //While there are still lives or bricks, play the game while (!(lives < 1) && !(numbricks < 1)) { //Create the paddle and ball paddle = new sprite(); paddle->image = (BITMAP*)data[Paddle].dat; paddle->x = 368; paddle->y = 550; paddle->width = 64; paddle->height = 8; paddle->type = "paddle"; sprites.push_back(paddle); numballs = 0; ball_generator(400, 400, 0, bspeed); //While the player has not quit the game, check for keyboard controls while (!key[KEY_ESC]) { //Control the paddle using left and right if (key[KEY_LEFT] && !key[KEY_RIGHT]) paddle->velx = PSPEED * -1; else if (!key[KEY_LEFT] && key[KEY_RIGHT]) paddle->velx = PSPEED; else if (!key[KEY_LEFT] && !key[KEY_RIGHT]) paddle->velx = 0; else if (key[KEY_LEFT] && key[KEY_RIGHT]) paddle->velx = 0; //Pause or play the music using ctrl+M if (key[KEY_LCONTROL] || key[KEY_RCONTROL]) if (key[KEY_M]) { if (musicplaying == 0 && musiccounter > 1000) { midi_resume(); musicplaying = 1; musiccounter = 0; } else if (musicplaying == 1 && musiccounter > 1000) { midi_pause(); musicplaying = 0; musiccounter = 0; } } //Activate the help screen using ctrl+H if (key[KEY_LCONTROL] || key[KEY_RCONTROL]) if (key[KEY_H]) gethelp(); //Draw the screen draw_screen(); //If all balls or bricks are gone, loop is over if (numballs == 0) break; if (numbricks == 0) break; } //After exiting loop, determine game state //If there are still balls and bricks, player chose to quit if (numballs != 0 && numbricks != 0) allegro_exit(); //If there are no balls, player lost if (numballs == 0) { //Destroy old paddle and any falling powerups, reset powerup if active and lose a life for (int n = 0; n < static_cast<int>(sprites.size()); n++) { if (sprites.at(n)->type == "paddle") { sprites.erase(sprites.begin() + n); n--; } else if (sprites.at(n)->type == "bpowerup" || sprites.at(n)->type == "rpowerup" || sprites.at(n)->type == "ypowerup") { sprites.erase(sprites.begin() + n); n--; } } lives--; rpowerup = 0; rpoweruptimer = 0; } } //Draw the background to the screen blit(bg, buffer, 0, 0, 0, 0, SCREENW, SCREENH); acquire_screen(); masked_blit(buffer, screen, 0, 0, 0, 0, SCREENW, SCREENH); release_screen(); } //Function to reset the stats when a new game is started //It takes no parameters void reset_stats() { //Resets all basic stats to default settings score = 0; level = 1; lives = NUMLIVES; bspeed = STARTBSPEED; numballs = 0; numbricks = 0; rpowerup = 0; rpoweruptimer = 0; } //Function to start a game //It takes no parameters void start_game() { //Keep going until the player quits int play = 1; while (play == 1) { //Reset the stats at the start of each game reset_stats(); while (lives > 0) { create_level(); //If there are no bricks left the level is complete //Proceed to the next and increase difficulty if (numbricks == 0) { level++; bspeed = bspeed + PLUSBSPEED; } } //When all lives are lost, display game over screen and wait for player to play again or quit acquire_screen(); masked_blit(again, screen, 0, 0, 0, 0, SCREENW, SCREENH); release_screen(); while (!key[KEY_SPACE]) if (key[KEY_ESC]) allegro_exit(); } } //Function to update the counters //It takes no parameters void update_counter() { //Update all counters counter++; musiccounter++; } int main(void) { //Initialize all needed allegro functions allegro_init(); set_color_depth(16); set_gfx_mode(GFX_AUTODETECT_WINDOWED, SCREENW, SCREENH, 0, 0); install_keyboard(); install_mouse(); install_timer(); data = load_datafile("datafile.dat"); LOCK_VARIABLE(counter); LOCK_VARIABLE(musiccounter); LOCK_FUNCTION(update_counter); install_keyboard(); install_int(update_counter, 1); install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, ""); show_mouse(screen); srand(time(NULL)); //Setup the bitmaps and music buffer = create_bitmap(SCREENW, SCREENH); set_volume(SEVOLUME, BGVOLUME); bmusic = (MIDI*)data[Music].dat; play_midi(bmusic, 1); startimage = (BITMAP*)data[Startup].dat; bg = (BITMAP*)data[Background].dat; help = (BITMAP*)data[Help].dat; again = (BITMAP*)data[PlayAgain].dat; clear_bitmap(screen); //Draw the start screen with title to the screen blit(startimage, screen, 0, 0, 0, 0, SCREENW, SCREENH); //Wait for player to proceed or quit, then display help screen while (!key[KEY_SPACE]) if (key[KEY_ESC]) allegro_exit(); clear_bitmap(screen); gethelp(); start_game(); allegro_exit(); return 0; } END_OF_MAIN()
true
0c658a5c0b48899cba34fc4f54e067fc63d3f1aa
C++
QiangAI/AI_CPlus
/山东大学/Day05资料/qmake_proj/guis/frame.cpp
UTF-8
1,059
2.515625
3
[ "Apache-2.0" ]
permissive
#include "frame.h" #include <iostream> MainFrame::MainFrame(): ui(new Ui::Camera()), dev(new CameraDev()){ ui->setupUi(this); // 启动多线程 dev->start(); // 绑定后信号与槽 QObject::connect(dev, SIGNAL(sig_video(cv::Mat)), this, SLOT(show_video(cv::Mat))); } MainFrame::~MainFrame(){ delete ui; delete dev; } void MainFrame::closeEvent(QCloseEvent *e){ // std::cout << "关闭窗体,释放设备!" << std::endl; dev->close(); } void MainFrame::capture(){ std::cout << "抓图" << std::endl; } void MainFrame::recognize(){ std::cout << "识别" << std::endl; } void MainFrame::show_video(cv::Mat img){ // 负责显示img图像 // std::cout << "有信号" << std::endl; // 把opencv的矩阵转换为QImage QImage q_img(img.data, img.cols, img.rows, QImage::Format_RGB888); // 有的版本不支持Format_BGR888 // 把QImage转换像素图QPixelmap QPixmap p_img = QPixmap::fromImage(q_img); // 设置到标签框 ui->lbl_video->setPixmap(p_img); }
true
153275858e3eadaa71d982f1422a7d4cbd438358
C++
BobDeng1974/openGeeL
/openGeeL/renderer/texturing/textureparams.h
UTF-8
922
2.59375
3
[]
no_license
#ifndef TEXTUREPARAMETERS_H #define TEXTUREPARAMETERS_H #include "texturetype.h" namespace geeL { class TextureParameters { public: TextureParameters(); TextureParameters(FilterMode filterMode, WrapMode wrapMode = WrapMode::Repeat, AnisotropicFilter aFilter = AnisotropicFilter::None); TextureParameters(TextureParameters&& other); ~TextureParameters(); TextureParameters& operator=(TextureParameters&& other); void bind(unsigned int layer) const; static void unbind(unsigned int layer); private: unsigned int id; FilterMode filterMode; WrapMode wrapMode; AnisotropicFilter aFilter; TextureParameters(const TextureParameters& other) = delete; TextureParameters& operator= (const TextureParameters& other) = delete; void initFilterMode(FilterMode mode); void initWrapMode(WrapMode mode); void initAnisotropyFilter(AnisotropicFilter filter); void remove(); }; } #endif
true
e234e66465c43ac354e7420c1808352865f67535
C++
chenyuxiangg/dayly_practice-by-lion
/龟兔赛跑.cpp
GB18030
2,641
3.140625
3
[]
no_license
/* *Ŀƣģ *ߣMr.c *ڣ2017211 */ #include<stdio.h> double tspeek;//ڹٶ double rspeek;//ӵٶ double xtime;//˯ʱ double lng;//ȫ /* *ܣǰ׼ȥϢ *룺 * */ void init()//Ϸʼ { printf("ڹٶȣ\n"); scanf_s("%lf", &tspeek);//ǵڶȫֱĽҪIJ printf("ӵٶȣ\n"); scanf_s("%lf", &rspeek); printf("˯ʱ䣺\n"); scanf_s("%lf", &xtime); printf("ȫ\n"); scanf_s("%lf", &lng); // //printf("ts = %f,rs = %f,len = %f,xt = %f", tspeek, rspeek, lng, xtime); printf("--------------------------------------------------------\n"); } /* *ܣģܹ *룺ܳ *ڹʱ */ double trun(double lng) { double t; t = lng / tspeek; printf("ڹʱΪ%.2lf\n", t); return (t); } /* *ܣģܹ *룺ܳ *ʱ */ double rrun(double lng) { double t; t = lng / rspeek; printf("%.2lf\n", t); printf("˯%.2lf\n", xtime); printf("ʱΪ%.2lf\n", t + xtime); return (t + xtime); } /* *ܣģܹ *룺 * */ void start() { double Tt; double Tr; printf("ڿʼ\n"); printf("棬Ҹʵת\n"); printf("\n"); printf("ǿڹѡ֣СڹȻȻƶᣬΪеĿĿ¸ǰ\n"); printf("ΪСڹͣ\n"); printf("Сӣ֪ӵıٶȱڹˡ\n"); printf("СӾȻҵһȻʼ˯ˣ\n"); printf("СӾȻôţΣĿԴɣ\n"); printf("\n"); printf("Ǽĵʱ̣\n"); printf("һ𿴿\n"); printf("------------------------------------------------------------\n"); Tt = trun(lng); printf("\n"); Tr = rrun(lng); printf("\n"); if (Tt < Tr) printf("~ 򲻸ˣڹ꾭иŬսʤӣ\n"); else if (Tt > Tr) printf("ȻӸ죡\n"); else printf("漣ˣڹͬʱ\n"); } int main(void) { init(); start(); return 0; }
true
41cacb1baa87e78c758c875a69fa444020fa61c7
C++
Thhethssmuz/mmm
/test/vec/func/trig.cpp
UTF-8
4,912
3.34375
3
[ "MIT" ]
permissive
#include <catch.hpp> #include <mmm.hpp> using namespace mmm; TEST_CASE("vector relational function radians", "[vec][rel]") { SECTION("scalar") { REQUIRE(radians(90) == Approx(1.5708)); REQUIRE(radians(90.f) == Approx(1.5708)); REQUIRE(radians(90.0) == Approx(1.5708)); REQUIRE(radians(90.l) == Approx(1.5708)); } SECTION("vec2") { vec2 v = radians(vec2(0, 45)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.785398)); } SECTION("vec3") { vec3 v = radians(vec3(0, 45, 90)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.785398)); REQUIRE(v[2] == Approx(1.5708)); } SECTION("vec4") { vec4 v = radians(vec4(0, 45, 90, 180)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.785398)); REQUIRE(v[2] == Approx(1.5708)); REQUIRE(v[3] == Approx(3.14159)); } } TEST_CASE("vector relational function degrees", "[vec][rel]") { SECTION("scalar") { REQUIRE(degrees(0) == Approx(0)); REQUIRE(degrees(1.5708f) == Approx(90)); REQUIRE(degrees(1.5708) == Approx(90)); REQUIRE(degrees(1.5708l) == Approx(90)); } SECTION("vec2") { vec2 v = degrees(vec2(0, 0.785398)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(45)); } SECTION("vec3") { vec3 v = degrees(vec3(0, 0.785398, 1.5708)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(45)); REQUIRE(v[2] == Approx(90)); } SECTION("vec4") { vec4 v = degrees(vec4(0, 0.785398, 1.5708, 3.14159)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(45)); REQUIRE(v[2] == Approx(90)); REQUIRE(v[3] == Approx(180)); } } TEST_CASE("vector relational function sin", "[vec][rel]") { SECTION("scalar") { REQUIRE(sin(radians(0)) == Approx(0)); REQUIRE(sin(radians(45)) == Approx(0.70711)); REQUIRE(sin(radians(-45.f)) == Approx(-0.70711)); REQUIRE(sin(radians(90.0)) == Approx(1)); } SECTION("vec2") { vec2 v = sin(radians(vec2(0, 45))); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.70711)); } SECTION("vec3") { vec3 v = sin(radians(vec3(0, 45, -45))); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.70711)); REQUIRE(v[2] == Approx(-0.70711)); } SECTION("vec4") { vec4 v = sin(radians(vec4(0, 45, -45, 90))); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.70711)); REQUIRE(v[2] == Approx(-0.70711)); REQUIRE(v[3] == Approx(1)); } } TEST_CASE("vector relational function cos", "[vec][rel]") { SECTION("scalar") { REQUIRE(cos(radians(0)) == Approx(1)); REQUIRE(cos(radians(45)) == Approx(0.70711)); REQUIRE(cos(radians(-45.f)) == Approx(0.70711)); REQUIRE(cos(radians(90.0)) == Approx(0)); } SECTION("vec2") { vec2 v = cos(radians(vec2(0, 45))); REQUIRE(v[0] == Approx(1)); REQUIRE(v[1] == Approx(0.70711)); } SECTION("vec3") { vec3 v = cos(radians(vec3(0, 45, -45))); REQUIRE(v[0] == Approx(1)); REQUIRE(v[1] == Approx(0.70711)); REQUIRE(v[2] == Approx(0.70711)); } SECTION("vec4") { vec4 v = cos(radians(vec4(0, 45, -45, 90))); REQUIRE(v[0] == Approx(1)); REQUIRE(v[1] == Approx(0.70711)); REQUIRE(v[2] == Approx(0.70711)); REQUIRE(v[3] == Approx(0)); } } TEST_CASE("vector relational function tan", "[vec][rel]") { SECTION("scalar") { REQUIRE(tan(radians(0)) == Approx(0)); REQUIRE(tan(radians(45)) == Approx(1)); REQUIRE(tan(radians(-45.f)) == Approx(-1)); REQUIRE(tan(radians(30.0)) == Approx(0.57735)); } SECTION("vec2") { vec2 v = tan(radians(vec2(0, 45))); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(1)); } SECTION("vec3") { vec3 v = tan(radians(vec3(0, 45, -45))); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(1)); REQUIRE(v[2] == Approx(-1)); } SECTION("vec4") { vec4 v = tan(radians(vec4(0, 45, -45, 30))); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(1)); REQUIRE(v[2] == Approx(-1)); REQUIRE(v[3] == Approx(0.57735)); } } // asin // acos // atan (single argument version) TEST_CASE("vector relational function atan", "[vec][rel]") { SECTION("scalar") { REQUIRE(atan(0, 0) == Approx(0)); REQUIRE(atan(1, 1) == Approx(0.78540)); REQUIRE(atan(1.f, -1) == Approx(2.35619)); REQUIRE(atan(-1.0, 1) == Approx(-0.78540)); } SECTION("vec2") { vec2 v = atan(vec2(0, 1), vec2(0, 1)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.78540)); } SECTION("vec3") { vec3 v = atan(vec3(0, 1, 1), vec3(0, 1, -1)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.78540)); REQUIRE(v[2] == Approx(2.35619)); } SECTION("vec4") { vec4 v = atan(vec4(0, 1, 1, -1), vec4(0, 1, -1, 1)); REQUIRE(v[0] == Approx(0)); REQUIRE(v[1] == Approx(0.78540)); REQUIRE(v[2] == Approx(2.35619)); REQUIRE(v[3] == Approx(-0.78540)); } }
true
3323b4f6f3233d5126ab13bdb2e3e4151556ef07
C++
derrick0714/infer
/vn/arl/src/symptoms/PeerToPeer/PeerToPeerConfiguration.cpp
UTF-8
3,025
2.59375
3
[]
no_license
/* * File: PeerToPeerConfiguration.cpp * Author: Mike * * Created on December 10, 2009, 10:32 PM */ #include <boost/lexical_cast.hpp> #include <iostream> #include "PeerToPeerConfiguration.h" #include "PeerToPeerParams.h" #include "../IPsubnet.h" namespace vn { namespace arl { namespace symptom { PeerToPeerConfiguration::PeerToPeerConfiguration(const boost::filesystem::path &fileName) : SynappConfiguration(fileName), _ephPortStart(1024), _ephPortEnd(65535), isPhase2(true) { setOptionsDescriptions(); parseOptions(); } const IPZone& PeerToPeerConfiguration::getMonitoredZone() const { return zone; } int PeerToPeerConfiguration::getEphemeralPortStart() const { return _ephPortStart; } int PeerToPeerConfiguration::getEphemeralPortEnd() const { return _ephPortEnd; } bool PeerToPeerConfiguration::isPhaseTwo() const { return isPhase2; } void PeerToPeerConfiguration::setOptionsDescriptions() { options.add_options() ( CFG_ZONE_VALUE, boost::program_options::value<string > (), "Monitored network zone." ) ( CFG_PHASE2, boost::program_options::value<string > (), "Perform phase 2 processing. True/False." ) ( CFG_EPH_PORT, boost::program_options::value<string > (), "Ephemeral port definition (1024-65535)." ); } void PeerToPeerConfiguration::parseOptions() { boost::program_options::variables_map vals; if (!_parseOptions(vals)) { return; } if (vals.count(CFG_ZONE_VALUE)) { string zone_str = vals[CFG_ZONE_VALUE].as<string > (); IPsubnet sn = zone.addAddressRangeList(zone_str); if (sn.errored()) { std::cout << "Error parsing zone string: " << zone_str << std::endl; } } if(vals.count(CFG_PHASE2)) { string phase2str = vals[CFG_PHASE2].as<string>(); try { isPhase2 = boost::lexical_cast<bool>(phase2str); } catch( const boost::bad_lexical_cast & ) { std::cout << "Error parsing boolean: " << phase2str << std::endl; } } if(vals.count(CFG_EPH_PORT)) { string port_str = vals[OPT_EPH_PORT].as<string>(); string::size_type dash = port_str.find("-"); string port1_str = port_str.substr(0, dash); string port2_str = port_str.substr(dash + 1); try { _ephPortStart = boost::lexical_cast< int >(port1_str); _ephPortEnd = boost::lexical_cast< int >(port2_str); } catch( const boost::bad_lexical_cast & ) { std::cout << "Error parsing port numbers: " << port_str << std::endl; } } } } } }
true
a446184f32489e9d5e5328123d8eaa7384c12804
C++
lodow/bomberman
/include/ACamera.hpp
UTF-8
950
2.515625
3
[]
no_license
#ifndef ACAMERA_H # define ACAMERA_H # include <Input.hh> # include <Clock.hh> # include <glm/glm.hpp> # include <glm/gtc/matrix_transform.hpp> # include "config.h" class ACamera { public: ACamera(const glm::vec3& pos = glm::vec3(0.0, 0.0, -10.0), const glm::vec3& forward = glm::vec3(0.0, 0.0, 0.0)); virtual ~ACamera(); virtual void update(UNUSED gdl::Input& input, UNUSED const gdl::Clock& clock) {}; virtual void update(UNUSED const glm::vec3 &toFollow) {}; virtual const glm::mat4& project(); void translate(const glm::vec3& pos); void setPosition(const glm::vec3& pos); void setForward(const glm::vec3& forw); void setUp(const glm::vec3& up); const glm::vec3& getPosition() const {return _pos;}; const glm::vec3& getForward() const {return _forward;}; const glm::vec3& getUp() const {return _up;}; protected: glm::mat4 _proj; glm::vec3 _pos; glm::vec3 _forward; glm::vec3 _up; }; #endif // ACAMERA_H
true
d9a706bed2229072461436349f649bf7b8909d1a
C++
KajiyaRyusei/WashFront
/ms_project/Source/World/grid_2D.h
SHIFT_JIS
1,942
3.03125
3
[]
no_license
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // 2Diq // // Created by Ryusei Kajiya on 20151028 // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //***************************************************************************** // dCN[hh~ #pragma once //***************************************************************************** // include #include "Data/data_position.h" //***************************************************************************** // O錾 class Unit; //***************************************************************************** // NX݌v class Grid2D { public: Grid2D() { for( s32 x = 0; x < kMaxCell; ++x ) { for( s32 z = 0; z < kMaxCell; ++z ) { _cells[x][z] = nullptr; } } } virtual ~Grid2D() { } // jbg̑ virtual void HandleUnit(Unit* unit, Unit* other_unit) = 0; // }Xڂ̃jbg void HandleCell(s32 x, s32 z); // jbg̒lj void AddUnit(Unit* unit, const data::Position& position); // jbg̈ړ void MoveUnit(Unit* unit, const data::Position& position); // WcellindexԂ void SelfCoordinatesCell( s32* cell_x, s32* cell_z, const data::Position& position); // Z̃TCY static const s32 S_GetMaxCell() { return kMaxCell; } // Z̐ static const s32 S_GetSizeCell() { return kSizeCell; } // ̃Z̒S|CgĂ D3DXVECTOR3 CellCenterPoint(s32 x, s32 z) { D3DXVECTOR3 work; work.x = static_cast<fx32>(kSizeCell)* x + (kSizeCell / 2); work.y = 0.f; work.z = static_cast<fx32>(kSizeCell)* z + (kSizeCell / 2); return work; } protected: static const s32 kMaxCell = 10; static const s32 kSizeCell = 50; Unit* _cells[kMaxCell][kMaxCell]; private: // Z̎Zo s32 CellCalculation(fx32 position); };
true
555c360e5a325a19a9085e48ac73552f39cef0aa
C++
moevm/oop
/8304/sanizayyad/codes/sources/LogicService/mediator.cpp
UTF-8
2,719
2.734375
3
[]
no_license
#include "mediator.hpp" #include "BattleField.hpp" #include "unit.hpp" #include "poisonobject.hpp" #include "proxy.hpp" using namespace unit; Mediator::Mediator(std::shared_ptr<BattleField> battleField, std::shared_ptr<Proxy> proxyLog) { this->battleField = battleField; this->proxyLog = proxyLog; } bool Mediator::notify(std::shared_ptr<unit::Unit> unit,const std::string& action) { Position2D currentPosition = unit->getPosition(); auto currentCell = battleField->getFieldCell(currentPosition); Position2D nextPoint = currentPosition; if(action == MOVE_TOP || action == MOVE_LEFT || action == MOVE_RIGHT || action == MOVE_BOTTOM){ if (action == MOVE_TOP) { nextPoint.y--; if (nextPoint.y < 0) { proxyLog->logMessage(UnitLog::moveMessage(unit, currentPosition,nextPoint), TYPE::ERR); return false; } } else if (action == MOVE_LEFT) { nextPoint.x--; if (nextPoint.x < 0) { proxyLog->logMessage(UnitLog::moveMessage(unit, currentPosition,nextPoint), TYPE::ERR); return false; } } else if (action == MOVE_RIGHT) { nextPoint.x++; if (nextPoint.x >= static_cast<int>(battleField->getWidth())) { proxyLog->logMessage(UnitLog::moveMessage(unit, currentPosition,nextPoint), TYPE::ERR); return false; } } else if (action == MOVE_BOTTOM) { nextPoint.y++; if (nextPoint.y >= static_cast<int>(battleField->getHeight())) { proxyLog->logMessage(UnitLog::moveMessage(unit, currentPosition,nextPoint), TYPE::ERR); return false; } } auto nextCell = battleField->getFieldCell(nextPoint); if (nextCell->isEmpty() && nextCell->getLandscape()->canMove(unit)) { proxyLog->logMessage(UnitLog::moveMessage(unit, currentPosition,nextPoint)); nextCell->addUnit(unit); nextCell->getLandscape()->hurtUnit(unit); currentCell->deleteUnit(); (*nextCell->getNeutralObject())[unit]; nextCell->deleteNeutralObject(); return true; } proxyLog->logMessage(UnitLog::moveMessage(unit, currentPosition,nextPoint), TYPE::ERR); }else if (action == CREATE_UNIT){ if (currentCell->isEmpty()) { proxyLog->logMessage(UnitLog::createMessage(unit)); currentCell->addUnit(unit); return true; } proxyLog->logMessage(UnitLog::createMessage(unit), TYPE::ERR); } return false; }
true
01293d5894665498112518962b76248c537a68d2
C++
emtiajium/practice
/Maksud Vai/TOP Coder Algorithm Code/DP/welcometocodejam.cpp
UTF-8
896
2.96875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; char str[]="welcome to code jam"; int google(string str1); int main() { string str; int val,test,Case=1; scanf("%d\n",&test); while(test--) { getline(cin,str); val=google(str); printf("Case #%d: %04d\n",Case++,val); } return 0; } int google(string str1) { vector<int>dp[510]; int i,j; for(i=0;i<=20;i++) { for(j=0;j<=str1.size();j++) { dp[i].push_back(0); } } for(i=0;i<=str1.size();i++) { dp[0][i]=1; } for(i=0;i<19;i++) { for(j=0;j<str1.size();j++) { if(str[i]==str1[j]) { dp[i+1][j+1]=(dp[i+1][j]+dp[i][j+1])%10000; } else dp[i+1][j+1]=dp[i+1][j]; } } return dp[19][str1.size()]; } /* 3 elcomew elcome to code jam wweellccoommee to code qps jam welcome to codejam Case #1: 0001 Case #2: 0256 Case #3: 0000 */
true
f6804574ee33744b2c8f5803fb6f46684a066bcc
C++
GuMiner/Fractal
/ObjectLoader.cpp
UTF-8
2,639
2.875
3
[ "MIT" ]
permissive
#include <algorithm> #include <sstream> #include <imgui\imgui.h> #include "WireCube.h" #include "InfiniteGrid.h" #include "ObjectLoader.h" ObjectLoader::ObjectLoader(GeometryGenerationScheduler* scheduler) : objects(), objectCreationMap(), objectCreationNames(), selectedObjectToCreate(0), selectedObject(0), lastSelectedObject(-1) { objectCreationMap["Test Cube"] = [scheduler]() { return new WireCube(scheduler); }; // objectCreationMap["Test Grid"] = []() { return new InfiniteGrid(); }; for (auto it = objectCreationMap.begin(); it != objectCreationMap.end(); it++) { objectCreationNames.push_back(it->first.c_str()); } } void ObjectLoader::UpdateObjectNames() { std::map<std::string, int> objectNameCounter; backingObjectNames.clear(); for (BaseObjectType* object : objects) { std::string name = object->GetName(); if (objectNameCounter.find(name) == objectNameCounter.end()) { objectNameCounter.insert(std::make_pair(name, 0)); } objectNameCounter[name]++; // This ensures we start counting at 1, not zero. std::stringstream nameWithId; nameWithId << name << " *" << objectNameCounter[name]; backingObjectNames.push_back(nameWithId.str()); } // ImGui needs a const char** data structure, so convert our backing store to that. objectNames.clear(); for (const std::string& name : backingObjectNames) { objectNames.push_back(name.c_str()); } } void ObjectLoader::Render() { ImGui::Begin("Object Loader", nullptr, ImVec2(100, 100), 0.50f); ImGui::ListBox("Objects To Create", &selectedObjectToCreate, &objectCreationNames[0], (int)objectCreationNames.size()); if (ImGui::Button("Create")) { objects.push_back(objectCreationMap[objectCreationNames[selectedObjectToCreate]]()); UpdateObjectNames(); } if (objectNames.size() != 0) { ImGui::ListBox("Objects", &selectedObject, &objectNames[0], (int)objectNames.size()); if (lastSelectedObject != selectedObject) { lastSelectedObject = selectedObject; } if (ImGui::Button("Delete")) { BaseObjectType* object = objects[selectedObject]; objects.erase(objects.begin() + selectedObject); delete object; UpdateObjectNames(); selectedObject = selectedObject >= (int)objectNames.size() ? std::max(0, (int)objectNames.size() - 1) : selectedObject; } } ImGui::End(); }
true
9a895d721820b68ff2ae5bc81c80e209497893b0
C++
stavrossk/Common-Oblivion-Engine-Framework
/Utilities/ITypes.h
UTF-8
12,095
2.59375
3
[]
no_license
/************************************** NOTE ******************************************* This file has been imported as-is from the 'common' subproject of OBSE v0019 All credit for this code goes to the OBSE team */ #pragma once #pragma warning(disable: 4221) #include <cmath> typedef unsigned char UInt8; //!< An unsigned 8-bit integer value typedef unsigned short UInt16; //!< An unsigned 16-bit integer value typedef unsigned long UInt32; //!< An unsigned 32-bit integer value typedef unsigned long long UInt64; //!< An unsigned 64-bit integer value typedef signed char SInt8; //!< A signed 8-bit integer value typedef signed short SInt16; //!< A signed 16-bit integer value typedef signed long SInt32; //!< A signed 32-bit integer value typedef signed long long SInt64; //!< A signed 64-bit integer value typedef float Float32; //!< A 32-bit floating point value typedef double Float64; //!< A 64-bit floating point value inline UInt32 Extend16(UInt32 in) { return (in & 0x8000) ? (0xFFFF0000 | in) : in; } inline UInt32 Extend8(UInt32 in) { return (in & 0x80) ? (0xFFFFFF00 | in) : in; } inline UInt16 Swap16(UInt16 in) { return ((in >> 8) & 0x00FF) | ((in << 8) & 0xFF00); } inline UInt32 Swap32(UInt32 in) { return ((in >> 24) & 0x000000FF) | ((in >> 8) & 0x0000FF00) | ((in << 8) & 0x00FF0000) | ((in << 24) & 0xFF000000); } inline UInt64 Swap64(UInt64 in) { UInt64 temp; temp = Swap32(in); temp <<= 32; temp |= Swap32(in >> 32); return temp; } inline float SwapFloat(float in) { UInt32 * temp = (UInt32 *)(&in); *temp = Swap32(*temp); return in; } inline float SwapDouble(double in) { UInt64 * temp = (UInt64 *)(&in); *temp = Swap64(*temp); return in; } inline bool IsBigEndian(void) { union { UInt16 u16; UInt8 u8[2]; } temp; temp.u16 = 0x1234; return temp.u8[0] == 0x12; } inline bool IsLittleEndian(void) { return !IsBigEndian(); } #define CHAR_CODE(a, b, c, d) (((a & 0xFF) << 0) | ((b & 0xFF) << 8) | ((c & 0xFF) << 16) | ((d & 0xFF) << 24)) #define MACRO_SWAP16(a) ((((a) & 0x00FF) << 8) | (((a) & 0xFF00) >> 8)) #define MACRO_SWAP32(a) ((((a) & 0x000000FF) << 24) | (((a) & 0x0000FF00) << 8) | (((a) & 0x00FF0000) >> 8) | (((a) & 0xFF000000) >> 24)) #define VERSION_CODE(primary, secondary, sub) (((primary & 0xFFF) << 20) | ((secondary & 0xFFF) << 8) | ((sub & 0xFF) << 0)) #define VERSION_CODE_PRIMARY(in) ((in >> 20) & 0xFFF) #define VERSION_CODE_SECONDARY(in) ((in >> 8) & 0xFFF) #define VERSION_CODE_SUB(in) ((in >> 0) & 0xFF) #define MAKE_COLOR(a, r, g, b) (((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0)) #define COLOR_ALPHA(in) ((in >> 24) & 0xFF) #define COLOR_RED(in) ((in >> 16) & 0xFF) #define COLOR_GREEN(in) ((in >> 8) & 0xFF) #define COLOR_BLUE(in) ((in >> 0) & 0xFF) /** * A 64-bit variable combiner * * Useful for endian-independent value extraction. */ union VarCombiner { UInt64 u64; SInt64 s64; double f64; struct { UInt32 b; UInt32 a; } u32; struct { SInt32 b; SInt32 a; } s32; struct { float b; float a; } f32; struct { UInt16 d; UInt16 c; UInt16 b; UInt16 a; } u16; struct { SInt16 d; SInt16 c; SInt16 b; SInt16 a; } s16; struct { UInt8 h; UInt8 g; UInt8 f; UInt8 e; UInt8 d; UInt8 c; UInt8 b; UInt8 a; } u8; struct { SInt8 h; SInt8 g; SInt8 f; SInt8 e; SInt8 d; SInt8 c; SInt8 b; SInt8 a; } s8; }; /** * A bitfield. */ template <typename T> class Bitfield { public: Bitfield() { field = 0; } ~Bitfield() { } void Clear(void) { field = 0; } //!< Clears all bits void RawSet(UInt32 data) { field = data; } //!< Modifies all bits void Set(UInt32 data) { field |= data; } //!< Sets individual bits void Clear(UInt32 data) { field &= ~data; } //!< Clears individual bits void UnSet(UInt32 data) { Clear(data); } //!< Clears individual bits void Mask(UInt32 data) { field &= data; } //!< Masks individual bits void Toggle(UInt32 data) { field ^= data; } //!< Toggles individual bits T Get(void) const { return field; } //!< Gets all bits T Get(UInt32 data) const { return field & data; } //!< Gets individual bits T Extract(UInt32 bit) const { return (field >> bit) & 1; } //!< Extracts a bit T ExtractField(UInt32 shift, UInt32 length) //!< Extracts a series of bits { return (field >> shift) & (0xFFFFFFFF >> (32 - length)); } bool IsSet(UInt32 data) const { return ((field & data) == data) ? true : false; } //!< Are all these bits set? bool IsUnSet(UInt32 data) const { return (field & data) ? false : true; } //!< Are all these bits clear? bool IsClear(UInt32 data) const { return IsUnSet(data); } //!< Are all these bits clear? private: T field; //!< bitfield data }; typedef Bitfield <UInt8> Bitfield8; //!< An 8-bit bitfield typedef Bitfield <UInt16> Bitfield16; //!< A 16-bit bitfield typedef Bitfield <UInt32> Bitfield32; //!< A 32-bit bitfield /** * A bitstring * * Essentially a long bitvector. */ class Bitstring { public: Bitstring(); Bitstring(UInt32 inLength); ~Bitstring(); void Alloc(UInt32 inLength); void Dispose(void); void Clear(void); void Clear(UInt32 idx); void Set(UInt32 idx); bool IsSet(UInt32 idx); bool IsClear(UInt32 idx); private: UInt8 * data; UInt32 length; //!< length in bytes }; /** * Time storage */ class Time { public: Time() { Clear(); } ~Time() { } //! Deinitialize the class void Clear(void) { seconds = minutes = hours = 0; hasData = false; } //! Sets the class to the current time //! @todo implement this void SetToNow(void) { Set(1, 2, 3); } //! Sets the class to the specified time void Set(UInt8 inS, UInt8 inM, UInt8 inH) { seconds = inS; minutes = inM; hours = inH; hasData = true; } //! Gets whether the class has been initialized or not bool IsSet(void) { return hasData; } UInt8 GetSeconds(void) { return seconds; } //!< return the seconds portion of the time UInt8 GetMinutes(void) { return minutes; } //!< return the minutes portion of the time UInt8 GetHours(void) { return hours; } //!< return the hours portion of the time private: UInt8 seconds, minutes, hours; bool hasData; }; const float kFloatEpsilon = 0.0001f; inline bool FloatEqual(float a, float b) { float magnitude = a - b; if(magnitude < 0) magnitude = -magnitude; return magnitude < kFloatEpsilon; } class Vector2 { public: Vector2() { } Vector2(const Vector2 & in) { x = in.x; y = in.y; } Vector2(float inX, float inY) { x = inX; y = inY; } ~Vector2() { } void Set(float inX, float inY) { x = inX; y = inY; } void SetX(float inX) { x = inX; } void SetY(float inY) { y = inY; } void Get(float * outX, float * outY) { *outX = x; *outY = y; } float GetX(void) { return x; } float GetY(void) { return y; } void Normalize(void) { float mag = Magnitude(); x /= mag; y /= mag; } float Magnitude(void) { return sqrt(x*x + y*y); } void Reverse(void) { float temp = -x; x = -y; y = temp; } void Scale(float scale) { x *= scale; y *= scale; } void SwapBytes(void) { x = SwapFloat(x); y = SwapFloat(y); } Vector2 & operator+=(const Vector2 & rhs) { x += rhs.x; y += rhs.y; return *this; } Vector2 & operator-=(const Vector2 & rhs) { x -= rhs.x; y -= rhs.y; return *this; } Vector2 & operator*=(float rhs) { x *= rhs; y *= rhs; return *this; } Vector2 & operator/=(float rhs) { x /= rhs; y /= rhs; return *this; } float x; float y; }; inline Vector2 operator+(const Vector2 & lhs, const Vector2 & rhs) { return Vector2(lhs.x + rhs.x, lhs.y + rhs.y); }; inline Vector2 operator-(const Vector2 & lhs, const Vector2 & rhs) { return Vector2(lhs.x - rhs.x, lhs.y - rhs.y); }; inline Vector2 operator*(const Vector2 & lhs, float rhs) { return Vector2(lhs.x * rhs, lhs.y * rhs); }; inline Vector2 operator/(const Vector2 & lhs, float rhs) { return Vector2(lhs.x / rhs, lhs.y / rhs); }; inline bool MaskCompare(void * lhs, void * rhs, void * mask, UInt32 size) { UInt8 * lhs8 = (UInt8 *)lhs; UInt8 * rhs8 = (UInt8 *)rhs; UInt8 * mask8 = (UInt8 *)mask; for(UInt32 i = 0; i < size; i++) if((lhs8[i] & mask8[i]) != (rhs8[i] & mask8[i])) return false; return true; } class Vector3 { public: Vector3() { } Vector3(const Vector3 & in) { x = in.x; y = in.y; z = in.z; } Vector3(float inX, float inY, float inZ) { x = inX; y = inY; z = inZ; } ~Vector3() { } void Set(float inX, float inY, float inZ) { x = inX; y = inY; z = inZ; } void Get(float * outX, float * outY, float * outZ) { *outX = x; *outY = y; *outZ = z; } void Normalize(void) { float mag = Magnitude(); x /= mag; y /= mag; z /= mag; } float Magnitude(void) { return sqrt(x*x + y*y + z*z); } void Scale(float scale) { x *= scale; y *= scale; z *= scale; } void SwapBytes(void) { x = SwapFloat(x); y = SwapFloat(y); z = SwapFloat(z); } Vector3 & operator+=(const Vector3 & rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } Vector3 & operator-=(const Vector3 & rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } Vector3 & operator*=(const Vector3 & rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; } Vector3 & operator/=(const Vector3 & rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; return *this; } union { struct { float x, y, z; }; float d[3]; }; }; inline Vector3 operator+(const Vector3 & lhs, const Vector3 & rhs) { return Vector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); } inline Vector3 operator-(const Vector3 & lhs, const Vector3 & rhs) { return Vector3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z); } inline Vector3 operator*(const Vector3 & lhs, const Vector3 & rhs) { return Vector3(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z); } inline Vector3 operator/(const Vector3 & lhs, const Vector3 & rhs) { return Vector3(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z); }
true
3bb54d9de8200c85ed411c1b28644e17d0710c7e
C++
Gowtham-369/InterviewBitMasterSolutions
/Arrays/merge_overlapping_intervals.cpp
UTF-8
2,892
3.515625
4
[]
no_license
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool mycomp(Interval &a, Interval &b) { return a.start < b.start; } void MergeIntervals(vector<Interval> &intervals, vector<Interval> &res) { //sort on start time int n = intervals.size(); sort(intervals.begin(), intervals.end(), mycomp); int start = intervals[0].start; int end = intervals[0].end; for (int i = 1; i < n; i++) { if (end < intervals[i].start) { res.push_back(Interval(start, end)); //update start and end start = intervals[i].start; end = intervals[i].end; } else { start = min(start, intervals[i].start); end = max(end, intervals[i].end); } } res.push_back(Interval(start, end)); return; } vector<Interval> Solution::insert(vector<Interval> &intervals, Interval newInterval) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details /* int start = newInterval.start; int end = newInterval.end; vector<Interval> res; // I need to get the interval index in which start and end will there //lowerbound of start int n = intervals.size(); int ind1 = -1; for(int i=0; i<n; i++){ if(start<=intervals[i].end){ ind1= i; break; } } if(ind1 == -1){ //insert at last; intervals.push_back(newInterval); return intervals; } int ind2 = -1; for(int i=n-1; i>=0; i--){ if(end>=intervals[i].start){ ind2 = i; break; } } if(ind2 == -1){ //create new interval intervals.insert(intervals.begin(),Interval(start,end)); return intervals; } for(int i=0; i<ind1; i++){ res.push_back(intervals[i]); } //merge intevals in between [ind1,ind2] or create one // cout<<"ind1 "<<ind1<<"ind2 "<<ind2<<"\n"; if(ind1>ind2){ //new interval res.push_back(Interval(start,end)); } else{ start = min(start,intervals[ind1].start);//merge end = max(end,intervals[ind2].end);//merge Interval In = Interval(start,end); res.push_back(In); } for(int i=ind2+1; i<n; i++){ res.push_back(intervals[i]); } return res; */ intervals.push_back(newInterval); vector<Interval> res; MergeIntervals(intervals, res); return res; }
true
3892d3c6486bd321407d398979ef42244f5911f6
C++
bhavyada/AlgorithmsTest
/FindArrIndexEqVal/src/FindArrIndexEqVal.cpp
UTF-8
1,192
3.40625
3
[]
no_license
//============================================================================ // Name : ArrIndexEqVal.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <assert.h> using namespace std; const int NUM_INDEX = 10; int ARR[NUM_INDEX] = {-6, -2, -1, 0, 3, 5, 9, 10, 11, 15}; int *InArr = ARR; int FindArrIndexEqVal(int *arr, int front, int back) { assert (front <= back); int middle = (front + back) / 2; if (arr[middle] == (middle)) return (middle); else if (front == back) { return -1; } else { int result = -1; if (arr[middle] < middle) { result = FindArrIndexEqVal(arr, middle+1, back); if (result != -1) return result; } else { result = FindArrIndexEqVal(arr, 0, middle-1); if (result != -1) return result; } } return -1; } int main() { printf("Array: "); for (int i = 0; i < NUM_INDEX; ++i) { printf("[%d] %d, ", i, ARR[i]); } printf("\nFindArrIndexEqVal : %d\n", FindArrIndexEqVal(InArr, 0, 9)); return 0; }
true
a1419a72e02049c33931d90055bfafe6e5df234f
C++
Peter-Moldenhauer/CPP-Projects-Built-For-Fun
/sizeofFunction/sizeofFunction.cpp
UTF-8
1,653
4.4375
4
[]
no_license
/***************************************************************************** *Name: Peter Moldenhauer *Date: 8/19/16 *Description: This program demonstrates the use of the sizeof function. The sizeof function determines the size of something (array, variable, etc) in bytes. The sizeof function is used a lot when working with pointers. ******************************************************************************/ #include <iostream> using namespace std; int main() { cout << "--This program demonstrates the use of the sizeof() function.-- \n" << endl; char c; int i; double d; cout << "The number of bytes a char variable takes up in memory is: " << sizeof(c) << endl; cout << "The number of bytes an int variable takes up in memory is: " << sizeof(i) << endl; cout << "The number of bytes a double variable takes up in memory is: " << sizeof(d) << endl; //If an array of 10 doubles is created, we know that each double is 8 bytes so the array should take up 80 bytes (8*10) double myDoubleArray[10]; cout << "The number of bytes an array of 10 doubles takes up in memory is: " << sizeof(myDoubleArray) << endl; //The sizeof() function can be used to find out how many elements are in an array //If for example, the user creates an array and you don't know how many elements are in the array. //Then, you can use the sizeof() function to find the total size of the array then divide that number by the sizeof() an individual element of the array. cout << "The number of elements that are in the array of doubles is: " << sizeof(myDoubleArray) / sizeof(myDoubleArray[0]) << endl; return 0; }
true
6a4c21e6ca17b67bd49f703d5943b4f806e84a18
C++
surendravarma1998/my_first
/friendclass.cpp
UTF-8
227
2.953125
3
[]
no_license
#include<iostream> using namespace std; class A{ private: int a; public: A(){a=0;} friend class B; }; class B{ private: int b; public: void showA(A& x) { cout<<"A::a= "<<x.a; } }; int main() { A a; B b; b.showA(a); return 0; }
true
67adc58c929cc14bf1e0fe3e006a2d6e1fc0bd95
C++
n-n-n/cs-basics
/data_strucrure/binary_tree/heap.cpp
UTF-8
2,870
3.84375
4
[]
no_license
/* Heap / Priority Queue. Definition: - Complete binary tree. (using the array representation) - The values stored in a heap are PARTIALLY ORDERED. Two variants. - MAX-heap : a value in a node is greater than or equal to its chirdren. the root is maximum. - MIN_heap : a value in a node is less than or eqaul to its chirdren. the root is minimum. Comparison BTW BST and Heap. - BST: total order on its nodes in that. folowing a inorder traversal, left->right : smaller to larger ro larger to smaller. - Heap; ordered in the decendant. no ordered-relation amoung its siblings. Usecase of the heap - Heapsort: max-heap, - Replacement Seleaction algorith: min-heap. CAUTION - Its physical implimentation is array and logical representaion is a tree. */ // max heap. template<typename E, typename Comp> class Heap { private: E* heap; int max_size; int n; // basic opration void shift_down(int pos) { while(!isLeaf(pos)) { int i = left_child(pos); int rc = right_child(pos); // CAUTION: no order btw the left and the right. if ((rc < n) && Comp::prior(heap[rc], heap[lc])){ i = rc; // choose the greater index. } if (Comp::prior(heap[pos], heap[i])) { return; } // parent - child swap. swap(heap, pos, lc); pos = i; // move down (go to the child) } } public: Heap(E* h, int num, int max) : heap(h), n(num), max_size(max) { // build_heap for (int i = n / 2 - 1; i >= 0; i--) shift_down(i) } int size() const { return n; } bool isLeaf(int pos) const { return (pos >= n / 2) && (pos < n);} int left_child(int pos) { return 2 * pos + 1; } int right_child(int pos) { return 2 * pos + 2; } int parent(int pos) { return (pos - 1) / 2; } void insert(const E& e) { assert(n < maxsize, "Heap is full."); // put the element in the last at once. int curr = n++; heap[curr] = e; // shift up along parents while(curr != 0 && Comp::prior(heap[curr], heap[parent(curr)])) { swap(heap, curr, parent(curr)); curr = parent(curr); } } E remove_first() { assert(n > 0, "Heap is empty."); swap(heap, 0, --n); if (n != 0) shift_down(0); return heap[n]; } E remove(int pos) { assert((pos >= 0) && (pos < n), "Bad position"); if (pos == (n - 1)) { n--; } else { swap(heap, pos, --n); while((pos != 0) && (Comp::prior(heap[pos], heap[parent(pos)]))) { swap(heap, pos, prarent(pos)); pos = parent(pos); } if (n != 0) shift_down(pos); } return heap[n]; } };
true
6f9bedf78228bfc53cfdb426c05c1f0abc19a977
C++
yupengfei8421/SLAM
/src/down_sampling.cpp
UTF-8
1,021
2.625
3
[]
no_license
#include <pcl/io/pcd_io.h> #include <pcl/filters/voxel_grid.h> int main(int argc, char** argv) { // Objects for storing the point clouds. pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr filteredCloud(new pcl::PointCloud<pcl::PointXYZ>); // Read a PCD file from disk. if (pcl::io::loadPCDFile<pcl::PointXYZ>("../cmake-build-debug/map.pcd", *cloud) != 0) {return -1;} // Filter object. pcl::VoxelGrid<pcl::PointXYZ> filter; filter.setInputCloud(cloud); // We set the size of every voxel to be 1x1x1cm // (only one point per every cubic centimeter will survive). filter.setLeafSize(0.01f, 0.01f, 0.01f); filter.filter(*filteredCloud); pcl::io::savePCDFileASCII("down_sampling.pcd", *filteredCloud); std::cout<<"the number of the original point cloud: "<<cloud->points.size()<<std::endl; std::cout<<"the number of the down_sampling point cloud: "<<filteredCloud->points.size()<<std::endl; }
true
9e0b10b86e4839ea6f986bd99c7e8d3786d6efa2
C++
shhavel/arduino_car
/Exp02_IRremote_Buttons.ino
UTF-8
760
2.578125
3
[]
no_license
#include <IRremote.h> int RECV_PIN = 9; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); irrecv.enableIRIn(); // Start the receiver } void loop() { if (irrecv.decode(&results)) { switch(results.value) { case 0x20DF00FF: Serial.println("MOVE FORWARD"); break; case 0x20DF22DD: Serial.println("STOP"); break; case 0x20DF807F: Serial.println("MOVE BACKWARD"); break; case 0x20DF40BF: Serial.println("TURN RIGHT"); break; case 0x20DFC03F: Serial.println("TURN LEFT"); break; default: Serial.println(results.value, HEX); } irrecv.resume(); // Receive the next value } delay(100); }
true
9c9162cc79345f0867ff1313ac8c6ce8249616e8
C++
Eudaemonal/cs6771_class_note
/wk2102/test.cpp
UTF-8
502
2.796875
3
[]
no_license
/* Copyright (c) 2016-2017 Eudaemon <eudaemonal@gmail.com> */ #include <iostream> #include <string> #include "test.hpp" /* Not work for blank name(heading space), get_line to get space */ using namespace std; int main(int argc, char* argv[]){ std::string name, greeting; std::cout << "Please enter your first name: "; while(std::cin >> name) { greeting = "Hello, " + name + "!"; std::cout << greeting << std::endl << std::endl; std::cout << "Please enter your first name: "; } return 0; }
true
8b638a9d26344ba30714c5b2bfe5e0b2b12559da
C++
zhanglei1949/LeetCodeSolution
/86-Partition List/86-Partition List.cpp
UTF-8
1,855
3.5625
4
[]
no_license
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x): val(x),next(NULL){} }; ListNode* partition(ListNode* head, int x) { //the idea is to iteratively move the elements larger than x to the back; ListNode *new_head = new ListNode(-1); ListNode *tmp1; ListNode *tmp2; new_head->next = head; if (head==NULL) return NULL; ListNode *cur_pre = new_head; ListNode *knownFarthestLarge = cur_pre->next; while (knownFarthestLarge){ //cout<<"cur_pre: "<<cur_pre->val<<endl; //cout<<"knownFarthestLarge: "<<knownFarthestLarge->val<<endl; if (cur_pre->next->val >= x){ while (knownFarthestLarge->next && knownFarthestLarge->next->val >= x){ knownFarthestLarge = knownFarthestLarge->next; } if (!knownFarthestLarge->next) break; //cout<<"known: "<<knownFarthestLarge->val<<endl; //known->next is less than x tmp1 = cur_pre->next; tmp2 = knownFarthestLarge->next; knownFarthestLarge->next = knownFarthestLarge->next->next; cur_pre->next = tmp2; cur_pre->next->next = tmp1; //ok } cur_pre = cur_pre->next; knownFarthestLarge = cur_pre->next; } return new_head->next; } int main() { ListNode *head; ListNode *tmp; head = new ListNode(5); tmp = head; tmp->next = new ListNode(4); tmp = tmp->next; tmp->next = new ListNode(3); tmp = tmp->next; tmp->next = new ListNode(2); tmp = tmp->next; tmp->next = new ListNode(5); tmp = tmp->next; tmp->next = new ListNode(1); tmp = head; ListNode *res = partition(head, 2); tmp = res; while (tmp){ cout<<tmp->val<<" "; tmp = tmp->next; } }
true
54efc40cda24a6af83892c02bf33dbf578d136cc
C++
Alexandre-Tavares/other-works
/cs435 - mathhammer.h
UTF-8
15,034
2.75
3
[]
no_license
#include <iostream> #include <windows.h> #include <cstdlib> #include <time.h> using namespace std; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // handle to screen for colors int diceroll_generator(); int To_Wound_melee (int StrenghtVToughnessArray[][10]); int To_Hit_weaponskill_Melee (int WSArray[][10]); int To_Hit_shooting (); int To_Wound_Vehicles (int diceRoll); // scattering function needs dice roll // function for rand number roll void data_Output (bool toWoundMelee, bool WSToHitMelee, bool toHitShooting, bool toWoundVehicles, int diceRoll, double rollNeeded); int main() { bool toWoundMelee = false, WSToHitMelee = false, toHitShooting = false, toWoundVehicles = false; int userInput, diceRoll; double rollNeeded; int StrenghtVToughnessArray[10][10] ={ // array for strength v toughness on character models { 4, 5, 6, 6, 0, 0, 0, 0, 0, 0 }, // _|Toughness 1-10 { 3, 4, 5, 6, 6, 0, 0, 0, 0, 0 }, // S { 2, 3, 4, 5, 6, 6, 0, 0, 0, 0 }, // t { 2, 2, 3, 4, 5, 6, 6, 0, 0, 0 }, // r { 2, 2, 2, 3, 4, 5, 6, 6, 0, 0 }, // e { 2, 2, 2, 2, 3, 4, 5, 6, 6, 0 }, // n { 2, 2, 2, 2, 2, 3, 4, 5, 6, 6 }, // g { 2, 2, 2, 2, 2, 2, 3, 4, 5, 6 }, // h { 2, 2, 2, 2, 2, 2, 2, 3, 4, 5 }, // t { 2, 2, 2, 2, 2, 2, 2, 2, 3, 4 } }; // 1-10 int WSArray[10][10] ={ // array for weapon skill on attacker and opponent character models { 4, 4, 5, 5, 5, 5, 5, 5, 5, 5 }, // WS_|Opponent 1-10 { 3, 4, 4, 4, 5, 5, 5, 5, 5, 5 }, // A { 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }, // t { 3, 3, 3, 4, 4, 4, 4, 4, 5, 5 }, // t { 3, 3, 3, 3, 4, 4, 4, 4, 4, 4 }, // a { 3, 3, 3, 3, 3, 4, 4, 4, 4, 4 }, // c { 3, 3, 3, 3, 3, 3, 4, 4, 4, 4 }, // k { 3, 3, 3, 3, 3, 3, 3, 4, 4, 4 }, // e { 3, 3, 3, 3, 3, 3, 3, 3, 4, 4 }, // r { 3, 3, 3, 3, 3, 3, 3, 3, 3, 4 } }; // 1-10 diceRoll = diceroll_generator(); // generates random number for the dice before the function decisions do // do-while loop for user input { cout << "to calculate the roll to wound(in melee) press 1,"<<endl; cout << "to calculate the roll to hit(in melee) pres 2" << endl; cout << "to calculate the roll to hit(in shooting) pres 3" << endl; cout << "to calculate the roll to wound Vehicles press 4,"<<endl; cout << "Enter a number : "; cin >> userInput; if (userInput < 1 || userInput > 4) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "input invalid" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } else { if(userInput == 1) { toWoundMelee = true; rollNeeded = To_Wound_melee(StrenghtVToughnessArray); } if(userInput == 2) { WSToHitMelee = true; rollNeeded = To_Hit_weaponskill_Melee (WSArray); } if(userInput == 3) { toHitShooting = true; rollNeeded = To_Hit_shooting (); } if(userInput == 4) { toWoundVehicles = true; rollNeeded = To_Wound_Vehicles (diceRoll); } } }while (userInput < 0 || userInput > 4); data_Output (toWoundMelee, WSToHitMelee, toHitShooting, toWoundVehicles, diceRoll, rollNeeded); Sleep(1000); return 0; } // end of main int To_Wound_melee (int StrenghtVToughnessArray[][10]) { int Toughness, Strenght, woundResult; do{ cout << "Enter the strength of the attacking unit : "; cin >> Strenght; cout << "Enter the toughness of the defending unit : "; cin >> Toughness; if (Strenght < 1 || Strenght > 10) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: Attacker's strength must be between 1 and 10" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } if (Toughness < 1 || Toughness >10) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: Defender's toughness must be between 1 and 10" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } }while(Strenght < 0 || Strenght > 10 || Toughness < 0 || Toughness > 10); Strenght = (Strenght - 1); Toughness = (Toughness - 1); woundResult = StrenghtVToughnessArray[Strenght][Toughness]; return(woundResult); } // end of to wound melee function int To_Hit_weaponskill_Melee (int WSArray[][10]) { int attackerWS, opponentWS, weaponHitResult; do{ cout << "Enter the Weapon skill of the attacker : "; cin >> attackerWS; cout << "Enter the weapon skill of the opponent : "; cin >> opponentWS; if (attackerWS < 1 || attackerWS > 10) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: Attacker's weapon skill must be between 1 and 10" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } if (opponentWS < 1 || opponentWS > 10) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: Defender's weapon skill must be between 1 and 10" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } }while((attackerWS < 0 || attackerWS > 10) || (opponentWS < 0 || opponentWS > 10)); attackerWS = (attackerWS - 1); opponentWS = (opponentWS -1); weaponHitResult = (WSArray[attackerWS][opponentWS]); return(weaponHitResult); }// end of to hit weapon skill melee function int To_Hit_shooting () { int ballisticSkill, ballisticResult; do{ cout << "Enter the Ballistic skill of the shooter : "; cin >> ballisticSkill; if(ballisticSkill < 1 || ballisticSkill > 10) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: Shooter's weapon skill must be between 1 and 10" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } }while(ballisticSkill < 1 || ballisticSkill > 10); if (ballisticSkill > 5) { ballisticResult = 2; } if (ballisticSkill == 4) { ballisticResult = 3; } if (ballisticSkill == 3) { ballisticResult = 4; } if (ballisticSkill == 2) { ballisticResult = 5; } if (ballisticSkill <= 1) { ballisticResult = 6; } return (ballisticResult); }//end of to hit shooting function int To_Wound_Vehicles (int diceRoll) { int armorValue, weaponStrenght, weaponArmorPierce, vehicalWoundResult, validInputCheck; do{ validInputCheck = 0; // resets the sentinal verable to 0 when loop reiterates, meaning the input was invalid cout << "Enter the strength of the weapon from the shooter : "; cin >> weaponStrenght; cout << "Enter the Armor Value of the Vehicle : "; cin >> armorValue; cout << "Enter the Weapon Armor Piercing value : "; cin >> weaponArmorPierce; if((weaponStrenght < 4 || weaponStrenght > 10)) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: Weapon strength must be between 4 and 10" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } else { validInputCheck++; } if ((armorValue < 10 || armorValue > 14)) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: vehicle armor must be between 10 and 14" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } else { validInputCheck++; } if ((weaponArmorPierce < 1 ) || (weaponArmorPierce > 6)) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << "Invalid input: weapon AP must be between 1 and 6" << endl; Sleep(1000); system("CLS"); SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white } else { validInputCheck++; } }while(validInputCheck < 3); vehicalWoundResult = (diceRoll + weaponStrenght); if (vehicalWoundResult > armorValue) { vehicalWoundResult = 3; // pen hit } else if (vehicalWoundResult == armorValue) { vehicalWoundResult = 2; // glancing hit } else { vehicalWoundResult = 1; // no effect of the hit } return (vehicalWoundResult); }// end of to wound vehicles function int diceroll_generator() { int diceResult; srand(time(NULL)); diceResult = (rand() % 6 + 1 ); return (diceResult); }// end of diceroll generator function void data_Output (bool toWoundMelee, bool WSToHitMelee, bool toHitShooting, bool toWoundVehicles, int diceRoll, double rollNeeded) { if (toWoundMelee == true) { if(rollNeeded == 0) // chance to hit above 6 on dice therefor unable to wound target { cout << " Not possible to wound"; } else { if ((rollNeeded == 3)) { SetConsoleTextAttribute( hConsole, (FOREGROUND_GREEN | FOREGROUND_INTENSITY)); // text color green } else if ((rollNeeded == 6)) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY));// text color red } else { SetConsoleTextAttribute(hConsole, (FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color yellow } cout << rollNeeded << "+ on the roll to wound" << endl; } SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white }// end of to wound melee if true if (WSToHitMelee == true) // to hit in melee combat { if (rollNeeded == 3) { SetConsoleTextAttribute( hConsole, (FOREGROUND_GREEN | FOREGROUND_INTENSITY)); // text color green } else if (rollNeeded == 5) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY));// text color red } else { SetConsoleTextAttribute(hConsole, (FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color yellow } cout << rollNeeded << "+ on the roll to Hit in melee" << endl; SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white }// end of WS to hit melee if true if(toHitShooting == true) // shooting to hit { if (rollNeeded <= 3) { SetConsoleTextAttribute( hConsole, (FOREGROUND_GREEN | FOREGROUND_INTENSITY)); // text color green } else if (rollNeeded >= 5) { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red } else { SetConsoleTextAttribute(hConsole, (FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color yellow } cout << rollNeeded << "+ on the roll to Hit in shooting" << endl; SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white }// end of to hit shooting if true if(toWoundVehicles == true) // to wound vehicle after shooting has hit { if (rollNeeded = 3) // pen hit { SetConsoleTextAttribute( hConsole, (FOREGROUND_GREEN | FOREGROUND_INTENSITY)); // text color green cout << " Attack Penned vehicle armor" << endl; } else if (rollNeeded = 2)// glancing hit { SetConsoleTextAttribute(hConsole, (FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color yellow cout << " Attack glanced vehicle armor" << endl; } else if (rollNeeded = 1)// no effect of the hit { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red cout << " Attack had no effect on vehicle armor" << endl; } if (diceRoll <= 2)//red color text for diceroll display { SetConsoleTextAttribute(hConsole, (FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color red } else if (diceRoll == 3 || diceRoll == 4)//yellow color text for dicetoll display { SetConsoleTextAttribute(hConsole, (FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)); // text color yellow } else if (diceRoll >= 5)// green color text for diceroll display { SetConsoleTextAttribute( hConsole, (FOREGROUND_GREEN | FOREGROUND_INTENSITY)); // text color green } cout << " " << diceRoll << " was rolled" << endl; SetConsoleTextAttribute( hConsole, (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED)); // text color white }// end of to wound vehicles if true
true
dc66e2f5dd544d9691b4810450cf76b7955e04ef
C++
aniec07/ChessBase
/chess_base/WORKING_VERSION_2.1/ChessBaseTracer/chessPieceFunctions.cpp
UTF-8
474
2.96875
3
[]
no_license
char chessPiece::getColor() { return color; } string chessPiece::getType() { return type; } int chessPiece::getRow() { return (position.row); } char chessPiece::getColumn() { return (position.column); } chessPiece::chessPiece(cell pos, string name, char col) { position.row = pos.row; position.column = pos.column; type = name; color = col; } void chessPiece::move(cell destination) { position.row = destination.row; position.column = destination.column; }
true
993fafb525e6b1036edd6d7316762bb63822fa4e
C++
rvillegasm/NuMath
/src/interpolation/newtonInterp.cpp
UTF-8
1,464
3.046875
3
[ "MIT" ]
permissive
#include "newtonInterp.h" #include <vector> #include <string> namespace numath{ namespace interpolation { std::string newton(std::vector<numath::Point> &points) { const unsigned int N = points.size(); double table[N][N]; std::string result = ""; // Initialize table with the F(x) values for (unsigned int i = 0; i < N; i++) { table[i][0] = points[i].y; } // Calculate all the values of the table for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 1; j <= i; j++) { table[i][j] = (table[i][j-1] - table[i-1][j-1]) / (points[i].x - points[i-j].x); } } // Build the polynomial for (unsigned int i = 0; i < N; i++) { // calculate each term of the polynomial equation std::string term; if (i == 0) { term = std::to_string(table[i][i]); } else { term = "+" + std::to_string(table[i][i]); } for (unsigned int k = 0; k < i; k++) { term = term + "*(x-" + std::to_string(points[k].x) + ")"; } result = result + term; } return result; } } }
true
13316dc0c3fce856b50803d0805e5a1003c453a5
C++
aleksejleskin/RetroRocketRampage
/SmallBoxStudios/Glyph.h
UTF-8
1,159
2.515625
3
[]
no_license
#ifndef INLCUDE_GUARD_GLYPH_H #define INLCUDE_GUARD_GLYPH_H #include "CellShaderObject.h" #include "PhysicsObject.h" using namespace std; class Glyph : public PhysicsObject { public: Glyph(); Glyph( string filename, float yaw, float pitch, float roll, float scale, bool physics ); ~Glyph(); bool LoadContent(string filename, float yaw, float pitch, float roll, float scale, bool physics, DxGraphics *dx, XMFLOAT3 position, ResourceManager& resource); void CreateRigidBody(btDynamicsWorld* dynamicsWorld, float mass ); void UnloadContent(); void Update(float dt); void Render(DxGraphics* dx, Camera& cam, LightManager& lightManager); bool GetLoaded(); XMFLOAT4 GetColour(); void SetColour(XMFLOAT4 _colour); void SetLetterOffset(XMFLOAT3 _letterOffset); XMFLOAT3 GetLetterOffset(); void ColourFadeSwitch(bool _switch); void SetLoadedGlyph(bool _loaded); bool GetLoadedGlyph(); private: bool m_loaded, m_physicsObj; CellShaderObject m_cellShader; //Colour of the letter, used for colourfade XMFLOAT4 m_colour; XMFLOAT3 m_letterOffset; float m_dt; bool m_colourFadeSwitch; bool m_loadedGlyph; }; #endif
true
f01ca3a1eaf034f0c45a14b28386bbf6ceb9ae8a
C++
leomaurodesenv/contest-codes
/contests/uri/uri-1251.cpp
ISO-8859-1
1,660
2.75
3
[ "MIT" ]
permissive
/* * Problema: Diga-me a Frequncia * https://www.urionlinejudge.com.br/judge/pt/problems/view/1251 */ #include <iostream> #include <iomanip> #include <cstdio> #include <cstdlib> #include <numeric> #include <string> #include <sstream> #include <iomanip> #include <locale> #include <bitset> #include <map> #include <vector> #include <queue> #include <stack> #include <algorithm> #include <cmath> #define INF 0x3F3F3F3F #define PI 3.14159265358979323846 #define EPS 1e-10 #define file_in(file) freopen(file".in", "r", stdin) #define file_out(file) freopen(file".out", "w+", stdout) #define vet_i(var, tipo, lin, col, inic) vector< vector< tipo > > var (lin, vector< tipo > (col, inic)) #define vet_d(tipo) vector< vector< tipo > > #define lli long long int #define llu unsigned long long int #define fore(var, inicio, final) for(int var=inicio; var<final; var++) #define forec(var, inicio, final, incremento) for(int var=inicio; var<final; incremento) #define forit(it, var) for( it = var.begin(); it != var.end(); it++ ) using namespace std; bool compareBySecond(const pair<char, int> &a, const pair<char, int> &b){ return a.second < b.second; } int main(){ string str; while(getline(cin, str)){ map<char, int> freq; fore(i, 0, str.size()){ freq[str[i]]++; } vector< pair<char, int> > out; map<char, int>::iterator it; forit(it, freq){ out.push_back(*it); } sort(out.begin(), out.end(), compareBySecond); fore(i, 0, out.size()){ printf("%d %d\n", out[i].first, out[i].second); } cout<<'\n'; } return 0; }
true
f59b71857fd60b0e5661be6406377f6bcad0c3d5
C++
faxinwang/cppNotes
/othes/io/02使用read和write函数读写二进制文件.cpp
GB18030
643
2.828125
3
[]
no_license
#include<fstream> #include<string.h> #include<iostream> using namespace std; //istream& read(unsigned char* buf,int num) //ostream& write(const unsigned char *buf,int num) int main2(){ ofstream fout("test.txt"); if(!fout){ cout<<"ļдʧ!"; return 1; } int a=123,b=0; char str[]="ļд˫ַ!",str2[50]; fout.write((char*)&a,sizeof(double)); fout.write(str,strlen(str)); fout.close(); ifstream fin("test.txt"); if(!fin){ cout<<"ļʧ"; return 1; } fin.read((char*)&b,sizeof(double)); fin.read(str,26); cout<<b<<" "<<str2<<endl; fin.close(); return 0; }
true
267b834e330430931a9464e85dc91be230093f64
C++
SubhamKhinchi/CPP
/LinkedList/DeleteNthNode.cpp
UTF-8
1,136
3.75
4
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Node{ int data; Node* next; }; void insert(Node** head, int k){ Node* temp = new Node(); temp->data = k; temp->next = *head; *head = temp; } Node* deletenode (Node** head, int key){ //if head has to be deleted. if((*head)->data == key){ Node* temp = (*head)->next; *head = temp; } Node* curr, *prev ; curr = *head; prev = NULL; while(curr){ if(curr->data == key){ prev->next = curr->next; return *head; } else{ prev = curr; curr = curr->next; } } return *head; } void printlist(Node* head){ Node* t = head; while(t){ cout<<t->data<<" "; t=t->next; } cout<<"\n"; } int main() { Node* head = NULL; insert(&head, 5); insert(&head, 4); insert(&head, 3); insert(&head, 2); insert(&head, 1); cout<<"original linked list : "; printlist(head); deletenode(&head , 2); cout<<"Linked list after deletion : "; printlist(head); return 0; }
true
443c0a15d8c877068bbe7b666dd462a5d61c7b03
C++
genc-ahmeti/personal-projects
/C++ Projects/Visual C++ Projects/Testübungen/Testübungen/CB_Letter Count.cpp
UTF-8
1,005
3.078125
3
[]
no_license
//#include <iostream> //#include <vector> //# include <string> //using namespace std; // //string MultipleLetters(string satz) //{ // vector <string> wort (10); // int i = 0; // int merk = -1; // satz[0] = tolower(satz[0]); // // for(int n = 0; n <= satz.length(); n++) // { // while(n < satz.length() && satz[n] != ' ') // wort[i] += satz[n++]; // ++i; // } // i = 1; // // int temp = 0; // for(int element = 0; element < wort.size(); element++) // { // if(wort[element].empty()) // break; // for(int car = 0; car < wort[element].length(); car++) // { // // for(int n = 0; n < wort[element].length(); n++) // { // if(car != n && wort[element][car] == wort[element][n]) // ++temp; // } // // if(temp > i) // { // i = temp; // merk = element; // } // temp = 0; // } //} // if(merk != -1) // return wort[merk]; // else // return "-1"; // // //} // //int main() //{ // string satz = "Hahaha hiiiiiiiiii lllolololoseses"; // // cout << MultipleLetters(satz); // // return 0; // //}
true
5289de70a62b23398d8a59ddfb517372018a1d4e
C++
garbb/tomtom.gps.auto.on
/old/1/tomtom.gps.auto.on/tomtom.gps.auto.on.ino
UTF-8
1,404
3.0625
3
[]
no_license
// The TomTom Mkii Bluetooth GPS receiver does not automatically turn on when power is applied via its charging port. // The power button must be held for approximately 1 second to turn it on. // This program is intented to be used with an ardunio with an I/O pin connected to one of the leads of the power button // to simulate a power button press and turn the device on as soon as the arduino powers on. // pin to be connected to tomtom gps power button #define pwrbuttonpin 10 // delay for simulated power button hold-down #define pwrbuttondelay 1200 // built-in led pin #define ledpin 13 void setup() { //pinMode(ledpin, OUTPUT); // set pwrbuttonpin pin HIGH (to 5v) digitalWrite(pwrbuttonpin, HIGH); // short pwrbuttonpin to ground // (simulate button press) pinMode(pwrbuttonpin, OUTPUT); //digitalWrite(ledpin, HIGH); // wait delay(pwrbuttondelay); // disconnect pwrbuttonpin (input mode = high impediance) // (simulate button release) pinMode(pwrbuttonpin, INPUT); //digitalWrite(ledpin, LOW); } void loop() { /* delay(pwrbuttondelay); // short pwrbuttonpin to ground // (simulate button press) pinMode(pwrbuttonpin, OUTPUT); digitalWrite(ledpin, HIGH); delay(pwrbuttondelay); // disconnect pwrbuttonpin (input mode = high impediance) // (simulate button release) pinMode(pwrbuttonpin, INPUT); digitalWrite(ledpin, LOW); */ }
true
e3f7bbf9e125dc9d3ea3e570acbcf8e00a5f89b2
C++
hail-pas/leetcode
/0004-median-of-two-sorted-arrays.cpp
UTF-8
1,679
3.328125
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> class Solution { public: double findMedianSortedArrays(const std::vector<int>& nums1, const std::vector<int>& nums2) { if (nums1.size() == 0 and nums2.size() == 0) return 0.0; if (nums1.size() < nums2.size()) { return findMedianSortedArrays(nums2, nums1); } int m = nums1.size(); int n = nums2.size(); int i_min = 0; int i_max = m; int i = 0, j = 0, max_left = 0, min_right = 0; while (i_min <= i_max) { i = (i_min + i_max) / 2; j = (m + n + 1) / 2 - i; if (i != 0 && j != n && nums1[i - 1] > nums2[j]) { i_max = i - 1; }else if (j!=0 && i!= m && nums2[j - 1]> nums1[i]) { i_min = i + 1; }else { if (i == 0) { max_left = nums2[j]; }else if (j == 0) { max_left = nums1[i]; }else { max_left = std::max(nums1[i-1], nums2[j-1]); } if ((m + n) % 2 != 0) { return max_left; } if (i==m) { min_right = nums2[j]; }else if (j == n) { min_right = nums1[i]; }else { min_right = std::min(nums1[i], nums2[j]); } return (max_left + min_right) / 2.0; } } return 0.0; } }; int main(int argc, char const *argv[]) { std::cout<<Solution().findMedianSortedArrays({1, 3}, {2, 4})<<std::endl; return 0; }
true
694ef64cd659d43e5687cebd00e084170e6393e2
C++
sgumhold/cgv
/libs/rect_pack/RectangleBinPack/ShelfNextFitBinPack.h
ISO-8859-1
849
3
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/** @file ShelfNextFitBinPack.h @author Jukka Jylnki @brief Implements the naive Shelf Next Fit bin packer algorithm. This algorithm is not recommended for real use at all - its only advantage is that it consumes only a constant amount of memory, whereas the other packers in this library use at least a linear amount of memory. This work is released to Public Domain, do whatever you want with it. */ #pragma once #include <vector> namespace rbp { class ShelfNextFitBinPack { public: struct Node { int x; int y; int width; int height; bool flipped; }; void Init(int width, int height); Node Insert(int width, int height); /// Computes the ratio of used surface area. float Occupancy() const; private: int binWidth; int binHeight; int currentX; int currentY; int shelfHeight; unsigned long usedSurfaceArea; }; }
true
154aa87247ff22a385c51b02684e6021b4d74034
C++
MathProgrammer/LeetCode
/Contests/Weekly Contest 342/Programs/Minimum Number of Operations to Make All Array Elements Equal to 1.cpp
UTF-8
1,433
2.890625
3
[]
no_license
class Solution { public: int minOperations(vector<int>& nums) { int frequency_1 = 0; int g = 0; for(int n : nums) { g = __gcd(g, n); frequency_1 += (n == 1); } if(g != 1) { return -1; } if(frequency_1 > 0) { return nums.size() - frequency_1; } int smallest_coprime_array = nums.size(); vector <vector <int> > gcd(nums.size() + 1, vector <int> (nums.size() + 1)); for(int length = 2; length <= nums.size(); length++) { for(int left = 0, right = left + length - 1; right < nums.size(); left++, right++) { if(length == 2) { gcd[left][right] = __gcd(nums[left], nums[right]); } else { gcd[left][right] = __gcd(nums[left], gcd[left + 1][right]); } if(gcd[left][right] == 1) { smallest_coprime_array = min(smallest_coprime_array, length); } } } int creating_first_1 = smallest_coprime_array - 1; cout << "S = " << smallest_coprime_array << "\n"; int answer = nums.size() - 1 + creating_first_1; return answer; } };
true
648534542a6b1a239e22e81a87b60c560c6b22a8
C++
AntI-HI/CSE241-HomeWorks
/HW3/main.cpp
UTF-8
3,809
3.296875
3
[]
no_license
#include "hex.h" using namespace std; int main(int argc, char *argv[]){ cout << endl << "Welcome to Drive File. " << endl << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; cout << endl << "First and Second GAME" << endl << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; HEX Hex1(8, 0); HEX Hex2(10, 0); // Testing play(int, int) function for Hex1 object Hex1.play(1,1); cout << "Testing play(int, int) function for Hex1 object" << endl; // Testing DrawTable()const function for Hex1 object cout << "Testing DrawTable()const function for Hex1 object" << endl; Hex1.DrawTable(); // Testing play() function for Hex1 object cout << "Testing play() function for Hex1 object" << endl; Hex1.play(); // Testing DrawTable()const function for Hex1 object cout << "Testing DrawTable()const function for Hex1 object" << endl; Hex1.DrawTable(); // Testing play(int, int) function for Hex2 object cout << "Testing play(int, int) function for Hex2 object" << endl; Hex2.play(2,1); // Testing DrawTable()const function for Hex2 object cout << "Testing DrawTable()const function for Hex2 object" << endl; Hex2.DrawTable(); // Testing play() function for Hex2 object cout << "Testing play() function for Hex2 object" << endl; Hex2.play(); // Testing DrawTable()const function for Hex2 object cout << "Testing DrawTable()const function for Hex2 object" << endl; Hex2.DrawTable(); // Testing SaveGame(const std::string&)const function and LoadGame(const std:: string&) functions. cout << "Testing SaveGame(const std::string&)const function and LoadGame(const std:: string&) functions." << endl; cout << "Saving Hex1 object to file.txt..." << endl; Hex1.SaveGame("file.txt"); cout << "Loading the game from file2.txt to Hex2 object." << endl; Hex2.LoadGame("file2.txt"); // Testing compareGames(const HEX&)const function. cout << "Comparing Hex1 and Hex2..." << endl; cout << Hex1.compareGames(Hex2) << endl; // Testing getNumberOfMarked() static function. cout << "Getting the number of Marked Cells from all HEX games..." << endl; cout << HEX::getNumberOfMarked() << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; cout << endl << "Third GAME" << endl << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; HEX Hex3; Hex3.LoadGame("file3.txt"); // Testing the getGame(int) function cout << "Testing the getGame(int) function" << endl; HEX& aux = HEX::getGame(2); aux.DrawTable(); //Test for IsGameOver() function cout << "Test for IsGameOver() function." << endl; cout << Hex3.IsGameOver() << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; cout << endl << "Fourth GAME" << endl << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; cout << "Testing the third constructor which takes fileName to Load the game from file." << endl; HEX Hex4("file3.txt"); // Fifth Game covers all the functionality that I implement within the HEX class. cout << "/////////////////////////////////////////////////////////////////" << endl; cout << endl << "Fifth GAME" << endl << endl; cout << "/////////////////////////////////////////////////////////////////" << endl; HEX Hex5; while(!HEX::getTerminate() && HEX::getNumberOfEndGame() < HEX::getNumberOfGames()) { HEX::getGame(HEX::getCurrentGame()-1).DrawTable(); HEX::getGame(HEX::getCurrentGame()-1).Update(); } return 0; }
true
ce1512de42cdce4d7739d4b847f731a96b1243ec
C++
TzuChieh/Photon-v2
/Engine/Source/SDL/SdlDependencyResolver.h
UTF-8
1,666
2.78125
3
[ "MIT" ]
permissive
#pragma once #include "SDL/sdl_fwd.h" #include "Utility/TSpan.h" #include <string> #include <string_view> #include <unordered_map> #include <vector> #include <cstddef> #include <queue> #include <optional> namespace ph { class SdlDependencyResolver final { public: SdlDependencyResolver(); /*! @brief Submit resources and start to resolve their dependencies. The containers for input do not need to be kept alive after this call. @param resources Resources to be analyzed. @param resourceNames Names for the resources. Must have exactly the same size as @p resources if provided. */ void analyze( TSpanView<const ISdlResource*> resources, TSpanView<std::string> resourceNames = {}); /*! @brief Get a resource from the analyzed scene with a valid dependency ordering. @return A resource. Can be called repeatedly until `nullptr` is returned (which indicates all analyzed resources are returned). */ const ISdlResource* next(); /*! @brief Get resource name by resource pointer. Only valid for the resources in the last `analyze()` call. */ std::string getResourceName(const ISdlResource* resource) const; private: struct ResourceInfo { const ISdlResource* resource; std::string name; inline ResourceInfo() : resource(nullptr), name() {} }; std::vector<ResourceInfo> m_resourceInfos; std::queue<const ISdlResource*> m_queuedResources; std::unordered_map<const ISdlResource*, std::size_t> m_resourceToInfoIndex; void calcDispatchOrderFromTopologicalSort(); std::optional<std::size_t> getResourceInfoIdx(const ISdlResource* resource) const; }; }// end namespace ph
true
ca7f7a668e752a495df6215e0895b807f3202596
C++
AdityaRJha/data_structure_n_algo
/array2.cpp
UTF-8
2,338
3.6875
4
[]
no_license
#include<iostream> using namespace std; struct Pair { int min; int max; }; Pair minmax(int arr[], int n) { Pair send; send.max = send.min = arr[0]; while(n) { if(arr[n -1] > send.max) send.max = arr[n -1]; if(arr[n-1] < send.min) send.min = arr[n-1]; --n; } return send; } Pair minmaxRecursion(int arr[], int high, int low) { Pair send, above, below; int mid; if(high == low) { send.max = send.min = arr[0]; return send; } if(high == low + 1) { if (arr[high] > arr[low]) { send.max = arr[high]; send.min = arr[low]; } else { send.max = arr[low]; send.min = arr[high]; } return send; } mid = (int)((low+high)/2); above = minmaxRecursion(arr, high, mid + 1); below = minmaxRecursion(arr, mid, low); if(above.max > below.max) send.max = above.max; else send.max = below.max; if(above.min < below.min) send.min = above.min; else send.min = below.min; return send; } Pair minmaxPairing(int arr[], int n) { Pair send; int i; if(n % 2 == 0) { if (arr[0] > arr[1]) { send.min = arr[1]; send.max = arr[0]; } else { send.max = arr[1]; send.min = arr[0]; } i = 2; } else { send.min = send.max = arr[0]; i = 1; } while (i < n -1) { if (arr[i] < arr[i + 1]) { if(arr[i] < send.min) send.min = arr[i]; if(arr[i + 1] > send.max) send.max = arr[i + 1]; } else { if(arr[i + 1] < send.min) send.min = arr[i + 1]; if(arr[i] > send.max) send.max = arr[i]; } i += 2; } return send; } void print(Pair p) { cout<<"\nMax: "<<p.max; cout<<"\nMin: "<<p.min; } int main() { int arr[] = {1321, 632, 56, 25, 36, 56, 751, 23, 1}; Pair p1, p2, p3; p1 = minmaxPairing(arr, 9); p2 = minmaxRecursion(arr, 8, 0); p3 = minmax(arr, 9); print(p1); print(p2); print(p3); }
true
01d053b8d4f10d4a5ecfc9c3b619a1818cc7d121
C++
mcagriardic/Blackjack-cpp
/BlackJack.cpp
UTF-8
16,369
2.765625
3
[]
no_license
#include "BlackJack.h" extern BlackJack* blackjack; BlackJack::BlackJack(const int& _playerCount, const int& _noOfDeck) : playerCount(_playerCount), noOfDecks(_noOfDeck) { setFSM(); setPlayers(); }; BlackJack::~BlackJack() { for (Participants* obj : participants) delete obj; participants.clear(); delete blackjack; } /* =========================== PRINTS =========================== */ void BlackJack::printDeck() { deck.print(); } void BlackJack::printCards(const bool& isStateDealing) { for (int playerIdx = 0; playerIdx < participants.size(); playerIdx++) { vector<Hand*> hands = participants[playerIdx]->getHands(); for (int handIdx = 0; handIdx < hands.size(); handIdx++) { participants[playerIdx]->displayHand(hands[handIdx], isStateDealing); } } } /* =========================== GETS =========================== */ int BlackJack::getWinnerIdx() { for (size_t i = 0; i < participants.size(); i++) { if (participants[i]->getisWinner()) { return i; } } } int BlackJack::getNextPlayer() { if (activePlayerIdx < playerCount) { return activePlayerIdx + 1; } else { return 0; } } int BlackJack::getNextHand() { return activeHandIdx + 1; } int BlackJack::getCurrentHandScore() { return participants[activePlayerIdx]->getHandByIdx(activeHandIdx)->score; } vector<Hand*> BlackJack::getnotBustHands() { vector<Hand*> notBustHands; for (int playerIdx = 1; playerIdx < participants.size(); playerIdx++) { for (Hand* hand : participants[playerIdx]->getHands()) { if (!hand->getisHandBust()) { notBustHands.push_back(hand); } } } return notBustHands; } vector<Hand*> BlackJack::getHandsScoreHigherThanDealerHand() { vector<Hand*> playerHandsHigherThanDealer; // dealer will always have one hand int dealerScore = participants[0]->getHandByIdx(0)->getScore(); for (int playerIdx = 1; playerIdx < participants.size(); playerIdx++) { for (Hand* hand : participants[playerIdx]->getHands()) { if ( dealerScore < hand->getScore() && !hand->getisHandBust() ) { playerHandsHigherThanDealer.push_back(hand); } } } return playerHandsHigherThanDealer; } vector<Hand*> BlackJack::getHandsScoreEqualToDealerHand() { vector<Hand*> playerHandsEqualToDealer; // dealer will always have one hand int dealerScore = participants[0]->getHandByIdx(0)->getScore(); for (int playerIdx = 1; playerIdx < participants.size(); playerIdx++) { for (Hand* hand : participants[playerIdx]->getHands()) { if ( dealerScore == hand->getScore() && !hand->getisHandBust() ) { playerHandsEqualToDealer.push_back(hand); } } } return playerHandsEqualToDealer; } int BlackJack::getIdxPlayerCanSplit() { for (size_t playerIdx = 1; playerIdx < participants.size(); playerIdx++) { if (!participants[playerIdx]->gethasRefusedSplit()) { vector<Hand*> hands = participants[playerIdx]->getHands(); for (int handIdx = 0; handIdx < hands.size(); handIdx++) { if (hands[handIdx]->cards[0].rank.compare( hands[handIdx]->cards[1].rank ) == 0) { return playerIdx; } } } } } int BlackJack::getIdxHandCanSplit() { for (size_t playerIdx = 1; playerIdx < participants.size(); playerIdx++) { if (!participants[playerIdx]->gethasRefusedSplit()) { vector<Hand*> hands = participants[playerIdx]->getHands(); for (int handIdx = 0; handIdx < hands.size(); handIdx++) { if (hands[handIdx]->cards[0].rank.compare(hands[handIdx]->cards[1].rank) == 0) { return handIdx; } } } } } /* =========================== SETS =========================== */ void BlackJack::setActivePlayer(const int& _activePlayerIdx) { activePlayerIdx = _activePlayerIdx; } void BlackJack::setActiveHand(const int& _activeHandIdx) { activeHandIdx = _activeHandIdx; } void BlackJack::setcanPlay(const bool& status) { participants[activePlayerIdx]->setcanPlay(status); } void BlackJack::setisWinner(const bool& status) { participants[activePlayerIdx]->setisWinner(status); } void BlackJack::setWinnerByIndex(const int& participantIdx) { participants[participantIdx]->setisWinner(true); } void BlackJack::setFSM() { fsm.setCurState("initialise"); fsm.addState("initialise", setInitialiseState()); fsm.addState("dealing", setDealingState()); fsm.addState("split", setsplitState()); fsm.addState("splitYes", setsplitYesState()); fsm.addState("splitNo", setsplitNoState()); fsm.addState("playerTurn", setplayerTurnState()); fsm.addState("playerHit", setplayerHitState()); fsm.addState("playerStand", setplayerStandState()); fsm.addState("handGoesBust", sethandGoesBustState()); fsm.addState("outOfTheGame", setoutOfTheGameState()); fsm.addState("dealerTurn", setdealerTurnState()); fsm.addState("playersLose", setplayersLoseState()); fsm.addState("dealerHit", setdealerHitState()); fsm.addState("dealerStand", setdealerStandState()); fsm.addState("dealerWin", setdealerWinState()); fsm.addState("dealerLose", setdealerLoseState()); fsm.addState("playerWin", setplayerWinState()); fsm.addState("canPlayHandsWin", setcanPlayHandsWinState()); fsm.addState("higherScoreHandsWin", sethigherScoreHandsWinState()); fsm.addState("standOff", setstandOffState()); fsm.addState("restart", setrestartState()); fsm.addState("quit", setquitState()); } void BlackJack::setPlayers() { Participants* dealer = new Dealer(); participants.push_back(dealer); for (int i = 0; i < playerCount; i++) { Participants* player = new Player(); participants.push_back(player); } }; /* =========================== RESETS =========================== */ void BlackJack::resetAttributes() { for (int i = 0; i < participants.size(); i++) { participants[i]->setisWinner(false); participants[i]->setcanPlay(true); participants[i]->sethasRefusedSplit(false); participants[i]->collectPrevRoundCards(); participants[i]->sethandIdx(1); participants[i]->setnoOfHands(1); } } /* ================================================================ */ void BlackJack::play() { fsm.postEventToQueue("next"); // while there are transitions to make, run the while loop // only the "quit" state has no transitions while (!fsm.states[fsm.activeState].transitions.empty()) { fsm.processQueuedEvents(); //cin >> directive; //fsm.postEventToQueue(directive); } } /* =========================== STATE CALLBACKS =========================== */ void BlackJack::onEnterState_dealing() { fsm.cleartransitionHistory(); deck.createDeck(noOfDecks); dealCards(); printCards(true); setActivePlayer(1); setActiveHand(0); fsm.postEventToQueue("dealt"); } void BlackJack::onEnterState_split() { cout << "Player " << getIdxPlayerCanSplit() << " do you wish to split?" << endl; fsm.postEventToQueue("yes"); } void BlackJack::onEnterState_splitYes() { setActivePlayer(getIdxPlayerCanSplit()); setActiveHand(getIdxHandCanSplit()); cout << "Splitting..." << endl << endl; split(); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_splitNo() { cout << "Player " << getIdxPlayerCanSplit() << " has refused to split..." << endl; participants[getIdxPlayerCanSplit()]->sethasRefusedSplit(false); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_playerTurn() { cout << "Player " << activePlayerIdx << "'s turn..." << endl; string toDisplay = activeHandIdx != 0 ? " for hand " + to_string(activeHandIdx + 1) : ""; cout << "Player " << activePlayerIdx << toDisplay <<", do you wish to hit or stand?" << endl; directive = (getCurrentHandScore() < 17) ? "hit" : "stand"; fsm.postEventToQueue(directive); } void BlackJack::onEnterState_playerHit() { string toDisplay = ( participants[activePlayerIdx]->getnoOfHands() > 1 ? " for hand " + to_string(activeHandIdx + 1) : "" ); cout << "Player " << activePlayerIdx << " hits" << toDisplay << "!..." <<endl << endl; hit(participants[activePlayerIdx]); printCards(); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_playerStand() { string toDisplay = ( participants[activePlayerIdx]->getnoOfHands() > 1 ? " for hand " + to_string(activeHandIdx + 1) : "" ); cout << "Player " << activePlayerIdx << " stands" << toDisplay << "!..." << endl << endl; stand(participants[activePlayerIdx]); printCards(); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_handGoesBust() { int noOfHands = participants[activePlayerIdx]->getnoOfHands(); if (noOfHands > 1){ cout << "Player " << activePlayerIdx << ": Hand " << activeHandIdx + 1 << " is over 21, hand goes bust!..." << endl; } else { cout << "Hand is above 21!..." << endl; } participants[activePlayerIdx]->setisHandBust( activeHandIdx, true ); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_outOfTheGame() { cout << "Player " << activePlayerIdx << " has no hands left to play!... Player " <<activePlayerIdx << " is out of the game!..." << endl << endl; setcanPlay(false); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_dealerTurn() { cout << "Dealer's turn!" << endl; directive = (getCurrentHandScore() < 17) ? "hit" : "stand"; fsm.postEventToQueue(directive); } void BlackJack::onEnterState_dealerHit() { cout << "Dealer hits!..." << endl; hit(participants[activePlayerIdx]); printCards(); fsm.postEventToQueue("hit"); } void BlackJack::onEnterState_dealerStand() { cout << "Dealer stands!..." << endl; stand(participants[activePlayerIdx]); fsm.postEventToQueue("stand"); } void BlackJack::onEnterState_playersLose() { cout << "Players Lose!" << endl; fsm.postEventToQueue("next"); } void BlackJack::onEnterState_dealerWin() { setWinnerByIndex(0); cout << "Dealer Wins!" << endl << endl; fsm.postEventToQueue("replay"); } void BlackJack::onEnterState_dealerLose() { cout << "Dealer is above 21, bust!..." << endl; participants[0]->setisHandBust(0 ,true); setcanPlay(false); fsm.postEventToQueue("next"); } void BlackJack::onEnterState_playerWin() { string toDisplay = (playerCount == 1) ? "Player wins!" : "Players win!"; cout << toDisplay << endl; fsm.postEventToQueue("next"); } void BlackJack::onEnterState_canPlayHandsWin() { vector<Hand*> winnerHands = getnotBustHands(); for (Hand* winnerHand : winnerHands) { int handBelongsToPlayer = winnerHand->getIdxBelongsToPlayer(); setWinnerByIndex(handBelongsToPlayer); winnerHand->setisHandWinner(true); if (participants[handBelongsToPlayer]->getnoOfHands() > 1) { cout << "Player " << handBelongsToPlayer << ": Hand " << winnerHand->gethandIdx() + 1 << " beats dealer's hand!..." << endl; } else { cout << "Player " << handBelongsToPlayer << " beats the dealer!..." << endl; } } cout << endl; fsm.postEventToQueue("replay"); } void BlackJack::onEnterState_higherScoreHandsWin() { vector<Hand*> winnerHands = getHandsScoreHigherThanDealerHand(); for (Hand* winnerHand : winnerHands) { int handBelongsToPlayer = winnerHand->getIdxBelongsToPlayer(); setWinnerByIndex(handBelongsToPlayer); winnerHand->setisHandWinner(true); if (participants[handBelongsToPlayer]->getnoOfHands() > 1) { cout << "Player " << handBelongsToPlayer << ": Hand " << winnerHand->gethandIdx() + 1 << " beats dealer's hand!..." << endl; } else { cout << "Player " << handBelongsToPlayer << " beats the dealer!..." << endl; } } cout << endl; fsm.postEventToQueue("replay"); } void BlackJack::onEnterState_standOff() { cout << "Draw..." << endl << endl; vector<Hand*> drawHands = getHandsScoreEqualToDealerHand(); for (Hand* drawHand : drawHands) { int handBelongsToPlayer = drawHand->getIdxBelongsToPlayer(); if (participants[handBelongsToPlayer]->getnoOfHands() > 1) { cout << "Player " << handBelongsToPlayer << ": Hand " << drawHand->gethandIdx() + 1 << " has the same score with the dealer's hand. Draw!..." << endl; } else { cout << "Player " << handBelongsToPlayer << " has the same score with dealer! Draw!..." << endl; } } cout << endl; fsm.postEventToQueue("replay"); } void BlackJack::onEnterState_restart() { printCards(); cout << "Do you wish to play again?..." << endl << endl; collectPrevRoundCards(); deck.clearDeck(); resetAttributes(); directive = ""; fsm.postEventToQueue("yes"); }; /* ================================================================ */ /* =========================== GUARDS ============================= */ bool BlackJack::canAnyPlayerSplit() { for (size_t i = 1; i < participants.size(); i++) { // if player has not refused to split // this is to prevent asking the same // player again if (!participants[i]->gethasRefusedSplit()) { vector<Hand*> hands = participants[i]->getHands(); for (int handIdx = 0; handIdx < hands.size(); handIdx++) { if (hands[handIdx]->cards[0].rank.compare( hands[handIdx]->cards[1].rank ) == 0) { return true; } } } } return false; } bool BlackJack::canAnyPlayerPlay() { for (size_t i = 1; i < participants.size(); i++) { if (participants[i]->getcanPlay()) { return true; } } return false; } bool BlackJack::isDirectiveHit() { return directive.compare("hit") == 0; } bool BlackJack::isDirectiveStand() { return directive.compare("stand") == 0; } bool BlackJack::handsLeftToPlay() { int handCount = participants[activePlayerIdx]->getnoOfHands(); // activeHandIdx starts with 0 if (activeHandIdx < handCount - 1) { return true; } return false; } bool BlackJack::isAllHandsBust() { for (int playerIdx = 1; playerIdx < participants.size(); playerIdx++) { for (Hand* hand : participants[playerIdx]->getHands()) { if (!hand->getisHandBust()) { return false; } } } return true; } bool BlackJack::isNextPlayerDealer() { return participants[getNextPlayer()]->isDealer(); } bool BlackJack::isDealerTurn() { return participants[activePlayerIdx]->isDealer(); } bool BlackJack::isDealerBust() { return participants[0]->getHandByIdx(0)->getisHandBust(); } bool BlackJack::playerHasHigherScore() { return getHandsScoreHigherThanDealerHand().size() > 0; } bool BlackJack::dealerAndPlayersHasSameScore() { return getHandsScoreEqualToDealerHand().size() > 0; } /* ================================================================ */ void BlackJack::split() { participants[activePlayerIdx]->createHand(); Hand* hand_to_split = participants[activePlayerIdx]->getHandByIdx(activeHandIdx); Hand* hand_to_append = participants[activePlayerIdx]->getLastHand(); hand_to_append->cards.emplace_back(hand_to_split->cards.back()); hand_to_split->cards.pop_back(); participants[activePlayerIdx]->addCard(hand_to_split, &popCard()); participants[activePlayerIdx]->addCard(hand_to_append, &popCard()); participants[activePlayerIdx]->recalculateScore(hand_to_split); participants[activePlayerIdx]->recalculateScore(hand_to_append); printCards(); setActivePlayer(1); setActiveHand(0); } Card BlackJack::popCard() { Card poppedCard = deck.activeDeck.back(); deck.activeDeck.pop_back(); return poppedCard; } void BlackJack::collectPrevRoundCards() { for (size_t i = 0; i < participants.size(); i++) { participants[i]->collectPrevRoundCards(); } } void BlackJack::dealCards() { for (size_t i = 0; i < participants.size(); i++) { Hand* hand = participants[i]->getHandByIdx(0); for (int j = 0; j < m_noOfCards; j++) { participants[i]->addCard(hand, &popCard()); } } } void BlackJack::hit(Participants* participant) { Hand* hand = participant->getHandByIdx(activeHandIdx); participant->addCard(hand, &popCard()); } void BlackJack::stand(Participants* participant) { ; }
true
b6c993a8e7c35a7e5480a91853679fe31ca6c628
C++
asserty308/TeamProject2014
/Project/Source/Client/MainMenuState.h
UTF-8
681
2.515625
3
[]
no_license
#pragma once #include "Gamestate.h" #include "Game.hpp" #include "Sprite.hpp" #include <sstream> #include <iostream> #include <string> enum MenuState { SPLASH_SCREEN, PROMPTING_NAME, PROMPTING_IP, PROMPTING_PORT, PROMPTING_CL_PORT }; class MainMenuState : public Gamestate { private: std::string name, ip, port, clPort; MenuState currentState; std::stringstream stream; Sprite *backgroundSprite; public: void init(); void update(); void render(); void quit(); void inputReceived(SDL_KeyboardEvent *key); void receivePacket(char* data); void appendSDLKey(SDL_KeyboardEvent *key, std::string *str); void switchPromptUp(); void switchPromptDown(); };
true
650d7352efa2c3cba1aa46bf3cb2bee9b3330519
C++
maxenergy/graduation-design
/singlenet-tflite-class/mbase64/base64Class.cpp
UTF-8
5,471
3.03125
3
[ "Apache-2.0" ]
permissive
// // Created by axv on 2021/6/11. // #include "base64Class.h" namespace gj{ uint32_t encode_len_record=0; uint8 * base64Class::encoder(const uint8 *text, uint32_t text_len) { //计算解码后的数据长度 //由以上可知 Base64就是将3个字节的数据(24位),拆成4个6位的数据,然后前两位补零 //将其转化为0-63的数据 然后根据编码字典进行编码 int encode_length = text_len/3*4; if(text_len%3>0) { encode_length += 4; } //为编码后数据存放地址申请内存 uint8 *encode = (uint8*)malloc(encode_length); memset(encode,0,encode_length); encode_len_record=encode_length; // std::cout<<"##### encoder allocate len:"<<encode_length<<std::endl; //编码 uint32_t i, j; for (i = 0, j = 0; i+3 <= text_len; i+=3) { encode[j++] = alphabet_map[text[i]>>2]; //取出第一个字符的前6位并找出对应的结果字符 encode[j++] = alphabet_map[((text[i]<<4)&0x30)|(text[i+1]>>4)]; //将第一个字符的后2位与第二个字符的前4位进行组合并找到对应的结果字符 encode[j++] = alphabet_map[((text[i+1]<<2)&0x3c)|(text[i+2]>>6)]; //将第二个字符的后4位与第三个字符的前2位组合并找出对应的结果字符 encode[j++] = alphabet_map[text[i+2]&0x3f]; //取出第三个字符的后6位并找出结果字符 } //对于最后不够3个字节的 进行填充 if (i < text_len) { uint32_t tail = text_len - i; if (tail == 1) { encode[j++] = alphabet_map[text[i]>>2]; encode[j++] = alphabet_map[(text[i]<<4)&0x30]; encode[j++] = '='; encode[j++] = '='; } else //tail==2 { encode[j++] = alphabet_map[text[i]>>2]; encode[j++] = alphabet_map[((text[i]<<4)&0x30)|(text[i+1]>>4)]; encode[j++] = alphabet_map[(text[i+1]<<2)&0x3c]; encode[j++] = '='; } } // std::cout<<"encoder final array len:"<<j<<std::endl; return encode; } std::string base64Class::base64_encode(std::string filename) { struct stat statbuff; if(stat(filename.c_str(), &statbuff) < 0){ return ""; }else{ std::cout << "base64: file length: "<<statbuff.st_size << std::endl; } //申请一块内存 用于读取文件数据 char *filePtr = (char *)malloc(statbuff.st_size); //将文件中的数据读出来 int fd = open(filename.c_str(),O_RDONLY); char buffer[1024]; int count = 0; if(fd > 0) { memset(buffer,0,1024); int len = 0; while ((len = read(fd,buffer,1000)) >0 ) { memcpy(filePtr + count,buffer,len); count += len; } } close(fd); //对数据进行编码 unsigned char* encodeData = encoder((unsigned char*)filePtr,count); //将编码数据放到string中 方便后面求长度 std::string data = (char*) encodeData; data=data.substr(0,encode_len_record); // std::cout<<"##### str len: "<<data.length()<<std::endl; return data; } uint8 * base64Class::decoder(const uint8 *code, uint32_t code_len) { //由编码处可知,编码后的base64数据一定是4的倍数个字节 assert((code_len&0x03) == 0); //如果它的条件返回错误,则终止程序执行。4的倍数。 //为解码后的数据地址申请内存 uint8 *plain = (uint8*)malloc(code_len/4*3); //开始解码 uint32_t i, j = 0; uint8 quad[4]; for (i = 0; i < code_len; i+=4) { for (uint32_t k = 0; k < 4; k++) { quad[k] = reverse_map[code[i+k]];//分组,每组四个分别依次转换为base64表内的十进制数 } assert(quad[0]<64 && quad[1]<64); plain[j++] = (quad[0]<<2)|(quad[1]>>4); //取出第一个字符对应base64表的十进制数的前6位与第二个字符对应base64表的十进制数的前2位进行组合 if (quad[2] >= 64) break; else if (quad[3] >= 64) { plain[j++] = (quad[1]<<4)|(quad[2]>>2); //取出第二个字符对应base64表的十进制数的后4位与第三个字符对应base64表的十进制数的前4位进行组合 break; } else { plain[j++] = (quad[1]<<4)|(quad[2]>>2); plain[j++] = (quad[2]<<6)|quad[3];//取出第三个字符对应base64表的十进制数的后2位与第4个字符进行组合 } } return plain; } void base64Class::base64_decode(std::string filecode, std::string filename) { unsigned char* data=decoder((unsigned char*)filecode.c_str(),(unsigned long int)filecode.length()); int fd_w=open(filename.c_str(),O_CREAT|O_WRONLY,S_IRUSR | S_IWUSR); if(fd_w > 0) { write(fd_w,(char*)data,sizeof(unsigned char)*filecode.length()/4*3); } close(fd_w); } };
true
e798edee9eac5cf141713b0ef28339d71f27ae2a
C++
rheineke/cpp-iem
/src/iem/order.hpp
UTF-8
2,787
2.59375
3
[ "MIT" ]
permissive
// Copyright 2014 Reece Heineke<reece.heineke@gmail.com> #ifndef CPPIEM_IEM_ORDER_HPP_ #define CPPIEM_IEM_ORDER_HPP_ #include <string> #include <vector> #include "boost/pool/pool_alloc.hpp" #include "iem/contract.hpp" #include "iem/pricetimelimit.hpp" #include "iem/side.hpp" namespace iem { using RequestCode = std::string; using OrderId = uint_fast32_t; using Quantity = uint_fast8_t; // Each filled order has either another market participant or the exchange as a // counterparty. Only fixed price bundle orders are counterparty to the // exchange. enum class Counterparty { EXCHANGE, PARTICIPANT }; std::ostream& operator<<(std::ostream& os, const Counterparty& cp); // IEM order base class. There are two order classes: a single contract order // and a bundle of contracts order class Order { public: inline Side side() const noexcept { return side_; } inline Quantity quantity() const noexcept { return quantity_; } inline const PriceTimeLimit price_time_limit() const { return price_time_limit_; } inline Counterparty counterparty() const { return counterparty_; } friend std::ostream& operator<<(std::ostream& os, const Order& o); protected: Order(const Side& side, const Quantity quantity, const PriceTimeLimit& price_time_limit, const Counterparty& counterparty); private: Side side_; Quantity quantity_; PriceTimeLimit price_time_limit_; Counterparty counterparty_; virtual void print(std::ostream* const p_os) const = 0; }; std::ostream& operator<<(std::ostream& os, const Order& o); // IEM single contract order class Single final : public Order { public: Single(const Contract& contract, const Side& side, const Quantity quantity, const PriceTimeLimit& price_time_limit); inline const Contract contract() const { return contract_; } inline OrderId id() const { return id_; } inline void set_id(const OrderId id) { id_ = id; } void print(std::ostream* const p_os) const final; private: Contract contract_; OrderId id_; }; inline bool valid_id(const Single& order) { return order.id() == std::numeric_limits<OrderId>::lowest(); } // IEM bundle contract order class Bundle final : public Order { public: Bundle(const ContractBundle& contract_bundle, const Side& side, const Quantity quantity, const Counterparty& counterparty); inline const ContractBundle contract_bundle() const { return contract_bundle_; } void print(std::ostream* const p_os) const final; private: ContractBundle contract_bundle_; }; // using SingleOrders = std::vector<Single, boost::pool_allocator<Single> >; using SingleOrders = std::vector<Single>; using Orders = std::vector<std::unique_ptr<Order>>; } // namespace iem #endif // CPPIEM_IEM_ORDER_HPP_
true
69714ae6a796ce3845ce9fce7f0c18c3fba0535a
C++
samatt/codeLab
/codeLabGravityForces/src/Attractor.cpp
UTF-8
776
3
3
[]
no_license
// // Attractor.cpp // codeLabGravityForces // // Created by Surya on 23/02/13. // // #include "Attractor.h" #include "ofConstants.h" Attractor:: Attractor(){ location.set(ofGetWidth()/2,ofGetHeight()/2); mass = 50; G=0.01; } void Attractor::display(){ ofSetColor(175,200); ofCircle(location.x, location.y, mass*2); } ofVec2f Attractor::attract(Mover m){ ofVec2f force; force = location- m.location; float distance = force.length(); distance= ofClamp(distance, 2, 5); force = force.normalize(); //This gives the unit vector in the direction of force. //cout<<distance<<endl; float strength = (G*mass*m.mass)/(distance*distance); force =force*strength; cout<<force<<endl; return force; }
true
25220a8b8caeadcef66a35354fe4d66164233da0
C++
sakhnik/aoc2016
/21.cpp
UTF-8
4,595
3.390625
3
[]
no_license
#include <iostream> #include <sstream> #include <fstream> #include <cassert> #include <algorithm> #include <vector> using namespace std; void Swap(string &s, int X, int Y) { swap(s[X], s[Y]); } void Swap(string &s, char A, char B) { swap(s[s.find(A)], s[s.find(B)]); } void RoL(string &s, int X) { rotate(begin(s), begin(s) + X % s.size(), end(s)); } void RoR(string &s, int X) { int idx = ((int)s.size() - X) % (int)s.size(); if (idx < 0) idx += s.size(); rotate(begin(s), begin(s) + idx, end(s)); } void RoB(string &s, char A) { int idx = s.find(A); if (idx >= 4) ++idx; ++idx; idx = ((int)s.size() - idx) % (int)s.size(); if (idx < 0) idx += s.size(); rotate(begin(s), begin(s) + idx, end(s)); } void Reverse(string &s, int X, int Y) { reverse(begin(s) + X, begin(s) + Y + 1); } void Move(string &s, int X, int Y) { char c = s[X]; s.erase(s.begin() + X); if (Y >= (int)s.size()) s.push_back(c); else s.insert(begin(s) + Y, c); } string Scramble(istream &&is, string s) { string line; while (getline(is, line)) { int X{}, Y{}; char A{}, B{}; if (2 == sscanf(line.c_str(), "swap position %d with position %d", &X, &Y)) Swap(s, X, Y); else if (2 == sscanf(line.c_str(), "swap letter %c with letter %c", &A, &B)) Swap(s, A, B); else if (1 == sscanf(line.c_str(), "rotate left %d steps", &X)) RoL(s, X); else if (1 == sscanf(line.c_str(), "rotate right %d steps", &X)) RoR(s, X); else if (1 == sscanf(line.c_str(), "rotate based on position of letter %c", &A)) RoB(s, A); else if (2 == sscanf(line.c_str(), "reverse positions %d through %d", &X, &Y)) Reverse(s, X, Y); else if (2 == sscanf(line.c_str(), "move position %d to position %d", &X, &Y)) Move(s, X, Y); } return s; } string Unscramble(istream &&is, string s) { vector<string> lines; string line; while (getline(is, line)) { lines.push_back(line); } for (; !lines.empty(); lines.pop_back()) { const auto &line = lines.back(); int X{}, Y{}; char A{}, B{}; if (2 == sscanf(line.c_str(), "swap position %d with position %d", &X, &Y)) Swap(s, X, Y); else if (2 == sscanf(line.c_str(), "swap letter %c with letter %c", &A, &B)) Swap(s, A, B); else if (1 == sscanf(line.c_str(), "rotate right %d steps", &X)) RoL(s, X); else if (1 == sscanf(line.c_str(), "rotate left %d steps", &X)) RoR(s, X); else if (1 == sscanf(line.c_str(), "rotate based on position of letter %c", &A)) { // Brute force initial position for (int i = 0, n = s.size(); i != n; ++i) { string s1(s); RoL(s1, i); RoB(s1, A); if (s1 == s) { RoL(s, i); break; } } } else if (2 == sscanf(line.c_str(), "reverse positions %d through %d", &X, &Y)) Reverse(s, X, Y); else if (2 == sscanf(line.c_str(), "move position %d to position %d", &Y, &X)) Move(s, X, Y); } return s; } int main() { assert("ebcda" == Scramble(istringstream("swap position 4 with position 0"), "abcde")); assert("edcba" == Scramble(istringstream("swap letter d with letter b"), "ebcda")); assert("dabc" == Scramble(istringstream("rotate right 1 steps"), "abcd")); assert("bcdea" == Scramble(istringstream("rotate left 1 steps"), "abcde")); assert("ecabd" == Scramble(istringstream("rotate based on position of letter b"), "abdec")); assert("decab" == Scramble(istringstream("rotate based on position of letter d"), "ecabd")); assert("abcde" == Scramble(istringstream("reverse positions 0 through 4"), "edcba")); assert("bdeac" == Scramble(istringstream("move position 1 to position 4"), "bcdea")); assert("abdec" == Scramble(istringstream("move position 3 to position 0"), "bdeac")); cout << Scramble(ifstream("21.txt"), "abcdefgh") << endl; assert("abcde" == Unscramble(istringstream("swap position 4 with position 0"), "ebcda")); assert("ebcda" == Unscramble(istringstream("swap letter d with letter b"), "edcba")); assert("abcd" == Unscramble(istringstream("rotate right 1 steps"), "dabc")); assert("abcde" == Unscramble(istringstream("rotate left 1 steps"), "bcdea")); assert("abdec" == Unscramble(istringstream("rotate based on position of letter b"), "ecabd")); assert("ecabd" == Unscramble(istringstream("rotate based on position of letter d"), "decab")); assert("edcba" == Unscramble(istringstream("reverse positions 0 through 4"), "abcde")); assert("bcdea" == Unscramble(istringstream("move position 1 to position 4"), "bdeac")); assert("bdeac" == Unscramble(istringstream("move position 3 to position 0"), "abdec")); cout << Unscramble(ifstream("21.txt"), "fbgdceah") << endl; return 0; }
true
1eabd1dd7ca845e6d69798e4b2b5181b587bf8ad
C++
vserret/cppLyA
/src/histo2d.cc
UTF-8
1,316
3.09375
3
[]
no_license
#include <iostream> #include "histo2d.h" #include <math.h> /* for floor */ #include <string.h> /* for memset*/ using namespace std; Histo2d::Histo2d(int nnx, const double& mminx, const double& mmaxx, int nny, const double& mminy, const double& mmaxy) { nx = nnx; ny = nny; minx = mminx; miny = mminy; if (mmaxx!= mminx) scalex = nx/(mmaxx-mminx); else { cerr << " Histo2d: minx = maxx requested" << endl; scalex = 1.0; } if (mmaxy != mminy) scaley = ny/(mmaxy-mminy); else { cerr << " Histo2d : maxy = miny requested" << endl; scaley = 1.0; } data = new double[nx*ny]; memset(data, 0, nx*ny*sizeof(double)); } Histo2d::Histo2d(const Histo2d &Other) { memcpy(this, &Other, sizeof(Histo2d)); data = new double[nx*ny]; memcpy(this->data, Other.data, nx*ny*sizeof(double)); } bool Histo2d::indices(const double &X, const double &Y, int &ix, int &iy) const { ix = (int) floor(( X - minx)*scalex); if (ix <0 || ix >= nx) return false; iy = (int) floor((Y - miny)*scaley); return (iy >=0 && iy < ny); } double Histo2d::BinContent(const double &X, const double &Y) const { int ix, iy; if (indices(X,Y,ix,iy)) return data[iy + ny*ix]; std::cout << " Histo2D::BinContent outside limits requested " << std::endl; return -1e30; }
true
cfa9a3732fd3b05fad648ec2c6d5f71cbb1cac53
C++
MNL82/oakmodelview
/Lib/OakXML/XMLServiceFunctions.h
UTF-8
1,295
2.578125
3
[ "MIT" ]
permissive
/** * oakmodelview - version 0.1.0 * -------------------------------------------------------- * Copyright (C) 2017, by Mikkel Nøhr Løvgreen (mikkel@oakmodelview.com) * Report bugs and download new versions at http://oakmodelview.com/ * * This library is distributed under the MIT License. * See accompanying file LICENSE in the root folder. */ #pragma once #include <list> #include <string> #include <vector> #include <memory> #include <limits> namespace Oak::XML { // ============================================================================= // Conversion service functions // ============================================================================= std::vector<std::string> split(const std::string &str, char seperator = ';', bool ignoreEmpty = false); std::vector<std::vector<std::string>> doubleSplit(const std::string &str, char outerSeperator = ';', char innerSeperator = ':', bool ignoreEmpty = false); int toInteger(const std::string &str, bool *ok = nullptr); template<typename TO, typename FROM> std::unique_ptr<TO> dynamic_unique_pointer_cast(std::unique_ptr<FROM>&& old) { TO* ptr = dynamic_cast<TO*>(old.get()); if (ptr) { old.release(); return std::unique_ptr<TO>(ptr); } assert(false); return std::unique_ptr<TO>(nullptr); } } // namespace Oak::XML
true
0bf959f20483f96f0e38bf54cd28d3dcbc83ef78
C++
KnewHow/TinyPathTracing
/src/main.cpp
UTF-8
2,762
2.609375
3
[]
no_license
#include <iostream> #include <thread> #include <chrono> #include "Vector.hpp" #include "common/Tools.hpp" #include "material/Material.hpp" #include "geometry/Sphere.hpp" #include "geometry/Triangle.hpp" #include "geometry/MeshTriangle.hpp" #include "Scene.hpp" #include "Renderer.hpp" int main() { int width = 784; int height = 784; Scene scene(width, height); std::shared_ptr<Material> red = std::make_shared<Material>(MaterialType::DIFFUSE, tinyMath::vec3f(0.0f, 0.0f,0.0f)); red->setKd(tinyMath::vec3f(0.63f, 0.065f, 0.05f)); std::shared_ptr<Material> green = std::make_shared<Material>(MaterialType::DIFFUSE, tinyMath::vec3f(0.0f, 0.0f,0.0f)); green->setKd(tinyMath::vec3f(0.14f, 0.45f, 0.091f)); std::shared_ptr<Material> white = std::make_shared<Material>(MaterialType::DIFFUSE, tinyMath::vec3f(0.0f, 0.0f,0.0f)); white->setKd(tinyMath::vec3f(0.725f, 0.71f, 0.68f)); std::shared_ptr<Material> light = std::make_shared<Material>(MaterialType::DIFFUSE, (8.0f * tinyMath::vec3f(0.747f+0.058f, 0.747f+0.258f, 0.747f) + 15.6f * tinyMath::vec3f(0.740f+0.287f,0.740f+0.160f,0.740f) + 18.4f *tinyMath::vec3f(0.737f+0.642f,0.737f+0.159f,0.737f))); light->setKd(tinyMath::vec3f(0.65f, 0.65f, 0.65f)); std::shared_ptr<MeshTriangle> floor = std::make_shared<MeshTriangle>("../models/cornellbox/floor.obj", white, "floor"); std::shared_ptr<MeshTriangle> shortbox = std::make_shared<MeshTriangle>("../models/cornellbox/shortbox.obj", white); std::shared_ptr<MeshTriangle> tallbox = std::make_shared<MeshTriangle>("../models/cornellbox/tallbox.obj", white); std::shared_ptr<MeshTriangle> left = std::make_shared<MeshTriangle>("../models/cornellbox/left.obj", red, "left"); std::shared_ptr<MeshTriangle> right = std::make_shared<MeshTriangle>("../models/cornellbox/right.obj", green, "right"); std::shared_ptr<MeshTriangle> lightMesh = std::make_shared<MeshTriangle>("../models/cornellbox/light.obj", light, "light"); scene.addObject(floor); scene.addObject(shortbox); scene.addObject(tallbox); scene.addObject(left); scene.addObject(right); scene.addObject(lightMesh); scene.buildBVH(); Renderer renderer; auto start = std::chrono::system_clock::now(); renderer.render(scene); auto stop = std::chrono::system_clock::now(); std::cout << "Render complete: \n"; std::cout << "Time taken: " << std::chrono::duration_cast<std::chrono::hours>(stop - start).count() << " hours\n"; std::cout << " : " << std::chrono::duration_cast<std::chrono::minutes>(stop - start).count() << " minutes\n"; std::cout << " : " << std::chrono::duration_cast<std::chrono::seconds>(stop - start).count() << " seconds\n"; return 0; }
true
1dac9b7100398c325b2ef38320b8f98444ac344d
C++
linouk23/leetcode
/278.cpp
UTF-8
613
3.03125
3
[]
no_license
// 278. First Bad Version - https://leetcode.com/problems/first-bad-version #include <bits/stdc++.h> using namespace std; // Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { long long L = 1LL - 1; long long R = 1LL * n + 1; while(R - L > 1) { long long M = L + (R - L) / 2; if (isBadVersion(M)) { R = M; } else { L = M; } } return R; } }; int main() { ios::sync_with_stdio(false); return 0; }
true
2666411bc5a8cfe307a78f777166e014c4178ea0
C++
utkd/lightcrawl
/src/utils.cpp
UTF-8
1,178
3.3125
3
[]
no_license
/* LightCrawl 1.0 Simple crawler to casually fetch web pages for text processing Author: Utkarsh Desai utils.cpp */ #include "utils.h" /* Function: getLinesFromFile Reads lines from a file and stores them in a vector Arguments: inputFile - An ifstream object corresponding to the input file (reference) lines - A vector of string type to store the individual lines (reference) Returns: The input ifstream object */ std::ifstream& getLinesFromFile(std::ifstream& inputFile, std::vector<std::string>& lines) { if(inputFile.is_open()) { lines.clear(); std::string singleLine; //Read in lines and insert in vector while(!inputFile.eof()) { getline(inputFile, singleLine); if(!singleLine.empty()) lines.push_back(singleLine); } inputFile.clear(); } return inputFile; } /* Function printToLog Prints messages to a log file Arguments: outputFile- An ofstream object corresponding to the log file (reference) message- A string message to be output Returns: The input ofstream object TODO: implement the function */ std::ofstream& printToLog(std::ofstream& outputFile, std::string message) { return outputFile; }
true
cdeff06a10f41f2f46bb6f31ec45969d957f4408
C++
ucbrise/confluo
/libconfluo/src/archival/io/incremental_file_writer.cc
UTF-8
2,989
2.78125
3
[ "Apache-2.0" ]
permissive
#include "archival/io/incremental_file_writer.h" namespace confluo { namespace archival { incremental_file_writer::incremental_file_writer(const std::string &path, const std::string &file_prefix, size_t max_file_size) : incremental_file_stream(path, file_prefix) { max_file_size_ = max_file_size; init(); } incremental_file_writer::incremental_file_writer(const incremental_file_writer &other) : incremental_file_stream() { close(); file_num_ = other.file_num_; dir_path_ = other.dir_path_; file_prefix_ = other.file_prefix_; max_file_size_ = other.max_file_size_; cur_ofs_ = open_new(cur_path()); transaction_log_ofs_ = open_new(transaction_log_path()); } incremental_file_writer::~incremental_file_writer() { close(); } incremental_file_writer &incremental_file_writer::operator=(const incremental_file_writer &other) { close(); file_num_ = other.file_num_; dir_path_ = other.dir_path_; file_prefix_ = other.file_prefix_; max_file_size_ = other.max_file_size_; cur_ofs_ = open_new(cur_path()); transaction_log_ofs_ = open_new(transaction_log_path()); return *this; } void incremental_file_writer::init() { if (file_utils::exists_file(transaction_log_path())) { std::ifstream transaction_log_ifs(transaction_log_path()); while (file_utils::exists_file(cur_path())) { file_num_++; } file_num_--; open(); } else { cur_ofs_ = open_new(cur_path()); transaction_log_ofs_ = open_new(transaction_log_path()); } } incremental_file_offset incremental_file_writer::tell() { return incremental_file_offset(cur_path(), static_cast<size_t>(cur_ofs_->tellp())); } void incremental_file_writer::flush() { cur_ofs_->flush(); transaction_log_ofs_->flush(); } void incremental_file_writer::open() { cur_ofs_ = open_existing(cur_path()); transaction_log_ofs_ = open_existing(transaction_log_path()); } void incremental_file_writer::close() { if (cur_ofs_) { close(cur_ofs_); } if (transaction_log_ofs_) close(transaction_log_ofs_); } bool incremental_file_writer::fits_in_cur_file(size_t append_size) { size_t off = static_cast<size_t>(cur_ofs_->tellp()); return off + append_size < max_file_size_; } incremental_file_offset incremental_file_writer::open_new_next() { close(cur_ofs_); file_num_++; cur_ofs_ = open_new(cur_path()); return tell(); } std::ofstream *incremental_file_writer::open_new(const std::string &path) { return new std::ofstream(path, std::ios::out | std::ios::trunc); } std::ofstream *incremental_file_writer::open_existing(const std::string &path) { // std::ios::in required to prevent truncation, caused by lack of std::ios::app return new std::ofstream(path, std::ios::in | std::ios::out | std::ios::ate); } void incremental_file_writer::close(std::ofstream *&ofs) { if (ofs->is_open()) ofs->close(); delete ofs; ofs = nullptr; } } }
true
1eaf687017601fe8521acce0aa7e6d6f40c4f5c6
C++
k0204/loli_profiler
/include/timeprofiler.h
UTF-8
606
2.75
3
[ "BSD-3-Clause", "CC-BY-4.0", "MIT", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef TIMEPROFILER_H #define TIMEPROFILER_H #include <chrono> #include <vector> #include <QDebug> #include <QString> using sclock = std::chrono::steady_clock; struct TimerProfiler{ TimerProfiler(const QString &msg) : msg_(msg) { startTime_ = sclock::now(); } ~TimerProfiler() { auto ms = std::chrono::duration<double, std::milli>(sclock::now() - startTime_); qDebug() << msg_ << " " << QString::number(ms.count()) << " ms" << Qt::endl; } private: std::chrono::time_point<std::chrono::steady_clock> startTime_; QString msg_; }; #endif // TIMEPROFILER_H
true
0844d0ef1938ad65953af407e9aff6f897eb5a35
C++
NishantRaj/program_files
/tsta.cpp
UTF-8
912
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long #define pii pair < int , int > #define pb push_back #define mp make_pair #define MOD 1000000007 #define ULL unsigned long long int ways(int N){ int total_ways = 0; if (N == 1) return 1; for (int i = 1 ; i<= N ; i++){ if (i == 1 or i == N){ total_ways = total_ways + ways(N - 1); total_ways = total_ways + 2; } else{ total_ways = total_ways + ways(i - 1); total_ways = total_ways + ways(N - i); total_ways = total_ways + 1; } } return total_ways; } ULL pow_mod(ULL n , ULL b){ ULL a = 1 , p = n; while(b){ if(b&1) a = (a*p)%MOD; p = (p * p)%MOD; b>>=1; } return a; } int main(){ int n; cin>>n; cout<<ways(n) - pow_mod(2 , n-1)<<endl; return 0; }
true
7c44686b56de21a0bfa50daf84749289c4129fb4
C++
yanmendes/bigdawg
/src/main/cmigrator/src/data-formatter/csv/csv.h
UTF-8
632
2.734375
3
[ "BSD-3-Clause" ]
permissive
#ifndef CSV_H #define CSV_H #include <string> #include "../format/format.h" #include "../common/formatterExceptions.h" class Csv: public Format { public: const static char defaultDelimiter; ~Csv() { } /** * Initialize the Csv formatter. * * @mode read or write (mode how to open the file) * @fileName the name of the file * @fileMode "r" read, "w" write */ Csv(const std::string & fileName, const char * fileMode); Csv(); virtual void setTypeAttributeMap(); virtual bool isTheEnd() { throw DataMigratorNotImplementedException( "The reading from csv source not implemented!"); } }; #endif // CSV_H
true
c687f8c6952231e89e57cdaf4996122ff1354033
C++
PeyWn/TDTS07
/lab1/main.cc
UTF-8
1,515
2.515625
3
[]
no_license
#include <systemc.h> #include "generator.h" #include "controller.h" #include "sensor.h" int sc_main(int argc, char **argv) { /* sc_set_default_time_unit(1, SC_SEC); sc_set_time_resolution(1, SC_MS); */ assert(argc == 7); sc_time sim_time(atof(argv[1]), SC_SEC); char *northfile = argv[2]; char *southfile = argv[3]; char *westfile = argv[4]; char *eastfile = argv[5]; char *outfile = argv[6]; // N<orth>G<enerator>_Sig<nal> sc_signal<bool> NG_sig, SG_sig, EG_sig, WG_sig; // N<orth>T<raffic>L<light>_Sig<nal> sc_signal<bool> NTL_sig, STL_sig, ETL_sig, WTL_sig; // N<orth>S<ensor>_Sig<nal> sc_signal<bool> NS_sig, SS_sig, ES_sig, WS_sig; Generator gen_north("North_traffic_generator", northfile); gen_north(NG_sig); Generator gen_south("South_traffic_generator", southfile); gen_south(SG_sig); Generator gen_west("West__traffic_generator", westfile); gen_west(WG_sig); Generator gen_east("East__traffic_generator", eastfile); gen_east(EG_sig); Sensor sensor_north("North_traffic_Sensor"); sensor_north(NG_sig, NTL_sig, NS_sig); Sensor sensor_south("South_traffic_Sensor"); sensor_south(SG_sig, STL_sig, SS_sig); Sensor sensor_west("West__traffic_Sensor"); sensor_west(WG_sig, WTL_sig, WS_sig); Sensor sensor_east("East__traffic_Sensor"); sensor_east(EG_sig, ETL_sig, ES_sig); Controller traffic_light("Traffic_light"); traffic_light(NS_sig, SS_sig, ES_sig, WS_sig, NTL_sig, STL_sig, ETL_sig, WTL_sig); sc_start(sim_time); return 0; }
true