filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.java
import java.util.Scanner; public class BiggestOfNNumbers { public static void main(String[] args) { Scanner data = new Scanner(System.in); System.out.print("Enter numbers of elements"); int n = data.nextInt(); System.out.println("Enter " + n + " numbers"); int max = data.nextInt(); for (int i = 1; i < n; ++i) { int temp = data.nextInt(); if(temp < max) continue; else max = temp; } System.out.println("Maximum is "+ max); } }
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.nims
## Find Biggest of given sequence of integers using built in proc proc biggestNum(numbers: seq[int]): int = max(numbers) ## Find Biggest of given sequence of integers by iteration proc biggestNumNative(numbers: seq[int]): int = for num in numbers: if num > result: result = num ## Tests biggestNum(@[3, 2, 6, 1]).echo # 6 biggestNum(@[10, 4, 3, 7]).echo # 10 biggestNumNative(@[3, 2, 6, 1]).echo # 6 biggestNumNative(@[10, 4, 3, 7]).echo # 10
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.py
elements = [] n = int(input("Enter number of elements:")) for i in range(0, n): elements.append(int(input("Enter element:"))) elements.sort() print("Largest element is : ", elements[n - 1])
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers2.cpp
#include <iostream> using namespace std; int main() { int n, max, tmp; cout << "Enter numbers of elements : "; cin >> n; cout << "Enter numbers\n"; cin >> tmp; max = tmp; for (int i = 0; i < n - 1; i++) { cin >> tmp; if (max < tmp) max = tmp; } cout << "Maximum is " << max << "\n"; return 0; }
code/unclassified/src/biggest_of_n_numbers/readme.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Biggest Of n numbers The aim is to find the maximum numbers among the n given numbers. The value n and the elements are taken as input from the user. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/biggest_suffix/biggest_suffix.c
#include <stdio.h> #include <string.h> int equality(char *s1, char *s2, int x) { if(strcmp(s1 + strlen(s1) - x, s2 + strlen(s2) - x) == 0) return 1; return 0; } char *biggest_suffix(char *s1, char *s2) { int i; int shortest_string; /* Finds the number of characters that needs to traversed to check smallest substring */ int reminder = 0; /* Keeps count of number of characters that are same in both the strings starting from back */ if(strlen(s1) > strlen(s2)) shortest_string = strlen(s2); else shortest_string = strlen(s1); for(i = 0; i <= shortest_string; i++) { if( equality(s1, s2, i) ) reminder = i; else break; } if(reminder == 0) return "No suffix"; else return s1 + strlen(s1) - reminder; } int main(void) { char s1[100]; char s2[100]; printf("Give first string:\n"); scanf("%s", s1); printf("Give second string:\n"); scanf("%s", s2); printf("Biggest suffix is: %s\n", biggest_suffix(s1, s2) ); return 0; }
code/unclassified/src/biggest_suffix/biggest_suffix.js
/** * * @param {string} longest One of the two strings for biggest common suffix * @param {string} shortest One of the two strings for biggest common suffix. It serves terminating condition for algorithm * @param {number} accumulator counter for common characters found * @returns {number} counter for no of characters matched */ const countMaxSuffix = (longest, shortest, accumulator) => { if (shortest.length == 0 || shortest.slice(-1) != longest.slice(-1)) return accumulator; return countMaxSuffix( longest.slice(0, -1), shortest.slice(0, -1), ++accumulator ); }; /** * * @param {string} first One of the two strings for biggest common suffix * @param {string} second One of the two strings for biggest common suffix. It serves terminating condition for algorithm * @returns {string} suffix biggest suffix of given two strings */ const findBiggestSuffix = (first, second) => { if (first.length <= 0 || second.length <= 0) { return 'No Suffix'; } const [shortest, longest] = [first, second].sort(); const charsMatched = countMaxSuffix(longest, shortest, 0); return charsMatched == 0 ? 'No Suffix' : longest.slice(-charsMatched); }; // Tests console.log(findBiggestSuffix('abcdef', 'def')); // def console.log(findBiggestSuffix('abc', 'abc')); // abc console.log(findBiggestSuffix('abcdef', 'abc')); // 'No Suffix'
code/unclassified/src/biggest_suffix/readme.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Biggest Suffix The aim is to find the biggest suffix of two strings where the strings are taken as input from the user. # Algorithm After taking both the strings as input we find the length of the smaller string because we only need to compare that many characters in both the strings. After finding the length of the smaller string we start traversing from end of both the strings and check if they are same. If yes, we increase the counter. Else, we break the loop and print the string traversed so far. # Exampler Few examples are: - s1 = "abcdef" , s2 = "def" : Biggest Suffix = "def" - s1 = "abc" , s2 = "abc" : Biggest Suffix = "abc" - s1 = "abcdef" , s2 = "abc" : Biggest Suffix = "" --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/fifteen_puzzle/fifteen.c
/** * fifteen.c * * Implements Game of Fifteen (generalized to d x d). * * Usage: fifteen d * * whereby the board's dimensions are to be d x d, * where d must be in [DIM_MIN,DIM_MAX] * * Note that usleep is obsolete, but it offers more granularity than * sleep and is simpler to use than nanosleep; `man usleep` for more. * Author:- Rishav Pandey * Part of Cosmos by OpenGenus Foundation */ #define _XOPEN_SOURCE 500 #include <stdio.h> #include <stdlib.h> #include <unistd.h> // constants #define DIM_MIN 3 #define DIM_MAX 9 // board int board[DIM_MAX][DIM_MAX]; // dimensions int d; // prototypes void clear(void); void greet(void); void init(void); void draw(void); int move(int tile); int won(void); int main(int argc, char *argv[]) { // ensure proper usage if (argc != 2) { printf("Usage: fifteen d\n"); return 1; } // ensure valid dimensions d = atoi(argv[1]); if (d < DIM_MIN || d > DIM_MAX) { printf("Board must be between %i x %i and %i x %i, inclusive.\n", DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX); return 2; } // open log FILE *file = fopen("log.txt", "w"); if (file == NULL) { return 3; } // greet user with instructions greet(); // initialize the board init(); // accept moves until game is won while (1) { // clear the screen clear(); // draw the current state of the board draw(); // log the current state of the board (for testing) for (int i = 0; i < d; i++) { for (int j = 0; j < d; j++) { fprintf(file, "%i", board[i][j]); if (j < d - 1) { fprintf(file, "|"); } } fprintf(file, "\n"); } fflush(file); // check for win if (won()) { printf("ftw!\n"); break; } // prompt for move printf("Tile to move: (0)exit "); int tile; scanf("%d", &tile); // quit if user inputs 0 (for testing) if (tile == 0) { break; } // log move (for testing) fflush(file); // move if possible, else report illegality if (!move(tile)) { printf("\nIllegal move.\n"); usleep(500000); } // sleep thread for animation's sake usleep(500000); } // close log fclose(file); // success return 0; } /** * Clears screen using ANSI escape sequences. */ void clear(void) { printf("\033[2J"); printf("\033[%d;%dH", 0, 0); } /** * Greets player. */ void greet(void) { clear(); printf("WELCOME TO GAME OF FIFTEEN\n"); usleep(2000000); } /** * Initializes the game's board with tiles numbered 1 through d*d - 1 * (i.e., fills 2D array with values but does not actually print them). */ void init(void) { // TODO int tiles = (d * d - 1); for (int i = 0; i < d; i++) for (int j = 0; j < d; j++) { board[i][j] = tiles; tiles--; } // to swap the second last and third last index of board when d is even. if (d % 2 == 0) { int temp = board[d - 1][d - 3]; board[d - 1][d - 3] = board[d - 1][d - 2]; board[d - 1][d - 2] = temp; } } /** * Prints the board in its current state. */ void draw(void) { // TODO for (int i = 0; i < d; i++) { for (int j = 0; j < d; j++) { if (!board[i][j]) { printf(" _ "); } else { printf("%2i ", board[i][j]); } } printf("\n"); } } /** * If tile borders empty space, moves tile and returns true, else * returns false. */ int move(int tile) { // TODO // For keeping the track of tile in the Game int row, column; for (int i = 0; i < d; ++i) { for (int j = 0; j < d; ++j) { if (board[i][j] == tile) { row = i; column = j; } } } // For keeping the track of blank tile in the Game int row1, column1; for (int i = 0; i < d; ++i) { for (int j = 0; j < d; ++j) { if (board[i][j] == 0) { row1 = i; column1 = j; } } } // For legal move of the tile towards Right if (board[row][column] == board[row1][column1 + 1]) { board[row1][column1 + 1] = 0; board[row1][column1] = tile; return 1; } //usleep(15000000); // For legal move of the tile towards Left if (board[row][column] == board[row1][column1 - 1]) { board[row1][column1 - 1] = 0; board[row1][column1] = tile; return 1; } // For legal move of the tile towards Up if (board[row][column] == board[row1 - 1][column1]) { board[row1 - 1][column1] = 0; board[row1][column1] = tile; return 1; } // For legal move of the tile towards Down if (board[row][column] == board[row1 + 1][column1]) { board[row1 + 1][column1] = 0; board[row1][column1] = tile; return 1; } return 0; } /** * Returns true if game is won (i.e., board is in winning configuration), * else false. */ int won(void) { // TODO int counter = 0; for (int i = 0; i < d; i++) { for (int j = 0; j < d; j++) { //++counter != (d*d) checks from starting to second last tile. //board[i][j] != counter returns false if values are incorrect. if (++counter != (d * d) && board[i][j] != counter) { return 0; } } } return 1; }
code/unclassified/src/fifteen_puzzle/log.txt
8|7|6 5|4|3 2|1|0 8|7|6 5|4|3 2|0|1 8|7|6 5|0|3 2|4|1 8|7|6 5|3|0 2|4|1 8|7|0 5|3|6 2|4|1
code/unclassified/src/fifteen_puzzle/makefile
fifteen: fifteen.c clang -ggdb3 -O0 -std=c11 -Wall -Werror -o fifteen fifteen.c -lcs50 -lm clean: rm -f *.o a.out core fifteen log.txt
code/unclassified/src/fifteen_puzzle/readme.md
# Fifteen Puzzle The 15-puzzle (also called Gem Puzzle, Boss Puzzle, Game of Fifteen, Mystic Square and many others) is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing. The puzzle also exists in other sizes, particularly the smaller 8-puzzle. If the size is 3×3 tiles, the puzzle is called the 8-puzzle or 9-puzzle, and if 4×4 tiles, the puzzle is called the 15-puzzle or 16-puzzle named, respectively, for the number of tiles and the number of spaces. **The object of the puzzle is to place the tiles in order by making sliding moves that use the empty space.** --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/flutter_res/README.md
[This Article](https://iq.opengenus.org/getting-started-with-flutter-development/) has been made to put forward and efforts have been made seeing to the emergence of the new Mobile Technology which is giving equal competition to the ones that are already existing in the it industry. This article contains the following parts : 1. What is Flutter? 2. Why Flutter? 3. Anatomy of a Flutter Application 4. Some popular award wining apps built using Flutter.
code/unclassified/src/jaccard_similarity/README.md
# Jaccard Similarity Coefficient # The Jaccard similarity coefficient is a statistic used for comparing the similarity and diversity of sample sets. The Jaccard coefficient measures similarity between finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets:- ![Jaccard Similarity Equation](https://i.stack.imgur.com/gL3oV.jpg) (If A and B are both empty, we define J(A,B) = 1.) Note that 0 ≤ J ( A , B ) ≤ 1. ## Further Reading ## To know further about Jaccard Similarity Coefficients and Its Applications , go through the following links :- * [Jaccard Index - Wikipedia](https://en.wikipedia.org/wiki/Jaccard_index) * [Calculating Jaccard Similarity Matrix with Mapreduce for Entity Pairs in Wikipedia](https://pdfs.semanticscholar.org/b5d1/74e1f1a851354b63628b498c68af66e75506.pdf) * [Using Jaccard Coefficient For Keyword Similarity](http://www.iaeng.org/publication/IMECS2013/IMECS2013_pp380-384.pdf) * [A note on Triangle Inequality on Jaccard Distance](https://arxiv.org/pdf/1612.02696v1.pdf) * [Notes on Jaccard Similarity(cs.utah.edu)](https://www.cs.utah.edu/~jeffp/teaching/cs5955/L4-Jaccard+Shingle.pdf)
code/unclassified/src/jaccard_similarity/jaccard.c
/* A simple C program to create Jaccard’s indices adjusted for differences in species richness across site */ #include <time.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <float.h> #define R 524 #define C 46 #define MAX 100 void main() { time_t toc; int M[R][C], B[R][C], S[C]; int i,j,k, in, un, b; float Jaccard[C][C], q; FILE *fpi, *fpo; time(&toc); /* random number seed */ srand((int)toc); /* generate pseudorandom number */ fpi = fopen("Africa.txt", "r"); /* open input file (maybe altered) */ fpo = fopen("foo.txt", "w"); /* standard output file (ditto) */ for (i = 0; i < R; i++) /* read presence–absence data */ for (j = 0; j < C; ++j) fscanf(fpi, "%d", &M[i][j]); for (b = 0; b < MAX; ++b) /* initialize Jaccard matrix to zero */ { for (j = 0; j < C; ++j) S[j] = 0; for (i = 0; i < C; ++i) for (j = 0; j < C; ++j) Jaccard[i][j] = 0.0; i = 0; for (i = 0; i < R ; ++i) /* obtain species data from input */ { k = (int)((float)(rand()/32767.0*(R-1))); for (j = 0; j < C; ++j) B[i][j] = M[k][j]; } for (j = 0; j < C; ++j) /* sum species */ for (i = 0; i < R; ++i) S[j] += B[i][j]; for (k = 0; k < C-1; ++k) /* calculated Jaccard’s index */ for (j = k+1; j < C; ++j) { in = un = 0; for (i = 0; i < R; ++i) { un += (B[i][k] || B[i][j]); in += (B[i][k] && B[i][j]); } q = S[k]<S[j] ? (float)S[j]/S[k] :(float)S[k]/S[j]; /* adjust index. . . */ Jaccard[k][j] = (float)in/un*q*100.0; /* by diff. richness */ } for (j = 1; j < C; ++j) /* output adjusted Jaccard’s */ { fprintf(fpo, "\n"); for (k = 0; k < j; ++k) fprintf(fpo, "%.1f ", 100.0-Jaccard[k][j]); } }
code/unclassified/src/jaccard_similarity/jaccard.java
package org.apache.commons.text.similarity; import java.util.HashSet; import java.util.Set; /** * Measures the Jaccard similarity (aka Jaccard index) of two sets of character * sequence. Jaccard similarity is the size of the intersection divided by the * size of the union of the two sets. * * <p> * For further explanation about Jaccard Similarity, refer * https://en.wikipedia.org/wiki/Jaccard_index * </p> * * @since 1.0 */ public class JaccardSimilarity implements SimilarityScore<Double> { /** * Calculates Jaccard Similarity of two set character sequence passed as * input. * * @param left first character sequence * @param right second character sequence * @return index * @throws IllegalArgumentException * if either String input {@code null} */ @Override public Double apply(CharSequence left, CharSequence right) { if (left == null || right == null) { throw new IllegalArgumentException("Input cannot be null"); } return Math.round(calculateJaccardSimilarity(left, right) * 100d) / 100d; } /** * Calculates Jaccard Similarity of two character sequences passed as * input. Does the calculation by identifying the union (characters in at * least one of the two sets) of the two sets and intersection (characters * which are present in set one which are present in set two) * * @param left first character sequence * @param right second character sequence * @return index */ private Double calculateJaccardSimilarity(CharSequence left, CharSequence right) { Set<String> intersectionSet = new HashSet<String>(); Set<String> unionSet = new HashSet<String>(); boolean unionFilled = false; int leftLength = left.length(); int rightLength = right.length(); if (leftLength == 0 || rightLength == 0) { return 0d; } for (int leftIndex = 0; leftIndex < leftLength; leftIndex++) { unionSet.add(String.valueOf(left.charAt(leftIndex))); for (int rightIndex = 0; rightIndex < rightLength; rightIndex++) { if (!unionFilled) { unionSet.add(String.valueOf(right.charAt(rightIndex))); } if (left.charAt(leftIndex) == right.charAt(rightIndex)) { intersectionSet.add(String.valueOf(left.charAt(leftIndex))); } } unionFilled = true; } return Double.valueOf(intersectionSet.size()) / Double.valueOf(unionSet.size()); } }
code/unclassified/src/jaccard_similarity/jaccard.js
/** * Calculates union of two given sets * @param {Set} setA * @param {Set} setB */ const union = (setA, setB) => { const _union = new Set(setA); for (let elem of setB) { _union.add(elem); } return _union; }; /** * Calculates intersection of two given sets * @param {Set} setA * @param {Set} setB */ const intersection = (setA, setB) => { const _intersection = new Set(); for (let elem of setB) { if (setA.has(elem)) { _intersection.add(elem); } } return _intersection; }; /** * * @param {Array} first * @param {Array} second */ const jaccardSimilarity = (first, second) => { intersection_cardinality = intersection(new Set(first), new Set(second)).size; union_cardinality = union(new Set(first), new Set(second)).size; return intersection_cardinality / union_cardinality; }; console.log(jaccardSimilarity([0, 1, 2, 5, 6], [0, 2, 3, 5, 7, 9]));
code/unclassified/src/jaccard_similarity/jaccard.nims
## Calculates Jaccard Similarity proc jaccardSimilarity[T](setA: set[T], setB: set[T]): float = card(setA * setB) / card(setA + setB) jaccardSimilarity({0, 1, 2, 5, 6}, {0, 2, 3, 5, 7, 9}).echo
code/unclassified/src/jaccard_similarity/jaccard.py
#!/usr/bin/env python def jaccard_similarity(x, y): intersection_cardinality = len(set.intersection(*[set(x), set(y)])) union_cardinality = len(set.union(*[set(x), set(y)])) return intersection_cardinality / float(union_cardinality) print(jaccard_similarity([0, 1, 2, 5, 6], [0, 2, 3, 5, 7, 9]))
code/unclassified/src/josephus_problem/README.md
# Josephus Problem Algorithm Josephus Problem is a theoretical Counting Game Problem. n people stand in a circle and are numbered from 1 to n in clockwise direction. Starting from 1 in clockwise direction each person kills the k<sup>th</sup> person next to him and this continues till a single person is left. The task is to choose a suitable position in initial circle to avoid execution. ## Explanation ![When k is 1](http://www.exploringbinary.com/wp-content/uploads/Josephus8.png) >Image credits: ([Exploring Binary](http://www.exploringbinary.com/powers-of-two-in-the-josephus-problem/)) ### Recurrence Relation `J(1,k) = 1` `J(n,k) = (J(n-1,k) + k-1 ) mod n +1` ## Complexity Time complexity = O(n) --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/josephus_problem/josephus.c
/*Part of Cosmos by OpenGenus Foundation*/ #include <stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; void position() { struct node *p,*q; int n,gap; printf("Enter no of horses:\n"); scanf("%d",&n); printf("Enter gap:\n"); scanf("%d",&gap); p=q=(struct node *)malloc(sizeof(struct node)); p->data=1; for(int i=2;i<=n;i++) { p->next=malloc(sizeof(struct node)); p=p->next; p->data=i; } p->next=q; for(int i=n;i>1;) { for(int j=0;j<gap-1;j++) { p=p->next; } p->next=p->next->next; i--; } printf("Safe position is: %d\n",p->data); } int main() { position(); return 0; }
code/unclassified/src/josephus_problem/josephus.cpp
//Part of Cosmos by OpenGenus Foundation #include <iostream> using namespace std; int josephus(int n, int k) { // Returns the safe position of n items // that have every kth item counted out // Note that the indice returned is zero-indexed if (n == 1) return 0; return (josephus(n - 1, k) + k) % n; } int main(void) { int n, k; cout << "n: "; cin >> n; cout << "k: "; cin >> k; cout << "Safe position: " << josephus(n, k) << endl; return 0; }
code/unclassified/src/josephus_problem/josephus.go
package main import ( "fmt" "strconv" ) func safePosition(n int,k int) int { if n <= 1 { return 0 } return (safePosition(n-1, k) + k) % n } func main() { var n int var k int fmt.Println("Enter the number of people:") fmt.Scanf("%d\n", &n) fmt.Println("Enter the kth value of people getting executed:") fmt.Scanf("%d\n", &k) fmt.Println("Safe Position is " + strconv.Itoa(safePosition(n, k) + 1)) }
code/unclassified/src/josephus_problem/josephus.js
function josephus(n, k) { // Returns the safe position of n items // that have every kth item counted out // Note that the indice returned is zero-indexed if (n == 1) { return 0; } return (josephus(n - 1, k) + k) % n; } function test(n, k, expected) { const result = josephus(n, k); if (result == expected) { console.log('PASS'); } else { console.log(`FAIL: josephus(${n}, ${k}) result ${result} does not match ${expected}`); } } test(1, 10, 0); test(13, 2, 10); test(8, 2, 0); test(1000, 2, 976);
code/unclassified/src/josephus_problem/josephus.py
def safePos(n, k): if n == 1: return 0 return (safePos(n - 1, k) + k) % n n = int(input("Enter the number of people : ")) k = int(input("Enter the kth value of people getting executed : ")) print( "The Safe position to stand is", safePos(n, k) + 1 ) # Answer is for 1 based indexing
code/unclassified/src/krishnamurthy_number/README.md
# What is A Krishnamurthy number? It's a number whose sum total of the factorials of each digit is equal to the number itself. ## Here's what I mean by that: ### "145" is a **Krishnamurthy** Number because, #### 1! + 4! + 5! = 1 + 24 + 120 = 145 ### "40585" is also a **Krishnamurthy** Number. #### 4! + 0! + 5! + 8! + 5! = 40585 ### "357" or "25965" is **NOT a Krishnamurthy** Number #### 3! + 5! + 7! = 6 + 120 + 5040 != 357
code/unclassified/src/krishnamurthy_number/krishnamurthyNumber.py
# helper function def factorial(n): fact = 1 while n != 0: fact *= n n -= 1 return fact def checkKrishnamurthy(n): sumOfDigits = 0 # will hold sum of FACTORIAL of digits temp = n while temp != 0: # get the factorial of of the last digit of n and add it to sumOfDigits sumOfDigits += factorial(temp % 10) # replace value of temp by temp/10 # i.e. will remove the last digit from temp temp //= 10 # returns True if number is krishnamurthy return (sumOfDigits == n) if __name__ == '__main__': n = 40585 # input number print(checkKrishnamurthy(40585))
code/unclassified/src/lapindrom_checker/README.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Lapindrome Checker The aim is to find if the string is lapindrome or not. The string is taken as input from the user. Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. Here, after taking string as an input from the user we divide it into two parts. If the length is even Part 1 goes from 0 to mid-1 and part goes from mid to end. Else if the string length is odd, we discard the middle character and Part 1 goes from 0 to mid-1 and part goes from mid+1 to end. Then we sort both the strings and compare them. If they are same, the given string is lapindrome else it is not. # Example - String= "gaga" : Lapindrome = YES - String= "abccab" : Lapindrome = YES - String= "rotor" : Lapindrome = YES - String= "abbaab" : Lapindrome = NO --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/lapindrom_checker/lapindrome_checker.cpp
// part of cosmos by opengenus foundation #include <iostream> #include <algorithm> // used for sort() using namespace std; bool isLapindrome(string str) { int mid = str.length() / 2; int delim = (str.length() % 2) == 0 ? mid : mid + 1; string first_half = str.substr(0, mid); string second_half = str.substr(delim); sort(first_half.begin(), first_half.end()); sort(second_half.begin(), second_half.end()); return first_half == second_half; } int main() { string test_case; cout << "Input the string to be checked" << endl; cin >> test_case; if (isLapindrome(test_case)) cout << test_case << "is a lapindrome.\n"; else cout << test_case << "is not a lapindrome.\n"; return 0; }
code/unclassified/src/lapindrom_checker/lapindrome_checker.py
# part of cosmos by opengenus foundation def isLapindrome(string): mid = len(string) // 2 delim = mid if len(string) % 2 == 1: delim += 1 # if string has odd number of characters first_half = string[:mid] second_half = string[delim:] first_half = "".join(sorted(first_half)) second_half = "".join(sorted(second_half)) return first_half == second_half testCase1 = "xyzyx" testCase2 = "abcdbba" if isLapindrome(testCase1): print("Lapindrome") else: print("Not a Lapindrome") if isLapindrome(testCase2): print("Lapindrome") else: print("Not a Lapindrome")
code/unclassified/src/leap_year/leap_year.c
#include <stdio.h> bool checkLeapYear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; if (year % 4 == 0) return true; return false; } int main() { int year1 , year2; printf("Enter the first year: "); scanf("%d",&year1); printf("Enter the second year year: "); scanf("%d",&year2); printf("The leap years between %d and %d are : \n",year1,year2); for(int i=year1 ; i<=year2 ; i++) { if(checkLeapYear(i)) { printf("%d\n",i); } } return 0; }
code/unclassified/src/leap_year/leap_year.cpp
#include <iostream> bool isLeapYear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; return year % 4 == 0; } void findLeapYears(int a, int b) { std::cout << "The leap years between " << a << " and " << b << " are : \n"; for (int i = a; i <= b; i++) if (isLeapYear(i)) std::cout << i << "\n"; } int main() { using namespace std; int year1, year2; cout << "Enter the first year: "; cin >> year1; cout << "Enter the second year year: "; cin >> year2; if (year1 > year2) findLeapYears(year2, year1); else findLeapYears(year1, year2); return 0; }
code/unclassified/src/leap_year/leap_year.cs
using System; namespace LeapTest { public class Program { private static bool isLeap(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } public static void Main() { int startYear, endYear; Console.Write("enter starting year : "); Int32.TryParse(Console.ReadLine(), out startYear); Console.Write("enter ending year : "); Int32.TryParse(Console.ReadLine(), out endYear); for(int i = startYear; i <= endYear; ++i) { if(isLeap(i)) { Console.WriteLine(i); } } } } }
code/unclassified/src/leap_year/leap_year.go
package main import "fmt" func IsLeapYear(year int) bool { if year%400 == 0 { return true } if year%100 == 0 { return false } if year%4 == 0 { return true } return false } func LeapYearsInRange(min, max int) []int { var res []int for i := min; i <= max; i++ { if IsLeapYear(i) { res = append(res, i) } } return res } func main() { res := LeapYearsInRange(2010, 2030) for _, year := range res { fmt.Println(year) } /* * Output: * 2012 * 2016 * 2020 * 2024 * 2028 */ }
code/unclassified/src/leap_year/leap_year.java
import java.io.InputStreamReader; import java.util.Scanner; class LeapYear { public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } public static void main(String []args) { Scanner in = new Scanner(new InputStreamReader(System.in)); System.out.println("Enter the starting year: "); int startyear = in.nextInt(); System.out.println("Enter the ending year: "); int endyear = in.nextInt(); for(int i = startyear; i <= endyear; ++i) if(isLeapYear(i)) System.out.println(i); in.close(); } }
code/unclassified/src/leap_year/leap_year.nim
func find_leap_year(start, last: int): seq[int] = for y in start..last: if (y mod 4 == 0 and y mod 100 != 0) or (y mod 400 == 0): result.add(y) when isMainModule: echo find_leap_year(2000, 2020)
code/unclassified/src/leap_year/leap_year.py
# This program takes two inputs (years) # and returns all leap years between them # using normal for...in loop and List Comprehension loop year_1 = int(input("Enter the first year: ")) year_2 = int(input("Enter the second year: ")) print("Normal way -----------------------------------") leaps = [] for y in range(year_1, year_2): if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0): leaps.append(y) print(leaps) # List Comprehension # [expression for item in interable if condition] print("List Comprehension way ---------------------------------------") leaps2 = [ y for y in range(year_1, year_2) if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0) ] print(leaps2)
code/unclassified/src/leap_year/leap_year.rs
// Part of Cosmos by OpenGenus // find_leap_year takes in 2 years as start and end value // and returns a vector containing the leap years between the given years. // [start, end); end year in not included fn find_leap_years(start: i32, end: i32) -> Vec<i32> { (start..end) .filter(|y| (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) .collect() } #[test] fn name() { assert_eq!( find_leap_years(2000, 2018), vec![2000, 2004, 2008, 2012, 2016] ); }
code/unclassified/src/leap_year/leap_years.js
function getLeapYears(start, end) { var startYear = Math.ceil(start / 4) * 4; var endYear = Math.floor(end / 4) * 4; var leapYears = []; if (isNaN(startYear) || isNaN(endYear)) return ['Invalid input']; while (startYear <= endYear) { if ( startYear % 100 || !(startYear % 400)) { leapYears.push(startYear); } startYear += 4; } return leapYears.length? leapYears : ['None']; }
code/unclassified/src/leap_year/readme.txt
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Leap year The aim is to find leap years between two given years which are taken as input from the user. Leap year is a year that contains 366 days. "A leap year (also known as an intercalary year or bissextile year) is a calendar year containing one additional day (or, in the case of lunisolar calendars, a month) added to keep the calendar year synchronized with the astronomical or seasonal year." To calculate which years will be leap years there are some conditions: -if a year is divisible by 4 and is not divisible by 100; -or; -if a year is divisible by 400; -then this year is a leap year; Source: https://en.wikipedia.org/wiki/Leap_year
code/unclassified/src/magic_square/magic_square.c
// Part of Cosmos by OpenGenus Foundation #include<stdio.h> #include<string.h> void MagicSquare(int n) { int magic[n][n],num; memset(magic, 0, sizeof(magic)); // Initialize position for 1 int i = n/2; int j = n-1; // One by one put all values in magic square for(num = 1; num <= n*n; ) { if (i==-1 && j==n) { j = n-2; i = 0; } else { // if next number goes to out of square's right side if (j == n) j = 0; //if next number goes to out of square's upper side if (i < 0) i=n-1; } if (magic[i][j]) { j -= 2; i++; continue; } else magic[i][j] = num++; //set number j++; i--; } // Print magic square printf("The Magic Square for n=%d:\nSum of each row or column %d:\n\n", n, n*(n*n+1)/2); for(i=0; i < n; i++) { for(j=0; j < n; j++) printf("%3d ", magic[i][j]); printf("\n"); } } int main() { int n = 7; // Works only when n is odd MagicSquare(n); return 0; }
code/unclassified/src/magic_square/magic_square.php
<?php /* Part of Cosmos by OpenGenus Foundation */ /* Usage: magicSquare(3); */ magicSquare(3); function magicSquare($num) { $magicSquare = array(); for ($row = 0; $row < $num; $row++) { for ($col = 0; $col < $num; $col++) { $rowMatrix = ((($num + 1) / 2 + $row + $col) % $num); $colMatrix = ((($num + 1) / 2 + $row + $num - $col - 1) % $num) + 1; $magicSquare[$row][$col] = ((($rowMatrix * $num) + $colMatrix)); } } foreach ($magicSquare as $rows) { echo implode("\t", $rows)."\r\n"; } }
code/unclassified/src/magic_square/magic_square.py
# MAgic Square generation for odd numbered squares import numpy as np N = input("Enter the dimension. Note that it should be odd : ") magic_square = np.zeros((N, N), dtype=int) n = 1 i, j = 0, N // 2 while n <= N ** 2: magic_square[i, j] = n n += 1 new_i, new_j = (i - 1) % N, (j + 1) % N if magic_square[new_i, new_j]: i += 1 else: i, j = new_i, new_j print(magic_square)
code/unclassified/src/magic_square/magic_square.swift
import Foundation let dimension = 5 // this should be an odd number var magicSquare = Array<Array<Int>>() for _ in 0..<dimension { magicSquare.append(Array<Int>(repeating: 0, count: dimension)) } var i = dimension / 2 var j = dimension - 1 var num = 1 while num < dimension * dimension { if i == -1 && j == dimension { j = dimension - 2 i = 0 } else { // if next number goes to out of square's right side if j == dimension { j = 0 } // if next number goes to out of square's upper side if i < 0 { i = dimension - 1 } } if magicSquare[i][j] != 0 { j = j - 2 i = i + 1 continue } else { magicSquare[i][j] = num // set number num = num + 1 } j = j + 1 i = i - 1 } for row in magicSquare { print(row) }
code/unclassified/src/majority_element/majority_element.cpp
#include <iostream> #include <vector> using namespace std; int n; vector<int> v; int main() { cin >> n; for (int i = 0; i < n; i++) { int tmp; cin >> tmp; v.push_back(tmp); } int m, i = 0; for (int k = 0; k < n; k++) { int x = v[k]; if (!i) { m = x; i = 1; } else if (m == x) i++; else i--; } cout << "The majority element is: " << m; return 0; }
code/unclassified/src/majority_element/majority_element_randomized.cpp
#include <iostream> #include <vector> using namespace std; int n; vector<int> v; // Randomized algorithm with expected runtime: O(n), and Space: O(1) int majorityElement(vector<int>& nums) { int pos = 0, n = nums.size(), freq; while(1) { freq = 0; for(int x : nums)if(x == nums[pos])++freq; if(freq > n / 2) return nums[pos]; pos = rand() % n; } } int main() { cin >> n; for (int i = 0; i < n; i++){ int tmp; cin >> tmp; v.push_back(tmp); } cout << "The majority element is: " << majorityElement(v); return 0; }
code/unclassified/src/maximum_subarray_sum/maximum_subarray_sum.cpp
// Part of Cosmos by OpenGenus Foundation // C++ implementation of simple algorithm to find // Maximum Subarray Sum in a given array // this implementation is done using Kadane's Algorithm which has a time complexity of O(n) #include <iostream> #include <vector> #include <climits> int maxSubarraySum(const std::vector<int>& arr) { int maxSumSoFar = INT_MIN; int currMax = 0; for (int element : arr) { currMax += element; if (maxSumSoFar < currMax) maxSumSoFar = currMax; if (currMax < 0) // if the current maximum sum becomes less than 0 then we make it 0 to represent an empty subarray currMax = 0; } return maxSumSoFar; } int main() { int n; std::cin >> n; std::vector<int> v(n); for (int i = 0; i < n; ++i) { int x; std::cin >> x; v[i] = x; } int answer = maxSubarraySum(v); std::cout << "Maximum subarray sum is " << answer << '\n'; return 0; }
code/unclassified/src/median_of_two_sorted_arrays/median_of_two_sorted_arrays.c
#include <math.h> #include <stdio.h> int main() { int t; scanf("%d", &t); for (int i = 0; i < t; ++i) { int n; scanf("%d", &n); int a[n], temp; for (int i = 0; i < n; ++i) //input { scanf("%d", &a[i]); } for (int i = 0; i < n; ++i) //sorting { for (int j = i + 1; j < n; ++j) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } float median; if (n % 2 != 0) { median = floor(a[(n) / 2]); } else { median = floor((a[n / 2] + a[(n - 1) / 2]) / 2); } printf("%f\n", floor(median)); } return 0; }
code/unclassified/src/median_two_sortedArrayOfDifferentLength/medianOfTwoSortedArrayOfDifferentLength.cpp
#include <bits/stdc++.h> using namespace std; double findMedian(int arr1[], int n1, int arr2[], int n2) { int lo = 0, hi = n1; while (lo <= hi) { int cut1 = lo + (hi - lo) / 2; int cut2 = (n1 + n2) / 2; double l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1]; double l2 = cut2 == 0 ? INT_MIN : arr2[cut2 - 1]; double r1 = cut1 == 0 ? INT_MAX : arr1[cut1]; double r2 = cut2 == 0 ? INT_MAX : arr2[cut2]; if (l1 > r2) { hi = cut1 - 1; } else if (l2 > r1) { lo = cut1 + 1; } else { if ((n1 + n2) % 2 == 0) { return ((max(l1, l2)) + (min(r1, r2))) / 2; } else { return min(r1, r2); } } return -1; } } int main() { int n1, n2; cin >> n1 >> n2; int arr1[n1], arr2[n2]; for (int i = 0; i < n1; i++) { cin >> arr1[i]; } for (int i = 0; i < n2; i++) { cin >> arr2[i]; } if (n2 > n1) cout << findMedian(arr1, n1, arr2, n2); else cout << findMedian(arr2, n2, arr1, n1); }
code/unclassified/src/merge_arrays/merge_arrays.cpp
#include <cstdlib> #include <iostream> #include <vector> void merge(std::vector<int> arr, std::vector<int> arr1, std::vector<int> arr2) { int k = 0; for (int val : arr1) { arr[k] = val; k++; } for (int val : arr2) { arr[k] = val; k++; } std::cout << "Merged array : \n"; for (int val : arr) std::cout << val << "\t"; } int main() { int n1, n2; std::cout << "Enter the size of array 1 : \n"; std::cin >> n1; std::cout << "Enter the size of array 2: \n"; std::cin >> n2; std::vector<int> arr1(n1); std::vector<int> arr2(n2); std::vector<int> arr(n1 + n2); std::cout << "Enter the values for array1 : \n"; for (int i = 0; i < n1; ++i) { int val; std::cin >> val; arr1[i] = val; } std::cout << "Enter the values for array2 : \n"; for (int i = 0; i < n2; ++i) { int val; std::cin >> val; arr2[i] = val; } merge(arr, arr1, arr2); } /*Sample Input Output Enter the size of array 1 : 5 Enter the size of array 2: 2 Enter the values for array1 : 10 12 14 16 18 Enter the values for array2 : -10 -20 Merged array : 10 12 14 16 18 -10 -20 */
code/unclassified/src/minimum_subarray_size_with_degree/minsubarraysizewithdegree.cpp
#include <iostream> #include <vector> #include <queue> #include <unordered_map> /* Part of Cosmos by OpenGenus Foundation */ using namespace std; int minSubArraySizeWithDegree(const vector<int> nums) { unordered_map <int, int> m; priority_queue<int> pq; int best_degree = 1, curr_best_degree = nums[0], i, j, s = nums.size(); for (int x = 0; x < s; x++) { m[nums[x]]++; if (m[nums[x]] > best_degree) best_degree = m[nums[x]]; } m.clear(); i = 0; j = 0; int n; m[nums[0]]++; while (i < s && j < s) { n = nums[j]; if (m[n] >= m[curr_best_degree]) curr_best_degree = n; if (m[curr_best_degree] < best_degree) { j++; m[nums[j]]++; } else { pq.push(-(j - i + 1)); m[nums[i]]--; i++; } } return -pq.top(); } #define pb push_back int main() { ios::sync_with_stdio(0); cin.tie(0); srand(time(NULL)); vector<int> v; for (int i = 0; i < 20; i++) { v.pb(rand() % 10); cout << v[i] << " "; } cout << endl; cout << minSubArraySizeWithDegree(v) << endl; return 0; }
code/unclassified/src/move_zeroes_to_end/move_zeroes_to_end.cpp
#include <cstdlib> #include <iostream> #include <vector> void move_zeroes(std::vector<int> arr, std::vector<int> a, int n) { int k = 0; for (int i = 0; i < n; ++i) { if (a[i] != 0) { arr.push_back(a[i]); k++; } } for (int i = k; i < n; ++i) { arr.push_back(0); } for (int i = 0; i < n; ++i) std::cout << arr[i] << " "; } int main() { int n; std::cout << "Enter the size of array : \n"; std::cin >> n; std::vector<int> a, arr; int val; std::cout << "Enter the values for the array : \n"; for (int i = 0; i < n; i++) { std::cin >> val; a.push_back(val); } move_zeroes(arr, a, n); return 0; } /*Sample Input-Output Enter the size of array : 8 Enter the values for the array : 12 0 18 13 0 0 11 0 12 18 13 11 0 0 0 0 */
code/unclassified/src/move_zeroes_to_end/move_zeroes_to_end.py
# Moving zeroes to the end of array ar = list(map(int, input("Enter the elements: ").split())) lis = [0] * len(ar) j = 0 for i in range(len(ar)): if ar[i] != 0: lis[j] = ar[i] j += 1 print("Final Array: ", *lis) # INPUT: # Enter the elements: 0 2 3 0 5 0 # OUTPUT: # Final Array: 2 3 5 0 0 0
code/unclassified/src/no_operator_addition/addition.c
#include <stdio.h> int add(int x, int y) { return printf("%*c%*c", x, '\r', y, '\r'); } int main() { // test cases int i, j; for(i = 1; i <= 3; i++) { for(j = 1; j <= 3; j++) { printf("%d + %d = %d \n", i, j, add(i, j)); } } }
code/unclassified/src/optimized_fibonacci/optimized_fibonacci.cpp
/* Fibonacci Series implemented using Memoization */ #include <iostream> long long fibonacci (int n) { static long long fib[100] = {}; // initialises the array with all elements as 0 fib[1] = 0; fib[2] = 1; if (n == 1 || n == 2) return fib[n]; else if (fib[n] != 0) return fib[n]; else { fib[n] = fibonacci (n - 1) + fibonacci (n - 2); return fib[n]; } } int main () { int n; std::cout << "Enter number of terms: "; std::cin >> n; for (int i = 1; i <= n; i++) std::cout << fibonacci (i) << std::endl; }
code/unclassified/src/paint_fill/paint_fill.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; void print_matrix(char matrix[][100], int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) cout << matrix[i][j]; cout << endl; } } void paint_fill(int i, int j, char dot, char colour, char matrix[][100], int n, int m) { if (matrix[i][j] != dot || i<0 || j<0 || i>n - 1 || j>m - 1) return; matrix[i][j] = colour; paint_fill(i + 1, j, dot, colour, matrix, n, m); paint_fill(i - 1, j, dot, colour, matrix, n, m); paint_fill(i, j + 1, dot, colour, matrix, n, m); paint_fill(i, j - 1, dot, colour, matrix, n, m); } int main() { int n, m; char matrix[100][100]; cout << "Enter N and M: "; cin >> n >> m; //enter matrix i.e. the image for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> matrix[i][j]; print_matrix(matrix, n, m); paint_fill(8, 13, '.', 'R', matrix, n, m); print_matrix(matrix, n, m); return 0; }
code/unclassified/src/palindrome/palindrome_check/palindrome.nim
func is_palindrome(str: string): bool = let length = str.len - 1 for i in 0..(length mod 2): if str[i] != str[length - i]: return false true from unicode import reversed func is_palindrome_str_rev(str: string): bool = str.reversed == str when isMainModule: assert("madam".is_palindrome) assert(not is_palindrome("nimrod")) assert("madam".is_palindrome_str_rev)
code/unclassified/src/palindrome/palindrome_check/palindrome.py
def main(): """ Determine whether or not a string is a palindrome. :print: 'That's a palindrome.' if the string is a palindrome, 'That isn't a palindrome' otherwise. """ input_str = input("Enter a string: ") if is_palindrome(input_str): print("That's a palindrome.") else: print("That isn't a palindrome.") def is_palindrome(string): """ Determine whether or not a string is a palindrome. :param string: string the characters to check :return: True if the string is a palindrome, False otherwise """ # check that the word is not one character or empty if len(string) <= 1: # if it gets to this statement, it's a palindrome return True # check if the characters at each index are the same if string[0] == string[-1]: # if it gets to this statement, it's a palindrome return is_palindrome(string[1:-1]) # Call the main function. if __name__ == "__main__": main()
code/unclassified/src/palindrome/palindrome_check/palindrome_check.c
#include <stdio.h> #include <string.h> int isPalindrome(char *arr) { int length = strlen(arr); int i, j; for(i = 0, j = length - 1; i < length / 2; ++i, --j) { if(arr[i] != arr[j]) { return 0; } } return 1; } int main() { printf("%d\n", isPalindrome("terabyte")); printf("%d\n", isPalindrome("nitin")); printf("%d\n", isPalindrome("gurkirat")); printf("%d\n", isPalindrome("lol")); // Output // 0 // 1 // 0 // 1 }
code/unclassified/src/palindrome/palindrome_check/palindrome_check.cpp
#include <iterator> #include <type_traits> #include <functional> namespace palindrome_check { template<typename _InputIter, typename _ValueNotEqualTo = std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>, typename _IterLess = std::less<_InputIter>> bool isPalindromeRecursive(_InputIter begin, _InputIter end) { if (begin != end) { --end; if (_IterLess()(begin, end)) { if (_ValueNotEqualTo()(*begin, *end)) return false; return isPalindromeRecursive<_InputIter, _ValueNotEqualTo, _IterLess>(++begin, end); } } return true; } template<typename _InputIter, typename _ValueNotEqualTo = std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>, typename _IterLess = std::less<_InputIter>> bool isPalindromeIterative(_InputIter begin, _InputIter end) { if (begin != end) { --end; while (_IterLess()(begin, end)) if (_ValueNotEqualTo()(*begin++, *end--)) return false; } return true; } template<typename _InputIter, typename _ValueNotEqualTo = std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>, typename _IterLess = std::less<_InputIter>> inline bool isPalindrome(_InputIter begin, _InputIter end) { // default is iterative return isPalindromeIterative<_InputIter, _ValueNotEqualTo, _IterLess>(begin, end); } } // palindrome_check
code/unclassified/src/palindrome/palindrome_check/palindrome_check.cs
using System; namespace Palindrome { class Program { public static bool isPalindrome(string str) { for (int i = 0, j = str.Length - 1; i < str.Length / 2; ++i, --j) { if(str[i] != str[j]) { return false; } } return true; } public static void Main() { Console.WriteLine(isPalindrome("lol")); // True Console.WriteLine(isPalindrome("lolwa")); // False } } }
code/unclassified/src/palindrome/palindrome_check/palindrome_check.java
/* checks whether a given string is palindrome or not */ import java.util.Scanner; public class palindrome_check { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String word = scan.nextLine(); if(word.equals(reverse(word))) System.out.println("yes it's a string"); else System.out.println("no itsn't a string"); } // reverses the given string public static String reverse(String word) { String new_word = ""; if(word.length() == 1) new_word = word; else { for(int i = word.length() - 1; i >= 0; i--) new_word += word.charAt(i); } return new_word; } }
code/unclassified/src/palindrome/palindrome_check/palindrome_check.js
function isPalindrome(str) { return [...str].reverse().join("") == str; } console.log(isPalindrome("lol")); console.log(isPalindrome("nitin")); console.log(isPalindrome("terabyte")); console.log(isPalindrome("tbhaxor")); // Output // true // true // false // false
code/unclassified/src/palindrome/palindrome_check/palindrome_check.rb
# careful using any variables named word, scoping gets weird def is_palindrome_recursive(word) # set both indices for iterating through the word word_start = 0 word_end = word.length - 1 # check that the word is not one character or empty if word_end != word_start # check that the word start index is less than the word end index if word_start < word_end # check if the characters at each index are the same return false if word[word_start] != word[word_end] # trim the word word[word_start] = '' word[word_end - 1] = '' # send the word back for another loop return is_palindrome_recursive(word) end end # if it gets to this statement, it's a palindrome true end def is_palindrome_iterative(word) # set both indices for iterating through the word word_start = 0 word_end = word.length - 1 # check that the word is not one character or empty if word_end != word_start # breaks when the indices reach one another while word_start < word_end # check if the characters at each index are the same return false if word[word_start] != word[word_end] # iterate both indices, bringing them towards the middle of the word word_start += 1 word_end -= 1 end return true end false end def is_palindrome(word) # use the iterative method as the default is_palindrome_iterative(word) end
code/unclassified/src/range_sum_of_BST/range_sum_of_bst.java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int rangeSumBST(TreeNode root, int low, int high) { if(root == null) return 0; int sum = 0; if(root.val >= low){ sum+=rangeSumBST(root.left,low,high); } if(root.val >= low && root.val <= high){ sum+=root.val; } if(root.val <= high){ sum+=rangeSumBST(root.right,low,high); } return sum; } }
code/unclassified/src/segregate_even_odd/segregate_even_odd.cpp
// Segregate all even numbers to left and odd numbers to right of the array #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> void even_odd(std::vector<int> a) { int i = 0; int j = a.size() - 1; while (i < j) { while (a[i] % 2 == 0 && i < j) i++; while (a[j] % 2 != 0 && i < j) j--; if (i < j) { std::swap(a[i], a[j]); i++; j--; } } std::cout << "After segregation : \n"; for (int i = 0; i < a.size(); ++i) std::cout << a[i] << " "; } int main() { int n; std::cout << "Enter the number of elements in array : "; std::cin >> n; std::vector<int> a(n); std::cout << "Enter the values of the elements : "; for (int i = 0; i < a.size(); ++i) { int val; std::cin >> val; a[i] = val; } even_odd(a); return 0; } /* Sample Input-Output Enter the number of elements in array : 8 Enter the values of the elements : 12 33 5 8 9 15 6 20 After segregation : 12 20 6 8 9 15 5 33 */
code/unclassified/src/segregate_even_odd/segregate_even_odd.py
# Implemented using Bubble Sort ar = list(map(int, input("Enter the elements: ").split())) n = len(ar) for i in range(n): swapped = False for j in range(0, n - i - 1): if ar[j] > ar[j + 1]: ar[j], ar[j + 1] = ar[j + 1], ar[j] swapped = True if not swapped: break print("The Final Array: ", *ar) # INPUT: # Enter the elements: -1 -2 4 8 2 -8 # OUTPUT: # The Final Array: -8 -2 -1 2 4 8
code/unclassified/src/segregate_positive_negative/segregate_positive_negative.cpp
// Segregate positive and negative numbers in an array // Here, we try to place all negative numbers to the left // and all positive elements to the right in O(n) time. // We can achieve this using Sorting also. But that takes O(nlogn) time. #include <iostream> #include <cstdlib> // Similar to the partition function in Quicksort // with pivot as 0 void segregate_pos_neg(int a[], int n) { int left = 0; int right = n - 1; while (1) { while (a[left] < 0 && left < right) left++; while (a[right] > 0 && left < right) right--; if (left < right) { int temp = a[left]; a[left] = a[right]; a[right] = temp; } else break; } } int main() { int n; std::cout << "Enter the size of the array : "; std::cin >> n; // allocating heap memory for array int *a = new int[n]; std::cout << "Enter the values of the array : \n"; for (int i = 0; i < n; i++) { std::cin >> a[i]; } segregate_pos_neg(a, n); std::cout << "Array after partition function\n"; for (int i = 0; i < n; i++) { std::cout << a[i] << "\t"; } } /* Enter the size of the array : 8 Enter the values of the array : -1 4 5 9 -12 -15 7 21 Array after partition function -1 -15 -12 9 5 4 7 21 */
code/unclassified/src/smallest_number_to_the_left/smallest.cpp
//Part of Cosmos by OpenGenus Foundation // C++ implementation of simple algorithm to find // smaller element on left side #include <iostream> #include <stack> using namespace std; // Prints smaller elements on left side of every element void printPrevSmaller(int arr[], int n) { // Create an empty stack stack<int> S; // Traverse all array elements for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.top() >= arr[i]) S.pop(); // If all elements in S were greater than arr[i] if (S.empty()) cout << "_, "; else //Else print the nearest smaller element cout << S.top() << ", "; // Push this element S.push(arr[i]); } } int main() { int arr[] = {1, 3, 0, 2, 5}; int n = sizeof(arr) / sizeof(arr[0]); printPrevSmaller(arr, n); return 0; }
code/unclassified/src/spiral_print/README.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Spiral Printing The aim is to print a given 2D array in spiral form. We take the dimensions of the array and the array as an input from the user. Dimensions of matrix are taken as mxn where m are the number of rows and n are the number of columns of the matrix. To print the matrix in spiral form we first keep a variable direction which can take 4 possible values : 0,1,2,3. 0 means we will print the first row from top which is not printed yet , 1 means first column from right, 2 means first rwo from bottom and 3 means first column from left. We will also be keeping four variables top,bottom,left and right initialised with 0,m-1,0,n-1 respectively which will give us the index of the extremes to be printed. -When direction = 0 , we print the top row from index left to right and we increment top by 1 -When direction = 1 , we print the right column from index top to bottom and we decrement right by 1 -When direction = 2 , we print the bottom row from index right to left and we decrement bottom by 1 -When direction = 3 , we print the left column from index bottom to top and we increment left by 1 # Example Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/spiral_print/spiral_print.c
#include <stdio.h> #include <stdlib.h> #include <time.h> // Part of Cosmos by OpenGenus Foundation void printSpiral(int N, int M, int[][M]); void print(int N, int M, int[][M]); int main() { srand(time(NULL)); const int N = 5; const int M = 5; int matrix[N][M]; // if you change N & M values, use malloc() int i, j; for(i = 0; i < N; i++) for(j = 0; j < M; j++) matrix[i][j] = rand()%100; //I'm filling the matrix with random numbers print(N, M, matrix); printf("\n"); printSpiral(N, M, matrix); } /* * Direction values: * 0: from left to right * 1: from top to bottom * 2: from right to left * 3: from bottom to top */ void print(int N, int M, int matrix[][M]) { int i, j; for(i = 0; i < N; i++) { for(j = 0; j < M; j++) printf("%d ", matrix[i][j]); printf("\n"); } } void printSpiral(int N, int M, int matrix[][M]) { int top = 0, bottom = N-1, left = 0, right = M-1; int direction = 0; int i; while(top <= bottom && left <= right) { //printf("\ndir: %d\n", direction); switch(direction) { case 0: for(i = left; i <= right; i++) printf("%d ", matrix[top][i]); top++; break; case 1: for(i = top; i <= bottom; i++) printf("%d ", matrix[i][right]); right--; break; case 2: for(i = right; i >= left; i--) printf("%d ", matrix[bottom][i]); bottom--; break; case 3: for(i = bottom; i >= top; i--) printf("%d ", matrix[i][left]); left++; break; } direction = (direction + 1) % 4; //if direction equals 3 it becomes 0, it increases by one otherwise } printf("\n"); }
code/unclassified/src/spiral_print/spiral_print.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <sstream> std::string spiralPrint(std::vector<std::vector<int>> vec, int row, int col) { int begRow = 0, endRow = row - 1, begCol = 0, endCol = col - 1; std::ostringstream res; while (begRow <= endRow && begCol <= endCol) { // Print the start row for (int i = begCol; i <= endCol; ++i) res << vec[begRow][i] << " "; ++begRow; // Print the end col for (int i = begRow; i <= endRow; ++i) res << vec[i][endCol] << " "; --endCol; // Print the end row if (endRow >= begRow) { for (int i = endCol; i >= begCol; --i) res << vec[endRow][i] << " "; --endRow; } // Print the start col if (begCol <= endCol) { for (int i = endRow; i >= begRow; --i) res << vec[i][begCol] << " "; ++begCol; } } auto s = res.str(); if (!s.empty()) s.pop_back(); return s; }
code/unclassified/src/spiral_print/spiral_print.go
package main import "fmt" // Part of Cosmos by OpenGenus Foundation func PrintSpiral(list [][]int, rows, cols int) { var T, B, L, R, dir int = 0, rows - 1, 0, cols - 1, 0 for { if T >= B || L >= R { break } // 0 - traverse right (going Left to Right) if dir == 0 { for i := 0; i <= R; i++ { fmt.Println(list[T][i]) } T++ dir = 1 } // 1 - traverse down (going Top to Bottom) if dir == 1 { for i := T; i <= B; i++ { fmt.Println(list[i][R]) } R-- dir = 2 } // 2 - traverse left if dir == 2 { for i := R; i >= L; i-- { //fmt.Println("---> ", R, i) fmt.Println(list[B][i]) } B-- dir = 3 } // 3 - traverse up if dir == 3 { for i := B; i >= T; i-- { fmt.Println(list[i][L]) } L++ dir = 0 } } } func main() { l := [][]int{ {2, 4, 6, 8}, {5, 9, 12, 16}, {1, 11, 5, 9}, {3, 2, 1, 8}, } m := len(l) // number of rows n := len(l) // number of columns PrintSpiral(l, m, n) }
code/unclassified/src/spiral_print/spiral_print.java
class Main { private static void printSpiralOrder(int[][] mat) { // base case if (mat == null || mat.length == 0) { return; } int top = 0, bottom = mat.length - 1; int left = 0, right = mat[0].length - 1; while (true) { if (left > right) { break; } // print top row for (int i = left; i <= right; i++) { System.out.print(mat[top][i] + " "); } top++; if (top > bottom) { break; } // print right column for (int i = top; i <= bottom; i++) { System.out.print(mat[i][right] + " "); } right--; if (left > right) { break; } // print bottom row for (int i = right; i >= left; i--) { System.out.print(mat[bottom][i] + " "); } bottom--; if (top > bottom) { break; } // print left column for (int i = bottom; i >= top; i--) { System.out.print(mat[i][left] + " "); } left++; } } public static void main(String[] args) { int[][] mat = { { 1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; printSpiralOrder(mat); } }
code/unclassified/src/spiral_print/spiral_print.py
from __future__ import print_function """ Part of Cosmos by OpenGenus Foundation """ matrix = lambda x: list(map(list, zip(*[iter(range(1, x * x + 1))] * x))) """ matrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] """ def main(size): a = matrix(size) center = int(size / 2) r = c = center l = 1 while l <= center: while c <= center + l: # right print(a[r][c]) c += 1 c -= 1 r += 1 while r <= center + l: # down print(a[r][c]) r += 1 r -= 1 c -= 1 while c >= center - l: # left print(a[r][c]) c -= 1 c += 1 r -= 1 while r >= center - l: # up print(a[r][c]) r -= 1 r += 1 c += 1 l += 1 for i in a[r][c:]: print(i) main(5) # One can change the size and matrix accordingly
code/unclassified/src/split_list/split_array.js
function splitArray(array, parts) { let subArray = []; for (let i = 0; i <= array.length; i += parts) { subArray.push(array.slice(i, i + parts)); } if (subArray[subArray.length - 1].length == 0) { subArray.pop(); } return subArray; } for (let x = 1; x <= 10; ++x) { console.log(splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], x)); }
code/unclassified/src/split_list/split_list.py
""" Function script to split a list in n parts This function can be reused in any project or script. If you have the following list: [1,2,3,4,5,6,7,8,9,10] and want to break it in 5 parts, you should do: >>> new_list = [1,2,3,4,5,6,7,8,9,10] >>> print breaker(new_list, 5) And you should get: [[1,2], [3,4], [5,6], [7,8], [9,10]] """ def breaker(array, parts): return list( array[part * len(array) / parts : (part + 1) * len(array) / parts] for part in range(parts) )
code/unclassified/src/sum_numbers_string/sum_numbers_string.cpp
// Given a string containing alphanumeric characters, calculate sum of all // numbers present in the string. #include <cctype> #include <cstdlib> #include <iostream> int sumNumbersString(std::string s) { int sum = 0; std::string str = ""; for (int i = 0; i < s.length(); i++) { if (isdigit(s[i])) { str += s[i]; if (!isdigit(s[i + 1])) { int n = std::stoi(str); sum += n; str = ""; } } } return sum; } int main() { std::string s; std::cout << "Enter the string : "; std::cin >> s; std::cout << "The sum of numbers present in the string : " << sumNumbersString(s); return 0; } /*Sample Input-Output Enter the string : this12is3just67another1string2 The sum of numbers present in the string : 85 */
code/unclassified/src/tokenizer/tokenizer.cpp
#include <iostream> #include <string> // Part of Cosmos by OpenGenus Foundation using namespace std; string myStrTok(char *input, char delim) { static char* ptr; if (input != nullptr) ptr = input; if (ptr == nullptr) return ""; string output = ""; int i; for (i = 0; ptr[i] != '\0'; i++) { if (ptr[i] == delim) { output[i] = '\0'; // for the case that the delimiter occurs multiple times. while (ptr[i] == delim) i++; ptr = ptr + i; return output; } output += ptr[i]; } ptr = nullptr; return output; } int main() { char in[] = "Hello this is a string tokenizer!"; string ans = myStrTok(in, ' '); while (ans != "") { std::cout << ans << "\n"; ans = myStrTok(nullptr, ' '); } char arr[] = "Hello world!"; ans = myStrTok(arr, ' '); cout << "\n" << ans << "\n"; ans = myStrTok(nullptr, ' '); cout << "\n" << ans << "\n"; return 0; }
code/unclassified/src/unique_number/unique_num_stl.cpp
#include <algorithm> #include <iostream> #include <vector> int main() { int n, i; std::cin >> n; // size of array element std::vector<int> arr(n); // declaration of vector for (i = 0; i < n; ++i) { std::cin >> arr[i]; // input } std::sort(arr.begin(), arr.end()); // sort the vector std::vector<int>::iterator it = unique(arr.begin(), arr.end()); arr.resize(distance(arr.begin(), it)); // resizing the array std::cout << arr.size() << "\n"; // display the size of the updated element. for (i = 0; i < arr.size(); ++i) { std::cout << arr[i] << " "; // display of unique elements in the array } }
code/unclassified/src/unique_number/unique_number.cpp
#include <algorithm> #include <iostream> #include <cstdlib> #include <vector> void display_unique(std::vector<int> arr, int n) { sort(arr.begin(), arr.end()); for (int i = 0; i < n; ++i) { while (i < n - 1 && arr[i] == arr[i + 1]) i++; std::cout << arr[i] << " "; } } int main() { int n, val; std::cout << "Enter the size of array : \n"; std::cin >> n; std::vector<int> arr; cout << "Enter the values for the array : \n"; for (int i = 0; i < n; ++i) { std::cin >> val; arr.push_back(val); } std::cout << "The unique elements are : \n"; display_unique(arr, n); return 0; } /*Sample Input- Output Enter the size of array : 5 Enter the values for the array : 12 34 15 12 16 The unique elements are : 12 15 16 34 */
code/unclassified/src/unique_number/unique_number.java
import java.util.*; public class UniqueNumber { public static void main(String[] args) { // token array to search int[] a = new int[10]; System.out.println(uniqueNumber(a)); } public int uniqueNumber(int[] a) { Map<Integer, Integer> numbers = new HashMap<Integer, Integer>(); for (int i=0; i<a.length; i++) { numbers.put(a[i], numbers.getOrDefault(a[i], 0) + 1); } for (int i=0; i<a.length; i++) { if (numbers.get(a[i]) != 3) { return numbers[i]; } } return -1; }
code/unclassified/src/unique_number/unique_number.py
# Unique numbers in an array l1 = list(map(int, input("Enter the elements: ").split())) uniq_list = [] for i in l1: if i not in uniq_list: uniq_list.append(i) print("Unique elements: ", *(uniq_list)) # INPUT: # Enter the elements: 1 2 2 3 4 5 5 # OUTPUT: # Unique elements: 1 2 3 4 5
code/unclassified/src/unique_numbers/unique_numbers.py
# Unique numbers in an array l1 = list(map(int, input("Enter the elements: ").split())) uniq_list = [] for i in l1: if i not in uniq_list: uniq_list.append(i) print("Unique elements: ", *(uniq_list)) # INPUT: # Enter the elements: 1 2 2 3 4 5 5 # OUTPUT: # Unique elements: 1 2 3 4 5
code/unclassified/src/utilities/convert2mp3.sh
#!/usr/bin/bash # A program that converts all media into 320kbps mp3 file. # I use it to organize my media in a common format and common bitrates. # Author: Adithya Bhat [[email protected]] # Dependencies: # Please install ffmpeg on your machine for the program to work # Usage: # $ convert2mp3 webm m4a # Converts all .webm, .m4a media files to .mp3 files and deletes the # original files after successful conversion. bitrate=320k format=mp3 delete=false for i do for file in *."$i" do ffmpeg -i "$file" -f $format -b:a $bitrate "`basename "$file" ."$i"`.$format" 2>/dev/null if [ $delete == true ]; then if [ $? -eq 0 ]; then rm "$file" fi fi done done
code/unclassified/src/utilities/download_link.sh
#!/usr/bin/bash # A program that downloads the link in your clipboard. # I use it to download links that I have copied. # Author: Adithya Bhat [[email protected]] # Dependencies: # Please install xclip and/or one of {axel,aria2c} on your machine to maximize the # download speeds. # Usage: # $ download # Downloads the last thing copied to the clipboard. if [ $(which axel 2>/dev/null) ]; then axel -an 32 "`xclip -o`" elif [ $(which aria2c 2>/dev/null) ]; then aria2c -x 8 -s 32 `xclip -o` else wget "`xclip -o`" fi
code/unclassified/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/unclassified/test/palindrome/palindrome_check/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/unclassified/test/palindrome/palindrome_check/test_palindrome_check.cpp
#include <iostream> #include <string> #include <vector> #include <map> #include <cassert> #include "../../../src/palindrome/palindrome_check/palindrome_check.cpp" using namespace std; using namespace palindrome_check; // for test struct MapValueEqual { bool operator()(std::pair<int, int> const &a, std::pair<int, int> const &b) const { return a.second != b.second; } }; template<typename _Type> struct GreaterEqual { bool operator()(typename _Type::iterator a, typename _Type::iterator b) const { return (*a).first < (*b).first; } }; void testTrueRecursive() { string sz = ""; assert(isPalindromeRecursive(sz.begin(), sz.end())); string s = "1221"; assert(isPalindromeRecursive(s.begin(), s.end())); string s2 = "12321"; assert(isPalindromeRecursive(s2.begin(), s2.end())); vector<int> v = {1, 2, 2, 1}; assert(isPalindromeRecursive(v.begin(), v.end())); vector<int> v2 = {1, 2, 3, 2, 1}; assert(isPalindromeRecursive(v2.begin(), v2.end())); int *ivz = nullptr; assert(isPalindromeRecursive(ivz, ivz)); int *iv = new int(4); *iv = 1; *(iv + 1) = 2; *(iv + 2) = 2; *(iv + 3) = 1; assert(isPalindromeRecursive(iv, iv + 4)); int *iv2 = new int(5); *iv2 = 1; *(iv2 + 1) = 2; *(iv2 + 2) = 3; *(iv2 + 3) = 2; *(iv2 + 4) = 1; assert(isPalindromeRecursive(iv2, iv2 + 5)); int ivaz[0]; assert(isPalindromeRecursive(ivaz, ivaz)); int iva[4] = {1, 2, 2, 1}; assert(isPalindromeRecursive(iva, iva + 4)); int iva2[5] = {1, 2, 3, 2, 1}; assert(isPalindromeRecursive(iva2, iva2 + 5)); map<int, int> se; se[1] = 1; se[2] = 2; se[4] = 2; se[5] = 1; assert((isPalindromeRecursive<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); se[3] = 3; assert((isPalindromeRecursive<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); } void testFalseRecursive() { string s = "1231"; assert(!isPalindromeRecursive(s.begin(), s.end())); string s2 = "12331"; assert(!isPalindromeRecursive(s2.begin(), s2.end())); vector<int> v = {1, 2, 3, 1}; assert(!isPalindromeRecursive(v.begin(), v.end())); vector<int> v2 = {1, 2, 3, 3, 1}; assert(!isPalindromeRecursive(v2.begin(), v2.end())); int *iv = new int(4); *iv = 1; *(iv + 1) = 2; *(iv + 2) = 3; *(iv + 3) = 1; assert(!isPalindromeRecursive(iv, iv + 4)); int *iv2 = new int(5); *iv2 = 1; *(iv2 + 1) = 2; *(iv2 + 2) = 3; *(iv2 + 3) = 3; *(iv2 + 4) = 1; assert(!isPalindromeRecursive(iv2, iv2 + 5)); int iva[4] = {1, 2, 3, 1}; assert(!isPalindromeRecursive(iva, iva + 4)); int iva2[5] = {1, 2, 3, 3, 1}; assert(!isPalindromeRecursive(iva2, iva2 + 5)); map<int, int> se; se[1] = 1; se[2] = 2; se[4] = 3; se[5] = 1; assert(!(isPalindromeRecursive<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); se[3] = 3; assert(!(isPalindromeRecursive<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); } void testTrueIterative() { string sz = ""; assert(isPalindrome(sz.begin(), sz.end())); string s = "1221"; assert(isPalindrome(s.begin(), s.end())); string s2 = "12321"; assert(isPalindrome(s2.begin(), s2.end())); vector<int> v = {1, 2, 2, 1}; assert(isPalindrome(v.begin(), v.end())); vector<int> v2 = {1, 2, 3, 2, 1}; assert(isPalindrome(v2.begin(), v2.end())); int *ivz = nullptr; assert(isPalindrome(ivz, ivz)); int *iv = new int(4); *iv = 1; *(iv + 1) = 2; *(iv + 2) = 2; *(iv + 3) = 1; assert(isPalindrome(iv, iv + 4)); int *iv2 = new int(5); *iv2 = 1; *(iv2 + 1) = 2; *(iv2 + 2) = 3; *(iv2 + 3) = 2; *(iv2 + 4) = 1; assert(isPalindrome(iv2, iv2 + 5)); int ivaz[0]; assert(isPalindrome(ivaz, ivaz)); int iva[4] = {1, 2, 2, 1}; assert(isPalindrome(iva, iva + 4)); int iva2[5] = {1, 2, 3, 2, 1}; assert(isPalindrome(iva2, iva2 + 5)); map<int, int> se; se[1] = 1; se[2] = 2; se[4] = 2; se[5] = 1; assert((isPalindrome<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); se[3] = 3; assert((isPalindrome<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); } void testFalseIterative() { string s = "1231"; assert(!isPalindrome(s.begin(), s.end())); string s2 = "12331"; assert(!isPalindrome(s2.begin(), s2.end())); vector<int> v = {1, 2, 3, 1}; assert(!isPalindrome(v.begin(), v.end())); vector<int> v2 = {1, 2, 3, 3, 1}; assert(!isPalindrome(v2.begin(), v2.end())); int *iv = new int(4); *iv = 1; *(iv + 1) = 2; *(iv + 2) = 3; *(iv + 3) = 1; assert(!isPalindrome(iv, iv + 4)); int *iv2 = new int(5); *iv2 = 1; *(iv2 + 1) = 2; *(iv2 + 2) = 3; *(iv2 + 3) = 3; *(iv2 + 4) = 1; assert(!isPalindrome(iv2, iv2 + 5)); int iva[4] = {1, 2, 3, 1}; assert(!isPalindrome(iva, iva + 4)); int iva2[5] = {1, 2, 3, 3, 1}; assert(!isPalindrome(iva2, iva2 + 5)); map<int, int> se; se[1] = 1; se[2] = 2; se[4] = 3; se[5] = 1; assert(!(isPalindrome<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); se[3] = 3; assert(!(isPalindrome<map<int, int>::iterator, MapValueEqual, GreaterEqual<map<int, int>>>(se.begin(), se.end()))); } int main() { testTrueRecursive(); testFalseRecursive(); testTrueIterative(); testFalseIterative(); return 0; } // */
code/unclassified/test/spiral_printing/test_spiral_print.cpp
#include "../../src/spiral_print/spiral_print.cpp" #include <cassert> int main() { using namespace std; vector<vector<int>> vec; // empty test assert("" == spiralPrint(vec, 0, 0)); /* row test (even col) * 1 2 3 4 5 6 * 7 8 9 10 11 12 * 13 14 15 16 17 18 * 19 20 21 22 23 24 */ vec.push_back({1, 2, 3, 4, 5, 6}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 4 5 6"); vec.push_back({7, 8, 9, 10, 11, 12}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 4 5 6 12 11 10 9 8 7"); vec.push_back({13, 14, 15, 16, 17, 18}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11"); vec.push_back({19, 20, 21, 22, 23, 24}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 4 5 6 12 18 24 23 22 21 20 19 13 7 8 9 10 11 17 16 15 14"); /* row test (odd col) * 1 2 3 * 4 5 6 * 7 8 9 */ vec.clear(); vec.push_back({1, 2, 3}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3"); vec.push_back({4, 5, 6}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 6 5 4"); vec.push_back({7, 8, 9}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 6 9 8 7 4 5"); /* col test * 1 * 2 * 3 */ vec.clear(); vec.push_back({1}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1"); vec.push_back({2}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2"); vec.push_back({3}); assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3"); return 0; }
generate_dependencies.make
#for Cpp .PHONY: all generate_dependency append_command all: generate_dependency append_command; G++FLAGS = -Wall -std=c++11 # warning: the '^^^^^^^^^^' cannot be used in file-name COSMOS_ROOT_PATH := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) RECOVER-NAME = $(subst ^^^^^^^^^^,\ ,$(strip $1)) RECOVER-NAME2 = $(subst ^^^^^^^^^^,\\\ ,$(strip $1)) CONVERT-CPP-TO-DEPENDENCY-NAME = $(subst .cpp,.d,$(1)) CONVERT-DEPENDENCY-TO-CPP-NAME = $(subst .d,.cpp,$(1)) FIND-CPP-TESTS = $(shell find "$(COSMOS_ROOT_PATH)/code/" -name "test_*.cpp" | sed 's: :^^^^^^^^^^:g') FIND-CPP-SOURCES = $(filter-out $(cpp_tests),$(cpp_all_files)) FIND-CPP-TEST-DEPENDENCIES = $(shell find "$(COSMOS_ROOT_PATH)/code/" -name "test_*.d" | sed 's: :^^^^^^^^^^:g') FIND-CPP-SOURCE-DEPENDENCIES = $(filter-out $(cpp_test_dependencies),$(cpp_all_dependencies)) cpp_all_files = $(shell find "$(COSMOS_ROOT_PATH)/code/" -name "*.cpp" | sed 's: :^^^^^^^^^^:g') cpp_tests = $(call FIND-CPP-TESTS) cpp_sources = $(call FIND-CPP-SOURCES) # the var i is used for prevent if has same target name ins = $(eval i=$(shell echo $$(($(i)+1)))) # get dependencies of all files, # only contains one target:prerequisites in each file. # e.g. %.o: %.cpp other.cpp\n # generate dependencies # detail # GENERATE-SOURCE-DEPENDENCIES = @$(foreach file,$(cpp_sources),echo printf $(i) '>' $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # printf '${i}' > $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # echo $(CXX) -MM $(call RECOVER-NAME,$(file)) '>>' $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # $(CXX) -MM $(call RECOVER-NAME,$(file)) >> $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # echo "cat $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)))";\ # cat $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # printf $(i)$(notdir $(call RECOVER-NAME2,$(subst .cpp,.o,$(file))))" " >> dependencies_list;\ # echo $(call ins);\ # echo "";) # brief GENERATE-SOURCE-DEPENDENCIES = @$(foreach file,$(cpp_sources),printf '${i}' > $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ $(CXX) -MM $(call RECOVER-NAME,$(file)) >> $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ printf $(i)$(notdir $(call RECOVER-NAME2,$(subst .cpp,.o,$(file))))" " >> dependencies_list;\ $(call ins)) # append gcc script # detail # GENERATE-TEST-DEPENDENCIES = @$(foreach file,$(cpp_tests),echo printf $(i) '>' $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # printf '${i}' > $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # echo $(CXX) -MM $(call RECOVER-NAME,$(file)) '>>' $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # $(CXX) -MM $(call RECOVER-NAME,$(file)) >> $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # echo "cat $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)))";\ # cat $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ # printf $(i)$(notdir $(call RECOVER-NAME2,$(subst .cpp,.o,$(file))))" " >> dependencies_list;\ # echo $(call ins);\ # echo "";) # brief GENERATE-TEST-DEPENDENCIES = @$(foreach file,$(cpp_tests),printf '${i}' > $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ $(CXX) -MM $(call RECOVER-NAME,$(file)) >> $(call RECOVER-NAME,$(call CONVERT-CPP-TO-DEPENDENCY-NAME,$(file)));\ printf $(i)$(notdir $(call RECOVER-NAME2,$(subst .cpp,.o,$(file))))" " >> dependencies_list;\ $(call ins)) ############################################## # add target and prerequisites to dependencies ############################################## generate_dependency: @echo "\n###############################\n\ \r# generating dependencies ... #\n\ \r###############################" # clear list @printf "" > dependencies_list $(call GENERATE-SOURCE-DEPENDENCIES) $(call GENERATE-TEST-DEPENDENCIES) cpp_all_dependencies = $(shell find "$(COSMOS_ROOT_PATH)/code/" -name "*.d" | sed 's: :^^^^^^^^^^:g') cpp_test_dependencies = $(call FIND-CPP-TEST-DEPENDENCIES) cpp_source_dependencies = $(call FIND-CPP-SOURCE-DEPENDENCIES) # detail # APPEND-SOURCE-COMMAND = @$(foreach file,$(cpp_source_dependencies),echo '$(CXX) -c $(G++FLAGS) $(call RECOVER-NAME,$(call CONVERT-DEPENDENCY-TO-CPP-NAME,$(file)))' '>>' $(call RECOVER-NAME,$(file));\ # echo '\t$(CXX) -c $(G++FLAGS) $(call RECOVER-NAME,$(call CONVERT-DEPENDENCY-TO-CPP-NAME,$(file)))' >> $(call RECOVER-NAME,$(file));\ # echo "cat $(call RECOVER-NAME,$(file))";\ # cat $(call RECOVER-NAME,$(file));\ # echo "";) # APPEND-TEST-COMMAND = @$(foreach file,$(cpp_test_dependencies),echo '$(CXX) -o $(G++FLAGS) $(call RECOVER-NAME,$(call CONVERT-DEPENDENCY-TO-CPP-NAME,$(file)))' '>>' $(call RECOVER-NAME,$(file));\ # echo '\t$(CXX) -o $(G++FLAGS) $(call RECOVER-NAME,$(call CONVERT-DEPENDENCY-TO-CPP-NAME,$(file)))' >> $(call RECOVER-NAME,$(file));\ # echo "cat $(call RECOVER-NAME,$(file))";\ # cat $(call RECOVER-NAME,$(file));\ # echo "";) # brief APPEND-SOURCE-COMMAND = @$(foreach file,$(cpp_source_dependencies),echo '\t$(CXX) -c $(G++FLAGS) $(call RECOVER-NAME,$(call CONVERT-DEPENDENCY-TO-CPP-NAME,$(file)))' >> $(call RECOVER-NAME,$(file));) APPEND-TEST-COMMAND = @$(foreach file,$(cpp_test_dependencies),echo '\t$(CXX) -o $(G++FLAGS) $(call RECOVER-NAME,$(call CONVERT-DEPENDENCY-TO-CPP-NAME,$(file)))' >> $(call RECOVER-NAME,$(file));) ############################ # add command to dependencies ############################ append_command: @echo "\n##################################\n\ \r# generating_compile command ... #\n\ \r##################################" $(call APPEND-SOURCE-COMMAND) $(call APPEND-TEST-COMMAND)
guides/README.md
# Cosmos Guides > Your personal library of every algorithm and data structure code that you will ever encounter This folder contains various guidelines in terms of new documentation and coding style that are useful when contributing to this repository. The folder `coding_style` contains style guides for various programming languages. The file `documentation_guide.md` contains a guide for adding explanations/guides for new or existing algorithms. Finally, the folder `installation_guides` contains guides for installing various programming languages. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
guides/coding_style/README.md
# Cosmos Guides > Your personal library of every algorithm and data structure code that you will ever encounter This folder contains style guides for various programming languages. To find one specific to the language you are looking for, open the file `lang_name/README.md`. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
guides/coding_style/c#/README.md
# Cosmos Guides > Your personal library of every algorithm and data structure code that you will ever encounter Please follow the official Microsoft [C# coding guidelines](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions). --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
guides/coding_style/c#/tryCatch.md
--- Title: Try Catch Statement --- ## Try Catch in CSharp In the world of programming most of the time for the newbie, they only code in a linear way, assuming that it will be a good practice and most of the time learning to error exception handling is left behind. But it's only just a normal for newbie programmers as I came from the same shoes.:) Since I start developing I always thinking in linear way of coding until such time that my code is mixing up together. I really came accross to hardly maintain especially I don't have any error handlers before but now I always implement it in my bunch of code as necessary. In C# the try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program. You can read more from here in [MSDN](https://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.90).aspx). Going back! Here is my example of coding in C# for exception handling. ``` protected void btnSave_Click(object sender, EventArgs e) { var insCmd = new MySqlCommand("INSERT INTO user VALUES (@Id, @firstNm, @lastNm, @Role)", con); insCmd.Parameters.AddWithValue("@Id", txtId.Text); insCmd.Parameters.AddWithValue("@firstNm", txtFirstNm.Text); insCmd.Parameters.AddWithValue("@lastNm", txtLastNm.Text); insCmd.Parameters.AddWithValue("@Role", ddlRole.SelectedItem); try { con.Open(); insCmd.ExecuteNonQuery(); lblMessage.Visible = true; lblMessage.Text = "Successfully Saved!"; } catch (Exception ex) { lblMessage.Visible = true; lblMessage.Text = "Error: " + ex.Message; } con.Close(); txtFirstNm.Text = ""; txtLastNm.Text = ""; } ``` The above code is came from one of my web based project where try catch is execute a message error if there will be an invalid character to insert in the database. Through this strategy it will avoid your program or web application to crushed in an unexpected situation. Hope it helps!
guides/coding_style/c++/README.md
# Cosmos Guides > Your personal library of every algorithm and data structure code that you will ever encounter # C++ Style Guide > All demonstrates are VALID version ## Index - [Comments](#comments) - [Code Width and Alignment](#code-width-and-alignment) - [Spaces](#spaces) - [Indentations](#indentations) - [Newlines](#newlines) - [Braces](#braces) - [Naming](#naming) <details open> <summary>categories</summary> <ul> <li><a href="#file-names">File Names</a></li> <li><a href="#type-names">Type Names</a></li> <li><a href="#variable-names">Variable Names</a></li> <li><a href="#function-names">Function Names</a></li> <li><a href="#macro-names">Macro Names</a></li> <li><a href="#exceptions-to-naming-rules">Exceptions to Naming Rules</a></li> </ul> </details> - [Including Header Files](#including-header-files) - [Namespaces](#namespaces) - [Functions](#functions) - [Classes](#classes) - [Enumerations](#enumerations) - [Aliases](#aliases) ## Comments Single line comments should use the standard style (`//`), and multi line comments should use multiline comments (`/* */`). There should be a space between the comment delimiter and the comment text. ```C++ // Example text /* * * Multiline comment * */ /* * * Simple multiline comment * * vector synopsis * * template <class T, class Allocator = allocator<T> > * class vector * { * public: * using value_type = T; * using allocator_type = Allocator; * } */ ``` ## Code Width and Alignment - Try to limit code width to 100 characters. - Split lines as close to the code width as possible (if a parameter is split onto another line, then all of the parameters should be split). - If the width is less than or equal to the maximum code width, then do not split the line (unless split at return type or for readability). - Template definitions should be split. ```C++ // n <= 100 columns bool operator==(Container<Type, Allocator> x, Container<T, Allocator> y); bool operator==(Container<Type, Allocator> x, Container<T, Allocator> y); template<class OtherType, class OtherAllocator> bool operator==(Container<OtherType, OtherAllocator> x, Container<OtherType, OtherAllocator> y); template<class OtherType, class OtherAllocator> bool operator==(Container<OtherType, OtherAllocator> x, Container<OtherType, OtherAllocator> y); // n > 100 columns void cloneTwo(Container<Type, Allocator> foo,              Container<Type, Allocator> bar,              Container<Type, Allocator> baz); template<class OtherType, class OtherAllocator> void cloneTwo(Container<OtherType, OtherAllocator> foo,         Container<OtherType, OtherAllocator> bar,         Container<OtherType, OtherAllocator> baz); ``` - The pointers `*` `**` and references `&` `&&` `*&` should be part of the variable/function name (even if variable name is not declared) or qualifier. Add a space between previous types or qualifiers (unless `**`, `&&`, and `*&`). ```C++ // pointers and references int a = 0; int *pa = &a; int *&rpa = pa; int **ppa = &pa; int &&rr = 0; bool operator==(int *x, int *y); bool operator==(int *const *x, int *const *y); bool operator==(const int **const x, const int **const y); bool &getReference(); bool *&getPointer(); bool *const getConstPointer(); bool *const &getReferenceOfConstPointer(); // even if variable name is not declared bool operator==(int *&, int *&); bool operator==(int &&, int &&); ``` - The `const` qualifier should be on the right hand side of its target but to the left of the type. ```C++ class Dummy {       const int value() const;    void value(const int *const v); int *getPointer();    const int *const *getOtherPointer() const; }; ``` - The logical operators should be placed after their conditions if there are many of them. If adding parentheses makes your intent clearer then go ahead and add them. ```C++ void foo() { bool res = true; short i = 1; long sum_short = 1; while (i != 0 && ++i) sum_short += i; if (i == 0 && (0 == i)) res &= true; else res &= false; if ((1 != 0) && (1 == true || 0 == false)) res &= true; else res &= false; if (res != true || (!(res == true) || (res == false))) cout << "wrong\n"; } ``` ## Spaces Put one space: - After commas. - Between operators. - Between condition and its opening brace. - Around initializer of class constructor; Remove spaces: - In whitespace-only line. - After opening brace/parenthese, and before closing brace/parenthes. - Between empty braces, and parentheses. Be clear, the demo not follow the Newline rules: ```C++ while () // 1 space between while and '(', 0 space between parentheses. { // 0 space after opening brace-only line. if (true) // 1 space between if and '('. { ClassName obj{1, 2, 3}; // 0 space after '{', before '}'. int i = (1 + 1) * 1; // 1 space around '=', '+', and '*'. doSomthing(obj, i, 1); // 1 space after commas. } } // 0 space after closing brace-only line. ``` ## Indentations Use only spaces, and indent 4 spaces at a time. We use spaces for indentation. Do not use tabs in our code. ```C++ bool predicateFunc(vector<int> vec) { for (; condition; ) // 4 spaces if (condition) // 8 spaces return false; // 12 spaces // none space return true; // 4 spaces } ``` ## Newlines Add newline: - Between two functions, classes, and conditions. - After `#define`, `#include`. - Between preconditions and its scope (ignore between preconditions). ```C++ #include <iostream> #ifndef DDD // no newline between #ifndef and #define line #define DDD int func1(); int func2() { int a{1}, b{0}; if (a == b) // ... while (a - b > 0) // ... } class A; class B { public: int func1(); int func2() { // ... } private: int v1; bool v2; int func3(); } #endif ``` ## Braces When using braces, put them on their own lines. When loops or `if` statements have only one statement, omit the braces (unless between `do` and `while` on do-while statements or to disambiguate a dangling else). ```C++ int main() { if (condition) { statement; statement; } else statement; if (condition) { if (condition) statement; else statement; } for (;condition;) statement; do { statement; } while (condition); } ``` ## Naming Names should be descriptive and avoid abbreviations, unless the abbreviation is commonly known. ```C++ int errorFlag; int currentIter; // the certain universally-known abbrs ("Iter") are OK int numberDnsConnections; // ok, most people know what "DNS" stands for ``` ### File Names C++ file should end in .cpp and header file should end in .hpp (do not end in .h). ### Type Names Types should be named like PascalCase. ```C++ using VecI = std::vector<int>; template<typename _T> using VecTwo = std::vector<std::vector<_T>>; class PascalCase; struct PascalCase; union PascalCase; enum PascalCase; enum class PascalCase; ``` ### Variable Names Local variables should be named using standard camelCase. ```C++ int name; int camelCase; ``` Global variables should be avoided for the most part. If they are necessary, then they should be named using prefix 'g\_' and standard camelCase. ```C++ int g_name; int g_camelCase; ``` Class members should be _private_, add an underscore to the end of their name. ```C++ class PascalCase; { int name_; int camelCase_; }; ``` Constant variables should be named using PascalCase. ```C++ const int Name; constexpr int VariableName; enum class ExampleEnum { One, TwoTwo }; ``` ### Function Names Functions should be named using standard camelCase. ```C++ int name(); int camelCase(); class PascalCase { int doSomething(); }; ``` ### Macro Names When naming macros, use uppercase for all the letters, and separate words by underscores. ```C++ #define VALID #define UPPERCASE_VALID ``` ### Exceptions to Naming Rules If you are naming something that is analogous to an existing C++ entity then you can follow the existing naming convention scheme. ```C++ sparse_hash_set<> ... // STL-like entity; follows STL naming conventions long BUFFER_MAX ... // a constant, as in INT_MAX using diff_t ... // as in ptrdiff_t ``` ## Including Header Files When including header files, only include files that are _portable_ across all compilers (Unless where applicable). Do not include `<bits/stdc++.h>`. Pay attention to whether the header is _not in use_, and do not include it if so. If only the implementation uses it, then include the file in .cpp, not .hpp. ```C++ // sample1.hpp #include <vector> // ok, return type is vector template<typename Ty> std::vector<Ty> toVector(Ty t[], size_t sz); // sample2.hpp class ListHelp { void sort(); }; // sample2.cpp #include "sample2.hpp" #include <utility> // ok, only use the swap function in implementation using namespace std; void ListHelp::sort() { // use the swap function } ``` ## Namespaces When using namespaces, pay attention to name collisions/name conflicts: In header files, do not use a `using` directive or declaration. ```C++ // sample1.hpp #include <vector> // ok, if users include this file, they also need to declare std namespace to use member of vector template<typename Ty> std::vector<Ty> toVector(Ty t[], size_t sz); // sample2.hpp class ListHelp { void sort(); } // sample2.cpp #include "sample2.hpp" #include <utility> using namespace std; // ok, users will include .hpp not .cpp void ListHelp::sort() { // may use the swap function } ``` ## Functions ### Parameters When listing POD (Plain Old Data) types, pass them by value. When listing user-defined types, pass them by `const` reference. When a function has to modify a variable, then, and only then pass the variable by reference. ```C++ void exampleFunction(int pod, const Example& object, char& modifiableChar) { // ... } ``` ## Classes ### Order of Encapsulation When listing members of a class, if possible list them in the order public, private, then protected. If using `using` for aliases, or using base class constructors, then the order can be broken. In this case, if possible, try and list the public interface of the class first. Encapsulation labels should be indented to the same level as the class. Add a new line after the end of each label for readability. ```C++ class Example { private: using Int = int; protected: using typename BaseClass::size_type; public: // ... private: // ... protected: // ... }; ``` ### Order of Member Functions When listing member functions of a class, first list the main constructor, then secondary constructors, and then copy assignment/copy construction/move assignment/move construction functions. After this, add the destructor. Then, add a new line, and then list all members of the class. * When possible, try to create a logical separation of member functions for clarity. * If a class has all public members (not member functions), then use the `struct` keyword, otherwise use the `class` keyword. ```C++ class Example { public: Example() { } Example(int value) { } Example(const Example& other) { } ~Example() void memberFunction(); private: int value_; }; ``` ### Member Initializer List When declaring a constructor, use a member initializer list to initialize class members. ```C++ class Example { public: Example(int a, int b) : a_{a}, b_{b} { } private: int a_, b_; }; ``` ## Enumerations ### enum vs enum class When dealing with enumerations, use `enum class`, not `enum` (Unless dealing with unnamed enumerations or C style code). Warning: if you dealing with low-level operation, and need use explicit type convertion, you must be careful about underlying type (default is the `int` it at least 2-bytes). ## Aliases ### using vs typedef When dealing with aliases, use `using`, not `typedef`. Don't put alias in `public`, unless the aliases is guaranteed to always be the same as the type it's currently aliased to. - The `using` declaration can be read almost as an English sentence. - More easily declare an alias with template. - [See more comparisons](http://www.stroustrup.com/C++11FAQ.html#template-alias) --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
guides/coding_style/c++/uncrustify_tests/input/space001.cpp
#include <iostream> #include<vector> using namespace std; void bar(int,int,int) { // less space if(true) { vector<int> vec{1,2,3}; int i=(1+2)*3; } } void foo( ) { // more space if (true) { vector<int> vec{1 , 2 , 3}; int i = (1 + 2) * 3; bar (1 , 2 , 3); } while (true) for (int i = 0; i < 10; ++i) do cout << 123; while (true); int i = 1 ; switch (i) { case 1 : cout << 1 ; break ; default : break ; } }
guides/coding_style/c++/uncrustify_tests/output/space001.cpp
#include <iostream> #include <vector> using namespace std; void bar(int, int, int) { // less space if (true) { vector<int> vec{1, 2, 3}; int i = (1 + 2) * 3; } } void foo() { // more space if (true) { vector<int> vec{1, 2, 3}; int i = (1 + 2) * 3; bar(1, 2, 3); } while (true) for (int i = 0; i < 10; ++i) do cout << 123; while (true); int i = 1; switch (i) { case 1: cout << 1; break; default: break; } }
guides/coding_style/c++/uncrustify_tests/test.sh
for full_path_file in `find 'input' -name '*.cpp'` do # format file uncrustify -c ../../../../third_party/uncrustify.cfg $full_path_file # compare file input_file=$full_path_file'.uncrustify' output_file='output/'`basename $full_path_file` diff $input_file $output_file done
guides/coding_style/c/README.md
# Cosmos Guides > Your personal library of every algorithm and data structures code that you will ever encounter ## C Code style C is a general-purpose mid level, procedural computer programming language originally developed between 1969 and 1973 and founded by Dennis Ritchie in AT&T Labs in 1972. # C Programming Style Guide This code style is known as Kernel Normal Form (KNF). ## Index - [Braces](#braces) - [Indentation](#indentation) - [Conditionals](#conditionals) - [Functions](#functions) - [Comments](#comments) ## Braces All braces should go on the same line as whatever the braces are delimiting, with the only exception being functions. For if/else statements, braces should only be used as required. ```C int main(int argc, char *argv[]) { if (!some_function()) { puts("Something happened!"); do_a_thing(); } else { some_other_thing(); } return (0); } ``` *argc stands for arguments count(ARGument count) *argv stands for arguments values(ARGument values) *argv[0] is the name of the program ## Indentation Indentation is done with a single tab character (Hard Tab). For code split across multiple lines a helper indent of 4 spaces is used. ```C int some_really_long_function(int a, int b, int c, int d, int e, int f) { do_something(); ``` ## Conditionals ```C if (a == 9) { ``` ```C for (;;) ``` Each case in a switch statement should not be indented but the code for each should be. Any case fallthroughs should be commented. Every case should be terminated with a break statement. ```C switch (ch) { case 'a': a_count++; /* FALLTHROUGH */ case 'b': do_something(); break; case 'c' other_thing(); break; default: def_thing(); } ``` ## Functions Functions should have the type on a seperate line proceeding the rest of the function definition. ```C int main(int argc, char *argv[]) { //Block of Code //" " " //" " " } ``` Return statements should have the value wrapped in parenthesis. ```C return (0); ``` ## Comments Always use C style comments (`/* */`) and not C++ style comments (`//`). A sample is shown below. ```C /* One line comment */ /* * Multiline comment. Fill it out like it were * a paragraph. */ ``` --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---