filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/bit_manipulation/src/lonely_integer/lonely_integer.java | /*
* 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.
*/
public class LonelyInt{
public static void main(String args[]){
int[] testArr = {1,1,2,4,2};
System.out.println(lonelyInt(testArr));
}
public static int lonelyInt(int[] arr){
int lonely = 0;
for(int i : arr){
lonely ^= i;
}
return lonely;
}
}
|
code/bit_manipulation/src/lonely_integer/lonely_integer.js | /*
* 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.
*/
function lonelyInt(arr) {
var lonely = 0;
arr.forEach(number => {
lonely ^= number;
});
return lonely;
}
function test() {
var test = [1, 1, 2, 4, 2];
console.log(lonelyInt(test));
}
test();
|
code/bit_manipulation/src/lonely_integer/lonely_integer.py | """
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.
"""
def LonelyInteger(a):
lonely = 0
# finds the xor sum of the array.
for i in a:
lonely ^= i
return lonely
a = [2, 3, 4, 5, 3, 2, 4]
print(LonelyInteger(a))
|
code/bit_manipulation/src/lonely_integer/lonely_integer.rs | /*
* Part of Cosmos by OpenGenus Foundation
*/
fn lonely_integer(a: &[i64]) -> i64 {
let mut lonely = 0;
for i in a {
lonely ^= *i;
}
lonely
}
fn main() {
let a = [2, 3, 4, 5, 3, 2, 4];
println!("{}", lonely_integer(&a));
}
|
code/bit_manipulation/src/magic_number/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/magic_number/magic_number.c | #include <stdio.h>
// Find the nth magic number where n is a positive number
// @param n: the nth number in the sequence to be calculated and returned
// @param fac: factor level.
// @return: an integer where it is the nth number that can be expressed as a power or sum of the factor level
int
magicNumber(int n, int fac)
{
int answer = 0;
int expo = 1;
while (n != 0)
{
expo = expo * fac;
if (n & 1)
answer += expo;
n = n >> 1;
}
return answer;
}
int
main()
{
int n, f;
printf("n: \n>> ");
scanf("%d", &n);
printf("factor: \n>> ");
scanf("%d", &f);
if (n > 0 && f > 0) {
printf("The magic number is: %d\n", magicNumber(n, f));
}
else {
printf("n and f must be positive and nonzero.\n");
}
return 0;
} |
code/bit_manipulation/src/magic_number/magic_number.cpp | //Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <cmath>
using namespace std;
// Function to find nth magic numebr
int nthMagicNo(int n)
{
int pow = 1, answer = 0;
// Go through every bit of n
while (n)
{
pow = pow * 5;
// If last bit of n is set
if (n & 1)
answer += pow;
// proceed to next bit
n >>= 1; // or n = n/2
}
return answer;
}
int main()
{
int n;
cin >> n;
cout << "nth magic number is " << nthMagicNo(n) << endl;
return 0;
}
|
code/bit_manipulation/src/magic_number/magic_number.java | // Part of Cosmos by OpenGenus Foundation
/*
**
** @AUTHOR: VINAY BADHAN
** @BIT MANIPULATION PROBLEM: Nth MAGIC NUMBER
** @GITHUB LINK: https://github.com/vinayb21
*/
import java.util.*;
import java.io.*;
class MagicNumber {
public static int magicNumber(int n)
{
int pow = 1, ans = 0;
while(n > 0)
{
pow = pow*5;
if (n%2==1)
ans += pow;
n >>= 1;
}
return ans;
}
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 = magicNumber(n);
out.println(n+"th Magic Number is "+ans);
}
}
|
code/bit_manipulation/src/magic_number/magic_number.py | # Python Program to Find nth Magic Number.
# A magic number is defined as a number which can be expressed as a power of 5 or sum of unique powers of 5
# Part of Cosmos by OpenGenus Foundation
# Function to find nth magic numebr
def nthMagicNo(n):
pow = 1
ans = 0
while n:
pow = pow * 5
# If last bit of n is set
if n & 1:
ans += pow
# proceed to next bit
n >>= 1
return ans
n = int(input())
print(nthMagicNo(n))
|
code/bit_manipulation/src/maximum_xor_value/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/maximum_xor_value/maximum_xor_value.cpp | #include <iostream>
using namespace std;
int maxXor(int l, int r)
{
int num = l ^ r, max = 0;
while (num > 0)
{
max <<= 1;
max |= 1;
num >>= 1;
}
return max;
}
int main()
{
int res, _l, _r;
cin >> _l;
cin >> _r;
res = maxXor(_l, _r);
cout << res;
return 0;
}
|
code/bit_manipulation/src/multiply_by_2/README.md | # Mutliply by 2
- A simple Program to multiply a number with 2 by using bit manipulation
|
code/bit_manipulation/src/multiply_by_2/multiply_by_2.cpp | #include<iostream>
using namespace std;
unsigned multiplyWith2(unsigned n) { //Since C++ 11 signed shift left of a negative int is undefined.
return (n << 1); //To avoid unexpected results always use unsigned when doing a multiply by 2
}
int main(){
cout << multiplyWith2(8) << endl;
cout << multiplyWith2(15) << endl;
return 0;
} |
code/bit_manipulation/src/power_of_2/power_of_2.c | /*
* Part of Cosmos by OpenGenus Foundation
* @Author: Ayush Garg
* @Date: 2017-10-13 18:46:12
* @Last Modified by: Ayush Garg
* @Last Modified time: 2017-10-13 18:50:15
*/
#include <stdio.h>
int isPowerOf2(long long n)
{
return n && (!(n & (n - 1)));
}
int main()
{
long long n;
printf("Enter number to check\n");
scanf("%lld", &n);
if (isPowerOf2(n))
printf("%lld Is a power of 2\n",n);
else
printf("%lld Not a power of 2\n",n);
return 0;
} |
code/bit_manipulation/src/power_of_2/power_of_2.cpp | /* Part of Cosmos by OpenGenus Foundation */
/* Created by Shubham Prasad Singh on 12/10/2017 */
/* Check if a number is a power of 2 */
#include <iostream>
using namespace std;
typedef long long ll;
/*
* If a power of two number is subtracted by 1
* then all the unset bits after the set bit become set,
* and the set bit become unset
*
* For Example : 4(power of 2) --> 100
* 4-1 --> 3 --> 011
*
* So,if a number n is a power of 2 then
* (n&(n-1)) = 0
*
* For Example: 4 & 3 = 0
* and 4 is a power of 2
*
* The expression (n & (n-1)) will not work when n=0
* To handle this case , the expression is modified to
* (n & (n&(n-1)))
*/
bool isPowerOf2(ll n)
{
return n && (!(n & (n - 1)));
}
int main()
{
ll n;
cout << "Enter a number\n";
cin >> n;
if (isPowerOf2(n))
cout << "Is a power of 2" << endl;
else
cout << "Not a power of 2" << endl;
return 0;
}
|
code/bit_manipulation/src/power_of_2/power_of_2.cs | using System;
class MainClass {
public static void Main(String[] args){
int num = Convert.ToInt32(Console.ReadLine());
if(((num & (num-1))==0) && (num != 0))
Console.WriteLine("Yes, the number is a power of 2");
else
Console.WriteLine("No, the number is not a power of 2");
}
}
|
code/bit_manipulation/src/power_of_2/power_of_2.go | // Part of Cosmos by OpenGenus Foundation
// @Author: Chanwit Piromplad
// @Date: 2017-10-15 20:57
package main
import (
"fmt"
)
func isPowerOf2(n int) bool {
return n > 0 && (n&(n-1) == 0)
}
func main() {
fmt.Println(isPowerOf2(64))
}
|
code/bit_manipulation/src/power_of_2/power_of_2.java | import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class PowerOf2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if(((num & (num-1))==0) && (num != 0))
System.out.println("Yes, the number is a power of 2");
else
System.out.println("No, the number is not a power of 2");
}
} |
code/bit_manipulation/src/power_of_2/power_of_2.jl | print("Enter a number to check if it is a power of 2: ")
n = parse(Int64, chomp(readline()))
if (n != 0) && (n & (n-1) == 0)
println("YES")
else
println("NO")
end
|
code/bit_manipulation/src/power_of_2/power_of_2.js | /*
Part of Cosmos by OpenGenus Foundation
Created by Jiraphapa Jiravaraphan on 14/10/2017
Check if a number is a power of 2 - javascript implementation
*/
function isPowerOf2(num) {
if (typeof num === "number") return num && (num & (num - 1)) === 0;
}
console.log(isPowerOf2(64));
|
code/bit_manipulation/src/power_of_2/power_of_2.php | <?php
function isPowerOf2($x)
{
if (($x & ($x - 1)) != 0)
return "$x is not power of 2";
else
{
return "$x is power of 2";
}
}
print_r(isPowerOf2(32)."\n");
print_r(isPowerOf2(31)."\n");
|
code/bit_manipulation/src/power_of_2/power_of_2.py | def isPowerOf2(num):
return ((num & (num - 1)) == 0) and (num != 0)
n = int(input("Enter a number: "))
if isPowerOf2(n):
print("Power of 2 spotted!")
else:
print("Not a power of 2")
|
code/bit_manipulation/src/power_of_2/power_of_2.rs | /* Part of Cosmos by OpenGenus Foundation */
/* Created by Luke Diamond on 13/10/2017 */
fn is_power_of_2(x: i32) -> bool {
x != 0 && ((x & (x - 1)) == 0)
}
fn main() {
let mut input_text = String::new();
println!("Input Number:");
std::io::stdin().read_line(&mut input_text);
let number = input_text.trim().parse::<i32>().unwrap();
if is_power_of_2(number) {
println!("{} Is a power of 2", number);
} else {
println!("{} Is not a power of 2", number);
}
}
|
code/bit_manipulation/src/power_of_4/Main.java | public class Main {
public static void main(String[] args) {
int number = 16; // Change this number to check if it's a power of 4
boolean result = isPowerOfFour(number);
if (result) {
System.out.println(number + " is a power of 4.");
} else {
System.out.println(number + " is not a power of 4.");
}
}
public static boolean isPowerOfFour(int num) {
if (num <= 0) {
return false;
}
// A number is a power of 4 if it is a power of 2 and has only one set bit in its binary representation.
// Count the number of set bits and check if it's odd.
int countSetBits = 0;
int temp = num;
while (temp > 0) {
temp = temp >> 1;
countSetBits++;
}
// Check if there is only one set bit and it's at an odd position (0-based index)
return (countSetBits == 1) && ((countSetBits - 1) % 2 == 0);
}
}
|
code/bit_manipulation/src/power_of_4/power_of_4.cpp | // part of cosmos repository
#include <iostream>
using namespace std ;
// Function to check if the number is a power of 4
bool isPowerOfFour(int num) {
// First if the num is +ve ,
// then it is a power of 2 ,
// then (4^n - 1) % 3 == 0
// another proof:
// (1) 4^n - 1 = (2^n + 1) * (2^n - 1)
// (2) among any 3 consecutive numbers, there must be one that is a multiple of 3
// among (2^n-1), (2^n), (2^n+1), one of them must be a multiple of 3, and (2^n) cannot be the one, therefore either (2^n-1) or (2^n+1) must be a multiple of 3, and 4^n-1 must be a multiple of 3 as well.
return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}
int main()
{
int n ;
cin>>n ;
isPowerOfFour(n)?cout<<"YES":cout<<"NO" ;
return 0;
}
|
code/bit_manipulation/src/set_ith_bit/set_ith_bit.cpp | /*
You are given two integers N and i. You need to make ith bit of binary representation of N to 1 and return the updated N.
Counting of bits start from 0 from right to left.
Input Format :
Two integers N and i (separated by space)
Output Format :
Updated N
Sample Input 1 :
4 1
Sample Output 1 :
6
Sample Input 2 :
4 4
Sample Output 2 :
20
*/
#include <iostream>
using namespace std;
int turnOnIthBit(int n, int i){
n = (n | (1 << i));
return n;
}
int main() {
int n, i;
cin >> n >> i;
cout<< turnOnIthBit(n, i) <<endl;
return 0;
}
|
code/bit_manipulation/src/set_ith_bit/set_ith_bit.py | def setithBit(n,i):
# ith bit of n is being
# set by this operation
return ((1 << i) | n)
# Driver code
n = 10
i = 2
print("Kth bit set number = ", setithBit(n, i))
|
code/bit_manipulation/src/subset_generation/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/subset_generation/subset_generator_using_bit.cpp | #include <iostream>
#include <cstring>
using namespace std;
typedef long long int ll;
void filter(char *a, int no)
{
int i = 0;
while (no > 0)
{
(no & 1) ? cout << a[i] : cout << "";
i++;
no = no >> 1;
}
cout << endl;
}
void generateSub(char *a)
{
int n = strlen(a);
int range = (1 << n) - 1;
for (int i = 0; i <= range; i++)
filter(a, i);
}
int main()
{
char a[4] = {'a', 'b', 'c', 'd'};
generateSub(a);
}
|
code/bit_manipulation/src/subset_generation/subset_mask_generator.cpp | #include <iostream>
typedef unsigned long long ll;
//Loops over all subsets of the bits in to_mask. Except to_mask itself
//For test input (111)
//110
//101
//100
//010
//001
//000
void generate_masks(ll to_mask)
{
for (int mask = to_mask; mask;)
{
--mask &= to_mask;
std::cout << mask << std::endl;
}
}
int main()
{
generate_masks(7);
}
|
code/bit_manipulation/src/subset_generation/subset_sum.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
using namespace std;
//To print all subset sums
void printSums(int arr[], int n)
{
long long total = 1 << n; //total = 2^n
for (long long i = 0; i < total; i++) //We are iterating from 0 to 2^n-1
{
long long sum = 0;
for (int j = 0; j < n; j++)
if (i & (1 << j))
sum += arr[j];
//Adding elements to set for which the bit is set
cout << sum << " ";
}
}
/*
* We are not generating all subsets, but we are calculating all
* subset sums based on all combinations of set bits
* which can be obtained by iterating through 0 to 2^n-1
*/
//Driver code
int main()
{
int arr[] = {4, 9, 3, 12, 6, 9};
int n = sizeof(arr) / sizeof(int);
printSums(arr, n);
return 0;
}
|
code/bit_manipulation/src/sum_binary_numbers/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/sum_binary_numbers/sum_binary_numbers.c | #include <stdio.h>
int main()
{
long bin1, bin2;
int i = 0, remainder = 0, sum[20];
printf("Enter the first binary number: ");
scanf("%ld", &bin1);
printf("Enter the second binary number: ");
scanf("%ld", &bin2);
while (bin1 != 0 || bin2 != 0)
{
sum[i++] =(bin1 % 10 + bin2 % 10 + remainder) % 2;
remainder =(bin1 % 10 + bin2 % 10 + remainder) / 2;
bin1 = bin1 / 10;
bin2 = bin2 / 10;
}
if (remainder != 0)
sum[i++] = remainder;
--i;
printf("Sum of two binary numbers: ");
while (i >= 0)
printf("%d", sum[i--]);
return 0;
}
|
code/bit_manipulation/src/sum_binary_numbers/sum_binary_numbers.cpp | #include <iostream>
using namespace std;
int main()
{
long bin1, bin2;
int i = 0, remainder = 0, sum[20];
cout<<"Enter the first binary number: ";
cin>>bin1;
cout<<"Enter the second binary number: ";
cin>>bin2;
while (bin1 != 0 || bin2 != 0)
{
sum[i++] =(bin1 % 10 + bin2 % 10 + remainder) % 2;
remainder =(bin1 % 10 + bin2 % 10 + remainder) / 2;
bin1 = bin1 / 10;
bin2 = bin2 / 10;
}
if (remainder != 0)
sum[i++] = remainder;
--i;
cout<<"Sum of two binary numbers: ";
while (i >= 0)
cout<<sum[i--];
return 0;
}
|
code/bit_manipulation/src/sum_equals_xor/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/sum_equals_xor/sum_equals_xor.c | #include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
/*
Counts the number of values between 0 and a given number that satisfy the condition x+n = x^n (0<=x<=n)
*/
long int solve(long int n) {
long c = 0;
while(n){
c += n%2?0:1;
n/=2;
}
c=pow(2,c);
return c;
}
int main() {
long int n;
scanf("%li", &n);
long int result = solve(n);
printf("%ld\n", result);
return 0;
}
|
code/bit_manipulation/src/sum_equals_xor/sum_equals_xor.cpp | /*
* Counts the number of values between 0 and a given number that satisfy the condition x+n = x^n (0<=x<=n)
*/
#include <iostream>
#include <cmath>
using namespace std;
long solve(long n)
{
long c = 0;
while (n)
{
c += n % 2 ? 0 : 1;
n /= 2;
}
c = pow(2, c);
return c;
}
int main()
{
long n;
cin >> n;
long result = solve(n);
cout << result << endl;
return 0;
}
|
code/bit_manipulation/src/sum_equals_xor/sum_equals_xor.py | # Counts the number of values between 0 and a given number that satisfy the condition x+n = x^n (0<=x<=n)
# Works for both python 2 and python 3
n = int(input("Enter number n"))
# x^n = x+n means that x can contain one's only in its binary representation where it is 0 in n and vice versa.
# To Implement it we calculate number of 0's in the binary representation of n and return the answer as pow(2,n) as there will be two possibilities for each of the 0's in n i.e. 1 and 0.
print(int(pow(2, (bin(n)[2:]).count("0"))))
|
code/bit_manipulation/src/thrice_unique_number/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/thrice_unique_number/thrice_unique_number.cpp | /*
*
* Part of Cosmos by OpenGenus Foundation
* Find unique number in an array where every element occours thrice except one.Find that unique Number
*
*/
#include <iostream>
using namespace std;
int n;
int a[104] = {1, 1, 1, 3, 3, 2, 3};
int f()
{
int count[65] = {0};
for (int i = 0; i < n; i++)
{
int j = 0;
int temp = a[i];
while (temp)
{
count[j] += (temp & 1);
j++;
temp = temp >> 1;
}
}
int p = 1, ans = 0;
for (int i = 0; i <= 64; i++)
{
count[i] %= 3;
ans += (count[i] * p);
p = p << 1;
}
return ans;
}
int main()
{
n = sizeof(a) / sizeof(a[0]);
cout << f();
return 0;
}
|
code/bit_manipulation/src/thrice_unique_number/thrice_unique_number.java | /*
* Part of Cosmos by OpenGenus Foundation
*/
import java.util.*;
public class ThriceUniqueNumber {
final public static int BITS=32;
public static int ConvertToDec(int bitArr[]){
int decNum=0;
for(int i=0;i<BITS;++i){
decNum+=bitArr[i]* (1<<i);
}
return decNum;
}
public static void SetArray(int bitArr[], int num){
// update the bitArr to binary code of num
int i=0;
while(num!=0){
if((num&1)!=0){
bitArr[i]++;
}
num>>=1;
i++;
}
}
public static int thriceUniqueNumber(int arr[], int size){
// at max the numeber of bits can be 32 in a binary no.
int[] bitArr=new int[BITS];
for(int i=0;i<size;++i){
SetArray(bitArr,arr[i]);
}
//by doing this all the numbers appearing thrice will be reomved from
//the binary form
for(int i=0;i<BITS;++i){
bitArr[i] %= 3;
}
int ans=ConvertToDec(bitArr);
return ans;
}
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
//size of the array ( Number of elements to input)
int size=s.nextInt();
int[] arr=new int[size];
//input size number of elements
for(int i=0;i<size;i++){
arr[i]=s.nextInt();
}
//function call
System.out.println(thriceUniqueNumber(arr,size));
/*Example
Input
10
1 1 1 2 2 2 9 9 9 8
OutPut
8*/
}
}
|
code/bit_manipulation/src/thrice_unique_number/thrice_unique_number.js | // Part of Cosmos by OpenGenus Foundation
let numbers = [
1,
1,
1,
2,
2,
2,
3,
3,
3,
4,
5,
5,
5,
6,
6,
6,
7,
7,
7,
8,
8,
8,
9,
9,
9
];
let counter = {};
for (var index = 0; index < numbers.length; index++) {
let current = counter[numbers[index]];
if (current === undefined) {
counter[numbers[index]] = 1;
} else {
counter[numbers[index]] = current + 1;
}
}
for (let num in counter) {
let count = counter[num];
if (count === 1) {
console.log(`Unique number is ${num}`);
}
}
|
code/bit_manipulation/src/thrice_unique_number/thrice_unique_number.py | # we define the function
def uniqueNumber(array):
d = {}
result = array[0]
# case multiple elements
if len(array) > 1:
for x in array:
# fill the dictionary in O(n)
if d.has_key(x):
d[x] += 1
else:
d[x] = 1
# case 1 element
else:
return result
keys = d.keys()
# find the result key in O(1/3 * n)
for k in keys:
if d.get(k) == 1:
return k
# asking for the parameters
array_lenght = input("Enter Size of array: ")
variable = []
for i in range(array_lenght):
array_index = input("Enter element: ")
variable.append(array_index)
result = uniqueNumber(variable)
# printing result
print(result)
|
code/bit_manipulation/src/twice_unique_number/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/src/twice_unique_number/twice_unique_number.c | #include <stdio.h>
void findUnique2(int *a,int n){
int res=0;
for(int i=0;i<n;i++){
res = res^a[i];
}
// find the rightmost set bit in res
int i=0;
int temp=res;
while(temp>0){
if(temp&1){
break;
}
i++;
temp = temp>>1;
}
int mask = (1<<i);
int firstNo = 0;
for(int i=0;i<n;i++){
if((mask&a[i])!=0){
firstNo = firstNo^a[i];
}
}
int secondNo = res^firstNo;
printf("%d\n",firstNo);
printf("%d\n",secondNo);
}
int main(){
int n;
int a[] = {1,3,5,6,3,2,1,2};
n = sizeof(a)/sizeof(int);
findUnique2(a,n);
return 0;
}
|
code/bit_manipulation/src/twice_unique_number/twice_unique_number.cpp | #include <iostream>
using namespace std;
//Part of Cosmos by OpenGenus Foundation
void findUnique2(int *a, int n)
{
int res = 0;
for (int i = 0; i < n; i++)
res = res ^ a[i];
// find the rightmost set bit in res
int i = 0;
int temp = res;
while (temp > 0)
{
if (temp & 1)
break;
i++;
temp = temp >> 1;
}
int mask = (1 << i);
int firstNo = 0;
for (int i = 0; i < n; i++)
if ((mask & a[i]) != 0)
firstNo = firstNo ^ a[i];
int secondNo = res ^ firstNo;
cout << firstNo << endl;
cout << secondNo << endl;
}
int main()
{
int n;
int a[] = {1, 3, 5, 6, 3, 2, 1, 2};
n = sizeof(a) / sizeof(int);
findUnique2(a, n);
return 0;
}
|
code/bit_manipulation/src/xor_swap/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
## Xor Swap
In computer programming, the XOR swap is an algorithm that uses the XOR
bitwise operation to swap values of distinct
variables having the same data type without using a temporary variable.
## Proof of correctness
Let's say we have two distinct registers R1 and R2 as in the table below,
with initial values A and B respectively.
| Step | Operation | R1 | R2 |
|--- |--- |--- |--- |
| 0 | Initial | A | B |
| 1 | R1 := R1 ^ R2 | A ^ B | B |
| 2 | R2 := R1 ^ R2 | A ^ B | (A ^ B) ^ B => A |
| 3 | R1 := R1 ^ R2 | (A ^ B) ^ A => B | A |
|
code/bit_manipulation/src/xor_swap/xor_swap.c | #include <stdio.h>
/*
* This can be similarly implemented for other data types
*/
void
xor_swap(int *a, int *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
return;
}
int main()
{
int a = 10, b = 15;
printf("Before swapping: A = %d and B = %d\n", a, b);
xor_swap(&a, &b);
printf("After swapping: A = %d and B = %d\n", a, b);
return 0;
} |
code/bit_manipulation/src/xor_swap/xor_swap.cpp | #include <iostream>
using namespace std;
void xor_swap(int * a, int * b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main()
{
int a = 10, b = 15;
cout << "Before swapping: A = " << a << " and B = " << b << "\n";
xor_swap(&a, &b);
cout << "After swapping: A = " << a << " and B = " << b << "\n";
return 0;
}
|
code/bit_manipulation/src/xor_swap/xor_swap.go | package main
import "fmt"
func XorSwap(r1 *int, r2 *int) {
*r1 = *r1 ^ *r2
*r2 = *r1 ^ *r2
*r1 = *r1 ^ *r2
return
}
func main() {
A := 10
B := 15
fmt.Printf("Before swapping: A = %d and B = %d\n", A, B)
XorSwap(&A, &B)
fmt.Printf("After swapping: A = %d and B = %d\n", A, B)
}
|
code/bit_manipulation/src/xor_swap/xor_swap.js | // Part of Cosmos by OpenGenus Foundation
function xorSwap(a, b) {
console.log(`Before swap: a = ${a}, b = ${b}`);
a = a ^ b; // Step 1: a now contains the XOR of both
b = a ^ b; // Step 2: b gets the original value of a
a = a ^ b; // Step 3: a gets the original value of b
console.log(`After swap: a = ${a}, b = ${b}`);
}
// Example usage:
let x = 5;
let y = 10;
xorSwap(x, y);
|
code/bit_manipulation/src/xor_swap/xor_swap.py | # Part of Cosmos by OpenGenus Foundation
# Swaps two given numbers making use of xor
# Works for both python 2 and python 3
def xorswap(n, m):
n = m ^ n
m = n ^ m
n = m ^ n
return n, m
n = 10
m = 15
print("Earlier A was equal to ", n, " and B was equal to ", m)
n, m = xorswap(n, m)
print("Now A is equal to ", n, " and B is equal to ", m)
|
code/bit_manipulation/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/bit_manipulation/test/addition_using_bits_test.cpp | #include <assert.h>
#include "./../src/addition_using_bits/addition_using_bits.cpp"
// Part of Cosmos by OpenGenus Foundation
int main()
{
// Testing bitwiseAddition function
assert(bitwiseAddition(10, 5) == (10 + 5));
assert(bitwiseAddition(5, 10) == (5 + 10));
assert(bitwiseAddition(0, 1) == (0 + 1));
assert(bitwiseAddition(2, 0) == (2 + 0));
assert(bitwiseAddition(-27, 3) == (-27 + 3));
assert(bitwiseAddition(27, -3) == (27 + -3));
assert(bitwiseAddition(-1, -1) == (-1 + -1));
// Testing bitwiseAdditionRecursive function
assert(bitwiseAdditionRecursive(2, 3) == (2 + 3));
assert(bitwiseAdditionRecursive(3, 2) == (3 + 2));
assert(bitwiseAdditionRecursive(1, 0) == (1 + 0));
assert(bitwiseAdditionRecursive(0, 3) == (0 + 3));
assert(bitwiseAdditionRecursive(25, -50) == (25 + -50));
assert(bitwiseAdditionRecursive(-25, 50) == (-25 + 50));
assert(bitwiseAdditionRecursive(-5, -10) == (-5 + -10));
std::cout << "Testing Complete" << "\n";
}
|
code/blockchain/Application.java | import java.util.*;
import java.util.List;
public class Application {
static List<Block> blockchain=new ArrayList<Block>();
final static int difficulty=4;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Create Genesis Block");
addBlock(new Block("0","this is first transaction"));
addBlock(new Block(blockchain.get(blockchain.size()-1).currentHashValue(),"Second Transaction"));
System.out.println(blockchain.toString());
System.out.println(UtilityClass.getJSONData(blockchain));
System.out.println(isChainValid(blockchain));
}
public static void addBlock(Block newBlock) {
newBlock.mineBlock(difficulty);
blockchain.add(newBlock);
System.out.println("Block added to blockchain");
}
public static Boolean isChainValid(List<Block> blockchain) {
Block currentBlock;
Block previousBlock;
//loop through blockchain to check hashes:
for(int i=1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i-1);
//compare registered hash and calculated hash:
if(!currentBlock.currentHashValue().equals(currentBlock.calculateHash()) ){
System.out.println("Current Hashes not equal");
return false;
}
//compare previous hash and registered previous hash
if(!previousBlock.currentHashValue().equals(currentBlock.prevHashValue()) ) {
System.out.println("Previous Hashes not equal");
return false;
}
}
return true;
}
} |
code/blockchain/Block.java | import java.util.Date;
public class Block {
private String previousHash;
private String currentHash;
private String data;
private Long timestamp;
private int nonce=0;
public Block(String previousHash,String data) {
this.previousHash=previousHash;
this.data=data;
this.timestamp=new Date().getTime();
this.currentHash=calculateHash();
}
public String currentHashValue()
{
return currentHash;
}
public String prevHashValue()
{
return previousHash;
}
public String calculateHash() {
String calculateHash=UtilityClass.getSHA256Hash(
previousHash+data+Long.toString(timestamp)+
Integer.toString(nonce)
);
return calculateHash;
}
public void mineBlock(int difficulty) {
String target=UtilityClass.getDifficultyString(difficulty);
while(!currentHash.substring(0,difficulty).equals(target)) {
nonce=nonce+1;
currentHash=calculateHash();
}
System.out.println("Block is mined "+currentHash);
}
} |
code/blockchain/UtilityClass.java | import java.security.MessageDigest;
import java.util.List;
import com.google.gson.GsonBuilder;
public class UtilityClass {
public static String getDifficultyString(int difficulty) {
return new String(new char[difficulty]).replace('\0','0');
}
public static String getSHA256Hash(String inputString) {
try {
MessageDigest message=MessageDigest.getInstance("SHA-256");
byte[] hash=message.digest(inputString.getBytes("UTF-8"));
StringBuffer hexString=new StringBuffer();
for(int i=0;i<hash.length;i++) {
String hex=Integer.toHexString(0xff&hash[i]);
if(hex.length()==1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
catch(Exception e) {
System.out.println("Exception occured");
}
return null;
}
public static String getJSONData(List<Block> blockchain) {
return new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
}
} |
code/blockchain/explainBlockchain.md | ### Explanation of blockchain
Please read article below for more details.
[Explaining Blockchain intuitively to a Five year old!](https://iq.opengenus.org/explaining-blockchain-to-a-5-year-old/)
Blockchain Technology basically helps in Trade. Because of this technology, you can trade with anyone around the globe, without knowing about him personally and without any intermediate party (like banks or other companies).
For eg: Let’s say you want to sell your smartphone. Currently you will use platform like ebay which acts as an intermediate between you and the person to whom you want to sell.
The payments might be processed via some bank which will cost you or/and the other person some money. Now because of blockchain, you will be able to sell your smartphone to that person without actually involving ebay or any other bank in between. That’s blockchain explained on very basic level.
Lets level up a bit. Blockchain is basically a network of computers called nodes which all have same history of transactions. So instead of one company or a database which holds all the information, now the information is spread across whole of the network. Whenever a transaction occurs, that is validated by everyone and is put ahead in that history of transactions in that network. All the transactions are encoded using a technique called cryptography.
Please note that blockchain is not only about Bitcoin. Because it is in news all over, people think blockchain means bitcoin. Bitcoin is simply a digital currency which is build using blockchain technology. There are many use cases being build over which we can basically trade any asset using blockchain.
The bottom line is that the basic explanation of a blockchain ledger includes the following concepts:
It's maintained by every user on the blockchain.
It's decentralized, meaning every user has a complete copy.
It can track the entire transaction history of any given item or currency. |
code/cellular_automaton/src/brians_brain/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Cellular Automaton
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/cellular_automaton/src/conways_game_of_life/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Cellular Automaton
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/cellular_automaton/src/conways_game_of_life/conway.java | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Conway extends JFrame {
private int size = 80, gen =0, kill = 1;
private JButton grid[][] = new JButton[size][size], toggle, wow, gun, clear;
private JButton exit; // for termination of the program
private int grid_num[][] = new int[size][size];
private JLabel status;
Conway() {
Container cp = this.getContentPane();
JPanel gd = new JPanel(new GridLayout(size, size));
for (int i = 0;i<size;i++)
for (int j = 0;j<size;j++) {
grid[i][j] = new JButton();
grid[i][j].setBackground(Color.WHITE);
gd.add(grid[i][j]);
grid[i][j].addActionListener(new Listen());
grid[i][j].setBorder(null);
}
JPanel st_bar = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
status = new JLabel("Status");
toggle = new JButton("Start");
wow = new JButton("Benchmark");
gun = new JButton("Glider Gun");
clear = new JButton("Clear");
exit = new JButton("Exit");
st_bar.add(status);
st_bar.add(toggle);
st_bar.add(wow);
st_bar.add(gun);
st_bar.add(clear);
st_bar.add(exit);
toggle.addActionListener(new Listen());
wow.addActionListener(new Listen());
gun.addActionListener(new Listen());
clear.addActionListener(new Listen());
exit.addActionListener(new Listen());
cp.setLayout(new BorderLayout());
cp.add(gd, BorderLayout.CENTER);
cp.add(st_bar, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Game of Life!");
setLocationRelativeTo(null);
setSize(600, 600);
setVisible(true);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {}
}
//A function that returns Live neighbours...
//---------------------------------LOGIC-------------------------
public int neigh(int x, int y) {
int ctr = 0;
int startPosX = (x - 1 < 0) ? x : x-1;
int startPosY = (y - 1 < 0) ? y : y-1;
int endPosX = (x + 1 > size-1) ? x : x+1;
int endPosY = (y + 1 > size-1) ? y : y+1;
for (int i = startPosX; i<=endPosX; i++)
for (int j = startPosY; j<=endPosY; j++)
if (grid_num[i][j] == 1)
ctr++;
return ctr;
}
//-------------------------------LOGIC ENDS---------------------
public void setGrid() {
for (int i=0;i<size;i++)
for (int j = 0;j<size;j++)
if (grid_num[i][j] == 1)
grid[i][j].setBackground(Color.BLACK);
else
grid[i][j].setBackground(Color.WHITE);
}
public void loop() {
int tmp = 0;
int tmp_grid[][] = new int[size][size];
for (int i=0;i<size;i++)
for (int j = 0;j<size;j++) {
tmp = neigh(i, j);
tmp = (grid_num[i][j] == 1) ? tmp-1 : tmp;
if (tmp < 2 || tmp > 3)
tmp_grid[i][j] = 0;
else if(tmp == 3)
tmp_grid[i][j] = 1;
else
tmp_grid[i][j] = grid_num[i][j];
}
grid_num = tmp_grid;
setGrid();
}
//----------------------------------------------------------------------------------------------------------------------------------
public static void main(String[] args) {
SwingUtilities.invokeLater(new Jobs());
}
public static class Jobs implements Runnable {
public void run() {
new Conway();
}
}
//-----------------------------------------------------------------------------------------------------------------------------------
public class Seed extends Thread {
public void run() {
for (int i =0;i<10000;i++){
if (kill == 1) break;
loop();
status.setText("Generation: "+(gen++));
try {
Thread.sleep(100);
}
catch(InterruptedException e) {}
}
}
}
public class Listen implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == toggle){
if (kill == 0) {
toggle.setText("Start");
kill = 1;
}
else {
toggle.setText("Stop");
kill = 0;
Seed t = new Seed();
t.start();
}
}
else if (ae.getSource() == wow) {
for (int i = 0;i<size;i++) {
grid[size/2][i].setBackground(Color.BLACK);
grid_num[size/2][i] = 1;
}
}
else if (ae.getSource() == gun) {
int i_fill[] = {4, 4, 5, 5, 2, 2, 3, 4, 5, 6, 7, 8, 8, 5, 3, 4, 5, 6, 5, 2, 3, 4 , 2, 3, 4, 1, 5, 0, 1, 5, 6, 2, 2, 3, 3,7};
int j_fill[] = {0,1,0,1,12,13,11,10,10,10,11,12,13,14,15,16,16,16,17,20,20,20,21,21,21,22,22,24,24,24,24,34,35,34,35, 15};
int shift = 4;
for (int i = 0;i<36;i++){
grid_num[i_fill[i]+shift][j_fill[i]+shift] = 1;
grid[i_fill[i]][j_fill[i]].setBackground(Color.BLACK);
}
}
else if (ae.getSource() == clear) {
for (int i = 0;i<size;i++)
for(int j=0;j<size;j++) {
grid_num[i][j] = 0;
grid[i][j].setBackground(Color.GRAY);
}
}
else if (ae.getSource() == exit) {
System.exit(0);
}
else {
for (int i = 0;i<size;i++)
for(int j=0;j<size;j++) {
if (ae.getSource() == grid[i][j]) {
if (grid_num[i][j] == 0) {
grid_num[i][j] = 1;
grid[i][j].setBackground(Color.BLACK);
return;
} else if (grid_num[i][j] == 1) {
grid_num[i][j] = 0;
grid[i][j].setBackground(Color.WHITE);
return;
}
}
}
}
}
}
}
|
code/cellular_automaton/src/conways_game_of_life/conways_game_of_life.rb | # Part of Cosmos by OpenGenus Foundation
class GameOfLife
attr_accessor :matrix, :rows, :columns
def initialize(rows, columns)
@rows = rows
@columns = columns
@matrix = []
rows.times do |row|
@matrix[row] ||= []
columns.times do |column|
@matrix[row][column] = false
end
end
end
def next_tick
new_matrix = []
rows.times do |row|
new_matrix[row] ||= []
columns.times do |column|
alive_neighbours_count = neighbours(row, column).count(true)
if !matrix[row][column] && alive_neighbours_count == 3
new_matrix[row][column] = true
elsif matrix[row][column] && alive_neighbours_count != 2 && alive_neighbours_count != 3
new_matrix[row][column] = false
else
new_matrix[row][column] = matrix[row][column]
end
end
end
self.matrix = new_matrix
end
def print_cells
rows.times do |row|
columns.times do |column|
matrix[row][column] ? print('O') : print('-')
end
print "\n"
end
print "\n"
end
def neighbours(row, column)
neighbours = []
rows_limit = matrix.count - 1
columns_limit = matrix[0].count - 1
([0, row - 1].max..[rows_limit, row + 1].min).to_a.each do |row_index|
([0, column - 1].max..[columns_limit, column + 1].min).to_a.each do |column_index|
neighbours << matrix[row_index][column_index] unless row_index == row && column_index == column
end
end
neighbours
end
end
game = GameOfLife.new(100, 100)
game.matrix[0][0] = true
game.matrix[0][1] = true
game.matrix[1][0] = true
game.matrix[1][2] = true
game.matrix[2][1] = true
game.matrix[2][2] = true
game.print_cells
5.times do
game.next_tick
game.print_cells
end
|
code/cellular_automaton/src/conways_game_of_life/game_of_life_c_sdl.c | /*
* Part of Cosmos by OpenGenus Foundation
* This program uses SDL 1.2
* Author : ABDOUS Kamel
*/
#include <stdlib.h>
#include <time.h>
#include <SDL/SDL.h>
/* -------------------------------------------------------------------- */
/* Change automaton state delay */
#define RESPAWN_DELAY 25
/*
* When SIMPLE_MODE = 1, the program displays dead cels in black, & alive cels in green.
* When SIMPLE_MODE = 0, the program also displays the reborn cells & cells that are going to die.
*/
#define SIMPLE_MODE 1
int X_NB_CELLS = 800, Y_NB_CELLS = 600, /* Number of cels */
X_CELL_SIZE = 1, Y_CELL_SIZE = 1, /* Size of cels */
WINDOW_WIDTH, WINDOW_HEIGHT; /* Calculated in main */
/* -------------------------------------------------------------------- */
/* This struct is passed as parameter to the SDL timer. */
typedef struct
{
int **cels, /* Cels matrix */
**buffer; /* This buffer is used to calculate the new state of the automaton */
} UpdateCelsTimerParam;
typedef enum
{
DEAD,
ALIVE,
REBORN,
DYING
} CelsState;
/* Function to call to launch the automaton */
int
launch_app(SDL_Surface* screen);
/* Updates the state of the automaton.
* That's a SDL timer callback function.
*/
Uint32
update_cels(Uint32 interval, void* param);
/* Inc neighborhood according to game of life rules. */
void
inc_neighborhood(int cel, int* neighborhood);
/* Returns the new state of cel regarding the value of neighborhood */
int
live_cel(int cel, int neighborhood);
void
display_cels(int** cels, SDL_Surface* screen);
void
display_one_cel(int cel, int x, int y, SDL_Surface* screen);
/* Function used to initialise the two matrices cels & buffer as size_x * size_y matrices. */
void
alloc_cels(int*** cels, int*** buffer, int size_x, int size_y);
void
free_cels(int** cels, int** buffer, int size_x);
/* Helper function that colores one pixel. */
void
set_pixel(SDL_Surface* surf, int x, int y, Uint32 color);
int
main()
{
srand(time(NULL));
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
fprintf(stderr, "Erreur lors de l'initialisation de la SDL : %s\n", SDL_GetError());
return (EXIT_FAILURE);
}
WINDOW_WIDTH = X_NB_CELLS * X_CELL_SIZE;
WINDOW_HEIGHT = Y_NB_CELLS * Y_CELL_SIZE;
SDL_Surface* screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
if (screen == NULL) {
fprintf(stderr, "Can't create application window : %s\n", SDL_GetError());
SDL_Quit();
return (EXIT_FAILURE);
}
int exit_code = launch_app(screen);
SDL_FreeSurface(screen);
SDL_Quit();
return (exit_code);
}
/* Function to call to launch the automaton */
int
launch_app(SDL_Surface* screen)
{
int **cels = NULL, **buffer;
alloc_cels(&cels, &buffer, X_NB_CELLS, Y_NB_CELLS);
SDL_Event event;
int stop = 0;
/* The SDL timer params */
UpdateCelsTimerParam timer_param = {cels, buffer};
SDL_AddTimer(RESPAWN_DELAY, update_cels, &timer_param);
while (!stop) {
SDL_PollEvent(&event);
switch (event.type) {
case SDL_QUIT:
stop = 1;
break;
}
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
display_cels(cels, screen);
SDL_Flip(screen);
}
free_cels(cels, buffer, X_NB_CELLS);
return (EXIT_SUCCESS);
}
/* Updates the state of the automaton.
* That's a SDL timer callback function.
*/
Uint32
update_cels(Uint32 interval, void* param)
{
UpdateCelsTimerParam* param_struct = param;
int **cels = param_struct->cels,
**buffer = param_struct->buffer;
int i = 0, j = 0, neighborhood;
/* Here we update the automaton state in the buffer */
while (i < X_NB_CELLS) {
j = 0;
/* Conditions in this loop are just an application of the game of life rules */
while (j < Y_NB_CELLS) {
if (cels[i][j] == REBORN)
buffer[i][j] = ALIVE;
else if (cels[i][j] == DYING)
buffer[i][j] = DEAD;
/* Number of useful cels in the neighborhood */
neighborhood = 0;
if (i != 0) {
inc_neighborhood(cels[i - 1][j], &neighborhood);
if (j != 0)
inc_neighborhood(cels[i - 1][j - 1], &neighborhood);
if (j != Y_NB_CELLS - 1)
inc_neighborhood(cels[i - 1][j + 1], &neighborhood);
}
if (i != X_NB_CELLS - 1) {
inc_neighborhood(cels[i + 1][j], &neighborhood);
if(j != 0)
inc_neighborhood(cels[i + 1][j - 1], &neighborhood);
if(j != Y_NB_CELLS - 1)
inc_neighborhood(cels[i + 1][j + 1], &neighborhood);
}
if (j != 0)
inc_neighborhood(cels[i][j - 1], &neighborhood);
if (j != Y_NB_CELLS - 1)
inc_neighborhood(cels[i][j + 1], &neighborhood);
buffer[i][j] = live_cel(cels[i][j], neighborhood);
j++;
}
++i;
}
/* Here we copy the new state in the cels matrix */
for (i = 0; i < X_NB_CELLS; ++i) {
for (j = 0; j < Y_NB_CELLS; ++j)
cels[i][j] = buffer[i][j];
}
return (interval);
}
/* Inc neighborhood according to game of life rules. */
void
inc_neighborhood(int cel, int* neighborhood)
{
if (cel == ALIVE || cel == REBORN)
(*neighborhood)++;
}
/* Returns the new state of cel regarding the value of neighborhood */
int
live_cel(int cel, int neighborhood)
{
if (!SIMPLE_MODE) {
if (cel == ALIVE || cel == REBORN) {
if(neighborhood == 2 || neighborhood == 3)
return (ALIVE);
else
return (DYING);
}
else {
if(neighborhood == 3)
return (REBORN);
else
return (DEAD);
}
}
else {
if (cel == ALIVE)
return (neighborhood == 2 || neighborhood == 3);
else
return (neighborhood == 3);
}
}
void
display_cels(int** cels, SDL_Surface* screen)
{
int i = 0, j = 0;
while (i < X_NB_CELLS) {
j = 0;
while (j < Y_NB_CELLS) {
display_one_cel(cels[i][j], i, j, screen);
++j;
}
++i;
}
}
void
display_one_cel(int cel, int x, int y, SDL_Surface* screen)
{
int i = 0, j = 0,
r = 0, g = 0, b = 0;
if (!SIMPLE_MODE) {
if (cel == ALIVE)
g = 255;
else if (cel == DEAD)
r = 255;
else if (cel == REBORN)
b = 255;
else {
r = 255;
g = 140;
}
}
else {
if (cel == DEAD)
return;
g = 255;
}
while (i < X_CELL_SIZE) {
j = 0;
while (j < Y_CELL_SIZE) {
set_pixel(screen, x * X_CELL_SIZE + i, y * Y_CELL_SIZE + j, SDL_MapRGB(screen->format, r, g, b));
++j;
}
++i;
}
}
/* Function used to initialise the two matrices cels & buffer as size_x * size_y matrices. */
void
alloc_cels(int*** cels, int*** buffer, int size_x, int size_y)
{
*cels = malloc(sizeof(int*) * size_x);
*buffer = malloc(sizeof(int*) * size_x);
int i = 0, j = 0;
while (i < size_x) {
(*cels)[i] = malloc(sizeof(int) * size_y);
(*buffer)[i] = malloc(sizeof(int) * size_y);
j = 0;
while (j < size_y) {
/* The initial state is picked randomly */
(*cels)[i][j] = rand() % 2;
++j;
}
i++;
}
}
void
free_cels(int** cels, int** buffer, int size_x)
{
int i = 0;
while (i < size_x) {
free(cels[i]);
free(buffer[i]);
++i;
}
free(cels);
free(buffer);
}
/* --------------------------------------------------------------------------------- */
/* Helper function that colores one pixel. */
void
set_pixel(SDL_Surface* surf, int x, int y, Uint32 color)
{
int bpp = surf->format->BytesPerPixel;
Uint8* p = (Uint8*)surf->pixels + y * surf->pitch + x * bpp;
switch (bpp) {
case 1:
*p = color;
break;
case 2:
*(Uint16*)p = color;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
p[0] = (color >> 16) & 0xff;
p[1] = (color >> 8) & 0xff;
p[2] = color & 0xff;
}
else {
p[0] = color & 0xff;
p[1] = (color >> 8) & 0xff;
p[2] = (color >> 16) & 0xff;
}
break;
case 4:
*(Uint32*)p = color;
break;
}
}
|
code/cellular_automaton/src/conways_game_of_life/gameoflife.hs | {-# LANGUAGE DeriveFunctor #-}
module GameOfLife where
import Control.Comonad
import Graphics.Gloss
import Data.List
import Control.Monad
import System.Random
data Zipper a = Zipper [a] a Int [a] deriving (Functor)
-- Zipper ls x n rs represents the doubly-infinite list (reverse ls ++
-- [x] ++ rs) viewed at offset n
instance (Show a) => Show (Zipper a) where
show (Zipper ls x n rs) =
show (reverse (take 3 ls)) ++ " " ++ show (x,n) ++ " " ++ show (take 3 rs)
instance Comonad Zipper
where
extract (Zipper _ x _ _) = x
duplicate z = Zipper (tail $ iterate back z) z 0 (tail $ iterate forth z)
back, forth :: Zipper a -> Zipper a
back (Zipper (l:ls) x n rs) = Zipper ls l (n-1) (x:rs)
forth (Zipper ls x n (r:rs)) = Zipper (x:ls) r (n+1) rs
newtype Grid a = Grid (Zipper (Zipper a)) deriving (Functor)
instance Show a => Show (Grid a) where
show (Grid (Zipper ls x n rs)) =
unlines $ zipWith (\a b -> a ++ " " ++ b)
(map show [n-3..n+3])
(map show (reverse (take 3 ls) ++ [x] ++ (take 3 rs)))
instance Comonad Grid
where
extract = get
duplicate (Grid z) = fmap Grid $ Grid $ roll $ roll z
where
roll g = Zipper (tail $ iterate (fmap back) g) g 0 (tail $ iterate (fmap forth) g)
up, down, right, left :: Grid a -> Grid a
up (Grid g) = Grid (back g)
down (Grid g) = Grid (forth g)
left (Grid g) = Grid (fmap back g)
right (Grid g) = Grid (fmap forth g)
set :: a -> Grid a -> Grid a
set y (Grid (Zipper ls row n rs)) = (Grid (Zipper ls (set' row) n rs))
where set' (Zipper ls' x m rs') = Zipper ls' y m rs'
get :: Grid a -> a
get (Grid (Zipper _ (Zipper _ x _ _) _ _)) = x
resetH :: Grid a -> Grid a
resetH g@(Grid (Zipper _ (Zipper _ _ m _) n _))
| m > 0 = resetH (left g)
| m < 0 = resetH (right g)
| otherwise = g
resetV :: Grid a -> Grid a
resetV g@(Grid (Zipper _ (Zipper _ _ m _) n _))
| n > 0 = resetV (up g)
| n < 0 = resetV (down g)
| otherwise = g
recenter :: Grid a -> Grid a
recenter = resetH . resetV
falseGrid :: Grid Bool
falseGrid =
let falseRow = Zipper falses False 0 falses
falses = repeat False
falseRows = repeat falseRow
in Grid (Zipper falseRows falseRow 0 falseRows)
copyBox :: [[a]] -> Grid a -> Grid a
copyBox [] g = recenter g
copyBox (xs:xss) g = copyBox xss (down $ copyArray xs g)
where
copyArray [] g = resetH g
copyArray (x:xs) g = copyArray xs (right $ set x g)
extractBox :: Int -> Int -> Grid a -> [[a]]
extractBox m n (Grid g) = map (f n) $ (f m) g
where
f m (Zipper _ x _ xs) = x : take (m - 1) xs
liveNeighborCount :: Grid Bool -> Int
liveNeighborCount grid = length . filter (True == ) $ map (\direction -> get $ direction grid) directions
where
directions = [left, right, up, down, up . left, up . right, down . left, down . right]
stepCell :: Grid Bool -> Bool
stepCell grid
| cell == True && numNeighbors < 2 = False
| cell == True && numNeighbors < 4 = True
| cell == True && numNeighbors > 3 = False
| cell == False && numNeighbors == 3 = True
| otherwise = cell
where
cell = extract grid
numNeighbors = liveNeighborCount grid
makeRandomGrid :: Int -> Int -> IO (Grid Bool)
makeRandomGrid m n = do
bools <- (replicateM m $ replicateM n (randomIO :: IO Bool))
return $ copyBox bools falseGrid
toPicture :: Int -> Int -> Grid Bool -> Picture
toPicture m n grid =
let bools = extractBox m n grid
(width, height) = (fromIntegral m , fromIntegral n)
indexed = map (zip [0.. ] . sequence) . zip [0..]
cell = rectangleSolid 10 10
draw (x, (y, s)) = color (if s then black else white) . translate ((x-width/2)*10+5) ((y-height/2)*10+5)
in pictures . map (pictures . map (\s -> draw s cell)) . indexed $ bools
main :: IO ()
main = do
grid <- makeRandomGrid 100 100
simulate FullScreen blue 1 grid (toPicture 100 100) (const $ const (=>> stepCell))
|
code/cellular_automaton/src/conways_game_of_life/life.c | #include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Part of Cosmos by OpenGenus Foundation
#define width 40
#define height 30
const char* clear = "\e[1;1H\e[2J";
int main(){
srand(time(NULL));
int board[height][width];
int temp[height][width];
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
board[i][j] = rand() % 2;
}
}
memcpy(temp, board, sizeof(int) * width * height);
while (1) {
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
putc(32 + 16 * board[i][j], stdout);
}
putc('\n', stdout);
}
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int sum = board[(i + 1) % height][(j + 1) % width] +
board[(i + 1) % height][j] +
board[(i + 1) % height][(j + width - 1) % width] +
board[i][(j + 1) % width] +
board[i][(j + width - 1) % width] +
board[(i + height - 1) % height][(j + 1) % width] +
board[(i + height - 1) % height][j] +
board[(i + height - 1) % height][(j + width - 1) % width];
temp[i][j] = (temp[i][j] && sum >= 2 && sum <= 3) || sum == 3;
}
}
memcpy(board, temp, sizeof(int) * width * height);
getchar();
printf("%s", clear);
}
return 0;
}
|
code/cellular_automaton/src/conways_game_of_life/life.cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Defines the world size parameters
const int SIZE_X = 50;
const int SIZE_Y = 160;
// Number of random cells are filled
const int number = SIZE_X * SIZE_Y / 8;
void loadConfig(char world[][SIZE_Y]);
// Initializes world and loads up several default values
void generation(char world[][SIZE_Y], int& gen);
// Takes the world array and decides whether cells live, die, or multiply.
void copyGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y]);
// Copies the current generation from world to worldCopy.
void updateGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y]);
// Updates the current generation in worldCopy to world.
void display(const char world[][SIZE_Y], ofstream& fout, const int gen);
// Outputs the world as text.
// Records each successive world generation in a text file.
int getNeighbors(const char world[][SIZE_Y], int posX, int posY);
// Retrieves the amount of neighbors a cell has
int main()
{
int gen(0);
char world[SIZE_X][SIZE_Y];
ofstream fout;
fout.open("life.txt");
if (fout.fail())
{
cout << "Opening file for output failed!\n";
exit(1);
}
loadConfig(world);
display(world, fout, gen);
char c;
cout << "\nPress return to create a new generation and press x to exit!\n";
cin.get(c);
while (c == '\n') {
generation(world, gen);
display(world, fout, gen);
cout << "\nPress return to create a new generation and press x to exit!\n";
cin.get(c);
}
return 0;
}
void loadConfig(char world[][SIZE_Y])
{
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
world[i][j] = '-';
srand(time(NULL));
for (int i = 0; i < number; i++)
{
int randX = rand() % SIZE_X;
int randY = rand() % SIZE_Y;
world[randX][randY] = '*';
}
}
int getNeighbors(const char world[][SIZE_Y], int posX, int posY)
{
int neighbors(0);
int row = posX - 1, column = posY - 1;
// Top-left
if (column >= 0 && row >= 0)
if (world[row][column] == '*')
neighbors++;
// Top-middle
column++;
if (row >= 0)
if (world[row][column] == '*')
neighbors++;
// Top-right
column++;
if (column < SIZE_Y && row >= 0)
if (world[row][column] == '*')
neighbors++;
row = posX, column = posY; // Reset
// Left
column--;
if (column >= 0)
if (world[row][column] == '*')
neighbors++;
// Right
column = posY + 1;
if (column < SIZE_Y)
if (world[row][column] == '*')
neighbors++;
row = posX + 1, column = posY - 1; // Reset
// Bottom-left
if (row < SIZE_X && column >= 0)
if (world[row][column] == '*')
neighbors++;
column++;
if (row < SIZE_X)
if (world[row][column] == '*')
neighbors++;
column++;
if (row < SIZE_X && column < SIZE_Y)
if (world[row][column] == '*')
neighbors++;
return neighbors;
}
void generation(char world[][SIZE_Y], int& gen)
{
char worldCopy[SIZE_X][SIZE_Y];
copyGeneration(world, worldCopy);
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
{
int neighbors = getNeighbors(world, i, j);
if (neighbors <= 1 || neighbors > 3)
worldCopy[i][j] = '-';
else if (neighbors == 3 && worldCopy[i][j] == '-')
worldCopy[i][j] = '*';
}
updateGeneration(world, worldCopy);
gen++;
}
void copyGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y])
{
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
worldCopy[i][j] = world[i][j];
}
void updateGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y])
{
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
world[i][j] = worldCopy[i][j];
}
void display(const char world[][SIZE_Y], ofstream& fout, const int gen)
{
cout << "Generation " << gen << endl;
fout << 'G' << ' ' << gen << '\n';
for (int i = 0; i < SIZE_X; i++)
{
for (int j = 0; j < SIZE_Y; j++)
{
char cell = world[i][j];
cout << cell;
fout << cell;
}
cout << endl;
fout << '\n';
}
cout << endl;
fout << '\n';
}
|
code/cellular_automaton/src/conways_game_of_life/life.go | package main
import (
"os"
"os/exec"
"bytes"
"fmt"
"math/rand"
"time"
)
type Game struct {
width int
height int
data [][]bool
}
func NewGame(width int, height int) *Game {
data := make([][]bool, height)
for i := range data {
data[i] = make([]bool, width)
}
return &Game{
width: width,
height: height,
data: data,
}
}
func (g *Game) Init(n int) {
for i := 0; i < n; i ++ {
g.Set(rand.Intn(g.width), rand.Intn(g.height), true)
}
}
func (g *Game) Set(i int, j int, b bool) {
g.data[j][i] = b
}
// Check the cell is alive
func (g *Game) Alive(i int, j int) bool {
i = (i + g.width) % g.width
j = (j + g.height) % g.height
return g.data[j][i]
}
// Return next state of a cell, false = dead, true = alive
func (g *Game) NextState(x int, y int) bool {
alive := 0
for i := -1; i <= 1; i++ {
for j := -1; j <= 1; j++ {
if !((i == 0) && (j == 0)) && g.Alive(x + i, y + j) {
alive++
}
}
}
return alive == 3 || alive == 2 && g.Alive(x, y)
}
func (g *Game) Next() *Game {
ng := NewGame(g.width, g.height)
for i := 0; i < g.width; i ++ {
for j := 0; j < g.height; j ++ {
ng.Set(i, j, g.NextState(i, j))
}
}
return ng
}
func (g *Game) String() string {
var buf bytes.Buffer
for j := 0; j < g.height; j ++ {
buf.WriteString("'")
for i := 0; i < g.width; i ++ {
if g.Alive(i, j) {
buf.WriteString("o")
} else {
buf.WriteString(" ")
}
}
buf.WriteString("'\n")
}
return buf.String()
}
func main() {
g := NewGame(10, 10)
g.Init(30)
for i := 0; i < 100; i ++ {
// Clear screen
c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()
fmt.Print(g)
g = g.Next()
time.Sleep(100 * time.Millisecond)
}
fmt.Println("vim-go")
}
|
code/cellular_automaton/src/conways_game_of_life/life.py | from tkinter import *
import random
class Game:
def __init__(self):
self.createButtons()
def createButtons(self):
self.buttons = {}
for i in range(0, 400):
status = random.choice([1, 0])
self.buttons[i] = [
Button(root, bg=("yellow" if status == 1 else "black")),
status,
]
self.buttons[i][0].grid(row=i // 20, column=i % 20)
def run(self):
for k in range(0, 400):
row = k // 20
column = k % 20
c = 0
for i in [row - 1, row, row + 1]:
for j in [column - 1, column, column + 1]:
if self.validButton(i, j):
c = c + self.buttons[i * 20 + j][1]
print(c)
c = c - self.buttons[k][1]
if c <= 1 or c >= 4:
self.buttons[k][0].configure(bg="black")
elif self.buttons[k][1] == 1 or c == 3:
self.buttons[k][0].configure(bg="yellow")
else:
self.buttons[k][0].configure(bg="black")
for k in range(0, 400):
self.buttons[k][1] = 0 if self.buttons[k][0].cget("bg") == "black" else 1
if k % 20 == 0:
print(" ")
root.after(500, self.run)
def validButton(self, i, j):
if i < 0 or j < 0 or j > 19 or i > 19:
return False
else:
return True
def main():
global root
root = Tk()
root.title("Game Of Life")
game = Game()
root.after(500, game.run)
root.mainloop()
if __name__ == "__main__":
main()
|
code/cellular_automaton/src/conways_game_of_life/life.rb | #!/usr/bin/env ruby
# Part of Cosmos by OpenGenus Foundation
class GameOfLife
attr_accessor :board
def initialize(board = [])
self.board = board.empty? ? Array.new(rand(1..10)) { Array.new(rand(1..10), rand(0..1)) } : board
end
def play(turns = 1)
for turn in 1..turns
next_board = Array.new(board.size) { Array.new(board.first.size, 0) }
next_board.each_index do |row|
next_board[row].each_index { |col| next_board[row][col] = next_state(row, col) }
end
self.board = next_board
pretty_print
end
end
def pretty_print
board.each do |row|
puts row.join(' ')
end
puts '**' * board.size
end
private
def next_state(row, col)
alive = count_alive_neighbors(row, col)
return 1 if (alive > 1) && (alive < 4) && (board[row][col] == 1)
return 1 if (alive == 3) && (board[row][col] == 0)
0
end
def count_alive_neighbors(row, col)
neighbors = 0
for i in -1..1
for j in -1..1
next if (i == 0) && (j == 0)
neighbors += 1 if alive_neighbor?(row + i, col + j)
end
end
neighbors
end
def alive_neighbor?(row, col)
(row >= 0) && (row < board.size) && (col >= 0) && (col < board.first.size) && (board[row][col] == 1)
end
end
board = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
game = GameOfLife.new(board)
game.pretty_print
game.play(3)
|
code/cellular_automaton/src/elementary_cellular_automata/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Cellular Automaton
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/cellular_automaton/src/elementary_cellular_automata/elementarycellularautomaton.java | /* Part of Cosmos by OpenGenus Foundation */
public class ElementaryCellularAutomaton {
private static final int SIZE = 200;
private static final int HISTORY = 200;
private final byte rule;
private boolean[][] grid = new boolean[HISTORY][SIZE];
private int step = 0;
public static void main(String[] args) {
ElementaryCellularAutomaton elCell = new ElementaryCellularAutomaton((byte)2);
do {
System.out.println(elCell);
} while(elCell.step());
}
/**
* This is the main class for an elementary cellular automaton
* @param ruleNr Identifier for which of the 256 rules should be used
*/
public ElementaryCellularAutomaton(byte ruleNr) {
rule = ruleNr;
/*
* Initialize center to 1
* (other initializations are possible and will result in different behavior)
*/
grid[0][SIZE / 2] = true;
}
public boolean step() {
if (step < (HISTORY-1)) {
for (int i = 0; i < SIZE; i++) {
byte neighbors = getNeighbors(i);
boolean nextValue = (((rule >> neighbors) & 1) == 1);
grid[step+1][i] = nextValue;
}
step++;
return true;
} else {
return false;
}
}
/*
* Convert the cell and its neighbors to a 3-bit number
*/
private byte getNeighbors(int cell) {
return (byte) ((grid[step][getCellIndex(cell-1)] ? 4 : 0) +
(grid[step][getCellIndex(cell)] ? 2 : 0) +
(grid[step][getCellIndex(cell+1)] ? 1 : 0));
}
/*
* Convert the cell number to the index of the grid array
*/
private int getCellIndex(int cell) {
int result = cell%SIZE;
if(result < 0) {
result += SIZE;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
boolean[] array = grid[step];
for (int i = 0; i < array.length; i++) {
if (array[i]) builder.append("1"); else builder.append("0");
}
return builder.toString();
}
}
|
code/cellular_automaton/src/genetic_algorithm/genetic.cpp | /**
* Root finding using genetic algorithm (Uses C++11).
* Reference: https://arxiv.org/abs/1703.03864
*/
#include <algorithm>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
struct StopCondition
{
StopCondition(double tol, long iter)
: tolerance(tol)
, iterations(iter)
{
}
double tolerance;
long iterations;
};
struct GAConfig
{
GAConfig(double learning_rate, double variance, long generation_size)
: lr(learning_rate)
, var(variance)
, size(generation_size)
{
factor = lr / (var * size);
}
double lr;
double var;
long size;
double factor;
};
template <typename UnaryFunc>
double solve(UnaryFunc f, double initial, GAConfig conf, StopCondition cond)
{
std::default_random_engine gen;
std::normal_distribution<double> normal(0, 1);
std::vector<double> noise(conf.size);
std::vector<double> generation(conf.size);
std::vector<double> fitness(conf.size);
double x = initial, error = 0;
long iter = 0;
do {
double delta = 0;
for (int i = 0; i < conf.size; ++i)
{
noise[i] = normal(gen);
generation[i] = x + conf.var * noise[i];
fitness[i] = exp(-abs(f(generation[i])));
delta += fitness[i] * noise[i];
}
x = x + conf.factor * delta;
error = std::abs(f(x));
std::cout << iter + 1 << "\tx = " << x << "\t error = " << error
<< std::endl;
} while ((error > cond.tolerance) && (++iter < cond.iterations));
return x;
}
int main()
{
auto f = [](double x)
{
return (x - 1.0) * (x - 2.0);
};
auto config = GAConfig{ 0.2, 0.1, 10 };
auto stop_condition = StopCondition{ 1e-3, 10000 };
double solution = solve(f, 0.0, config, stop_condition);
std::cout << solution << std::endl;
}
|
code/cellular_automaton/src/genetic_algorithm/genetic_algorithm.go | package main
import (
"fmt";
"math/rand";
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
const geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
target := "Not all those who wander are lost."
calc := func (candidate string) int {
return getFitness(target, candidate)
}
start := time.Now()
disp := func (candidate string) {
fmt.Print(candidate)
fmt.Print("\t")
fmt.Print(calc(candidate))
fmt.Print("\t")
fmt.Println(time.Since(start))
}
var best = getBest(calc, disp, geneSet, len(target))
println(best)
fmt.Print("Total time: ")
fmt.Println(time.Since(start))
}
func getBest(getFitness func(string) int, display func(string), geneSet string, length int) string {
var bestParent = generateParent(geneSet, length)
value := getFitness(bestParent)
var bestFitness = value
for bestFitness < length {
child := mutateParent(bestParent, geneSet)
fitness := getFitness(child)
if fitness > bestFitness {
display(child)
bestFitness = fitness
bestParent = child
}
}
return bestParent
}
func mutateParent(parent, geneSet string) string {
geneIndex := rand.Intn(len(geneSet))
parentIndex := rand.Intn(len(parent))
candidate := ""
if parentIndex > 0 {
candidate += parent[:parentIndex]
}
candidate += geneSet[geneIndex:1+geneIndex]
if parentIndex+1 < len(parent) {
candidate += parent[parentIndex+1:]
}
return candidate
}
func generateParent(geneSet string, length int) string {
s := ""
for i := 0; i < length; i++ {
index := rand.Intn(len(geneSet))
s += geneSet[index:1+index]
}
return s
}
func getFitness(target, candidate string) int {
differenceCount := 0
for i := 0; i < len(target); i++ {
if target[i] != candidate[i] {
differenceCount++
}
}
return len(target) - differenceCount
}
|
code/cellular_automaton/src/genetic_algorithm/genetic_algorithm.java | import javax.swing.*;
import java.awt.*;
import java.util.*;
public class GeneticAlgorithm extends JFrame {
Random rnd = new Random(1);
int n = rnd.nextInt(300) + 250;
int generation;
double[] x = new double[n];
double[] y = new double[n];
int[] bestState;
{
for (int i = 0; i < n; i++) {
x[i] = rnd.nextDouble();
y[i] = rnd.nextDouble();
}
}
public void geneticAlgorithm() {
bestState = new int[n];
for (int i = 0; i < n; i++)
bestState[i] = i;
final int populationLimit = 100;
final Population population = new Population(populationLimit);
final int n = x.length;
for (int i = 0; i < populationLimit; i++)
population.chromosomes.add(new Chromosome(optimize(getRandomPermutation(n))));
final double mutationRate = 0.3;
final int generations = 10_000;
for (generation = 0; generation < generations; generation++) {
int i = 0;
while (population.chromosomes.size() < population.populationLimit) {
int i1 = rnd.nextInt(population.chromosomes.size());
int i2 = (i1 + 1 + rnd.nextInt(population.chromosomes.size() - 1)) % population.chromosomes.size();
Chromosome parent1 = population.chromosomes.get(i1);
Chromosome parent2 = population.chromosomes.get(i2);
int[][] pair = crossOver(parent1.p, parent2.p);
if (rnd.nextDouble() < mutationRate) {
mutate(pair[0]);
mutate(pair[1]);
}
population.chromosomes.add(new Chromosome(optimize(pair[0])));
population.chromosomes.add(new Chromosome(optimize(pair[1])));
}
population.nextGeneration();
bestState = population.chromosomes.get(0).p;
repaint();
}
}
int[][] crossOver(int[] p1, int[] p2) {
int n = p1.length;
int i1 = rnd.nextInt(n);
int i2 = (i1 + 1 + rnd.nextInt(n - 1)) % n;
int[] n1 = p1.clone();
int[] n2 = p2.clone();
boolean[] used1 = new boolean[n];
boolean[] used2 = new boolean[n];
for (int i = i1; ; i = (i + 1) % n) {
n1[i] = p2[i];
used1[n1[i]] = true;
n2[i] = p1[i];
used2[n2[i]] = true;
if (i == i2) {
break;
}
}
for (int i = (i2 + 1) % n; i != i1; i = (i + 1) % n) {
if (used1[n1[i]]) {
n1[i] = -1;
} else {
used1[n1[i]] = true;
}
if (used2[n2[i]]) {
n2[i] = -1;
} else {
used2[n2[i]] = true;
}
}
int pos1 = 0;
int pos2 = 0;
for (int i = 0; i < n; i++) {
if (n1[i] == -1) {
while (used1[pos1])
++pos1;
n1[i] = pos1++;
}
if (n2[i] == -1) {
while (used2[pos2])
++pos2;
n2[i] = pos2++;
}
}
return new int[][]{n1, n2};
}
void mutate(int[] p) {
int n = p.length;
int i = rnd.nextInt(n);
int j = (i + 1 + rnd.nextInt(n - 1)) % n;
reverse(p, i, j);
}
// http://en.wikipedia.org/wiki/2-opt
static void reverse(int[] p, int i, int j) {
int n = p.length;
// reverse order from i to j
while (i != j) {
int t = p[j];
p[j] = p[i];
p[i] = t;
i = (i + 1) % n;
if (i == j) break;
j = (j - 1 + n) % n;
}
}
double eval(int[] state) {
double res = 0;
for (int i = 0, j = state.length - 1; i < state.length; j = i++)
res += dist(x[state[i]], y[state[i]], x[state[j]], y[state[j]]);
return res;
}
static double dist(double x1, double y1, double x2, double y2) {
double dx = x1 - x2;
double dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
int[] getRandomPermutation(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int j = rnd.nextInt(i + 1);
res[i] = res[j];
res[j] = i;
}
return res;
}
// try all 2-opt moves
int[] optimize(int[] p) {
int[] res = p.clone();
for (boolean improved = true; improved; ) {
improved = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || (j + 1) % n == i) continue;
int i1 = (i - 1 + n) % n;
int j1 = (j + 1) % n;
double delta = dist(x[res[i1]], y[res[i1]], x[res[j]], y[res[j]])
+ dist(x[res[i]], y[res[i]], x[res[j1]], y[res[j1]])
- dist(x[res[i1]], y[res[i1]], x[res[i]], y[res[i]])
- dist(x[res[j]], y[res[j]], x[res[j1]], y[res[j1]]);
if (delta < -1e-9) {
reverse(res, i, j);
improved = true;
}
}
}
}
return res;
}
class Chromosome implements Comparable<Chromosome> {
final int[] p;
private double cost = Double.NaN;
public Chromosome(int[] p) {
this.p = p;
}
public double getCost() {
return Double.isNaN(cost) ? cost = eval(p) : cost;
}
@Override
public int compareTo(Chromosome o) {
return Double.compare(getCost(), o.getCost());
}
}
static class Population {
List<Chromosome> chromosomes = new ArrayList<>();
final int populationLimit;
public Population(int populationLimit) {
this.populationLimit = populationLimit;
}
public void nextGeneration() {
Collections.sort(chromosomes);
chromosomes = new ArrayList<>(chromosomes.subList(0, (chromosomes.size() + 1) / 2));
}
}
// visualization code
public GeneticAlgorithm() {
setContentPane(new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
int w = getWidth() - 5;
int h = getHeight() - 30;
for (int i = 0, j = n - 1; i < n; j = i++)
g.drawLine((int) (x[bestState[i]] * w), (int) ((1 - y[bestState[i]]) * h),
(int) (x[bestState[j]] * w), (int) ((1 - y[bestState[j]]) * h));
g.setColor(Color.RED);
for (int i = 0; i < n; i++)
g.drawOval((int) (x[i] * w) - 1, (int) ((1 - y[i]) * h) - 1, 3, 3);
g.setColor(Color.BLACK);
g.drawString(String.format("length: %.3f", eval(bestState)), 5, h + 20);
g.drawString(String.format("generation: %d", generation), 150, h + 20);
}
});
setSize(new Dimension(600, 600));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
new Thread(this::geneticAlgorithm).start();
}
public static void main(String[] args) {
new GeneticAlgorithm();
}
}
|
code/cellular_automaton/src/genetic_algorithm/genetic_algorithm.js | var Gene = function(code) {
if (code) this.code = code;
this.cost = 9999;
};
Gene.prototype.code = "";
Gene.prototype.random = function(length) {
while (length--) {
this.code += String.fromCharCode(Math.floor(Math.random() * 255));
}
};
Gene.prototype.mutate = function(chance) {
if (Math.random() > chance) return;
var index = Math.floor(Math.random() * this.code.length);
var upOrDown = Math.random() <= 0.5 ? -1 : 1;
var newChar = String.fromCharCode(this.code.charCodeAt(index) + upOrDown);
var newString = "";
for (var i = 0; i < this.code.length; i++) {
if (i == index) newString += newChar;
else newString += this.code[i];
}
this.code = newString;
};
Gene.prototype.mate = function(gene) {
var pivot = Math.round(this.code.length / 2) - 1;
var child1 = this.code.substr(0, pivot) + gene.code.substr(pivot);
var child2 = gene.code.substr(0, pivot) + this.code.substr(pivot);
return [new Gene(child1), new Gene(child2)];
};
Gene.prototype.calcCost = function(compareTo) {
var total = 0;
for (var i = 0; i < this.code.length; i++) {
total +=
(this.code.charCodeAt(i) - compareTo.charCodeAt(i)) *
(this.code.charCodeAt(i) - compareTo.charCodeAt(i));
}
this.cost = total;
};
var Population = function(goal, size) {
this.members = [];
this.goal = goal;
this.generationNumber = 0;
while (size--) {
var gene = new Gene();
gene.random(this.goal.length);
this.members.push(gene);
}
};
Population.prototype.display = function() {
document.body.innerHTML = "";
document.body.innerHTML +=
"<h2>Generation: " + this.generationNumber + "</h2>";
document.body.innerHTML += "<ul>";
for (var i = 0; i < this.members.length; i++) {
document.body.innerHTML +=
"<li>" + this.members[i].code + " (" + this.members[i].cost + ")";
}
document.body.innerHTML += "</ul>";
};
Population.prototype.sort = function() {
this.members.sort(function(a, b) {
return a.cost - b.cost;
});
};
Population.prototype.generation = function() {
for (var i = 0; i < this.members.length; i++) {
this.members[i].calcCost(this.goal);
}
this.sort();
this.display();
var children = this.members[0].mate(this.members[1]);
this.members.splice(this.members.length - 2, 2, children[0], children[1]);
for (var i = 0; i < this.members.length; i++) {
this.members[i].mutate(0.5);
this.members[i].calcCost(this.goal);
if (this.members[i].code == this.goal) {
this.sort();
this.display();
return true;
}
}
this.generationNumber++;
var scope = this;
setTimeout(function() {
scope.generation();
}, 20);
};
var population = new Population("Hello, world!", 20);
population.generation();
|
code/cellular_automaton/src/genetic_algorithm/genetic_algorithm.py | import random
#
# Global variables
# Setup optimal string and GA input variables.
#
OPTIMAL = "Hello, World"
DNA_SIZE = len(OPTIMAL)
POP_SIZE = 20
GENERATIONS = 5000
#
# Helper functions
# These are used as support, but aren't direct GA-specific functions.
#
def weighted_choice(items):
"""
Chooses a random element from items, where items is a list of tuples in
the form (item, weight). weight determines the probability of choosing its
respective item. Note: this function is borrowed from ActiveState Recipes.
"""
weight_total = sum((item[1] for item in items))
n = random.uniform(0, weight_total)
for item, weight in items:
if n < weight:
return item
n = n - weight
return item
def random_char():
"""
Return a random character between ASCII 32 and 126 (i.e. spaces, symbols,
letters, and digits). All characters returned will be nicely printable.
"""
return chr(int(random.randrange(32, 126, 1)))
def random_population():
"""
Return a list of POP_SIZE individuals, each randomly generated via iterating
DNA_SIZE times to generate a string of random characters with random_char().
"""
pop = []
for i in range(POP_SIZE):
dna = ""
for c in range(DNA_SIZE):
dna += random_char()
pop.append(dna)
return pop
#
# GA functions
# These make up the bulk of the actual GA algorithm.
#
def fitness(dna):
"""
For each gene in the DNA, this function calculates the difference between
it and the character in the same position in the OPTIMAL string. These values
are summed and then returned.
"""
fitness = 0
for c in range(DNA_SIZE):
fitness += abs(ord(dna[c]) - ord(OPTIMAL[c]))
return fitness
def mutate(dna):
"""
For each gene in the DNA, there is a 1/mutation_chance chance that it will be
switched out with a random character. This ensures diversity in the
population, and ensures that is difficult to get stuck in local minima.
"""
dna_out = ""
mutation_chance = 100
for c in range(DNA_SIZE):
if int(random.random() * mutation_chance) == 1:
dna_out += random_char()
else:
dna_out += dna[c]
return dna_out
def crossover(dna1, dna2):
"""
Slices both dna1 and dna2 into two parts at a random index within their
length and merges them. Both keep their initial sublist up to the crossover
index, but their ends are swapped.
"""
pos = int(random.random() * DNA_SIZE)
return (dna1[:pos] + dna2[pos:], dna2[:pos] + dna1[pos:])
#
# Main driver
# Generate a population and simulate GENERATIONS generations.
#
if __name__ == "__main__":
# Generate initial population. This will create a list of POP_SIZE strings,
# each initialized to a sequence of random characters.
population = random_population()
# Simulate all of the generations.
for generation in range(GENERATIONS):
print("Generation %s... Random sample: '%s'" % (generation, population[0]))
weighted_population = []
# Add individuals and their respective fitness levels to the weighted
# population list. This will be used to pull out individuals via certain
# probabilities during the selection phase. Then, reset the population list
# so we can repopulate it after selection.
for individual in population:
fitness_val = fitness(individual)
# Generate the (individual,fitness) pair, taking in account whether or
# not we will accidently divide by zero.
if fitness_val == 0:
pair = (individual, 1.0)
else:
pair = (individual, 1.0 / fitness_val)
weighted_population.append(pair)
population = []
# Select two random individuals, based on their fitness probabilites, cross
# their genes over at a random point, mutate them, and add them back to the
# population for the next iteration.
for _ in range(POP_SIZE // 2):
# Selection
ind1 = weighted_choice(weighted_population)
ind2 = weighted_choice(weighted_population)
# Crossover
ind1, ind2 = crossover(ind1, ind2)
# Mutate and add back into the population.
population.append(mutate(ind1))
population.append(mutate(ind2))
# Display the highest-ranked string after all generations have been iterated
# over. This will be the closest string to the OPTIMAL string, meaning it
# will have the smallest fitness value. Finally, exit the program.
fittest_string = population[0]
minimum_fitness = fitness(population[0])
for individual in population:
ind_fitness = fitness(individual)
if ind_fitness <= minimum_fitness:
fittest_string = individual
minimum_fitness = ind_fitness
print("Fittest String: %s" % fittest_string)
exit(0)
|
code/cellular_automaton/src/genetic_algorithm/genetic_algorithm2.py | import math
import random
def poblacion_inicial(max_poblacion, num_vars):
# Crear poblacion inicial aleatoria
poblacion = []
for i in range(max_poblacion):
gen = []
for j in range(num_vars):
if random.random() > 0.5:
gen.append(1)
else:
gen.append(0)
poblacion.append(gen[:])
return poblacion
def adaptacion_3sat(gen, solucion):
# contar clausulas correctas
n = 3
cont = 0
clausula_ok = True
for i in range(len(gen)):
n = n - 1
if gen[i] != solucion[i]:
clausula_ok = False
if n == 0:
if clausula_ok:
cont = cont + 1
n = 3
clausula_ok = True
if n > 0:
if clausula_ok:
cont = cont + 1
return cont
def evalua_poblacion(poblacion, solucion):
# evalua todos los genes de la poblacion
adaptacion = []
for i in range(len(poblacion)):
adaptacion.append(adaptacion_3sat(poblacion[i], solucion))
return adaptacion
def seleccion(poblacion, solucion):
adaptacion = evalua_poblacion(poblacion, solucion)
# suma de todas las puntuaciones
total = 0
for i in range(len(adaptacion)):
total = total + adaptacion[i]
# escogemos dos elementos
val1 = random.randint(0, total)
val2 = random.randint(0, total)
sum_sel = 0
for i in range(len(adaptacion)):
sum_sel = sum_sel + adaptacion[i]
if sum_sel >= val1:
gen1 = poblacion[i]
break
sum_sel = 0
for i in range(len(adaptacion)):
sum_sel = sum_sel + adaptacion[i]
if sum_sel >= val2:
gen2 = poblacion[i]
break
return gen1, gen2
def cruce(gen1, gen2):
# creuza 2 genes y obtiene 2 descendientes
nuevo_gen1 = []
nuevo_gen2 = []
corte = random.randint(0, len(gen1))
nuevo_gen1[0:corte] = gen1[0:corte]
nuevo_gen1[corte:] = gen2[corte:]
nuevo_gen2[0:corte] = gen2[0:corte]
nuevo_gen2[corte:] = gen1[corte:]
return nuevo_gen1, nuevo_gen2
def mutacion(prob, gen):
# muta un gen con una probabilidad prob
if random.random() < prob:
cromosoma = random.randint(0, len(gen))
if gen[cromosoma - 1] == 0:
gen[cromosoma - 1] = 1
else:
gen[cromosoma - 1] = 0
return gen
def elimina_peores_genes(poblacion, solucion):
# elimina los dos peores genes
adaptacion = evalua_poblacion(poblacion, solucion)
i = adaptacion.index(min(adaptacion))
del poblacion[i]
del adaptacion[i]
i = adaptacion.index(min(adaptacion))
del poblacion[i]
del adaptacion[i]
def mejor_gen(poblacion, solucion):
# devuelve el mejor gen de la poblacion
adaptacion = evalua_poblacion(poblacion, solucion)
return poblacion[adaptacion.index(max(adaptacion))]
def algoritmo_genetico():
max_iter = 10
max_poblacion = 50
num_vars = 10
fin = False
solucion = poblacion_inicial(1, num_vars)[0]
poblacion = poblacion_inicial(max_poblacion, num_vars)
iteraciones = 0
while not fin:
iteraciones = iteraciones + 1
for i in range(len(poblacion) // 2):
gen1, gen2 = seleccion(poblacion, solucion)
nuevo_gen1, nuevo_gen2 = cruce(gen1, gen2)
nuevo_gen1 = mutacion(0.1, nuevo_gen1)
nuevo_gen2 = mutacion(0.1, nuevo_gen2)
poblacion.append(nuevo_gen1)
poblacion.append(nuevo_gen2)
elimina_peores_genes(poblacion, solucion)
if max_iter < iteraciones:
fin = True
print("Solucion: " + str(solucion))
mejor = mejor_gen(poblacion, solucion)
return mejor, adaptacion_3sat(mejor, solucion)
if __name__ == "__main__":
random.seed()
mejor_gen = algoritmo_genetico()
print("Mejor gen encontrado:" + str(mejor_gen[0]))
print("Funcion de adaptacion: " + str(mejor_gen[1]))
|
code/cellular_automaton/src/langtons_ant/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Cellular Automaton
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/cellular_automaton/src/langtons_ant/langtons_ant.cpp | #include <iostream>
#include <vector>
#include <array>
using std::cout;
using std::cin;
using std::vector;
using std::array;
class Direction
{
public:
int x;
int y;
const static Direction north;
const static Direction east;
const static Direction south;
const static Direction west;
const static array<Direction, 4> directions;
private:
int i;
private:
Direction(int x_, int y_, int i_)
{
x = x_;
y = y_;
i = i_;
};
public:
Direction() : Direction(north)
{
};
Direction right() const
{
return directions.at((this->i + 1) % 4);
}
Direction left() const
{
return directions.at((this->i + 3) % 4);
}
};
const Direction Direction::north{0, 1, 0};
const Direction Direction::east{1, 0, 1};
const Direction Direction::south{0, -1, 2};
const Direction Direction::west{-1, 0, 3};
const array<Direction, 4> Direction::directions({
north, east, south, west,
});
class LangtonAnt
{
private:
vector<vector<unsigned char>> board;
int ant_x;
int ant_y;
int width;
int height;
Direction direction;
public:
LangtonAnt(int width_, int height_)
{
board.assign(width_, vector<unsigned char>(height_, 0));
width = width_;
height = height_;
ant_x = width / 2;
ant_y = height / 2;
}
void show()
{
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
cout << (board[j][i] ? '#' : ' ');
cout << '\n';
}
}
void step()
{
if (board[ant_x][ant_y])
{
board[ant_x][ant_y] = 0;
direction = direction.left();
}
else
{
board[ant_x][ant_y] = 1;
direction = direction.right();
}
ant_x = (ant_x + direction.x + width) % width;
ant_y = (ant_y + direction.y + height) % height;
}
};
int main()
{
const int width = 100;
const int height = 50;
const int max_step = 10000;
LangtonAnt langtonAnt(width, height);
for (int step = 0; step <= max_step; ++step)
{
cout << "Step " << step << '\n';
langtonAnt.show();
cin.get();
langtonAnt.step();
}
}
|
code/cellular_automaton/src/langtons_ant/langtons_ant.html | <!DOCTYPE html>
<html>
<head>
<style>
canvas {
position: absolute;
left: 0;
top: 0;
border: 1px solid #000000;
}
div {
position: relative;
}
</style>
<script>
//Size of the pixel to display (1 is too small to really see)
var scale = 10;
function fillPixel(x, y) {
var canvas = document.getElementById("gridCanvas").getContext("2d");
canvas.fillRect(x * scale, y * scale, scale, scale);
}
function clearPixel(x, y) {
var canvas = document.getElementById("gridCanvas").getContext("2d");
canvas.clearRect(x * scale, y * scale, scale, scale);
}
function isFilled(x, y) {
var canvas = document.getElementById("gridCanvas").getContext("2d");
var imageData = canvas.getImageData(x * scale, y * scale, scale, scale).data;
//Don't need to check them all but doesn't hurt
for (var i = 0; i < imageData.length; i++) {
if (imageData[i] > 0) {
return true;
}
}
return false;
}
function drawAnt(x, y) {
var canvas = document.getElementById("antCanvas").getContext("2d");
canvas.clearRect(0, 0, document.getElementById("antCanvas").width, document.getElementById("antCanvas").height);
canvas.strokeStyle = "#FF0000";
canvas.strokeRect(x * scale + 2, y * scale + 2, scale - 4, scale - 4);
}
var direction = [{
dx: -1,
dy: 0
}, //Left
{
dx: 0,
dy: 1
}, //Up
{
dx: 1,
dy: 0
}, //Right
{
dx: 0,
dy: -1
} //Down
];
var directionIndex = 0;
function turnLeft() {
directionIndex--;
//Should only iterate once
while (directionIndex < 0) {
directionIndex = directionIndex + 4;
}
}
function turnRight() {
directionIndex = (directionIndex + 1) % 4;
}
//height/width is 200 with a scale of 10 so 20 coordinates. 10 is half
var x = 10;
var y = 10;
function nextMove() {
//Flip current
if (isFilled(x, y)) {
clearPixel(x, y);
} else {
fillPixel(x, y);
}
//Step forward
x += direction[directionIndex].dx;
y += direction[directionIndex].dy;
//Turn for next move
if (isFilled(x, y)) {
turnLeft();
} else {
turnRight();
}
drawAnt(x, y);
}
</script>
</head>
<body>
<h2>Langton Ant</h2>
<button type="button" onclick="nextMove()">Step</button><br><br>
<div>
<canvas id="gridCanvas" width="200" height="200" style="z-index: 0;"></canvas>
<canvas id="antCanvas" width="200" height="200" style="z-index: 1;"></canvas>
</div>
</body>
</html>
|
code/cellular_automaton/src/langtons_ant/langtons_ant.java | import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LangtonAnt {
private static final int STEPS = 11000;
private Point position = new Point(0, 0);
private Direction direction = Direction.LEFT;
private ArrayList<Point> blackTiles = new ArrayList<>();
private void step() {
if (blackTiles.contains(position)) {
direction = direction.turnRight();
} else {
direction = direction.turnLeft();
}
int index;
if((index = blackTiles.indexOf(position)) != -1) {
blackTiles.remove(index);
} else {
blackTiles.add((Point)position.clone());
}
switch (direction) {
case LEFT:
position.translate(-1, 0);
break;
case RIGHT:
position.translate(1, 0);
break;
case UP:
position.translate(0, 1);
break;
case DOWN:
position.translate(0, -1);
break;
}
}
public static void main(String[] args) {
LangtonAnt ant = new LangtonAnt();
JFrame frame = new JFrame("Langtons Ant");
GridPanel gridPanel = ant.new GridPanel();
frame.getContentPane().add(gridPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
for (int steps = 0; steps < STEPS; steps++) {
ant.step();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.repaint();
}
}
private enum Direction {
LEFT, RIGHT, UP, DOWN;
public Direction turnLeft() {
switch (this) {
case LEFT:
return DOWN;
case RIGHT:
return UP;
case UP:
return LEFT;
case DOWN:
return RIGHT;
default:
// Should never happen
return UP;
}
}
public Direction turnRight() {
switch (this) {
case LEFT:
return UP;
case RIGHT:
return DOWN;
case UP:
return RIGHT;
case DOWN:
return LEFT;
default:
// Should never happen
return UP;
}
}
}
private class GridPanel extends JPanel {
private static final int GRID_SIZE = 10;
private static final int DISPLAY_TILES = 60;
private static final int PIXEL_SIZE = GRID_SIZE*DISPLAY_TILES;
private static final int CENTER = PIXEL_SIZE/2;
public GridPanel() {
setPreferredSize(new Dimension(DISPLAY_TILES*GRID_SIZE, DISPLAY_TILES*GRID_SIZE));
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
for (Point tile : blackTiles) {
g2d.fillRect(tile.x*GRID_SIZE+CENTER, tile.y*GRID_SIZE+CENTER, GRID_SIZE, GRID_SIZE);
}
g2d.setColor(Color.RED);
g2d.fillOval(position.x*GRID_SIZE+CENTER, position.y*GRID_SIZE+CENTER, GRID_SIZE, GRID_SIZE);
}
}
} |
code/cellular_automaton/src/langtons_ant/langtons_ant.py | import turtle
import numpy
def update_maps(graph, turtle, color):
graph[turtle_pos(turtle)] = color
return None
def turtle_pos(turtle):
return (round(turtle.xcor()), round(turtle.ycor()))
def langton_move(turtle, pos, maps, step):
if pos not in maps or maps[pos] == "white":
turtle.fillcolor("black")
turtle.stamp()
update_maps(maps, turtle, "black")
turtle.right(90)
turtle.forward(step)
pos = turtle_pos(turtle)
elif maps[pos] == "black":
turtle.fillcolor("white")
update_maps(maps, turtle, "white")
turtle.stamp()
turtle.left(90)
turtle.forward(step)
pos = turtle_pos(turtle)
return pos
def move():
# Screen
BACKGROUND_COLOR = "white"
WIDTH = 2000
HEIGHT = 2000
# Ant
SHAPE = "square"
SHAPE_SIZE = 0.5
SPEED = -1
STEP = 11
# Data structure ex. {(x, y): "black", ..., (x_n, y_n): "white"}
maps = {}
# Initialize Window
window = turtle.Screen()
window.bgcolor(BACKGROUND_COLOR)
window.screensize(WIDTH, HEIGHT)
# Initialize Ant
ant = turtle.Turtle()
ant.shape(SHAPE)
ant.shapesize(SHAPE_SIZE)
ant.penup()
ant.speed(SPEED)
ant.right(180)
pos = turtle_pos(ant)
moves = 0
while True:
pos = langton_move(ant, pos, maps, STEP)
moves += 1
print("Movements:", moves)
move()
|
code/cellular_automaton/src/nobili_cellular_automata/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Cellular Automaton
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/cellular_automaton/src/von_neumann_cellular_automata/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Cellular Automaton
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/cellular_automaton/src/von_neumann_cellular_automata/von_neumann_cellular_automata.c | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define WIDTH 20
#define HEIGHT 30
const char* clear = "\e[1;1H\e[2J";
enum states{ U, /*Empty state (__)*/
S, S0, S00, S000, S01, S1, S10, S11, //Transition states (??)*/
C00, C01, C10, C11, /*Confluent states ([])*/
C_NORTH, C_EAST, C_SOUTH, C_WEST, /*Common Transmition states (/\, ->, \/, <-)*/
S_NORTH, S_EAST, S_SOUTH, S_WEST /*Special Transition states (/\, ->, \/, <-)*/
};
struct cell{
short state;
short active;
};
void
transmition(struct cell board[][WIDTH], struct cell temp[][WIDTH], int i, int j){
assert(board[i][j].active <= 1);
if(board[i][j].active == 1){
switch(board[i][j].state){
/*Common States*/
case C_NORTH:
if(i > 0 && board[i -1][j].state <= C_WEST){
if(board[i -1][j].state == U)
temp[i -1][j].state = S;
else
temp[i -1][j].active++;
}
else if(i > 0)
temp[i -1][j].state = U;
temp[i][j].active--;
break;
case C_EAST:
if(j < WIDTH && board[i][j +1].state <= C_WEST){
if(board[i][j +1].state == U)
temp[i][j +1].state = S;
else
temp[i][j +1].active++;
}
else if(j < WIDTH)
temp[i][j +1].state = U;
temp[i][j].active--;
break;
case C_SOUTH:
if(i < HEIGHT && board[i +1][j].state <= C_WEST){
if(board[i +1][j].state == U)
temp[i +1][j].state = S;
else
temp[i +1][j].active++;
}
else if(i < HEIGHT)
temp[i][j +1].state = U;
temp[i][j].active--;
break;
case C_WEST:
if(j > 0 && board[i][j -1].state <= C_WEST){
if(board[i][j -1].state == U)
temp[i][j -1].state = S;
else
temp[i][j -1].active++;
}
else if(j > 0)
temp[i][j -1].state = U;
temp[i][j].active--;
break;
/*Special states*/
case S_NORTH:
if(i > 0 && (board[i -1][j].state >= S_NORTH || board[i -1][j].state < C_NORTH)){
if(board[i -1][j].state == U)
temp[i -1][j].state = S;
else if(board[i -1][j].state >= C00 && board[i -1][j].state <= C11)
temp[i -1][j].state = U;
else
temp[i -1][j].active++;
}
if(i > 0)
temp[i -1][j].state = U;
temp[i][j].active--;
break;
case S_EAST:
if(j < WIDTH && (board[i][j +1].state >= S_NORTH || board[i][j +1].state < C_NORTH)){
if(board[i][j +1].state == U)
temp[i][j +1].state = S;
else if(board[i][j + 1].state >= C00 && board[i][j +1].state <= C11)
temp[i][j +1].state = U;
else
temp[i][j +1].active++;
}
else if(j < WIDTH)
temp[i][j +1].state = U;
temp[i][j].active--;
break;
case S_SOUTH:
if(i < HEIGHT && (board[i +1][j].state >= S_NORTH || board[i +1][j].state < C_NORTH)){
if(board[i +1][j].state == U)
temp[i +1][j].state = S;
else if(board[i +1][j].state >= C00 && board[i +1][j].state <= C11)
temp[i +1][j].state = U;
else
temp[i +1][j].active++;
}
else if(i < HEIGHT)
temp[i][j +1].state = U;
temp[i][j].active--;
break;
case S_WEST:
if(j > 0 && (board[i][j -1].state >= S_NORTH || board[i][j -1].state < C_NORTH)){
if(board[i][j -1].state == U)
temp[i][j -1].state = S;
else if(board[i][j -1].state >= C00 && board[i][j -1].state <= C11)
temp[i][j -1].state = U;
else
temp[i][j -1].active++;
}
else if(j > 0)
temp[i][j -1].state = U;
temp[i][j].active--;
break;
}
}
}
void
confluent(struct cell board[][WIDTH], struct cell temp[][WIDTH], int i, int j){
int aux[4]; /*Neighborhood vector [up, left, down, right]*/
int in = 0, out = 0;
aux[0] = (i > 0 && board[i -1][j].state == C_SOUTH && ++in) -
(i > 0 && (board[i -1][j].state == C_NORTH || board[i -1][j].state == S_NORTH) && ++out);
aux[1] = (j > 0 && board[i][j -1].state == C_EAST && ++in) -
(j > 0 && (board[i][j -1].state == C_WEST || board[i][j -1].state == S_WEST)&& ++out);
aux[2] = (i < HEIGHT && board[i +1][j].state == C_NORTH && ++in) -
(i < HEIGHT && (board[i +1][j].state == C_SOUTH || board[i +1][j].state == S_SOUTH) && ++out);
aux[3] = (j < WIDTH && board[i][j +1].state == C_WEST && ++in) -
(j < WIDTH && (board[i][j +1].state == C_EAST || board[i][j +1].state == S_EAST) && ++out);
switch(board[i][j].state){
case C00:
if(temp[i][j].active >= in)
temp[i][j].state = C01;
temp[i][j].active = 0;
break;
case C01:
if(out > 0){ /*Transfering data for neighborhood*/
if(aux[0] == -1) temp[i -1][j].active++;
if(aux[1] == -1) temp[i][j -1].active++;
if(aux[2] == -1) temp[i +1][j].active++;
if(aux[3] == -1) temp[i][j +1].active++;
}
if(temp[i][j].active >= in)
temp[i][j].state = C11;
else
temp[i][j].state = C10;
temp[i][j].active = 0;
break;
case C10:
if(temp[i][j].active >= in)
temp[i][j].state = C01;
else
temp[i][j].state = C00;
temp[i][j].active = 0;
break;
case C11:
if(out > 0){
if(aux[0] == -1) temp[i -1][j].active++;
if(aux[1] == -1) temp[i][j -1].active++;
if(aux[2] == -1) temp[i +1][j].active++;
if(aux[3] == -1) temp[i][j +1].active++;
}
if(temp[i][j].active >= in)
temp[i][j].state = C11;
else
temp[i][j].state = C10;
temp[i][j].active = 0;
break;
}
}
void
transition(struct cell board[][WIDTH], struct cell temp[][WIDTH], int i, int j){
switch(board[i][j].state){
case S:
if(temp[i][j].active == 1)
temp[i][j].state = S1;
else
temp[i][j].state = S0;
temp[i][j].active--;
break;
case S0:
if(temp[i][j].active == 1)
temp[i][j].state = S01;
else
temp[i][j].state = S00;
temp[i][j].active--;
break;
case S00:
if(temp[i][j].active == 1)
temp[i][j].state = C_WEST;
else
temp[i][j].state = S000;
temp[i][j].active--;
break;
case S000:
if(temp[i][j].active == 1)
temp[i][j].state = C_NORTH;
else
temp[i][j].state = C_EAST;
temp[i][j].active--;
break;
case S01:
if(temp[i][j].active == 1)
temp[i][j].state = S_EAST;
else
temp[i][j].state = C_SOUTH;
temp[i][j].active--;
break;
case S1:
if(temp[i][j].active == 1)
temp[i][j].state = S11;
else
temp[i][j].state = S10;
temp[i][j].active--;
break;
case S10:
if(temp[i][j].active == 1)
temp[i][j].state = S_WEST;
else
temp[i][j].state = S_NORTH;
temp[i][j].active--;
break;
case S11:
if(temp[i][j].active == 1)
temp[i][j].state = C00;
else
temp[i][j].state = S_SOUTH;
temp[i][j].active--;
break;
}
}
void
update(struct cell board[][WIDTH], struct cell temp[][WIDTH]){
int i, j;
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
temp[i][j].active = temp[i][j].active > 0;
board[i][j].state = temp[i][j].state;
board[i][j].active = temp[i][j].active;
}
}
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
if(board[i][j].state >= C_NORTH) /*Transmition states*/
transmition(board, temp, i, j);
}
}
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
if(board[i][j].state == U) /*Empty state*/
continue;
else if(board[i][j].state < C00) /*Transition states*/
transition(board, temp, i, j);
else if(board[i][j].state < C_NORTH) /*Confluent states*/
confluent(board, temp, i, j);
}
}
}
void print_board(struct cell board[][WIDTH]){
int i, j;
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
if(board[i][j].active == 1)
printf("++");
else if(board[i][j].state == U )
printf("__");
else if(board[i][j].state < C00)
printf("??");
else if(board[i][j].state < C_NORTH)
printf("<>");
else{
if((board[i][j].state - C_NORTH) % 4 == 0)
printf("/\\");
else if((board[i][j].state - C_NORTH) % 4 == 1)
printf("->");
else if((board[i][j].state - C_NORTH) % 4 == 2)
printf("\\/");
else if((board[i][j].state - C_NORTH) % 4 == 3)
printf("<-");
}
printf(".");
}
printf("\n");
}
}
void clear_board(struct cell board[][WIDTH], struct cell temp[][WIDTH]){
int i, j;
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
board[i][j].state = U;
board[i][j].active = 0;
temp[i][j].state = U;
temp[i][j].active = 0;
}
}
}
void initial_board(struct cell board[][WIDTH], struct cell temp[][WIDTH]){
int i;
/*Create loop*/
for(i = 5; i <= 10; i++){
board[5][i].state = C_EAST;
board[10][i].state = C_WEST;
board[i][5].state = C_NORTH;
board[i][10].state = C_SOUTH;
temp[5][i].state = C_EAST;
temp[10][i].state = C_WEST;
temp[i][5].state = C_NORTH;
temp[i][10].state = C_SOUTH;
}
board[5][5].state = C_EAST;
board[5][10].state = C_SOUTH;
board[10][10].state = C_WEST;
board[10][5].state = C_NORTH;
temp[5][5].state = C_EAST;
temp[5][10].state = C00;
temp[5][11].state = S_EAST;
temp[10][10].state = C_WEST;
temp[10][5].state = C_NORTH;
/*initial condition*/
temp[10][5].active = 1;
temp[10][7].active = 1;
temp[10][8].active = 1;
}
int main(){
struct cell board[HEIGHT][WIDTH];
struct cell temp[HEIGHT][WIDTH];
clear_board(board, temp);
initial_board(board, temp);
do{
/*Update boards*/
update(board, temp);
print_board(board);
getchar();
printf("%s", clear);
}while(1);
}
|
code/cellular_automaton/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/compression/src/README.md | # cosmos #
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/compression/src/lossless_compression/README.md | # cosmos #
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/compression/src/lossless_compression/huffman/README.md | # cosmos #
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/compression/src/lossless_compression/huffman/huffman.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* huffman compression synopsis
*
* template<typename _Tp>
* struct BinaryTreeNode {
* _Tp value;
* std::shared_ptr<BinaryTreeNode<_Tp> > left, right;
* BinaryTreeNode(_Tp v,
* std::shared_ptr<BinaryTreeNode<_Tp> > l = {},
* std::shared_ptr<BinaryTreeNode<_Tp> > r = {});
* };
*
* template<typename _Tp>
* struct Comp {
* public:
* bool operator()(_Tp a, _Tp b) const;
* };
*
* class HuffmanTest;
*
* class Huffman {
* private:
* typedef size_t size_type;
* typedef unsigned long long base_type;
* typedef std::pair<char, size_type> freq_node_type;
* typedef std::unordered_map<char, size_type> freq_type;
* typedef std::pair<size_type, std::pair<char, std::string> > value_type;
* typedef BinaryTreeNode<value_type> tree_node_type;
* typedef std::priority_queue<std::shared_ptr<tree_node_type>,
* std::vector<std::shared_ptr<tree_node_type> >,
* Comp<std::shared_ptr<tree_node_type> > > tree_type;
* typedef std::unordered_map<char, std::string> dictionary_type;
* typedef std::unordered_map<std::string, char> reverse_dictionary_type;
*
* public:
* Huffman()
* :frequency_(), tree_(), dictionary_(), reverse_dictionary_(), sentinel_(), binary_bit_();
*
* std::string compression(std::string const &in);
*
* std::string compression(std::istream &in);
*
* void compression(std::string const &in, std::ostream &out);
*
* void compression(std::istream &in, std::ostream &out);
*
* std::string decompression(std::string const &in);
*
* std::string decompression(std::istream &in);
*
* void decompression(std::string const &in, std::ostream &out);
*
* void decompression(std::istream &in, std::ostream &out);
*
* private:
* freq_type frequency_;
* tree_type tree_;
* dictionary_type dictionary_;
* reverse_dictionary_type reverse_dictionary_;
* std::shared_ptr<tree_node_type> sentinel_;
* size_type binary_bit_;
* std::vector<size_type> power_;
* const char DELIMITER = ' ';
* const size_type GUARANTEE_BIT = sizeof(base_type) * 8;
* const int HEX_BIT = 16;
*
* void calculateFrequency(std::string const &input);
*
* // no cover test
* void buildForest();
*
* // no cover test
* void initialTree();
*
* // no cover test
* void initialForest();
*
* // no cover test
* void appendDegree();
*
* // no cover test
* void buildDictionary();
*
* std::pair<std::string, std::string> seperateHeaderAndCode(std::string const &str);
*
* // no cover test
* std::string restore(std::string const &input);
*
* std::string exportHeader();
*
* std::string exportDictionary();
*
* void importHeader(std::string const &str);
*
* void importDictionary(std::string const &str);
*
* std::string addSeperateCode(std::string const &str);
*
* std::string removeSeperateCode(std::string const &str);
*
* std::string stringToHex(std::string const &str);
*
* std::string stringToBinary(std::string const &input);
*
* // return string always fill 0 while size is not N * GUARANTEE_BIT
* std::string binaryToHex(std::string const &str);
*
* std::string hexToBinary(std::string const &str);
* };
*/
#include <functional>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <memory>
#include <cmath>
#include <stack>
#include <string>
#include <vector>
#include <queue>
#include <unordered_map>
#include <cassert>
#include <iostream>
template<typename _Tp>
struct BinaryTreeNode
{
_Tp value;
std::shared_ptr<BinaryTreeNode<_Tp>> left, right;
BinaryTreeNode(_Tp v,
std::shared_ptr<BinaryTreeNode<_Tp>> l = {},
std::shared_ptr<BinaryTreeNode<_Tp>> r = {}) : value(v), left(l), right(r)
{
};
};
template<typename _Tp>
struct Comp
{
public:
bool operator()(_Tp a, _Tp b) const
{
return a->value.first > b->value.first;
}
};
class HuffmanTest;
class Huffman {
private:
typedef size_t size_type;
typedef unsigned long long base_type;
typedef std::pair<char, size_type> freq_node_type;
typedef std::unordered_map<char, size_type> freq_type;
typedef std::pair<size_type, std::pair<char, std::string>> value_type;
typedef BinaryTreeNode<value_type> tree_node_type;
typedef std::priority_queue<std::shared_ptr<tree_node_type>,
std::vector<std::shared_ptr<tree_node_type>>,
Comp<std::shared_ptr<tree_node_type>>> tree_type;
typedef std::unordered_map<char, std::string> dictionary_type;
typedef std::unordered_map<std::string, char> reverse_dictionary_type;
public:
Huffman()
: frequency_(), tree_(), dictionary_(), reverse_dictionary_(), sentinel_(), binary_bit_()
{
power_.resize(GUARANTEE_BIT);
for (auto i = GUARANTEE_BIT; i > 0; --i)
power_.at(i - 1) = pow(2, GUARANTEE_BIT - i);
};
std::string compression(std::string const &in)
{
calculateFrequency(in);
buildForest();
buildDictionary();
// don't change order on this and next line
// because stringToHex will calc. binary length
std::string res = stringToHex(in);
res = addSeperateCode(exportHeader()) + res;
return res;
}
std::string compression(std::istream &in)
{
return compression(readFile(in));
}
void compression(std::string const &in, std::ostream &out)
{
out << compression(in);
}
void compression(std::istream &in, std::ostream &out)
{
out << compression(in);
}
std::string decompression(std::string const &in)
{
std::pair<std::string, std::string> header_and_code = seperateHeaderAndCode(in);
importHeader(header_and_code.first);
std::string res = hexToBinary(header_and_code.second);
res = restore(res);
return res;
}
std::string decompression(std::istream &in)
{
return decompression(readFile(in));
}
void decompression(std::string const &in, std::ostream &out)
{
out << decompression(in);
}
void decompression(std::istream &in, std::ostream &out)
{
out << decompression(in);
}
private:
freq_type frequency_;
tree_type tree_;
dictionary_type dictionary_;
reverse_dictionary_type reverse_dictionary_;
std::shared_ptr<tree_node_type> sentinel_;
unsigned long long binary_bit_;
std::vector<size_type> power_;
const char DELIMITER = ' ';
const unsigned long long GUARANTEE_BIT = sizeof(base_type) * 8;
const unsigned long long HEX_BIT = 16;
std::string readFile(std::istream &in)
{
std::string s{};
char c;
while (in >> std::noskipws >> c)
s.push_back(c);
return s;
}
void calculateFrequency(std::string const &input)
{
char c;
std::stringstream in(input);
while (in >> std::noskipws >> c)
{
if (frequency_.find(c) == frequency_.end())
frequency_.insert(std::make_pair(c, 1));
else
frequency_.at(c) += 1;
}
}
// no cover test
void buildForest()
{
initialTree();
initialForest();
appendDegree();
}
// no cover test
void initialTree()
{
for_each(frequency_.begin(),
frequency_.end(),
[&] (freq_node_type freq_node)
{
value_type n{std::make_pair(freq_node.second, std::make_pair(freq_node.first, ""))};
tree_.push({std::make_shared<tree_node_type>(tree_node_type((n),
sentinel_,
sentinel_))});
});
if (frequency_.size() == 1)
tree_.push({std::make_shared<tree_node_type>(tree_node_type({}))});
}
// no cover test
void initialForest()
{
while (tree_.size() > 1)
{
std::shared_ptr<tree_node_type> left{}, right{}, parent{};
left = tree_.top();
tree_.pop();
right = tree_.top();
tree_.pop();
if (Comp<std::shared_ptr<tree_node_type>>()(left, right))
swap(left, right);
parent = std::make_shared<tree_node_type>(tree_node_type({}, left, right));
parent->value.first = left->value.first + right->value.first;
tree_.push(parent);
}
}
// no cover test
void appendDegree()
{
if (!tree_.empty())
{
std::string degree{};
std::stack<std::shared_ptr<tree_node_type>> nodes;
nodes.push(tree_.top());
// post order travel
while (!nodes.empty())
{
while (nodes.top()->left)
{
nodes.push(nodes.top()->left);
degree += '0';
}
while (!nodes.empty() && nodes.top()->right == sentinel_)
{
if (nodes.top()->left == sentinel_)
nodes.top()->value.second.second = degree;
nodes.pop();
while (!degree.empty() && degree.back() == '1')
degree.pop_back();
if (!degree.empty())
degree.pop_back();
}
if (!nodes.empty())
{
auto right = nodes.top()->right;
nodes.pop();
nodes.push(right);
degree += '1';
}
}
}
}
// no cover test
void buildDictionary()
{
if (tree_.size() == 1)
{
std::stack<std::shared_ptr<tree_node_type>> nodes;
nodes.push(tree_.top());
tree_.pop();
// post order travel
while (!nodes.empty())
{
while (nodes.top()->left != sentinel_)
nodes.push(nodes.top()->left);
while (!nodes.empty() && nodes.top()->right == sentinel_)
{
if (nodes.top()->left == sentinel_)
dictionary_.insert(make_pair(nodes.top()->value.second.first,
nodes.top()->value.second.second));
nodes.pop();
}
if (!nodes.empty())
{
auto right = nodes.top()->right;
nodes.pop();
nodes.push(right);
}
}
}
}
std::pair<std::string, std::string> seperateHeaderAndCode(std::string const &str)
{
auto it = --str.begin();
size_type separate_count{};
while (++it != str.end())
if (separate_count == 4 && it + 1 != str.end() && *(it + 1) != ' ')
break;
else if (*it == ' ')
++separate_count;
else
separate_count = 0;
return std::make_pair(std::string{str.begin(), it - 4}, std::string{it, str.end()});
}
// no cover test
std::string restore(std::string const &input)
{
std::stringstream ss{input};
std::string res{};
char c;
std::string k;
while (ss >> c)
{
k = {};
ss.putback(c);
while (reverse_dictionary_.find(k) == reverse_dictionary_.end())
{
if (ss >> c)
k.push_back(c);
else
break;
}
if (reverse_dictionary_.find(k) != reverse_dictionary_.end())
res.push_back(reverse_dictionary_.at(k));
else
break;
}
return res;
}
std::string exportHeader()
{
return std::to_string(binary_bit_) + DELIMITER + exportDictionary();
}
std::string exportDictionary()
{
std::string res{};
for_each(dictionary_.begin(),
dictionary_.end(),
[&] (std::pair<char, std::string> value)
{
res.push_back(value.first);
res += DELIMITER;
res.append(value.second);
res += DELIMITER;
});
if (!res.empty())
res.erase(--res.end());
return res;
}
void importHeader(std::string const &str)
{
auto it = str.begin();
while (it != str.end() && *it != DELIMITER)
++it;
binary_bit_ = stoull(std::string{str.begin(), it});
if (it != str.end())
++it;
importDictionary({it, str.end()});
}
void importDictionary(std::string const &str)
{
char key{}, delimiter{};
std::stringstream ss{str};
std::string value{};
while (ss >> std::noskipws >> key)
{
ss >> std::noskipws >> delimiter;
ss >> std::noskipws >> value;
ss >> std::noskipws >> delimiter;
reverse_dictionary_.insert(make_pair(value, key));
}
}
std::string addSeperateCode(std::string const &str)
{
return str + DELIMITER + DELIMITER + DELIMITER + DELIMITER;
}
std::string removeSeperateCode(std::string const &str)
{
if (str.size() >= 4)
{
auto it = str.end();
if (*--it == DELIMITER
&& *--it == DELIMITER
&& *--it == DELIMITER
&& *--it == DELIMITER)
return std::string(str.begin(), str.end() - 4);
}
return str;
}
std::string stringToHex(std::string const &str)
{
return binaryToHex(stringToBinary(str));
}
std::string stringToBinary(std::string const &input)
{
std::string res{};
char c{};
std::stringstream in(input);
while (in >> std::noskipws >> c)
res.append(dictionary_.at(c));
binary_bit_ = res.size();
return res;
}
// return string always fill 0 while size is not N * GUARANTEE_BIT
std::string binaryToHex(std::string const &str)
{
if (str.empty())
return {};
std::stringstream res{};
size_type seat{};
base_type c{};
while (true)
{
if (seat < str.size())
c |= (str.at(seat) == '1') ? 1 : 0;
++seat;
if ((seat % GUARANTEE_BIT) == 0)
{
res << std::hex << c << DELIMITER;
c = {};
if (seat >= str.size())
break;
}
c <<= 1;
}
return res.str();
}
std::string hexToBinary(std::string const &str)
{
std::stringstream in_ss{str};
std::string res{}, s{};
size_type seat{}, g{};
base_type c{};
seat = 0 - 1;
while (true)
{
if (++seat < str.size())
{
in_ss >> s;
c = static_cast<base_type>(stoull(s, 0, HEX_BIT));
g = 0 - 1;
}
else if (g % GUARANTEE_BIT == 0)
break;
while (++g < GUARANTEE_BIT)
if (c >= power_.at(g))
{
c -= power_.at(g);
res.push_back('1');
}
else
res.push_back('0');
}
res.erase(res.begin() + binary_bit_, res.end());
return res;
}
// for test
friend HuffmanTest;
};
|
code/compression/src/lossless_compression/lempel_ziv_welch/README.md | # Lempel-Ziv-Welch compression
The **Lempel-Ziv-Welch** (LZW) algorithm is a dictionary-based lossless compressor. The algorithm uses a dictionary to map a sequence of symbols into codes which take up less space. LZW performs especially well on files with frequent repetitive sequences.
## Encoding algorithm
1. Start with a dictionary of size 256 or 4096 (where the key is an ASCII character and the values are consecutive)
2. Find the longest entry W in the dictionary that matches the subsequent values.
3. Output the index of W and remove W from the input.
4. Add (W + (the next value)) to the dictionary as a key with value (dictionary size + 1)
5. Repeat steps 2 to 4 until the input is empty
**Example:** the input "ToBeOrNotToBeABanana" (length of 20) would be encoded in 17.
```
[T][o][B][e][O][r][N][o][t][To][Be][A][B][a][n][an][a]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
```
The brackets separate the values (e.g. `[To]` is encoded as one value). The LZW algorithm replaces the second occurences of `To`, `Be`, and `an` with one value, eliminating data redundancy.
Note that there is **no need to store the dictionary** because the LZW uncompression process reconstructs the dictionary as it goes along.
### Encoding example

