3
//Overflow Int: (2) or 4 bytes long int 4Bytes short int 2Bytes float 4Bytes double 8Bytes unsigned(short) int limit = UINT_MAX=2^16-1 General -- Cannot start with a digit or underscore -- (0 <= num <= 100) It is always true. Robot Robot (int x, int y, Direction = east); void Move (int distance = 1); bool Blocked (); void TurnRight (); void SetColor (Color color); void ShowMessage() void GetInput(,) String s.substr(int pos, int length) string s = "hello"; int len = s.length(); string substr(int pos, int len) s.find("he"); s.rfind("he"); s.find("he", 5); s.rfind("he", 15); s.find(string x), s.rfind(x)returns int; if not found, returns string::npos s.insert(5, str, 8, 4); where to insert, added str, to add str’s substr s.replace (1, 3, str, 1, 2) s.at(4) = '!'; // s is now "Hell! World" #include ”strutils.h” void ToLower(string & s); void ToUpper(string & s); void StripPunc(string & s); void StripWhite(string & s); string LowerString(const string & s); string UpperString(const string & s); int atoi(const string & s); // returns int equivalent double atof(const string & s); // returns double equivalent string itoa(int n); // returns string equivalent string tostring(int n); // like itoa, convert int to string string tostring(double d); // convert double to string # include <cmath> sqrt(double x) fabs(double x) //pozitif yapan function pow(double x, double y) sin(double x) x in radians asin(double x) arcsin atan2(double x, y) arctan(x/y) floor(double x) largest int <= x ceil(double x) smallest int >= x //do-while Do { cout << "enter number in range [0..100]"; cin >> num;} while (num < 0 || num > 100 ); //while-for k = low; while (k <= high) {if (IsPrime(k)) {cout << k << endl; numPrimes += 1;} k += 1;} for (k = low; k <= high; k += 1) {if (IsPrime(k)) {cout << k << endl; numPrimes += 1;}} ------------------------------------------ //SWTICH int num; cin >> num; switch (num) {case 1: cout << "between" << endl; break; default: cout << "not between" << endl;} ------------------------------------------ A B || && TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE TRUE FALSE ------------------------------------------ mutuator=> it updates a private data member accessor=> does not updates a data member constructor: a special member func create object of a class --------------------------------------------- //ROBOT void Robot::Teleport(int x,int y,Direction d) { ShortDelay(this); bool kill_it=false; Robot *p = next; while (p != this) //check all robots { if (p->xPos == x && p->yPos == y) //if one is found in x,y { p->stalled=true; //kill it theRobotWindow->Redraw(p); kill_it=true; } p = p->next; } if (kill_it) //if a robot was found in x,y { stalled = true; //kill the object robot theRobotWindow->Redraw(this); } else //otherwise beam it up Scotty! { visible = false; theRobotWindow->Invalid(this); xPos = x; yPos = y; direction = d; visible = true; theRobotWindow->Redraw(this); } } ------------------------------------------ void Robot::TurnFace (Direction dir) { direction = dir; theRobotWindow->Redraw(this);} ------------------------------------------ void Robot::PickAll () { while (GetCellCount(xPos,yPos)!=0) { theRobotWorld->DecrCount(xPos, yPos); bag+ +;} theRobotWorld->dirty = false; theRobotWindow->Redraw(this);} ------------------------------------------ bool Robot::IsItAlive () { return stalled;} ------------------------------------------ void Robot::Resurrect () { stalled=false;} ------------------------------------------ int Robot::BagCount () { return bag; } ------------------------------------------ int Robot::GetXCoordinate () { return xPos;} ------------------------------------------ bool Robot::IsVisible () {return visible;} ------------------------------------------- void Robot::KillIt () {stalled=true;} ------------------------------------------- void RandomMove(Robot &r, int step) {int dirRand = 0; RandGen rand; for (int i=0; i < step; i++) {do {dirRand = rand.RandInt(0, 3); if (dirRand==0) r.Turn(east); else if (dirRand == 1) r.Turn(south); else if (dirRand == 2) r.Turn(west); else if (dirRand == 3) r.Turn(north);} while(r.FacingWall()); r.Move();}} ------------------------------------------- int Robot::PickThings(int count) { int picked = 0; while (!CellEmpty() && picked < count) { PickThing(); picked++; } return picked;} ----------------------------------------- CLASS DICE { public: Dice(int sides); // constructor int Roll(); // return the random roll int NumSides() const; // return number of sides this die has int NumRolls() const; // return number of times this die rolled void ResetRollCount(); private: int myRollCount; // number of times die rolled int mySides; // number of sides on die }; CLASS DATE int DaysIn()--- return number of days in month long Absolute() --- returns absolute # of date assuming that Jan 1, 1 AD is day 1. Has property that Absolute() % 7 = k, where k = 0 is Sunday, k = 1 is monday, ... k = 6 is saturday string ToString() -- returns string version of date, e.g., d.SetDate (11,23,1963); then d.ToString() returns string "November 23 1963" int Month() const; // return month corresponding to date int Day() const; // return day corresponding to date int Year() const; // return year corresponding to date int DaysIn() const; // return # of days in month string DayName() const; // "monday", "tuesday", ... or "sunday" string MonthName() const; // "january","february",... or "december" long Absolute() const; // number of days since 1 A.D. for date string ToString() const; // returns string for date in ascii int DaysRemaining() const; // return # of remaining days in month ------------------------------------------- //DICE ÖRNEĞİ #include <iostream> #include "dice.h" using namespace std; int main() { Dice zar(6); Dice para(2); cout << zar.Roll() << endl; cout << para.Roll() << endl; if (zar.Roll() == 3) { cout << zar.Roll() << endl; } else { cout << para.Roll() << endl; } return 0; } ------------------------------------------ //SEQUENCE INTEGER #include <iostream> using namespace std; int main() {int numPre, numCur; bool ordered = true;

