filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/backtracking/src/number_of_ways_in_maze/number_of_ways_in_maze.c
#include<stdio.h> #define MAX_SIZE 10 /* * Part of Cosmos by OpenGenus Foundation */ ///i,j = current cell, m,n = destination void solveMaze(char maze[][10],int sol[][10],int i,int j,int m,int n,int *ways){ ///Base Case if(i==m && j==n){ sol[m][n] = 1; (*ways)++; ///Print the soln for(int i=0;i<=m;i++){ for(int j=0;j<=n;j++){ printf("%d ", sol[i][j]); } printf("\n"); } printf("\n"); return ; } if (sol[i][j]) { return; } ///Rec Case ///Assume there is a way from this cell sol[i][j] = 1; /// Try going Right if(j+1<=n && maze[i][j+1]!='X'){ solveMaze(maze,sol,i,j+1,m,n,ways); } /// Try going Left if(j-1>=0 && maze[i][j-1]!='X'){ solveMaze(maze,sol,i,j-1,m,n,ways); } /// Try going Up if(i-1>=0 && maze[i-1][j]!='X'){ solveMaze(maze,sol,i-1,j,m,n,ways); } /// Try going Down if(i+1<=m && maze[i+1][j]!='X'){ solveMaze(maze,sol,i+1,j,m,n,ways); } ///Backtracking! sol[i][j] =0; return; } int main(){ char maze[MAX_SIZE][MAX_SIZE] = { "00XXX", "00000", "0XX00", "000X0", "0X000" }; int m = 4,n=4; int sol[MAX_SIZE][MAX_SIZE]; int i,j; for (i = 0; i < MAX_SIZE; i++) { for (j = 0; j <MAX_SIZE; j++) { sol[i][j]=0; } } int ways=0; solveMaze(maze,sol,0,0,m,n,&ways); if(ways){ printf("Total ways %d\n", ways); } else{ printf("No ways\n"); } return 0; }
code/backtracking/src/number_of_ways_in_maze/number_of_ways_in_maze.cpp
#include <iostream> using namespace std; ///i,j = current cell, m,n = destination bool solveMaze(char maze[][10], int sol[][10], int i, int j, int m, int n, int &ways) { ///Base Case if (i == m && j == n) { sol[m][n] = 1; ways++; ///Print the soln for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) cout << sol[i][j] << " "; cout << endl; } cout << endl; return true; } ///Rec Case ///Assume jis cell pe khada hai vaha se rasta hai sol[i][j] = 1; /// Right mein X nahi hai if (j + 1 <= n && maze[i][j + 1] != 'X') { bool rightSeRastaHai = solveMaze(maze, sol, i, j + 1, m, n, ways); if (rightSeRastaHai) { // return true; } } /// Down jake dekho agr rasta nahi mila right se if (i + 1 <= m && maze[i + 1][j] != 'X') { bool downSeRastaHai = solveMaze(maze, sol, i + 1, j, m, n, ways); if (downSeRastaHai) { //return true; } } ///Agr code is line mein aagya ! - Backtracking sol[i][j] = 0; return false; } int main() { char maze[10][10] = { "00XXX", "00000", "0XX00", "000X0", "0X000" }; int m = 4, n = 4; int sol[10][10] = {0}; int ways = 0; solveMaze(maze, sol, 0, 0, m, n, ways); if (ways != 0) cout << "Total ways " << ways << endl; else cout << "Koi rasta nahi hai " << endl; return 0; }
code/backtracking/src/number_of_ways_in_maze/number_of_ways_in_maze.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" type Point struct { X int Y int } var totalWays int func SolveMaze(maze [][]byte, sol [][]byte, current, end Point, limitH, limitW int) { if maze[current.X][current.Y] == '1' { return } if sol[current.X][current.Y] == '1' { return } sol[current.X][current.Y] = '1' if current == end { totalWays++ for _, v := range sol { for _, k := range v { fmt.Printf("%c ", k) } fmt.Print("\n") } fmt.Print("\n") } if current.X+1 < limitH { current.X += 1 SolveMaze(maze, sol, current, end, limitH, limitW) current.X -= 1 } if current.X-1 >= 0 { current.X -= 1 SolveMaze(maze, sol, current, end, limitH, limitW) current.X += 1 } if current.Y+1 < limitW { current.Y += 1 SolveMaze(maze, sol, current, end, limitH, limitW) current.Y -= 1 } if current.Y-1 >= 0 { current.Y -= 1 SolveMaze(maze, sol, current, end, limitH, limitW) current.Y += 1 } sol[current.X][current.Y] = '0' return } func main() { maze := [][]byte{ {'0', '0', '1', '1', '1'}, {'0', '0', '0', '0', '0'}, {'0', '1', '1', '0', '0'}, {'0', '0', '0', '1', '0'}, {'0', '1', '0', '0', '0'}, } solution := [][]byte{ {'0', '0', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, } totalWays = 0 start := Point{X: 0, Y: 0} end := Point{X: 4, Y: 4} SolveMaze(maze, solution, start, end, 5, 5) fmt.Printf("There are %d ways to escape from (%d:%d) to (%d:%d)\n", totalWays, start.X, start.Y, end.X, end.Y) }
code/backtracking/src/number_of_ways_in_maze/number_of_ways_in_maze.java
/* * Part of Cosmos by OpenGenus Foundation */ public class RatMaze { final int N = 4; /* A function to print solution matrix sol[N][N] */ void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + sol[i][j] + " "); System.out.println(); } } /* A function to check if x,y is valid index for N*N maze */ boolean isSafe(int maze[][], int x, int y) { // if (x,y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1); } boolean solveMaze(int maze[][]) { int sol[][] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.print("Solution doesn't exist"); return false; } printSolution(sol); return true; } boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x,y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x,y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If none of the above movements work then BACKTRACK: unmark x,y as part of solution path */ sol[x][y] = 0; return false; } return false; } public static void main(String args[]) { RatMaze rat = new RatMaze(); int maze[][] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1} }; rat.solveMaze(maze); } }
code/backtracking/src/number_of_ways_in_maze/number_of_ways_in_maze.rs
extern crate nalgebra as na; extern crate num; use na::DMatrix; use na::Scalar; use na::dimension::Dynamic; use num::FromPrimitive; use std::fmt::Display; trait MazeSolve { fn solveMaze(&mut self, end: (usize, usize)); fn solveMazeRec(&mut self, pos: (usize, usize), end: (usize, usize), ways: &mut usize); fn printSolution(&self, end: (usize, usize)); } const BK: usize = 0; const BLOCK: usize = 1; const PASSED: usize = 2; static START: (usize, usize) = (0, 0); impl<S> MazeSolve for DMatrix<S> where S: Scalar + Display + FromPrimitive, { fn solveMaze(&mut self, end: (usize, usize)) { let mut ways: usize = 0; self.solveMazeRec(START, end, &mut ways); if ways != 0 { println!("Total ways: {}", ways); } else { println!("No way"); } } fn solveMazeRec(&mut self, pos: (usize, usize), end: (usize, usize), ways: &mut usize) { unsafe { *self.get_unchecked_mut(pos.0, pos.1) = FromPrimitive::from_usize(PASSED).unwrap(); } let check_move = [(0, 1), (1, 0)].to_vec(); if pos == end { *ways += 1; println!("Solution {}", *ways); self.printSolution(end); } else { for (m_x, m_y) in check_move { let after_mov = (pos.0 + m_x, pos.1 + m_y); if after_mov.0 <= end.0 && after_mov.1 <= end.1 { let self_at: S = FromPrimitive::from_usize(BLOCK).unwrap(); if self.iter() .enumerate() .filter(|i| { i.0 == after_mov.0 + after_mov.1 * (end.0 + 1) && *i.1 == self_at }) .count() == 0 { self.solveMazeRec(after_mov, end, ways); } } } } unsafe { *self.get_unchecked_mut(pos.0, pos.1) = FromPrimitive::from_usize(BK).unwrap(); } } fn printSolution(&self, end: (usize, usize)) { for (idx, item) in self.iter().enumerate() { let bk: S = FromPrimitive::from_usize(BK).unwrap(); let block: S = FromPrimitive::from_usize(BLOCK).unwrap(); let passed: S = FromPrimitive::from_usize(PASSED).unwrap(); let charector = if *item == bk { "O" } else if *item == block { "X" } else if *item == passed { "*" } else { "O" }; print!("{position:>1}", position = charector); if idx % (end.0 + 1) == end.0 { println!(); } } println!(); } } fn main() { let map_sample = [ [0, 0, 1, 1, 1], [0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 0], ]; let mut map = DMatrix::from_fn_generic(Dynamic::new(5), Dynamic::new(5), |r, c| map_sample[c][r]); println!("Print Map"); map.printSolution((4, 4)); map.solveMaze((4, 4)); }
code/backtracking/src/partitions_of_number/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/backtracking/src/partitions_of_number/partitions_of_number.cpp
/// Part of Cosmos by OpenGenus Foundation #include <stdio.h> #include <vector> void backtrack(int level); void print_sol(int length); std::vector<int> solution; int N, S = 0; int solsFound = 0; int main() { scanf("%d", &N); solution.reserve(N + 1); solution[0] = 1; backtrack(1); return 0; } void backtrack(int level) { if (S == N) print_sol(level - 1); else for (int i = solution[level - 1]; i <= N - S; i++) { solution[level] = i; S += i; backtrack(level + 1); S -= i; } } void print_sol(int length) { printf("SOLUTION %d\n", ++solsFound); printf("%d=", N); for (int i = 1; i <= length - 1; i++) printf("%d+", solution[i]); printf("%d\n", solution[length]); }
code/backtracking/src/partitions_of_number/partitions_of_number.go
/// Part of Cosmos by OpenGenus Foundation package main import "fmt" var totalSol int func partitions(input int, sol []int, start int) { if input == 0 { fmt.Println(sol) totalSol++ return } for i := start; i <= input; i++ { sol = append(sol, i) partitions(input-i, sol, i) sol = sol[:len(sol)-1] } } func main() { input := 10 sol := []int{} totalSol = 0 partitions(input, sol, 1) fmt.Printf("There are %d ways to combine %d\n", totalSol, input) }
code/backtracking/src/partitions_of_number/partitions_of_number.rs
#[macro_use] extern crate text_io; fn main() { let n: usize = read!(); let mut s: usize = 0; let mut solution: Vec<usize> = Vec::new(); solution.push(1); for _ in 0..n { solution.push(0); } backtrack(&mut solution, n, &mut s, 1); } fn backtrack(vec: &mut Vec<usize>, n: usize, s: &mut usize, level: usize) { //println!("{:?}", vec); if n == *s { printsol(vec, n, level - 1); } else { let mut i = vec[level - 1]; while i <= n - *s { if let Some(elem) = vec.get_mut(level) { *elem = i; } *s += i; backtrack(vec, n, s, level + 1); *s -= i; i += 1; } } } fn printsol(map: &Vec<usize>, num: usize, level: usize) { println!("Solution"); print!("{} = ", num); for idx in 1..level + 1 { if idx == 1 { print!("{:?}", map[idx]); } else { print!(" + {:?}", map[idx]); } } println!(); }
code/backtracking/src/partitions_of_set/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/backtracking/src/partitions_of_set/partitions_of_set.cpp
/// Part of Cosmos by OpenGenus Foundation #include <stdio.h> #include <vector> void backtrack(int level); void print_sol(); std::vector<int> v; std::vector<int> solution; int maxfromSol = 0; int N; int solsFound = 0; int main() { scanf("%d", &N); v.reserve(N + 1); solution.reserve(N + 1); for (int i = 1; i <= N; i++) scanf("%d", &v[i]); backtrack(1); return 0; } void backtrack(int level) { if (level == N + 1) print_sol(); else { for (int i = 1; i <= maxfromSol; i++) { solution[level] = i; backtrack(level + 1); } solution[level] = maxfromSol + 1; maxfromSol++; backtrack(level + 1); maxfromSol--; } } void print_sol() { printf("SOLUTION %d\n", ++solsFound); for (int i = 1; i <= maxfromSol; i++) { printf("Partition %d:", i); for (int j = 1; j <= N; j++) if (solution[j] == i) printf("%d ", v[j]); printf("\n"); } }
code/backtracking/src/partitions_of_set/partitions_of_set.go
/// Part of Cosmos by OpenGenus Foundation package main import "fmt" var totalSol int /* expected output: solution 1 [1 2 3] solution 2 [1 2] [3] solution 3 [1 3] [2] solution 4 [1] [2 3] solution 5 [1] [2] [3] */ func setPartition(data []int, indexArr []int, index, currentLevel int) { if index == len(data) { totalSol++ fmt.Printf("solution %d\n", totalSol) for level := 0; level <= currentLevel; level++ { ans := []int{} for i, v := range indexArr { if v == level { ans = append(ans, data[i]) } } fmt.Println(ans) } return } //Try eveny level within currentLevel for current index for i := 0; i <= currentLevel; i++ { indexArr[index] = i setPartition(data, indexArr, index+1, currentLevel) } //Move to next level indexArr[index] = currentLevel + 1 currentLevel++ setPartition(data, indexArr, index+1, currentLevel) currentLevel-- } func main() { data := []int{1, 2, 3} //Use index array to indicate which partition the element belong to index := make([]int, len(data)) //Since {1},{2,3} is equal to {2,3},{1}, //We can always put first element in first partition and generate the partition of the rest of elements. index[0] = 0 totalSol = 0 setPartition(data, index, 1, 0) }
code/backtracking/src/permutations_of_string/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/backtracking/src/permutations_of_string/permutations_of_string.c
#include <stdio.h> #include <string.h> /* Function to swap values at two pointers */ // Part of Cosmos by OpenGenus Foundation void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */ void permute(char *a, int l, int r) { int i; if (l == r) { printf("%s\n", a); } else { for (i = l; i <= r; i++) { swap((a+l), (a+i)); permute(a, l+1, r); swap((a+l), (a+i)); //backtrack } } } /* Driver program to test above functions */ int main() { char str[] = "ABC"; int n = strlen(str); permute(str, 0, n - 1); return 0; } /*OUTPUT ABC ACB BAC BCA CBA CAB*/
code/backtracking/src/permutations_of_string/permutations_of_string.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" func permutation(data []byte, start, end int) { if start == end { fmt.Println(string(data)) } else { for i := start; i <= end; i++ { data[start], data[i] = data[i], data[start] permutation(data, start+1, end) data[start], data[i] = data[i], data[start] } } } func main() { data := string("ABC") byteArray := []byte(data) permutation(byteArray, 0, len(byteArray)-1) }
code/backtracking/src/permutations_of_string/permutations_of_string.kt
// Part of Cosmos by OpenGenus Foundation fun permute(s: String, l: Int = 0, r: Int = s.length - 1) { val builder = StringBuilder(s) var i: Int if (l == r) { println(s) } else { i = l while (i <= r) { var tmp = builder[l] builder[l] = builder[i] builder[i] = tmp permute(builder.toString(), l + 1, r) tmp = builder[l] builder[l] = builder[i] builder[i] = tmp i++ } } } fun main(args: Array<String>) { permute("ABC") /* Output: ABC ACB BAC BCA CBA CAB */ }
code/backtracking/src/permutations_of_string/permutations_of_string.py
# Part of Cosmos by OpenGenus Foundation import typing def permute(s: str, i: int = 0) -> typing.Iterator[str]: """ >>> list(permute('ABC')) ['ABC', 'ACB', 'BAC', 'BCA', 'CBA', 'CAB'] """ if i == len(s) - 1: yield "".join(s) else: for j in range(i, len(s)): yield from permute(s[:i] + s[i : j + 1][::-1] + s[j + 1 :], i + 1)
code/backtracking/src/permutations_of_string/permutations_of_string_itertools.py
# Part of Cosmos by OpenGenus Foundation import itertools import typing def permute(string: str) -> typing.Iterator[str]: """ >>> list(permute('ABC')) ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] """ yield from map("".join, itertools.permutations(string))
code/backtracking/src/permutations_of_string/permutations_of_string_stl.cpp
// Part of Cosmos by OpenGenus Foundation #include <algorithm> #include <iostream> #include <string> using namespace std; int main() { string s; cin >> s; sort(s.begin(), s.end()); do cout << s << endl; while (next_permutation(s.begin(), s.end())); return 0; }
code/backtracking/src/power_set/power_set.c
#include <stdio.h> #include <math.h> void find_power_set(char *set, int set_size) { unsigned int power_set_size = 1 << set_size; int counter, j; for (counter = 0; counter < power_set_size; counter++) { for (j = 0; j < set_size; j++) { if (counter & (1 << j)) printf("%c", set[j]); } printf("\n"); } } int main() { char set[] = {'a', 'b', 'c'}; find_power_set(set, sizeof(set) / sizeof(set[0])); return (0); }
code/backtracking/src/power_set/power_set.go
//Part of Open Genus foundation package main /* {1 2 3 } {1 2 } {1 3 } {1 } {2 3 } {2 } {3 } {} */ import "fmt" func powerSet(input, record []int, index int) { if index == len(input) { fmt.Printf("{") for i, v := range record { if v == 1 { fmt.Printf(" %v", input[i]) } } fmt.Printf(" }\n") return } record[index] = 1 powerSet(input, record, index+1) record[index] = 0 powerSet(input, record, index+1) } func main() { input := []int{1, 2, 3} record := make([]int, len(input)) powerSet(input, record, 0) }
code/backtracking/src/power_set/power_set.java
/** * Part of Cosmos by OpenGenus Foundation * This code snippet shows how to generate the powerset of a set which is the * set of all subsets of a set. There are two common ways of doing this which * are to use the binary representation of numbers on a computer or to * do it recursively. Both methods are shown here, pick your flavor! * * Time Complexity: O( 2^n ) * * @author William Fiset, [email protected] **/ public class PowerSet { // Use the fact that numbers represented in binary can be // used to generate all the subsets of an array static void powerSetUsingBinary(int[] set) { final int N = set.length; final int MAX_VAL = 1 << N; for (int subset = 0; subset < MAX_VAL; subset++) { System.out.print("{ "); for (int i = 0; i < N; i++) { int mask = 1 << i; if ((subset & mask) == mask) System.out.print(set[i] + " "); } System.out.println("}"); } } // Recursively generate the powerset (set of all subsets) of an array by maintaining // a boolean array used to indicate which element have been selected static void powerSetRecursive(int at, int[] set, boolean[] used) { if (at == set.length) { // Print found subset! System.out.print("{ "); for (int i = 0; i < set.length; i++) if (used[i]) System.out.print(set[i] + " "); System.out.println("}"); } else { // Include this element used[at] = true; powerSetRecursive(at + 1, set, used); // Backtrack and don't include this element used[at] = false; powerSetRecursive(at + 1, set, used); } } public static void main(String[] args) { // Example usage: int[] set = {1, 2, 3 }; powerSetUsingBinary(set); // prints: // { } // { 1 } // { 2 } // { 1 2 } // { 3 } // { 1 3 } // { 2 3 } // { 1 2 3 } System.out.println(); powerSetRecursive(0, set, new boolean[set.length]); // prints: // { 1 2 3 } // { 1 2 } // { 1 3 } // { 1 } // { 2 3 } // { 2 } // { 3 } // { } } }
code/backtracking/src/rat_in_a_maze/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/backtracking/src/rat_in_a_maze/rat_in_a_maze.cpp
/* C/C++ program to solve Rat in a Maze problem using * backtracking */ #include <stdio.h> // Maze size #define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", sol[i][j]); printf("\n"); } } /* A utility function to check if x,y is valid index for N*N maze */ bool isSafe(int maze[N][N], int x, int y) { // if (x,y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false; } /* This function solves the Maze problem using Backtracking. It mainly * uses solveMazeUtil() to solve the problem. It returns false if no * path is possible, otherwise return true and prints the path in the * form of 1s. Please note that there may be more than one solutions, * this function prints one of the feasible solutions.*/ bool solveMaze(int maze[N][N]) { int sol[N][N] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) { // if (x,y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x,y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; /* If moving in x direction doesn't give solution then * Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; /* If none of the above movements work then BACKTRACK: * unmark x,y as part of solution path */ sol[x][y] = 0; return false; } return false; } // driver program to test above function int main() { int maze[N][N] = { {1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1} }; solveMaze(maze); return 0; }
code/backtracking/src/rat_in_a_maze/rat_in_a_maze.py
# Maze size N = 4 def solve_maze_util(maze, x, y, sol): # if (x,y is goal) return True if x == N - 1 and y == N - 1: sol[x][y] = 1 return True # Check if maze[x][y] is valid if is_safe(maze, x, y): # Mark x,y as part of solution path sol[x][y] = 1 # Move forward in x direction if solve_maze_util(maze, x + 1, y, sol): return True # If moving in x direction doesn't give a solution then move down in y direction if solve_maze_util(maze, x, y + 1, sol): return True # If none of the above movements work, then BACKTRACK: unmark x,y as part of the solution path sol[x][y] = 0 return False return False def is_safe(maze, x, y): # if (x,y outside maze) return False if 0 <= x < N and 0 <= y < N and maze[x][y] == 1: return True return False def print_solution(sol): for row in sol: for val in row: print(val, end=' ') print() def solve_maze(maze): sol = [[0 for _ in range(N)] for _ in range(N)] if not solve_maze_util(maze, 0, 0, sol): print("Solution doesn't exist") return False print_solution(sol) return True # Driver program to test above function if __name__ == "__main__": maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1]] solve_maze(maze)
code/backtracking/src/subset_sum/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter SubsetSum is to compute a sum S using a selected subset of a given set of N weights. It works by backtracking, returning all possible solutions one at a time, keeping track of the selected weights using a 0/1 mask vector of size N. A={1,2,3,4,7} S=4 subets={1,3},{4}
code/backtracking/src/subset_sum/subset_sum.c
// Part of Cosmos by OpenGenus Foundation #include <stdio.h> // Recursive Solution // Driver program to test above function // Returns true if there is a subset of set[] with sun equal to given sum int isSubsetSum(int set[], int n, int sum) { // Base Cases if (sum == 0) return 1; if (n == 0 && sum != 0) return 0; // If last element is greater than sum, then ignore it if (set[n-1] > sum) return isSubsetSum(set, n-1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]); } int main() { int n,i,sum; printf("Input number of elements\n"); scanf("%d",&n); int set[n]; printf("Input array elements\n"); for(i = 0; i < n;i++) scanf("%d",&set[i]); printf("Enter Sum to check\n"); scanf("%d",&sum); if (isSubsetSum(set, n, sum) == 1) printf("Found a subset with given sum\n"); else printf("No subset with given sum\n"); return 0; }
code/backtracking/src/subset_sum/subset_sum.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> using namespace std; /* * Generate all possible subset sums * of array v that sum up to targetSum */ vector< vector<int>> generateSubsetSums(int v[], size_t size, int targetSum) { vector< vector<int>> solutions; for (int i = 0; i < (1 << size); ++i) { int currentSum = 0; for (size_t j = 0; j < size; ++j) if (i & (1 << j)) currentSum += v[j]; if (currentSum == targetSum) { vector<int> subsetSum; for (size_t j = 0; j < size; ++j) if (i & (1 << j)) subsetSum.push_back(v[j]); solutions.push_back(subsetSum); } } return solutions; } int main() { int v[] = {5, 12, -3, 10, -2, 7, -1, 8, 11}; int targetSum = 7; vector< vector<int>> subsetSums = generateSubsetSums(v, sizeof(v) / sizeof(v[0]), targetSum); cout << "Subset sums:\n"; for (size_t i = 0; i < subsetSums.size(); ++i) { cout << subsetSums[i][0]; for (size_t j = 1; j < subsetSums[i].size(); ++j) cout << ", " << subsetSums[i][j]; cout << '\n'; } return 0; }
code/backtracking/src/subset_sum/subset_sum.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" var totalSol int /* Expected output: [1 2 3] [1 5] [2 4] [6] There're 4 ways to combine 6 from [1 2 3 4 5 6 7 8 9 10 11 12 13 14] */ func subSetSum(data []int, sol []int, index, target int) { if target == 0 { totalSol++ fmt.Println(sol) return } if target < 0 || index >= len(data) { return } sol = append(sol, data[index]) subSetSum(data, sol, index+1, target-data[index]) sol = sol[:len(sol)-1] subSetSum(data, sol, index+1, target) } func main() { data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} sol := []int{} target := 6 totalSol = 0 subSetSum(data, sol, 0, target) fmt.Printf("There're %d ways to combine %d from %v\n", totalSol, target, data) }
code/backtracking/src/subset_sum/subset_sum.java
import java.util.ArrayList; import java.util.Scanner; public class SubsetSum { public static ArrayList<ArrayList<Integer>> SubsetGenerate(int arr[], int requiredSum){ ArrayList<ArrayList<Integer>> RequiredSubsets = new ArrayList<ArrayList<Integer>>(); int temp,size = arr.length; for(int i=0;i<(1<<size);i++){ temp = 0; for(int j=0;j<size;j++) if((i & (1<<j)) > 0) temp += arr[j]; if(requiredSum == temp){ ArrayList<Integer> subset = new ArrayList<>(); for(int j=0;j<size;j++) if((i & (1<<j)) > 0) subset.add(arr[j]); RequiredSubsets.add(subset); } } return RequiredSubsets; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter n >> "); int n = sc.nextInt(); int arr[] = new int[n]; System.out.print("Enter n array elements >> "); for(int i=0;i<n;i++) arr[i] = sc.nextInt(); System.out.print("Enter required Subset Sum >> "); int requiredSum = sc.nextInt(); ArrayList<ArrayList<Integer>> RequiredSubsets = SubsetGenerate(arr,requiredSum); int temp; System.out.println("Subsets with sum = " + requiredSum + " : "); for(int i=0;i<RequiredSubsets.size();i++){ temp = RequiredSubsets.get(i).size(); for(int j=0;j<temp;j++){ System.out.print(RequiredSubsets.get(i).get(j) + " "); } System.out.println(); } } }
code/backtracking/src/subset_sum/subset_sum.py
# Part of Cosmos by OpenGenus Foundation # subsetsum function below def subsetsum(cs, k, r, x, w, d): x[k] = 1 if cs + w[k] == d: for i in range(0, k + 1): if x[i] == 1: print(w[i], end=" ") print() elif cs + w[k] + w[k + 1] <= d: subsetsum(cs + w[k], k + 1, r - w[k], x, w, d) if (cs + r - w[k] >= d) and (cs + w[k] <= d): x[k] = 0 subsetsum(cs, k + 1, r - w[k], x, w, d) # driver for the above code # Main array w w = [2, 3, 4, 5, 0] x = [0 for i in range(len(w))] print("Enter the no u want to get the subsets sum for") num = int(input()) if num <= sum(w): print("The subsets are:-\n") subsetsum(0, 0, sum(w), x, w, num) else: print( "Not possible The no is greater than the sum of all the elements in the array" )
code/backtracking/src/subset_sum/subset_sum_duplicates.py
def combinationSum(candidates, target): """ Problem description: Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Args: candidates: list of pickable integers target: target sum Returns: List of subsets that sum to the target sum of target """ result_set = [] backtrack(0, sorted(candidates), target, 0, result_set, []) return result_set def backtrack(pos, candidates, target, currentSum, result_set, sequence): """ Helper function for backtracking. Initially does a DFS traversal on each index to check all combinations of subsets to see if they sum to the target sum. Args: pos: current pivot index candidates: candidates list (main list of pickable integers) currentSum: current sum of the list result_set: list to store all result_set sequence: list being used to contain elements relevent to the current DFS Returns: None """ if currentSum == target: result_set.append(sequence[:]) elif currentSum < target: for i in range(pos, len(candidates)): newSum = currentSum + candidates[i] if newSum > target: break sequence.append(candidates[i]) backtrack(i, candidates, target, newSum, result_set, sequence) sequence.pop() if __name__ == "__main__": arr = [2, 3, 6, 7] print(combinationSum(arr, 7))
code/backtracking/src/sudoku_solve/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/backtracking/src/sudoku_solve/sudoku_solve.c
/* ** Reimua ** Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> static const int map_size = 9; /* ** Check a number's existance on a line. */ int exist_on_line(char map[map_size][map_size + 2], const int pos_y, const char c) { int i = 0; while (i < map_size) { if (map[pos_y][i++] == c) return (1); } return (0); } /* ** Check a number's existance on a column. */ int exist_on_column(char map[map_size][map_size + 2], const int pos_x, const char c) { int i = 0; while (i < map_size) { if (map[i++][pos_x] == c) return (1); } return (0); } /* ** Check a number's existance on a block. */ int exist_on_block(char map[map_size][map_size + 2], const int pos_x, const int pos_y, const char c) { int i = pos_y - (pos_y % 3); int j = pos_x - (pos_x % 3); int m = i; int n = j; while (m < i + 3) { while (n < j + 3) { if (map[m][n] == c) return (1); n++; } m++; n = j; } return (0); } /* ** Solve the sudoku by using backtracking. ** ** The following could be improved by changing ** the order of completion instead of going ** from 0 to map_size². */ int resolve_sudoku(char map[map_size][map_size + 2], const int pos) { if (pos == map_size * map_size) return (1); int pos_x = pos % 9; int pos_y = pos / 9; if (map[pos_y][pos_x] != '0') return (resolve_sudoku(map, pos + 1)); char c = '1'; while (c <= map_size + '0') { if (!exist_on_line(map, pos_y, c) && !exist_on_column(map, pos_x, c) && !exist_on_block(map, pos_x, pos_y, c)) { map[pos_y][pos_x] = c; if (resolve_sudoku(map, pos + 1)) return (1); } c++; } map[pos_y][pos_x] = '0'; return (0); } /* ** Read from stdin. */ int read_map(char map[map_size][map_size + 2]) { int i = 0; while (i < map_size) { if (!fgets(map[i], map_size + 2, stdin) || (int)strlen(map[i]) < map_size) return (1); map[i++][map_size] = '\0'; } return (0); } int main(void) { int i = 0; char map[map_size][map_size + 2]; if (read_map(map)) return (1); resolve_sudoku(map, 0); while (i < map_size) printf("%s\n", map[i++]); return (0); }
code/backtracking/src/sudoku_solve/sudoku_solve.cpp
#include <iostream> using namespace std; /* * Part of Cosmos by OpenGenus Foundation */ int n = 9; bool isPossible(int mat[][9], int i, int j, int no) { ///Row or col should not have no for (int x = 0; x < n; x++) if (mat[x][j] == no || mat[i][x] == no) return false; /// Subgrid should not have no int sx = (i / 3) * 3; int sy = (j / 3) * 3; for (int x = sx; x < sx + 3; x++) for (int y = sy; y < sy + 3; y++) if (mat[x][y] == no) return false; return true; } void printMat(int mat[][9]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << mat[i][j] << " "; if ((j + 1) % 3 == 0) cout << '\t'; } if ((i + 1) % 3 == 0) cout << endl; cout << endl; } } bool solveSudoku(int mat[][9], int i, int j) { ///Base Case if (i == 9) { printMat(mat); return true; } ///Crossed the last Cell in the row if (j == 9) return solveSudoku(mat, i + 1, 0); ///Skip if filled cell if (mat[i][j] != 0) return solveSudoku(mat, i, j + 1); ///White Cell ///Try to place every possible no for (int no = 1; no <= 9; no++) if (isPossible(mat, i, j, no)) { ///Place the no - assuming solution is possible with this mat[i][j] = no; bool isSolve = solveSudoku(mat, i, j + 1); if (isSolve) return true; ///loop will place the next no. } ///Backtracking mat[i][j] = 0; return false; } int main() { int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, {0, 0, 0, 0, 8, 0, 0, 7, 9}}; printMat(mat); cout << "Solution " << endl; solveSudoku(mat, 0, 0); return 0; }
code/backtracking/src/sudoku_solve/sudoku_solve.py
# A Backtracking program in Pyhton to solve Sudoku problem # A Utility Function to print the Grid def print_grid(arr): for i in range(9): for j in range(9): print(arr[i][j], end=" "), print(end="\n") # Function to Find the entry in the Grid that is still not used # Searches the grid to find an entry that is still unassigned. If # found, the reference parameters row, col will be set the location # that is unassigned, and true is returned. If no unassigned entries # remain, false is returned. # 'l' is a list variable that has been passed from the solve_sudoku function # to keep track of incrementation of Rows and Columns def find_empty_location(arr, l): for row in range(9): for col in range(9): if arr[row][col] == 0: l[0] = row l[1] = col return True return False # Returns a boolean which indicates whether any assigned entry # in the specified row matches the given number. def used_in_row(arr, row, num): for i in range(9): if arr[row][i] == num: return True return False # Returns a boolean which indicates whether any assigned entry # in the specified column matches the given number. def used_in_col(arr, col, num): for i in range(9): if arr[i][col] == num: return True return False # Returns a boolean which indicates whether any assigned entry # within the specified 3x3 box matches the given number def used_in_box(arr, row, col, num): for i in range(3): for j in range(3): if arr[i + row][j + col] == num: return True return False # Checks whether it will be legal to assign num to the given row,col # Returns a boolean which indicates whether it will be legal to assign # num to the given row,col location. def check_location_is_safe(arr, row, col, num): # Check if 'num' is not already placed in current row, # current column and current 3x3 box return ( not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num) ) # Takes a partially filled-in grid and attempts to assign values to # all unassigned locations in such a way to meet the requirements # for Sudoku solution (non-duplication across rows, columns, and boxes) def solve_sudoku(arr): # 'l' is a list variable that keeps the record of row and col in find_empty_location Function l = [0, 0] # If there is no unassigned location, we are done if not find_empty_location(arr, l): return True # Assigning list values to row and col that we got from the above Function row = l[0] col = l[1] # consider digits 1 to 9 for num in range(1, 10): # if looks promising if check_location_is_safe(arr, row, col, num): # make tentative assignment arr[row][col] = num # return, if sucess, ya! if solve_sudoku(arr): return True # failure, unmake & try again arr[row][col] = 0 # this triggers backtracking return False # Driver main function to test above functions if __name__ == "__main__": # creating a 2D array for the grid grid = [[0 for x in range(9)] for y in range(9)] # assigning values to the grid grid = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # if sucess print the grid if solve_sudoku(grid): print_grid(grid) else: print("No solution exists")
code/backtracking/src/sudoku_solve/sudoku_solve.rs
// Part of Cosmos by OpenGenus const N: usize = 9; const UNASSIGNED: u8 = 0; type Board = [[u8; N]; N]; fn solve_sudoku(grid: &mut Board) -> bool { let row; let col; if let Some((r, c)) = find_unassigned_cells(&grid) { row = r; col = c; } else { // SOLVED return true; } for num in 1..=9 { if is_safe(&grid, row, col, num) { grid[row][col] = num; if solve_sudoku(grid) { return true; } // Failed, try again grid[row][col] = UNASSIGNED; } } false } fn used_in_row(grid: &Board, row: usize, num: u8) -> bool { for col in 0..N { if grid[row][col] == num { return true; } } false } fn used_in_col(grid: &Board, col: usize, num: u8) -> bool { for row in grid.iter().take(N) { if row[col] == num { return true; } } false } fn used_in_box(grid: &Board, row_start: usize, col_start: usize, num: u8) -> bool { for row in 0..3 { for col in 0..3 { if grid[row + row_start][col + col_start] == num { return true; } } } false } fn is_safe(grid: &Board, row: usize, col: usize, num: u8) -> bool { !used_in_row(grid, row, num) && !used_in_col(grid, col, num) && !used_in_box(grid, row - (row % 3), col - (col % 3), num) } fn find_unassigned_cells(grid: &Board) -> Option<(usize, usize)> { for (row, _) in grid.iter().enumerate().take(N) { for col in 0..N { if grid[row][col] == UNASSIGNED { return Some((row, col)); } } } None } fn print_grid(grid: &Board) { for row in grid.iter().take(N) { for col in 0..N { print!("{} ", row[col]); } println!(); } } #[test] fn test1() { let mut board = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ]; // Can solve assert!(solve_sudoku(&mut board)); let solved_board = [ [3, 1, 6, 5, 7, 8, 4, 9, 2], [5, 2, 9, 1, 3, 4, 7, 6, 8], [4, 8, 7, 6, 2, 9, 5, 3, 1], [2, 6, 3, 4, 1, 5, 9, 8, 7], [9, 7, 4, 8, 6, 3, 1, 2, 5], [8, 5, 1, 7, 9, 2, 6, 4, 3], [1, 3, 8, 9, 4, 7, 2, 5, 6], [6, 9, 2, 3, 5, 1, 8, 7, 4], [7, 4, 5, 2, 8, 6, 3, 1, 9], ]; assert_eq!(board, solved_board) } #[test] fn test2() { let mut board = [ [2, 0, 0, 9, 0, 0, 1, 0, 0], [6, 0, 0, 0, 5, 1, 0, 0, 0], [0, 9, 5, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 0, 0], [5, 0, 9, 1, 0, 2, 4, 0, 3], [0, 0, 8, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 5, 6, 3, 0], [0, 0, 0, 4, 6, 0, 0, 0, 9], [0, 0, 3, 0, 0, 9, 0, 0, 2], ]; // Can solve assert!(solve_sudoku(&mut board)); let solved = [ [2, 3, 4, 9, 7, 6, 1, 8, 5], [6, 8, 7, 3, 5, 1, 9, 2, 4], [1, 9, 5, 2, 4, 8, 3, 7, 6], [4, 1, 6, 5, 3, 7, 2, 9, 8], [5, 7, 9, 1, 8, 2, 4, 6, 3], [3, 2, 8, 6, 9, 4, 7, 5, 1], [9, 4, 1, 8, 2, 5, 6, 3, 7], [7, 5, 2, 4, 6, 3, 8, 1, 9], [8, 6, 3, 7, 1, 9, 5, 4, 2], ]; assert_eq!(board, solved); }
code/backtracking/src/sudoku_solve/sudoku_solveNxN.cpp
#include<iostream> using std ::cout; using std ::cin; const int n = 9; int grid[n][n]; void input_grid() { //int i, j; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> grid[i][j]; } } } void print_grid() { //int i, j; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << grid[i][j] << " "; } cout << '\n'; } } bool can_be_placed(int row, int col, int num) { int ii = 0, jj = col; // row check while (ii < n) { if (grid[ii][jj] == num) { return false; } ii++; } // col check ii = row; jj = 0; while (jj < n) { if (grid[ii][jj] == num) { return false; } jj++; } // 3*3 check int startrow, startcol; startrow = (row / 3) * 3; startcol = (col / 3) * 3; for (ii = startrow; ii < startrow + 3; ii++) { for (jj = startcol; jj < startcol + 3; jj++) { if (grid[ii][jj] == num) { return false; } } } return true; } void sudoku_solver(int row, int col) { // cout<<row<<" "<<col<<'\n'; if (row == n && col == 0) { print_grid(); return ; } if (grid[row][col] == 0) { for (int num = 1; num <= n; num++) { if ((can_be_placed(row, col, num))) { grid[row][col] = num; if (col == n - 1) { sudoku_solver(row + 1, 0); } else { sudoku_solver(row, col + 1); } grid[row][col] = 0; } } } else { if (col == n - 1) { sudoku_solver(row + 1, 0); } else { sudoku_solver(row, col + 1); } } } int main() { input_grid(); sudoku_solver(0, 0); } //created by aryan
code/backtracking/src/sudoku_solve/sudoku_solver.java
public static boolean isSafe(int[][] board, int row, int col, int num) { for (int d = 0; d < board.length; d++) { if (board[row][d] == num) { return false; } } for (int r = 0; r < board.length; r++) { if (board[r][col] == num) { return false; } } int sqrt = (int)Math.sqrt(board.length); int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r][d] == num) { return false; } } } return true; } public static boolean solveSudoku( int[][] board, int n) { int row = -1; int col = -1; boolean isEmpty = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 0) { row = i; col = j; isEmpty = false; break; } } if (!isEmpty) { break; } } if (isEmpty) { return true; } for (int num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row][col] = num; if (solveSudoku(board, n)) { return true; } else { board[row][col] = 0; } } } return false; } public static void print( int[][] board, int N) { for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { System.out.print(board[r][d]); System.out.print(" "); } System.out.print("\n"); if ((r + 1) % (int)Math.sqrt(N) == 0) { System.out.print(""); } } } public static void main(String args[]) { int[][] board = new int[][] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; int N = board.length; if (solveSudoku(board, N)) { print(board, N); } else { System.out.println("No solution"); } }
code/backtracking/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/Find the element that appears once/Find_the_element_that_appears_once.cpp
// C++ program to find the element // that occur only once #include <bits/stdc++.h> using namespace std; #define INT_SIZE 32 int getSingle(int arr[], int n) { // Initialize result int result = 0; int x, sum; // Iterate through every bit for (int i = 0; i < INT_SIZE; i++) { // Find sum of set bits at ith position in all // array elements sum = 0; x = (1 << i); for (int j = 0; j < n; j++) { if (arr[j] & x) sum++; } // The bits with sum not multiple of 3, are the // bits of element with single occurrence. if ((sum % 3) != 0) result |= x; } return result; } // Driver code int main() { int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The element with single occurrence is " << getSingle(arr, n); return 0; } // This code is contributed by rathbhupendra
code/bit_manipulation/src/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/addition_using_bits/addition_using_bits.c
/* Problem Statement : Add two numbers using bitwise operators (i.e without using arithmetic operators) */ #include <stdio.h> #include <limits.h> // Function to add two numbers using bitwise operators int bitwiseAddition(int n, int m) { while (m != 0) { int carry = n & m; n = n ^ m; m = carry << 1; // Check for overflow (positive to negative or vice versa) if ((n < 0 && m > 0) || (n > 0 && m < 0)) { fprintf(stderr, "Overflow detected. Cannot add numbers.\n"); return INT_MAX; // Return the maximum possible value } } return n; } // recursive function int bitwiseAdditionRecursive(int n, int m) { if (m == 0) return n; else { int carry = n & m; return bitwiseAdditionRecursive(n ^ m, carry << 1); } } int main() { int a, b; printf("Enter two numbers: "); if (scanf("%d %d", &a, &b) != 2) { fprintf(stderr, "Invalid input. Please enter two integers.\n"); return 1; // Exit with an error code } int result = bitwiseAddition(a, b); if (result == INT_MAX) { return 1; // Exit with an error code } printf("\nBitwise addition using iterative function : %d", bitwiseAddition(a, b)); printf("\nBitwise addition using recursive function : %d", bitwiseAdditionRecursive(a, b)); return 0; } /* Enter two numbers : 3 5 Bitwise addition using iterative function : 8 Bitwise addition using recursive function : 8 */
code/bit_manipulation/src/addition_using_bits/addition_using_bits.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation int bitwiseAddition(int n, int m) { while (m != 0) { int carry = n & m; // Variable carry keeps track of bits that carry over n = n ^ m; // This adds up the individual bits m = carry << 1; // Shift carry over bits so they can be added } return n; } int bitwiseAdditionRecursive(int n, int m) { if (m == 0) return n; else { int carry = n & m; return bitwiseAdditionRecursive(n ^ m, carry << 1); } }
code/bit_manipulation/src/addition_using_bits/addition_using_bits.cs
using System; namespace BitwiseAddition { class Program { static internal int bitwiseRecursiveAddition(int n, int m) { if(m == 0) return n; var carry = n & m; return bitwiseRecursiveAddition(n ^ m, carry << 1); } static internal int bitwiseIterativeAddition(int n, int m) { while(m != 0) { var carry = n & m; n ^= m; m = carry << 1; } return n; } static public void Main() { Console.WriteLine(bitwiseRecursiveAddition(10, 20)); Console.WriteLine(bitwiseIterativeAddition(50, 20)); } } }
code/bit_manipulation/src/addition_using_bits/addition_using_bits.java
/* Problem Statement : Add two numbers using bitwise operators (i.e without using arithmetic operators) */ import java.util.Scanner; class Addition_Using_Bits { // iterative function static int bitwiseAddition(int n, int m) { while (m != 0) { int carry = n & m; n = n ^ m; m = carry << 1; } return n; } // recursive function static int bitwiseAdditionRecursive(int n, int m) { if (m == 0) return n; else { int carry = n & m; return bitwiseAdditionRecursive(n ^ m, carry << 1); } } public static void main(String args[]) { Scanner in = new Scanner(System.in); int a, b; System.out.print("Enter two numbers : "); a = in.nextInt(); b = in.nextInt(); System.out.println("\nBitwise addition using iterative function : " + bitwiseAddition(a, b)); System.out.println("Bitwise addition using recursive function : " + bitwiseAdditionRecursive(a, b)); } } /* Enter two numbers : 3 5 Bitwise addition using iterative function : 8 Bitwise addition using recursive function : 8 */
code/bit_manipulation/src/addition_using_bits/addition_using_bits.js
function bitwiseRecursiveAddition(n, m) { if (m == 0) return n; let carry = n & m; return bitwiseRecursiveAddition(n ^ m, carry << 1); } function bitwiseIterativeAddition(n, m) { while (m != 0) { let carry = n & m; n ^= m; m = carry << 1; } return n; } console.log(bitwiseIterativeAddition(10, 20)); console.log(bitwiseRecursiveAddition(30, 20));
code/bit_manipulation/src/addition_using_bits/addition_using_bits.py
# Part of Cosmos by OpenGenus Foundation # Function adds 2 numbers a and b without using + operator def addition(a, b): while b != 0: c = a & b # carry contains set bits of both a and b a = a ^ b # a ^ b is equal to 1 if, the bits of a and b are different b = c << 1 # carry is right-shifted by 1 return a # Driver code if __name__ == "__main__": print(addition(5, 9)) print(addition(4, 3))
code/bit_manipulation/src/bit_division/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/bit_division/bit_division.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation unsigned bitDivision(unsigned numerator, unsigned denominator) { unsigned current = 1; unsigned answer=0; if ( denominator > numerator) return 0; else if ( denominator == numerator) return 1; while (denominator < numerator) { denominator <<= 1; current <<= 1; } denominator >>= 1; current >>= 1; while (current!=0) { if ( numerator >= denominator) { numerator -= denominator; answer |= current; } current >>= 1; denominator >>= 1; } return answer; } void test(){ int numerator = 23, denominator = 5; printf("%d\n", bitDivision(numerator,denominator)); } int main() { test(); return 0; }
code/bit_manipulation/src/bit_division/bit_division.cpp
/* Problem Statement : Divide two numbers using bitwise operators (i.e without using arithmetic operators) */ #include <iostream> using namespace std; int bitDivision(int numerator, int denominator) { int current = 1; int answer = 0; if (denominator > numerator) return 0; else if (denominator == numerator) return 1; while (denominator < numerator) { denominator <<= 1; current <<= 1; } denominator >>= 1; current >>= 1; while (current != 0) { if (numerator >= denominator) { numerator -= denominator; answer |= current; } current >>= 1; denominator >>= 1; } return answer; } int main() { int numerator, denominator; // numerator -> represents dividend // denominator -> represents divisor cout << "Enter numerator and denominator : "; cin >> numerator >> denominator; cout << "\nQuotient after bitwise division : " << bitDivision(numerator, denominator) << endl; return 0; } /* Enter numerator and denominator : 10 4 Quotient after bitwise division : 2 */
code/bit_manipulation/src/bit_division/bit_division.go
package main // Part of Cosmos by OpenGenus Foundation import ( "fmt" "math" "errors" ) func divide(dividend int, divisor int) (int, error) { var positive bool = false var answer int = 0 if divisor == 0 { return 0, errors.New("cannot divide by zero") } if dividend > 0 && divisor > 0 { positive = true } dividend = int(math.Abs(float64(dividend))) divisor = int(math.Abs(float64(divisor))) for dividend >= divisor { temp, i := divisor, 1 for dividend >= temp { dividend -= temp answer += i i <<= 1 temp <<= 1 } } if !positive { answer = -answer } return answer, nil }
code/bit_manipulation/src/bit_division/bit_division.java
import java.util.Scanner; // Part of Cosmos by OpenGenus Foundation class BitDivision { static int division(int divident, int divisor) { int curr=1; int result=0; if ( divisor >divident) return 0; else if ( divisor ==divident) return 1; while (divisor <divident) { divisor <<= 1; curr <<= 1; } divisor >>= 1; curr >>= 1; while (curr!=0) { if (divident >= divisor) { divident -= divisor; result |= curr; } curr >>= 1; divisor >>= 1; } return result; } public static void main(String[]args) { Scanner scan=new Scanner(System.in); //a -> represents divident int a=scan.nextInt(); //b -> represents divisor int b=scan.nextInt(); System.out.println(division(a,b)); } }
code/bit_manipulation/src/bit_division/bit_division.js
/* Part of Cosmos by OpenGenus Foundation */ function divide(dividend, divisor) { if (divisor === 0) { return "undefined"; } const isPositive = dividend > 0 && divisor > 0; dividend = Math.abs(dividend); divisor = Math.abs(divisor); var answer = 0; while (dividend >= divisor) { let temp = divisor; let i = 1; while (dividend >= temp) { dividend -= temp; answer += i; i <<= 1; temp <<= 1; } } if (!isPositive) { answer = -answer; } return answer; } function test() { var testCases = [[9, 4], [-10, 3], [103, -10], [-9, -4], [0, -3], [2, 0]]; testCases.forEach(test => console.log(`${test[0]} / ${test[1]} = ${divide(test[0], test[1])}`) ); } test();
code/bit_manipulation/src/bit_division/bit_division.py
""" Part of Cosmos by OpenGenus Foundation """ def divide(dividend, divisor): if divisor == 0: return "undefined" isPositive = (dividend > 0) is (divisor > 0) dividend = abs(dividend) divisor = abs(divisor) answer = 0 while dividend >= divisor: temp, i = divisor, 1 while dividend >= temp: dividend -= temp answer += i i <<= 1 temp <<= 1 if not isPositive: answer = -answer return answer def test(): testCases = [[9, 4], [-10, 3], [103, -10], [-9, -4], [0, -3], [2, 0]] for test in testCases: print("{:3} / {:<3} = {:<3}".format(test[0], test[1], divide(test[0], test[1]))) test()
code/bit_manipulation/src/byte_swapper/byte_swapper.java
// Part of Cosmos by OpenGenus Foundation public class ByteSwapper { private ByteSwapper() { throw new AssertionError(); } public static short swap (short value) { int b1 = value & 0xFF; int b2 = value >> 8 & 0xFF; return (short) (b1 << 8 | b2 << 0); } public static int swap (int value) { int b1 = value >> 0 & 0xff; int b2 = value >> 8 & 0xff; int b3 = value >> 16 & 0xff; int b4 = value >> 24 & 0xff; return b1 << 24 | b2 << 16 | b3 << 8 | b4 << 0; } public static long swap (long value) { long b1 = value >> 0 & 0xff; long b2 = value >> 8 & 0xff; long b3 = value >> 16 & 0xff; long b4 = value >> 24 & 0xff; long b5 = value >> 32 & 0xff; long b6 = value >> 40 & 0xff; long b7 = value >> 48 & 0xff; long b8 = value >> 56 & 0xff; return b1 << 56 | b2 << 48 | b3 << 40 | b4 << 32 | b5 << 24 | b6 << 16 | b7 << 8 | b8 << 0; } public static float swap (float value) { int intValue = Float.floatToIntBits(value); intValue = swap(intValue); return Float.intBitsToFloat(intValue); } public static double swap (double value) { long longValue = Double.doubleToLongBits(value); longValue = swap(longValue); return Double.longBitsToDouble(longValue); } public static void swap (final short[] array) { if (array == null || array.length <= 0) { throw new IllegalArgumentException("Array can't be null or empty"); } for (int i = 0; i < array.length; i++) { array[i] = swap(array[i]); } } public static void swap (int[] array) { if (array == null || array.length <= 0) { throw new IllegalArgumentException("Array can't be null or empty"); } for (int i = 0; i < array.length; i++) { array[i] = swap(array[i]); } } public static void swap (long[] array) { if (array == null || array.length <= 0) { throw new IllegalArgumentException("Array can't be null or empty"); } for (int i = 0; i < array.length; i++) { array[i] = swap(array[i]); } } public static void swap (float[] array) { if (array == null || array.length <= 0) { throw new IllegalArgumentException("Array can't be null or empty"); } for (int i = 0; i < array.length; i++) { array[i] = swap(array[i]); } } public static void swap (double[] array) { if (array == null || array.length <= 0) { throw new IllegalArgumentException("Array can't be null or empty"); } for (int i = 0; i < array.length; i++) { array[i] = swap(array[i]); } } }
code/bit_manipulation/src/clear_bits_from_msb/clear_bits_from_msb.c
/* Problem Statement : Clear all MSB's except for the first i LSB's of a number n. MSB -> Most Significant Bit LSB -> Most Significant Bit */ #include <stdio.h> int clearBitsFromMsb(int n, int i) { int mask = (1 << i) - 1; return n & mask; } int main() { int n, i; printf("Enter n and i : "); scanf("%d %d", &n, &i); n = clearBitsFromMsb(n, i); printf("\nResult : %d", n); return 0; } /* Enter n and i : 14 3 Result : 6 */
code/bit_manipulation/src/clear_bits_from_msb/clear_bits_from_msb.cpp
// Part of Cosmos (OpenGenus) #include <iostream> #include <bits/stdc++.h> using namespace std; int clearAllBits(int n, int i){ int mask = (1 << i) - 1; n = n & mask; return n; } int main() { int n, i; cin >> n >> i; cout<< clearAllBits(n, i) <<endl; return 0; }
code/bit_manipulation/src/clear_bits_from_msb/clear_bits_from_msb.java
/* Problem Statement : Clear all MSB's except for the first i LSB's of a number n. MSB -> Most Significant Bit LSB -> Most Significant Bit */ import java.util.*; class ClearBitsFromMsb { static int clearBitsFromMsb(int n, int i) { int mask = (1 << i) - 1; return n & mask; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter n and i : "); int n = sc.nextInt(); int i = sc.nextInt(); n = clearBitsFromMsb(n, i); System.out.println("\nResult : " + n); } } /* Enter n and i : 14 3 Result : 6 */
code/bit_manipulation/src/clear_bits_from_msb/clear_bits_from_msb.py
""" Problem Statement : Clear all MSB's except for the first i LSB's of a number n. MSB -> Most Significant Bit LSB -> Most Significant Bit """ def clear_bits_from_msb(n, i): mask = (1 << i) - 1 return n & mask if __name__ == "__main__": print("Enter n and i : ") n, i = map(int, input().split()) n = clear_bits_from_msb(n, i) print("Result : " + str(n)) """ Enter n and i : 14 3 Result : 6 """
code/bit_manipulation/src/convert_number_binary/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter ## Package: Convert number to binary Programs in this folder are about converting numbers from `base 10`(decimal) to `base 2`(binary) ### Examples: ---------------- | Decimal | Binary | | :---: | :---: | | 0 | 0 | | 1 | 1 | | 2 | 10 | | 3 | 11 | | 4 | 100 | | 16 | 10000 | ---------------- ### Main idea: Binary numbers have `2` permissible digits `0` **and** `1`. ### How to convert? Let `n` be a decimal number. Let `k` denote the `k` number of bits in the binary number `b`. `mod` is the modulus function, divides the left operand with right operand and provides just the remainder. `quot` is the quotient function, divides left operand by right operand and provides just the quotient. * step 1 n `mod` 2 = b<sub>k - 1</sub> n `quot` 2 = n<sub>1</sub> * step 2 n<sub>1</sub> `mod` 2 = b<sub>k-2</sub> n<sub>1</sub> `quot` 2 = n<sub>2</sub> ... (continue till final step) * final step n<sub>k - 1</sub> `mod` 2 = b<sub>0</sub> n<sub>k - 1</sub> `quot` 2 = 0 Lets walk with example of converting number `5` into a `8-bit` binary number: n = 5, k = 8 --- 5 `mod` 2 = 1 -- b<sub>7</sub> 5 `quot` 2 = 2 --- 2 `mod` 2 = 0 -- b<sub>6</sub> 2 `quot` 2 = 1 --- 1 `mod` 2 = 1 -- b<sub>5</sub> 1 `quot` 2 = 0 -- calc ends(end), all 0s after this point --- 0 `mod` 2 = 0 -- b<sub>4</sub> 0 `quot` 2 = 0 --- 0 `mod` 2 = 0 -- b<sub>3</sub> 0 `quot` 2 = 0 --- 0 `mod` 2 = 0 -- b<sub>2</sub> 0 `quot` 2 = 0 --- 0 `mod` 2 = 0 -- b<sub>1</sub> 0 `quot` 2 = 0 --- 0 `mod` 2 = 0 -- b<sub>0</sub> 0 `quot` 2 = 0 --- b = [0, 0, 0, 0, 0, 1, 0, 1] -- "00000101" --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/bit_manipulation/src/convert_number_binary/binary_to_integer.py
# Part of Cosmos by OpenGenus Foundation def binary_to_int(binary_input): """ Parameters ---------- binary_input : String Returns ------- integer_output : Integer """ integer_output = 0 """ it reads from the left most to the right most. Eventually the left-most is going to have the largest value added to the integer output. """ for digit in binary_input: integer_output = integer_output * 2 + int(digit) return integer_output # test sample_binary_input = "01111101" print( "Integer value of " + sample_binary_input + " is " + str(binary_to_int(sample_binary_input)) )
code/bit_manipulation/src/convert_number_binary/convert_number_binary.c
#include <stdio.h> int main(void) { long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0; printf("Enter a decimal integer \n"); scanf("%ld", &num); decimal_num = num; while (num > 0) { remainder = num % 2; /* To count the number of ones */ if (remainder == 1) { no_of_1s++; } binary = binary + remainder * base; num = num / 2; base = base * 10; } printf("Input number is = %ld\n", decimal_num); printf("Its binary equivalent is = %ld\n", binary); printf("No.of 1's in the binary number is = %ld\n", no_of_1s); return 0; }
code/bit_manipulation/src/convert_number_binary/convert_number_binary.cpp
#include <iostream> #include <string.h> using namespace std; // Part of Cosmos by OpenGenus Foundation string to_binary(int n) { string binary = ""; while (n > 0) { if ((n & 1) == 0) binary = '0' + binary; else binary = '1' + binary; n >>= 1; } return binary; } int to_number(string s) { int number = 0; int n = s.length(); for (int i = 0; i < n; i++) if (s[i] == '1') number += (1 << (n - 1 - i)); return number; } int main() { //sample test string binary = to_binary(10); cout << binary << endl; int number = to_number("111"); cout << number << endl; return 0; }
code/bit_manipulation/src/convert_number_binary/convert_number_binary.hs
-- convert_number_binary.hs -- -- @author Sidharth Mishra -- @description Program to convert Decimal numbers into Binary numbers -- @created Thu Oct 12 2017 17:15:23 GMT-0700 (PDT) -- @last-modified Thu Oct 12 2017 17:15:38 GMT-0700 (PDT) module NumConv ( convDecToBin ) where -- Binary is used as an type alias for [Char] or String -- [MSD......LSD] type Binary = String notEnoughBits :: String notEnoughBits = "Need atleast 1 bit to represent the binary nbr :)" needMoreBits :: String needMoreBits = "Needs more bits to convert, partially converted" negativeNumberNotSupported :: String negativeNumberNotSupported = "Negative Ints not supported yet" convDecToBin :: Int -> Int -> Binary -- Converts a Decimal positive number to its Binary equivalent -- first param -- number of bits in the Binary number -- second param -- the decimal number -- result -- the binary number convDecToBin 0 _ = notEnoughBits convDecToBin k n | n >= 0 = case convDecToBin' k n "" of Left s -> s Right b -> b | otherwise = negativeNumberNotSupported convDecToBin' :: Int -> Int -> Binary -> Either String Binary -- private helper convDecToBin' 0 n b | n >= 1 = Left needMoreBits | otherwise = return b convDecToBin' k n b = convDecToBin' (k - 1) n' b' where n' = n `quot` 2 r' = n `mod` 2 b' = show r' ++ b -- For testing processInput :: [String] -> Maybe (Int, Int) -- processes the input from the console/stdin processInput [] = Nothing processInput [s] = return (32, read s::Int) processInput (s:ss) = return (k,n) where [k,n] = map (\x -> read x :: Int) (s:ss) assert :: String -> String -> Bool -- asserts if expected and actual are equal assert ex ac = ex == ac main :: IO() main = do t <- getLine let (k,n) = case processInput $ words t of Nothing -> (32,0) Just (x,y) -> (x,y) b = convDecToBin k n putStrLn $ "\"" ++ b ++ "\"" print $ assert (convDecToBin 3 3) "011" print $ assert (convDecToBin 3 4) "100" print $ assert (convDecToBin 32 32) "00000000000000000000000000100000" print $ assert (convDecToBin 10 743) "1011100111" print $ assert (convDecToBin 2 4) needMoreBits print $ assert (convDecToBin 2 (-4)) negativeNumberNotSupported
code/bit_manipulation/src/convert_number_binary/convert_number_binary.java
// Part of Cosmos by OpenGenus Foundation public class ConvertNumberBinary { public static void main(String[] args) { String binary = toBinary(20); System.out.println(binary); int number = toNumber("10101"); System.out.println(number); } public static String toBinary(int n) { StringBuilder binary = new StringBuilder(""); while (n > 0) { if ((n&1) == 0) binary.append('0'); else binary.append('1'); n >>= 1; } return binary.toString(); } public static int toNumber(String s) { int number = 0; int n = s.length(); for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') { number += (1 << (n - 1 - i)); } } return number; } }
code/bit_manipulation/src/convert_number_binary/convert_number_binary.js
/* Part of Cosmos by OpenGenus Foundation */ //Using built in functions: function toBinary(val) { return val.toString(2); } function fromBinary(bitString) { return parseInt(bitString, 2); } //Using bitshifts function toBinary_B(val) { let out = ""; while (val > 0) { out = (val & 1) + out; val >>= 1; } return out; } function fromBinary_B(bitString) { let out = 0; let l = bitString.length; let i = 0; for (; i < l; i++) { out += +bitString[i] ? 1 << (l - i - 1) : 0; } return out; }
code/bit_manipulation/src/convert_number_binary/convert_number_binary.php
<?php /** * Part of Cosmos by OpenGenus Foundation */ /** * Converts binary number to decimal number * * @param int $bin binary number * @return int decimal number */ function binary_to_decimal(int $bin) { $arr = array_map('intval', str_split($bin)); $cnt = count($arr); $dec = 0; for ($i = 1; $i < $cnt + 1; $i++) { $dec += $arr[$i - 1] * (2 ** ($cnt - $i)); } return $dec; } /** * Converts decimal number to binary number * * @param int decimal number * @return int $bin binary number */ function decimal_to_binary(int $dec) { $i = 1; $bin = 0; while ($dec > 0) { $rem = $dec % 2; $bin = $bin + ($i * $rem); $dec = floor($dec / 2); $i *= 10; } return $bin; } echo "binary_to_decimal\n"; $test_data = [ [0, 0], [1, 1], [10, 2], [101, 5], [1001, 9], [1010, 10], [1001001010100, 4692], [1001011110100, 4852], ]; foreach ($test_data as $test_case) { $input = $test_case[0]; $expected = $test_case[1]; $result = binary_to_decimal($input); printf( " input %d, expected %s, got %s: %s\n", $input, var_export($expected, true), var_export($result, true), ($expected === $result) ? 'OK' : 'FAIL' ); } echo "decimal_to_binary\n"; $test_data = [ [0, 0], [1, 1], [2, 10], [5, 101], [9, 1001], [10, 1010], [4692, 1001001010100], [4852, 1001011110100], ]; foreach ($test_data as $test_case) { $input = $test_case[0]; $expected = $test_case[1]; $result = decimal_to_binary($input); printf( " input %d, expected %s, got %s: %s\n", $input, var_export($expected, true), var_export($result, true), ($expected === $result) ? 'OK' : 'FAIL' ); }
code/bit_manipulation/src/convert_number_binary/convert_number_binary.py
# part of Cosmos by OpenGenus Foundation import math def intToBinary(i): if i == 0: return "0" s = "" while i: if i % 2 == 1: s = "1" + s else: s = "0" + s i /= 2 return s # sample test n = 741 print(intToBinary(n))
code/bit_manipulation/src/count_set_bits/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/count_set_bits/brian_kernighan_algo/brian_kernighan_algorithm.cpp
//Brian Kernighan’s Algorithm. This programme uses O(logn) to count set bits. #include <iostream> int countSetBits(int n) { // base case if (n == 0) { return 0; } else { // if last bit is set, add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } } int main() { int n; std::cout << "Enter a positive integer : "; std::cin >> n; std::cout << countSetBits(n); return 0; }
code/bit_manipulation/src/count_set_bits/count_set_bits.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation int count_set_bits(int n){ int c = 0; while (n) { c++; n&=(n-1); } return c; } int main() { int n; scanf("%d", &n); printf("%d\n", count_set_bits(n)); return 0; }
code/bit_manipulation/src/count_set_bits/count_set_bits.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation int count(int n) { int c = 0; while (n) { c++; n &= (n - 1); } return c; } int main() { int n; cin >> n; #ifdef BUILTIN cout << __builtin_popcount(n); // use builtin popcount #else cout << count(n); // manual #endif return 0; }
code/bit_manipulation/src/count_set_bits/count_set_bits.cs
using System; namespace CountSetBits { class Program { static internal int countSetBits(int number) { string bin = Convert.ToString(number, 2); // getting binary number int count = 0; foreach (char bit in bin) { if(bit == '1') count++; } return count; } static public void Main() { Console.WriteLine(countSetBits(13)); } } }
code/bit_manipulation/src/count_set_bits/count_set_bits.java
// Part of Cosmos by OpenGenus Foundation /* ** ** @AUTHOR: VINAY BADHAN ** @GREEDY PROBLEM: COUNT SET BITS ** @GITHUB LINK: https://github.com/vinayb21 */ import java.util.*; import java.io.*; class CountSetBits { public static int countSetBits(int n) { int count = 0,bit; while(n>0) { bit = n&1; if(bit==1) count++; n >>= 1; } return count; } /** * Counts the number of set bits in parallel. * @param n 32-bit integer whose set bits are to be counted * @return the number of set bits in (n) * @see <a href="https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel">Bit Twiddling Hacks</a> */ public static int countSetBitsParallel(int n) { final int[] S = { 1, 2, 4, 8, 16 }; final int[] B = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF }; int C = n - ((n >>> 1) & B[0]); C = ((C >>> S[1]) & B[1]) + (C & B[1]); C = ((C >>> S[2]) + C) & B[2]; C = ((C >>> S[3]) + C) & B[3]; C = ((C >>> S[4]) + C) & B[4]; return C; } public static void main(String[] args) throws IOException { int n; InputStreamReader in = new InputStreamReader(System.in); BufferedReader buffer = new BufferedReader(in); PrintWriter out = new PrintWriter(System.out, true); String line = buffer.readLine().trim(); n = Integer.parseInt(line); int ans = countSetBitsParallel(n); out.println("No. of set bits in "+n+" is "+ans); } }
code/bit_manipulation/src/count_set_bits/count_set_bits.js
// Part of Cosmos by OpenGenus Foundation export default function countSetBits(n) { n = +n; if (!(n >= 0 || n < 0)) { return 0; } else if (n < 0) { throw new Error("negtive numbers are not supported"); } let cnt = 0; while (n) { cnt++; n &= n - 1; } return cnt; }
code/bit_manipulation/src/count_set_bits/count_set_bits.py
# Part of Cosmos by OpenGenus Foundation def count_set_bit(number): count = 0 while number: count = count + (number & 1) number = number >> 1 return count print(count_set_bit(9))
code/bit_manipulation/src/count_set_bits/count_set_bits_lookup_table.cpp
// Part of Cosmos by OpenGenus Foundation #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <random> #include <chrono> // I'm not crazy, I generated this lookup table with a Ruby script ;) const unsigned bits[] = { 0, // 0 1, // 1 1, // 10 2, // 11 1, // 100 2, // 101 2, // 110 3, // 111 1, // 1000 2, // 1001 2, // 1010 3, // 1011 2, // 1100 3, // 1101 3, // 1110 4, // 1111 1, // 10000 2, // 10001 2, // 10010 3, // 10011 2, // 10100 3, // 10101 3, // 10110 4, // 10111 2, // 11000 3, // 11001 3, // 11010 4, // 11011 3, // 11100 4, // 11101 4, // 11110 5, // 11111 1, // 100000 2, // 100001 2, // 100010 3, // 100011 2, // 100100 3, // 100101 3, // 100110 4, // 100111 2, // 101000 3, // 101001 3, // 101010 4, // 101011 3, // 101100 4, // 101101 4, // 101110 5, // 101111 2, // 110000 3, // 110001 3, // 110010 4, // 110011 3, // 110100 4, // 110101 4, // 110110 5, // 110111 3, // 111000 4, // 111001 4, // 111010 5, // 111011 4, // 111100 5, // 111101 5, // 111110 6, // 111111 1, // 1000000 2, // 1000001 2, // 1000010 3, // 1000011 2, // 1000100 3, // 1000101 3, // 1000110 4, // 1000111 2, // 1001000 3, // 1001001 3, // 1001010 4, // 1001011 3, // 1001100 4, // 1001101 4, // 1001110 5, // 1001111 2, // 1010000 3, // 1010001 3, // 1010010 4, // 1010011 3, // 1010100 4, // 1010101 4, // 1010110 5, // 1010111 3, // 1011000 4, // 1011001 4, // 1011010 5, // 1011011 4, // 1011100 5, // 1011101 5, // 1011110 6, // 1011111 2, // 1100000 3, // 1100001 3, // 1100010 4, // 1100011 3, // 1100100 4, // 1100101 4, // 1100110 5, // 1100111 3, // 1101000 4, // 1101001 4, // 1101010 5, // 1101011 4, // 1101100 5, // 1101101 5, // 1101110 6, // 1101111 3, // 1110000 4, // 1110001 4, // 1110010 5, // 1110011 4, // 1110100 5, // 1110101 5, // 1110110 6, // 1110111 4, // 1111000 5, // 1111001 5, // 1111010 6, // 1111011 5, // 1111100 6, // 1111101 6, // 1111110 7, // 1111111 1, // 10000000 2, // 10000001 2, // 10000010 3, // 10000011 2, // 10000100 3, // 10000101 3, // 10000110 4, // 10000111 2, // 10001000 3, // 10001001 3, // 10001010 4, // 10001011 3, // 10001100 4, // 10001101 4, // 10001110 5, // 10001111 2, // 10010000 3, // 10010001 3, // 10010010 4, // 10010011 3, // 10010100 4, // 10010101 4, // 10010110 5, // 10010111 3, // 10011000 4, // 10011001 4, // 10011010 5, // 10011011 4, // 10011100 5, // 10011101 5, // 10011110 6, // 10011111 2, // 10100000 3, // 10100001 3, // 10100010 4, // 10100011 3, // 10100100 4, // 10100101 4, // 10100110 5, // 10100111 3, // 10101000 4, // 10101001 4, // 10101010 5, // 10101011 4, // 10101100 5, // 10101101 5, // 10101110 6, // 10101111 3, // 10110000 4, // 10110001 4, // 10110010 5, // 10110011 4, // 10110100 5, // 10110101 5, // 10110110 6, // 10110111 4, // 10111000 5, // 10111001 5, // 10111010 6, // 10111011 5, // 10111100 6, // 10111101 6, // 10111110 7, // 10111111 2, // 11000000 3, // 11000001 3, // 11000010 4, // 11000011 3, // 11000100 4, // 11000101 4, // 11000110 5, // 11000111 3, // 11001000 4, // 11001001 4, // 11001010 5, // 11001011 4, // 11001100 5, // 11001101 5, // 11001110 6, // 11001111 3, // 11010000 4, // 11010001 4, // 11010010 5, // 11010011 4, // 11010100 5, // 11010101 5, // 11010110 6, // 11010111 4, // 11011000 5, // 11011001 5, // 11011010 6, // 11011011 5, // 11011100 6, // 11011101 6, // 11011110 7, // 11011111 3, // 11100000 4, // 11100001 4, // 11100010 5, // 11100011 4, // 11100100 5, // 11100101 5, // 11100110 6, // 11100111 4, // 11101000 5, // 11101001 5, // 11101010 6, // 11101011 5, // 11101100 6, // 11101101 6, // 11101110 7, // 11101111 4, // 11110000 5, // 11110001 5, // 11110010 6, // 11110011 5, // 11110100 6, // 11110101 6, // 11110110 7, // 11110111 5, // 11111000 6, // 11111001 6, // 11111010 7, // 11111011 6, // 11111100 7, // 11111101 7, // 11111110 8, // 11111111 }; unsigned long long popcount_naive(unsigned size, uint16_t* data) { unsigned long long acc = 0; for (unsigned i = 0; i < size; ++i) { uint16_t num = data[i]; while (num) { // Naive approach: Get the last bit and shift the number acc += num & 1; num = num >> 1; } } return acc; } unsigned long long popcount_lookup_table(unsigned size, uint8_t* data) { unsigned long long acc = 0; for (unsigned i = 0; i < size; ++i) // Look it up! acc += bits[data[i]]; return acc; } unsigned long long popcount_builtin(unsigned size, uint64_t* data) { unsigned long long acc = 0; for (unsigned i = 0; i < size; ++i) // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html // This is really fast if your CPU has a dedicated instruction (and it should) acc += __builtin_popcountll(data[i]); return acc; } // Usage: // ./count_set_bits_lookup_table <amount of random numbers>, e.g: // ./count_set_bits_lookup_table 2017 // -> Naive approach: 7962 in 107μs // -> Lookup table: 7962 in 20μs // -> GCC builtin: 7962 in 5μs int main(int argc, char* argv[]) { if (argc < 2) return -1; unsigned amount; std::stringstream ss; ss << argv[1]; ss >> amount; // we want length divisible by 4 unsigned length = amount + (-amount) % 4; uint16_t* numbers = new uint16_t[length]; std::default_random_engine generator; std::uniform_int_distribution<uint16_t> dist(0, 255); for (unsigned n = 0; n < amount; ++n) numbers[n] = dist(generator); // pad with zeros for (unsigned n = amount; n < length; ++n) numbers[n] = 0; unsigned long long count; std::chrono::high_resolution_clock a_clock; auto start = a_clock.now(); count = popcount_naive(amount, numbers); auto end = a_clock.now(); std::cout << "Naive approach: " << count << " in " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "μs" << std::endl; start = a_clock.now(); count = popcount_lookup_table(2 * amount, (uint8_t*)(numbers)); end = a_clock.now(); std::cout << "Lookup table: " << count << " in " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "μs" << std::endl; start = a_clock.now(); count = popcount_builtin(length / 4, (uint64_t*)(numbers)); end = a_clock.now(); std::cout << "GCC builtin: " << count << " in " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "μs" << std::endl; }
code/bit_manipulation/src/first_set_bit/first_set_bit.cpp
// Part of Cosmos (OpenGenus) #include <bits/stdc++.h> using namespace std; int returnFirstSetBit(int n) { if(n == 0) return 0; int position = 1; int m = 1; while (!(n & m)) { m = m << 1; position++; } return (1 << (position - 1)); } int main() { int n; cin >> n; cout << returnFirstSetBit(n) << endl; return 0; }
code/bit_manipulation/src/flip_bits/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/flip_bits/flipbits.java
// Part of Cosmos by OpenGenus Foundation /* ** ** @AUTHOR: VINAY BADHAN ** @BIT MANIPULATION PROBLEM: FLIP BITS ** @GITHUB LINK: https://github.com/vinayb21 */ import java.util.*; import java.io.*; class FlipBits { public static int flipBits(int n) { int flipN = 0; int pow = 0; while(n>0) { if(n%2==0) flipN += (1 << pow); n/=2; pow++; } return flipN; } public static void main(String[] args) throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedReader buffer = new BufferedReader(in); String line = buffer.readLine().trim(); int n = Integer.parseInt(line); int ans = flipBits(n); System.out.println("Number obtained by flipping bits of "+n +" is "+ans); } }
code/bit_manipulation/src/flip_bits/flippingbits.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation int main() { int count; unsigned int to_flip; unsigned int flipped; printf("How many flips? "); scanf("%d", &count); while(count--) { printf("To flip: "); scanf("%d", &to_flip); flipped = ~to_flip; printf("Flipped: %d\n", flipped); } }
code/bit_manipulation/src/flip_bits/flippingbits.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; int main() { int T; unsigned int n; cin >> T; while (T--) { cin >> n; cout << ~n << endl; } return 0; }
code/bit_manipulation/src/flip_bits/flippingbits.py
#! /usr/bin/env python3 # Part of Cosmos by OpenGenus Foundation def main(): count = int(input("How many flips? ")) while count > 0: to_flip = int(input("To flip: ")) flipped = ~to_flip print("Flipped:", flipped) count -= 1 if __name__ == "__main__": main()
code/bit_manipulation/src/hamming_distance/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/hamming_distance/hamming_distance.c
#include<stdio.h> #define BITS 8 void hamming(int ar1[],int ar2[]); void input(int ar1[]); int count_ham(int ar[]); int n; int main(){ int ar1[BITS],ar2[BITS]; printf("Enter the number of bits(max 8-bits):"); scanf("%d",&n); printf("Enter a binary number(space between each bit and MAX 8-bit):"); input(ar1); printf("Enter a binary number(space between each bit and MAX 8-bit):"); input(ar2); hamming(ar1,ar2); return 0; } void input(int ar1[]){ int i; for(i=0;i<n;i++){ scanf("%d",&ar1[i]); } } int count_ham(int ar[]){ int i,count=0; for(i=0;i<n;i++){ if(ar[i]==1) count++; } return count; } void hamming(int ar1[],int ar2[]){ int i,count; int res[BITS]; for(i=0;i<n;i++){ if((ar1[i]==1 && ar2[i]==0)||(ar1[i]==0 && ar2[i]==1)){ res[i] = 1; } else{ res[i] = 0; } } count = count_ham(res); printf("Hamming distance will be: %d",count); printf("\n"); }
code/bit_manipulation/src/hamming_distance/hamming_distance.cpp
/* * * Part of Cosmos by OpenGenus Foundation * * The Hamming distance between two integers is the number of positions * at which the corresponding bits are different. * * Given two integers x and y, calculate the Hamming distance. */ int hammingDistance(int x, int y) { int temp = x ^ y; int count = 0; //count the number of set bits in the xor of two numbers while (temp) { temp = temp & (temp - 1); count++; } return count; }
code/bit_manipulation/src/hamming_distance/hamming_distance.go
package main import "fmt" // Hamming distance between two integers is the number of positions // at which the corresponding bits are different. func HammingDistance(x, y int) (count int) { t := x ^ y //count the number of set bits in the xor of two numbers for t != 0 { t = t & (t - 1) count++ } return } func main() { fmt.Printf("Hamming distance beetwen (%d) and (%d) is (%d)\n", 1, 2, HammingDistance(1, 2)) }
code/bit_manipulation/src/hamming_distance/hamming_distance.java
// Part of Cosmos by OpenGenus Foundation // The Hamming distance between two integers is the number of positions // at which the corresponding bits are different. import java.io.*; import java.lang.*; import java.math.*; import java.util.*; class HammingDistance { private int hammingDistance(int x, int y) { int temp = x^y; int count = 0; //count the number of set bits in the xor of two numbers while(temp != 0){ temp = temp&(temp-1); count++; } return count; } public static void main(String args[]) { HammingDistance ob = new HammingDistance(); int testHammingDistance = ob.hammingDistance(2,5); System.out.println(testHammingDistance); } }
code/bit_manipulation/src/hamming_distance/hamming_distance.py
# Part of Cosmos by OpenGenus Foundation # The Hamming distance between two integers is the number of positions # at which the corresponding bits are different. def hammingDistance(x, y): res = x ^ y ans = 0 while res: ans += 1 res = res & (res - 1) return ans print(hammingDistance(2, 1))
code/bit_manipulation/src/hamming_distance/hamming_distance2.py
def main(): num = input("enter a number") return ("{0:08b}".format(x)).count("1") if __name__ == "__main__": main()
code/bit_manipulation/src/invert_bit/invert_bit.c
#include <stdio.h> //Part of Cosmos by OpenGenus Foundation int invert_bit(int n, int number_bit) { n ^= 1 << number_bit; return (n); } int main() { int numeric, number_bit, res; printf("Enter numeric: "); scanf("%d", &numeric); printf("Enter number bit: "); scanf("%d", &number_bit); res = invert_bit(numeric, number_bit); printf("Result: %d\n", res); return (0); }
code/bit_manipulation/src/invert_bit/invert_bit.cpp
#include <iostream> #include <bitset> //Part of Cosmos by OpenGenus Foundation int invertBit(int n, int numBit) { n ^= 1 << numBit; return n; } int main() { int numeric, numberBit, res; std::cout << "Enter numeric: " << std::endl; std::cin >> numeric; std::bitset<32> bs(numeric); std::cout << bs << '\n'; std::cout << "Enter number bit: " << std::endl; std::cin >> numberBit; res = invertBit(numeric, numberBit); std::bitset<32> bsRes(res); std::cout << res << std::endl; std::cout << bsRes << std::endl; return 0; }
code/bit_manipulation/src/invert_bit/invert_bit.js
const invertBit = (num, bit) => num ^ (1 << bit); console.log(invertBit(10, 5)); // 42
code/bit_manipulation/src/invert_bit/invert_bit.py
# Part of Cosmos by OpenGenus Foundation def invert_bit(digit, number_bit): digit ^= 1 << number_bit return digit number = int(input("Enter numeric: ")) num_bit = int(input("Enter number bit: ")) res = invert_bit(number, num_bit) print(res)
code/bit_manipulation/src/invert_bit/invert_bit.rs
// Part of Cosmos by OpenGenus Foundation use std::{io::{self, Write}, process}; /// Invert a bit at a given place /// /// # Arguments /// /// * `bits` - The value/bits you want to modify /// /// * `place` - The position of the bit you want to invert /// /// # Examples /// ``` /// let value = 50; // 110010 /// let place = 2; // ^ 000100 /// let new_value = invert_bit(value, place); // = 110110 /// ``` fn invert_bit(bits: u32, place: u8) -> u32 { bits ^ 1 << place } fn main() { // Get value print!("enter a value: "); io::stdout().flush().unwrap(); let mut value = String::new(); io::stdin().read_line(&mut value).unwrap_or_else(|_| { eprintln!("error: unable to read input (value)"); process::exit(1); }); let value = value.trim(); let value = value.parse::<u32>().unwrap_or_else(|_| { eprintln!("error: invalid input (value must be unsigned 32-bit integer)"); process::exit(1); }); // Get place print!("enter a place: "); io::stdout().flush().unwrap(); let mut place = String::new(); io::stdin().read_line(&mut place).unwrap_or_else(|_| { eprintln!("error: unable to read input (place)"); process::exit(1); }); let place = place.trim(); let place = place.parse::<u8>().unwrap_or_else(|_| { eprintln!("error: invalid input (place must be unsigned 8-bit integer)"); process::exit(1); }); if place > 31 { eprintln!("error: left bit shift overflow (place must be between 0 inclusive and 31 inclusive)"); process::exit(1); } // Invert bit let new_value = invert_bit(value, place); println!("{:>8}: {:032b}", "input", value); println!("{:>8}: {:032b}", "output", new_value); }
code/bit_manipulation/src/lonely_integer/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/bit_manipulation/src/lonely_integer/lonely_integer.c
/* *Part of Cosmos by OpenGenus Foundation *The Lonely Integer Problem *Given an array in which all the no. are present twice except one, find that lonely integer. */ #include <stdio.h> int a[7] = {0,0,1,1,3,3,2}; int lonely(int n) { int no=0; for(int i=0;i<n;i++) { no^=a[i]; } return (no); } int main() { int n=sizeof(a)/sizeof(int); printf("Lonely Integer is %d\n",lonely(n)); return (0); }
code/bit_manipulation/src/lonely_integer/lonely_integer.cpp
/* * Part of Cosmos by OpenGenus Foundation * The Lonely Integer Problem * Given an array in which all the no. are present twice except one, find that lonely integer. */ #include <iostream> using namespace std; int LonelyInteger(int *a, int n) { int lonely = 0; //finds the xor sum of the array. for (int i = 0; i < n; i++) lonely ^= a[i]; return lonely; } int main() { int a[] = {2, 3, 4, 5, 3, 2, 4}; cout << LonelyInteger(a, sizeof(a) / sizeof(a[0])); return 0; }
code/bit_manipulation/src/lonely_integer/lonely_integer.go
/* Part of Cosmos by OpenGenus Foundation The Lonely Integer Problem Given an array in which all the no. are present twice except one, find that lonely integer. */ package main import "fmt" func LonelyInteger(a []int) int{ lonely := 0 for i := 0; i < len(a); i++ { lonely ^= a[i] } return lonely } func main() { a := []int{2,3,4,5,3,2,4} fmt.Println(LonelyInteger(a)) }