> Image credits: https://slideplayer.com/slide/5049613/
## Decoding algorithm
1. Start with a dictionary of size 256 or 4096 (must be the same as what the encoding process used in step 1)
2. Variable PREV = ""
3. Is the next code V in the dictionary?
- Yes:
1. Variable T = dictionary key whose value = V
2. Output T
3. Add (PREV + (first character of T)) to the dictionary
- No:
1. Variable T = PREV + (first character of PREV)
2. Output T
3. Add T to the dictionary
4. Repeat step 3 until the end of the input is reached
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/compression/src/lossless_compression/lempel_ziv_welch/lzw.cpp | #include <string>
#include <map>
#include <iostream>
#include <iterator>
#include <vector>
/* Compress a string to a list of output symbols.
* The result will be written to the output iterator
* starting at "result"; the final iterator is returned.
*/
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result)
{
// Build the dictionary.
int dictSize = 256;
std::map<std::string, int> dictionary;
for (int i = 0; i < 256; i++)
dictionary[std::string(1, i)] = i;
std::string w;
for (std::string::const_iterator it = uncompressed.begin();
it != uncompressed.end(); ++it)
{
char c = *it;
std::string wc = w + c;
if (dictionary.count(wc)) w = wc;
else
{
*result++ = dictionary[w];
// Add wc to the dictionary.
dictionary[wc] = dictSize++;
w = std::string(1, c);
}
}
// Output the code for w.
if (!w.empty())
*result++ = dictionary[w];
return result;
}
/*
* Decompress a list of output ks to a string.
* "begin" and "end" must form a valid range of ints
*/
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end)
{
// Build the dictionary.
int dictSize = 256;
std::map<int, std::string> dictionary;
for (int i = 0; i < 256; i++)
dictionary[i] = std::string(1, i);
std::string w(1, *begin++);
std::string result = w;
std::string entry;
for (; begin != end; begin++)
{
int k = *begin;
if (dictionary.count(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
else
throw "Bad compressed k";
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry[0];
w = entry;
}
return result;
}
int main()
{
//Test Case 1
std::vector<int> compressed;
compress("Hello world !!", std::back_inserter(compressed));
copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
std::string decompressed = decompress(compressed.begin(), compressed.end());
std::cout << decompressed << std::endl;
return 0;
}
|
code/compression/src/lossless_compression/lempel_ziv_welch/lzw.py | #!/usr/bin/env python3
def compress(input_string):
"""Compresses the given input string"""
# Build the dictionary
dict_size = 256 # All ASCII characters
dictionary = {chr(i): i for i in range(dict_size)}
buffer = ""
result = []
for ch in input_string:
tmp = buffer + ch
if tmp in dictionary:
buffer = tmp
else:
result.append(dictionary[buffer])
dictionary[tmp] = dict_size
dict_size += 1
buffer = ch
if buffer:
result.append(dictionary[buffer])
return result
def decompress(compressed):
"""Given a list of numbers given by compress to a string"""
dict_size = 256 # ASCII characters
dictionary = {i: chr(i) for i in range(dict_size)}
result = ""
buffer = chr(compressed.pop(0))
result += buffer
for ch in compressed:
if ch in dictionary:
entry = dictionary[ch]
elif ch == dict_size:
entry = ch + ch[0]
else:
raise ValueError("Bad Compression for %s" % ch)
result += entry
dictionary[dict_size] = buffer = entry[0]
dict_size += 1
buffer = entry
return result
if __name__ == "__main__":
"""Test cases for LZW"""
# Test 1
test_case_1 = "Hello World!!"
compressed = compress(test_case_1)
print(compressed)
decompressed = decompress(compressed)
print(decompressed)
|
code/compression/src/lossy_compression/README.md | # cosmos #
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/compression/test/lossless_compression/huffman/test_huffman.cpp | #include "../../../src/lossless_compression/huffman/huffman.cpp"
#include <iostream>
#include <fstream>
#include <iterator>
using namespace std;
// test only for Huffman::base_type is 64bit
class HuffmanTest {
public:
HuffmanTest()
{
if (sizeof(Huffman::base_type) != 8)
cout << "the test require that Huffman::base_type based on 64bit\n";
testCalculateFrequency();
testImportDictionary();
testExportDictionary();
testSeperateHeaderAndCode();
testSeperateCode();
testStringToBinary();
testBinaryToHex();
testHexToBinary();
}
void testCalculateFrequency()
{
Huffman huf;
assert(huf.frequency_.empty() == true);
huf.frequency_.clear();
huf.calculateFrequency("a");
assert(huf.frequency_.size() == 1
&& huf.frequency_.find('a') != huf.frequency_.end()
&& huf.frequency_.find('a')->second == 1);
huf.frequency_.clear();
huf.calculateFrequency("aba");
assert(huf.frequency_.size() == 2
&& huf.frequency_.find('a') != huf.frequency_.end()
&& huf.frequency_.find('a')->second == 2
&& huf.frequency_.find('b') != huf.frequency_.end()
&& huf.frequency_.find('b')->second == 1
&& huf.frequency_.find('c') == huf.frequency_.end());
}
void testImportDictionary()
{
Huffman huf;
std::string parameter{};
assert(huf.reverse_dictionary_.empty() == true);
parameter.clear();
huf.reverse_dictionary_.clear();
parameter = "";
huf.importDictionary(parameter);
assert(huf.reverse_dictionary_.empty() == true);
parameter.clear();
huf.reverse_dictionary_.clear();
parameter.append("c");
parameter += huf.DELIMITER;
parameter.append("123");
parameter += huf.DELIMITER;
huf.importDictionary(parameter);
assert(huf.reverse_dictionary_.size() == 1
&& huf.reverse_dictionary_.find("123")->second == 'c');
}
void testExportDictionary()
{
Huffman huf;
std::string res{};
assert(huf.dictionary_.empty() == true);
huf.dictionary_.insert(std::make_pair('c', "123"));
assert(huf.dictionary_.size() == 1
&& huf.dictionary_.find('c')->second == "123");
}
void testSeperateHeaderAndCode()
{
Huffman huf;
std::pair<std::string, std::string> res;
res = huf.seperateHeaderAndCode(huf.addSeperateCode(""));
assert(res.first == "" && res.second == "");
res = huf.seperateHeaderAndCode(huf.addSeperateCode("123"));
assert(res.first == "123" && res.second == "");
res = huf.seperateHeaderAndCode(huf.addSeperateCode("123").append("456"));
assert(res.first == "123" && res.second == "456");
}
void testSeperateCode()
{
Huffman huf;
std::string res;
res = huf.removeSeperateCode(huf.addSeperateCode(""));
assert(res == "");
res = huf.removeSeperateCode(huf.addSeperateCode(huf.addSeperateCode("")));
assert(res == huf.addSeperateCode(""));
res = huf.removeSeperateCode(huf.addSeperateCode("123"));
assert(res == "123");
res = huf.removeSeperateCode( \
huf.addSeperateCode(huf.removeSeperateCode(huf.addSeperateCode("456"))));
assert(res == "456");
}
void testStringToBinary()
{
Huffman huf;
std::string res;
huf.dictionary_.insert(std::make_pair('a', "0"));
huf.dictionary_.insert(std::make_pair('b', "10"));
huf.dictionary_.insert(std::make_pair('c', "11"));
res = huf.stringToBinary("");
assert(res == "");
res = huf.stringToBinary("a");
assert(res == "0");
res = huf.stringToBinary("ab");
assert(res == "010");
res = huf.stringToBinary("abc");
assert(res == "01011");
res = huf.stringToBinary("abca");
assert(res == "010110");
res = huf.stringToBinary("cbabc");
assert(res == "111001011");
}
void testBinaryToHex()
{
Huffman huf;
std::string res, expect;
std::string delim{}, bin{};
bin = "";
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "";
while (expect.size() % (int)(huf.GUARANTEE_BIT / sqrt(huf.HEX_BIT)))
expect.push_back('0');
assert(res == "");
bin = "1011";
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "b000000000000000 ";
assert(res == expect);
bin = "10111110";
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "be00000000000000 ";
assert(res == expect);
bin = "101111101001";
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "be90000000000000 ";
assert(res == expect);
bin = "1011111010010111";
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "be97000000000000 ";
assert(res == expect);
bin = "10111110100101111010011100101000";
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "be97a72800000000 ";
assert(res == expect);
bin = ("10111110100101111010011100101000111");
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin);
expect = "be97a728e0000000 ";
assert(res == expect);
bin = ("1011111010010111101001110010100011100100111010001011111110110101" \
"1011111010010111101001110010100011100100111010001011111110110101");
huf.binary_bit_ = bin.size();
res = huf.binaryToHex(bin); expect = "be97a728e4e8bfb5 be97a728e4e8bfb5 ";
assert(res == expect);
}
void testHexToBinary()
{
Huffman huf;
std::string hex, res;
std::string delim{};
hex = "";
huf.binary_bit_ = hex.size() * 4;
while (hex.size() % huf.GUARANTEE_BIT)
hex.push_back('0');
res = huf.hexToBinary(hex);
assert(res == "");
hex = "b00000000000000 ";
huf.binary_bit_ = hex.size() * 4;
res = huf.hexToBinary(hex);
assert(res == "0000101100000000000000000000000000000000000000000000000000000000");
hex = "be97a728e4e8bfb5 be97a728e4e8bfb5 ";
huf.binary_bit_ = hex.size() * 4;
res = huf.hexToBinary(hex);
assert(res == ("1011111010010111101001110010100011" \
"1001001110100010111111101101011011" \
"1110100101111010011100101000111001" \
"0011101000101111111011010110111110"));
}
};
int main()
{
HuffmanTest test;
Huffman huf;
if (huf.decompression(huf.compression(huf.decompression(huf.compression("")))) != "")
cout << "error empty\n";
Huffman huf2;
if (huf2.decompression(huf2.compression(huf2.decompression(huf2.compression(" "))))
!= " ")
cout << "error separate\n";
Huffman huf6;
if (huf6.decompression(huf6.compression(huf6.decompression(
huf6.compression("COMPRESSION_TESTCOMPRESSION_TEST"))))
!= "COMPRESSION_TESTCOMPRESSION_TEST")
cout << "error binary6\n";
Huffman huf7;
if (huf7.decompression(huf7.compression(huf7.decompression(huf7.compression(" ")))) != " ")
cout << "error delimiter\n";
// Huffman huf8;
// fstream in, out;
// in.open("input.png");
// out.open("output.png", ios::out | ios::trunc);
// if (in.fail() || out.fail())
// cout << "error find file\n";
// else
// huf8.decompression(huf8.compression(in), out);
// in.close();
// out.close();
return 0;
}
|
code/computational_geometry/src/2d_line_intersection/2d_line_intersection.c | // computational geometry | 2D line intersecton | C
// Part of Cosmos by OpenGenus Foundation
// main.c
// forfun
//
// Created by Daniel Farley on 10/10/17.
// Copyright © 2017 Daniel Farley. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
typedef struct{
double x;
double y;
} vec2;
/* return point of intersection, in parent's coordinate space of its parameters */
vec2 fintersection(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4){
double x12 = x1 - x2;
double x34 = x3 - x4;
double y12 = y1 - y2;
double y34 = y3 - y4;
double c = x12 * y34 - y12 * x34;
double a = x1 * y2 - y1 * x2;
double b = x3 * y4 - y3 * x4;
double x = (a * x34 - b * x12) / c;
double y = (a * y34 - b * y12) / c;
vec2 ret;
ret.x = x;
ret.y = y;
return ret;
}
/* line segments defined by 2 points a-b, and c-d */
vec2 intersection(vec2 a, vec2 b, vec2 c, vec2 d){
return fintersection(a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y);
}
int main() {
//example set 1
vec2 a; a.x=10; a.y=3;
vec2 b; b.x=20; b.y=10;
vec2 c; c.x=10; c.y=10;
vec2 d; d.x=20; d.y=3;
vec2 intersectionpoint = intersection(a,b,c,d);
if(intersectionpoint.x >= min(a.x, b.x) && intersectionpoint.x <= max(a.x, b.x) &&
intersectionpoint.y >= min(a.y, b.y) && intersectionpoint.y <= max(a.y, b.y)){
printf("intersection: %f %f", intersectionpoint.x, intersectionpoint.y);
} else {
printf("no intersection");
}
return 0;
}
|
code/computational_geometry/src/2d_line_intersection/2d_line_intersection.cpp | // computational geometry | 2D line intersecton | C++
// main.cpp
// forfun
//
// Created by Ivan Reinaldo Liyanto on 10/5/17.
// Copyright © 2017 Ivan Reinaldo Liyanto. All rights reserved.
// Path of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct vec2
{
double x;
double y;
vec2(double x, double y) : x(x), y(y)
{
}
};
/* return point of intersection, in parent's coordinate space of its parameters */
vec2 intersection(double x1, double y1, double x2, double y2, double x3, double y3, double x4,
double y4)
{
double x12 = x1 - x2;
double x34 = x3 - x4;
double y12 = y1 - y2;
double y34 = y3 - y4;
double c = x12 * y34 - y12 * x34;
double a = x1 * y2 - y1 * x2;
double b = x3 * y4 - y3 * x4;
double x = (a * x34 - b * x12) / c;
double y = (a * y34 - b * y12) / c;
return vec2(x, y);
}
/* line segments defined by 2 points a-b, and c-d */
vec2 intersection(vec2 a, vec2 b, vec2 c, vec2 d)
{
return intersection(a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y);
}
int main()
{
//example set 1
vec2 a(10, 3);
vec2 b(20, 10);
vec2 c(10, 10);
vec2 d(20, 3);
//example set 2
// vec2 a(10, 3);
// vec2 b(20, 3);
// vec2 c(10, 5);
// vec2 d(20, 5);
vec2 intersectionpoint = intersection(a, b, c, d);
if (intersectionpoint.x >= min(a.x, b.x) && intersectionpoint.x <= max(a.x, b.x) &&
intersectionpoint.y >= min(a.y, b.y) && intersectionpoint.y <= max(a.y, b.y))
cout << "intersection: " << intersectionpoint.x << " " << intersectionpoint.y;
else
cout << "no intersection";
return 0;
}
|
code/computational_geometry/src/2d_line_intersection/2d_line_intersection.cs | // computational geometry | 2D line intersecton | C#
using System;
/**
Model class which represents a Vector.
**/
class Vector {
public int x { get; set; }
public int y { get; set; }
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
}
/**
Model class which represents a Line in form Ax + By = C
**/
class Line {
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public Line(int a, int b, int c) {
this.A = a;
this.B = b;
this.C = c;
}
}
/**
Class which provides useful helper methods for straight lines.
**/
class LineOperation {
/**
Returns point of intersection, in parent's coordinate space of its parameters
**/
public Vector getIntersection(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
int x12 = x1 - x2;
int x34 = x3 - x4;
int y12 = y1 - y2;
int y34 = y3 - y4;
int c = x12 * y34 - y12 * x34;
int a = x1 * y2 - y1 * x2;
int b = x3 * y4 - y3 * x4;
int x = (a * x34 - b * x12) / c;
int y = (a * y34 - b * y12) / c;
return new Vector(x, y);
}
/**
Line segments defined by 2 points a-b and c-d
**/
public Vector getIntersection(Vector vec1, Vector vec2, Vector vec3, Vector vec4) {
return getIntersection(vec1.x, vec1.y, vec2.x, vec2.y, vec3.x, vec3.y, vec4.x, vec4.y);
}
// Accepts line in Ax + By = C format
public Vector getIntersection(Line line1, Line line2) {
int A1 = line1.A;
int B1 = line1.B;
int C1 = line1.C;
int A2 = line2.A;
int B2 = line2.B;
int C2 = line2.C;
int delta = A1*B2 - A2*B1;
if (delta == 0)
Console.WriteLine("Lines are parallel");
int x = (B2*C1 - B1*C2) / delta;
int y = (A1*C2 - A2*C1) / delta;
return new Vector(x, y);
}
}
// Driver Program
class MainClass {
static void printVector(Vector intersectionPoint) {
Console.WriteLine(String.Format("Lines intersect at x:{0}, y:{1}", intersectionPoint.x, intersectionPoint.y ) );
}
public static void Main(string[] args) {
// 3x + 4y = 1
Line line1 = new Line(3, 4, 1);
// 2x + 5y = 3
Line line2 = new Line(2, 5, 3);
LineOperation lineOperation = new LineOperation();
Vector intersectionPoint = lineOperation.getIntersection(line1, line2);
Console.WriteLine("Test using line equation");
printVector(intersectionPoint);
Console.WriteLine("Test using points");
intersectionPoint = lineOperation.getIntersection(new Vector(2, 5), new Vector(5, 3), new Vector(7, 4), new Vector(1, 6) );
printVector(intersectionPoint);
}
}
|
code/computational_geometry/src/2d_line_intersection/2d_line_intersection.hs | -- computational geometry | 2D line intersecton | Haskell
-- line2dintersection.hs
-- @author Sidharth Mishra
-- @description 2 dimensional line intersection program in Haskell
-- @copyright 2017 Sidharth Mishra
-- @created Fri Oct 13 2017 20:42:25 GMT-0700 (PDT)
-- @last-modified Fri Oct 13 2017 20:43:52 GMT-0700 (PDT)
--
module Lines (
Line(..),
Point,
getIntersectionPoint,
convertToSlopeIntercept,
getLineFromPoints
) where
-- Line can be represented in the following ways
-- SlopeIntercept (y = mx + c)
-- GeneralForm (ax + by = c)
-- XAxis (y = c)
-- YAxis (x = c)
data Line = SlopeIntercept {
slope :: Double,
intercept :: Double
}
| GeneralForm {
xcoef :: Double,
ycoef :: Double,
constant :: Double
}
| XAxis {
yintercept :: Double
}
| YAxis {
xintercept :: Double
}
deriving (Show)
-- Point in 2-D plane
data Point = Point {
x::Double,
y::Double
}
deriving (Show)
convertToSlopeIntercept :: Line -> Line
-- converts the line from General form to Slope Intercept form
-- XAxis and YAxis and lines parallel to the axes remain unchanged
convertToSlopeIntercept l1 = case l1 of
(GeneralForm a b c) -> SlopeIntercept {
slope = (-1) * (a/b),
intercept = c/b
}
(SlopeIntercept s i) -> SlopeIntercept {
slope = s,
intercept = i
}
(YAxis c) -> YAxis c
(XAxis c) -> SlopeIntercept {
slope = 0,
intercept = c
}
getIntersectionPoint :: Line -> Line -> Maybe Point
-- Finds the intersection point of the 2 lines
-- first, convert each line into slope-intercept form,
-- then, if m1 == m2, lines are parallel -- return Nothing
-- otherwise, finds the intersection point
getIntersectionPoint l1 l2 = getIntersectionPoint' (convertToSlopeIntercept l1) (convertToSlopeIntercept l2)
getIntersectionPoint' :: Line -> Line -> Maybe Point
-- function for internal usage
-- y = m1x + c1 :: Line #1
-- y = m2x + c2 :: Line #2
-- --------------
-- x = (c2 - c1) / (m1 - m2)
-- y = (m1(c2 - c1) / (m1 - m2)) + c1
getIntersectionPoint' (SlopeIntercept m c) (YAxis c') = getIntersectionPoint' (YAxis c') (SlopeIntercept m c)
getIntersectionPoint' (YAxis c') (SlopeIntercept m c) =
-- intersection between YAxis and the line -- x = c', y = (m*c' + c)
return Point {
x = c',
y = (m * c') + c
}
getIntersectionPoint' (SlopeIntercept m1 c1) (SlopeIntercept m2 c2) =
if m1 == m2
then
Nothing -- lines are parallel
else
return Point {
x = (c2 - c1) / (m1 - m2),
y = (m1 * (c2 - c1) / (m1 - m2)) + c1
}
getIntersectionPoint' _ _ = Nothing -- catch all condition, this should not be possible though
getLineFromPoints :: Point -> Point -> Line
-- creates a line in slope intercept form from the given 2 points
-- (x1,y1) ------ (x2,y2)
-- given the line is of form y = mx + b
-- slope = m = (y1 - y2) / (x1 - x2)
-- intercept = b = y1 - (m * x1)
getLineFromPoints (Point x1 y1) (Point x2 y2)
| x1 == x2 = YAxis { xintercept = x1 } -- m = Infinity
| y1 == y2 = XAxis { yintercept = y1 } -- m = 0
| otherwise = SlopeIntercept {
slope = m,
intercept = b
}
where m = (y1 - y2) / (x1 - x2)
b = y1 - (m * x1)
-- For testing, Testing harness
line1 :: Line
-- example line :: y = 0.7x -4
line1 = getLineFromPoints (Point 10 3) (Point 20 10)
line2 :: Line
-- example line :: y = -0.7x + 17
line2 = getLineFromPoints (Point 10 10) (Point 20 3)
line3 :: Line
-- example line :: y = x + 3
line3 = SlopeIntercept { slope = 1, intercept = 3 }
line4 :: Line
-- example line :: y = x + 4
line4 = SlopeIntercept { slope = 1, intercept = 4 }
line5 :: Line
-- example line :: y = 0 -- X Axis
line5 = SlopeIntercept { slope = 0, intercept = 0 }
line6 :: Line
-- example line :: x = 1 -- Y Axis
line6 = getLineFromPoints (Point 1 5) (Point 1 8)
testIntersection :: Line -> Line -> String
-- for testing intersection of 2 lines
testIntersection l1 l2 = "Intersection point:: " ++ case getIntersectionPoint l1 l2 of
Nothing -> "None, Lines are parallel"
Just i -> show i
main :: IO()
-- main driver for testing logic
{- Sample output
*Lines Data.Maybe> main
Line1:: SlopeIntercept {slope = 0.7, intercept = -4.0}
Line2:: SlopeIntercept {slope = -0.7, intercept = 17.0}
Line3:: SlopeIntercept {slope = 1.0, intercept = 3.0}
Line4:: SlopeIntercept {slope = 1.0, intercept = 4.0}
Line5:: SlopeIntercept {slope = 0.0, intercept = 0.0}
Line6:: YAxis {xintercept = 1.0}
Line1 & Line2:: Intersection point:: Point {x = 15.000000000000002, y = 6.5}
Line2 & Line3:: Intersection point:: Point {x = 8.23529411764706, y = 11.235294117647058}
Line3 & Line4:: Intersection point:: None, Lines are parallel
Line1 & Line4:: Intersection point:: Point {x = -26.666666666666664, y = -22.666666666666664}
Line1 & Line3:: Intersection point:: Point {x = -23.33333333333333, y = -20.33333333333333}
Line2 & Line4:: Intersection point:: Point {x = 7.647058823529412, y = 11.647058823529413}
Line2 & Line5:: Intersection point:: Point {x = 24.28571428571429, y = 0.0}
Line5 & Line6:: Intersection point:: Point {x = 1.0, y = 0.0}
Line6 & Line5:: Intersection point:: Point {x = 1.0, y = 0.0}
*Lines Data.Maybe>
-}
main = do
putStrLn $ "Line1:: " ++ show line1
putStrLn $ "Line2:: " ++ show line2
putStrLn $ "Line3:: " ++ show line3
putStrLn $ "Line4:: " ++ show line4
putStrLn $ "Line5:: " ++ show line5
putStrLn $ "Line6:: " ++ show line6
putStrLn $ "Line1 & Line2:: " ++ testIntersection line1 line2
putStrLn $ "Line2 & Line3:: " ++ testIntersection line2 line3
putStrLn $ "Line3 & Line4:: " ++ testIntersection line3 line4
putStrLn $ "Line1 & Line4:: " ++ testIntersection line1 line4
putStrLn $ "Line1 & Line3:: " ++ testIntersection line1 line3
putStrLn $ "Line2 & Line4:: " ++ testIntersection line2 line4
putStrLn $ "Line2 & Line5:: " ++ testIntersection line2 line5
putStrLn $ "Line5 & Line6:: " ++ testIntersection line5 line6
putStrLn $ "Line6 & Line5:: " ++ testIntersection line6 line5
|
code/computational_geometry/src/2d_line_intersection/2d_line_intersection.java | /**
computational geometry | 2D line intersecton | C
Model class which represents a Vector.
**/
class Vector {
int x;
int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
}
/**
Model class which represents a Line in form Ax + By = C
**/
class Line {
int A;
int B;
int C;
public Line(int a, int b, int c) {
this.A = a;
this.B = b;
this.C = c;
}
}
/**
Class which provides useful helper methods for straight lines.
**/
class LineOperation {
/**
Returns point of intersection, in parent's coordinate space of its parameters
**/
public Vector getIntersection(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
int x12 = x1 - x2;
int x34 = x3 - x4;
int y12 = y1 - y2;
int y34 = y3 - y4;
int c = x12 * y34 - y12 * x34;
int a = x1 * y2 - y1 * x2;
int b = x3 * y4 - y3 * x4;
int x = (a * x34 - b * x12) / c;
int y = (a * y34 - b * y12) / c;
return new Vector(x, y);
}
/**
Line segments defined by 2 points a-b and c-d
**/
public Vector getIntersection(Vector vec1, Vector vec2, Vector vec3, Vector vec4) {
return getIntersection(vec1.x, vec1.y, vec2.x, vec2.y, vec3.x, vec3.y, vec4.x, vec4.y);
}
// Accepts line in Ax + By = C format
public Vector getIntersection(Line line1, Line line2) {
int A1 = line1.A;
int B1 = line1.B;
int C1 = line1.C;
int A2 = line2.A;
int B2 = line2.B;
int C2 = line2.C;
int delta = A1*B2 - A2*B1;
if (delta == 0)
System.out.println("Lines are parallel");
int x = (B2*C1 - B1*C2) / delta;
int y = (A1*C2 - A2*C1) / delta;
return new Vector(x, y);
}
}
// Driver Program
class Main {
static void printVector(Vector intersectionPoint) {
System.out.println(String.format("Lines intersect at x:%d, y:%d", intersectionPoint.x, intersectionPoint.y ) );
}
public static void main(String[] args) {
// 3x + 4y = 1
Line line1 = new Line(3, 4, 1);
// 2x + 5y = 3
Line line2 = new Line(2, 5, 3);
LineOperation lineOperation = new LineOperation();
Vector intersectionPoint = lineOperation.getIntersection(line1, line2);
System.out.println("Test using line equation");
printVector(intersectionPoint);
System.out.println("Test using points");
intersectionPoint = lineOperation.getIntersection(new Vector(2, 5), new Vector(5, 3), new Vector(7, 4), new Vector(1, 6) );
printVector(intersectionPoint);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.