cs Cheat Sheet 2

Embed Size (px)

Citation preview

Page 1: cs Cheat Sheet 2

//OverflowInt: (2) or 4 bytes long int 4Bytes short int 2Bytesfloat 4Bytesdouble 8Bytesunsigned(short) int limit = UINT_MAX=2^16-1General-- Cannot start with a digit or underscore-- (0 <= num <= 100) It is always true. RobotRobot (int x, int y, Direction = east);void Move (int distance = 1);bool Blocked ();void TurnRight ();void SetColor (Color color);void ShowMessage()void GetInput(,)

Strings.substr(int pos, int length)string s = "hello";int len = s.length();string substr(int pos, int len)s.find("he");s.rfind("he");s.find("he", 5);s.rfind("he", 15);s.find(string x), s.rfind(x)returns int; if not found, returns string::nposs.insert(5, str, 8, 4); where to insert, added str, to add str’s substrs.replace (1, 3, str, 1, 2)s.at(4) = '!'; // s is now "Hell! World"

#include ”strutils.h”void ToLower(string & s);void ToUpper(string & s);void StripPunc(string & s);void StripWhite(string & s);string LowerString(const string & s);string UpperString(const string & s);int atoi(const string & s); // returns int equivalentdouble atof(const string & s); // returns double equivalentstring itoa(int n); // returns string equivalentstring tostring(int n); // like itoa, convert int to stringstring tostring(double d); // convert double to string

# include <cmath>sqrt(double x)fabs(double x) //pozitif yapan functionpow(double x, double y)sin(double x) x in radiansasin(double x) arcsinatan2(double x, y) arctan(x/y)floor(double x) largest int <= xceil(double x) smallest int >= x

//do-whileDo{ cout << "enter number in range [0..100]"; cin >> num;} while (num < 0 || num > 100 );

//while-fork = low;while (k <= high){if (IsPrime(k)) {cout << k << endl; numPrimes += 1;} k += 1;}

for (k = low; k <= high; k += 1){if (IsPrime(k)){cout << k << endl; numPrimes += 1;}} ------------------------------------------//SWTICHint num; cin >> num; switch (num) {case 1: cout << "between" << endl; break; default: cout << "not between" << endl;}------------------------------------------A B || &&TRUE TRUE TRUE TRUEFALSE FALSE FALSE FALSETRUE FALSE TRUE FALSEFALSE TRUE TRUE FALSE------------------------------------------

mutuator=> it updates a private data memberaccessor=> does not updates a data member constructor:a special member func create object of a class---------------------------------------------

//ROBOTvoid Robot::Teleport(int x,int y,Direction d){ ShortDelay(this); bool kill_it=false; Robot *p = next; while (p != this) //check all robots{ if (p->xPos == x && p->yPos == y) //if one is found in x,y{ p->stalled=true; //kill ittheRobotWindow->Redraw(p);kill_it=true; }p = p->next; } if (kill_it) //if a robot was found in x,y{ stalled = true; //kill the object robot theRobotWindow->Redraw(this); } else //otherwise beam it up Scotty!{ visible = false; theRobotWindow->Invalid(this); xPos = x; yPos = y; direction = d; visible = true; theRobotWindow->Redraw(this); } }------------------------------------------void Robot::TurnFace (Direction dir){ direction = dir; theRobotWindow->Redraw(this);}------------------------------------------void Robot::PickAll (){ while (GetCellCount(xPos,yPos)!=0){ theRobotWorld->DecrCount(xPos, yPos); bag++;}

theRobotWorld->dirty = false;theRobotWindow->Redraw(this);}

