Coding Snippets
`Stop Watch Code Snippet`
```
#define MAX_ROUNDTRIP_COUNT 32
typedef struct stopWatch_s {
struct timeval eachTime[MAX_ROUNDTRIP_COUNT+1];
uint16_t roundTripCount;
} stopWatch_t;
void stopWatch_start(stopWatch_t *stopWatch) {
stopWatch->roundTripCount = 0;
gettimeofday(stopWatch->eachTime, NULL);
}
int stopWatch_createRoundTrip(stopWatch_t *stopWatch) {
if ( !timerisset(&stopWatch->eachTime[0]) ) return -1;
if(stopWatch->roundTripCount >= MAX_ROUNDTRIP_COUNT) {
fprintf(stderr, \\"RoundtripCount of %d reached\n\\", MAX_ROUNDTRIP_COUNT);
return -1;
}
stopWatch->roundTripCount += 1;
gettimeofday(&stopWatch->eachTime[stopWatch->roundTripCount], NULL);
return 0;
}
int stopWatch_printLatestTime(stopWatch_t *stopWatch) {
if ( !timerisset(&stopWatch->eachTime[0]) ) return -1;
struct timeval timeFromStart, timeFromLastRoundtrip;
gettimeofday(&timeFromStart, NULL);
gettimeofday(&timeFromLastRoundtrip, NULL);
/* calculate time deltas */
timersub(&timeFromStart, &stopWatch->eachTime[0], &timeFromStart);
if( stopWatch->roundTripCount == 0 ) {
timerclear(&timeFromLastRoundtrip);
} else {
timersub(&stopWatch->eachTime[stopWatch->roundTripCount],
&stopWatch->eachTime[stopWatch->roundTripCount-1],
&timeFromLastRoundtrip);
}
printf(\\"#%d delta:%ld.%06ld, sum:%ld.%06ld\n\\",
stopWatch->roundTripCount,
timeFromLastRoundtrip.tv_sec, timeFromLastRoundtrip.tv_usec,
timeFromStart.tv_sec, timeFromStart.tv_usec);
return 0;
}
```
`Tic Tac Toe` ``` /* xo.o * * Created by ptrs on 2012-10-08 * * Copyright (c) 2012 Petar Stupar * 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<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #define OK 0 #define MOVE_MADE 1 #define OUT_OF_RANGE 2 #define WINNER 3 #define EXIT 666 char player[] = {'O', 'X'}; char grid[3][3][2]; int computer = 0; int wins[] = {0, 0, 0, 0, 0, 0, 0, 0}; /* There are only 8 possible wins. Three horizontal, three vertical, and two diagonal. These are shown by marking the fields in this array */ void format_grid(){ int x, y; char ch = '\0'; for(x = 0, y = 0; x < 3; x++){ while(y < 3){ grid[x][y][0] = ' '; grid[x][y][1] = ch; y++; } y = 0; } } void print_grid(){ int x, y; printf("\t\t .0.1.2.Y\n"); for(x = 0, y = 0; x < 3; x++){ while(y < 3){ if(y == 0) printf("\t\t%i", x); printf("|%s", grid[x][y]); y++; } printf("|\n"); y = 0; } printf("\t\tX\n"); } int is_winner(char ch){ int x, y; int count; /* Horizontal check */ for(x = 0, y = 0, count = 0; x < 3; x++){ while(y < 3){ if(grid[x][y][0] == ch){ count++; } y++; } if(count == 3) return WINNER; else count = 0; y = 0; } /* Vertical check */ for(x = 0, y = 0, count = 0; y < 3; y++){ while(x < 3){ if(grid[x][y][0] == ch){ count++; } x++; } if(count == 3) return WINNER; else count = 0; x = 0; } /* Diagonal checks */ if(grid[0][0][0] == ch && grid[1][1][0] == ch && grid[2][2][0] == ch) return WINNER; if(grid[2][0][0] == ch && grid[1][1][0] == ch && grid[0][2][0] == ch) return WINNER; return OK; } int maxarrey(){ int i, ti, tn, n; for(i = 0, ti = tn = 0; i < 8; i++){ if(wins > tn){ tn = wins; ti = i; } if(wins == tn && wins > 0){ for(n = 0; n < 3; n++){ if(i >= 0 && i <= 2){ if(grid[n][0] == ' '){ ti = i; tn = wins; } } if(i >= 3 && i <= 5){ if(grid[n][0] == ' '){ ti = i; tn = wins; } } if(i == 6 && (grid[0][0][0] == ' ' || grid[1][1][0] == ' ' || grid[2][2][0] == ' ')){ ti = i; tn = wins; } if(i == 7 && (grid[0][2][0] == ' ' || grid[1][1][0] == ' ' || grid[2][0][0] == ' ')){ ti = i; tn = wins; } } } } return ti; } int minarrey(){ int i, ti, tn, n; for(i = 0, ti = tn = 0; i < 8; i++){ if(wins < tn){ tn = wins; ti = i; } if(wins == tn && wins < 0){ for(n = 0; n < 3; n++){ if(i >= 0 && i <= 2){ if(grid[n][0] == ' '){ ti = i; tn = wins; } } if(i >= 3 && i <= 5){ if(grid[n][0] == ' '){ ti = i; tn = wins; } } if(i == 6 && (grid[0][0][0] == ' ' || grid[1][1][0] == ' ' || grid[2][2][0] == ' ')){ ti = i; tn = wins; } if(i == 7 && (grid[0][2][0] == ' ' || grid[1][1][0] == ' ' || grid[2][0][0] == ' ')){ ti = i; tn = wins; } } } } return ti; } void computer_move(int *x, int *y){ int tmp_x, tmp_y; int max, min, n; max = maxarrey(); min = minarrey(); if(wins[min] == -2 && wins[max] < 2){ /* Is the user winning?? */ if(min >= 0 && min <= 2){ tmp_x = min; for(n = 0; n < 3; n++){ if(grid[tmp_x][n][0] == ' '){ tmp_y = n; } } } else if(min >= 3 && min <= 5){ tmp_y = min - 3; for(n = 0; n < 3; n++){ if(grid[n][tmp_y][0] == ' '){ tmp_x = n; } /* else tmp_x = n; */ } if(tmp_y == 2) tmp_x--; } else if(min == 6){ if(grid[0][0][0] == ' '){ tmp_x = 0; tmp_y = 0; } else if(grid[1][1][0] == ' '){ tmp_x = 1; tmp_y = 1; } else if(grid[2][2][0] == ' '){ tmp_x = 2; tmp_y = 2; } } else if(min == 7){ if(grid[2][0][0] == ' '){ tmp_x = 2; tmp_y = 0; } else if(grid[1][1][0] == ' '){ tmp_x = 1; tmp_y = 1; } else if(grid[0][2][0] == ' '){ tmp_x = 2; tmp_y = 2; } } } else{ /* User is not winning */ if(max >= 0 && max <= 2){ tmp_x = max; for(n = 0; n < 3; n++){ if(grid[tmp_x][n][0] == ' '){ tmp_y = n; } } } else if(max >= 2 && max <= 5){ tmp_y = max; for(n = 0; n < 3; n++){ if(grid[n][tmp_y][0] == ' '){ tmp_x = n; } } } else if(max == 6){ if(grid[2][0][0] == ' '){ tmp_x = 0; tmp_y = 0; } else if(grid[1][1][0] == ' '){ tmp_x = 1; tmp_y = 1; } else if(grid[0][2][0] == ' '){ tmp_x = 2; tmp_y = 2; } } else if(max == 7){ if(grid[0][0][0] == ' '){ tmp_x = 0; tmp_y = 0; } else if(grid[1][1][0] == ' '){ tmp_x = 1; tmp_y = 1; } else if(grid[2][2][0] == ' '){ tmp_x = 2; tmp_y = 2; } } } *x = tmp_x; *y = tmp_y; wins[*x] = wins[*x] + 1; wins[(*y + 3)] = wins[(*y + 3)] + 1; if(*x == 1 && *y == 1){ wins[6] += 1; wins[7] += 1; } if((*x == 0 && *y == 0) || (*x == 2 && *y == 2)){ wins[6] += 1; } if((*x == 0 && *y == 2) || (*x == 2 && *y == 0)){ wins[7] += 1; } } int make_move(char ch){ int mov_x, mov_y; if(computer == 1 && ch == 'O'){ computer_move(&mov_x, &mov_y); grid[mov_x][mov_y][0] = ch; return is_winner(ch); } else{ printf("Enter x and y coordinates separated by a comma (ex. 1,2) or -1 to exit: "); scanf("%i,%i", &mov_x, &mov_y); if(mov_x == -1 && mov_y == -1) return EXIT; if((mov_x >= 0 && mov_x <= 2) && (mov_y >= 0 && mov_y <= 2)){ if(grid[mov_x][mov_y][0] == ' '){ grid[mov_x][mov_y][0] = ch; wins[mov_x] -= 1; wins[(mov_y + 3)] -= 1; if(mov_x == 1 && mov_y == 1){ wins[6] -= 1; wins[7] -= 1; } if((mov_x == 0 && mov_y == 0) || (mov_x == 2 && mov_y == 2)){ wins[6] -= 1; } if((mov_x == 0 && mov_y == 2) || (mov_x == 2 && mov_y == 0)){ wins[7] -= 1; } return is_winner(ch); } else{ return MOVE_MADE; } } else{ return OUT_OF_RANGE; } } return is_winner(ch); } int main(int argc, char *argv[]){ int move = 1; int winner = 0; int outcome; char sw; while((sw = getopt(argc, argv, "c")) != EOF){ switch(sw){ case 'c': computer = 1; } } format_grid(); print_grid(); while(move < 9){ while(move <= 9 && (outcome = make_move(player[move % 2])) == OK){ print_grid(); move++; } if(outcome == MOVE_MADE){ printf("That move was already made. Try again.\n"); continue; } if(outcome == OUT_OF_RANGE){ printf("No such field. Out of range. Try again.\n"); continue; } if(outcome == WINNER){ print_grid(); printf("the WINNER is: %c\n", player[move % 2]); return 0; } if(outcome == EXIT){ return 0; } if(move >= 9){ printf("No winner...\n"); return 0; } } } ```
`Simple Clock` ``` #include<stdio.h> #include<time.h> #include<windows.h> #include <stdlib.h> int main() { struct tm *tmp; time_t s; for(;;) { s = time(NULL); tmp = localtime(&t); printf("%d:%0d:%d\n",tmp->tm_hour,tmp->tm_min,tmp->tm_sec); Sleep(1000); system ("cls"); } return 0; }
`Calendar` ``` #include <iostream> #include <iomanip> bool isLeapYear( unsigned int& ); //checks if 'year' is leap year unsigned int firstDayOfJanuary( unsigned int& year ); unsigned int numOfDaysInMonth( unsigned int , unsigned int& ); // takes the number of the month, and 'year' as arguments void printHeader( unsigned int ); //takes the number of the month, and the first day, prints, and updates void printMonth( unsigned int , unsigned int& ); //takes number of days in month, and reference to 'firstDayInCurrentMonth' so it updates after every call void skip( unsigned int ); //prints the specified amount of spaces int main() { unsigned int year , firstDayInCurrentMonth; std::cout << "Calendar year? "; std::cin >> year; std::cout << "\n"; firstDayInCurrentMonth = firstDayOfJanuary( year ); skip(9); std::cout << year << "\n"; for ( unsigned int currentMonth = 1 ; currentMonth <= 12 ; currentMonth++ ) { printHeader( currentMonth ); printMonth( numOfDaysInMonth( currentMonth , year ) , firstDayInCurrentMonth ); std::cout << "\n\n\n"; } std::cout << "Press Enter to Exit..."; std::cin.ignore(); std::cin.get(); } bool isLeapYear( unsigned int& year ) { //if number is multiple of 4 and is either multiple of 400 or not multiple of 100, is leap year return ( year % 4 == 0 ) && ( year % 100 != 0 || year % 400 == 0 ); } unsigned int firstDayOfJanuary( unsigned int& year ) { /* "( 97 * year - 97 ) / 400" is the simplification of: x1 = (year - 1)/ 4; x2 = (year - 1)/ 100; x3 = (year - 1)/ 400; day_start = (year + x1 - x2 + x3) % 7; after each value is plugged in */ return ( year + ( 97 * year - 97 ) / 400 ) % 7; } unsigned int numOfDaysInMonth( unsigned int m , unsigned int& year ) { if ( m == 2 ) return isLeapYear( year ) ? 29 : 28; //if month is February, return correct number based on whether it is leap year else return 30 + ( m % 2 ); //otherwise return 31 if month number is odd, 30 if month number is even } void printHeader( unsigned int m ) { skip( 7 ); if ( m == 1 ) std::cout << "January"; else if ( m == 2 ) std::cout << "February"; else if ( m == 3 ) std::cout << "March"; else if ( m == 4 ) std::cout << "April"; else if ( m == 5 ) std::cout << "May"; else if ( m == 6 ) std::cout << "June"; else if ( m == 7 ) std::cout << "July"; else if ( m == 8 ) std::cout << "August"; else if ( m == 9 ) std::cout << "September"; else if ( m == 10 ) std::cout << "October"; else if ( m == 11 ) std::cout << "November"; else if ( m == 12 ) std::cout << "December"; std::cout << "\n S M T W T F S" << "\n"; std::cout << "____________________" << "\n"; } void skip( unsigned int i ) { while ( i > 0 ) { std::cout << " "; i--; } } void printMonth( unsigned int numDays, unsigned int &weekDay ) { skip( 3 * weekDay ); //3 is width of a calendar number for ( unsigned int day = 1 ; day <= numDays ; day++ ) { std::cout << std::setw(2) << day << " "; if ( weekDay == 6 ) { std::cout << "\n"; weekDay = 0; } else weekDay++; } }
`Distance Calculator` ``` #include <iostream> #include <cmath> #include <string> /* This program takes 2 x,y coords and calculates the distance between them. I wrote this cause I was getting tired of doing the math on paper for my college algebra class :). There is no input validation but I'll leave that up to anyone who wants to use it. */ void getValues(double &x, double &x1, double &y, double &y1); void getDistance(const double x, const double x1, const double y, const double y1); int main(void) { double x; double x1; double y; double y1; bool exit = false; std::string exitletter; while(!exit) { getValues(x,x1,y,y1); getDistance(x,x1,y,y1); std::cout<<"Another? (y or n)"<<std::endl; std::cin>>exitletter; if(exitletter == "n") { exit = true; } } return 0; } void getValues(double &x, double &x1, double &y, double &y1) { std::cout<<"Enter x"<<std::endl; std::cin>>x; std::cout<<"Enter y"<<std::endl; std::cin>>y; std::cout<<"Enter x2"<<std::endl; std::cin>>x1; std::cout<<"Enter y2"<<std::endl; std::cin>>y1; } void getDistance(const double x, const double x1, const double y, const double y1) { double distance; double preSqrtValue; preSqrtValue = ( pow( (x1 - x), 2) + pow( (y1 - y), 2) ); distance = sqrt( ( pow( (x1 - x), 2) + pow( (y1 - y), 2) ) ); std::cout<<"Before taking the square root "<<preSqrtValue<<std::endl; std::cout<<"Distance equals "<<distance<<std::endl; }
`Simple Calculator` ``` #include <iostream> //A simple calculator using templates template <class T> T add(T a, T b) { T result; result = a + b; return result; } template <class T> T subtract(T a, T b) { T result; result = a - b; return result; } template <class T> T divide(T a, T b) { T result; result = a / b; return result; } template <class T> T multiply(T a, T b) { T result; result = a * b; return result; } int main(void) { std::cout<<add<int>(10,20)<<std::endl; std::cout<<subtract<float>(5.4,2.3)<<std::endl; std::cout<<multiply<int>(4,5)<<std::endl; std::cout<<divide<int>(9,3)<<std::endl; std::cin.get(); return 0; }
`Prime factor of a given number calculator` ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> int main() { int x,div=2; int i=0,j=0; printf("Enter Number X : "); scanf("%d",&x); int num=x; int *prime=(int *) malloc(x*sizeof(int)); printf("\n Allocated \n"); getch(); if (x==1 || x==0) { printf(" Number %d have no prime Factors",x); *prime=0; } else { while(x>1) { if ((x%div)==0) { *(prime+i)=div;x=x/div;i++;printf("\n Prime Factor\n"); } else { div++; } } } printf("\n The Prime Factors for Number %d are :\n",num); for(j=0;j<i;j++) { printf (" %d ",*(prime+j)); } return(0); }
``` \nyeh
``` <div style="text-align:center;width:400px;padding:1em 0;"> <h2><a style="text-decoration:none;" href="http://www.zeitverschiebung.net/en/city/5128581"><span style="color:gray;">Current local time in</span><br />New York City, United States</a></h2> <iframe src="https://www.zeitverschiebung.net/clock-widget-iframe-v2?language=en&timezone=America%2FNew_York" width="100%" height="150" frameborder="0" seamless></iframe> <small style="color:gray;">© <a href="http://www.zeitverschiebung.net/en/" style="color: gray;">Time Difference</a></small> </div>
``` <!DOCTYPE html> <html> <head> <title>Image Preview</title> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style type="text/css"> * { box-sizing: border-box; position: relative; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; } body { background:#fff; font-family:helvetica, arial, sans-serif; color:#222; font-size:16px; } form { margin:3em; } form div.row { width:400px; padding:1em; overflow:hidden; background:#ededed; border-radius:0.5em; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; } form div.file-preview { background:#ccc; border:5px solid #fff; box-shadow:0 0 4px rgba(0, 0, 0, 0.5); -moz-box-shadow:0 0 4px rgba(0, 0, 0, 0.5); -webkit-box-shadow:0 0 4px rgba(0, 0, 0, 0.5); display:inline-block; float:left; margin-right:1em; width:60px; height:60px; text-align:center; } form div.row label { font-weight:bold; display:block; margin-bottom:0.25em; } </style> </head> <body> <form action="blah" method="post" enctype="multipart/form-data"> <h1>Upload Image Preview</h1> <p>Choose upload image.</p> <div class="row"> <div class="file-preview"></div> <label for="file-input">Select a File:</label> <input id="file-input" type="file" name="file"> </div> </form> <script type="text/javascript"> $('input[type=file]').change(function(e) { if(typeof FileReader == "undefined") return true; var elem = $(this); var files = e.target.files; for (var i = 0, f; f = files; i++) { if (f.type.match('image.*')) { var reader = new FileReader(); reader.onload = (function(theFile) { return function(e) { var image = e.target.result; previewDiv = $('.file-preview', elem.parent()); bg_width = previewDiv.width() * 2; previewDiv.css({ "background-size":bg_width + "px, auto", "background-position":"50%, 50%", "background-image":"url("+image+")", }); }; })(f); reader.readAsDataURL(f); } } }); </script> </body> </html>
Join our real-time social learning platform and learn together with your friends!