------------------------------------------bool Robot::IsItAlive (){ return stalled;}------------------------------------------void Robot::Resurrect (){ stalled=false;}------------------------------------------int Robot::BagCount (){ return bag; }------------------------------------------int Robot::GetXCoordinate (){ return xPos;}------------------------------------------bool Robot::IsVisible (){return visible;}-------------------------------------------void Robot::KillIt (){stalled=true;}-------------------------------------------void RandomMove(Robot &r, int step){int dirRand = 0;RandGen rand;for (int i=0; i < step; i++){do{dirRand = rand.RandInt(0, 3);if (dirRand==0)r.Turn(east);else if (dirRand == 1)r.Turn(south);else if (dirRand == 2)r.Turn(west);else if (dirRand == 3)r.Turn(north);} while(r.FacingWall());r.Move();}}-------------------------------------------int Robot::PickThings(int count) { int picked = 0; while (!CellEmpty() && picked < count) { PickThing(); picked++; }return picked;}-----------------------------------------CLASS DICE { public: Dice(int sides); // constructor int Roll(); // return the random roll int NumSides() const; // return number of sides this die has int NumRolls() const; // return number of times this die rolled void ResetRollCount(); private: int myRollCount; // number of times die rolled

int mySides; // number of sides on die };

CLASS DATEint DaysIn()--- return number of days in monthlong Absolute() --- returns absolute # of date assuming that Jan 1, 1 AD is day 1. Has property that Absolute() % 7 = k, where k = 0 is Sunday, k = 1 is monday, ... k = 6 is saturdaystring ToString() -- returns string version of date, e.g., d.SetDate (11,23,1963); then d.ToString()returns string "November 23 1963"int Month() const; // return month corresponding to dateint Day() const; // return day corresponding to dateint Year() const; // return year corresponding to dateint DaysIn() const; // return # of days in monthstring DayName() const; // "monday", "tuesday", ... or "sunday"string MonthName() const; // "january","february",... or "december"long Absolute() const; // number of days since 1 A.D. for datestring ToString() const; // returns string for date in asciiint DaysRemaining() const; // return # of remaining days in month-------------------------------------------//DICE ÖRNEĞİ#include <iostream> #include "dice.h" using namespace std; int main() { Dice zar(6); Dice para(2); cout << zar.Roll() << endl; cout << para.Roll() << endl; if (zar.Roll() == 3) { cout << zar.Roll() << endl; } else { cout << para.Roll() << endl; } return 0; }------------------------------------------//SEQUENCE INTEGER#include <iostream>using namespace std;int main() {int numPre, numCur; bool ordered = true; cout << "Enter the sequence of integers:"; cin >> numPre;

if (numPre == -1){cout << "List not started" << endl;} else{cin >> numCur; while (numCur != -1 && ordered)

{if (numCur < numPre){ordered = false;} else{numPre = numCur; cin >> numCur;} }

if (ordered){cout << "Ordered List" << endl;}else{cout << "Not an ordered List" << endl;} }return 0;}-----------------------------------------//string-integer-yerdeğiştirmestring f1(string mystr, int myint){string result = mystr; int strLen= mystr.length(); int pos; if (myint < strLen){pos = strLen - myint; result = mystr.substr(pos, myint) + mystr.substr(0, pos);}return result;}string f2(string mystr, int myint){string result = mystr; int ctr = 0; int strLen = mystr.length(); if (myint < strLen)

{result = ""; while (ctr < myint){ctr++;result = mystr.substr(strLen-ctr, 1) + result;}for (ctr=0; ctr < strLen-myint; ctr++){result = result + mystr.substr(ctr, 1);}}return result;}

Page 2: cs Cheat Sheet 2

string changeWord(string s1, string s2, string s3){unsigned int index=0, length, s2_len, s3_len;length = s1.length();s2_len = s2.length();s3_len = s3.length();

while (index < length){index = s1.find(s2, index); if (index != string::npos){s1 = s1.substr(0,index) + s3 +s1.substr(index + s2_len, length);

index += s3_len;length = s1.length();}}return s1;}------------------------------------------//MOVE DIAGONAL#include <string>#include "Robots.h"using namespace std;void TurnLeft(Robot &r){r.TurnRight(); r.TurnRight(); r.TurnRight();}

void MoveDiagonal(Robot &r){ TurnLeft(r); r.Move(); r.TurnRight(); r.Move();}

int main(){ Robot r1(0, 0, east, 0); r1.SetColor(red); Robot r2(0, 1, east, 0); r2.SetColor(yellow); int step = 0; while (step < 10){ MoveDiagonal(r2); MoveDiagonal(r1); step++;}return 0;}------------------------------------------//FenerBahçe-Galatasaray-stringstring func(string s, char c) { string result = ""; for (int i=0; i < s.size(); i++) { if (s.at(i) != c) { result += s.substr(i, 1); } } return result; } -------------------------------------------//Palindrome-kabak,tARak,kırMIZI#include <iostream> #include <string> #include "strutils.h" using namespace std; string ReverseString(string str) {string rev; int length = str.length(); for (int i=length-1; i >= 0 ; i--) {rev = rev + str.at(i); } return rev; }

bool IsPalindrome(string word) {return ( word == ReverseString(word) );}

int main() {string upper, input; cout << "Please enter your word: "; cin >> input; upper = UpperString(input); while (upper != "END") { if (IsPalindrome(upper)) {cout<<"The word '"<<upper<<"' is a palindrome"<<endl;} else {cout << "Palindrome of '" << upper << "' is: " << upper << ReverseString(upper) << endl;} cout << "Please enter a new word: "; cin >> input; upper = UpperString(input); } cout << "Exiting..." << endl; return 0; }------------------------------------------//Robot-things#include "Robots.h" using namespace std; void sideMove(Robot & robot, int length) { robot.TurnRight(); for (int i=0; i < length; i++) { robot.PutThing(); robot.Move(); } }

void moveRobot(Robot & robot, int x, int y) { for (int i=0; i < 4; i++) { if (i%2 == 0) sideMove(robot, y);

else sideMove(robot, x); } robot.Move(); }

int main()

{int xpos, ypos; GetInput("Please Enter X position of the robot", xpos);

GetInput("Please Enter Y position of the robot", ypos); if (xpos > 0 && ypos > 0) { Robot rob(xpos, ypos, east, 2*(xpos+ypos)); moveRobot(rob, xpos, ypos); } else { ShowMessage("Not a Valid Coordinate! Exiting..."); } return 0;}-----------------------------------------//DATE ÖRNEĞİ#include <iostream>#include <string>#include "date.h"using namespace std;int main(){ int month=4,day=23, year=1900; //any year value would work bool check=true; while(check){ Date date1(month,day,year);if(date1.DayName()!="Sunday"){year++; }elsecheck=false;}month=10;day=29;Date date2(month,day,year);cout << date2.DayName()<<endl;return 0;}----------------------------------------“koysalar onume bariyer de” and “cocuk da yaparim kariyer de”, then the function should return 9 due to “ariyer de” part of both strings. int min (int a, int b){if (a < b) return a; else return b;}int rhymecounter (string s1, string s2){int count=0, i; int s1Length = s1.length(); int s2Length = s2.length(); int upTo = min(s1Length, s2Length); for (i=1; i<=upTo && s1.at(s1Length - i) == s2.at(s2Length - i);i++) {count++;}return count;}------------------------------------------------void Dice::ResetRollCount(){myRollCount=0;}------------------------------------------------int Dice::MultipleRoll (int n) {int i, sum=0;for (i=1; i<=n; i++){sum = sum + Roll();}return sum;}------------------------------------------------//return the number of digits in numberint Mystery(int number){ int count = 0; while (number > 0){ number /= 10; count++;}return(count);}------------------------------------------------//DATE ÖRNEĞİint calcHolidays (int year) {int month, day;int count = 0;for (month = 1; month <= 12; month++){Date tarih (month, 1, year);int x = tarih.DaysIn() ;for (day = 1; day <= x; day++){if ( tarih.DayName() == "Saturday" ||tarih.DayName() == "Sunday" ||(day==28 && month==8) ||(day==23 && month==5) ){count++;}tarih++;}}

return count;}

Member function implementation

void Robot::MoveDiagonal(Direction dir1,Direction dir2){if (stalled) return;if ( (dir1==west || dir1==east) && (dir2==west || dir2==east) )return;else if ( (dir1==north || dir1==south) && (dir2==north || dir2==south) )return;direction = dir2;Move();direction = dir1;Move();}

Program#include <iostream>#include "Robots.h"#include "randgen.h"using namespace std;int main(){int n;RandGen gen;n = gen.RandInt(1,20);Robot rob(0,0);while (n > 0){ rob.MoveDiagonal(north,east);n--;}return 0;}------------------------------------------------void Robot::RandomTurn(){ if (stalled)return;int dirCode=0;RandGen rand;// find a direction which is blocked by another robot, but not with a wallwhile ( (!Blocked() || FacingWall()) && dirCode < 4 ){ direction = Direction(dirCode); dirCode++;}// if no direction has a robot, then find a random direction with no wallif ( !Blocked() || FacingWall() ){ do{ dirCode = rand.RandInt(0,3); direction = Direction(dirCode);} while(FacingWall());} theRobotWindow->Redraw(this);}------------------------------------------------