Full Code of hacktoon/1001 for AI

master 9117eea9389d cached
202 files
263.4 KB
95.4k tokens
369 symbols
1 requests
Download .txt
Showing preview only (315K chars total). Download the full file or copy to clipboard to get everything.
Repository: hacktoon/1001
Branch: master
Commit: 9117eea9389d
Files: 202
Total size: 263.4 KB

Directory structure:
gitextract_g4n0chn_/

├── README.md
├── algorithms/
│   ├── ai/
│   │   ├── Astar.py
│   │   ├── hamming.py
│   │   └── knn.py
│   ├── bioinformatics/
│   │   ├── gc_skew_diagram.py
│   │   ├── reverse_complement.py
│   │   ├── traducao.py
│   │   └── transcricao.py
│   ├── color/
│   │   └── rgb-to-cmyk.py
│   ├── combinatory/
│   │   └── derangement.py
│   ├── crypto/
│   │   ├── cesar.py
│   │   ├── rot13.py
│   │   ├── rsa.py
│   │   └── vigenere.py
│   ├── data-structures/
│   │   ├── arraysum.py
│   │   ├── heap.py
│   │   └── stack.py
│   ├── date/
│   │   └── leap-year.py
│   ├── economics/
│   │   └── financiamento.py
│   ├── geography/
│   │   └── haversine.py
│   ├── graphs/
│   │   ├── BellmanFord.py
│   │   ├── Dijkstra.py
│   │   ├── EdmondsKarp.py
│   │   └── FloydWarshall.py
│   ├── math/
│   │   ├── algebra/
│   │   │   ├── bhaskara.py
│   │   │   ├── dda.py
│   │   │   ├── media-num.py
│   │   │   ├── media.py
│   │   │   └── permutation.py
│   │   ├── bisection-method.py
│   │   ├── linear-algebra/
│   │   │   └── matrix-transpose.py
│   │   ├── luhn.py
│   │   └── number-theory/
│   │       ├── bozofactoring.py
│   │       ├── divisors.py
│   │       ├── eratosthenes.py
│   │       ├── euclid.py
│   │       ├── fatorial.py
│   │       ├── fibonacci-matrix-form.py
│   │       ├── fibonacci.py
│   │       ├── miller-rabin.py
│   │       ├── newton_raphson_sqrt.py
│   │       ├── perfectnumber.py
│   │       ├── pow.py
│   │       ├── powmod.py
│   │       └── stirling.py
│   ├── misc/
│   │   └── helloworld.py
│   ├── optimization/
│   │   ├── inteval_scheduling.py
│   │   └── knapsack.py
│   ├── pattern-matching/
│   │   ├── AhoCorasick.py
│   │   ├── hamming.py
│   │   ├── kmp.py
│   │   └── levenshtein.py
│   ├── physics/
│   │   └── ballistic.py
│   ├── search/
│   │   ├── binary-search.py
│   │   └── linear-search.py
│   ├── sequence/
│   │   └── token.py
│   └── sorting/
│       ├── bozosort.py
│       ├── bubblesort.py
│       ├── dropsort.py
│       ├── insertionsort.py
│       ├── masochisticsort.py
│       ├── mergesort.py
│       ├── quicksort.py
│       ├── selectionsort.py
│       └── sleepsort.py
├── modelo.txt
└── other-languages/
    ├── ai/
    │   ├── genealogicaltree/
    │   │   └── genealogicaltree.pro
    │   ├── sokoban/
    │   │   ├── alberta/
    │   │   │   ├── screen.1
    │   │   │   ├── screen.1.sol
    │   │   │   └── screen.31
    │   │   ├── runtests.sh
    │   │   ├── sokoban.cpp
    │   │   └── sokobanonline/
    │   │       └── classic/
    │   │           └── thinkingrabbit/
    │   │               └── Boxxle/
    │   │                   ├── sk01-01.in
    │   │                   ├── sk01-01.out
    │   │                   ├── sk01-01.sol
    │   │                   ├── sk01-02.in
    │   │                   ├── sk01-02.out
    │   │                   ├── sk01-02.sol
    │   │                   ├── sk01-03.in
    │   │                   ├── sk01-03.out
    │   │                   ├── sk01-03.sol
    │   │                   ├── sk01-04.in
    │   │                   ├── sk01-04.out
    │   │                   ├── sk01-04.sol
    │   │                   ├── sk01-05.in
    │   │                   ├── sk01-05.out
    │   │                   ├── sk01-05.sol
    │   │                   ├── sk01-06.in
    │   │                   ├── sk01-06.out
    │   │                   ├── sk01-06.sol
    │   │                   ├── sk01-07.in
    │   │                   ├── sk01-07.sol
    │   │                   ├── sk01-08.in
    │   │                   ├── sk01-08.sol
    │   │                   ├── sk01-09.in
    │   │                   ├── sk01-09.sol
    │   │                   ├── sk02-10.in
    │   │                   └── sk02-10.sol
    │   └── sudoku/
    │       ├── sudoku.cpp
    │       └── test_001.in
    ├── array/
    │   ├── merge/
    │   │   └── merge.rb
    │   └── partition/
    │       └── partition.rb
    ├── bitwise/
    │   ├── BitScanForwardDebruijn64.cs
    │   ├── HammingWeight64.cs
    │   ├── bsf-debruijn/
    │   │   └── BitScanForwardDebruijn64.cs
    │   ├── dec2hex/
    │   │   └── dec2hex.c
    │   ├── hamming-weight/
    │   │   └── HammingWeight64.cs
    │   ├── operations/
    │   │   └── operations.cpp
    │   └── swap_xor/
    │       ├── swap_xor.c
    │       ├── swap_xor.cs
    │       └── swap_xor.php
    ├── date/
    │   └── leap-year/
    │       ├── leap-year.lisp
    │       ├── leap-year.php
    │       └── leap-year.rb
    ├── economics/
    │   ├── financiamento/
    │   │   ├── financiamento.cs
    │   │   ├── financiamento.lisp
    │   │   ├── financiamento.php
    │   │   └── financiamento.rb
    │   └── juros-compostos/
    │       └── juros-compostos.lisp
    ├── geography/
    │   └── haversine/
    │       └── haversine.rb
    ├── graphs/
    │   ├── dijkstra/
    │   │   ├── dijkstra.cpp
    │   │   └── dijkstra.java
    │   ├── floyd-warshall/
    │   │   └── floyd-warshall.cpp
    │   └── prim/
    │       └── prim.java
    ├── lang/
    │   └── nums2words.c
    ├── math/
    │   ├── bhaskara/
    │   │   ├── bhaskara.lisp
    │   │   ├── bhaskara.php
    │   │   └── bhaskara.rb
    │   ├── dda/
    │   │   ├── dda.cpp
    │   │   ├── dda.cs
    │   │   ├── dda.java
    │   │   ├── dda.php
    │   │   └── dda.rb
    │   ├── determinant/
    │   │   ├── determinant.cpp
    │   │   └── determinant.rb
    │   ├── divisors/
    │   │   └── divisor.rb
    │   ├── eratostenes/
    │   │   └── eratostenes.java
    │   ├── even/
    │   │   └── even.c
    │   ├── fatorial/
    │   │   ├── fatorial.cs
    │   │   ├── fatorial.lisp
    │   │   ├── fatorial.php
    │   │   └── fatorial.rb
    │   ├── fibonacci/
    │   │   ├── fibonacci.c
    │   │   ├── fibonacci.clj
    │   │   ├── fibonacci.cs
    │   │   ├── fibonacci.java
    │   │   ├── fibonacci.lisp
    │   │   ├── fibonacci.lua
    │   │   ├── fibonacci.php
    │   │   └── fibonacci.rb
    │   ├── gauss/
    │   │   └── sumgauss.cpp
    │   ├── geometric-mean/
    │   │   └── geometric-mean.cpp
    │   ├── linear-system/
    │   │   └── linear-system.c
    │   ├── lu-decomposition/
    │   │   ├── lu-decomposition.cpp
    │   │   └── lu-decomposition.rb
    │   ├── matrix-transpose/
    │   │   └── matrix-transpose.cpp
    │   ├── media/
    │   │   ├── media.lisp
    │   │   ├── media.php
    │   │   └── media.rb
    │   ├── media-num/
    │   │   ├── media-num.c
    │   │   └── media-num.rb
    │   ├── multiply-matrix/
    │   │   └── multiply-matrix.cpp
    │   ├── n-root/
    │   │   └── MetodosNumericos.java
    │   ├── perfect-numbers/
    │   │   └── perfectnumber.rb
    │   ├── pow/
    │   │   └── pow.c
    │   └── stirlings-approximation/
    │       └── stirling.clj
    ├── number-theory/
    │   ├── euclid/
    │   │   ├── euclid.lisp
    │   │   └── euclid.rb
    │   ├── inverse/
    │   │   └── inverse.c
    │   ├── modular-exponentiation/
    │   │   └── modular-exponentiation.cpp
    │   ├── odd/
    │   │   └── odd.c
    │   ├── odd-even/
    │   │   └── odd-even.c
    │   └── sieve/
    │       ├── sieve.cpp
    │       └── sieve.lisp
    ├── pattern-matching/
    │   └── lcs/
    │       └── lcs.rb
    ├── physics/
    │   └── ballistic/
    │       └── ballistic.lisp
    ├── puzzle/
    │   ├── hanoi/
    │   │   └── hanoi.cpp
    │   └── sudoku-validation/
    │       └── sudoku-validation.cpp
    ├── search/
    │   ├── binary-search/
    │   │   └── BuscaBinaria.java
    │   ├── linear-search/
    │   │   └── linear-search.rb
    │   └── simul-smaller-higher/
    │       └── simul-smaller-higher.cpp
    ├── sequence/
    │   └── token/
    │       ├── token.php
    │       └── token.rb
    └── sorting/
        ├── bozosort/
        │   ├── bozosort.lisp
        │   ├── bozosort.php
        │   └── bozosort.rb
        ├── bubblesort/
        │   ├── bubblesort.lisp
        │   └── bubblesort.php
        ├── fisher-yates/
        │   └── fisher-yates.c
        ├── heapsort/
        │   └── heapsort.c
        ├── insertionsort/
        │   ├── insertionsort.cpp
        │   ├── insertionsort.php
        │   └── insertionsort.rb
        ├── mergesort/
        │   ├── mergesort.c
        │   └── mergesort.rb
        ├── quicksort/
        │   ├── quicksort.c
        │   ├── quicksort.php
        │   └── quicksort.rb
        ├── selectionsort/
        │   ├── selectionsort.cpp
        │   └── selectionsort.php
        ├── shellsort/
        │   └── shellsort.cpp
        └── stoogesort/
            └── stoogesort.cpp

================================================
FILE CONTENTS
================================================

================================================
FILE: README.md
================================================
# 1001 algoritmos para implementar antes de morrer

Vamos reunir 1001 implementações de algoritmos em um livro digital interativo que servirá principalmente de aprendizado para quem colaborar e guia/referência para jovens aspirantes a programadores. Do Bozosort ao crivo de Eratóstenes, teremos de tudo!

Os códigos devem estar de acordo com os requisitos abaixo:

* Siga este modelo de arquivo: [https://github.com/karlisson/1001/blob/master/modelo.txt](https://github.com/karlisson/1001/blob/master/modelo.txt)
* Ser em Python. Lembre-se, é para iniciantes.
* O algoritmo deve ser abrangente e multi-plataforma, ou seja, coisas específicas demais como "código para ligar o led da placa XPTO" não serão aceitas. Exemplo: problemas clássicos da computação e exercícios em geral.
* Navegue no repositório e veja os algoritmos já adicionados antes de submeter.
* O código não pode depender de bibliotecas extras que precisam ser instaladas.
* O código deve conter testes ou exemplos de uso para que possa ser avaliado rapidamente, e não pode ser muito extenso (i.e. verboso).
* O patch deve consistir em apenas um arquivo, cujo nome deve seguir o formato nome-algoritmo.py, onde 'nome-algoritmo' é o nome abreviado, minúsculo e sem espaços ou acentos.



================================================
FILE: algorithms/ai/Astar.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo A* 
Autores: 
    Peter Hart, Nils Nilsson and Bertram Raphael 
Colaborador:
 	Péricles Lopes Machado [gogo40] (pericles.raskolnikoff.gmail.com)
Tipo: 
    graphs
Descrição: 
    O Algoritmo A* é uma generalização do algoritmo de Dijkstra que
permite acelerar a busca com uma heuristica que utiliza propriedades do grafo 
para estimar a distância para o destino. Este algoritmo é ideal quando aplicados
em grades ou representações espaciais e em situações em que já conhecemos a
posição do destino.

Complexidade: 
    O(|E| log |V|)
Dificuldade: 
    medio
Referências:
    [1] http://en.wikipedia.org/wiki/A*_search_algorithm
    [2] http://falapericles.blogspot.com.br/2009/05/o-algoritmo.html
"""

"""
Função para imprimir o caminho
"""
def imprime_caminho(pi, u):
	ux = u[0];
	uy = u[1];

	if pi[ux][uy] == None:
		print u;
	else:
		imprime_caminho(pi, pi[ux][uy]);
		print u;

"""
Função para 'renderizar' o jogador numa posição da grade
"""
def renderizar_grade(G, ux, uy):
	l = list(G[ux]);
	l[uy] = 'x';
	G[ux] = "".join(l);

	for i in range(0, len(G)):
		print " ", G[i];

	print "---------";

	l = list(G[ux]);
	l[uy] = '.';
	G[ux] = "".join(l);

"""
Função para 'renderizar' a trajetória percorrida
"""
def renderizar_caminho(pi, G, u):
	ux = u[0];
	uy = u[1];

	if pi[ux][uy] == None:
		renderizar_grade(G, ux, uy);
	else:
		renderizar_caminho(pi, G, pi[ux][uy]);
		renderizar_grade(G, ux, uy);

from heapq import *;
from math import *;


"""
Este algoritmo utiliza uma grade para realizar a busca.
A origem é marcada com o símbolo 'x' e o destino é marcado
com o simbolo '+'.

"""
G = [
"###..####################..####################..####################..####################..#################.",
".........*........#.#..........*........#.#...........*........#.#...........*........#.............*.......#..",
"....#....#.##.#####.#......#....#.##.#####.#......#....#.##.#####.#......#....#.##.#####........#....#.##.###..",
"#...#....#..#......*..#...#....#..#......*..#...#....#..#......*..#...#....#..#......*......#....#..#......*...",
"#.####...#*##+.....*.##.####...#*##......*.##.####...#*##......*.##.####...#*##......*.##.####...#*##......*.#.",
"#....#..##.........#.##....#..##.........#.##....#..##.........#.##....#..##.........#.##..................#.#.",
"#....#...#.###.##..####....#...#.###.##..####....#...#.###.##..####....#...#.###.##..####........#.###.##..###.",
"#....#.......#..#....##....#.......#..#....##....#.......#..#....##....#...............##............#..#....#.",
"#....#.......#..#....##....#.......#..#....##....#.......#..#....##....#.............................#..#....#.",
"###..#.##########.#######..#.##########.#######..#.##########.#######..#.##########.##.####..#.##########.####.",
"#...##.....#....#.#.......##.....#....#.#..##...##.....#....#.#.......##.....#....#.#.......##.....#....#.#..#.",
"#..........#.....................#.........##..........#.....................#.........##..........#.........#.",
"###..#.....##############..#.....##############..#.x...##############..#.....#########.####..#.....######..###.",
".........*.....................*......................*........#.#...........*..........#...........*.......#..",
"....#....#.##.#####.#......#....#.##.#####.#......#....#.##.#####.#......#....#.##.#####.#......#....#.##..##..",
"#...#....#..#......*..#...#....#..#......*..#...#....#..#......*...........#..#......*..#...#....#..#......*...",
"#.####...#*##......*.##.####...#*##......*.##.####...#*##......*.##.####...#*##......*.##.####...#*##......*.#.",
"#....#..##.........#.##....#..##.........#.##....#..##.........#.##....#..##.........#.......#..##.........#.#.",
"#....#...#.###.##..####....#...#.###.##..####....#...#.###.##..####....#...#.###.##..####....#...#.###.##..###.",
"#....#.......#..#....##....#.......#..#....##....#.......#..#....##....#.......#..#....##............#..#....#.",
"#....#.......#..#....##....#.......#..#....##....#.......#..#....##....#.......#..#....##....#.......#..#....#.",
"###..#.##########.#######..#.##########.#######..#.##########.#######..#.##########.#######..#.##########.####.",
"#...##.....#....#.#..##...##.....#....#.#..##...##.....#....#.#..##...##.....#....#.#..##...##.....#....#.#..#.",
"#..........#.........##..........#.........##..........#.........##..........#.........##..........#.........#.",
"###..#.....##############..#.....##############..#.....##############..#.....##############..#.....###########.",
"..............................................................................................................."];

"""
Localizando a posição do jogador ('x') e do destino ('+')
e inicializa matriz com estimativa de distância D.
"""

D = [];
pi = [];
for x in range(0, len(G)):
	D += [[]];
	pi += [[]];
	for y in range(0, len(G[x])):
		D[x] += [None];
		pi[x] += [None];
		if G[x][y] == 'x':
			s = (x, y);
			l = list(G[x]);
			l[y] = '.';
			G[x] = "".join(l);
		elif G[x][y] == '+':
			t = (x, y);

"""
Possibilidades de movimentação:
...
.x.
...
"""

dx = [-1, -1, -1,  0,  0,  1,  1,  1];
dy = [-1,  0,  1, -1,  1, -1,  0,  1];


"""
Heurística que estima a distancia para o destino:

H(p, t) = sqrt((p.x - t.x)^2 + (p.y - t.y)^2)

Nesse código utilizamos o quadrado da distância euclidiana como estimativa.
"""

def H(s, t):
	Dx = s[0] - t[0];
	Dy = s[1] - t[1];
	return sqrt(Dx * Dx + Dy * Dy);

def dist(s, t):
	Dx = s[0] - t[0];
	Dy = s[1] - t[1];
	return sqrt(Dx * Dx + Dy * Dy);



Q = [];

D[s[0]][s[1]] = 0;
heappush(Q, (0, s));

"""
Enquanto a fila de prioridade não estiver vazia tente verificar se o topo
da fila é melhor opção de rota para se chegar nos adjascentes. Como o topo
já é o mínimo, então garante-se que D[u] já está minimizado no momento.
"""
while Q:
	p = heappop(Q)[1];

	u = (p[0], p[1]);
	ux = u[0];
	uy = u[1];

	"""
	Como já chegamos no destino, podemos parar a busca
	"""
	if u == t:
		break;

	for i in range(0, len(dx)):
		vx = u[0] + dx[i];
		vy = u[1] + dy[i];

		v = (vx, vy);

		duv = dist(u, v);
		if vx > -1 and vx < len(G):
			if vy > -1 and vy < len(G[vx]): 
				if (D[vx][vy] > D[ux][uy] + duv or D[vx][vy] == None) and G[vx][vy] != '#':
					D[vx][vy] = D[ux][uy] + duv;
					pi[vx][vy] = u;
					"""
					A única diferença entre o A* e o dijkstra é o modo como é ordenado a heap.
					No caso, ela utiliza a heurítica H que procura colocar no topo os pontos mais
					próximos do destino.
					"""
					heappush(Q, (D[vx][vy] + H(v, t), v));
		

if D[t[0]][t[1]] != None:
	print "A distância entre s e t é: ", D[t[0]][t[1]]; 
	"""
	Descomente essa linha caso queira ver a sequencia de passos percorrido pelo jogador
	"""
	imprime_caminho(pi, t);
	"""
	Descomente essa linha se quiseres ver o caminho percorrido na grade
	"""
	#renderizar_caminho(pi, G, u);
else:
	print "Não existe caminho entre s e t!"



================================================
FILE: algorithms/ai/hamming.py
================================================
# coding: utf-8
'''
Hamming Distance
Autor:
	Hamming
Colaborador:
	Adriano Melo <adriano@adrianomelo.com>
	Dayvid Victor <victor.dvro@gmail.com>
Tipo:
	artificial-intelligence
Descrição:
	Algorítmo para calcular a distância entre vetores com dados categóricos.
Complexidade:  
	O(n) - sendo n o tamanho do vetor
Dificuldade:
	fácil
Referências:

'''

def hamming(a, b):
	return sum([hamming_i(ai, bi) for ai, bi in zip(a,b)])

def hamming_i(ai, bi):
	return (0 if ai == bi else 1)

def knn(k, treino, padrao, distancia=lambda a,b: sum([(c-d)**2 for c,d in zip(a,b)])):
	k_nearest = sorted([[distancia(pe[:-1], padrao), pe[-1]] for pe in treino])[:k]
	return max(set([e[-1] for e in k_nearest]), key = [e[-1] for e in k_nearest].count)



if __name__ == '__main__':
	train = [['gordo', 'baixo', 'devagar', 'golfista'],
		['magro', 'alto', 'rapido', 'jogador de basquete'],
		['magro', 'baixo','rapido', 'jogador de futebol'],
		['gordo', 'alto', 'rapido', 'jogador de futebol americano'],
		['medio', 'medio', 'rapido', 'jogador de tenis']]
	
	padrao = ['magro', 'medio', 'rapido']
	
	print knn(1, train, padrao, distancia = hamming)



================================================
FILE: algorithms/ai/knn.py
================================================
# coding: utf-8
'''
K-Nearest Neighboor (k-NN)
Autor:
    Belur V. Dasarathy
Colaborador:
	Adriano Melo <adriano@adrianomelo.com>
	Dayvid Victor <victor.dvro@gmail.com>
Tipo:
    artificial-intelligence
Descrição:
    Algoritmo de aprendizagem baseado em instâncias.
    Uma matriz é dada ao algoritmo contendo vetores e as classes que eles pertencem,
    um vetor não classificado é a segunda entrada do algoritmo. 
    A saída é a classe que o vetor não classificado pertence.
Complexidade:  
    O(n * m * k) = O(n)
    n: número de instâncias
    m: tamanho dos vetores
    k: K-primeiros vizinhos
Dificuldade:
    medio
Referências:
    Belur V. Dasarathy, ed (1991). Nearest Neighbor (NN) Norms: NN Pattern Classification Techniques. ISBN 0-8186-8930-7.
'''

def knn(k, treino, padrao, distancia=lambda a,b: sum([(c-d)**2 for c,d in zip(a,b)])):
	k_nearest = sorted([[distancia(pe[:-1], padrao), pe[-1]] for pe in treino])[:k]
	return max(set([e[-1] for e in k_nearest]), key = [e[-1] for e in k_nearest].count)

treino = [
	[1,2,3,4,5,6,'classe 1'],
        [1,2,3,3,5,6,'classe 1'],
        [2,3,5,6,7,8,'classe 2'],
        [9,9,9,9,9,9,'classe 3'],
        [9,9,9,9,9,8,'classe 3'],
        [9,9,9,9,9,7,'classe 3']]

print knn(1, treino, [2,3,4,6,7,8])
print knn(3, treino, [2,3,4,6,7,8])
print knn(6, treino, [2,3,4,6,7,8])



================================================
FILE: algorithms/bioinformatics/gc_skew_diagram.py
================================================
# coding: utf-8
"""
Skew Diagram
Autor:

Colaborador:
    Guido Luz Percú (guidopercu@gmail.com)
Tipo:
   bioinformatics
Descrição:
    Monta os pontos de um diagrama GC Skew, um diagrama que mostra a diferença entre G (guanina) e C (citosina) em um DNA.
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    https://en.wikipedia.org/wiki/GC_skew
Licenca:
    MIT
"""

def gc_skew_diagram(genome):
    qtd_c = 0
    qtd_g = 0
    skew = [0]
    for base in genome:
        if base == 'C':
            qtd_c += 1
        elif base == 'G':
            qtd_g += 1
        skew.append(qtd_g - qtd_c)
    return skew

print(gc_skew_diagram('ACCCCGTACTGGGGG'))


================================================
FILE: algorithms/bioinformatics/reverse_complement.py
================================================
# coding: utf-8
"""
Reverse Complement
Autor:

Colaborador:
    Guido Luz Percú (guidopercu@gmail.com)
Tipo:
   bioinformatics
Descrição:
    Converte uma sequência de DNA em seu complemento, isto é, inverte a string e troca A por T, T por A, C por G e G por C.
Complexidade:
    ?
Dificuldade:
    facil
Licenca:
    MIT
"""


def reverse_complement(genoma):
    dicionario = {"A": "T", "T": "A", "C": "G", "G": "C"}
    complemento_reverso = [dicionario[x] for x in genoma[::-1]]
    return "".join(complemento_reverso)

print(reverse_complement('ATCG')) # CGAT


================================================
FILE: algorithms/bioinformatics/traducao.py
================================================
# coding: utf-8
"""
Tradução
Autor:

Colaborador:
    Guido Luz Percú (guidopercu@gmail.com)
Tipo:
   bioinformatics
Descrição:

Complexidade:
    ?
Dificuldade:
    facil
Referências:
    https://pt.wikipedia.org/wiki/Tradu%C3%A7%C3%A3o_%28gen%C3%A9tica%29
    https://en.wikipedia.org/wiki/Genetic_code
Licenca:
    MIT
"""


def traducao(rna):
    assert len(rna) % 3 == 0
    resultado = ''
    codigo_genetico = {
        'UUC': 'F', 'CUC': 'L', 'AUC': 'I', 'GUC': 'V', 'UUU': 'F', 'CUU': 'L', 'AUU': 'I', 'GUU': 'V', 'UUA': 'L',
        'CUA': 'L', 'AUA': 'I', 'GUA': 'V', 'UUG': 'L', 'CUG': 'L', 'AUG': 'M', 'GUG': 'V', 'UCU': 'S', 'CCU': 'P',
        'ACU': 'T', 'GCU': 'A', 'UCC': 'S', 'CCC': 'P', 'ACC': 'T', 'GCC': 'A', 'UCA': 'S', 'CCA': 'P', 'ACA': 'T',
        'GCA': 'A', 'UCG': 'S', 'CCG': 'P', 'ACG': 'T', 'GCG': 'A', 'UAU': 'Y', 'CAU': 'H', 'AAU': 'N', 'GAU': 'D',
        'UAC': 'Y', 'CAC': 'H', 'AAC': 'N', 'GAC': 'D', 'UAA': '', 'CAA': 'Q', 'AAA': 'K', 'GAA': 'E', 'UAG': '',
        'CAG': 'Q', 'AAG': 'K', 'GAG': 'E', 'UGU': 'C', 'CGU': 'R', 'AGU': 'S', 'GGU': 'G', 'UGC': 'C', 'CGC': 'R',
        'AGC': 'S', 'GGC': 'G', 'UGA': '', 'CGA': 'R', 'AGA': 'R', 'GGA': 'G', 'UGG': 'W', 'CGG': 'R', 'AGG': 'R',
        'GGG': 'G',
    }
    for i in range(0, len(rna), 3):
        traducao = codigo_genetico[rna[i:i+3]]
        if traducao != '':
            resultado +=traducao
    return resultado
print(traducao('ACGUUA'))


================================================
FILE: algorithms/bioinformatics/transcricao.py
================================================
# coding: utf-8
"""
Transcrição
Autor:

Colaborador:
    Guido Luz Percú (guidopercu@gmail.com)
Tipo:
   bioinformatics
Descrição:
    Transcrição é o processo de formação do RNAm mensageiro a partir da cadeia-molde de DNA
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    https://pt.wikipedia.org/wiki/Transcri%C3%A7%C3%A3o_%28gen%C3%A9tica%29
Licenca:
    MIT
"""
def transcrever(dna):
  """ Transforma string DNA em string RNAm """
  return dna.replace('T', 'U')

print(transcrever('ACGT'))


================================================
FILE: algorithms/color/rgb-to-cmyk.py
================================================
# encoding: utf-8

'''
RGB to CMYK
Autor:
    ?
Colaborador:
    Aurélio A. Heckert
Tipo:
    color
Descrição:
    Converte uma cor definida em RGB para CMYK.

    RGB é um sistema aditivo de definição de cores, representa a mistura de luz. Suas componentes são (em ordem) vermelho, verde e azul.
    CMYK é um sistema subtrativo de definição de cores, representa a mistura de pigmentos. Suas componentes são (em ordem) ciano, magenta, amarelo e preto. O preto no CMYK deriva uma necessidade do uso prático, já que a mistura dos 3 pigmentos é custoso, não é realmente preto e a sobreposição de impressões tornaria o desalinhamento mais perceptível nos detalhes escuros.
    O algorítimo deste exemplo considera as componentes como valores flutuantes entre 0 e 1, onde 0 significa sem representação e 1 máxima representação. Sendo assim o branco seria (1,1,1) em RGB e (0,0,0,0) em CMYK, o vermelho intenso seria (1,0,0) em RGB e (0,1,1,0) em CMYK e o laranja seria (1,0.5,0) em RGB e (0,0.5,1,0) em CMYK. A representação das componentes em valores flutuantes entre 0 e 1 pode parecer estranho pelo nosso costume em ver cores definidas com 1 byte por unidade, mas essa representação é bastante útil em vários algorítimos para manipulação de cores e ainda viabiliza representações com maior profundidades de cores (mais de 1 byte por componente).
Complexidade:  
    O(1)
DIficuldade:
    facil
Referências:
    http://en.wikipedia.org/wiki/RGB
    http://en.wikipedia.org/wiki/CMYK
'''

def rgb2cmyk( red, green, blue ):

    black = min( 1-red, 1-green, 1-blue )
    nb = 1 - black  # negative black
    if black == 1:
        cyan    = 0
        magenta = 0
        yellow  = 0
    elif nb > 0:
        cyan    = ( nb - red   ) / nb
        magenta = ( nb - green ) / nb
        yellow  = ( nb - blue  ) / nb
    else:
        cyan    = 1 - red
        magenta = 1 - green
        yellow  = 1 - blue

    return "%.1f  %.1f  %.1f  %.1f" % ( cyan, magenta, yellow, black )


print 'Preto:\t\t\t',       rgb2cmyk( 0.0, 0.0, 0.0 )
print 'Cinza escuro:\t\t',  rgb2cmyk( 0.3, 0.3, 0.3 )
print 'Cinza médio:\t\t',   rgb2cmyk( 0.5, 0.5, 0.5 )
print 'Cinza claro:\t\t',   rgb2cmyk( 0.7, 0.7, 0.7 )
print 'Branco:\t\t\t',      rgb2cmyk( 1.0, 1.0, 1.0 )
print 'Vermelho vivo:\t\t', rgb2cmyk( 1.0, 0.0, 0.0 )
print 'Vermelho sangue:\t', rgb2cmyk( 0.7, 0.0, 0.0 )
print 'Laranja:\t\t',       rgb2cmyk( 1.0, 0.5, 0.0 )
print 'Verde Musgo:\t\t',   rgb2cmyk( 0.6, 0.7, 0.6 )


================================================
FILE: algorithms/combinatory/derangement.py
================================================
#!usr/bin/python
# encoding: utf-8

"""
Desarranjo
Autor:
    Pierre Raymond de Montmort
Colaborador:
    Carlos Rodrigues c11a10r9l8o7s6f5e4l3i2x1@yahoo.com.br
Tipo:
    math
Descrição:
    Algoritmo que calcula permutação caótica
Dificuldade:
    facil
Complexidade:
    ?
Referência:
    http://pt.wikipedia.org/wiki/Desarranjo
"""

from __future__ import division

def fatorial(x):
    if x <= 1:
        return 1
    else:
        return x * fatorial(x-1)

n = 5
d = 0
for i in range(0, n):
    d = d + ((-1) ** i / fatorial(i))
print fatorial(n) * d


================================================
FILE: algorithms/crypto/cesar.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""
Cesar Cipher (Cifra de César)
Autor:
    César
Colaborador:
    Apu, Sigano, InFog, Paulo, Doug, ExHora <gccsd@lista.gccsd.com.br>
Tipo:
    crypto
Descrição:
    Este algoritmo implementa a Cifra de César
    Este algoritmo foi implementado em um Dojo do Grupo de Compartilhamento do
    Conhecimento Santos Dumont <http://gccsd.com.br>
Complexidade:  
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Cifra_de_C%C3%A9sar
Licenca:
    GPL
"""

__authors__ = (
    "Apu",
    "Sigano",
    "InFog",
    "Paulo",
    "Doug",
    "ExHora"
)

import string

class Cesar(object): 
    
    def __init__(self):
        self.INICIO = 65
        self.FIM = 90
        self.ESPACO = 32
    
    def crypt(self, entrada = "", chave = 0):
        saida = ""
        entrada = entrada.upper()

        for letra in entrada:
            valor = ord(letra)
            
            if (not valor == self.ESPACO):
                valor += chave
                if (valor > self.FIM):
                    valor -= 26
            saida += chr(valor)
            
        return saida
    
    def decrypt(self, entrada = "", chave = 0):
        saida = ""
        entrada = entrada.upper()
        
        for letra in entrada:
            valor = ord(letra)
            
            if (not valor == self.ESPACO):
                valor -= chave
                if (valor < self.INICIO):
                    valor += 26
            saida += chr(valor)
        
        return saida

c = Cesar()
print c.crypt("a ligeira raposa marrom saltou sobre o cachorro cansado", 3)
print c.decrypt("D OLJHLUD UDSRVD PDUURP VDOWRX VREUH R FDFKRUUR FDQVDGR", 3)


================================================
FILE: algorithms/crypto/rot13.py
================================================
#!/usr/bin/env python3.1

"""
ROT13
Autor:
    ?
Colaborador:
    Fernando Medeiros <fekomedeiros - at - gmail.com>
Tipo:
    sequence
Descrição: 
    Implementação do algoritmo ROT-13, ou "Rotate By 13".
    É um procedimento simples mas eficaz para garantir que textos eletrônicos 
    não sejam lidos por distração ou acidente.
    Util para proteger mensagens que talvez o leitor não queira ler. 
    Exemplo, "spoilers" sobre determinado assunto em Fóruns ou listas de discussão.
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/ROT13
"""

def rot13(text):
    alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    rotated = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
    r13 = "".maketrans(alpha, rotated)
    return text.translate(r13)

#Exemplos de uso:

print(rot13("Agora estou usando ROT-13!"))
#Exibe a mensagem: Ntben rfgbh hfnaqb EBG-13!

print(rot13("Ntben rfgbh hfnaqb EBG-13!"))
#Exibe a mensagem: Agora estou usando ROT-13!
#Note que a mesma função é usada para codificar e decodificar o texto.


================================================
FILE: algorithms/crypto/rsa.py
================================================
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
"""
RSA
Autor:
    Ron Rivest, Adi Shamir, e Leonard Adleman 
Colaborador:
    Juan Lopes <me@juanlopes.net>
Tipo:
    crypto
Descrio: 
    Implementao simples do algoritmo RSA.
    
    Este algoritmo se baseia na dificuldade computacional da fatorao de
    nmeros inteiros.
    
    A idia que a chave pblica e privada sejam baseadas na multiplicao
    de dois nmeros primos (geralmente grandes) e que a relao entre elas
    exija o conhecimento dos fatores dessa multiplicao.
Complexidade:
    O(n)
Dificuldade:
    medio
Referncias:
    http://en.wikipedia.org/wiki/RSA_(algorithm)
"""

def gcd(a,b):
    if b==0: return (1, 0)
    q = a/b
    x,y = gcd(b, a-q*b)
    return (y, x-q*y)
    
def inverse(a, b):
    x,y = gcd(a,b)
    return (x if x > 0 else x+b)
   
def rsa(n, e, M):
    return map(lambda m: pow(m, e, n), M)
   
p,q = 41, 47              #primos             
n,phi = p*q, (p-1)*(q-1)  #mdulo and totiente
e,d = 7, inverse(7,phi)   #expoentes pblico e privado

plain = (1,2,3,4,5,6,7,42)
encrypted = rsa(n, e, plain)
plain_again = rsa(n, d, encrypted)

print 'Chave pblica:', (n,e)
print 'Chave privada:', (n,d)
print '---'
print 'Mensagem original:', plain
print 'Mensagem encriptada:', encrypted
print 'Mensagem decriptada:', plain_again

================================================
FILE: algorithms/crypto/vigenere.py
================================================
#!usr/bin/python
# encoding: utf-8

"""
Vigenère cipher (Cifra de Vigenère)
Autor:
  Giovan Battista Bellaso (1553) "La cifra del. Sig. Giovan Battista Bellaso"
  Foi erradamente atribuida a Blaise de Vigenère
Colaborador:
  damor - dave-world (at) hotmail.com
Tipo:
  Crypto
Descrição:
  Este algoritmo implementa o metodo de criptografia "Cifra de Vigenère"
  "A cifra de Vigenère consiste no uso de várias cifras de César em sequência,
  com diferentes valores de deslocamento ditados por uma "palavra-chave"" - Wiki
Complexidade:
  ?
Dificuldade:
  facil
Referências: (opcional)
  http://pt.wikipedia.org/wiki/Cifra_de_Vigen%C3%A8re
Licenca:(opcional)
  GPL
"""

class Vigenere(object):
  def __init__(self):
    self.tabulaRecta = [ [ 0 for i in range(26) ] for j in range(26) ] # Construir a tabula recta (Grelha de Vigenere)
    for i in range(26):
      for j in range(26):
        ch = ord("A")+j+i
        if (ch>90): ch-=26
        self.tabulaRecta[i][j] = chr(ch)

  def crypt(self, plaintext = "", chave= ""):
    self.newKey=chave
    while len(self.newKey)<len(plaintext): self.newKey+=chave
    chave = self.newKey[:len(plaintext)]
    pos = 0
    cipher = ""
    for c in plaintext:
      cipher += self.tabulaRecta[ord(chave[pos]) % 26][ord(c) % 26]
      pos += 1
    return cipher

  def decrypt(self, ciphertext = "", chave=""):
    self.newKey=chave
    while len(self.newKey)<len(ciphertext): self.newKey+=chave
    chave = self.newKey[:len(ciphertext)]
    cipher = ""
    iter = 0
    for c in chave:
      pos = 0
      for k in range(26):
        if (self.tabulaRecta[ord(c)-ord("A")][k] == ciphertext[iter]):
          cipher += chr(ord("A")+pos)
        pos += 1
      iter += 1
    return cipher

v = Vigenere()
encWord = v.crypt("ATACARBASESUL","LIMAO")
print encWord
print v.decrypt(encWord,"LIMAO")


================================================
FILE: algorithms/data-structures/arraysum.py
================================================
# coding: utf-8
'''
Array Sum
Autor:
    ?
Colaborador:
    Dayvid Victor (victor.dvro@gmail.com)
Descricao:
    Esse programa recebe como parametro uma lista
    e retorna a soma dos elementos desta lista.
Complexidade:
    O(n)
Dificuldade:
    facil
Licenca:
    GPL
'''

def arraysum(l, key = lambda a, b: a + b):
	s = 0
	for e in l:
		s = key(s,e)
	return s

if __name__ == '__main__':
	l1 = [1,2,3,4,5,6,7,8,9,10]
	l2 = [-4,-3,-2,-1,0,1,2,3,4]

	print arraysum(l1)
	print arraysum(l2)



================================================
FILE: algorithms/data-structures/heap.py
================================================
# -*- encoding: utf-8 -*-
"""
Binary Heap
Autor:
    M. D. ATKINSON, J. R. SACK, N. SANTORO, and T. STROTHOTT
Colaborador:
    Juan Lopes (me@juanlopes.net)
Tipo:
    data-structures
Descrição:
    Implementação de priority queue usando uma binary min-heap.
    
Complexidade:  
    Inserção: O(log n) 
    Remoção: O(log n)
    Obter mínimo: O(1)
Dificuldade:
    Fácil
Referências: (opcional)
    http://en.wikipedia.org/wiki/Binary_heap
"""

class BinaryHeap:
    def __init__(self, V = []):
        self.V = [None] + list(V)
        self.heapify()
        
    def heapify(self):
        for i in range(self.count()/2, 0, -1):
            self.bubble_down(i)
        
    def count(self):
        return len(self.V) - 1
        
    def top(self):
        return (self.V[1] if self.count() > 0 else None)

    def push(self, value):
        self.V.append(value)
        self.bubble_up(self.count())
    
    def pop(self):
        if self.count() == 0: return None
        
        value = self.V[1]
        self.V[1] = self.V[-1]
        self.V.pop()
        self.bubble_down(1)
        return value
   
    def pop_all(self):
        while self.count() > 0:
            yield self.pop()
   
    def bubble_up(self, n):
        while n != 1 and self.less(n, n/2):
            self.swap(n, n/2)
            n /= 2
            
    def bubble_down(self, n):
        while self.less(n*2, n) or self.less(n*2+1, n):
            c = self.min(n*2, n*2+1)
            self.swap(n, c)
            n = c

    def less(self, a, b):
        if a>self.count(): return False
        if b>self.count(): return True
        return self.V[a]<self.V[b]
        
    def min(self, a, b):
        return (a if self.less(a,b) else b)
        
    def swap(self, a, b):
        self.V[a], self.V[b] = self.V[b], self.V[a]

heap = BinaryHeap()
heap.push(10)
heap.push(2)
heap.push(5)
heap.push(-100)
print heap.pop() #-100
print heap.pop() #2
print heap.pop() #5
print heap.pop() #10

print
print 'Heap sort'

V = [10, 2, 5, -100]
print V, '->', list(BinaryHeap(V).pop_all())


================================================
FILE: algorithms/data-structures/stack.py
================================================

"""
Stack
Autor:
    ?
Colaborador:
    Guido Luz Percú (guidopercu@gmail.com)
Tipo:
    data-structures
Descrição:
    Implementação da estrutura de dados Stack, uma coleção de elementos com duas
    operações principais: push e pop. Também conhecida por LIFO (last in, first
    out).
Complexidade:
    ?
Dificuldade:
    facil
Referências: (opcional)
    http://www.wikiwand.com/en/Stack_%28abstract_data_type%29
"""


class Stack:
    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def __str__(self):
        return "{}".format(self._stack)

    def top(self):
        return self._stack[-1]

    def push(self, value):
        self._stack.append(value)

    def pop(self):
        self._stack.pop()


if __name__ == "__main__":
    pilha = Stack()
    pilha.push(1)
    pilha.push(2)
    pilha.push(3)
    print(pilha)
    print(pilha.top())
    print("Tamanho da pilha: {}".format(len(pilha)))

    pilha.pop()
    print(pilha)
    print("Tamanho da pilha: {}".format(len(pilha)))
    print(pilha.top())


================================================
FILE: algorithms/date/leap-year.py
================================================
# -*- encoding: utf-8 -*-
"""
Bissexto
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz . at . gmail . com>
Tipo:
    date
Descrição:
    Calcula os próximos anos bissextos
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Ano_bissexto#Calend.C3.A1rio_Gregoriano

"""

from datetime import datetime

def anoBissexto(anos):
	anoAtual = datetime.now().year
	proximoAno = anoAtual + anos
	for ano in range(anoAtual,proximoAno):
		if ano % 4 == 0 and (ano % 100 or ano % 400 == 0):
			yield ano

for ano in anoBissexto(100): print ano


================================================
FILE: algorithms/economics/financiamento.py
================================================
# -*- encoding: utf-8 -*-

"""
Financiamento
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz@gmail.com>
Tipo:
    ?
Descrição:
	Calcula o valor das parcelas do financiamneto
	baseado no capital inicial e taxa de juros
	de acordo na função Price
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Tabela_price#C.C3.A1lculo
"""

def parcelas(investimento, juros, periodo):
	return (investimento*juros) / (1 - (1/(1+juros)**periodo))
	
print parcelas(1000, 0.03, 4)


================================================
FILE: algorithms/geography/haversine.py
================================================
# -*- encoding: utf-8 -*-
"""
Haversine
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz . at . gmail . com>
Tipo:
    geography
Descrição:
    Calcula a distancia mais curta
    entre dois pontos com latitude e longitude
    na superficie da Terra
    usando a formula de haversine
Complexidade:
    ?
Dificuldade:
    medio
Referências:
    http://en.wikipedia.org/wiki/Haversine_formula

"""
from __future__ import division
import math


def strTodegree(string):
    grau, minuto, segundo = [int(x) for x in string.split()]
    if(string.find("-") == -1):
        grau += (minuto/60) + (segundo/3600)
    else:
        grau -= (minuto/60) + (segundo/3600)
    return grau


def haversin(theta):
	return math.sin(theta/2)**2


def distancia(latitude1, longitude1, latitude2, longitude2):
	Radius = 6371 #Terra
	deltaLatitude = math.radians(latitude2 - latitude1)
	deltaLongitude = math.radians(longitude2 - longitude1)
	h = haversin(deltaLatitude) + math.cos(math.radians(latitude1))*math.cos(math.radians(latitude2))*haversin(deltaLongitude)
	return 2*Radius*math.asin(math.sqrt(h))

print distancia(strTodegree("53 08 50"),strTodegree("-01 50 58"),strTodegree("52 12 16"),strTodegree("00 08 26"))


================================================
FILE: algorithms/graphs/BellmanFord.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo de Bellman-Ford.

Autor:
	Richard Bellman & Lester R. Ford Jr. (1958)

Colaborador:
	Pedro Arthur Duarte (JEdi)
	pedroarthur.jedi@gmail.com

Tipo:
	graph
	shortest path on directed graphs with negative weighted edges

Descrição:
	O algoritmo de Bellman-Ford determina o caminho mais curto de origem única
	em grafos com arestas de pesos negativos. Para grafos sem arestas negativas,
	o algoritmo de Dijkstra apresenta melhor desempenho.

Complexidade:
	O(V*E), onde 'V' é a cardinalidade o conjunto de vértices e 'E' a
	cardinalidade do conjunto de arestas.

Dificuldade:
	media

Referências:
	http://en.wikipedia.org/wiki/Bellman-Ford_algorithm

Licença:
	GPLv3

"""

from sys import maxint

class NegativeWeightCycleError(Exception):
	pass


class Vertex:
	'''
	Abstração de vértice para a implementação através de lista de adjacência;
	estão inclusos atributos extras para a implementação do algoritmo
	'''
	def __init__(self, label, distance, predecessors=None):
		self.label = label

		self.distance = distance
		self.predescessor = None

	def __repr__(self):
		return str(self.label)

class Edge:
	'''
	Abstração de aresta para a implementação através de lista de adjacência
	'''
	def __init__(self, source, destination, weight):
		self.src = source
		self.dst = destination
		self.wht = weight

class Graph:
	'''
	Abstração de grafo para a implementação através de lista de adjacência.
	'''
	def __init__(self, graph=None):
		'''
		Caso seja passada uma matriz de adjacência, essa é transformada numa
		lista de adjacência.
		'''
		self.vertex = { }
		self.edges = [ ]

		if graph == None:
			return

		for i in xrange(0, len(graph)):
			for j in xrange(0, len(graph)):
				if graph[i][j] == None:
					continue

				self.addEdge(i, j, graph[i][j])

	def addEdge(self, source, destination, weight):
		if source not in self.vertex:
			self.vertex[source] = Vertex(source, maxint)

		if destination not in self.vertex:
			self.vertex[destination] = Vertex(destination, maxint)

		self.edges.append(
			Edge(self.vertex[source], self.vertex[destination], weight))

class BellmanFord:
	def __init__(self, g):
		self.graph = g

	def adjacencyMatrixShortestPath(self, source, destination):
		'''Implementação através de matriz de adjacência'''

		# Etapa de inicialização: todas as distâncias são definidas como
		# infinitas para que sejam então atualizadas durante a relaxação
		self.distances = [ maxint for s in self.graph ]
		self.distances[source] = 0

		# Arranjo auxiliar para que possamos reconstruir o menor caminho
		self.predecessors = [ 0 for s in self.graph ]

		# Para cada v em V:
		for i in xrange(0, len(self.graph)):
			# Para cada e em E
			#	Aqui, devido ao uso da matriz de adjacência, precisamos
			#	utilizar dois laços "para" (for) de forma que possamos
			#	percorrer todas as aresta
			for u in xrange(0, len(self.graph)):
				for v in xrange(0, len(self.graph)):
					if self.graph[u][v] == None:
						continue

					# Etapa de "relaxação" do grafo
					if self.distances[u] + self.graph[u][v] < self.distances[v]:
						self.distances[v] = self.distances[u] + self.graph[u][v]
						self.predecessors[v] = u

		# Verificação da existência de círculos negativos
		for u in xrange(0, len(self.graph)):
			for v in xrange(0, len(self.graph)):
				if self.graph[u][v] == None:
					continue

				if self.distances[u] + self.graph[u][v] < self.distances[v]:
					raise NegativeWeightCycleError

		# lista de saída; índice -1 indica o custo total do menor caminho
		output = [ self.distances[destination] ]

		# Reconstruindo o menor caminho através do predecessor do destino
		while True:
			output.insert(0, destination)

			if destination == source:
				break
			else:
				destination = self.predecessors[destination]

		# Crianças, não façam isso em casa.
		return output[:-1], output[-1]

	def adjacencytListShortestPath(self, source, destination):
		'''
		Implementação através de lista de adjacência;

		Funcionalmente, o mesmo código acima. Porém, bem mais limpo e menos
		devorador de memória. Adequado para matrizes esparsas.
		'''
		
		source, destination = (self.graph.vertex[source],
								self.graph.vertex[destination])

		# A etapa de inicialização está parcialmente implícita no construtor
		# da classe Vertex. Assim, precisamos apenas atualizar o valor de
		# distância do nó origem.
		source.distance = 0

		for _ in self.graph.vertex:
			for e in self.graph.edges:
				if e.src.distance + e.wht < e.dst.distance:
					e.dst.distance = e.src.distance + e.wht
					e.dst.predescessor = e.src

		for e in self.graph.edges:
			if e.src.distance + e.wht < e.dst.distance:
				raise NegativeWeightCycleError

		output = [ destination.distance ]

		while True:
			output.insert(0, destination)

			if destination == source:
				break
			else:
				destination = destination.predescessor

		return output[:-1], output[-1]

'''
Matriz de adjacência; None pode ser utilizado para representar a inexistência
de arestas entre dois vértices.
'''
graph = [
	[7, 6, 8, 3, 5, 3, 2, 7, 1, 2, ],
	[0, 5, 2, 9, 1, 6, 2, 9, 9, 7, ],
	[6, 8, 7, 5, 8, 5, 7, 9, 8, 2, ],
	[6, 9, 7, 5, 8, 9, 8, 6, 3, 4, ],
	[0, 4, 8, 1, 6, 5, 8, 0, 7, 9, ],
	[2, 3, 3, 9, 9, 0, 0, 3, 0, 4, ],
	[7, 8, 0, 7, 7, 2, 9, 6, 0, 8, ],
	[3, 3, 5, 4, 8, 8, 8, 4, 4, 0, ],
	[9, 7, 2, 5, 0, 5, 4, 9, 0, 3, ],
	[6, 1, 8, 6, 6, 6, 1, 6, 7, 9, ],
]

# Calculando o menor caminho através da matriz
print BellmanFord(graph).adjacencyMatrixShortestPath(0,9)

# Calculando o menor caminho através da lista
print BellmanFord(Graph(graph)).adjacencytListShortestPath(0,9)


================================================
FILE: algorithms/graphs/Dijkstra.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo de Dijkstra (com lista de adjascencias)
Autores: 
    Edsger Dijkstra
Colaborador:
 	Péricles Lopes Machado (pericles.raskolnikoff@gmail.com)
Tipo: 
    graphs
Descrição: 
    O Algoritmo de Dijsktra é um algoritmo em grafos clássico que determina a
    menor distância de um determinado vértice para todos os outros. Nessa implementação
	utiliza-se uma heap
Complexidade: 
    O(|E| log |V|)
Dificuldade: 
    medio
Referências:
    [1] http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
    [2] Cormem, Thomas H. Introduction to Algorithms, 3rd Edition. 
        ISBN 978-0-262-53305-8. Páginas 658-659.
"""

from heapq import *;

"""
Função para imprimir rota
"""

def imprime_rota(pi, u):
	if pi[u] != None:
		imprime_rota(pi, pi[u]);
	print " ", u;

"""
Lista de adjacência; Para cada nó 'u' é fornecida uma lista de pares (v, d), onde 'v' é um 
nó que está conectado a 'u' e 'd' é a distancia entre 'u' e 'v'
"""

G = [
	[(1, 2), (3, 4), (5, 3), (8, 9)], 
	[(2, 7), (4, 6), (7, 8)],
	[(4, 9), (7, 9)],
	[(1, 13), (4, 4), (6, 3), (2, 3)], 
	[(1, 23), (7, 4), (5, 3), (8, 1), (4, 9)], 
	[(3, 11), (4, 7), (8, 9)], 
	[(5, 2), (3, 5), (4, 3), (5, 9)], 
	[(1, 2), (7, 4), (5, 9), (6, 8)], 
	[(7, 2), (2, 3), (1, 1), (3, 1)], 
]; 


"""
Origem s e destino t
"""
s = 1;
t = 6;

N = len(G);

"""
Estimativa de distancia inicial
None representa o infinito e código pai usado para recuperar a rota
"""
D = [];
pi = [];

for i in range(0, N):
	D += [None];
	pi += [None];

"""
Priority queue utilizada para o acesso rápido a melhor estimativa
"""
Q = [];

D[s] = 0;
heappush(Q, (0, s));

"""
Enquanto a fila de prioridade não estiver vazia tente verificar se o topo
da fila é melhor opção de rota para se chegar nos adjascentes. Como o topo
já é o mínimo, então garante-se que D[u] já está minimizado no momento.
"""
while Q:
	u = heappop(Q)[1];
	for adj in G[u]:
		v = adj[0];
		duv = adj[1];
		if D[v] > D[u] + duv or D[v] == None:
			D[v] = D[u] + duv;
			pi[v] = u;
			heappush(Q, (D[v], v));

if D[t] != None:
	print "Distância(", s, ",", t, ") = ", D[t]; 
	print "Rota:";
	imprime_rota(pi, t);
else:
	print "Não há rota entre os nós ", s, " e ", t;




================================================
FILE: algorithms/graphs/EdmondsKarp.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo de Edmonds-Karp.

Autor:
  Jack Edmonds & Richard Karp (1972)

Colaborador:
  Pedro Arthur Duarte (JEdi)
  pedroarthur.jedi@gmail.com

Tipo:
  graph

Descrição:
  O Algoritmo de Edmonds-Karp é uma implementação do método de Ford-Fulkerson
  para o cálculo do fluxo máximo em uma rede de fluxos. Esse algoritmo é
  idêntico ao método de Ford-Fulkerson excetuando-se no critério que utiliza
  para a escolha do caminho aumentante: o caminho precisa ser o menor caminho
  que possibilita o aumento do fluxo.

Complexidade:
  O(V*E²),  onde 'V' é a cardinalidade o conjunto de vértices e 'E' a
            cardinalidade do conjunto de arestas.

Dificuldade:
  alta (?)

Referências:
  http://en.wikipedia.org/wiki/Edmonds

Licença:
  GPLv3

"""

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
from sys import stdin;

DIMACS = 0
WFLOW = 1
RAW = 2

IMPERATIVE = 0
FUNCTIONAL = 1

class EdmondsKarp:
  # Cria nova instância da classe.
  # Parâmetros:
  #   c: matriz de fluxos (f[i,j] = c[i][j])
  #   s: vértice do qual se origina o fluxo;
  #   t: vértice de destino do fluxo;
  def __init__(self, c, s, t):
    self.c = c
    self.s = s
    self.t = t

    # Matriz auxiliar dos fluxos
    self.f = [[0] * len(i) for i in c]

    #print c

  # Iterador para auxiliar na construção da resposta
  def __iter__(self):
    return self

  # Busca primeiro em largura:
  def next(self):
    q = [ self.s ]
    p = { self.s: [] }

    # Critério: capacidade(e) - fluxoatual(e) > 0

    # Implementação imperativa (aquela que se encontra geralmente nos livros)
    if self.approach == IMPERATIVE:
      for u in q:
        for v in xrange(len(self.c)):
          if self.c[u][v] - self.f[u][v] > 0 and v not in p:
            p[v] = p[u] + [(u,v)]
            if v == self.t:
              return p[v]
            q.append(v)

    # Implementação por meio de diretivas funcionais. Bonito, mas impraticável
    # para grandes instâncias desse problema.
    else:
      fcond = (lambda x: x[0][1] - x[1] > 0 and x[0][0] not in p)
      for u in q:
        for v in map(
                  lambda x: x[0][0],
                  filter(fcond, zip(enumerate(self.c[u]), self.f[u]))):
          p[v] = p[u] + [(u,v)]
          if v == self.t:
            return p[v]
          q.append(v)

    raise StopIteration

  # Esse algoritmo também é capaz de determinar o corte mínimo.
  # Esse método faz isso :-)
  def MinCutVertex(self):
    q = [ self.s ]
    o = [ ]

    for u in q:
      for v in xrange(len(self.c)):
        if self.c[u][v] - self.f[u][v] > 0 and v not in o:
          o.append(v)
          q.append(v)

    return o

  # Retorna a matriz de fluxos
  def FlowEdges(self, outtype=RAW):
    # Retorna a própria matriz de fluxos
    if outtype == RAW:
      return self

    # seleciona apenas os vértices que possuem algum fluxo
    if outtype == WFLOW:
      q = [ self.s ]
      p = []
      u = 0

      fcond =

      for u in q:
        f = map(
              lambda x: x[0][0],
              filter(
                   lambda x:x[1]>0 and (u,x[0][0],self.f[u][x[0][0]]) not in p,
                   zip(enumerate(self.c[u]), self.f[u])
              )
        )
        for v in f:
          p = p + [(u,v,self.f[u][v])]
          q.append(v)

      return p

    # retorna nada =p
    else:
      return [ ]

  # Implementação do algoritmo de Edmonds-Karp
  def MaxFlow(self, approach=IMPERATIVE):
    self.approach = approach

    # Enquanto houverem caminhos aumentantes,
    # selecione aquele de menor custo;
    for p in self:

      # Dentro desse caminho, encontre a aresta
      # que possuí menor capacidade de vazão:
      mf = min(map(lambda e: self.c[e[0]][e[1]] - self.f[e[0]][e[1]], p))

      # Ajuste os valores da matriz de fluxo de
      # acordo com o vazão da aresta encontrada
      # no passo anterior
      for u,v in p:
        self.f[u][v] += mf
        self.f[v][u] -= mf

    # Retorna o fluxo máximo
    return sum(self.f[self.s])



================================================
FILE: algorithms/graphs/FloydWarshall.py
================================================
 
# -*- coding: utf-8 -*-

"""
Algoritmo de Floyd-Warshall.

Autor:
	Robert W. Floyd & Stephen Warshall (1962)

Colaborador:
	Pedro Arthur Duarte (JEdi)
	pedroarthur.jedi@gmail.com

Tipo:
	graph
	all-pairs shortest path in weighted graphs
	dynamic programming

Descrição:
	O algoritmo de Floyd-Warshall computa os caminhos mais curtos entre todos os pares de um grafo valorado de pesos arbitrários.

	A formulação em programação dinâmica para esse problema consiste em
	determinar de forma bottom-up os menores caminhos para todos os vértices
	considerando que os caminhos intermediários consistem apenas de um
	subconjunto de vértices. Assim, $d_{ij}^{(k)}$ é menor caminho do vértice
	$i$ ao vértice $j$ tal que esse caminho consiste apenas de vértices
	intermediários em $k$. Assim, a seguinte formulação é empregada no
	algoritmo de Floyd-Warshall:

	$$ d_{ij}^{(k)} = min(d_{ij}^{(k)}, d_{ik}^{(k-1)} + d_{kj}^{(k-1)}) $$

	Essa formulação assuma que $d_{ij} = 0$ se $i=j$, e $d_{ij}=\infty$ se não
	há uma aresta entre os vértices $i$ e $j$.

Complexidade:
	Θ(V³),  onde 'V' é a cardinalidade o conjunto de vértices.

Dificuldade:
	média

Referências:
	Cormen; Leiserson; Rivest; Stein. Introduction to Algorithms (2 ed). ISBN: 978-0262033848.
	https://secure.wikimedia.org/wikipedia/en/wiki/Floyd–Warshall_algorithm

Licença:
  GPLv3

"""

from sys import maxint as Infinity

class NoSuchAPathError(Exception):
	pass

class FloydWarshall:
	def __init__(self, matrix):
		self.matrix = [ ]
		self.paths = [ ]

		for r in matrix:
			self.matrix.append([ ])
			self.paths.append([ ])

			for c in r:
				self.matrix[-1].append(c)
				self.paths[-1].append(None)

	def shortestPaths(self):
		for k in xrange(0, len(self.matrix)):
			for i in xrange(0, len(self.matrix)):
				for j in xrange(0, len(self.matrix)):
					if self.matrix[i][k] + self.matrix[k][j] < self.matrix[i][j]:
						self.matrix[i][j] = self.matrix[i][k] + self.matrix[k][j]
						self.paths[i][j] = k

		return self

	def getItermediate(self, source, destination):
		if self.matrix[source][destination] == Infinity:
			raise NoSuchAPathError

		intermediate = self.paths[source][destination]

		if intermediate is None:
			return [ ]

		return (self.getItermediate(source, intermediate)
					+ [ intermediate ]
						+ self.getItermediate(intermediate, destination))

	def getPath(self, source, destination):
		return ([ source ]
					+ self.getItermediate(source, destination)
						+ [ destination ])

graph = [
	[0, 6, 8, 3, 5, 3, 2, 7, 1, 2, ],
	[0, 0, 2, 9, 1, 6, 2, 9, 9, 7, ],
	[6, 8, 0, 5, 8, 5, 7, 9, 8, 2, ],
	[6, 9, 7, 0, 8, 9, 8, 6, 3, 4, ],
	[0, 4, 8, 1, 0, 5, 8, 0, 7, 9, ],
	[2, 3, 3, 9, 9, 0, 0, 3, 0, 4, ],
	[7, 8, 0, 7, 7, 2, 0, 6, 0, 8, ],
	[3, 3, 5, 4, 8, 8, 8, 0, 4, 0, ],
	[9, 7, 2, 5, 0, 5, 4, 9, 0, 3, ],
	[6, 1, 8, 6, 6, 6, 1, 6, 7, 0, ],
]

print FloydWarshall(graph).shortestPaths().getPath(1,9)


================================================
FILE: algorithms/math/algebra/bhaskara.py
================================================
# encoding: utf-8

"""
Bhaskara
Autor:
    Bhaskara Akaria [1]
Colaborador:
    Karlisson Bezerra
Tipo:
    math
Descrição:
    Calcula as raízes de uma equação de segundo grau
Complexidade:  
    O(1)
DIficuldade:
    facil
Referências:
    [1] http://pt.wikipedia.org/wiki/Bhaskara_Akaria
"""

import math

def bhaskara(a, b, c):
    delta = b ** 2 - 4 * a * c
    if delta < 0:
        return None
    else:
        raizes = []
        m1 = math.sqrt(delta)
        r1 =(-b + m1) / (2 * a)
        raizes.append(r1)
        r2 =(-b - m1) / (2 * a)
        raizes.append(r2)
        return raizes

print(bhaskara(1, -1, -2))


================================================
FILE: algorithms/math/algebra/dda.py
================================================
'''
DDA (Digital Differential Analyzer)
Autor:
    ?
Colaborador:
    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hotmail.com)
Tipo:
	math
Descrio:
    DDA  um algoritmo de interpolao linear entre dois pontos, inicial e final.
	Ele  muito usado na rea de Computao Grfica para rasterizar linhas e polgonos.
Complexidade:  
    O(n)
Dificuldade:
    facil
Referncias:
    http://www.dca.fee.unicamp.br/courses/IA725/1s2006/notes/n4.pdf
	http://en.wikipedia.org/wiki/Digital_Differential_Analyzer_(graphics_algorithm)
'''

import math

def DDA(x1, y1, x2, y2):
	
	points = [] #Guardar os pontos criados na forma (x, y)
	
	if (math.fabs(x2 - x1) >= math.fabs(y2 - y1)):
		
		len = math.fabs(x2 - x1)
	else:
		
		len = math.fabs(y2 - y1)
	
	deltax = (x2 - x1) / len
	deltay = (y2 - y1) / len
	x = x1 + math.copysign(0.5, deltax)
	y = y1 + math.copysign(0.5, deltay)
	
	for i in range(int(len)) :
	
		points.append((math.floor(x), math.floor(y)))
		x += deltax
		y += deltay
	
	points.append((math.floor(x), math.floor(y)))
	
	return points

if __name__ == "__main__" :
	
	print DDA(-1, -1, 12, 9)

================================================
FILE: algorithms/math/algebra/media-num.py
================================================
# -*- encoding: utf-8 -*-

"""
Media Numerica
Autor:
    ?
Colaborador:
	Bruno Lara Tavares <bruno.exz@gmail.com>
    Guilherme Carlos (@guiessence)
Tipo:
    math
Descrição:
    Calcula a média de numeros inseridos pelo usuário
Complexidade:  
    0(1)
Dificuldade:
    facil
"""

from __future__ import division

def media(*args):
	sum = 0
	for i in args:
		sum += i
	return sum / len(args)

#Adicione a quantidade de numeros que for preciso
print media(2,3,4,10)


================================================
FILE: algorithms/math/algebra/media.py
================================================
# encoding: utf-8

"""
Cálculo da média ponderada
Autor:
    ?
Colaborador:
    Karlisson Bezerra
Tipo:
    math
Descrição:
    Calcula a média ponderada - é um algoritmo
    comum em qualquer curso de introdução à programação,
    que pode variar de acordo com os pesos.
Complexidade:  
    O(1)
Dificuldade:
    facil
"""

import math

def media(n1, n2, n3):
    p1, p2, p3 = 4, 5, 6
    return (n1 * p1 + n2 * p2 + n3 * p3) / (p1 + p2 + p3)

print media(7.0, 8.0, 10.0)


================================================
FILE: algorithms/math/algebra/permutation.py
================================================
# encoding: utf-8

"""
Permutation
Autor:
    Fabian Stedma
Colaborador:
    Bruno Gabriel dos Santos (bruno.gsantos89@gmail.com)
Tipo:
    math
Descrição:
    Calcula o número de combinações distintas que são possíveis de serem formadas por um array numérico.
Complexidade:  
    O(n!)
Dificuldade:
    medio
Referências: 
    [1] https://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
"""

def permutation(input_data, temp_data, position):
	if position == len(input_data):
		print ''.join(str(temp_data))
	else:
		for i in xrange(len(input_data)):
			is_same = False
			for j in xrange(position):
				if temp_data[j] == input_data[i]:
					is_same = True
			if not is_same:
				if len(temp_data) <= i:
					temp_data.append(input_data[i])
				else:
					temp_data[position] = input_data[i]
				permutation(input_data, temp_data, position+1)

permutation([1,2,3], [], 0)



================================================
FILE: algorithms/math/bisection-method.py
================================================
# encoding: utf-8
"""
Método da Bisseção
Autor:
    ?
Colaborador:
    Lucas Andrade (lucasfael@gmail.com)
Tipo:
    math
Descrição:
    Calcula a raiz aproximada de uma equação polinomial qualquer
    dentro de um intervalo até uma precisão desejada.
Complexidade:  
    O(log n)
Dificuldade:
    facil
Referências:
    http://www.im.ufrj.br/dmm/projeto/projetoc/precalculo/sala/conteudo/capitulos/cap114.html
    
"""

import math

def root(function, x0, x1, precision=0.0001):
    x0 *= 1.0
    x1 *= 1.0
    while (math.fabs(x0-x1) > precision):
        fx0 = function(x0)
        fx1 = function(x1)
        if (fx0 * fx1) > 0:
            return
        if fx0 == 0:
            return x0
        if fx1 == 0:
            return x1
        x2 = (x0 + x1) / 2
        fx2 = function(x2)
        if (fx0 * fx2) < 0:
            x1 = x2
        else:
            x0 = x2
    return x0

def funcao(x):
    return math.pow(x, 3)-(9 * x) + 3

x = root (funcao, 0, 1)
print x


================================================
FILE: algorithms/math/linear-algebra/matrix-transpose.py
================================================
# coding: utf-8
'''
Transposição de matrizes
Autor: 
    ?
Colaborador:
    Dayvid Victor (victor.dvro@gmail.com)
Tipo:
    math
Descrição: 
    Calcula a matriz tranposta de uma matriz qualquer, ou seja, a matriz
    resultante da troca das linhas pelas colunas.
Complexidade de tempo: 
    O(m*n)
Dificuldade: 
    facil
Referências:
    http://en.wikipedia.org/wiki/Transpose
'''

def get_transpose(matrix):
	return [[c for c in [l[i] for l in matrix]] for i in range(len(matrix[0]))]

if __name__ == '__main__':
	matrix = [[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
	print matrix
	print get_transpose(matrix)
	


================================================
FILE: algorithms/math/luhn.py
================================================
# coding: utf-8
'''
Algorítimo de Luhn
Autor:
    Hans Peter Luhn
Colaborador:
    Alberto Chvaicer <achvaicer@gmail.com>
Tipo:
    math
Descrição:
    Algoritimo utilizado para calular o dígito verificador baseado no módulo de 10. Utilizado por cartões de crédito e número IMEI.
Complexidade de tempo:
    O(n)
Dificuldade:
    media
Referências:
    https://en.wikipedia.org/wiki/Luhn_algorithm
'''
def luhn_checksum(card_number):
    def digits_of(n):
        return [int(d) for d in str(n)]
    digits = digits_of(card_number)
    odd_digits = digits[-1::-2]
    even_digits = digits[-2::-2]
    checksum = 0
    checksum += sum(odd_digits)
    for d in even_digits:
        checksum += sum(digits_of(d*2))
    return checksum % 10

def calculate_luhn(partial_card_number):
    check_digit = luhn_checksum(int(partial_card_number) * 10)
    return check_digit if check_digit == 0 else 10 - check_digit

print 'the check digit of 7992739871 is %d' % (calculate_luhn(7992739871)) # should be 3


================================================
FILE: algorithms/math/number-theory/bozofactoring.py
================================================
# encoding: utf-8

"""
Bozo factoring
Autor:
    Ricardo Bittencourt
Colaborador:
    Ricardo Bittencourt (bluepenguin@gmail.com)
Tipo:
    number-theory
Descrição:
    Calcula os fatores primos de um numero usando o pior algoritmo conhecido.
Complexidade:  
    O(n^n)
Dificuldade:
    medio
Referências:
    http://blog.ricbit.com/2010/07/o-algoritmo-mais-lento-do-oeste.html
Licenca:
    GPL
"""

import itertools

def factor(n):
  solutions = []
  for f in itertools.product(range(1,1+n),repeat=n):
    if reduce(lambda x,y: x*y, f) == n:
      solutions.append(filter(lambda x:x>1, list(f)))
  solutions.sort(key=len, reverse=True)
  return solutions[0]

print factor(6)


================================================
FILE: algorithms/math/number-theory/divisors.py
================================================
# * encoding: UTF-8 *

"""
Divisors
Autor:
    ?
Colaborador:
    ?
Descricao:
   Mostra os divisores de um número
Complexidade:
    O(n)
Dificuldade:
    facil
"""

n = int(raw_input("Digite um numero: "))
for i in range(1, n+1):
    if not n % i:
        print i,


================================================
FILE: algorithms/math/number-theory/eratosthenes.py
================================================
# -*- encoding: utf-8 -*-
"""
Crivo de Eratóstenes
Autor:
    Eratóstenes de Cirene
Colaborador:
    Juan Lopes (me@juanlopes.net)
Tipo:
    Exemplos: math
Descrição:
    Gera array de primalidade de inteiros através de algoritmo com baixa 
    complexidade.
Complexidade:  
    O(n loglogn)
Dificuldade:
    Médio
Referências: (opcional)
    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""

from math import sqrt

def sieve(n):
    P = [True]*n
    P[0] = False
    P[1] = False
    
    for i in xrange(2, int(sqrt(n))):
        if P[i]:
            for j in xrange(i**2, n, i):
                P[j] = False
    return P

def primes_up_to(n):
    for i, p in enumerate(sieve(n)):
        if p: 
            yield i
    
print 'Primos ate 20:'
for i in primes_up_to(20):
    print i



================================================
FILE: algorithms/math/number-theory/euclid.py
================================================
# encoding: utf-8

"""
Algoritmo de Euclides
Autor:
    Euclides de Alexandria
Colaborador:
    Liquen 
Tipo:
    number-theory
Descrição:
    Algoritmo de Euclides em sua forma moderna. Computa o máximo
    divisor comum (MDC) entre dois números inteiros. Parte do princípio de
    que o MDC não muda se o menor número for subtraído do maior. [1] [2]
Complexidade:
    O(n^2), onde n é o número de dígitos da entrada. [3]
    O número de passos é no máximo
        log(max(a, b) * sqrt(5)) / log(phi),
    onde phi = 1.618... é a proporção áurea. [3]
Dificuldade:
    facil
Referências:
    [1] http://en.wikipedia.org/wiki/Euclidean_algorithm
    [2] http://pt.wikipedia.org/wiki/Algoritmo_de_Euclides
    [3] http://mathworld.wolfram.com/EuclideanAlgorithm.html
"""

def euclides(a, b):
    while b != 0:
        a, b = b, a % b
    return a

print(euclides(1071, 462))


================================================
FILE: algorithms/math/number-theory/fatorial.py
================================================
# encoding: utf-8

"""
Cálculo de fatorial
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz@gmail.com>
Tipo:
    math
Descrição:
    Calcula o fatorial de um número
Complexidade:  
    ?
Dificuldade:
    facil
"""


def fatorial(b):
	return 1 if b <= 1 else b*fatorial(b-1)

print fatorial(6)


================================================
FILE: algorithms/math/number-theory/fibonacci-matrix-form.py
================================================
# coding: utf-8
"""
 * Sequência de Fibonacci
 *
 * Autor:
 *   Antonio Ribeiro <alvesjunior.antonio@gmail.com>
 * Tipo:
 *   math
 * Descrição:
 *   Na matemática, os Números de Fibonacci são uma sequência definida como recursiva.
 *   O algoritmo recursivo que define a série aplica-se, na prática, conforme a regra sugere: 
 *   começa-se a série com 0 e 1; a seguir, obtém-se o próximo número de Fibonacci somando-se 
 *   os dois anteriores e, assim, sucessiva e infinitamente.
 *
 *   Esta implementação baseia-se na propriedade de dividir-para-conquistar aplicada à
 *   potenciação de matrizes para acelerar o cálculo do número de fibonacci, reduzindo
 *   a complexidade do algoritmo para O(lg n)
 * Complexidade:
 *   O(lg n)
 * Dificuldade:
 *   Médio
 * Referências:
 *   http://assemblando.wordpress.com/2011/05/14/pela-uniao-dos-seus-poderes/
 *
"""

matriz_semente = [[1,1],[1,0]]

def pow_matriz(b,n):
    """Realiza a potenciação da matriz b pelo expoente n usando dividir-para-conquistar"""
    
    if n==1:
        return b

    if n%2:
        h = pow_matriz(b,(n-1)/2)
        return multi_matriz(multi_matriz(h,h),b)

    else:
        h = pow_matriz(b,n/2)
        return multi_matriz(h,h)


def multi_matriz(ma,mb):
    "Realiza a multiplicação de duas matrizes 2x2"

    (a,b),(c,d) = ma
    (e,f),(g,h) = mb
    return [[a*e+b*g,a*f+b*h],[c*e+d*g,c*f+d*h]]


def fibo(n):
    "Realiza (matriz_semente)^n e retorna o elemento da linha zero, coluna um"

    if n==0 or n==1:
        return n

    return pow_matriz(matriz_semente, n)[0][1]


if __name__=='__main__':
    for i in range(100):
        print fibo(i)


================================================
FILE: algorithms/math/number-theory/fibonacci.py
================================================
# -*- encoding: utf-8 -*-
"""
 * Sequência de Fibonacci
 *
 * Autor:
 *   Felipe Djinn <felipe@felipedjinn.com.br>
 * Colaborador:
 *   Bruno Lara Tavares <bruno.exz@gmail.com>
 *   Dilan Nery <dnerylopes@gmail.com>
 * Tipo:
 *   math
 * Descrição:
 *   Na matemática, os Números de Fibonacci são uma sequência definida como recursiva.
 *   O algoritmo recursivo que define a série aplica-se, na prática, conforme a regra sugere: 
 *   começa-se a série com 0 e 1; a seguir, obtém-se o próximo número de Fibonacci somando-se 
 *   os dois anteriores e, assim, sucessiva e infinitamente.
 * Complexidade:
 *   O(n)
 * Referências:
 *   http://pt.wikipedia.org/wiki/N%C3%BAmero_de_Fibonacci
 *
"""
def fibonacci(nesimo):
    c, n1, n2 = 0, 0, 1
    while c < nesimo:
        n1, n2 = n2, n1 + n2
        c += 1
    return n2

for nesimo in range(100):
	print fibonacci(nesimo)


================================================
FILE: algorithms/math/number-theory/miller-rabin.py
================================================
# -*- encoding: utf-8 -*-
"""
Teste de primalidade de Miller-Rabin
Autor:
    Gary L Miller e Michael O. Rabin
Colaborador:
    Juan Lopes (me@juanlopes.net)
Tipo:
    math
Descrição:
    Teste probabilistico de primalidade. Prova-se que para valores até 
    4.759.123.141, basta testar com as 'testemunhas' 2, 7 e 61. Este teste é 
    muito mais rápido do que testar através de 'trial division', principalmente 
    para números grandes.
Complexidade:  
    ?
Dificuldade:
    difícil
Referências: (opcional)
    http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""

def witness(a, n):
   u,t= (n/2, 1)
   while(u%2==0): 
      u,t = (u/2, t+1)
      
   prev = pow(a,u,n);
   
   for i in xrange(t):
      curr=(prev*prev)%n
      if curr==1 and prev!=1 and prev!=n-1: return True
      prev=curr
      
   return curr != 1
 
def is_prime(n):
   if n in (0, 1): return False
   if n in (2, 7, 61): return True
   if witness(2,n): return False
   if witness(7,n): return False
   if witness(61,n): return False
   return True
    
print 'Primos ate 20:'
for i in xrange(1, 20):
    if is_prime(i):
        print i

print '2 147 483 647?', is_prime(2147483647)
print '2 147 483 648?', is_prime(2147483648)
        


================================================
FILE: algorithms/math/number-theory/newton_raphson_sqrt.py
================================================
# -*- encoding: utf-8 -*-
"""
Cálculo da raíz quadrada através do método de Newton-Raphson
Autor:
     Isaac Newton e Joseph Raphson
Colaborador:
    Alysson Oliveira (lssn.oliveira@gmail.com)
Tipo:
    math
Descrição:
    Método interativo para estimar as raízes de funções e pode ser aplicado
    a para o cálculo de rais quadrada.
Complexidade:
    ?
Dificuldade:
    fácil
Referências: (opcional)
    https://pt.wikipedia.org/wiki/M%C3%A9todo_de_Newton-Raphson
    https://courses.csail.mit.edu/6.006/fall11/rec/rec12_newton.pdf
    http://www.iaps.org.in/journal/index.php/journaliaps/article/view/161/146
    Guttag, John V. Introduction to Computation and Programming Using \
    Python. MIT Press. 2013. ISBN 978-0-262-52500-8
"""


def newton_raphson_sqrt(n, precisao=0.001, debug=False):
    """
    n: Valor que se deseja obter a raíz
    precisao: Valor de precisão (ex.: 0.01)
    debug: Quando True mostra os chutes até que a precisão seja satisfeita
    """
    chute = 0.5 * n
    while abs(chute * chute - n) >= precisao:
        if debug:
            print('    Chute:', chute)
        chute = chute - (((chute**2) - n) / (2 * chute))
    return chute


# Testando a função
for i in 49, 64:
    print('Calculando raíz de {}'.format(i))
    print('Resultado: {}'.format(newton_raphson_sqrt(i)))
    print(35 * '=')


for i in 81, 100:
    print('Calculando raíz de {}'.format(i))
    print('Resultado: {}'.format(newton_raphson_sqrt(i, 0.01, True)))
    print(35 * '=')


================================================
FILE: algorithms/math/number-theory/perfectnumber.py
================================================
# encoding: utf-8
""" 
Números perfeitos
Autor: 
      ?
Colaborador:
      Anna Cruz (anna.cruz@gmail.com)
Tipo:
    math, number-theory
Descrição:
    Esse algoritmo serve para verificar se um número é perfeito ou não. Números perfeitos são aqueles cuja soma dos divisores (exceto ele mesmo) é igual ao próprio número, como por exemplo 6, cujos divisores são 1, 2 e 3 e 1+2+3 = 6
Complexidade:
      ?
Dificuldade:
      fácil
Referências:
      http://en.wikipedia.org/wiki/Perfect_numbers
"""

def calc_perf(number):
  counter = 1
  divisors = []
  sumarize = 0
  while counter <= number/2:
    if number%counter == 0:
      divisors.append(counter)
    counter += 1
  for divisor in divisors:
    temp = divisor
    sumarize += divisor
  if sumarize == number:
    print "This is a perfect number"
  else:
    print "This is not a perfect number try again"

calc_perf(8128)


================================================
FILE: algorithms/math/number-theory/pow.py
================================================
# coding: utf-8
'''
Exponenciação
Autor: 
    	?
Colaborador:
    	Dayvid Victor (victor.dvro@gmail.com)
Tipo:
    	math
Descrição: 
	calcula exponenciação
Complexidade de tempo: 
    	O(log n)
Dificuldade: 
    	fácil
Referências:
	?
'''
def pow(x, n):
	if n < 0:
		return float(1) / float(pow(x, -n))
	p = (pow(x, n/2) if n != 0 else 1)
	return (p * p if n % 2 == 0 else p * p * x)

print [pow(2,n) for n in range(11)]
print [pow(2,n) for n in range(-11,0)]





================================================
FILE: algorithms/math/number-theory/powmod.py
================================================
# coding: utf-8
'''
Exponenciação Modular
Autor: 
    ?
Colaborador:
    Juan Lopes <me@juanlopes.net>
Tipo:
    math
Descrição: 
    Calcula exponenciação modular de inteiros em tempo logaritmico.
        
    Baseia-se no fato de que:
    (a*b)%n == ((a%n) * (b%n)) % n
Complexidade de tempo: 
    O(log n)
Dificuldade: 
    fácil
Referências:
    ?
'''
def pow(x, e, m):
    if e==0: return 1
    p = pow(x,e/2,m)%m
    k = (1 if e%2==0 else x)
    return (p*p*k)%m

for i in range(20):
    print '3 ^ %d mod 1000 = %d (%d)' % (i, pow(3, i, 1000), 3**i)





================================================
FILE: algorithms/math/number-theory/stirling.py
================================================
# -*- encoding: utf-8 -*-
"""
 Fórmula de Stirling

 Autor:
   Pedro Menezes <eu@pedromenezes.com>
   DiogoK <diogo@diogok.net>
 Tipo:
   math
 Descrição:
   A Fórmula de Stirling estabelece uma aproximação assintótica para o fatorial de um número.
 Referências:
   http://pt.wikipedia.org/wiki/F%C3%B3rmula_de_Stirling
"""

from math import sqrt, pi, e, pow

def stirling(n):
    return sqrt(2*pi*n) * pow(n/e, n)

if __name__ == '__main__':
    for n in xrange(1, 10):
        print("fat %d ~ %f" %(n, stirling(n)))

================================================
FILE: algorithms/misc/helloworld.py
================================================
"""
Helloworld
Autor:
    ?
Colaborador:
    Karlisson - contato@nerdson.com
Tipo:
    misc
Descrição:
    Imprime a string Hello world
Complexidade:  
    O(1)
Dificuldade:
    facil
"""

print "Hello world"


================================================
FILE: algorithms/optimization/inteval_scheduling.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo guloso de agendamento de intervalos

Autor:

Colaborador:
	Pedro Arthur Duarte (JEdi)
	pedroarthur.jedi@gmail.com

Tipo:
	Interval Scheduling
	Greed Algorithms
	Optimization

Descrição:
	Dado um conjunto de tarefas expressos como t = (s,e), onde 's' especifica
	o inicio da tarefa e 'e' o seu fim, determinar o subconjunto máximo de
	tarefas que não se sobrepõem.

	Uma das maneiras de determinar esse subconjunto consiste em selecionar
	gulosamente as tarefas com base no seu horário de término: as tarefas com
	término mais cedo que não se sobrepõem são selecionadas para formar o
	subconjunto de saída.

Complexidade:
	O(n), para um conjunto de tarefas ordenadas;

	O(n) + O(g(n)), para um conjunto de tarefas não ordenadas, onde 'g' é
                    uma função de ordenação.

Dificuldade:
	Fácil

Referências:
	Kleinberg, Jon; Tardos, Eva (2006). Algorithm Design.
	ISBN 0-321-29535-8

Licença:
	GPLv3

"""

def intervalScheduling(tasks):
	# Cópia a lista de tarefas e a ordena. O método "sort" das listas Python
	# é local. Portanto, caso seja necessário a lista original, não devemos
	# chamá-lo sem antes cloná-la.
	tasks = tasks[:]
	tasks.sort()

	# A tarefa com termino mais cedo sempre é a primeira do subconjunto
	# de saída
	scheduling = [ tasks[0] ]

	# Agora, para todos os outros elementos da lista ordenada de tarefas, nós
	# verificamos se esse elemento é compatível com as tarefas já presentes
	# no subconjunto de saída. Para uma lista ordenada, essa operação é O(1)
	# pois necessita apenas acessar a última tarefa inserida.
	for t in tasks[1:]:
		# Se o momento de inicio da tarefa é maior ou igual ao fim da última
		# tarefa do subconjunto de saída, ela é compatível.
		if t.start >= scheduling[-1].end:
			# E, logo, nós a inserimos no subconjunto de saída
			scheduling.append(t)

	# Por último, retornamos a lista
	return scheduling

# Conjunto de tarefas de exemplo
#  --- ---- --------
# ---- --- - --- ----
#  ----  -- -- --- --
#   ---- --- ---- ---

class Task:
	'''
	Abstração das tarefas
	'''
	start = 0
	end = 0

	def __init__(self, start, end):
		self.start = start
		self.end = end

	def __repr__(self):
		return '''<Task %s:%s>''' % (self.start, self.end)

	def __cmp__(self, o):
		if self.end < o.end:
			return -1

		if self.end == o.end:
			if self.start < o.start:
				return -1
			elif self.start > o. start:
				return 0
			else:
				return 1

		return 1

# Em formato de lista
tasks = [ Task(40, 70), Task(80, 120), Task(130, 210),
 Task(30, 70), Task(80, 110), Task(120, 130), Task(140, 170), Task(180, 220),
 Task(40, 80), Task(100, 120), Task(130, 150), Task(160, 190), Task(200, 220),
 Task(50, 90), Task(100, 130), Task(140, 180), Task(190, 220) ]

print intervalScheduling(tasks)


================================================
FILE: algorithms/optimization/knapsack.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo da Mochila

Autor:

Colaborador:
	Pedro Arthur Duarte (JEdi)
	pedroarthur.jedi@gmail.com

Tipo:
	0-1 Knapsack Problem
	Unbounded Knapsack
	Dynamic Programming

Descrição:
 	Dado uma conjunto de itens $I$ onde cada item $i$ possui um peso $p_i$ e um
	benefício $b_i$ associado, e uma mochila de carga máxima $m$, maximizar o
	benefício provido por uma combinação de itens respeitando a carga máxima
	suportda pela mochila. Em outras, palavras,
	satisfazer ao seguinte problema de otimização:
	%
	\begin{itemize}
		\item[] Maximizar $$\sum_{i=1}^{n} b_i x_i$$
		\item[] com a restrição $$\sum_{i=1}^{n} p_i x_i \le m$$
	\end{itemize}
	%
	onde $x_i$ é no número de repetiçoes do item $i$. A versão mais simples do
	problema, com cada item repetindo-se no máximo uma vez, ou $x_i \le 1$, é
	conhecida como 0-1 Knapsack. Instâncias sem essa limitação são conhecidas
	como Unbounded Knapsack.

    % OBS: a descrição acima é melhor visualizada após processada pelo LaTeX.
    % Visite http://scribtex.com/ para um compilador on-line

Complexidade:
	O(nm),	pseudo-polinomial no tempo, onde 'n' é cardinalidade do conjunto de
			item e 'm' é a carga máxima da mochila.

	O(nm),	pseudo-polinomial no espaço para o 0-1 Knapsack
	 O(m),	pseudo-polinomial no espaço para o Unbounded Knapsack

Dificuldade:
	Média

Referências:
	Robert Sdgewick. Algorithms in C. ISBN 0-201-51425-7
	https://secure.wikimedia.org/wikipedia/en/wiki/Knapsack_problem

Licença:
	GPLv3

"""

class Item:
	def __init__(self, value, weight, label=None):
		self.value = value
		self.weight = weight

		if label == None:
			self.label = str((self.value, self.weight))
		else:
			self.label = label

	def __repr__(self):
		return '<Item ' + self.label + '>'

class Knapsack:
	def __init__(self, maxWeight, items=None):
		self.maxWeight = maxWeight
		self.items = items

	def zeroOne(self, items=None):
		'''
		Essa instância do problema da mochila possuí subestrutura ótima. Logo,
		é passível de resolução através de programação dinâmica. A seguinte
		formulação nos permite resolver esse problema numa abordagem bottom-up:

		% obs: LaTex code
		\[
			M[i,j] = \left\{
				\begin{array}{l l}
					M[i-1,j] & \text{se } p_i < j \\
					max(M[i-1,j], M[i,j-p_i] + b_i) & \text{se } p_i \ge j\\
				\end{array}
			\right.
		\]
		%
		Onde $M$ é uma matriz $n \times m$, $n$ é cardinalidade do conjunto
		de itens e $m$ a capacidade máxima da mochila.
		'''
		if not items:
			items = self.items

		M = [[ 0 ] * (self.maxWeight+1)]

		for i,item in enumerate(items, start=1):
			M.append([ 0 ] * (self.maxWeight+1))

			for w in xrange(1, self.maxWeight+1):
				if item.weight <= w:
					if M[i-1][w] > M[i-1][w-item.weight] + item.value:
						M[i][w] = M[i-1][w]
					else:
						M[i][w] = M[i-1][w-item.weight] + item.value
				else:
					M[i][w] = M[i-1][w]

		'''
		$M[n,m]$ nos informa o máximo benefício obtido. Porém, para recuperar
		a lista de itens escolhidos, Precisamos analisar a matriz $M$ mais a
		fundo.

		Caso o benefício da mochila com configuração $M[i,m]$ seja diferente do
		benefício da mochila com configuração $M[i-1,m]$, o item $i$ está entre
		os itens escolhidos. Assim, devemos continuar nossa busca na posição
		$M[i-1,m-p_i]$. Caso contrário, o item $i$ não está em nossa mochila e
		devemos continuar a busca na posição $M[i-1,m]$.

		O código abaixo o descrito acima.
		'''
		i,m = len(items), self.maxWeight
		output = [ ]

		while m > 0:
			if M[i][m] != M[i-1][m]:
				output.append(items[i-1])
				m = m - items[i-1].weight

			i = i - 1

		return M[-1][-1], output

	def unbounded(self, items=None):
		'''
		Essa instância do problema também possuí subestrutura ótima. Logo,
		também é passível de resolução através de programação dinâmica. A
		seguinte formulação nos permite resolver esse problema numa abordagem
		bottom-up:

		% obs: LaTex code
		$$ \displaystyle
		M[j] = max(M[j-1], ~\max_{\forall i \in I | p_i < j}(b_i + M[j-p_i]))
		$$
		%
		Onde $M$ é uma arranjo de cardinalidade $m$ e $m$ é a capacidade
		máxima da mochila.
		'''
		if not items:
			items = self.items

		M = [0] * (self.maxWeight+1)
		# Para que possamos recupera a lista de itens escolhidos, precisamos
		# de um arranjo auxiliar para armazenar a melhor escolha para a mochila
		# de tamanho 'j'.
		c = [None] * (self.maxWeight+1)

		for i,item in enumerate(items, start=1):
			for j in xrange(1, self.maxWeight+1):
				if item.weight <= j:
					if M[j] < M[j-item.weight] + item.value:
						M[j] = M[j-item.weight] + item.value
						c[j] = item

		'''
		Conceitualmente, $c[m]$ sempre está na mochila. Agora, para recuperar o
		restante dos itens, pasta decrementar m pelo peso do do item na posição
		em questão ($m = m - p_{c[m]}$)
		'''
		m = self.maxWeight
		output = [ ]

		while m > 0:
			output.append(c[m])
			m = m - c[m].weight

		return M[-1], output

items = [
	Item(15,2), Item(5,1), Item(20,3), Item(60,2)
]

k = Knapsack(6, items)

print k.zeroOne()
print k.unbounded()

================================================
FILE: algorithms/pattern-matching/AhoCorasick.py
================================================
# -*- coding: utf-8 -*-

"""
Algoritmo de Aho-Corasick.

Autor:
	Alfred Aho and Margaret Corasick (1975)

Colaborador:
	Pedro Arthur Duarte (JEdi)
	pedroarthur.jedi@gmail.com

Tipo:
	multi pattern string matching
	finite automate-based

Descrição:
	Dado um conjunto de padrões, esse algoritmo constrói uma máquina de estados
	finitos de forma que seja possível buscá-los no texto de entrada em tempo
	linearmente proporcional ao tamanho dessa última. Para isso, o algoritmo de
	Aho-Corasick utiliza uma estrutura de dados semelhante as Tries, porém com
	nós adicionais que evitam a necessidade de backtracking. Esse nós
	adicionais representam o maior prefixo comum presente entre os padrões.

Complexidade:
	O(⅀m) de pré-processamento, onde "m" é o tamanho do padrão
	O(n)  de busca, onde "n" é o tamanho do texto de entrada

Dificuldade:
  média (?)

Referências:
  https://en.wikipedia.org/wiki/Aho-Corasick_algorithm

Licença:
  GPLv3

"""

class AhoCoraski(dict):
	failTransition = None
	isTerminal = False

	def __init__(self, patternList=None, thenBuild=False):
		if patternList is not None:
			self.add(patternList)

		if thenBuild is True:
			self.build()

	def add(self, pattern):
		if isinstance(pattern, list):
			for w in pattern:
				self.add(w)

			return self

		currentState = self

		for c in pattern:
			if c not in currentState:
				currentState[c] = AhoCoraski()

			currentState = currentState[c]

		currentState.isTerminal = pattern

		return self

	def build(self):
		queue = [ self ]

		while len(queue) > 0:
			current = queue.pop(0)

			for transition, next in current.iteritems():
				state = current.failTransition

				while state is not None and transition not in state:
					state = state.failTransition

				if state is not None:
					next.failTransition = state[transition]
				else:
					next.failTransition = self

				queue.append(next)

		return self

	def match(self, subject):
		output = [ ]
		current = self

		if isinstance(subject, list):
			for s in subject:
				output += self.match(s)

			return output

		for c in subject:
			if c in current:
				current = current[c]
			else:
				current = current.failTransition

				while current is not None and c not in current:
					current = current.failTransition

				if current is not None:
					current = current[c]
				else:
					current = self

			if current.isTerminal is not False:
				output.append(current.isTerminal)

		return output

patternList = [ 'he', 'she', 'his', 'her', 'show', 'shall', 'hall', ]

print AhoCoraski(patternList, True).match("This phrase shall match")


================================================
FILE: algorithms/pattern-matching/hamming.py
================================================
# coding: utf-8
"""
Hamming Distance
Autor:
    Richard Hamming
Colaborador:
    Guido Luz Percú (guidopercu@gmail.com)
Tipo:
   edit-distance
Descrição:
    A distância de Hamming, é o número de posições em duas strings de mesmo
    tamanho onde os símbolos correspondentes são diferentes. Mede o mínimo
    número de substituições (ou o número de erros) necessárias para transformar
    uma string em outra.
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    https://pt.wikipedia.org/wiki/Dist%C3%A2ncia_de_Hamming
    http://www.caip.rutgers.edu/~bushnell/dsdwebsite/hamming.pdf
Licenca:
    MIT
"""


def hamming_distance(s1, s2):
    assert len(s1) == len(s2)
    return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))


print(hamming_distance('ACGT', 'AGCT'))


================================================
FILE: algorithms/pattern-matching/kmp.py
================================================
# -*- encoding: utf-8 -*-
"""
KMP (Knuth-Morris-Pratt) algorithm
Autor:
    Donald Knuth, Vaughan Pratt and James H. Morris
Colaborador:
    Juan Lopes (me@juanlopes.net)
Tipo:
    pattern-matching
Descrição:
    Encontra todas as instâncias de P em Q em tempo linear.
    Usa tabela de lookup inicializada por P.
Complexidade:  
    O(n+m)
Dificuldade:
    Médio
Referências: (opcional)
    http://en.wikipedia.org/wiki/KMP_algorithm
"""

def kmp_init(P):
    F = [0]*(len(P)+1)
    i, j= 1, 0;
    while i<len(P):
        if P[i] == P[j]: 
            i+=1; j+=1; F[i] = j
        elif j == 0: 
            i+=1; F[i] = 0;
        else:            
            j = F[j];
    return F
    
def kmp(Q, P):
    F = kmp_init(P)
   
    i,j,n,m = 0,0,len(Q),len(P)
    
    while i-j <= n-m:
        while j < m:
            if P[j] == Q[i]: i+=1; j+=1
            else: break
        
        if j == m: yield i-m;
        elif j == 0: i+=1;
        j = F[j];


print list(kmp("casacasacasa", "casa")) #0, 4, 8
print list(kmp("cacacacacaca", "caca")) #0, 2, 4, 6, 8

================================================
FILE: algorithms/pattern-matching/levenshtein.py
================================================
# coding: utf-8
'''
Distância Levenshtein
Autor:
    Vladimir Levenshtein (1965)
Colaborador:
    Flávio Juvenal da Silva Junior (flaviojuvenal@gmail.com)
Descricao:
    A distância Levenshtein ou distância de edição entre duas strings
    é dada pelo número mínimo de operações necessárias para transformar
    uma string na outra. Entendemos por operações a inserção, deleção ou
    substituição de um caractere. Dessa forma, essa distância mede a
    quantidade de diferença entre duas strings (quanto maior, mais diferentes).
    E por isso é útil para aplicações de casamento de padrões, como
    corretores ortográficos.
Complexidade:
    O(len(s) * len(t)), onde s e t são as strings
Dificuldade:
    médio
Referências:
    http://en.wikipedia.org/wiki/Levenshtein_distance
    http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Dynamic/Edit/
Licenca:
    MIT
'''

def levenshtein(s, t):
    '''
    Implementação da versão não-recursiva do algoritmo.
    Veja em: http://en.wikipedia.org/wiki/Levenshtein_distance#Computing_Levenshtein_distance
    Observação: os -1 nas linhas 49 e 60 são porque em Python os índices
    das listas começam em 0.
    '''
    m = len(s) + 1
    n = len(t) + 1
    from_0_to_m = range(m)
    from_0_to_n = range(n)
    d = [[0]*n for _ in from_0_to_m]
    
    for i in from_0_to_m:
	d[i][0] = i
    for j in from_0_to_n:
	d[0][j] = j
    
    from_1_to_m = from_0_to_m[1:]
    from_1_to_n = from_0_to_n[1:]
    for j in from_1_to_n:
	for i in from_1_to_m:
	    if s[i-1] == t[j-1]:
		d[i][j] = d[i-1][j-1] #nenhuma operação necessária
	    else:
		d[i][j] = min(
		    d[i-1][j] + 1,   #uma exclusão
		    d[i][j-1] + 1,   #uma inserção
		    d[i-1][j-1] + 1, #uma substituição
		)
    return d[m-1][n-1]

if __name__ == '__main__':
    s = "kitten"
    t = "sitting"
    result = levenshtein(s, t)
    expected_result = 3
    #3, já que deve trocar k por s, e por i e inserir g
    assert result == expected_result
    print result


================================================
FILE: algorithms/physics/ballistic.py
================================================
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
Balistica
Autor:
    ?
Colaborador:    
    GabrielBap <gabrielbap1@gmail.com>
Tipo:
    physics
Descrição:
    Informa a distância horizontal quem um projétil atingiu baseado na força aplicada, força da gravidade e ângulo da força.
Complexidade:
    0(1)
Dificuldade:
    facil
Referências:
    [1]http://www.algosobre.com.br/fisica/balistica-e-lancamento-de-projetil.html
"""

from math import pi, sin, cos, radians

def simula_tiro(angle, forca, gravidade, startY):
   
   angleR = radians(angle) # As funções sin e cos trabalham com radianos
   
   time = 0 # tempo inicial do tiro
   # Define os vetores de força vertical e horizontal
   VetorVertical = sin(angleR) * forca
   VetorHorizontal = cos(angleR) * forca
   # Pow!
   Y = startY
   X = 0
   while Y > 0: # Enquanto a bala não cair...
      X = VetorHorizontal * time # Distância atual em X (S = V * t)
      Y = startY + (VetorVertical * time) - (gravidade * (time**2)) # Distância atual em Y (S = S0 + V*t + (a * t^2)/2)
      time += 1
   
   return angle, X, Y

forca = float(raw_input("Qual será a força? "))
gravidade = float(raw_input("Qual será a força da gravidade? "))
startY = float(raw_input("Qual será a altura do canhão? "))
try:
   angle = float(raw_input("Qual será o ângulo? (Opcional) "))
   dados = simula_tiro(angle, forca, gravidade, startY)
   resultado = "Ângulo = %i\n X = %.5f\n Y = %.5f\n\n" % (dados[0], dados[1], dados[2])
   print resultado
except:  
   for angle in range(0,91): # Faz a simulação em todos os ângulos de 0 a 90
      dados = simula_tiro(angle, forca, gravidade, startY)
      resultado = "\nÂngulo = %i\nX = %.5f\nY = %.5f\n" % (dados[0], dados[1], dados[2])
      print resultado


================================================
FILE: algorithms/search/binary-search.py
================================================
# coding: utf-8
'''
Busca Binária

Autor: 
    	Jon Bentley
Colaborador:
    	Dayvid Victor (victor.dvro@gmail.com)
Tipo:
	search
Descrição: 
	Faz uma busca em um vetor ordenado, usando o recurso
	'dividir para conquistar'. Ele compara o valor a ser
	buscado com o centro do vetor, se for menor, o mesmo
	procedimento é feito com o sub-vetor da esquerda, se
	for maior, com o sub-vetor da direita.	
Complexidade de tempo: 
    O(log n)
Dificuldade: 
    fácil
Referências:
	http://pt.wikipedia.org/wiki/Pesquisa_binária
'''

def binary_search(value, l):
	if len(l) == 0:
		return None
	mid = len(l)/2
	if value < l[mid]:
		return binary_search(value, l[:mid])
	elif value > l[mid]:
		tmp = binary_search(value, l[(mid + 1):])
		return (tmp is not None) and tmp + mid + 1 or None
	
	return mid

l = [0,1,2,3,4,7]
print binary_search(-1,l)
print binary_search(0,l)
print binary_search(1,l)
print binary_search(2,l)
print binary_search(3,l)
print binary_search(4,l)
print binary_search(5,l)
print binary_search(6,l)
print binary_search(7,l)
print binary_search(8,l)
print binary_search(9,l)









================================================
FILE: algorithms/search/linear-search.py
================================================
# encoding: utf-8


"""
  Linear Search
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz@gmail.com>
    José Alberto O. Morais Filho (j.moraisg12@gmail.com)
Tipo:
    search
Descrição:
    Utiliza força bruta em um array para retornar a posição de um valor nesse array, ou retornar -1, se nada
  for encontrado.
Complexidade:
    O(n)
Dificuldade:
    fácil
"""

# Entrada:
#   array = vetor onde o valor será pesquisado
#   search = valor procurado
# Saída:
#   a posição da primeira ocorrência do valor, ou -1, caso o valor não for encontrado

def linear_search(array, search):
  for k,v in enumerate(array):
    if v == search:
      return k
  
  return -1

# Exemplos

a = [1,5, 6, 3, 7,4]

print linear_search(a, 6)
print linear_search(a, 60)



================================================
FILE: algorithms/sequence/token.py
================================================
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
Token

Autor:
    ?
Colaborador:
    Felipe Djinn <felipe@felipedjinn.com.br>
Tipo:
    sequence
Descrição:
    Gera um token aleatório
Complexidade:
    ?
Dificuldade:
    facil
"""

import random
import string

def token(length = 10):
 return ''.join(random.choice(string.letters) for i in xrange(length)) 


"""
Examples
"""

print "Token com 10 caracteres (padrão): " + token()
print "Token com 5 caracteres: " +token(5)
print "Token com 15 caracteres " +token(15)


================================================
FILE: algorithms/sorting/bozosort.py
================================================
# encoding: utf-8

"""
Bozosort
Autor:
    Bozo
Colaborador:
    Karlisson Bezerra
Tipo:
    sorting
Descrição:
    Embaralha um vetor indefinidamente, até que os números estejam em ordem.
Complexidade:  
    O(infinito)
Dificuldade:
    facil
Referências:
    http://nerdson.com/blog/libbozo-01/
    http://pt.wikipedia.org/wiki/Bogosort
"""

from random import shuffle

def is_sorted(seq):
  # We define an empty sequence to be sorted by default.
  if not seq:
      return True

  # Otherwise, the sequence is sorted if every element is less or equal
  # than the next one.
  last = seq[0]
  for element in seq:
      if last > element:
          return False
      last = element
  return True

def bozosort(seq):
    while not is_sorted(seq):
        shuffle(seq)
    return seq

print bozosort([2,4,9,1,0,-4,17,8,0,23,67,-1])


================================================
FILE: algorithms/sorting/bubblesort.py
================================================
# encoding: utf-8

"""
Bubblesort
Autor:
    ?
Tipo:
    sorting
Descrição:
    Varre o vetor comparando cada um dos pares de números
    possíveis e trocando suas posições no vetor se necessário
Complexidade:  
    Pior caso: O(n²)
    Melhor caso: O(n²)
Dificuldade:
    facil
Referências:
    http://en.wikipedia.org/wiki/Bubble_sort
"""

def bubble(lst):
    for i, val1 in enumerate(lst):
        for j, val2 in enumerate(lst):
            if lst[i] < lst[j]:
               lst[i], lst[j] = lst[j], lst[i]
    return lst

print bubble([6, -7, 1, 12, 9, 3, 5])


================================================
FILE: algorithms/sorting/dropsort.py
================================================
#!/usr/bin/env python2
# -*- coding: utf-8 -*- 
"""
Nome do algoritmo
Autor:
    David Morgan-Mar. <dmm@dangermouse.net>
Colaborador:
    Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>
Tipo:
    sorting
Descrição:
    Dropsort é um algoritmo de ordernação lossy (causa perdas de informações)
    rápido, one-pass (lê a entrada exatamente uma vez, em ordem)

    O dropsort itera sobre os elementos da lista e, quando encontra um elemento
    menor que o anterior, descarta-o.
Complexidade:  
    O(n)
Dificuldade:
    facil
Referências:
    http://www.dangermouse.net/esoteric/dropsort.html
    http://students.cs.ndsu.nodak.edu/~abrjacks/dropsort.php (otimizações)
Licenca:
    MIT
"""

def dropsort(lst):
    i = 0
    prev = None
    while i != len(lst):
        if prev > lst[i]:
            del lst[i]
        else:
            prev = lst[i]
            i += 1

    return lst

if __name__ == '__main__':
    if dropsort([]) != []:
        exit(1)

    if dropsort([1, 2, 5, 3, 4, 6]) != [1, 2, 5, 6]:
        exit(1)

    if dropsort([1, 2, 2, 4]) != [1, 2, 2, 4]:
        exit(1)

    if dropsort([2, 11, 9, 8, 5, 4, 10, 3, 6, 0, 7, 13, 1, 12]) != [2, 11, 13]:
        exit(1)


================================================
FILE: algorithms/sorting/insertionsort.py
================================================
#!/usr/bin/env python
# encoding: utf-8

'''
Insertion Sort
Autor: 
    ?
Tipo:
    sorting
Descrição:
    Percorre uma lista da esquerda para direita e vai deixando os elementos
    mais a esquerda ordenados à medida que avança pela lista.
Complexidade:
    Pior caso: O(n²)
    Melhor caso: O(n)
Dificuldade:
    Facil
Referencia:
    http://pt.wikipedia.org/wiki/Insertion_sort
'''

def insertion_sort(L):
    for i in range(1, len(L)):
        elemento = L[i]
        j = i - 1

        while j >= 0 and L[j] > elemento:
            L[j+1] = L[j]
            j -= 1
            L[j+1] = elemento

    return L


================================================
FILE: algorithms/sorting/masochisticsort.py
================================================
#!/usr/bin/env python
# coding: utf-8

"""
Masochistic Sort
Author:
    Dilan Nery <dnerylopes AT gmail DOT com>
Colaborador:
    Dilan Nery <dnerylopes AT gmail DOT com>
Tipo:
    Ordenação
Descrição:
    Testa todas combinações possiveis de uma lista até encontrar a combinação
    em que a lista esteja ordenada
Complexidade:
    ?
Dificuldade:
    medio
Licensa:
    LGPL
"""

def masoquist_sort(L):
    if len(L) == 1:
        yield L
    elif len(L) == 2:
        count = 0
        while count < 2:
            L[0],L[1] = L[1],L[0]
            yield L
            count += 1
    else:
        for i in range(len(L)):
            L_copy = L[:]
            key = L_copy.pop(i)
            invert = masoquist_sort(L_copy)

            for i in invert:
                yield [key] + i
                
def is_sorted(L):
    flag = True
    for i in range(1,len(L)):
        if L[i-1] > L[i]:
            flag = False
    return flag                

if __name__ == '__main__':
    teste1 = masoquist_sort([2,4,1,5,4])
    for t1 in teste1:
        if is_sorted(t1):
            print t1
            break

    teste2 = masoquist_sort([2, 11, 9, 8, 5, 4, 10, 3, 6, 0, 7, 13, 1, 12])
    for t2 in teste2:
        if is_sorted(t2):
            print t2
            break


================================================
FILE: algorithms/sorting/mergesort.py
================================================
# coding: utf-8

"""
Mergesort
Autor:
	John von Neumann, em 1945
Colaborador:
	Adriano Melo (adriano@adrianomelo.com)
	Dayvid Victor (victor.dvro@gmail.com)
Tipo:
	sorting
Descrição:
	O algoritmo ordena um vetor dividindo-o pela metade e, depois de processar
	cada metade recursivamente, intercala as metades ordenadas.
Complexidade:
	O (n*log(n))
Dificuldade:
	fácil
Referências:
	?
"""

def intercala (inicio, fim):
	result = []
	i, j   = 0, 0

	while i < len(inicio) and j < len(fim):
		if inicio[i] < fim[j]:
			result.append(inicio[i])
			i = i + 1

		elif inicio[i] >= fim[j]:
			result.append(fim[j])
			j = j + 1

	result = result + inicio[i:]
	result = result + fim [j:]
	
	return result

def mergesort(array):
	tamanho = len(array)

	if tamanho == 1:
		return array

	inicio = mergesort (array[0:tamanho/2])
	fim    = mergesort (array[tamanho/2:])

	return intercala (inicio, fim)

print mergesort ([2,8,-2,1,45,37,-463,24,50,80,4,3,7,4,55])
print mergesort ([8,7,3,4,5])




================================================
FILE: algorithms/sorting/quicksort.py
================================================
# coding: utf-8
"""
Quicksort
Autor:
    C.A.R. Hoare
Colaborador:
    Adriano Melo (adriano@adrianomelo.com)
    Juan Lopes (me@juanlopes.net)
Tipo:
    sorting
Descrição:
    Quicksort é um algorítmo de ordenação de vetores cuja estratégia é
    dividir para conquistar. Basicamente o algorítmo organiza os elementos
    dos vetores de forma que os menores estejam antes dos maiores.
    Esse passo é feito recursivamente até que a lista completa esteja ordenada.
Complexidade:  
    O(n log(n)) - Melhor caso e médio caso.
    O(n²) - Pior caso.
Dificuldade:
    facil
Referências: (opcional)
    http://pt.wikipedia.org/wiki/Quicksort
"""
from random import randint

def quicksort(V):
    if len(V) <= 1: 
        return V
    
    pivot = V[0]
    equal = [x for x in V if x == pivot]
    lesser = [x for x in V if x < pivot]
    greater = [x for x in V if x > pivot]
    return quicksort(lesser) + equal + quicksort(greater)

print quicksort([i for i in xrange(30)]) # worst case
print quicksort([3 for i in xrange(30)]) # best case
print quicksort([randint(-100, 400) for i in xrange(30)]) # average case



================================================
FILE: algorithms/sorting/selectionsort.py
================================================
# encoding: utf-8
'''
Insertion Sort
Autor:
    ?
Colaborador:
	Bruno Coimbra <bbcoimbra@gmail.com>
Tipo:
    sorting
Descrição:
	Percorre uma lista a procura do menor valor e inclui na posição correta.
Complexidade:
	O(n²)
Dificuldade:
    Facil
Referencia:
    http://pt.wikipedia.org/wiki/Selection_sort
'''
from random import randint

def selectionsort(L):
	for i in range(0, len(L)):
		minor = L[i]
		minor_pos = i
		for j in range(i+1, len(L)):
			if L[j] < minor:
				minor = L[j]
				minor_pos = j
		L[i], L[minor_pos] = minor, L[i]
	return L

A = [randint(1, 50) for i in range(30)]
print A
print selectionsort(A)



================================================
FILE: algorithms/sorting/sleepsort.py
================================================
# -*- coding: utf-8 -*-

"""
Sleepsort
Autor:
    ?
Colaborador:
    Saulo Andrade Almeida <sauloandrade@gmail.com>
Tipo:
    sorting
Descrição:
    Uma brincadeira sobre ordenacao numerica baseada em threads e sleep.
    O algoritimo dispara threads para cada numero que sera ordenado com o 
    tempo de espera baseado no valor do numero, ou seja quanto maior o 
    numero mais ele demora para acordar e ser reinserido na nova estrututa 
    ordenada.

    Para utilizar o algoritimo basta executar o arquivo e uma lista padrao 
    sera executado, ou informar um lista de valores separados por espacos.
    Ex: $ python sleepsort.py ou $ python sleepsort 4 7 3 9 8 1 2
Complexidade:  
    ?
Dificuldade:
    facil
Referências: (opcional)
    Adaptado de http://dis.4chan.org/read/prog/1295544154
"""

import sys, time, threading

def sleepit(val):
    time.sleep(val/4.0)
    print val

# se nao vier parametro, usa uma lista padrao
if not sys.argv[1:] :
    values = [7,9,2,5,6,4,1,8,3]

# se vier, usa a lisra informada
else:
    values = sys.argv[1:]

# loop que dispara as threads    
print "Ordenando a lista ", values
[ threading.Thread(target=sleepit, args=[int(a)]).start() for a in values ]


================================================
FILE: modelo.txt
================================================

"""
Nome do algoritmo
Autor:
    Nome do autor do algoritmo ou ? caso nao saiba
Colaborador:
    Seu nome e email
Tipo:
    tipo do algoritmo (em ingles, minusculo, separado por hifen)
    Exemplos: math, number-theory, sorting
Descrição:
    O que este algoritmo faz? Serve pra que? Tente explicar
    da melhor forma possivel, ja que este projeto tem como
    publico-alvo os iniciantes.
Complexidade:  
    O(n), O(n^2)... ou ?, caso nao saiba
Dificuldade:
    facil, medio ou dificil
Referências: (opcional)
    links de referencia, um por linha
Licenca:(opcional)
    GPL, BSD...
"""

#codigo


================================================
FILE: other-languages/ai/genealogicaltree/genealogicaltree.pro
================================================
/*
Árvore Genealógica
Autor:
    ???
Colaborador:
    Filipe Saraiva (filip.saraiva@gmail.com)
Tipo:
    ai
Descrição:
    Implementação de uma árvore genealógica em
    Prolog. Teste do mecanismo de inferência da
    linguagem.
Complexidade:
    ???
Dificuldade:
    médio
Referências:
    [1] Palazzo, L. Introdução à Programação Prolog, Editora da
	Universidade Católica de Pelotas, Pelotas, 1997.
*/

/*
 * Este código serve para apresentar os rudimentos da inferência
 * lógica da linguagem Prolog. Nele, criamos uma árvore genealógica
 * e, a partir da base de dados ("fatos"), conseguiremos extrair
 * conhecimento não disponível anteriormente.
 */

/*
 * Fatos - Base de Dados
 */
pai(raimundo, ana).
pai(raimundo, renata).
pai(raimundo, lucio).

pai(estevao, marcelo).
pai(estevao, pamela).

pai(henrique, filomena).

mae(marcela, ana).
mae(marcela, renata).

mae(sofia, lucio).

mae(clarisse, marcelo).
mae(clarisse, pamela).

mae(sofia, filomena).

masculino(raimundo).
masculino(estevao).
masculino(henrique).
masculino(lucio).
masculino(marcelo).

feminina(marcela).
feminina(sofia).
feminina(clarisse).
feminina(ana).
feminina(renata).
feminina(pamela).
feminina(filomena).

/*
 * Predicados
 */

% Verifica quais pessoas tem o mesmo pai e a mesma mãe de uma
% pessoa "X". Estas são "irmãos total".
irmaostotal(X, Z) :- pai(Y, X), mae(K, X), pai(Y, Z), mae(K, Z).


================================================
FILE: other-languages/ai/sokoban/alberta/screen.1
================================================
11 19
###################
#####...###########
#####o..###########
#####..o###########
###..o.o.##########
###.#.##.##########
#...#.##.#####..xx#
#.o..o..........xx#
#####.###.#I##..xx#
#####.....#########
###################



================================================
FILE: other-languages/ai/sokoban/alberta/screen.1.sol
================================================


================================================
FILE: other-languages/ai/sokoban/alberta/screen.31
================================================
16 18
##################
###..#############
###..##..#...#####
##..o#.oIo...#####
##o..o..#.o.o#..##
##..o##.#o.o.....#
#..#..#.#...ooo..#
#.o....o..o##.####
#.o.o.#o#..#..####
##..###..###o.####
##..#xxxx.....####
#####xxxxxx#######
####xxxx##########
####xxx###########
####xxx###########
##################




================================================
FILE: other-languages/ai/sokoban/runtests.sh
================================================
echo "As saídas do programa são jogadas nos arquivos .sol"
g++ -O2 -o sokoban sokoban.cpp

echo "teste 1"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.sol

echo "teste 2"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.sol

echo "teste 3"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.sol

echo "teste 4"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.sol

echo "teste 5"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.sol

return;

echo "teste 6"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.sol

echo "teste 7"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.sol

echo "teste 8"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.sol

echo "teste 9"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.out sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.sol

echo "teste 10"
 ./sokoban < sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.in > sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.out
diff sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.out sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.sol



================================================
FILE: other-languages/ai/sokoban/sokoban.cpp
================================================
/*
# -*- coding: utf-8 -*-

"""
Algoritmo A* aplicado na resolução de um sokoban + representação de estados 
por meio de grafo de estados.

Autores: 
    Peter Hart, Nils Nilsson and Bertram Raphael 
Colaborador:
 	Péricles Lopes Machado [gogo40] (pericles.raskolnikoff.gmail.com)
Tipo: 
    graphs
Descrição: 
    O Algoritmo A* é uma generalização do algoritmo de Dijkstra que
permite acelerar a busca com uma heuristica que utiliza propriedades do grafo 
para estimar a distância para o destino. Este algoritmo é ideal quando aplicados
em grades ou representações espaciais e em situações em que já conhecemos a
posição do destino. 
	O grafo de estados é uma representação importante que permite implementar
mais facilmente AIs que buscam soluções ótimas pra puzzles.
	O sokoban é um problema NP difícil, então basicamente procura-se utilizar
heurísticas que estimam a solução correta para acelarar as buscas. Este
algoritmo realiza algumas podas para evitar expandir muito o grafo de estados.
Obviamente, ele é muito simples ainda, já que há heurísticas bem mais sofisticadas
disponíveis na literatura[4].

Complexidade: 
    O(2^N)
Dificuldade: 
    Difícil
Referências:
    [1] http://en.wikipedia.org/wiki/A*_search_algorithm
    [2] http://falapericles.blogspot.com.br/2009/05/o-algoritmo.html
	[3] http://falapericles.blogspot.com.br/2009/05/grafo-de-estados-e-suas-aplicacoes.html
	[4] http://webdocs.cs.ualberta.ca/~games/Sokoban/
"""
*/


/*
Para testar esse programa, por favor utilize o script runtests.sh.
Como ele é uma heurística, ainda é necessário melhorias para que ele
consiga resolver todos problemas disponíveis nesse branch.

A repositório onde se encontra o desenvolvimento contínuo desse
programa se encontra aqui: git@github.com:gogo40/gogoSokoban.git
*/

#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <string>
#include <utility>
#include <algorithm>
#include <queue>
#include <ctime>
#include <cstdlib>

using namespace std;

/*
Estrutura de dados para representar um estado do problema
Alfabeto do jogo:
		'.' espaco vazio
		'#' parede
		'I' personagem
		'J' personagem no destino
		'x' destino caixa
		'o' caixa
		'O' caixa no destino
*/
static int mask[600];
static char rm[8];

void initCState() {
	mask['.'] = 0; rm[0] = '.';
	mask['#'] = 1; rm[1] = '#';
	mask['I'] = 2; rm[2] = 'I';
	mask['J'] = 3; rm[3] = 'J';
	mask['x'] = 4; rm[4] = 'x';
	mask['o'] = 5; rm[5] = 'o';
	mask['O'] = 6; rm[6] = 'O';

}

/*
Nós representamos um estado por meio de palavra de (N*M)/10 bytes, onde
N e M são as dimensões da grade do sokoban
*/
class cState {
	public:
	
		cState(const cState& s) {
			N = s.N;
			M = s.M;
			v = s.v;
		}
		
		cState(int N = 0, int M = 0)
		: N(N), M(M), v( (N*M)/10 + 1, 0) {}
		
		char get(int i, int j) {
			int k = i * M + j;
			int p = k / 10;
			int n = k % 10;
			int value = (v[p] >> (3 * n) ) & 7;
			
			return rm[value];
		}
		
		void insert(int i, int j, char c) {
			int value = mask[c];
			int k = i * M + j;
			int p = k / 10;
			int n = k % 10;
			int w = v[p] & (7 << (3*n));
			v[p] ^= w;
			v[p] |= value << (3 * n); 
		}
		
		
		cState& operator=(const cState& x) {
			N = x.N;
			M = x.M;
			v = x.v;
			return *this;
		}
		
		void print() {
			for (int i = 0; i < N; ++i) {
				for (int j = 0; j < M; ++j) {
					printf("%c", get(i, j));
				}
				printf("\n");
			}
		}
	
	friend bool operator<(const cState& a, const cState& b);
	friend bool operator==(const cState& a, const cState& b);
	
	bool operator()(const cState& b) {
		if (N > b.N or M > b.M) return false;
		if (*this == b) return false;
		
		for (int i = 0; i < v.size(); ++i) 
			if (v[i] > b.v[i]) {
				printf("false...\n");
				return false;
			}
		printf("true...\n");
		return true;
	}
	
	private:
	
		
		int N, M;
		
		vector<int> v;
};


/* Verifica se dois estados são iguais*/
bool operator==(const cState& a, const cState& b) {

	for (int i = 0; i < a.v.size(); ++i) 
		if (a.v[i] != b.v[i]) {
			return false;
		}

	return true;
}

/* realiza a comparação lexicográfica dos dois estados*/
bool operator<(const cState& a, const cState& b) {
	
	return lexicographical_compare(a.v.begin(), a.v.end(), b.v.begin(), b.v.end());
}

///////////////////////////////////////////////////////

int N, M;

/* Movimentações possíveis pelo jogador do sokoban*/
int dx[] = {-1,  1,  0,  0};
int dy[] = { 0,  0, -1,  1};


typedef pair<int, int> State;
typedef pair<int, State> pState;

vector<cState> vs;
vector<vector<int> > vbox;
map<cState, int> ids;

/*Imprime um estado*/
void print(cState& s) {
	s.print();
	cout << endl;
}

/*Transforma um estado numa string*/
string getStr(cState& s) {
	string out = "";
	for (int i = 0; i < N; ++i)
		for (int j = 0; j < M; ++j)
			out += s.get(i, j);
	return out;
}

/* Transforma uma string num grafo de estado*/
cState getVec(string& s) {
	cState v(N, M);

	int n = 0;

	for (int i = 0; i < N; ++i)
		for (int j = 0; j < M; ++j){
			v.insert(i, j, s[n]);
			++n;
		}

	return v;
}

/*Destinos das caixas*/
vector<int> pfx;
vector<int> pfy;

inline int abs(int a) { return a>0?a:-a; }

/*Calcula estimativa de jogadas que faltam pra concluir o sokoban*/
int h(cState& s, int p, int id) {
	int d = 0;
	int x = p/M;
	int y = p%M;
	int nc = 0;

	for (int n = 0; n < vbox[id].size(); ++n) {
			int i = vbox[id][n] / M;
			int j = vbox[id][n] % M;
			if (s.get(i, j) == 'o') {
				int dv = 2*(N + M);
				for (int k = 0; k < pfx.size(); ++k) {
					int dx = abs(pfx[k] - i);
					int dy = abs(pfy[k] - j);
					int dp = (dx+dy);
					if (dp < dv) dv = dp;
				}
				d += dv;
				nc++;
			}
	}
	return d;
}


/*Verifica se chegamos num estado "morto"*/
bool isDead(cState& s, int id) {
	bool ok = false;
/*
##
#o (i-1, j+1)

##
o# (i+1, j+1)


o#
## (i+1, j-1)

#o
## (i-1, j-1)
*/
	for (int n = 0; n < vbox[id].size(); ++n) {
		int i = vbox[id][n] / M;
		int j = vbox[id][n] % M;
		if (s.get(i, j) == 'o') {
			if ((s.get(i-1, j) == '#' and s.get(i, j+1) == '#') or
				(s.get(i+1, j) == '#' and s.get(i, j+1) == '#') or
				(s.get(i+1, j) == '#' and s.get(i, j-1) == '#') or
				(s.get(i-1, j) == '#' and s.get(i, j-1) == '#')
				) {
					ok = true;
					break;
				}
		}
	}
	return ok;
}


/*Realiza um movimento*/
bool makeMove(cState& s, int x, int y, int k) {

	int px = x + dx[k];
	int py = y + dy[k];

	if (not (px > -1 and px < N and py > -1 and py < M)) {
		return false;
	}

	switch (s.get(px, py)) {
		case '.': s.insert(px, py, 'o'); break;
		case 'x': s.insert(px, py, 'O'); break;
		default: return false;
	}

	return true;
}

/*Calcula a distância entre uma caixa e um posição final para a mesma.
Simula o jogador realizando o movimento na caixa*/
int calcDist(cState& s, int x, int y, int xf, int yf) {
	map<int, int> D;
	queue<int> Q;
	int ini, fim;
	ini = fim = 0;
	
	Q.push(x * M + y);
	
	D[x * M + y] = 0;

	while (not Q.empty()) {
		int u = Q.front();
		
		int du = D[u];
		int ux = u / M;
		int uy = u % M;

		if (ux  ==  xf and uy == yf) break;

		Q.pop();
		
		for (int k = 0; k < 4; ++k) {
			int vx = ux + dx[k];
			int vy = uy + dy[k];
			int v = vx * M +vy;

			if (vx > -1 and vx < N and vy > -1 and vy < M)
				if (s.get(vx, vy) == '.' || s.get(vx, vy) == 'x') {
					if (D.find(v) == D.end() || D[v] > du + 1) {
						D[v] = du + 1;
						Q.push(v);
					}
				}
		}
	}

	return D.find(xf * M + yf) == D.end()? -1 : D[xf * M + yf];
}

State ini, fim;
map<State, State> pi;

/* Imprime a solução */
void print_sol(State& u, int p, int du) {
	if (u == ini) return;

	print_sol(pi[u], p + 1, du);

	if (u == fim) return;

	cState m = vs[u.first];
	int po = u.second;
	int x = po/M;
	int y = po%M;

	m.insert(x, y, 'I');

	cout<< du - p<< endl;
	print(m);
}

/* Localiza a caixa na grade*/
void findBox(vector<int>& vb, cState& s) {
	for (int i = 0; i < N; ++i)
		for (int j = 0; j < M; ++j)
			if (s.get(i, j) == 'o' || s.get(i, j) == 'O') {
				vb.push_back(i * M + j);
			}
}

int main()
{
	srand(time(NULL));
	initCState();
	
	/*Lê o estado inicial do jogo*/
	cin>>N>>M;

	cState s(N, M), f(N, M);

	for (int i = 0; i < N; ++i) {
		string a;
		cin>>a;
		for (int j = 0; j < M; ++j) {
			f.insert(i, j, a[j]);
			s.insert(i, j, a[j]);
		}
	}
	
	/*
	Alfabeto do jogo:
		'.' espaco vazio
		'#' parede
		'I' personagem
		'J' personagem no destino
		'x' destino caixa
		'o' caixa
		'O' caixa no destino
	*/

	int xo, yo, po;

	pfx.clear();
	pfy.clear();

	/* Localiza elementos importantes da grade*/
	for (int i = 0; i < N; ++i)
		for (int j = 0; j < M; ++j)
			if (s.get(i, j) == 'I') {
				f.insert(i, j, '.');
				s.insert(i, j, '.');
				
				po = i * M +j;
				xo = i;
				yo = j;
			}else if (s.get(i, j) == 'J') {
				s.insert(i, j, 'x');
				f.insert(i, j, 'O');
				
				po = i * M +j;
				xo = i;
				yo = j;
			} else if (s.get(i, j) == 'x') {
				f.insert(i, j, 'O');
				
				pfx.push_back(i);
				pfy.push_back(j);
			} else if (s.get(i, j) == 'o') {
				f.insert(i, j, '.');
				
			} else {
				f.insert(i, j, s.get(i,j));
			}

	/*Localiza caixas*/
	vs.push_back(s);
	vbox.push_back(vector<int>());
	findBox(vbox[0], s);
	ids[s] = 0;

	vs.push_back(f);
	vbox.push_back(vector<int>());
	findBox(vbox[1], f);
	ids[f] = 1;

	
	ini.first = 0;
	ini.second = po;

	fim.first = 1;
	fim.second = -1;

	pi.clear();

	map<State, int> D;

	D[ini] = 0;

	bool ok = false;
	int ck = 1;
	int dmin = 1<<20;

	/* Tenta-se estimar quantas jogadas são necessárias para se concluir o jogo
		caso a profundidade da busca ultrapasse L, então a busca é encerrada.
		O L é o "branch factor" do algoritmo.*/
	for (int L = 250; L < 1000; L *= 2) {

		if (ok) break;

		priority_queue<pState> Q;
		D.clear();
		Q.push(pState(0, ini));
		D[ini] = 0;

		while (!Q.empty()) {
			int uest = -Q.top().first;
			State u = Q.top().second;
			int du = D[u];
			
			if (u == fim){
				ok = true;
				dmin = du;
				break;
			}

			int p = u.second;
			int x = p / M;
			int y = p % M;
			
			Q.pop();

			if ( uest > L or uest >= dmin) continue;
			else if (u == fim){
				dmin = du;
			}
			
			if (ck % 50000 == 0) {
				cerr << du << " dmin= " << dmin << endl;
			}
			++ck;
			
			/*
			Para cada estado u, realiza-se uma busca nos 4 estados adjascentes.
			*/
			for (int nb = 0; nb < vbox[u.first].size(); ++nb){
					int i = vbox[u.first][nb] / M;
					int j = vbox[u.first][nb] % M;
					if (vs[u.first].get(i, j) == 'o' || vs[u.first].get(i, j) == 'O') {
						int q = i * M + j;

						for (int k = 0; k < 4; ++k) {

							cState m = vs[u.first];
							
							if (makeMove(m, i, j, k)) {
								m.insert(i, j, (vs[u.first].get(i, j) =='o')?'.':'x');
								
								int xf = i - dx[k];
								int yf = j - dy[k];

								int dup = calcDist(vs[u.first], x, y, xf, yf);
								if (dup > -1) {
									State v;
									
									if (ids.find(m) == ids.end()) {
										v.first = ids[m] = vs.size();
										vbox.push_back(vector<int>());
										findBox(vbox[vs.size()], m);
										vs.push_back(m);
									} else v.first = ids[m];
									
									if (isDead(m, v.first)) continue;
									
									if (v.first == fim.first) q = -1;

									v.second = q;

									if (D.find(v) == D.end()) {
										D[v] = du + dup + 1;
										pi[v]= u;
										int est = du + dup + 1 + h(m, p, v.first);
										if (est < dmin and est < L) Q.push(pState(-est, v));
									} else if (D[v] > du + dup + 1) {
										D[v] = du + dup + 1;
										pi[v] = u;
										int est = du + dup + 1 + h(m, p, v.first);
										if (est < dmin and est < L) Q.push(pState(-est, v));
									}
								}
							}
						}
					}
			}
		}
	}

	if (ok) {
		print_sol(fim, 0, D[fim]);
	} else {
		cout << "[Nao ha solucao... =(]\n";
	}

	return 0;
}



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.in
================================================
9 9
#########
#I..#####
#.oo#####
#.o.###x#
###.###x#
###....x#
##...#..#
##...####
#########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.out
================================================
59
#########
#...#####
#.oI#####
#.oo###x#
###.###x#
###....x#
##...#..#
##...####
#########

60
#########
#...#####
#.o.#####
#.oI###x#
###o###x#
###....x#
##...#..#
##...####
#########

61
#########
#...#####
#.o.#####
#.o.###x#
###I###x#
###o...x#
##...#..#
##...####
#########

62
#########
#...#####
#.o.#####
#.o.###x#
###.###x#
###I...x#
##.o.#..#
##...####
#########

63
#########
#...#####
#.o.#####
#.o.###x#
###.###x#
###....x#
##.Io#..#
##...####
#########

64
#########
#...#####
#.o.#####
#.o.###x#
###.###x#
###.o..x#
##..I#..#
##...####
#########

65
#########
#...#####
#.Io#####
#.o.###x#
###.###x#
###.o..x#
##...#..#
##...####
#########

66
#########
#...#####
#..I#####
#.oo###x#
###.###x#
###.o..x#
##...#..#
##...####
#########

67
#########
#...#####
#...#####
#.oI###x#
###o###x#
###.o..x#
##...#..#
##...####
#########

68
#########
#...#####
#...#####
#.o.###x#
###I###x#
###oo..x#
##...#..#
##...####
#########

69
#########
#...#####
#...#####
#.o.###x#
###.###x#
###Io..x#
##.o.#..#
##...####
#########

70
#########
#...#####
#...#####
#.o.###x#
###.###x#
###.Io.x#
##.o.#..#
##...####
#########

71
#########
#...#####
#...#####
#.o.###x#
###.###x#
###..Iox#
##.o.#..#
##...####
#########

72
#########
#...#####
#...#####
#.o.###x#
###.###x#
###...IO#
##.o.#..#
##...####
#########

73
#########
#...#####
#...#####
#.o.###x#
###.###O#
###....I#
##.o.#..#
##...####
#########

74
#########
#...#####
#...#####
#.o.###O#
###.###I#
###....x#
##.o.#..#
##...####
#########

75
#########
#...#####
#...#####
#.o.###O#
###.###x#
###....x#
##.Io#..#
##...####
#########

76
#########
#...#####
#...#####
#.o.###O#
###.###x#
###.o..x#
##..I#..#
##...####
#########

77
#########
#...#####
#...#####
#.Io###O#
###.###x#
###.o..x#
##...#..#
##...####
#########

78
#########
#...#####
#...#####
#..I###O#
###o###x#
###.o..x#
##...#..#
##...####
#########

79
#########
#...#####
#...#####
#...###O#
###I###x#
###oo..x#
##...#..#
##...####
#########

80
#########
#...#####
#...#####
#...###O#
###.###x#
###Io..x#
##.o.#..#
##...####
#########

81
#########
#...#####
#...#####
#...###O#
###.###x#
###.Io.x#
##.o.#..#
##...####
#########

82
#########
#...#####
#...#####
#...###O#
###.###x#
###..Iox#
##.o.#..#
##...####
#########

83
#########
#...#####
#...#####
#...###O#
###.###x#
###...IO#
##.o.#..#
##...####
#########

84
#########
#...#####
#...#####
#...###O#
###.###O#
###....I#
##.o.#..#
##...####
#########

85
#########
#...#####
#...#####
#...###O#
###.###O#
###....x#
##.Io#..#
##...####
#########

86
#########
#...#####
#...#####
#...###O#
###.###O#
###.o..x#
##..I#..#
##...####
#########

87
#########
#...#####
#...#####
#...###O#
###.###O#
###.Io.x#
##...#..#
##...####
#########

88
#########
#...#####
#...#####
#...###O#
###.###O#
###..Iox#
##...#..#
##...####
#########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.sol
================================================
59
#########
#...#####
#.oI#####
#.oo###x#
###.###x#
###....x#
##...#..#
##...####
#########

60
#########
#...#####
#.o.#####
#.oI###x#
###o###x#
###....x#
##...#..#
##...####
#########

61
#########
#...#####
#.o.#####
#.o.###x#
###I###x#
###o...x#
##...#..#
##...####
#########

62
#########
#...#####
#.o.#####
#.o.###x#
###.###x#
###I...x#
##.o.#..#
##...####
#########

63
#########
#...#####
#.o.#####
#.o.###x#
###.###x#
###....x#
##.Io#..#
##...####
#########

64
#########
#...#####
#.o.#####
#.o.###x#
###.###x#
###.o..x#
##..I#..#
##...####
#########

65
#########
#...#####
#.Io#####
#.o.###x#
###.###x#
###.o..x#
##...#..#
##...####
#########

66
#########
#...#####
#..I#####
#.oo###x#
###.###x#
###.o..x#
##...#..#
##...####
#########

67
#########
#...#####
#...#####
#.oI###x#
###o###x#
###.o..x#
##...#..#
##...####
#########

68
#########
#...#####
#...#####
#.o.###x#
###I###x#
###oo..x#
##...#..#
##...####
#########

69
#########
#...#####
#...#####
#.o.###x#
###.###x#
###Io..x#
##.o.#..#
##...####
#########

70
#########
#...#####
#...#####
#.o.###x#
###.###x#
###.Io.x#
##.o.#..#
##...####
#########

71
#########
#...#####
#...#####
#.o.###x#
###.###x#
###..Iox#
##.o.#..#
##...####
#########

72
#########
#...#####
#...#####
#.o.###x#
###.###x#
###...IO#
##.o.#..#
##...####
#########

73
#########
#...#####
#...#####
#.o.###x#
###.###O#
###....I#
##.o.#..#
##...####
#########

74
#########
#...#####
#...#####
#.o.###O#
###.###I#
###....x#
##.o.#..#
##...####
#########

75
#########
#...#####
#...#####
#.o.###O#
###.###x#
###....x#
##.Io#..#
##...####
#########

76
#########
#...#####
#...#####
#.o.###O#
###.###x#
###.o..x#
##..I#..#
##...####
#########

77
#########
#...#####
#...#####
#.Io###O#
###.###x#
###.o..x#
##...#..#
##...####
#########

78
#########
#...#####
#...#####
#..I###O#
###o###x#
###.o..x#
##...#..#
##...####
#########

79
#########
#...#####
#...#####
#...###O#
###I###x#
###oo..x#
##...#..#
##...####
#########

80
#########
#...#####
#...#####
#...###O#
###.###x#
###Io..x#
##.o.#..#
##...####
#########

81
#########
#...#####
#...#####
#...###O#
###.###x#
###.Io.x#
##.o.#..#
##...####
#########

82
#########
#...#####
#...#####
#...###O#
###.###x#
###..Iox#
##.o.#..#
##...####
#########

83
#########
#...#####
#...#####
#...###O#
###.###x#
###...IO#
##.o.#..#
##...####
#########

84
#########
#...#####
#...#####
#...###O#
###.###O#
###....I#
##.o.#..#
##...####
#########

85
#########
#...#####
#...#####
#...###O#
###.###O#
###....x#
##.Io#..#
##...####
#########

86
#########
#...#####
#...#####
#...###O#
###.###O#
###.o..x#
##..I#..#
##...####
#########

87
#########
#...#####
#...#####
#...###O#
###.###O#
###.Io.x#
##...#..#
##...####
#########

88
#########
#...#####
#...#####
#...###O#
###.###O#
###..Iox#
##...#..#
##...####
#########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.in
================================================
9 10
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.o.I.##
###.....##
##########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.out
================================================
28
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.Io..##
###.....##
##########

29
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###..Io.##
###.....##
##########

30
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###...Io##
###.....##
##########

31
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#o##
###....I##
###.....##
##########

32
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o....o##
#####.#I##
###.....##
###.....##
##########

33
##########
#xx......#
#xxo..#..#
#..#o##o##
#.o....I##
#####.#.##
###.....##
###.....##
##########

34
##########
#xx......#
#xxo..#o.#
#..#o##I##
#.o.....##
#####.#.##
###.....##
###.....##
##########

35
##########
#xx....o.#
#xxo..#I.#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

36
##########
#xx...oI.#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

37
##########
#xx..oI..#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

38
##########
#xx.oI...#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

39
##########
#xxoI....#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

40
##########
#xOI.....#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

41
##########
#OI......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

42
##########
#Ox......#
#xOI..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

43
##########
#Ox......#
#OI...#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

44
##########
#Ox......#
#Ox...#..#
#..#o##.##
#.Io....##
#####.#.##
###.....##
###.....##
##########

45
##########
#Ox......#
#Ox...#..#
#..#o##.##
#..Io...##
#####.#.##
###.....##
###.....##
##########

46
##########
#Ox......#
#Ox...#..#
#..#o##.##
#...Io..##
#####.#.##
###.....##
###.....##
##########

47
##########
#Ox......#
#Ox.o.#..#
#..#I##.##
#....o..##
#####.#.##
###.....##
###.....##
##########

48
##########
#Ox......#
#Ox.o.#..#
#..#.##.##
#....Io.##
#####.#.##
###.....##
###.....##
##########

49
##########
#Ox......#
#Ox.o.#..#
#..#.##.##
#.....Io##
#####.#.##
###.....##
###.....##
##########

50
##########
#Ox......#
#Ox.o.#..#
#..#.##o##
#......I##
#####.#.##
###.....##
###.....##
##########

51
##########
#Ox......#
#Ox.o.#o.#
#..#.##I##
#.......##
#####.#.##
###.....##
###.....##
##########

52
##########
#Ox....o.#
#Ox.o.#I.#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

53
##########
#Ox...oI.#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

54
##########
#Ox..oI..#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

55
##########
#Ox.oI...#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

56
##########
#OxoI....#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

57
##########
#OOI.....#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

58
##########
#OO......#
#OxoI.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.sol
================================================
28
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.Io..##
###.....##
##########

29
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###..Io.##
###.....##
##########

30
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###...Io##
###.....##
##########

31
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#o##
###....I##
###.....##
##########

32
##########
#xx......#
#xxo..#..#
#..#o##.##
#.o....o##
#####.#I##
###.....##
###.....##
##########

33
##########
#xx......#
#xxo..#..#
#..#o##o##
#.o....I##
#####.#.##
###.....##
###.....##
##########

34
##########
#xx......#
#xxo..#o.#
#..#o##I##
#.o.....##
#####.#.##
###.....##
###.....##
##########

35
##########
#xx....o.#
#xxo..#I.#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

36
##########
#xx...oI.#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

37
##########
#xx..oI..#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

38
##########
#xx.oI...#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

39
##########
#xxoI....#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

40
##########
#xOI.....#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

41
##########
#OI......#
#xxo..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

42
##########
#Ox......#
#xOI..#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

43
##########
#Ox......#
#OI...#..#
#..#o##.##
#.o.....##
#####.#.##
###.....##
###.....##
##########

44
##########
#Ox......#
#Ox...#..#
#..#o##.##
#.Io....##
#####.#.##
###.....##
###.....##
##########

45
##########
#Ox......#
#Ox...#..#
#..#o##.##
#..Io...##
#####.#.##
###.....##
###.....##
##########

46
##########
#Ox......#
#Ox...#..#
#..#o##.##
#...Io..##
#####.#.##
###.....##
###.....##
##########

47
##########
#Ox......#
#Ox.o.#..#
#..#I##.##
#....o..##
#####.#.##
###.....##
###.....##
##########

48
##########
#Ox......#
#Ox.o.#..#
#..#.##.##
#....Io.##
#####.#.##
###.....##
###.....##
##########

49
##########
#Ox......#
#Ox.o.#..#
#..#.##.##
#.....Io##
#####.#.##
###.....##
###.....##
##########

50
##########
#Ox......#
#Ox.o.#..#
#..#.##o##
#......I##
#####.#.##
###.....##
###.....##
##########

51
##########
#Ox......#
#Ox.o.#o.#
#..#.##I##
#.......##
#####.#.##
###.....##
###.....##
##########

52
##########
#Ox....o.#
#Ox.o.#I.#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

53
##########
#Ox...oI.#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

54
##########
#Ox..oI..#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

55
##########
#Ox.oI...#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

56
##########
#OxoI....#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

57
##########
#OOI.....#
#Ox.o.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########

58
##########
#OO......#
#OxoI.#..#
#..#.##.##
#.......##
#####.#.##
###.....##
###.....##
##########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.in
================================================
8 6
######
##..##
#Io.##
##o.##
##.o.#
#xo..#
#xxOx#
######


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.out
================================================
20
######
##..##
#.Io##
##o.##
##.o.#
#xo..#
#xxOx#
######

21
######
##..##
#..o##
##I.##
##oo.#
#xo..#
#xxOx#
######

22
######
##..##
#..o##
##..##
##oI.#
#xoo.#
#xxOx#
######

23
######
##..##
#..o##
##..##
##o..#
#xoo.#
#xOIx#
######

24
######
##..##
#..o##
##..##
##o..#
#xoo.#
#OIxx#
######

25
######
##..##
#..o##
##..##
##o..#
#xoI.#
#OxOx#
######

26
######
##..##
#..o##
##..##
##o..#
#OI..#
#OxOx#
######

27
######
##..##
#..o##
##..##
##o..#
#O...#
#OxIO#
######

28
######
##..##
#..o##
##..##
##I..#
#Oo..#
#OxxO#
######

29
######
##..##
#..o##
##..##
##...#
#OI..#
#OOxO#
######

30
######
##..##
#..I##
##.o##
##...#
#O...#
#OOxO#
######

31
######
##..##
#...##
##.I##
##.o.#
#O...#
#OOxO#
######

32
######
##..##
#...##
##..##
##.I.#
#O.o.#
#OOxO#
######



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.sol
================================================
20
######
##..##
#.Io##
##o.##
##.o.#
#xo..#
#xxOx#
######

21
######
##..##
#..o##
##I.##
##oo.#
#xo..#
#xxOx#
######

22
######
##..##
#..o##
##..##
##oI.#
#xoo.#
#xxOx#
######

23
######
##..##
#..o##
##..##
##o..#
#xoo.#
#xOIx#
######

24
######
##..##
#..o##
##..##
##o..#
#xoo.#
#OIxx#
######

25
######
##..##
#..o##
##..##
##o..#
#xoI.#
#OxOx#
######

26
######
##..##
#..o##
##..##
##o..#
#OI..#
#OxOx#
######

27
######
##..##
#..o##
##..##
##o..#
#O...#
#OxIO#
######

28
######
##..##
#..o##
##..##
##I..#
#Oo..#
#OxxO#
######

29
######
##..##
#..o##
##..##
##...#
#OI..#
#OOxO#
######

30
######
##..##
#..I##
##.o##
##...#
#O...#
#OOxO#
######

31
######
##..##
#...##
##.I##
##.o.#
#O...#
#OOxO#
######

32
######
##..##
#...##
##..##
##.I.#
#O.o.#
#OOxO#
######



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.in
================================================
8 8
########
##I.####
##.o..##
###.#.##
#x#.#..#
#xo..#.#
#x...o.#
########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.out
================================================
40
########
##..####
##.I..##
###o#.##
#x#.#..#
#xo..#.#
#x...o.#
########

41
########
##..####
##....##
###o#.##
#x#.#..#
#xo..#.#
#x..oI.#
########

42
########
##..####
##....##
###o#.##
#x#.#..#
#xo..#.#
#x.oI..#
########

43
########
##..####
##....##
###o#.##
#x#.#..#
#OI..#.#
#x.o...#
########

44
########
##..####
##....##
###o#.##
#O#.#..#
#I...#.#
#x.o...#
########

45
########
##..####
##....##
###o#.##
#O#.#..#
#x...#.#
#xoI...#
########

46
########
##..####
##....##
###o#.##
#O#.#..#
#x...#.#
#OI....#
########

47
########
##..####
##....##
###I#.##
#O#o#..#
#x...#.#
#O.....#
########

48
########
##..####
##....##
###.#.##
#O#I#..#
#x.o.#.#
#O.....#
########

49
########
##..####
##....##
###.#.##
#O#.#..#
#xoI.#.#
#O.....#
########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.sol
================================================
40
########
##..####
##.I..##
###o#.##
#x#.#..#
#xo..#.#
#x...o.#
########

41
########
##..####
##....##
###o#.##
#x#.#..#
#xo..#.#
#x..oI.#
########

42
########
##..####
##....##
###o#.##
#x#.#..#
#xo..#.#
#x.oI..#
########

43
########
##..####
##....##
###o#.##
#x#.#..#
#OI..#.#
#x.o...#
########

44
########
##..####
##....##
###o#.##
#O#.#..#
#I...#.#
#x.o...#
########

45
########
##..####
##....##
###o#.##
#O#.#..#
#x...#.#
#xoI...#
########

46
########
##..####
##....##
###o#.##
#O#.#..#
#x...#.#
#OI....#
########

47
########
##..####
##....##
###I#.##
#O#o#..#
#x...#.#
#O.....#
########

48
########
##..####
##....##
###.#.##
#O#I#..#
#x.o.#.#
#O.....#
########

49
########
##..####
##....##
###.#.##
#O#.#..#
#xoI.#.#
#O.....#
########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.in
================================================
7 10
##########
##.....###
##o###...#
#.I.o..o.#
#.xx#.o.##
##xx#...##
##########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.out
================================================
88
##########
##.....###
##o###...#
#...Io.o.#
#.xx#.o.##
##xx#...##
##########

89
##########
##.....###
##o###...#
#....Ioo.#
#.xx#.o.##
##xx#...##
##########

90
##########
##.....###
##o###.o.#
#.....oI.#
#.xx#.o.##
##xx#...##
##########

91
##########
##.....###
##o###.o.#
#....oI..#
#.xx#.o.##
##xx#...##
##########

92
##########
##.....###
##I###.o.#
#.o..o...#
#.xx#.o.##
##xx#...##
##########

93
##########
##.....###
##.###.o.#
#.I..o...#
#.Ox#.o.##
##xx#...##
##########

94
##########
##.....###
##.###.o.#
#....o...#
#.Ix#.o.##
##Ox#...##
##########

95
##########
##.....###
##.###.o.#
#...oI...#
#.xx#.o.##
##Ox#...##
##########

96
##########
##.....###
##.###.o.#
#..oI....#
#.xx#.o.##
##Ox#...##
##########

97
##########
##.....###
##.###.o.#
#.oI.....#
#.xx#.o.##
##Ox#...##
##########

98
##########
##.....###
##.###.o.#
#.I......#
#.Ox#.o.##
##Ox#...##
##########

99
##########
##.....###
##.###.o.#
#........#
#.IO#.o.##
##Ox#...##
##########

100
##########
##.....###
##.###oI.#
#........#
#.xO#.o.##
##Ox#...##
##########

101
##########
##.....###
##.###I..#
#.....o..#
#.xO#.o.##
##Ox#...##
##########

102
##########
##.....###
##.###...#
#....oI..#
#.xO#.o.##
##Ox#...##
##########

103
##########
##.....###
##.###...#
#...oI...#
#.xO#.o.##
##Ox#...##
##########

104
##########
##.....###
##.###...#
#..oI....#
#.xO#.o.##
##Ox#...##
##########

105
##########
##.....###
##.###...#
#.oI.....#
#.xO#.o.##
##Ox#...##
##########

106
##########
##.....###
##.###...#
#.o......#
#.xI#.o.##
##OO#...##
##########

107
##########
##.....###
##.###...#
#.I......#
#.Ox#.o.##
##OO#...##
##########

108
##########
##.....###
##.###...#
#........#
#.IO#.o.##
##OO#...##
##########

109
##########
##.....###
##.###...#
#.....o..#
#.xO#.I.##
##OO#...##
##########

110
##########
##.....###
##.###...#
#....oI..#
#.xO#...##
##OO#...##
##########

111
##########
##.....###
##.###...#
#...oI...#
#.xO#...##
##OO#...##
##########

112
##########
##.....###
##.###...#
#..oI....#
#.xO#...##
##OO#...##
##########

113
##########
##.....###
##.###...#
#.oI.....#
#.xO#...##
##OO#...##
##########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.sol
================================================
88
##########
##.....###
##o###...#
#...Io.o.#
#.xx#.o.##
##xx#...##
##########

89
##########
##.....###
##o###...#
#....Ioo.#
#.xx#.o.##
##xx#...##
##########

90
##########
##.....###
##o###.o.#
#.....oI.#
#.xx#.o.##
##xx#...##
##########

91
##########
##.....###
##o###.o.#
#....oI..#
#.xx#.o.##
##xx#...##
##########

92
##########
##.....###
##I###.o.#
#.o..o...#
#.xx#.o.##
##xx#...##
##########

93
##########
##.....###
##.###.o.#
#.I..o...#
#.Ox#.o.##
##xx#...##
##########

94
##########
##.....###
##.###.o.#
#....o...#
#.Ix#.o.##
##Ox#...##
##########

95
##########
##.....###
##.###.o.#
#...oI...#
#.xx#.o.##
##Ox#...##
##########

96
##########
##.....###
##.###.o.#
#..oI....#
#.xx#.o.##
##Ox#...##
##########

97
##########
##.....###
##.###.o.#
#.oI.....#
#.xx#.o.##
##Ox#...##
##########

98
##########
##.....###
##.###.o.#
#.I......#
#.Ox#.o.##
##Ox#...##
##########

99
##########
##.....###
##.###.o.#
#........#
#.IO#.o.##
##Ox#...##
##########

100
##########
##.....###
##.###oI.#
#........#
#.xO#.o.##
##Ox#...##
##########

101
##########
##.....###
##.###I..#
#.....o..#
#.xO#.o.##
##Ox#...##
##########

102
##########
##.....###
##.###...#
#....oI..#
#.xO#.o.##
##Ox#...##
##########

103
##########
##.....###
##.###...#
#...oI...#
#.xO#.o.##
##Ox#...##
##########

104
##########
##.....###
##.###...#
#..oI....#
#.xO#.o.##
##Ox#...##
##########

105
##########
##.....###
##.###...#
#.oI.....#
#.xO#.o.##
##Ox#...##
##########

106
##########
##.....###
##.###...#
#.o......#
#.xI#.o.##
##OO#...##
##########

107
##########
##.....###
##.###...#
#.I......#
#.Ox#.o.##
##OO#...##
##########

108
##########
##.....###
##.###...#
#........#
#.IO#.o.##
##OO#...##
##########

109
##########
##.....###
##.###...#
#.....o..#
#.xO#.I.##
##OO#...##
##########

110
##########
##.....###
##.###...#
#....oI..#
#.xO#...##
##OO#...##
##########

111
##########
##.....###
##.###...#
#...oI...#
#.xO#...##
##OO#...##
##########

112
##########
##.....###
##.###...#
#..oI....#
#.xO#...##
##OO#...##
##########

113
##########
##.....###
##.###...#
#.oI.....#
#.xO#...##
##OO#...##
##########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.in
================================================
13 11
###########
########I.#
########..#
####......#
#...x###.##
#.#.#....##
#.#.o.o#x.#
#.#..O..#.#
#.x#o.o.#.#
##....#.#.#
##.###x...#
##.....####
###########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.out
================================================


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.sol
================================================
107
###########
########..#
########..#
####......#
#...x###.##
#.#.#....##
#.#oI.o#x.#
#.#..O..#.#
#.x#o.o.#.#
##....#.#.#
##.###x...#
##.....####
###########

108
###########
########..#
########..#
####......#
#...x###.##
#.#.#....##
#.#o..o#x.#
#.#..O..#.#
#.x#I.o.#.#
##..o.#.#.#
##.###x...#
##.....####
###########

109
###########
########..#
########..#
####......#
#...x###.##
#.#.#....##
#.#o..o#x.#
#.#..O..#.#
#.x#..o.#.#
##.oI.#.#.#
##.###x...#
##.....####
###########

110
###########
########..#
########..#
####......#
#...x###.##
#.#o#....##
#.#I..o#x.#
#.#..O..#.#
#.x#..o.#.#
##.o..#.#.#
##.###x...#
##.....####
###########

111
###########
########..#
########..#
####......#
#..ox###.##
#.#I#....##
#.#...o#x.#
#.#..O..#.#
#.x#..o.#.#
##.o..#.#.#
##.###x...#
##.....####
###########

112
###########
########..#
########..#
####......#
#..ox###.##
#.#.#....##
#.#...o#x.#
#.#..I..#.#
#.x#.oo.#.#
##.o..#.#.#
##.###x...#
##.....####
###########

113
###########
########..#
########..#
####......#
#..IO###.##
#.#.#....##
#.#...o#x.#
#.#..x..#.#
#.x#.oo.#.#
##.o..#.#.#
##.###x...#
##.....####
###########

114
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..x..#.#
#.x#.oo.#.#
##oI..#.#.#
##.###x...#
##.....####
###########

115
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..x..#.#
#.O#.oo.#.#
##I...#.#.#
##.###x...#
##.....####
###########

116
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..O..#.#
#.O#.Io.#.#
##....#.#.#
##.###x...#
##.....####
###########

117
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..O..#.#
#.O#..Io#.#
##....#.#.#
##.###x...#
##.....####
###########

118
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..O..#.#
#.O#...I#.#
##....#o#.#
##.###x...#
##.....####
###########

119
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..O..#.#
#.O#....#.#
##....#I#.#
##.###xo..#
##.....####
###########

120
###########
########..#
########..#
####......#
#...O###.##
#.#.#....##
#.#...o#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###OI..#
##.....####
###########

121
###########
########..#
########..#
####......#
#...O###.##
#.#.#.o..##
#.#...I#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

122
###########
########..#
########..#
####......#
#...O###.##
#.#.#.Io.##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

123
###########
########..#
########..#
####......#
#...O###.##
#.#.#..Io##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

124
###########
########..#
########..#
####......#
#...O###o##
#.#.#...I##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

125
###########
########..#
########..#
####....o.#
#...O###I##
#.#.#....##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

126
###########
########..#
########o.#
####....I.#
#...O###.##
#.#.#....##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

127
###########
########..#
########I.#
####....o.#
#...O###.##
#.#.#....##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

128
###########
########..#
########..#
####....I.#
#...O###o##
#.#.#....##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########

129
###########
########..#
########..#
####......#
#...O###I##
#.#.#...o##
#.#....#x.#
#.#..O..#.#
#.O#....#.#
##....#.#.#
##.###O...#
##.....####
###########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.in
================================================
8 9
#########
###..#.I#
##...#..#
##o.o.o.#
##.o##..#
##.o.#.##
xxxxx..##
#########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.sol
================================================
50
#########
###..#..#
##...#..#
##o.o.o.#
##.o##..#
##oI.#.##
xxxxx..##
#########

51
#########
###..#..#
##...#..#
##ooo.o.#
##.I##..#
##o..#.##
xxxxx..##
#########

52
#########
###..#..#
##.o.#..#
##oIo.o.#
##..##..#
##o..#.##
xxxxx..##
#########

53
#########
###..#..#
##.o.#..#
##o.Ioo.#
##..##..#
##o..#.##
xxxxx..##
#########

54
#########
###..#..#
##.I.#..#
##oo.oo.#
##..##..#
##o..#.##
xxxxx..##
#########

55
#########
###..#..#
##...#..#
##oI.oo.#
##.o##..#
##o..#.##
xxxxx..##
#########

56
#########
###..#..#
##...#..#
##o..oo.#
##.I##..#
##oo.#.##
xxxxx..##
#########

57
#########
###..#..#
##...#..#
##o..oo.#
##..##..#
##oI.#.##
xxxOx..##
#########

58
#########
###..#..#
##...#..#
##o..oo.#
##..##..#
##o..#.##
xxOIx..##
#########

59
#########
###..#..#
##...#..#
##o..oo.#
##..##..#
##o..#.##
xOIxx..##
#########

60
#########
###..#..#
##...#..#
##o..oo.#
##..##..#
##o..#.##
OIxxx..##
#########

61
#########
###..#..#
##...#..#
##o..oo.#
##..##..#
##I..#.##
OxOxx..##
#########

62
#########
###..#..#
##...#..#
##o..oo.#
##..##..#
##...#.##
OOIxx..##
#########

63
#########
###..#..#
##...#o.#
##o..oI.#
##..##..#
##...#.##
OOxxx..##
#########

64
#########
###..#..#
##...#o.#
##o.oI..#
##..##..#
##...#.##
OOxxx..##
#########

65
#########
###..#..#
##...#o.#
##ooI...#
##..##..#
##...#.##
OOxxx..##
#########

66
#########
###..#..#
##...#o.#
##oI....#
##.o##..#
##...#.##
OOxxx..##
#########

67
#########
###..#..#
##...#o.#
##o.....#
##.I##..#
##.o.#.##
OOxxx..##
#########

68
#########
###..#..#
##...#o.#
##o.....#
##..##..#
##.I.#.##
OOxOx..##
#########

69
#########
###..#..#
##...#o.#
##o.....#
##..##..#
##...#.##
OOxIO..##
#########

70
#########
###..#..#
##...#I.#
##o...o.#
##..##..#
##...#.##
OOxxO..##
#########

71
#########
###..#..#
##...#..#
##o..oI.#
##..##..#
##...#.##
OOxxO..##
#########

72
#########
###..#..#
##...#..#
##o.oI..#
##..##..#
##...#.##
OOxxO..##
#########

73
#########
###..#..#
##...#..#
##ooI...#
##..##..#
##...#.##
OOxxO..##
#########

74
#########
###..#..#
##...#..#
##oI....#
##.o##..#
##...#.##
OOxxO..##
#########

75
#########
###..#..#
##...#..#
##o.....#
##.I##..#
##.o.#.##
OOxxO..##
#########

76
#########
###..#..#
##...#..#
##o.....#
##..##..#
##.I.#.##
OOxOO..##
#########

77
#########
###..#..#
##...#..#
##I.....#
##o.##..#
##...#.##
OOxOO..##
#########

78
#########
###..#..#
##...#..#
##......#
##I.##..#
##o..#.##
OOxOO..##
#########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.in
================================================
7 10
##########
####....##
##x.o##.##
#xxo.o..I#
#xx.o.o.##
#####...##
##########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.sol
================================================
29
##########
####....##
##x.o##.##
#xxooI...#
#xx.o.o.##
#####...##
##########

30
##########
####....##
##x.o##.##
#xxoo....#
#xxoI.o.##
#####...##
##########

31
##########
####....##
##x.o##.##
#xxoo....#
#xOI..o.##
#####...##
##########

32
##########
####....##
##xoo##.##
#xxIo....#
#xO...o.##
#####...##
##########

33
##########
####....##
##xoo##.##
#xx.o....#
#OI...o.##
#####...##
##########

34
##########
####....##
##xoo##.##
#xxoI....#
#Ox...o.##
#####...##
##########

35
##########
####....##
##xoo##.##
#xOI.....#
#Ox...o.##
#####...##
##########

36
##########
####....##
##xoI##.##
#xO.o....#
#Ox...o.##
#####...##
##########

37
##########
####....##
##OI.##.##
#xO.o....#
#Ox...o.##
#####...##
##########

38
##########
####....##
##O..##.##
#OI.o....#
#Ox...o.##
#####...##
##########

39
##########
####....##
##O..##.##
#OxoI....#
#Ox...o.##
#####...##
##########

40
##########
####....##
##O..##.##
#OOI.....#
#Ox...o.##
#####...##
##########

41
##########
####....##
##O..##.##
#OO......#
#Ox..oI.##
#####...##
##########

42
##########
####....##
##O..##.##
#OO......#
#Ox.oI..##
#####...##
##########

43
##########
####....##
##O..##.##
#OO......#
#OxoI...##
#####...##
##########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.in
================================================
9 11
###########
##..##...##
##...o...##
##o.###.o##
##.#xxx#.##
##.#xxx#.##
#.o..o..o.#
#.....#.I.#
###########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.sol
================================================
130
###########
##..##...##
##...o...##
##o.###.o##
##.#xxx#.##
##.#xOx#.##
#.o..I..o.#
#.....#...#
###########

131
###########
##..##...##
##...o...##
##o.###.o##
##.#xxx#.##
##.#xIO#.##
#.o.....o.#
#.....#...#
###########

132
###########
##..##...##
##...o...##
##o.###.o##
##.#xxx#.##
##.#xxO#.##
#.o....oI.#
#.....#...#
###########

133
###########
##..##...##
##...o...##
##o.###.o##
##.#xxx#.##
##.#xxO#.##
#.o...oI..#
#.....#...#
###########

134
###########
##..##...##
##...o...##
##o.###.o##
##.#xxx#.##
##.#xxO#.##
#.o..oI...#
#.....#...#
###########

135
###########
##..##...##
##...o...##
##o.###.o##
##.#xxO#.##
##.#xxI#.##
#.o..o....#
#.....#...#
###########

136
###########
##..##...##
##...o...##
##o.###.o##
##.#xxO#.##
##.#xxx#.##
#.Io.o....#
#.....#...#
###########

137
###########
##..##...##
##o..o...##
##I.###.o##
##.#xxO#.##
##.#xxx#.##
#..o.o....#
#.....#...#
###########

138
###########
##..##...##
##o..Io..##
##..###.o##
##.#xxO#.##
##.#xxx#.##
#..o.o....#
#.....#...#
###########

139
###########
##..##...##
##o...Io.##
##..###.o##
##.#xxO#.##
##.#xxx#.##
#..o.o....#
#.....#...#
###########

140
###########
##..##...##
##o....o.##
##..###.I##
##.#xxO#o##
##.#xxx#.##
#..o.o....#
#.....#...#
###########

141
###########
##..##...##
##o....o.##
##..###..##
##.#xxO#I##
##.#xxx#o##
#..o.o....#
#.....#...#
###########

142
###########
##..##...##
##o....o.##
##..###..##
##.#xxO#.##
##.#xxx#I##
#..o.o..o.#
#.....#...#
###########

143
###########
##..##...##
##o....Io##
##..###..##
##.#xxO#.##
##.#xxx#.##
#..o.o..o.#
#.....#...#
###########

144
###########
##..##...##
##o.....o##
##..###..##
##.#xxO#.##
##.#xxx#.##
#..Ioo..o.#
#.....#...#
###########

145
###########
##..##...##
##o.....o##
##..###..##
##.#xxO#.##
##.#Oxx#.##
#...Io..o.#
#.....#...#
###########

146
###########
##..##...##
##o.....o##
##..###..##
##.#xxO#.##
##.#OOx#.##
#....I..o.#
#.....#...#
###########

147
###########
##..##...##
##o.....o##
##..###..##
##.#OxO#.##
##.#IOx#.##
#.......o.#
#.....#...#
###########

148
###########
##..##...##
##o.....o##
##..###..##
##.#OxO#.##
##.#xIO#.##
#.......o.#
#.....#...#
###########

149
###########
##..##...##
##o.....o##
##..###..##
##.#OxO#.##
##.#xxO#.##
#......oI.#
#.....#...#
###########

150
###########
##..##...##
##o.....o##
##..###..##
##.#OxO#.##
##.#xxO#.##
#.....oI..#
#.....#...#
###########

151
###########
##..##...##
##o.....o##
##..###..##
##.#OxO#.##
##.#xxO#.##
#....oI...#
#.....#...#
###########

152
###########
##..##...##
##o.....I##
##..###.o##
##.#OxO#.##
##.#xxO#.##
#....o....#
#.....#...#
###########

153
###########
##..##...##
##o......##
##..###.I##
##.#OxO#o##
##.#xxO#.##
#....o....#
#.....#...#
###########

154
###########
##..##...##
##o......##
##..###..##
##.#OxO#I##
##.#xxO#o##
#....o....#
#.....#...#
###########

155
###########
##..##...##
##o......##
##..###..##
##.#OxO#.##
##.#xxO#I##
#....o..o.#
#.....#...#
###########

156
###########
##..##...##
##o......##
##..###..##
##.#OxO#.##
##.#xOO#.##
#....I..o.#
#.....#...#
###########

157
###########
##..##...##
##o......##
##..###..##
##.#OxO#.##
##.#xOO#.##
#......oI.#
#.....#...#
###########

158
###########
##..##...##
##I......##
##o.###..##
##.#OxO#.##
##.#xOO#.##
#......o..#
#.....#...#
###########

159
###########
##..##...##
##.......##
##I.###..##
##o#OxO#.##
##.#xOO#.##
#......o..#
#.....#...#
###########

160
###########
##..##...##
##.......##
##..###..##
##I#OxO#.##
##o#xOO#.##
#......o..#
#.....#...#
###########

161
###########
##..##...##
##.......##
##..###..##
##.#OxO#.##
##I#xOO#.##
#.o....o..#
#.....#...#
###########

162
###########
##..##...##
##.......##
##..###..##
##.#OxO#.##
##.#xOO#.##
#.o...oI..#
#.....#...#
###########

163
###########
##..##...##
##.......##
##..###..##
##.#OxO#.##
##.#xOO#.##
#.o..oI...#
#.....#...#
###########

164
###########
##..##...##
##.......##
##..###..##
##.#OxO#.##
##.#xOO#.##
#.o.oI....#
#.....#...#
###########

165
###########
##..##...##
##.......##
##..###..##
##.#OOO#.##
##.#xIO#.##
#.o.o.....#
#.....#...#
###########

166
###########
##..##...##
##.......##
##..###..##
##.#OOO#.##
##.#OxO#.##
#.o.I.....#
#.....#...#
###########

167
###########
##..##...##
##.......##
##..###..##
##.#OOO#.##
##.#OxO#.##
#.Io......#
#.....#...#
###########

168
###########
##..##...##
##.......##
##..###..##
##.#OOO#.##
##.#OxO#.##
#..Io.....#
#.....#...#
###########

169
###########
##..##...##
##.......##
##..###..##
##.#OOO#.##
##.#OxO#.##
#...Io....#
#.....#...#
###########



================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.in
================================================
7 8
########
#..#...#
#.oxxo.#
#IoxO.##
#.oxxo.#
#..#...#
########


================================================
FILE: other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.sol
================================================
41
########
#..#...#
#.IOxo.#
#.oxO.##
#.oxxo.#
#..#...#
########

42
########
#..#...#
#..Oxo.#
#.oxO.##
#.IOxo.#
#..#...#
########

43
########
#..#...#
#.oOxo.#
#.IxO.##
#..Oxo.#
#..#...#
########

44
########
#..#...#
#.oOxo.#
#..xIo##
#..Oxo.#
#..#...#
########

45
########
#..#...#
#.oOxo.#
#..xxo##
#.oIxo.#
#..#...#
########

46
########
#..#...#
#.oOxo.#
#..xxo##
#.oxOI.#
#..#...#
########

47
########
#..#...#
#.oOxo.#
#..xxo##
#.oOI..#
#..#...#
########

48
########
#..#...#
#.oOOI.#
#..xxo##
#.oOx..#
#..#...#
########

49
########
#..#...#
#.oOO..#
#..xxI##
#.oOxo.#
#..#...#
########

50
########
#..#...#
#.oOO..#
#..xx.##
#.oOOI.#
#..#...#
########

51
########
#..#...#
#.IOO..#
#.oxx.##
#.oOO..#
#..#...#
########

52
########
#..#...#
#..OO..#
#.IOx.##
#.oOO..#
#..#...#
########

53
########
#..#...#
#..OO..#
#..IO.##
#.oOO..#
#..#...#
########

54
########
#..#...#
#..OO..#
#.oxO.##
#.IOO..#
#..#...#
########



================================================
FILE: other-languages/ai/sudoku/sudoku.cpp
================================================
/*
# -*- coding: utf-8 -*-

"""
Backtracking e Heurísticas aplicadas para se resolver um sudoku.
A busca é feita no grafo de estados do problema
Autores: 
    ? 
Colaborador:
 	Péricles Lopes Machado [gogo40] (pericles.raskolnikoff.gmail.com)
Tipo: 
    search
Descrição: 
    Sudokus são problema NP-difíceis, por isso na maior parte
do tempo procuramos heurísticas que acelerem a busca. Nesse código
são implementadas algumas heurísticas humanas, como limitar as opções
de jogada em cada estado usando as regras do jogo.
	Existe uma solução mais eficiente utilizando-se o algoritmo X[5].
Futuramente, planejo implementar essa outra abordagem. Este código
é apenas um exemplo de como heurísticas podem acelerar a busca de uma solução de sudoku.

Complexidade: 
    O(2^N)
Dificuldade: 
    Difícil
Referências:
    [1] http://en.wikipedia.org/wiki/Backtracking
    [2] http://en.wikipedia.org/wiki/Heuristic
	[3] http://falapericles.blogspot.com.br/2009/05/grafo-de-estados-e-suas-aplicacoes.html
	[4] http://webdocs.cs.ualberta.ca/~games/Sokoban/
	[5] http://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X
"""
*/


/*
Para testar o código pode-se utilizar o seguinte problema do SPOJ brasil:

http://br.spoj.com/problems/BSUDO/

Ou digitar no terminal a seguinte entrada (test_001.in):
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

O '0' representa uma posição vaga na grade

Este algoritmo é bem eficiente para o caso 9x9, mas para o caso 16x16 ainda é preciso melhorias.
O algoritmo X do Knuth é mais eficiente, mas é um pouco mais complexo.
*/
#include <stdio.h>

#define INF 500

using namespace std;


/*vetor de palavras com tamanho menor que 32 bits**/
typedef long long lint;
typedef unsigned long long ulint;

/*Esta estrtura representa um nó no grafo de estados do problema*/
struct V{
	//tam_word=9  NMAX=20;
	//n_words=64/9 numero de palavras por chunck
	
	int n_words, nbits, MASK;
	
	ulint v[6];
	ulint mask;
	
	V(int n_words=5,int nbits=10, int MASK=1023)
	:n_words(n_words),nbits(nbits),mask(MASK){
		for(int i=0;i<6;i++) v[i]=0;
	}
	
	V(const V& b){
		n_words=b.n_words; nbits=b.nbits;
		MASK=b.MASK; mask=b.mask;
		for(int i=0;i<6;i++) v[i]=b.v[i];
	}
	
	inline
	void insert(int p, ulint V){
		int i;
		
		i=p/n_words;
		p=p%n_words;
		
		p*=nbits;
		
		v[i]=(v[i]^(v[i] & (mask<<p))) | (V<<p);
	}
	
	inline
	int get(int p){
		int i;
		
		i=p/n_words;
		p=p%n_words;
		p*=nbits;
		
		return (int)((v[i]>>p)&mask);
	}
	
	V& operator=(const V& b){
		n_words=b.n_words; nbits=b.nbits;
		MASK=b.MASK;  mask=b.mask;
		for(int i=0;i<6;i++) v[i]=b.v[i];
		return *this;
	}

};

/****************************/


//Armazena estado anterior
struct st{
	V s, pl, pc, ps;//estado anterior
	int le, x, y;//ultima escolha e posicao onde ocorreu
	
	st():s(16,4,15),pl(),pc(),ps(),le(1),x(0),y(0){}
	
	st(const V& s, const V& pl, const V& pc, const V& ps, int le=1, int x=0, int y=0)
	:s(s),pl(pl),pc(pc),ps(ps),le(le),x(x),y(y){}
	
	st& operator=(const st& a){
		s=a.s; pl=a.pl; pc=a.pc; ps=a.ps;
		le=a.le; x=a.x; y=a.y;
		return *this;
	}
};


/*Pilha de estados*/
static st Q[81];
int ip;
static int hel[10];
static int lg[1<<10];
static int ones[1<<10];
static const ulint inf=~(0LL);

// Imprime solução
inline
void print(V& sol)
{
	int i, j;
	for(i=0;i<9;i++){
		for(j=0;j<9;j++) printf("%d",sol.get(i*9+j));
		printf("\n");
	}
}

/*Função de backtracking que explora a arvore de possibilidades do jogo*/

bool solve(V& s){
	V podeLin, podeCol, podeSet;
	int i, j, x, y, a, b, set;
	int px, py, mi, l, ns;
	bool ok;

	/*Inicializa opções para cada linha coluna e setor*/
	for(i=0;i<2;i++) podeCol.v[i]=podeSet.v[i]=podeLin.v[i]=inf;
	
	ok=true;
	ip=0;
	int np=0;
	for(;;){
	
		//Verifica se já resolvi o sudoku s
		//print(s);
		init:
		np++;
		//Caso não foi possível realizar uma jogada na iteração anterior desempilha-se um estado da pilha
		if(!ok)
			for(;;){
				ip--;
				
				/*Se já tentei todas opções da pilha e mesmo assim não resolvi o sudoku, 
				então o sudoku não tem solução*/
				if(ip==-1) return false;
				else{
					/*Desempilho um ramo que 
					pode conter uma solução*/
					s=Q[ip].s;
					/*Recupero opções pra linha, coluna e setor*/
					podeLin=Q[ip].pl; podeCol=Q[ip].pc; podeSet=Q[ip].ps;

					/*Posição de referencia utilizada para fazer a busca*/
					px=i=Q[ip].x; py=j=Q[ip].y;
					
					a=(i/3); b=(j/3); set=a*3+b;
					y=podeLin.get(i); y&=podeCol.get(j); y&=podeSet.get(set); 
					
					for(i=Q[ip].le+1;i<10;i++)
						if((y>>i)&0x1){
							/*Empilho opções restantes*/
							Q[ip]=st(s,podeLin,podeCol,podeSet,i,px,py);
							ip++;
							s.insert(px*9+py,i);
							goto cont;//Preciso sair desse mais aninhado
						}
				}
			}
		
		cont:
		
		//Realiza travas  e procura posições que tem opcoes unicas
		ns=0;
		for(i=0;i<9;i++)
			for(j=0;j<9;j++){
				x=s.get(i*9+j);
				a=(i/3); b=(j/3); set=a*3+b;
					
				if(x>0){
					ns++;
					//Atualiza opções pra linha
					y=podeLin.get(i); y&=hel[x]; podeLin.insert(i,y);
					//Atualiza opções pra coluna
					y=podeCol.get(j); y&=hel[x]; podeCol.insert(j,y);
					//Atualiza opções pro setor
					y=podeSet.get(set); y&=hel[x]; podeSet.insert(set,y);
				}
			}
		
		/*Caso eu já tenha preenchido todas 81 casas, então eu resolvi o sudoku*/
		if(ns==81){ print(s);  return true; }
		
		/* Atualiza opções para cada linha e coluna*/
		mi=INF; ok=false;
		for(i=0;i<9;i++)
			for(j=0;j<9;j++){	
				x=s.get(i*9+j);
				a=(i/3); b=(j/3); set=a*3+b;
					
				if(x==0){
					y=podeLin.get(i); y&=podeCol.get(j); y&=podeSet.get(set); 
					x=lg[y];
					if(x>0){
						/*Insere possivel valor pra posição i, j da grade*/
						s.insert(i*9+j,x);
						/*bloqueia x como opção para linha i, coluna j e setor set*/
						y=podeLin.get(i); y&=hel[x]; podeLin.insert(i,y);
						y=podeCol.get(j); y&=hel[x]; podeCol.insert(j,y);
						y=podeSet.get(set); y&=hel[x]; podeSet.insert(set,y);
						ok=true;
					}else if(y==0)  goto init; 
					else{
						/*opções pra pra posição i, j*/
						x=ones[y]; 
						if(x<mi){ mi=x; l=y; px=i; py=j; }
					}
				}
			}
		
		/*Caso não foi possível realizar um movimento nesse laço empilha-se todas opções
		disponíveis e tenta-se qual delas gera uma solução válida*/
		if(!ok){
			i=px; j=py; a=(i/3); b=(j/3); set=a*3+b;
			y=podeLin.get(i); y&=podeCol.get(j); y&=podeSet.get(set); 
			
			for(i=1;i<10;i++)
				if((y>>i)&0x1){
					Q[ip]=st(s,podeLin,podeCol,podeSet,i,px,py);
					ip++;
					s.insert(px*9+py,i);
					ok=true;
					break;
				}
		}
	}
}

//*********************************************************//
//MAIN
//*********************************************************//

/*Verifica é possivel resolver a grade*/
bool find_error(V& s){
	for(int n=1;n<10;n++){
		int noc;
		for(int i=0;i<9;i++){
			noc=0;
			for(int j=0;j<9;j++)
				if(s.get(i*9+j)==n) noc++;
			if(noc>1) return false;
		}
		
		for(int i=0;i<9;i++){
			noc=0;
			for(int j=0;j<9;j++)
				if(s.get(j*9+i)==n) noc++;
			if(noc>1) return false;
		}
		
		for(int i=0;i<3;i++){
			int lm=3*(i+1);
			int auxI=3*i;
			
			for(int j=0;j<3;j++){
				int lp=3*(j+1);
				noc=0;
				
				for(int m=auxI;m<lm;m++)
					for(int p=3*j;p<lp;p++){
						int x=s.get(m*9+p);
						if(x==n) noc++;
					}
				if(noc>1) return false;
			}	
		}
		
	}
	return true;
}

int main()
{
	int N, x, i, j, len, m,c;
	V s(16,4,15);
	
	len=1<<10; m=len-1;
	for(i=0;i<len;i++) {
		lg[i]=-1;
		x=0;
		for(j=0;j<10;j++)
			if(i>>j & 0x1)x++;
		ones[i]=x;
	}
	
	for(i=0;i<10;i++)  { 
		lg[1<<i]=i;
		hel[i]=m-(1<<i);
		if(i>0) hel[i]--;
	}
	
	c=1;
	scanf("%d",&N);
	while(N--){
		for(i=0;i<9;i++)
			for(j=0;j<9;j++){
				scanf("%1d",&x);
				s.insert(i*9+j,x);
			}
		
		if(!find_error(s)) printf("Could not complete this grid.\n");
		else if(!solve(s)) printf("Could not complete this grid.\n");
		c++;
	}
	return 0;
}





================================================
FILE: other-languages/ai/sudoku/test_001.in
================================================
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107



================================================
FILE: other-languages/array/merge/merge.rb
================================================

=begin
  Merge
Autor:
    ?
Colaborador:
    José Alberto O. Morais Filho (j.moraisg12@gmail.com)
Tipo:
    array-operations
Descrição:
    Combina dois subvetores (ordernados), gerando um vetor ordenado
Complexidade:
    O(n)
Dificuldade:
    médio
Referências:
   [1] Cormem, Thomas H. Introduction to Algorithms, 3rd Edition. (Páginas 29-34)
=end

def merge(array, left, mid, right)
  n1 = mid - left + 1
  n2 = right - mid

  l = Array.new(n1 + 1) {0}
  r = Array.new(n2 + 1) {0}

  for i in 0...n1 do
    l[i] = array[left + i]
  end

  for j in 1..n2 do
    r[j - 1] = array[mid + j]
  end

  l[n1] = 999999
  r[n2] = 999999

  i = 0
  j = 0

  for k in left..right do
    if l[i] <= r[j]
      array[k] = l[i]
      i += 1
    else
      array[k] = r[j]
      j += 1
    end
  end
end

# Exemplos

a = [5, 6, 7, 8, 9, 1, 2, 3, 4]
merge(a, 0, 4, 8)
print a

puts

b = [1, 3, 5, 7, 2, 4, 6, 8]
merge(b, 0, 3, 7)
print b = right - mid

  l = Array.new(n1 + 1) {0}
  r = Array.new(n2 + 1) {0}

  for i in 0...n1 do

================================================
FILE: other-languages/array/partition/partition.rb
================================================

=begin
  Partition
Autor:
    ?
Colaborador:
    José Alberto O. Morais Filho (j.moraisg12@gmail.com)
Tipo:
    array-operations
Descrição:
    Reposiciona os valores de um array de tal forma que todos os elementos da esquerda do pivô (ultimo elemento) sejam
  menores que ele e os da direita sejam maiores.
Complexidade:
    O(n)
Dificuldade:
    médio
Referências:
   [1] Cormem, Thomas H. Introduction to Algorithms, 3rd Edition. (Páginas 171-172)
=end

# Entrada:
#   array = um vetor a ser reposicionado;
#   left = primeira posição do vetor (ou subvetor);
#   right = última posição do vetor (ou subvetor);
# Saída:
#   A posição do pivô no novo vetor

def partition(array, left, right)
  x = array[right]
  i = left - 1

  for j in left...right do
    if array[j] <= x then
      i += 1
      array[i], array[j] = array[j], array[i]
    end
  end

  array[i + 1], array[right] = array[right], array[i + 1]

  i + 1

end

# Exemplos
a = [2, 8, 7, 1, 3, 5, 6, 4]
b = [3, 1, 2, 6, 7, 4, 5]

print(partition a, 0, 7)
puts
print(partition b, 0, 6)or (ou subvetor);
#   right = última posição do vetor (ou subvetor);
# Saída:
#   A posição do pivô no novo vetor

def partition(array, left, right)
  x = array[right]
  i = left - 1

  for j in left...right do
    if array[j] <= x then
      i += 1
      array[i], array[j] = array[j], array[i]
    end
  end

  array[i + 1], array[right] = array[right], array[i + 1]

  i + 1

end

# Exemplos
a = [2, 8, 7, 1, 3, 5, 6, 4]
b = [3, 1, 2, 6, 7, 4, 5]

print(partit

================================================
FILE: other-languages/bitwise/BitScanForwardDebruijn64.cs
================================================
//BitScanForward com De Bruijn (64 bits)
//Autor:
//    Juan Lopes <juanplopes@gmail.com>
//Tipo:
//    bitwise
//Descrio:
//    Encontra o ndice do LSB (Least Significant Bit) em O(1)
//Complexidade:  
//    Pior caso: O(1)
//    Melhor caso: O(1)
//Dificuldade:
//    facil
//Referncias:
//    http://en.wikipedia.org/wiki/De_Bruijn_sequence

using System;

namespace BitScanForwardDebruijn64
{
    class Program
    {
        static int[] index64 = new[] 
        {
           63,  0, 58,  1, 59, 47, 53,  2,
           60, 39, 48, 27, 54, 33, 42,  3,
           61, 51, 37, 40, 49, 18, 28, 20,
           55, 30, 34, 11, 43, 14, 22,  4,
           62, 57, 46, 52, 38, 26, 32, 41,
           50, 36, 17, 19, 29, 10, 13, 21,
           56, 45, 25, 31, 35, 16,  9, 12,
           44, 24, 15,  8, 23,  7,  6,  5
        };

        public static int BitScanForward(ulong value)
        {
            if (value == 0) return -1;
            const ulong debruijn64 = 0x07EDD5E59A4E28C2ul;
            return index64[((value & (~value + 1)) * debruijn64) >> 58];
        }

        static void Main(string[] args)
        {
            Console.WriteLine(BitScanForward(128));
        }
    }
}


================================================
FILE: other-languages/bitwise/HammingWeight64.cs
================================================
//Hamming Weight (64 bits)
//Autor:
//    Juan Lopes <juanplopes@gmail.com>
//Tipo:
//    bitwise
//Descrio:
//    Conta o nmero de bits ligados
//    em um inteiro de 64 bits.
//Complexidade:  
//    Pior caso: O(1)
//    Melhor caso: O(1)
//Dificuldade:
//    facil
//Referncias:
//    http://en.wikipedia.org/wiki/Hamming_weight

using System;

namespace HammingWeight64
{
    class Program
    {
        public static int PopCount(ulong x)
        {
            unchecked
            {
                const ulong h01 = 0x0101010101010101;
                const ulong m1 = 0x5555555555555555;
                const ulong m2 = 0x3333333333333333;
                const ulong m4 = 0x0f0f0f0f0f0f0f0f;

                x -= (x >> 1) & m1;
                x = (x & m2) + ((x >> 2) & m2);
                x = (x + (x >> 4)) & m4;
                return (int)((x * h01) >> 56);
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine(PopCount(128));
        }
    }
}


================================================
FILE: other-languages/bitwise/bsf-debruijn/BitScanForwardDebruijn64.cs
================================================
//BitScanForward com De Bruijn (64 bits)
//Autor:
//     Nicolaas Govert de Bruijn
//Tipo:
//    bitwise
//Descrio:
//    Encontra o ndice do LSB (Least Significant Bit) em O(1)
//Complexidade:  
//    O(1)
//Dificuldade:
//    facil
//Referncias:
//    http://en.wikipedia.org/wiki/De_Bruijn_sequence

using System;

namespace BitScanForwardDebruijn64
{
    class Program
    {
        static int[] index64 = new[] 
        {
           63,  0, 58,  1, 59, 47, 53,  2,
           60, 39, 48, 27, 54, 33, 42,  3,
           61, 51, 37, 40, 49, 18, 28, 20,
           55, 30, 34, 11, 43, 14, 22,  4,
           62, 57, 46, 52, 38, 26, 32, 41,
           50, 36, 17, 19, 29, 10, 13, 21,
           56, 45, 25, 31, 35, 16,  9, 12,
           44, 24, 15,  8, 23,  7,  6,  5
        };

        public static int BitScanForward(ulong value)
        {
            if (value == 0) return -1;
            const ulong debruijn64 = 0x07EDD5E59A4E28C2ul;
            return index64[((value & (~value + 1)) * debruijn64) >> 58];
        }

        static void Main(string[] args)
        {
            Console.WriteLine(BitScanForward(128));
        }
    }
}


================================================
FILE: other-languages/bitwise/dec2hex/dec2hex.c
================================================
/*
Conversor Decimal/Hexadecimal
Autor:
    ?
Colaborador:
    Ramon Caldeira Faria (ramoncaldeira_328@hotmail.com)
Tipo:
    bitwise
Descrição:
    O algoritmo devolve uma string da representação
    hexadecimal de um determinado inteiro de 8 bits.
Complexidade:
    O(1)
Dificuldade:
    medio
*/

#include <stdlib.h>

const char* HEXA = "0123456789ABCDEF";

/* @param dec número no intervalo [0,255] */
char* decToHex(unsigned dec) {
   char* hexadecimal = (char*) calloc(3, sizeof(char));
   hexadecimal[0] = HEXA[ (dec & 0xF0) >> 4 ];
   hexadecimal[1] = HEXA[ dec & 0x0F ];
   hexadecimal[2] = '\0';
   return hexadecimal;   
}


================================================
FILE: other-languages/bitwise/hamming-weight/HammingWeight64.cs
================================================
//Hamming Weight (64 bits)
//Autor:
//    ?
//Tipo:
//    bitwise
//Descrio:
//    Conta o nmero de bits ligados
//    em um inteiro de 64 bits.
//Complexidade:  
//    O(1)
//Dificuldade:
//    facil
//Referncias:
//    http://en.wikipedia.org/wiki/Hamming_weight

using System;

namespace HammingWeight64
{
    class Program
    {
        public static int PopCount(ulong x)
        {
            unchecked
            {
                const ulong h01 = 0x0101010101010101;
                const ulong m1 = 0x5555555555555555;
                const ulong m2 = 0x3333333333333333;
                const ulong m4 = 0x0f0f0f0f0f0f0f0f;

                x -= (x >> 1) & m1;
                x = (x & m2) + ((x >> 2) & m2);
                x = (x + (x >> 4)) & m4;
                return (int)((x * h01) >> 56);
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine(PopCount(128));
        }
    }
}


================================================
FILE: other-languages/bitwise/operations/operations.cpp
================================================
/*
Operações bitwise
Autor:
    ?
Colaborador:
    Ramon Caldeira (ramoncaldeira_328@hotmail.com)
Tipo:
    bitwise
Descrição:
    Coletânea de algotitmos bitwise.
Complexidade:  
    O(1)
Dificuldade:
    fácil
*/

/* verifica se um número é par */
bool isOdd(int num) { return num & 1; }

/* verifica se um número é potência de 2
  ex: 16 = 10000(2)
      15 = 01111(2)
      => 16 & 15 = 10000 & 01111 = 0
 */
bool isPower2(int num) { return !(num-1 & num); }

/* permuta case de caractere 
   funcionamento: na tabela ASCII
   os caracteres minúsculos se diferenciam dos maiúsculos
   através do 5° bit = 32 = 20(H)
   ex: A(65) a(97) a - A = 32
*/
void toggleCase(char& ch) { ch ^= 0x20; }

/* seta case maiúsculo */
void toUpper(char& ch) { ch &= ~0x20; }

/* seta case minúsculo */
void toLower(char& ch) { ch |= 0x20; }


================================================
FILE: other-languages/bitwise/swap_xor/swap_xor.c
================================================
/*
Algoritimo de troca de variveis
Autor:
    ?
Colaborador:
    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hotmail.com)
Tipo:
    bitwise
Descrio:
    Algoritimo que tem objetivo de trocar os valores
	de duas variveis sem o uso de uma varivel temporria
	usando apenas o operdador boolean "ou exclusivo".
	Lembrando que esse algortimo s funciona se as variveis
	tiverem em locais diferentes na memria
Complexidade:
    O(1)
Dificuldade:
    fcil
Referncias:
	http://en.wikipedia.org/wiki/XOR_swap_algorithm
*/

#include <stdio.h>

void swap(int* a, int* b) {

	*a = *a ^ *b;
	*b = *a ^ *b;
	*a = *a ^ *b;
}

int main(int argc, char* argv[]) {

	int var1 = 22;
	int var2 = 4;
	printf("Valores antes da troca: var1=%d var2=%d\n", var1, var2);
	swap(&var1, &var2);
	printf("Valores depois da troca: var1=%d var2=%d\n", var1, var2);
	
	return 0;
}

================================================
FILE: other-languages/bitwise/swap_xor/swap_xor.cs
================================================
/*
Algoritimo de troca de variveis
Autor:
    ?
Colaborador:
    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hotmail.com)
Tipo:
    bitwise
Descrio:
    Algoritimo que tem objetivo de trocar os valores
	de duas variveis sem o uso de uma varivel temporria
	usando apenas o operdador boolean "ou exclusivo".
	Lembrando que esse algortimo s funciona se as variveis
	tiverem em locais diferentes na memria
Complexidade:
    O(1)
Dificuldade:
    fcil
Referncias:
	http://en.wikipedia.org/wiki/XOR_swap_algorithm
*/

using System;

public sealed class SwapXor {

	public static void swap(ref int a, ref int b) {
	
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
	}
	
	public static void Main() {
	
		int var1 = 1234;
		int var2 = 5678;
		
		Console.WriteLine("Valores antes da troca: var1 = {0} var2 = {1}", var1, var2);
		SwapXor.swap(ref var1, ref var2);
		Console.WriteLine("Valores depois da troca: var1 = {0} var2 = {1}", var1, var2);
	}
}

================================================
FILE: other-languages/bitwise/swap_xor/swap_xor.php
================================================
<?php
/*
Algoritimo de troca de variveis
Autor:
    ?
Colaborador:
    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hotmail.com)
Tipo:
    bitwise
Descrio:
    Algoritimo que tem objetivo de trocar os valores
	de duas variveis sem o uso de uma varivel temporria
	usando apenas o operdador boolean "ou exclusivo".
	Lembrando que esse algortimo s funciona se as variveis
	tiverem em locais diferentes na memria
Complexidade:
    O(1)
Dificuldade:
    fcil
Referncias:
	http://en.wikipedia.org/wiki/XOR_swap_algorithm
*/

function swap(&$a, &$b) {

	$a = $a ^ $b;
	$b = $a ^ $b;
	$a = $a ^ $b;
}

$var1 = 1991;
$var2 = 1989;

echo "Valores antes da troca: \$var1=$var1 \$var2=$var2<br />";
swap($var1, $var2);
echo "Valores despois da troca: \$var1=$var1 \$var2=$var2<br />";
?>

================================================
FILE: other-languages/date/leap-year/leap-year.lisp
================================================
#|
Bissexto
Autor:
    ?
Colaborador
    Daniel Valio <valium97@mail.com>
Tipo:
    date
Complexidade:
    O(1)
Dificuldade:
    Facil
|#

(defun ano-bissexto-p (&optional (ano (nth-value 5 (get-decoded-time))))
  (and (= (mod ano 4) 0) (or (/= (mod ano 100) 0) (= (mod ano 400) 0))))
  

================================================
FILE: other-languages/date/leap-year/leap-year.php
================================================
<?php

/*
Bissexto
Autor:
    ?
Colaborador:
    Sérgio Mandrake <sergio_mandrake@yahoo.com.br>
Tipo:
    date
Descrição:
    Calcula os próximos anos bissextos
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Ano_bissexto#Calend.C3.A1rio_Gregoriano
*/

function bissexto($numAnos = 4) {
    $anoAtual = $anoFinal = date('Y');
    $anoFinal += $numAnos;
    
    $anos = array();
    for ($i = $anoAtual; $i <= $anoFinal; $i++) {
        if ($i % 4 == 0 and ($i % 100 or $i % 400 == 0)) {
            $anos[] = $i;
        }
    }
    
    return $anos;
}

$proxAnosBissexto = bissexto(100);
echo join(', ', $proxAnosBissexto);


================================================
FILE: other-languages/date/leap-year/leap-year.rb
================================================
=begin

Bissexto
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz . at . gmail . com>
Tipo:
    date
Descrição:
    Calcula os próximos anos bissextos
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Ano_bissexto#Calend.C3.A1rio_Gregoriano

=end

def anoBissexto(anos)
	anoAtual = Time.now.year
	proximoAno = anoAtual + anos
	bissextos = []
	(anoAtual..proximoAno).each do |ano|
		if (ano%4 == 0) && (ano % 100 != 0 || ano % 400 == 0)
			bissextos << ano
		end
	end
	bissextos
end

puts anoBissexto(100)



================================================
FILE: other-languages/economics/financiamento/financiamento.cs
================================================
/*
Financiamento
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz@gmail.com>
Tipo:
    ?
Descrição:
	Calcula o valor das parcelas do financiamneto
	baseado no capital inicial e taxa de juros
	de acordo na função Price
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Tabela_price#C.C3.A1lculo
*/


using System;

namespace financiamneto
{
	class MainClass
	{
		static public double financiamneto(double investimento, double juros, int periodo)
		{
			return (investimento*juros) / (1 - (1/Math.pow((1+juros),periodo));
		}
		
		public static void Main (string[] args)
		{
			Console.WriteLine (financiamneto(1000,0.03,4));
			Console.ReadKey();
		}
	}
}


================================================
FILE: other-languages/economics/financiamento/financiamento.lisp
================================================
#|
Financiamento
Autor:
    ?
Colaborador:
    Daniel Valio <valium97@mail.com>
Tipo:
    economics
Descricao:
    Calcula o valor das parcelas do financiamento
    baseado no capital inicial e taxa de juros
    de acordo com a funcao Price
Complexidade:
    ?
Dificuldade:
    Facil
|#

(defun valor-parcela (capital juros periodo)
  (/ (* capital juros) (- 1 (/ 1 (expt (1+ juros) periodo)))))

================================================
FILE: other-languages/economics/financiamento/financiamento.php
================================================
<?php
/**
Financiamento
Autor:
    Bruno Lara Tavares <bruno.exz@gmail.com>
Colaborador:
    Felipe Djinn <felipe@felipedjinn.com.br>
Tipo:
    econimics
Descrição:
	Calcula o valor das parcelas do financiamneto
	baseado no capital inicial e taxa de juros
	de acordo na função Price
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Tabela_price#C.C3.A1lculo
*/
function financiamento($investimento, $juros, $periodo) {
    return ($investimento * $juros) / (1 - (1 / pow((1 + $juros), $periodo)));
}

echo financiamento(1000, 0.03, 4), "\n";


================================================
FILE: other-languages/economics/financiamento/financiamento.rb
================================================
# -*- encoding: utf-8 -*-

=begin
Financiamento
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz@gmail.com>
Tipo:
    ?
Descrição:
	Calcula o valor das parcelas do financiamneto
	baseado no capital inicial e taxa de juros
	de acordo na função Price
Complexidade:
    ?
Dificuldade:
    facil
Referências:
    http://pt.wikipedia.org/wiki/Tabela_price#C.C3.A1lculo
=end

def parcelas(investimento, juros, periodo)
	(investimento*juros) / (1 - (1/(1+juros)**periodo))
end
	
puts parcelas(1000, 0.03, 4)


================================================
FILE: other-languages/economics/juros-compostos/juros-compostos.lisp
================================================
#|
Calculo de juros compostos
Autor:
    ?
Colaborador:
    Daniel Valio <valium97@mail.com>
Tipo:
    economics
Descricao:
    Varias formas de se calcular varias modalidades de
    juros compostos.
Complexidade:
    O(1)
Dificulade:
    Facil
|#

;;;; Nota: os juros sao colocados em fracoes decimais,
;;;; e nao porcentagens.

(defun juros-compostos-continuos (capital juros tempo)
  (* capital (exp (* juros tempo))))


================================================
FILE: other-languages/geography/haversine/haversine.rb
================================================
# -*- encoding: utf-8 -*-
=begin
Haversine
Autor:
    ?
Colaborador:
    Bruno Lara Tavares <bruno.exz . at . gmail . com>
Tipo:
    geography
Descrição:
    Calcula a distancia mais curta
    entre dois pontos com latitude e longitude
    na superficie da Terra
    usando a formula de haversine
Complexidade:
    ?
Dificuldade:
    medio
Referências:
    http://en.wikipedia.org/wiki/Haversine_formula

=end

class String	
	def Todegree
	    grau, minuto, segundo = self.split().collect {|i| i.to_f}
	    if(self.include? "-")
	        grau -= (minuto/60) + (segundo/3600)
	    else
	        grau += (minuto/60) + (segundo/3600)
            end
	end
end

class Numeric
	def degrees
	    self * Math::PI / 180.0
	end
end

def haversin(theta)
	Math.sin(theta/2)**2
end

Radius = 6371 
def distancia(latitude1, longitude1, latitude2, longitude2)
	deltaLatitude = (latitude2 - latitude1).degrees
	deltaLongitude = (longitude2 - longitude1).degrees
	h = haversin(deltaLatitude) + Math.cos(latitude1.degrees)*Math.cos(latitude2.degrees )*haversin(deltaLongitude)
	2*Radius*Math.asin(Math.sqrt(h))
end

puts distancia("53 08 50".Todegree,"-01 50 58".Todegree,"52 12 16".Todegree,"00 08 26".Todegree)


================================================
FILE: other-languages/graphs/dijkstra/dijkstra.cpp
================================================
/*
Algoritmo de Dijkstra (com matriz de adjacências)
Autores: 
    Edsger Dijkstra
Colaborador:
    Luiz Rodrigo (luizrodri.go@hotmail.com)
Alteração:
	Péricles Lopes Machado (pericles.raskolnikoff@gmail.com)
Tipo: 
    graphs
Descrição: 
    O Algoritmo de Dijsktra é um algoritmo em grafos clássico que determina a
    menor distância de um determinado vértice para todos os outros. Essa é a
    implementação utilizando matriz de adjacências, que tem desempenho 
    inferior.
Complexidade: 
    O(|E| log |V|)
Dificuldade: 
    medio
Referências:
    [1] http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
    [2] Cormem, Thomas H. Introduction to Algorithms, 3rd Edition. 
        ISBN 978-0-262-53305-8. Páginas 658-659.
*/

#include <iostream>
#include <queue>
#include <vector>
#include <stdio.h>

using namespace std;

/*
Parâmetros:
    dist: a matriz de adjacências contendo as distâncias entre os vértices
*/

const int n = 5;
const int INFINITY = (1 << 30)-1; // 2^30-1

/*
Parâmetros:
    dist: matriz de adjacências que contém as distâncias entre os vértices
    origin: o vértice a partir do qual serão calculadas as menores distâncias
    min_dist: vetor para armazenar as menores distâncias calculadas com o algoritmo
    previous: vetor para armazenar o vértice anterior para chegar ao vértice atual
        (permite determinar as rotas).
*/

void dijkstra(int dist[n][n], int origin, int min_dist[n], int previous[n]) {

    // define a lista de adjascencias que é uma representação melhor 
	// para o algoritmo de Dijkstra. Lembrando que representação é 
	// uma parte importante na construção de um algoritmo eficiente

	typedef vector<vector<int> > Graph;
	Graph G(n);

    // inicializa (todas as menores distâncias como infinito)
    for (int i = 0; i < n; i++) { 
        min_dist[i] = INFINITY;
        previous[i] = -1;

		// cria a lista de adjascências
		for (int j = 0; j < n; ++j)
			if (i != j and dist[i][j] < INFINITY) {
				G[i].push_back(j);
			}
    }
    
    // exceto a da origem para a origem, que é 0
    min_dist[origin] = 0;
    
	// heap utilizada para acelerar a busca pelo melhor opção atual
	typedef pair<int, int> Pair;
	priority_queue<Pair> Q;
	
	// a distancia atual para a origin é utilizada como primeira chave para a ordenação da heap
	Q.push(Pair(0, origin));

    while (!Q.empty()) {
		int u = Q.top().second; 
		Q.pop();
    
        for (int i = 0; i < G[u].size(); i++) {
			int v = G[u][i];
            if  (min_dist[u] + dist[u][v] < min_dist[i]) {
                min_dist[v] = min_dist[u] + dist[u][v];
                previous[v] = u;

				// como a priority_queue utiliza a chave de mais alta prioridade para ordenar
				// basta multiplar por -1 a estimativa atual para ordenar adequadamente a heap
				Q.push(Pair(-min_dist[v], v));
            }
		}
    }
}

void print_path(int previous[], int n) {
    if ( previous[n] != -1 ) {
        print_path(previous, previous[n]);
        printf("-> %d ", n);
    } else 
        printf("%d ", n);
}

int main( ) {

    // Visualização desse grafo: http://i52.tinypic.com/2qx6z2p.png
    // Distâncias INFINITY indicam que não há aresta que ligue os dois vértices
    int dist[n][n] = {
        {0, 10, INFINITY, 5, INFINITY},
        {INFINITY, 0, 1, 2, INFINITY},
        {INFINITY, INFINITY, 0,  INFINITY, 4},
        {INFINITY, 3, 9, 0, 2},
        {2, INFINITY, 6, INFINITY, 0}};
    int min_dist[n], prev[n];
    
    dijkstra(dist, 0, min_dist, prev);
    
    for (int i = 1; i < n; i++) {
        printf("Shortest path from 0 to %d: ", i); 
        print_path(prev, i);
        printf(". Distance: %d\n", min_dist[i]);
    }
        
    return 0;
}



================================================
FILE: other-languages/graphs/dijkstra/dijkstra.java
================================================
/*
Algoritmo de Dijkstra
Autor:
    Esdger Dijkstra
Colaborador:
    Filipe Saraiva (filip.saraiva@gmail.com)
Tipo:
    graph
Descrição:
    O Algoritmo de Dijsktra é um algoritmo em grafos clássico que determina a
    menor distância de um determinado vértice para todos os outros.
Complexidade:
    O(n²)
Dificuldade:
    medio
Referências:
    [1] http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
    [2] http://pt.wikipedia.org/wiki/Algoritmo_de_Dijkstra
    [3] http://www-b2.is.tokushima-u.ac.jp/~ikeda/suuri/dijkstra/Dijkstra.shtml
Licenca:
    GPLv3
*/

import java.util.ArrayList;

public class dijkstra {
	
	/**
	 * Implementação do Algoritmo de Dijkstra
	 */
	public static int [][] dijkstra(int [][] matrizSistema){
		
		/**
		 * ArrayList para guardar os vértices já verificados pelo Algoritmo de Dijkstra
		 */
		ArrayList<Boolean> verticesVerificados = new ArrayList<Boolean>();
		
		/**
		 * ArrayList para guardar as distâncias relativas para cada vértice em cada
		 * iteração do Algoritmo de Dijkstra 
		 */
		ArrayList<Integer> distanciaRelativa = new ArrayList<Integer>();
		
		/**
		 * ArrayList unidimensional que guarda os nós vizinhos de cada nó do grafo
		 * da árvore final produzida pelo Algoritmo de Dijkstra
		 */
		ArrayList<Integer> nosVizinhos = new ArrayList<Integer>();
		
		/**
		 * Inicialização de variáveis
		 */
		for(Integer contador = 0; contador < matrizSistema[0].length; contador++){
			verticesVerificados.add(false);
			nosVizinhos.add(0);
			distanciaRelativa.add(Integer.MAX_VALUE);
		}
		
		distanciaRelativa.set(0, new Integer(0));
		
		/**
		 * Definição do ponto que será a raiz da árvore resultante
		 */
		Integer pontoAvaliado = 0;
		
		/**
		 * Estrutura para execução das iterações do Algoritmo de Dijkstra
		 */
		for(Integer contadorPontosAvaliados = 0; contadorPontosAvaliados < matrizSistema[0].length; contadorPontosAvaliados++){
			for(Integer contadorVizinhos = 0; contadorVizinhos < matrizSistema[0].length; contadorVizinhos++){

				/**
				 * Verifica se o nó a ser avaliado nesta iteração já foi avaliado anteriormente;
				 * se sim, passa para a próxima iteração
				 */
				if((verticesVerificados.get(contadorVizinhos)) || (contadorVizinhos == pontoAvaliado)){
					continue;
				}
				
				/**
				 * Duas comparações aqui:
				 * 
				 * 1ª - Verifica se na matrizSistema há algum valor na coluna que seja > 0. Caso afirmativo,
				 * significa que há uma aresta entre estes dois pontos do grafo.
				 * 
				 * 2ª - Verifica se a soma do peso da aresta entre os dois nós mais a distanciaRelativa do nó
				 * que serve como pontoAvaliado é menor que a atual distanciaRelativa do nó vizinho.
				 * 
				 * Caso correto, a distanciaRelativa do nó vizinho ao que está sendo avaliado no momento será
				 * atualizada pelo valor da distanciaRelativa até o pontoAvaliado + distancia entre o pontoAvaliado
				 * e o nó vizinho.
				 */
				
				if((matrizSistema[pontoAvaliado][contadorVizinhos] > 0) &&
						((matrizSistema[pontoAvaliado][contadorVizinhos] + distanciaRelativa.get(pontoAvaliado) < 
								distanciaRelativa.get(contadorVizinhos)))){
					
					distanciaRelativa.set(contadorVizinhos, matrizSistema[pontoAvaliado][contadorVizinhos] +
							 distanciaRelativa.get(pontoAvaliado));
					
					nosVizinhos.set(contadorVizinhos, pontoAvaliado);
					
				}
			}
			
			/**
			 * Marca o vértice de pontoAvaliado como um vértice já verificado
			 */
			verticesVerificados.set(pontoAvaliado, true);
			
			/**
			 * Preparação para seleção do próximo vértice a ser avaliado
			 */
			pontoAvaliado = new Integer(0);
			Integer distanciaComparada = new Integer(Integer.MAX_VALUE);
			
			/**
			 * Seleção do próximo vértice a ser avaliado
			 */
			for(Integer contador = 1; contador < verticesVerificados.size(); contador++){
				
				/**
				 * Se o vertice a ser verificado já foi verificado anteriormente (true)
				 * passa à próxima iteração.
				 */
				if(verticesVerificados.get(contador)){
					continue;
				}
				
				/**
				 * Se a distância relativa desse ponto for menor que a do ponto avaliado
				 * assume-se esse novo ponto como o ponto avaliado.
				 * 
				 * Ao final da iteração, será selecionado o ponto com menor
				 * distância relativa.
				 */
				if(distanciaRelativa.get(contador) < distanciaComparada){
					distanciaComparada = distanciaRelativa.get(contador);
					pontoAvaliado = contador;
				}
				
			}
			
		}
		
		int [][] matrizResposta = new int [matrizSistema[0].length][matrizSistema[0].length];
		
		/**
		 * Criação da matrizResposta com a árvore resultante do Algoritmo de Dijkstra 
		 */
		for(int contador = 1; contador < nosVizinhos.size(); contador++){
			matrizResposta[contador][nosVizinhos.get(contador)] = matrizSistema[contador][nosVizinhos.get(contador)];
			matrizResposta[nosVizinhos.get(contador)][contador] = matrizResposta[contador][nosVizinhos.get(contador)];
		}
		
		return matrizResposta;
	}
		
	/**
	 * Método main para executar o Algoritmo de Dijkstra
	 */
	public static void main(String[] args) {

		/**
		 * Exemplo de grafo - matriz de adjacência onde um número diferente de 0 significa o peso da ligação
		 * entre os nós da matriz
		 * 
		 * Você poderá substituir por qualquer matriz quadrada não negativa
		 */
		int [][] matrizSistema = {{0, 0, 13, 0, 16, 8}, {0, 0, 0, 6, 0, 10}, {13, 0, 0, 14, 0, 11},
				{0, 6, 14, 0, 5, 17}, {16, 0, 0, 5, 0, 7}, {8, 10, 11, 17, 7, 0}};
		
		/**
		 * Chamada do Algoritmo de Dijkstra
		 */
		int[][] matrizResultado = dijkstra(matrizSistema);
		
		/**
		 * Impressão da matrizResultado com a resposta do Algoritmo de Dijkstra
		 */
		for(int contadorHorizontal = 0; contadorHorizontal < matrizResultado[0].length; contadorHorizontal++){
			for(int contadorVertical = 0; contadorVertical < matrizResultado[0].length; contadorVertical++){
				
				System.out.print(matrizResultado[contadorHorizontal][contadorVertical] + " ");
			}
			
			System.out.println();
		}
		
	}

}


================================================
FILE: other-languages/graphs/floyd-warshall/floyd-warshall.cpp
================================================
/*
Algoritmo de Floyd-Warshall
Autores: 
    Robert Floyd e Stephen Warshall
Colaborador:
    Luiz Rodrigo (luizrodri.go@hotmail.com)
Tipo: 
    graphs
Descrição: 
    O Algoritmo de Floyd-Warshall, a partir de uma grafo representado
    em uma matriz (matriz de adjacências), determina as menores distâncias
    entre todos os pares (ou seja, as menores distâncias de todos os 
    vértices para todos os vértices).
Complexidade: 
    O(|V|³)
Dificuldade: 
    medio
Referências:
    [1] http://en.wikipedia.org/wiki/Floyd-Warshall
    [2] Cormem, Thomas H. Introduction to Algorithms, 3rd Edition. 
        ISBN 978-0-262-53305-8. Páginas 693-695.
*/

#include <iostream>

/*
Parâmetros:
    dist: a matriz de adjacências contendo as distâncias entre os vértices
*/

const int n = 3;

void floyd_warshall(int dist[n][n]) {
    for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) 
                if ( dist[i][k] + dist[k][j] < dist[i][j] )
                    dist[i][j] = dist[i][k] + dist[k][j];
}

int main( ) {
    int dist[n][n] = { 
        {0, 3, 10},
        {3, 0, 1000},
        {10, 1000, 0}
    };

    floyd_warshall(dist);
    
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            std::cout << "Menor distancia de " << i << " para " << j << ": " 
                    << dist[i][j] << "\n";
    return 0;
}


================================================
FILE: other-languages/graphs/prim/prim.java
================================================
/*
Algoritmo de Prim
Autor:
    Vojtěch Jarník(1930) e Robert C. Prim(1957)
Colaborador:
    Filipe Saraiva (filip.saraiva@gmail.com)
Tipo:
    graph
Descrição:
    O Algoritmo de Prim é um algoritmo em grafos clássico que determina a
    árvore geradora mínima de um grafo conectado não-orientado.
Complexidade:
    O(n²)
Dificuldade:
    medio
Referências:
    [1] http://en.wikipedia.org/wiki/Prim%27s_algorithm
    [2] http://pt.wikipedia.org/wiki/Algoritmo_de_Prim
    [3] http://www-b2.is.tokushima-u.ac.jp/~ikeda/suuri/dijkstra/Prim.shtml
Licenca:
    GPLv3
*/

import java.util.ArrayList;

public class prim {
	
	/**
	 * Implementação do Algoritmo de Prim
	 */
	public static int [][] prim(int [][] matrizSistema){
		
		/**
		 * ArrayList para guardar os vértices já verificados pelo Algoritmo de Prim
		 */
		ArrayList<Boolean> verticesVerificados = new ArrayList<Boolean>();
		
		/**
		 * ArrayList para guardar as distâncias relativas para cada vértice em cada
		 * iteração do Algoritmo de Prim
		 */
		ArrayList<Integer> distanciaRelativa = new ArrayList<Integer>();
		
		/**
		 * ArrayList unidimensional que guarda os nós vizinhos de cada nó do grafo
		 * da árvore final produzida pelo Algoritmo de Prim
		 */
		ArrayList<Integer> nosVizinhos = new ArrayList<Integer>();
		
		/**
		 * Inicialização de variáveis
		 */
		for(Integer contador = 0; contador < matrizSistema[0].length; contador++){
			verticesVerificados.add(false);
			nosVizinhos.add(0);
			distanciaRelativa.add(Integer.MAX_VALUE);
		}
		
		distanciaRelativa.set(0, new Integer(0));
		
		/**
		 * Definição do ponto que será a raiz da árvore resultante
		 */
		Integer pontoAvaliado = 0;
		
		/**
		 * Estrutura para execução das iterações do Algoritmo de Prim
		 */
		for(Integer contadorPontosAvaliados = 0; contadorPontosAvaliados < matrizSistema[0].length; contadorPontosAvaliados++){
			for(Integer contadorVizinhos = 0; contadorVizinhos < matrizSistema[0].length; contadorVizinhos++){

				/**
				 * Verifica se o nó a ser avaliado nesta iteração já foi avaliado anteriormente;
				 * se sim, passa para a próxima iteração
				 */
				if((verticesVerificados.get(contadorVizinhos)) || (contadorVizinhos == pontoAvaliado)){
					continue;
				}
				
				/**
				 * Duas comparações aqui:
				 * 
				 * 1ª - Verifica se na matrizSistema há algum valor na coluna que seja > 0. Caso afirmativo,
				 * significa que há uma aresta entre estes dois pontos do grafo.
				 * 
				 * 2ª - Verifica se o peso da aresta entre os dois nós é menor que a atual distanciaRelativa
				 * do nó vizinho.
				 * 
				 * Caso correto, a distanciaRelativa do nó vizinho ao que está sendo avaliado no momento será
				 * atualizada pelo valor dessa nova distancia avaliada até o pontoAvaliado.
				 */
				
				if((matrizSistema[pontoAvaliado][contadorVizinhos] > 0) &&
						((matrizSistema[pontoAvaliado][contadorVizinhos] < 
								distanciaRelativa.get(contadorVizinhos)))){
					
					distanciaRelativa.set(contadorVizinhos, matrizSistema[pontoAvaliado][contadorVizinhos]);
					
					nosVizinhos.set(contadorVizinhos, pontoAvaliado);
					
				}
			}
			
			/**
			 * Marca o vértice de pontoAvaliado como um vértice já verificado
			 */
			verticesVerificados.set(pontoAvaliado, true);
			
			/**
			 * Preparação para seleção do próximo vértice a ser avaliado
			 */
			pontoAvaliado = new Integer(0);
			Integer distanciaComparada = new Integer(Integer.MAX_VALUE);
			
			/**
			 * Seleção do próximo vértice a ser avaliado
			 */
			for(Integer contador = 1; contador < verticesVerificados.size(); contador++){
				
				/**
				 * Se o vertice a ser verificado já foi verificado anteriormente (true)
				 * passa à próxima iteração.
				 */
				if(verticesVerificados.get(contador)){
					continue;
				}
				
				/**
				 * Se a distância relativa desse ponto for menor que a do ponto avaliado
				 * assume-se esse novo ponto como o ponto avaliado.
				 * 
				 * Ao final da iteração, será selecionado o ponto com menor
				 * distância relativa.
				 */
				if(distanciaRelativa.get(contador) < distanciaComparada){
					distanciaComparada = distanciaRelativa.get(contador);
					pontoAvaliado = contador;
				}
				
			}
			
		}
		
		int [][] matrizResposta = new int [matrizSistema[0].length][matrizSistema[0].length];
		
		/**
		 * Criação da matrizResposta com a árvore resultante do Algoritmo de Prim
		 */
		for(int contador = 1; contador < nosVizinhos.size(); contador++){
			matrizResposta[contador][nosVizinhos.get(contador)] = matrizSistema[contador][nosVizinhos.get(contador)];
			matrizResposta[nosVizinhos.get(contador)][contador] = matrizResposta[contador][nosVizinhos.get(contador)];
		}
		
		return matrizResposta;
	}
		
	/**
	 * Método main para executar o Algoritmo de Prim
	 */
	public static void main(String[] args) {

		/**
		 * Exemplo de grafo - matriz de adjacência onde um número diferente de 0 significa o peso da ligação
		 * entre os nós da matriz
		 * 
		 * Você poderá substituir por qualquer matriz quadrada não negativa
		 */
		int [][] matrizSistema = {{0, 5, 30, 0, 0, 0}, {5, 0, 20, 10, 0, 0}, {30, 20, 0, 10, 15, 0}, 
					  {0, 10, 10, 0, 5, 20}, {0, 0, 15, 5, 0, 15}, {0, 0, 0, 20, 15, 0}};

		/**
		 * Chamada do Algoritmo de Prim
		 */
		int[][] matrizResultado = prim(matrizSistema);
		
		/**
		 * Impressão da matrizResultado com a resposta do Algoritmo de Prim
		 */
		for(int contadorHorizontal = 0; contadorHorizontal < matrizResultado[0].length; contadorHorizontal++){
			for(int contadorVertical = 0; contadorVertical < matrizResultado[0].length; contadorVertical++){
				
				System.out.print(matrizResultado[contadorHorizontal][contadorVertical] + " ");
			}
			
			System.out.println();
		}
		
	}

}


================================================
FILE: other-languages/lang/nums2words.c
================================================
/*
nums2words
Autor:
    ? 
Colaborador:
    Stanislaw Pusep 
Tipo:
    lang
Descrio:
    Conversor de nmeros inteiros em strings de numerais cardinais em portugus.
    Exemplo:
        9223372036854775807 (maior inteiro positivo de 64 bits) => "nove quinqualhes e duzentos e vinte e trs quatrilhes e trezentos e setenta e dois trilhes e trinta e seis bilhes e oitocentos e cinqenta e quatro milhes e setecentos e setenta e cinco mil e oitocentos e sete"
Complexidade:
    ?
Dificuldade:
    medio
Referncias: 
    [1] http://sysd.org/stas/node/20
    [2] http://pt.wikipedia.org/wiki/Nomes_dos_n%C3%BAmeros
    [3] http://pt.wikipedia.org/wiki/Escalas_curta_e_longa
*/

#include <malloc.h>
#include <stdio.h>
#include <string.h>

// tamanhos dos buffers
#define MAXRES_S		512
#define MAXTERN_S		64

// formato da estrutura da tabela de transio
typedef struct {
    unsigned int n;
    char *w;
} node;

/*
 * Expande blocos de milhares.
 * Os nmeros maiores do que mil so "quebrados" em ternas que depois recebem um multiplicador.
 */
char *ext999 (unsigned int n) {
    unsigned int i, x, y;
    char *buf;
    // mapeamento nmero => nome
    node rel[] = {
        {900,	"novecentos"},	{800,	"oitocentos"},
        {700,	"setecentos"},	{600,	"seiscentos"},
        {500,	"quinhentos"},	{400,	"quatrocentos"},
        {300,	"trezentos"},	{200,	"duzentos"},
        {100,	"cento"},	    {90,	"noventa"},
        {80,	"oitenta"},	    {70,	"setenta"},
        {60,	"sessenta"},	{50,	"cinquenta"},
        {40,	"quarenta"},	{30,	"trinta"},
        {20,	"vinte"},	    {19,	"dezenove"},
        {18,	"dezoito"},	    {17,	"dezessete"},
        {16,	"dezesseis"},	{15,	"quinze"},
        {14,	"quatorze"},	{13,	"treze"},
        {12,	"doze"},	    {11,	"onze"},
        {10,	"dez"},		    {9,	    "nove"},
        {8,	    "oito"},	    {7,	    "sete"},
        {6,	    "seis"},	    {5,	    "cinco"},
        {4,	    "quatro"},	    {3,	    "trs"},
        {2,	    "dois"},	    {1,	    "um"},
    };

    buf = (char *) malloc(MAXTERN_S);
    buf[0] = '\0';

    // casos especiais
    if (!n) {
        strcpy(buf, "zero");
        return buf;
    } else if (n == 100) {
        strcpy(buf, "cem");
        return buf;
    }

    // faz a reduo do nmero fatorando pelos ndices do mapeamento
    while (n) {
        for (i = 0; i < sizeof(rel); i++) {
            x = rel[i].n;
            y = n % x;
            if (x + y == n) {
                n = y;
                strcat(buf, rel[i].w);
                if (n)
                    strcat(buf, " e ");
                break;
            }
        }
    }

    return buf;
}

char *nums2
Download .txt
gitextract_g4n0chn_/

├── README.md
├── algorithms/
│   ├── ai/
│   │   ├── Astar.py
│   │   ├── hamming.py
│   │   └── knn.py
│   ├── bioinformatics/
│   │   ├── gc_skew_diagram.py
│   │   ├── reverse_complement.py
│   │   ├── traducao.py
│   │   └── transcricao.py
│   ├── color/
│   │   └── rgb-to-cmyk.py
│   ├── combinatory/
│   │   └── derangement.py
│   ├── crypto/
│   │   ├── cesar.py
│   │   ├── rot13.py
│   │   ├── rsa.py
│   │   └── vigenere.py
│   ├── data-structures/
│   │   ├── arraysum.py
│   │   ├── heap.py
│   │   └── stack.py
│   ├── date/
│   │   └── leap-year.py
│   ├── economics/
│   │   └── financiamento.py
│   ├── geography/
│   │   └── haversine.py
│   ├── graphs/
│   │   ├── BellmanFord.py
│   │   ├── Dijkstra.py
│   │   ├── EdmondsKarp.py
│   │   └── FloydWarshall.py
│   ├── math/
│   │   ├── algebra/
│   │   │   ├── bhaskara.py
│   │   │   ├── dda.py
│   │   │   ├── media-num.py
│   │   │   ├── media.py
│   │   │   └── permutation.py
│   │   ├── bisection-method.py
│   │   ├── linear-algebra/
│   │   │   └── matrix-transpose.py
│   │   ├── luhn.py
│   │   └── number-theory/
│   │       ├── bozofactoring.py
│   │       ├── divisors.py
│   │       ├── eratosthenes.py
│   │       ├── euclid.py
│   │       ├── fatorial.py
│   │       ├── fibonacci-matrix-form.py
│   │       ├── fibonacci.py
│   │       ├── miller-rabin.py
│   │       ├── newton_raphson_sqrt.py
│   │       ├── perfectnumber.py
│   │       ├── pow.py
│   │       ├── powmod.py
│   │       └── stirling.py
│   ├── misc/
│   │   └── helloworld.py
│   ├── optimization/
│   │   ├── inteval_scheduling.py
│   │   └── knapsack.py
│   ├── pattern-matching/
│   │   ├── AhoCorasick.py
│   │   ├── hamming.py
│   │   ├── kmp.py
│   │   └── levenshtein.py
│   ├── physics/
│   │   └── ballistic.py
│   ├── search/
│   │   ├── binary-search.py
│   │   └── linear-search.py
│   ├── sequence/
│   │   └── token.py
│   └── sorting/
│       ├── bozosort.py
│       ├── bubblesort.py
│       ├── dropsort.py
│       ├── insertionsort.py
│       ├── masochisticsort.py
│       ├── mergesort.py
│       ├── quicksort.py
│       ├── selectionsort.py
│       └── sleepsort.py
├── modelo.txt
└── other-languages/
    ├── ai/
    │   ├── genealogicaltree/
    │   │   └── genealogicaltree.pro
    │   ├── sokoban/
    │   │   ├── alberta/
    │   │   │   ├── screen.1
    │   │   │   ├── screen.1.sol
    │   │   │   └── screen.31
    │   │   ├── runtests.sh
    │   │   ├── sokoban.cpp
    │   │   └── sokobanonline/
    │   │       └── classic/
    │   │           └── thinkingrabbit/
    │   │               └── Boxxle/
    │   │                   ├── sk01-01.in
    │   │                   ├── sk01-01.out
    │   │                   ├── sk01-01.sol
    │   │                   ├── sk01-02.in
    │   │                   ├── sk01-02.out
    │   │                   ├── sk01-02.sol
    │   │                   ├── sk01-03.in
    │   │                   ├── sk01-03.out
    │   │                   ├── sk01-03.sol
    │   │                   ├── sk01-04.in
    │   │                   ├── sk01-04.out
    │   │                   ├── sk01-04.sol
    │   │                   ├── sk01-05.in
    │   │                   ├── sk01-05.out
    │   │                   ├── sk01-05.sol
    │   │                   ├── sk01-06.in
    │   │                   ├── sk01-06.out
    │   │                   ├── sk01-06.sol
    │   │                   ├── sk01-07.in
    │   │                   ├── sk01-07.sol
    │   │                   ├── sk01-08.in
    │   │                   ├── sk01-08.sol
    │   │                   ├── sk01-09.in
    │   │                   ├── sk01-09.sol
    │   │                   ├── sk02-10.in
    │   │                   └── sk02-10.sol
    │   └── sudoku/
    │       ├── sudoku.cpp
    │       └── test_001.in
    ├── array/
    │   ├── merge/
    │   │   └── merge.rb
    │   └── partition/
    │       └── partition.rb
    ├── bitwise/
    │   ├── BitScanForwardDebruijn64.cs
    │   ├── HammingWeight64.cs
    │   ├── bsf-debruijn/
    │   │   └── BitScanForwardDebruijn64.cs
    │   ├── dec2hex/
    │   │   └── dec2hex.c
    │   ├── hamming-weight/
    │   │   └── HammingWeight64.cs
    │   ├── operations/
    │   │   └── operations.cpp
    │   └── swap_xor/
    │       ├── swap_xor.c
    │       ├── swap_xor.cs
    │       └── swap_xor.php
    ├── date/
    │   └── leap-year/
    │       ├── leap-year.lisp
    │       ├── leap-year.php
    │       └── leap-year.rb
    ├── economics/
    │   ├── financiamento/
    │   │   ├── financiamento.cs
    │   │   ├── financiamento.lisp
    │   │   ├── financiamento.php
    │   │   └── financiamento.rb
    │   └── juros-compostos/
    │       └── juros-compostos.lisp
    ├── geography/
    │   └── haversine/
    │       └── haversine.rb
    ├── graphs/
    │   ├── dijkstra/
    │   │   ├── dijkstra.cpp
    │   │   └── dijkstra.java
    │   ├── floyd-warshall/
    │   │   └── floyd-warshall.cpp
    │   └── prim/
    │       └── prim.java
    ├── lang/
    │   └── nums2words.c
    ├── math/
    │   ├── bhaskara/
    │   │   ├── bhaskara.lisp
    │   │   ├── bhaskara.php
    │   │   └── bhaskara.rb
    │   ├── dda/
    │   │   ├── dda.cpp
    │   │   ├── dda.cs
    │   │   ├── dda.java
    │   │   ├── dda.php
    │   │   └── dda.rb
    │   ├── determinant/
    │   │   ├── determinant.cpp
    │   │   └── determinant.rb
    │   ├── divisors/
    │   │   └── divisor.rb
    │   ├── eratostenes/
    │   │   └── eratostenes.java
    │   ├── even/
    │   │   └── even.c
    │   ├── fatorial/
    │   │   ├── fatorial.cs
    │   │   ├── fatorial.lisp
    │   │   ├── fatorial.php
    │   │   └── fatorial.rb
    │   ├── fibonacci/
    │   │   ├── fibonacci.c
    │   │   ├── fibonacci.clj
    │   │   ├── fibonacci.cs
    │   │   ├── fibonacci.java
    │   │   ├── fibonacci.lisp
    │   │   ├── fibonacci.lua
    │   │   ├── fibonacci.php
    │   │   └── fibonacci.rb
    │   ├── gauss/
    │   │   └── sumgauss.cpp
    │   ├── geometric-mean/
    │   │   └── geometric-mean.cpp
    │   ├── linear-system/
    │   │   └── linear-system.c
    │   ├── lu-decomposition/
    │   │   ├── lu-decomposition.cpp
    │   │   └── lu-decomposition.rb
    │   ├── matrix-transpose/
    │   │   └── matrix-transpose.cpp
    │   ├── media/
    │   │   ├── media.lisp
    │   │   ├── media.php
    │   │   └── media.rb
    │   ├── media-num/
    │   │   ├── media-num.c
    │   │   └── media-num.rb
    │   ├── multiply-matrix/
    │   │   └── multiply-matrix.cpp
    │   ├── n-root/
    │   │   └── MetodosNumericos.java
    │   ├── perfect-numbers/
    │   │   └── perfectnumber.rb
    │   ├── pow/
    │   │   └── pow.c
    │   └── stirlings-approximation/
    │       └── stirling.clj
    ├── number-theory/
    │   ├── euclid/
    │   │   ├── euclid.lisp
    │   │   └── euclid.rb
    │   ├── inverse/
    │   │   └── inverse.c
    │   ├── modular-exponentiation/
    │   │   └── modular-exponentiation.cpp
    │   ├── odd/
    │   │   └── odd.c
    │   ├── odd-even/
    │   │   └── odd-even.c
    │   └── sieve/
    │       ├── sieve.cpp
    │       └── sieve.lisp
    ├── pattern-matching/
    │   └── lcs/
    │       └── lcs.rb
    ├── physics/
    │   └── ballistic/
    │       └── ballistic.lisp
    ├── puzzle/
    │   ├── hanoi/
    │   │   └── hanoi.cpp
    │   └── sudoku-validation/
    │       └── sudoku-validation.cpp
    ├── search/
    │   ├── binary-search/
    │   │   └── BuscaBinaria.java
    │   ├── linear-search/
    │   │   └── linear-search.rb
    │   └── simul-smaller-higher/
    │       └── simul-smaller-higher.cpp
    ├── sequence/
    │   └── token/
    │       ├── token.php
    │       └── token.rb
    └── sorting/
        ├── bozosort/
        │   ├── bozosort.lisp
        │   ├── bozosort.php
        │   └── bozosort.rb
        ├── bubblesort/
        │   ├── bubblesort.lisp
        │   └── bubblesort.php
        ├── fisher-yates/
        │   └── fisher-yates.c
        ├── heapsort/
        │   └── heapsort.c
        ├── insertionsort/
        │   ├── insertionsort.cpp
        │   ├── insertionsort.php
        │   └── insertionsort.rb
        ├── mergesort/
        │   ├── mergesort.c
        │   └── mergesort.rb
        ├── quicksort/
        │   ├── quicksort.c
        │   ├── quicksort.php
        │   └── quicksort.rb
        ├── selectionsort/
        │   ├── selectionsort.cpp
        │   └── selectionsort.php
        ├── shellsort/
        │   └── shellsort.cpp
        └── stoogesort/
            └── stoogesort.cpp
Download .txt
SYMBOL INDEX (369 symbols across 150 files)

FILE: algorithms/ai/Astar.py
  function imprime_caminho (line 30) | def imprime_caminho(pi, u):
  function renderizar_grade (line 43) | def renderizar_grade(G, ux, uy):
  function renderizar_caminho (line 60) | def renderizar_caminho(pi, G, u):
  function H (line 148) | def H(s, t):
  function dist (line 153) | def dist(s, t):

FILE: algorithms/ai/hamming.py
  function hamming (line 21) | def hamming(a, b):
  function hamming_i (line 24) | def hamming_i(ai, bi):
  function knn (line 27) | def knn(k, treino, padrao, distancia=lambda a,b: sum([(c-d)**2 for c,d i...

FILE: algorithms/ai/knn.py
  function knn (line 27) | def knn(k, treino, padrao, distancia=lambda a,b: sum([(c-d)**2 for c,d i...

FILE: algorithms/bioinformatics/gc_skew_diagram.py
  function gc_skew_diagram (line 22) | def gc_skew_diagram(genome):

FILE: algorithms/bioinformatics/reverse_complement.py
  function reverse_complement (line 21) | def reverse_complement(genoma):

FILE: algorithms/bioinformatics/traducao.py
  function traducao (line 24) | def traducao(rna):

FILE: algorithms/bioinformatics/transcricao.py
  function transcrever (line 21) | def transcrever(dna):

FILE: algorithms/color/rgb-to-cmyk.py
  function rgb2cmyk (line 26) | def rgb2cmyk( red, green, blue ):

FILE: algorithms/combinatory/derangement.py
  function fatorial (line 24) | def fatorial(x):

FILE: algorithms/crypto/cesar.py
  class Cesar (line 37) | class Cesar(object):
    method __init__ (line 39) | def __init__(self):
    method crypt (line 44) | def crypt(self, entrada = "", chave = 0):
    method decrypt (line 59) | def decrypt(self, entrada = "", chave = 0):

FILE: algorithms/crypto/rot13.py
  function rot13 (line 25) | def rot13(text):

FILE: algorithms/crypto/rsa.py
  function gcd (line 28) | def gcd(a,b):
  function inverse (line 34) | def inverse(a, b):
  function rsa (line 38) | def rsa(n, e, M):

FILE: algorithms/crypto/vigenere.py
  class Vigenere (line 27) | class Vigenere(object):
    method __init__ (line 28) | def __init__(self):
    method crypt (line 36) | def crypt(self, plaintext = "", chave= ""):
    method decrypt (line 47) | def decrypt(self, ciphertext = "", chave=""):

FILE: algorithms/data-structures/arraysum.py
  function arraysum (line 19) | def arraysum(l, key = lambda a, b: a + b):

FILE: algorithms/data-structures/heap.py
  class BinaryHeap (line 23) | class BinaryHeap:
    method __init__ (line 24) | def __init__(self, V = []):
    method heapify (line 28) | def heapify(self):
    method count (line 32) | def count(self):
    method top (line 35) | def top(self):
    method push (line 38) | def push(self, value):
    method pop (line 42) | def pop(self):
    method pop_all (line 51) | def pop_all(self):
    method bubble_up (line 55) | def bubble_up(self, n):
    method bubble_down (line 60) | def bubble_down(self, n):
    method less (line 66) | def less(self, a, b):
    method min (line 71) | def min(self, a, b):
    method swap (line 74) | def swap(self, a, b):

FILE: algorithms/data-structures/stack.py
  class Stack (line 23) | class Stack:
    method __init__ (line 24) | def __init__(self):
    method __len__ (line 27) | def __len__(self):
    method __str__ (line 30) | def __str__(self):
    method top (line 33) | def top(self):
    method push (line 36) | def push(self, value):
    method pop (line 39) | def pop(self):

FILE: algorithms/date/leap-year.py
  function anoBissexto (line 23) | def anoBissexto(anos):

FILE: algorithms/economics/financiamento.py
  function parcelas (line 23) | def parcelas(investimento, juros, periodo):

FILE: algorithms/geography/haversine.py
  function strTodegree (line 27) | def strTodegree(string):
  function haversin (line 36) | def haversin(theta):
  function distancia (line 40) | def distancia(latitude1, longitude1, latitude2, longitude2):

FILE: algorithms/graphs/BellmanFord.py
  class NegativeWeightCycleError (line 39) | class NegativeWeightCycleError(Exception):
  class Vertex (line 43) | class Vertex:
    method __init__ (line 48) | def __init__(self, label, distance, predecessors=None):
    method __repr__ (line 54) | def __repr__(self):
  class Edge (line 57) | class Edge:
    method __init__ (line 61) | def __init__(self, source, destination, weight):
  class Graph (line 66) | class Graph:
    method __init__ (line 70) | def __init__(self, graph=None):
    method addEdge (line 88) | def addEdge(self, source, destination, weight):
  class BellmanFord (line 98) | class BellmanFord:
    method __init__ (line 99) | def __init__(self, g):
    method adjacencyMatrixShortestPath (line 102) | def adjacencyMatrixShortestPath(self, source, destination):
    method adjacencytListShortestPath (line 153) | def adjacencytListShortestPath(self, source, destination):

FILE: algorithms/graphs/Dijkstra.py
  function imprime_rota (line 31) | def imprime_rota(pi, u):

FILE: algorithms/graphs/EdmondsKarp.py
  class EdmondsKarp (line 48) | class EdmondsKarp:
    method __init__ (line 54) | def __init__(self, c, s, t):
    method __iter__ (line 65) | def __iter__(self):
    method next (line 69) | def next(self):
    method MinCutVertex (line 102) | def MinCutVertex(self):
    method FlowEdges (line 115) | def FlowEdges(self, outtype=RAW):
    method MaxFlow (line 147) | def MaxFlow(self, approach=IMPERATIVE):

FILE: algorithms/graphs/FloydWarshall.py
  class NoSuchAPathError (line 52) | class NoSuchAPathError(Exception):
  class FloydWarshall (line 55) | class FloydWarshall:
    method __init__ (line 56) | def __init__(self, matrix):
    method shortestPaths (line 68) | def shortestPaths(self):
    method getItermediate (line 78) | def getItermediate(self, source, destination):
    method getPath (line 91) | def getPath(self, source, destination):

FILE: algorithms/math/algebra/bhaskara.py
  function bhaskara (line 23) | def bhaskara(a, b, c):

FILE: algorithms/math/algebra/dda.py
  function DDA (line 23) | def DDA(x1, y1, x2, y2):

FILE: algorithms/math/algebra/media-num.py
  function media (line 22) | def media(*args):

FILE: algorithms/math/algebra/media.py
  function media (line 23) | def media(n1, n2, n3):

FILE: algorithms/math/algebra/permutation.py
  function permutation (line 21) | def permutation(input_data, temp_data, position):

FILE: algorithms/math/bisection-method.py
  function root (line 24) | def root(function, x0, x1, precision=0.0001):
  function funcao (line 44) | def funcao(x):

FILE: algorithms/math/linear-algebra/matrix-transpose.py
  function get_transpose (line 21) | def get_transpose(matrix):

FILE: algorithms/math/luhn.py
  function luhn_checksum (line 19) | def luhn_checksum(card_number):
  function calculate_luhn (line 31) | def calculate_luhn(partial_card_number):

FILE: algorithms/math/number-theory/bozofactoring.py
  function factor (line 25) | def factor(n):

FILE: algorithms/math/number-theory/eratosthenes.py
  function sieve (line 23) | def sieve(n):
  function primes_up_to (line 34) | def primes_up_to(n):

FILE: algorithms/math/number-theory/euclid.py
  function euclides (line 28) | def euclides(a, b):

FILE: algorithms/math/number-theory/fatorial.py
  function fatorial (line 20) | def fatorial(b):

FILE: algorithms/math/number-theory/fibonacci-matrix-form.py
  function pow_matriz (line 29) | def pow_matriz(b,n):
  function multi_matriz (line 44) | def multi_matriz(ma,mb):
  function fibo (line 52) | def fibo(n):

FILE: algorithms/math/number-theory/fibonacci.py
  function fibonacci (line 23) | def fibonacci(nesimo):

FILE: algorithms/math/number-theory/miller-rabin.py
  function witness (line 23) | def witness(a, n):
  function is_prime (line 37) | def is_prime(n):

FILE: algorithms/math/number-theory/newton_raphson_sqrt.py
  function newton_raphson_sqrt (line 26) | def newton_raphson_sqrt(n, precisao=0.001, debug=False):

FILE: algorithms/math/number-theory/perfectnumber.py
  function calc_perf (line 20) | def calc_perf(number):

FILE: algorithms/math/number-theory/pow.py
  function pow (line 19) | def pow(x, n):

FILE: algorithms/math/number-theory/powmod.py
  function pow (line 22) | def pow(x, e, m):

FILE: algorithms/math/number-theory/stirling.py
  function stirling (line 18) | def stirling(n):

FILE: algorithms/optimization/inteval_scheduling.py
  function intervalScheduling (line 45) | def intervalScheduling(tasks):
  class Task (line 76) | class Task:
    method __init__ (line 83) | def __init__(self, start, end):
    method __repr__ (line 87) | def __repr__(self):
    method __cmp__ (line 90) | def __cmp__(self, o):

FILE: algorithms/optimization/knapsack.py
  class Item (line 56) | class Item:
    method __init__ (line 57) | def __init__(self, value, weight, label=None):
    method __repr__ (line 66) | def __repr__(self):
  class Knapsack (line 69) | class Knapsack:
    method __init__ (line 70) | def __init__(self, maxWeight, items=None):
    method zeroOne (line 74) | def zeroOne(self, items=None):
    method unbounded (line 135) | def unbounded(self, items=None):

FILE: algorithms/pattern-matching/AhoCorasick.py
  class AhoCoraski (line 40) | class AhoCoraski(dict):
    method __init__ (line 44) | def __init__(self, patternList=None, thenBuild=False):
    method add (line 51) | def add(self, pattern):
    method build (line 70) | def build(self):
    method match (line 91) | def match(self, subject):

FILE: algorithms/pattern-matching/hamming.py
  function hamming_distance (line 27) | def hamming_distance(s1, s2):

FILE: algorithms/pattern-matching/kmp.py
  function kmp_init (line 21) | def kmp_init(P):
  function kmp (line 33) | def kmp(Q, P):

FILE: algorithms/pattern-matching/levenshtein.py
  function levenshtein (line 27) | def levenshtein(s, t):

FILE: algorithms/physics/ballistic.py
  function simula_tiro (line 24) | def simula_tiro(angle, forca, gravidade, startY):

FILE: algorithms/search/binary-search.py
  function binary_search (line 25) | def binary_search(value, l):

FILE: algorithms/search/linear-search.py
  function linear_search (line 28) | def linear_search(array, search):

FILE: algorithms/sequence/token.py
  function token (line 24) | def token(length = 10):

FILE: algorithms/sorting/bozosort.py
  function is_sorted (line 24) | def is_sorted(seq):
  function bozosort (line 38) | def bozosort(seq):

FILE: algorithms/sorting/bubblesort.py
  function bubble (line 21) | def bubble(lst):

FILE: algorithms/sorting/dropsort.py
  function dropsort (line 28) | def dropsort(lst):

FILE: algorithms/sorting/insertionsort.py
  function insertion_sort (line 22) | def insertion_sort(L):

FILE: algorithms/sorting/masochisticsort.py
  function masoquist_sort (line 23) | def masoquist_sort(L):
  function is_sorted (line 41) | def is_sorted(L):

FILE: algorithms/sorting/mergesort.py
  function intercala (line 23) | def intercala (inicio, fim):
  function mergesort (line 41) | def mergesort(array):

FILE: algorithms/sorting/quicksort.py
  function quicksort (line 26) | def quicksort(V):

FILE: algorithms/sorting/selectionsort.py
  function selectionsort (line 21) | def selectionsort(L):

FILE: algorithms/sorting/sleepsort.py
  function sleepit (line 31) | def sleepit(val):

FILE: other-languages/ai/sokoban/sokoban.cpp
  function initCState (line 77) | void initCState() {
  class cState (line 92) | class cState {
    method cState (line 95) | cState(const cState& s) {
    method cState (line 101) | cState(int N = 0, int M = 0)
    method get (line 104) | char get(int i, int j) {
    method insert (line 113) | void insert(int i, int j, char c) {
    method cState (line 124) | cState& operator=(const cState& x) {
    method print (line 131) | void print() {
  function print (line 199) | void print(cState& s) {
  function string (line 205) | string getStr(cState& s) {
  function cState (line 214) | cState getVec(string& s) {
    method cState (line 95) | cState(const cState& s) {
    method cState (line 101) | cState(int N = 0, int M = 0)
    method get (line 104) | char get(int i, int j) {
    method insert (line 113) | void insert(int i, int j, char c) {
    method cState (line 124) | cState& operator=(const cState& x) {
    method print (line 131) | void print() {
  function abs (line 232) | inline int abs(int a) { return a>0?a:-a; }
  function h (line 235) | int h(cState& s, int p, int id) {
  function isDead (line 261) | bool isDead(cState& s, int id) {
  function makeMove (line 296) | bool makeMove(cState& s, int x, int y, int k) {
  function calcDist (line 316) | int calcDist(cState& s, int x, int y, int xf, int yf) {
  function print_sol (line 359) | void print_sol(State& u, int p, int du) {
  function findBox (line 378) | void findBox(vector<int>& vb, cState& s) {
  function main (line 386) | int main()

FILE: other-languages/ai/sudoku/sudoku.cpp
  type V (line 70) | struct V{
    method V (line 79) | V(int n_words=5,int nbits=10, int MASK=1023)
    method V (line 84) | V(const V& b){
    method insert (line 90) | inline
    method get (line 102) | inline
    method V (line 113) | V& operator=(const V& b){
  type st (line 126) | struct st{
    method st (line 130) | st():s(16,4,15),pl(),pc(),ps(),le(1),x(0),y(0){}
    method st (line 132) | st(const V& s, const V& pl, const V& pc, const V& ps, int le=1, int x=...
    method st (line 135) | st& operator=(const st& a){
  function print (line 152) | inline
  function solve (line 164) | bool solve(V& s){
  function find_error (line 287) | bool find_error(V& s){
  function main (line 325) | int main()

FILE: other-languages/array/merge/merge.rb
  function merge (line 20) | def merge(array, left, mid, right)

FILE: other-languages/array/partition/partition.rb
  function partition (line 28) | def partition(array, left, right)
  function partition (line 56) | def partition(array, left, right)

FILE: other-languages/bitwise/BitScanForwardDebruijn64.cs
  class Program (line 20) | class Program
    method BitScanForward (line 34) | public static int BitScanForward(ulong value)
    method Main (line 41) | static void Main(string[] args)

FILE: other-languages/bitwise/HammingWeight64.cs
  class Program (line 21) | class Program
    method PopCount (line 23) | public static int PopCount(ulong x)
    method Main (line 39) | static void Main(string[] args)

FILE: other-languages/bitwise/bsf-debruijn/BitScanForwardDebruijn64.cs
  class Program (line 19) | class Program
    method BitScanForward (line 33) | public static int BitScanForward(ulong value)
    method Main (line 40) | static void Main(string[] args)

FILE: other-languages/bitwise/hamming-weight/HammingWeight64.cs
  class Program (line 20) | class Program
    method PopCount (line 22) | public static int PopCount(ulong x)
    method Main (line 38) | static void Main(string[] args)

FILE: other-languages/bitwise/operations/operations.cpp
  function isOdd (line 18) | bool isOdd(int num) { return num & 1; }
  function isPower2 (line 25) | bool isPower2(int num) { return !(num-1 & num); }
  function toggleCase (line 33) | void toggleCase(char& ch) { ch ^= 0x20; }
  function toUpper (line 36) | void toUpper(char& ch) { ch &= ~0x20; }
  function toLower (line 39) | void toLower(char& ch) { ch |= 0x20; }

FILE: other-languages/bitwise/swap_xor/swap_xor.c
  function swap (line 25) | void swap(int* a, int* b) {
  function main (line 32) | int main(int argc, char* argv[]) {

FILE: other-languages/bitwise/swap_xor/swap_xor.cs
  class SwapXor (line 25) | public sealed class SwapXor {
    method swap (line 27) | public static void swap(ref int a, ref int b) {
    method Main (line 34) | public static void Main() {

FILE: other-languages/bitwise/swap_xor/swap_xor.php
  function swap (line 24) | function swap(&$a, &$b) {

FILE: other-languages/date/leap-year/leap-year.php
  function bissexto (line 21) | function bissexto($numAnos = 4) {

FILE: other-languages/date/leap-year/leap-year.rb
  function anoBissexto (line 21) | def anoBissexto(anos)

FILE: other-languages/economics/financiamento/financiamento.cs
  class MainClass (line 26) | class MainClass
    method financiamneto (line 28) | static public double financiamneto(double investimento, double juros, ...
    method Main (line 33) | public static void Main (string[] args)

FILE: other-languages/economics/financiamento/financiamento.php
  function financiamento (line 21) | function financiamento($investimento, $juros, $periodo) {

FILE: other-languages/economics/financiamento/financiamento.rb
  function parcelas (line 23) | def parcelas(investimento, juros, periodo)

FILE: other-languages/geography/haversine/haversine.rb
  class String (line 24) | class String
    method Todegree (line 25) | def Todegree
  class Numeric (line 35) | class Numeric
    method degrees (line 36) | def degrees
  function haversin (line 41) | def haversin(theta)
  function distancia (line 46) | def distancia(latitude1, longitude1, latitude2, longitude2)

FILE: other-languages/graphs/dijkstra/dijkstra.cpp
  function dijkstra (line 50) | void dijkstra(int dist[n][n], int origin, int min_dist[n], int previous[...
  function print_path (line 99) | void print_path(int previous[], int n) {
  function main (line 107) | int main( ) {

FILE: other-languages/graphs/dijkstra/dijkstra.java
  class dijkstra (line 26) | public class dijkstra {
    method dijkstra (line 31) | public static int [][] dijkstra(int [][] matrizSistema){
    method main (line 162) | public static void main(String[] args) {

FILE: other-languages/graphs/floyd-warshall/floyd-warshall.cpp
  function floyd_warshall (line 33) | void floyd_warshall(int dist[n][n]) {
  function main (line 41) | int main( ) {

FILE: other-languages/graphs/prim/prim.java
  class prim (line 26) | public class prim {
    method prim (line 31) | public static int [][] prim(int [][] matrizSistema){
    method main (line 160) | public static void main(String[] args) {

FILE: other-languages/lang/nums2words.c
  type node (line 32) | typedef struct {
  function main (line 168) | int main (void) {

FILE: other-languages/math/bhaskara/bhaskara.php
  function bhaskara (line 21) | function bhaskara($a, $b, $c) {

FILE: other-languages/math/bhaskara/bhaskara.rb
  function bhaskara (line 22) | def bhaskara(a, b, c)

FILE: other-languages/math/dda/dda.cpp
  type Point (line 26) | struct Point {
    method Point (line 33) | Point(int x, int y) {
  class DDA (line 41) | class DDA {
    method DDA (line 77) | DDA() {}
  function main (line 82) | int main(int argc, char* argv[]) {

FILE: other-languages/math/dda/dda.cs
  type Point (line 23) | public struct Point {
    method Point (line 28) | public Point(int x, int y) {
  class DDA (line 35) | public static class DDA {
    method rasteriza (line 37) | public static Point[] rasteriza(Point ini, Point fim) {
  class MainDDA (line 71) | public class MainDDA {
    method Main (line 73) | public static void Main() {

FILE: other-languages/math/dda/dda.java
  class dda (line 24) | public class dda {
    method rasteriza (line 26) | public static Point[] rasteriza(Point ini, Point fim) {
    method main (line 56) | public static void main(String[] args) {

FILE: other-languages/math/dda/dda.php
  class Point (line 22) | class Point {
    method __construct (line 27) | public function __construct($x, $y) {
  class DDA (line 34) | class DDA {
    method rasteriza (line 36) | public static function rasteriza($ini, $fim) {

FILE: other-languages/math/dda/dda.rb
  function DDA (line 25) | def DDA(x1, y1, x2, y2)

FILE: other-languages/math/determinant/determinant.cpp
  function lu_decomposition (line 32) | void lu_decomposition(float A[n][n], float U[n][n]) {
  function determinant (line 69) | float determinant(float A[n][n]) {
  function main (line 81) | int main( ) {

FILE: other-languages/math/determinant/determinant.rb
  function lu_decompose (line 27) | def lu_decompose(a)
  function determinant (line 67) | def determinant(a)

FILE: other-languages/math/divisors/divisor.rb
  class Numeric (line 18) | class Numeric
    method divisores (line 19) | def divisores()

FILE: other-languages/math/eratostenes/eratostenes.java
  class eratostenes (line 24) | public class eratostenes {
    method eratostenes (line 30) | public static ArrayList<Integer> eratostenes(ArrayList<Integer> lista,...
    method main (line 107) | public static void main(String[] args) {

FILE: other-languages/math/even/even.c
  function numerosPares (line 24) | void numerosPares(int num){
  function numerosPares_2 (line 55) | void numerosPares_2(int num) {
  function main (line 64) | int main(){

FILE: other-languages/math/fatorial/fatorial.cs
  class MainClass (line 22) | class MainClass
    method fatorial (line 24) | static public double fatorial(int num)
    method Main (line 29) | public static void Main (string[] args)

FILE: other-languages/math/fatorial/fatorial.php
  function fatorial (line 19) | function fatorial($b) {

FILE: other-languages/math/fatorial/fatorial.rb
  function fatorial (line 20) | def fatorial(b)

FILE: other-languages/math/fibonacci/fibonacci.c
  function fibonacci_recursivo (line 22) | unsigned int fibonacci_recursivo(unsigned int nTermo) {
  function fibonacci_iterativo (line 35) | unsigned int fibonacci_iterativo(unsigned int nTermo) {
  function main (line 63) | int main(int argc, char* argv[]) {

FILE: other-languages/math/fibonacci/fibonacci.cs
  class Fibonacci (line 22) | public class Fibonacci {
    method fibonacci_recursivo (line 24) | public static uint fibonacci_recursivo(uint ntermo) {
    method fibonacci_iterativo (line 40) | public static uint fibonacci_iterativo(uint ntermo) {
    method Main (line 65) | public static void Main() {

FILE: other-languages/math/fibonacci/fibonacci.java
  class fibonacci (line 20) | public class fibonacci {
    method fibonacci_recursivo (line 22) | public static int fibonacci_recursivo(int ntermo) {
    method fibonacci_iterativo (line 38) | public static int fibonacci_iterativo(int ntermo) {
    method main (line 63) | public static void main(String[] args) {

FILE: other-languages/math/fibonacci/fibonacci.php
  function fibonacci (line 25) | function fibonacci($n) {

FILE: other-languages/math/fibonacci/fibonacci.rb
  class Numeric (line 26) | class Numeric
    method fibonacci (line 27) | def fibonacci

FILE: other-languages/math/gauss/sumgauss.cpp
  function gaussSum (line 25) | int gaussSum(int number)
  function main (line 32) | int main ()

FILE: other-languages/math/geometric-mean/geometric-mean.cpp
  function geometric_mean (line 26) | double geometric_mean(double values[], int n) {
  function main (line 36) | int main( ) {

FILE: other-languages/math/linear-system/linear-system.c
  function escalonaSistemaLinear (line 22) | int escalonaSistemaLinear(double **m, int n, double R[]){

FILE: other-languages/math/lu-decomposition/lu-decomposition.cpp
  function lu_decomposition (line 30) | void lu_decomposition(float A[n][n], float L[n][n], float U[n][n]) {
  function main (line 67) | int main( ) {

FILE: other-languages/math/lu-decomposition/lu-decomposition.rb
  function lu_decompose (line 27) | def lu_decompose(a)

FILE: other-languages/math/matrix-transpose/matrix-transpose.cpp
  function transpose (line 25) | double transpose(int a[m][n], int b[n][m]) {
  function main (line 31) | int main( ) {

FILE: other-languages/math/media-num/media-num.c
  function main (line 24) | void main(){

FILE: other-languages/math/media-num/media-num.rb
  function media (line 20) | def media(*args)

FILE: other-languages/math/media/media.php
  function media (line 21) | function media($n1, $n2, $n3) {

FILE: other-languages/math/media/media.rb
  function media (line 23) | def media(n1, n2, n3)

FILE: other-languages/math/multiply-matrix/multiply-matrix.cpp
  function matrix_multiplication (line 32) | void matrix_multiplication(int a[m][n], int b[n][p], int c[m][p]) {
  function main (line 45) | int main( ) {

FILE: other-languages/math/n-root/MetodosNumericos.java
  class MetodosNumericos (line 22) | public class MetodosNumericos{
    method main (line 24) | public static void main(String args[]){
    method root (line 29) | public static double root (double x, int n, double error_allowed){

FILE: other-languages/math/perfect-numbers/perfectnumber.rb
  function calc_perf (line 22) | def calc_perf(number)

FILE: other-languages/math/pow/pow.c
  function recursive_pow (line 25) | float recursive_pow (float x, int n)
  function main (line 44) | int main(void)

FILE: other-languages/number-theory/euclid/euclid.rb
  function euclides (line 29) | def euclides(a, b)

FILE: other-languages/number-theory/inverse/inverse.c
  function inverse (line 20) | int inverse(int input)
  function main (line 31) | int main()

FILE: other-languages/number-theory/modular-exponentiation/modular-exponentiation.cpp
  function modular_exponentiation (line 26) | int modular_exponentiation(int a, int b, int n) {
  function main (line 51) | int main( ) {

FILE: other-languages/number-theory/odd-even/odd-even.c
  function main (line 26) | void main(void)

FILE: other-languages/number-theory/odd/odd.c
  function numerosImpares (line 23) | void numerosImpares(int num){
  function main (line 54) | int main(){

FILE: other-languages/number-theory/sieve/sieve.cpp
  function eratostenes (line 33) | void eratostenes(bool primo[], int n) {
  function main (line 51) | int main( ) {

FILE: other-languages/pattern-matching/lcs/lcs.rb
  class LCS (line 38) | class LCS
    method initialize (line 39) | def initialize(string1, string2)
    method length (line 44) | def length
    method string (line 49) | def string
    method compute_lcs_matrix (line 57) | def compute_lcs_matrix
    method find_lcs_in_matrix (line 72) | def find_lcs_in_matrix
    method recursive_find_lcs_in_matrix (line 76) | def recursive_find_lcs_in_matrix(i, j)

FILE: other-languages/puzzle/hanoi/hanoi.cpp
  function hanoi (line 34) | void hanoi(int nDiscos, int pInicial = 0,
  function main (line 46) | int main() {

FILE: other-languages/puzzle/sudoku-validation/sudoku-validation.cpp
  function validate_sudoku (line 24) | bool validate_sudoku(int sudoku[9][9]) {
  function main (line 51) | int main( ) {

FILE: other-languages/search/binary-search/BuscaBinaria.java
  class BuscaBinaria (line 22) | public class BuscaBinaria {
    method BuscaBinaria (line 30) | public BuscaBinaria(int[] vetor, int valorProcurado) {
    method getPosicao (line 37) | public int getPosicao() {
    method main (line 55) | public static void main(String[] args) {

FILE: other-languages/search/linear-search/linear-search.rb
  function linear_search (line 25) | def linear_search(array, search)

FILE: other-languages/search/simul-smaller-higher/simul-smaller-higher.cpp
  function min_max (line 37) | void min_max(int a[], int n, int &min, int &max) {
  function main (line 61) | int main( ) {

FILE: other-languages/sequence/token/token.php
  function token (line 19) | function token($comprimento = 6) {

FILE: other-languages/sequence/token/token.rb
  function token (line 21) | def token(length = 10)

FILE: other-languages/sorting/bozosort/bozosort.php
  function bogo (line 21) | function bogo($valores) {

FILE: other-languages/sorting/bozosort/bozosort.rb
  class Array (line 22) | class Array
    method bozosort (line 23) | def bozosort
  class TestBozosort (line 32) | class TestBozosort < Test::Unit::TestCase
    method test_bozosort (line 33) | def test_bozosort

FILE: other-languages/sorting/bubblesort/bubblesort.php
  function bubble (line 23) | function bubble($valores) {

FILE: other-languages/sorting/fisher-yates/fisher-yates.c
  function imprime_vetor (line 45) | void imprime_vetor(int *vetor, int qtde_elementos )
  function main (line 55) | int main()

FILE: other-languages/sorting/heapsort/heapsort.c
  function heapSort (line 35) | void heapSort(int* array, int size) {
  function buildMaxHeap (line 49) | void buildMaxHeap(int* array, int size) {
  function maxHeapify (line 57) | void maxHeapify(int* array, int pos, int n) {
  function swap (line 71) | void swap ( int* v, int i, int j ) {

FILE: other-languages/sorting/insertionsort/insertionsort.cpp
  function insertionSort (line 31) | void insertionSort(int vetor[], int tam)
  function main (line 69) | int main(void)

FILE: other-languages/sorting/insertionsort/insertionsort.php
  function insertionSort (line 26) | function insertionSort($vetor)

FILE: other-languages/sorting/insertionsort/insertionsort.rb
  class Array (line 23) | class Array
    method insertion_sort! (line 24) | def insertion_sort!()

FILE: other-languages/sorting/mergesort/mergesort.c
  function intercala (line 24) | void intercala(int v[], int inicio, int meio, int fim) {
  function mergesort_recursivo (line 62) | void mergesort_recursivo(int v[], int inicio, int fim) {
  function mergesort (line 75) | void mergesort(int v[], int n) {
  function main (line 79) | int main() {

FILE: other-languages/sorting/mergesort/mergesort.rb
  function merge (line 21) | def merge(array, left, mid, right)
  function mergesort (line 53) | def mergesort(array, left, right)

FILE: other-languages/sorting/quicksort/quicksort.c
  function swap (line 27) | void swap (int vector[], int a, int b)
  function quicksort (line 34) | void quicksort(int vector[], int begin, int end)
  function main (line 61) | int main()

FILE: other-languages/sorting/quicksort/quicksort.php
  function quicksort (line 22) | function quicksort($vetor) {

FILE: other-languages/sorting/quicksort/quicksort.rb
  function partition (line 30) | def partition(array, left, right)
  function quicksort (line 47) | def quicksort(array, left, right)

FILE: other-languages/sorting/selectionsort/selectionsort.cpp
  function selection_sort (line 26) | void selection_sort(int a[], int n) {
  function main (line 44) | int main( ) {

FILE: other-languages/sorting/selectionsort/selectionsort.php
  function selection_sort (line 25) | function selection_sort($a) {

FILE: other-languages/sorting/shellsort/shellsort.cpp
  function shell_sort (line 25) | void shell_sort(int a[], int n) {
  function main (line 54) | int main( ) {

FILE: other-languages/sorting/stoogesort/stoogesort.cpp
  function stooge_sort (line 25) | void stooge_sort(int a[], int left, int right) {
  function main (line 40) | int main( ) {
Condensed preview — 202 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (309K chars).
[
  {
    "path": "README.md",
    "chars": 1251,
    "preview": "# 1001 algoritmos para implementar antes de morrer\n\nVamos reunir 1001 implementações de algoritmos em um livro digital i"
  },
  {
    "path": "algorithms/ai/Astar.py",
    "chars": 6870,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo A* \nAutores: \n    Peter Hart, Nils Nilsson and Bertram Raphael \nColaborador:\n \tPé"
  },
  {
    "path": "algorithms/ai/hamming.py",
    "chars": 1134,
    "preview": "# coding: utf-8\n'''\nHamming Distance\nAutor:\n\tHamming\nColaborador:\n\tAdriano Melo <adriano@adrianomelo.com>\n\tDayvid Victor"
  },
  {
    "path": "algorithms/ai/knn.py",
    "chars": 1337,
    "preview": "# coding: utf-8\n'''\nK-Nearest Neighboor (k-NN)\nAutor:\n    Belur V. Dasarathy\nColaborador:\n\tAdriano Melo <adriano@adriano"
  },
  {
    "path": "algorithms/bioinformatics/gc_skew_diagram.py",
    "chars": 661,
    "preview": "# coding: utf-8\n\"\"\"\nSkew Diagram\nAutor:\n\nColaborador:\n    Guido Luz Percú (guidopercu@gmail.com)\nTipo:\n   bioinformatics"
  },
  {
    "path": "algorithms/bioinformatics/reverse_complement.py",
    "chars": 564,
    "preview": "# coding: utf-8\n\"\"\"\nReverse Complement\nAutor:\n\nColaborador:\n    Guido Luz Percú (guidopercu@gmail.com)\nTipo:\n   bioinfor"
  },
  {
    "path": "algorithms/bioinformatics/traducao.py",
    "chars": 1444,
    "preview": "# coding: utf-8\n\"\"\"\nTradução\nAutor:\n\nColaborador:\n    Guido Luz Percú (guidopercu@gmail.com)\nTipo:\n   bioinformatics\nDes"
  },
  {
    "path": "algorithms/bioinformatics/transcricao.py",
    "chars": 504,
    "preview": "# coding: utf-8\n\"\"\"\nTranscrição\nAutor:\n\nColaborador:\n    Guido Luz Percú (guidopercu@gmail.com)\nTipo:\n   bioinformatics\n"
  },
  {
    "path": "algorithms/color/rgb-to-cmyk.py",
    "chars": 2461,
    "preview": "# encoding: utf-8\n\n'''\nRGB to CMYK\nAutor:\n    ?\nColaborador:\n    Aurélio A. Heckert\nTipo:\n    color\nDescrição:\n    Conve"
  },
  {
    "path": "algorithms/combinatory/derangement.py",
    "chars": 556,
    "preview": "#!usr/bin/python\n# encoding: utf-8\n\n\"\"\"\nDesarranjo\nAutor:\n    Pierre Raymond de Montmort\nColaborador:\n    Carlos Rodrigu"
  },
  {
    "path": "algorithms/crypto/cesar.py",
    "chars": 1713,
    "preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\n\"\"\"\nCesar Cipher (Cifra de César)\nAutor:\n    César\nColaborador:\n    Apu"
  },
  {
    "path": "algorithms/crypto/rot13.py",
    "chars": 1078,
    "preview": "#!/usr/bin/env python3.1\n\n\"\"\"\nROT13\nAutor:\n    ?\nColaborador:\n    Fernando Medeiros <fekomedeiros - at - gmail.com>\nTipo"
  },
  {
    "path": "algorithms/crypto/rsa.py",
    "chars": 1307,
    "preview": "#!/usr/bin/python\n# -*- coding: iso-8859-1 -*-\n\"\"\"\nRSA\nAutor:\n    Ron Rivest, Adi Shamir, e Leonard Adleman \nColaborador"
  },
  {
    "path": "algorithms/crypto/vigenere.py",
    "chars": 1832,
    "preview": "#!usr/bin/python\n# encoding: utf-8\n\n\"\"\"\nVigenère cipher (Cifra de Vigenère)\nAutor:\n  Giovan Battista Bellaso (1553) \"La "
  },
  {
    "path": "algorithms/data-structures/arraysum.py",
    "chars": 492,
    "preview": "# coding: utf-8\n'''\nArray Sum\nAutor:\n    ?\nColaborador:\n    Dayvid Victor (victor.dvro@gmail.com)\nDescricao:\n    Esse pr"
  },
  {
    "path": "algorithms/data-structures/heap.py",
    "chars": 2059,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nBinary Heap\nAutor:\n    M. D. ATKINSON, J. R. SACK, N. SANTORO, and T. STROTHOTT\nColaborado"
  },
  {
    "path": "algorithms/data-structures/stack.py",
    "chars": 1070,
    "preview": "\n\"\"\"\nStack\nAutor:\n    ?\nColaborador:\n    Guido Luz Percú (guidopercu@gmail.com)\nTipo:\n    data-structures\nDescrição:\n   "
  },
  {
    "path": "algorithms/date/leap-year.py",
    "chars": 581,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nBissexto\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz . at . gmail . com>\nT"
  },
  {
    "path": "algorithms/economics/financiamento.py",
    "chars": 513,
    "preview": "# -*- encoding: utf-8 -*-\n\n\"\"\"\nFinanciamento\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nTipo"
  },
  {
    "path": "algorithms/geography/haversine.py",
    "chars": 1212,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nHaversine\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz . at . gmail . com>\n"
  },
  {
    "path": "algorithms/graphs/BellmanFord.py",
    "chars": 5598,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo de Bellman-Ford.\n\nAutor:\n\tRichard Bellman & Lester R. Ford Jr. (1958)\n\nColaborado"
  },
  {
    "path": "algorithms/graphs/Dijkstra.py",
    "chars": 2192,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo de Dijkstra (com lista de adjascencias)\nAutores: \n    Edsger Dijkstra\nColaborador"
  },
  {
    "path": "algorithms/graphs/EdmondsKarp.py",
    "chars": 4035,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo de Edmonds-Karp.\n\nAutor:\n  Jack Edmonds & Richard Karp (1972)\n\nColaborador:\n  Ped"
  },
  {
    "path": "algorithms/graphs/FloydWarshall.py",
    "chars": 2895,
    "preview": " \n# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo de Floyd-Warshall.\n\nAutor:\n\tRobert W. Floyd & Stephen Warshall (1962)\n\nColabora"
  },
  {
    "path": "algorithms/math/algebra/bhaskara.py",
    "chars": 627,
    "preview": "# encoding: utf-8\n\n\"\"\"\nBhaskara\nAutor:\n    Bhaskara Akaria [1]\nColaborador:\n    Karlisson Bezerra\nTipo:\n    math\nDescriç"
  },
  {
    "path": "algorithms/math/algebra/dda.py",
    "chars": 1145,
    "preview": "'''\r\nDDA (Digital Differential Analyzer)\r\nAutor:\r\n    ?\r\nColaborador:\r\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho22"
  },
  {
    "path": "algorithms/math/algebra/media-num.py",
    "chars": 466,
    "preview": "# -*- encoding: utf-8 -*-\n\n\"\"\"\nMedia Numerica\nAutor:\n    ?\nColaborador:\n\tBruno Lara Tavares <bruno.exz@gmail.com>\n    Gu"
  },
  {
    "path": "algorithms/math/algebra/media.py",
    "chars": 473,
    "preview": "# encoding: utf-8\n\n\"\"\"\nCálculo da média ponderada\nAutor:\n    ?\nColaborador:\n    Karlisson Bezerra\nTipo:\n    math\nDescriç"
  },
  {
    "path": "algorithms/math/algebra/permutation.py",
    "chars": 896,
    "preview": "# encoding: utf-8\n\n\"\"\"\nPermutation\nAutor:\n    Fabian Stedma\nColaborador:\n    Bruno Gabriel dos Santos (bruno.gsantos89@g"
  },
  {
    "path": "algorithms/math/bisection-method.py",
    "chars": 974,
    "preview": "# encoding: utf-8\n\"\"\"\nMétodo da Bisseção\nAutor:\n    ?\nColaborador:\n    Lucas Andrade (lucasfael@gmail.com)\nTipo:\n    mat"
  },
  {
    "path": "algorithms/math/linear-algebra/matrix-transpose.py",
    "chars": 613,
    "preview": "# coding: utf-8\n'''\nTransposição de matrizes\nAutor: \n    ?\nColaborador:\n    Dayvid Victor (victor.dvro@gmail.com)\nTipo:\n"
  },
  {
    "path": "algorithms/math/luhn.py",
    "chars": 996,
    "preview": "# coding: utf-8\n'''\nAlgorítimo de Luhn\nAutor:\n    Hans Peter Luhn\nColaborador:\n    Alberto Chvaicer <achvaicer@gmail.com"
  },
  {
    "path": "algorithms/math/number-theory/bozofactoring.py",
    "chars": 676,
    "preview": "# encoding: utf-8\n\n\"\"\"\nBozo factoring\nAutor:\n    Ricardo Bittencourt\nColaborador:\n    Ricardo Bittencourt (bluepenguin@g"
  },
  {
    "path": "algorithms/math/number-theory/divisors.py",
    "chars": 266,
    "preview": "# * encoding: UTF-8 *\n\n\"\"\"\nDivisors\nAutor:\n    ?\nColaborador:\n    ?\nDescricao:\n   Mostra os divisores de um número\nCompl"
  },
  {
    "path": "algorithms/math/number-theory/eratosthenes.py",
    "chars": 792,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nCrivo de Eratóstenes\nAutor:\n    Eratóstenes de Cirene\nColaborador:\n    Juan Lopes (me@juan"
  },
  {
    "path": "algorithms/math/number-theory/euclid.py",
    "chars": 873,
    "preview": "# encoding: utf-8\n\n\"\"\"\nAlgoritmo de Euclides\nAutor:\n    Euclides de Alexandria\nColaborador:\n    Liquen \nTipo:\n    number"
  },
  {
    "path": "algorithms/math/number-theory/fatorial.py",
    "chars": 304,
    "preview": "# encoding: utf-8\n\n\"\"\"\nCálculo de fatorial\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nTipo:\n"
  },
  {
    "path": "algorithms/math/number-theory/fibonacci-matrix-form.py",
    "chars": 1639,
    "preview": "# coding: utf-8\n\"\"\"\n * Sequência de Fibonacci\n *\n * Autor:\n *   Antonio Ribeiro <alvesjunior.antonio@gmail.com>\n * Tipo:"
  },
  {
    "path": "algorithms/math/number-theory/fibonacci.py",
    "chars": 875,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\n * Sequência de Fibonacci\n *\n * Autor:\n *   Felipe Djinn <felipe@felipedjinn.com.br>\n * Co"
  },
  {
    "path": "algorithms/math/number-theory/miller-rabin.py",
    "chars": 1233,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nTeste de primalidade de Miller-Rabin\nAutor:\n    Gary L Miller e Michael O. Rabin\nColaborad"
  },
  {
    "path": "algorithms/math/number-theory/newton_raphson_sqrt.py",
    "chars": 1487,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nCálculo da raíz quadrada através do método de Newton-Raphson\nAutor:\n     Isaac Newton e Jo"
  },
  {
    "path": "algorithms/math/number-theory/perfectnumber.py",
    "chars": 879,
    "preview": "# encoding: utf-8\n\"\"\" \nNúmeros perfeitos\nAutor: \n      ?\nColaborador:\n      Anna Cruz (anna.cruz@gmail.com)\nTipo:\n    ma"
  },
  {
    "path": "algorithms/math/number-theory/pow.py",
    "chars": 463,
    "preview": "# coding: utf-8\n'''\nExponenciação\nAutor: \n    \t?\nColaborador:\n    \tDayvid Victor (victor.dvro@gmail.com)\nTipo:\n    \tmath"
  },
  {
    "path": "algorithms/math/number-theory/powmod.py",
    "chars": 560,
    "preview": "# coding: utf-8\n'''\nExponenciação Modular\nAutor: \n    ?\nColaborador:\n    Juan Lopes <me@juanlopes.net>\nTipo:\n    math\nDe"
  },
  {
    "path": "algorithms/math/number-theory/stirling.py",
    "chars": 517,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\n Fórmula de Stirling\n\n Autor:\n   Pedro Menezes <eu@pedromenezes.com>\n   DiogoK <diogo@diog"
  },
  {
    "path": "algorithms/misc/helloworld.py",
    "chars": 209,
    "preview": "\"\"\"\nHelloworld\nAutor:\n    ?\nColaborador:\n    Karlisson - contato@nerdson.com\nTipo:\n    misc\nDescrição:\n    Imprime a str"
  },
  {
    "path": "algorithms/optimization/inteval_scheduling.py",
    "chars": 2774,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo guloso de agendamento de intervalos\n\nAutor:\n\nColaborador:\n\tPedro Arthur Duarte (J"
  },
  {
    "path": "algorithms/optimization/knapsack.py",
    "chars": 5003,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo da Mochila\n\nAutor:\n\nColaborador:\n\tPedro Arthur Duarte (JEdi)\n\tpedroarthur.jedi@gm"
  },
  {
    "path": "algorithms/pattern-matching/AhoCorasick.py",
    "chars": 2573,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo de Aho-Corasick.\n\nAutor:\n\tAlfred Aho and Margaret Corasick (1975)\n\nColaborador:\n\t"
  },
  {
    "path": "algorithms/pattern-matching/hamming.py",
    "chars": 771,
    "preview": "# coding: utf-8\n\"\"\"\nHamming Distance\nAutor:\n    Richard Hamming\nColaborador:\n    Guido Luz Percú (guidopercu@gmail.com)\n"
  },
  {
    "path": "algorithms/pattern-matching/kmp.py",
    "chars": 1063,
    "preview": "# -*- encoding: utf-8 -*-\n\"\"\"\nKMP (Knuth-Morris-Pratt) algorithm\nAutor:\n    Donald Knuth, Vaughan Pratt and James H. Mor"
  },
  {
    "path": "algorithms/pattern-matching/levenshtein.py",
    "chars": 1971,
    "preview": "# coding: utf-8\n'''\nDistância Levenshtein\nAutor:\n    Vladimir Levenshtein (1965)\nColaborador:\n    Flávio Juvenal da Silv"
  },
  {
    "path": "algorithms/physics/ballistic.py",
    "chars": 1742,
    "preview": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nBalistica\nAutor:\n    ?\nColaborador:    \n    GabrielBap <gabrielbap1@g"
  },
  {
    "path": "algorithms/search/binary-search.py",
    "chars": 1095,
    "preview": "# coding: utf-8\n'''\nBusca Binária\n\nAutor: \n    \tJon Bentley\nColaborador:\n    \tDayvid Victor (victor.dvro@gmail.com)\nTipo"
  },
  {
    "path": "algorithms/search/linear-search.py",
    "chars": 761,
    "preview": "# encoding: utf-8\n\n\n\"\"\"\n  Linear Search\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\n    José "
  },
  {
    "path": "algorithms/sequence/token.py",
    "chars": 520,
    "preview": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nToken\n\nAutor:\n    ?\nColaborador:\n    Felipe Djinn <felipe@felipedjinn"
  },
  {
    "path": "algorithms/sorting/bozosort.py",
    "chars": 832,
    "preview": "# encoding: utf-8\n\n\"\"\"\nBozosort\nAutor:\n    Bozo\nColaborador:\n    Karlisson Bezerra\nTipo:\n    sorting\nDescrição:\n    Emba"
  },
  {
    "path": "algorithms/sorting/bubblesort.py",
    "chars": 566,
    "preview": "# encoding: utf-8\n\n\"\"\"\nBubblesort\nAutor:\n    ?\nTipo:\n    sorting\nDescrição:\n    Varre o vetor comparando cada um dos par"
  },
  {
    "path": "algorithms/sorting/dropsort.py",
    "chars": 1192,
    "preview": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*- \n\"\"\"\nNome do algoritmo\nAutor:\n    David Morgan-Mar. <dmm@dangermouse.net>"
  },
  {
    "path": "algorithms/sorting/insertionsort.py",
    "chars": 614,
    "preview": "#!/usr/bin/env python\n# encoding: utf-8\n\n'''\nInsertion Sort\nAutor: \n    ?\nTipo:\n    sorting\nDescrição:\n    Percorre uma "
  },
  {
    "path": "algorithms/sorting/masochisticsort.py",
    "chars": 1272,
    "preview": "#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nMasochistic Sort\nAuthor:\n    Dilan Nery <dnerylopes AT gmail DOT com>\nColabor"
  },
  {
    "path": "algorithms/sorting/mergesort.py",
    "chars": 984,
    "preview": "# coding: utf-8\n\n\"\"\"\nMergesort\nAutor:\n\tJohn von Neumann, em 1945\nColaborador:\n\tAdriano Melo (adriano@adrianomelo.com)\n\tD"
  },
  {
    "path": "algorithms/sorting/quicksort.py",
    "chars": 1113,
    "preview": "# coding: utf-8\n\"\"\"\nQuicksort\nAutor:\n    C.A.R. Hoare\nColaborador:\n    Adriano Melo (adriano@adrianomelo.com)\n    Juan L"
  },
  {
    "path": "algorithms/sorting/selectionsort.py",
    "chars": 624,
    "preview": "# encoding: utf-8\n'''\nInsertion Sort\nAutor:\n    ?\nColaborador:\n\tBruno Coimbra <bbcoimbra@gmail.com>\nTipo:\n    sorting\nDe"
  },
  {
    "path": "algorithms/sorting/sleepsort.py",
    "chars": 1204,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nSleepsort\nAutor:\n    ?\nColaborador:\n    Saulo Andrade Almeida <sauloandrade@gmail.com>\nTipo"
  },
  {
    "path": "modelo.txt",
    "chars": 599,
    "preview": "\n\"\"\"\nNome do algoritmo\nAutor:\n    Nome do autor do algoritmo ou ? caso nao saiba\nColaborador:\n    Seu nome e email\nTipo:"
  },
  {
    "path": "other-languages/ai/genealogicaltree/genealogicaltree.pro",
    "chars": 1378,
    "preview": "/*\nÁrvore Genealógica\nAutor:\n    ???\nColaborador:\n    Filipe Saraiva (filip.saraiva@gmail.com)\nTipo:\n    ai\nDescrição:\n "
  },
  {
    "path": "other-languages/ai/sokoban/alberta/screen.1",
    "chars": 227,
    "preview": "11 19\n###################\n#####...###########\n#####o..###########\n#####..o###########\n###..o.o.##########\n###.#.##.#####"
  },
  {
    "path": "other-languages/ai/sokoban/alberta/screen.1.sol",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "other-languages/ai/sokoban/alberta/screen.31",
    "chars": 312,
    "preview": "16 18\n##################\n###..#############\n###..##..#...#####\n##..o#.oIo...#####\n##o..o..#.o.o#..##\n##..o##.#o.o.....#\n"
  },
  {
    "path": "other-languages/ai/sokoban/runtests.sh",
    "chars": 2691,
    "preview": "echo \"As saídas do programa são jogadas nos arquivos .sol\"\ng++ -O2 -o sokoban sokoban.cpp\n\necho \"teste 1\"\n ./sokoban < s"
  },
  {
    "path": "other-languages/ai/sokoban/sokoban.cpp",
    "chars": 11682,
    "preview": "/*\n# -*- coding: utf-8 -*-\n\n\"\"\"\nAlgoritmo A* aplicado na resolução de um sokoban + representação de estados \npor meio de"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.in",
    "chars": 104,
    "preview": "9 9\r\n#########\r\n#I..#####\r\n#.oo#####\r\n#.o.###x#\r\n###.###x#\r\n###....x#\r\n##...#..#\r\n##...####\r\n#########\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.out",
    "chars": 2820,
    "preview": "59\n#########\n#...#####\n#.oI#####\n#.oo###x#\n###.###x#\n###....x#\n##...#..#\n##...####\n#########\n\n60\n#########\n#...#####\n#.o"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-01.sol",
    "chars": 2820,
    "preview": "59\n#########\n#...#####\n#.oI#####\n#.oo###x#\n###.###x#\n###....x#\n##...#..#\n##...####\n#########\n\n60\n#########\n#...#####\n#.o"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.in",
    "chars": 114,
    "preview": "9 10\r\n##########\r\n#xx......#\r\n#xxo..#..#\r\n#..#o##.##\r\n#.o.....##\r\n#####.#.##\r\n###.o.I.##\r\n###.....##\r\n##########\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.out",
    "chars": 3193,
    "preview": "28\n##########\n#xx......#\n#xxo..#..#\n#..#o##.##\n#.o.....##\n#####.#.##\n###.Io..##\n###.....##\n##########\n\n29\n##########\n#xx"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-02.sol",
    "chars": 3193,
    "preview": "28\n##########\n#xx......#\n#xxo..#..#\n#..#o##.##\n#.o.....##\n#####.#.##\n###.Io..##\n###.....##\n##########\n\n29\n##########\n#xx"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.in",
    "chars": 69,
    "preview": "8 6\r\n######\r\n##..##\r\n#Io.##\r\n##o.##\r\n##.o.#\r\n#xo..#\r\n#xxOx#\r\n######\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.out",
    "chars": 780,
    "preview": "20\n######\n##..##\n#.Io##\n##o.##\n##.o.#\n#xo..#\n#xxOx#\n######\n\n21\n######\n##..##\n#..o##\n##I.##\n##oo.#\n#xo..#\n#xxOx#\n######\n\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-03.sol",
    "chars": 780,
    "preview": "20\n######\n##..##\n#.Io##\n##o.##\n##.o.#\n#xo..#\n#xxOx#\n######\n\n21\n######\n##..##\n#..o##\n##I.##\n##oo.#\n#xo..#\n#xxOx#\n######\n\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.in",
    "chars": 85,
    "preview": "8 8\r\n########\r\n##I.####\r\n##.o..##\r\n###.#.##\r\n#x#.#..#\r\n#xo..#.#\r\n#x...o.#\r\n########\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.out",
    "chars": 760,
    "preview": "40\n########\n##..####\n##.I..##\n###o#.##\n#x#.#..#\n#xo..#.#\n#x...o.#\n########\n\n41\n########\n##..####\n##....##\n###o#.##\n#x#.#"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-04.sol",
    "chars": 760,
    "preview": "40\n########\n##..####\n##.I..##\n###o#.##\n#x#.#..#\n#xo..#.#\n#x...o.#\n########\n\n41\n########\n##..####\n##....##\n###o#.##\n#x#.#"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.in",
    "chars": 90,
    "preview": "7 10\r\n##########\r\n##.....###\r\n##o###...#\r\n#.I.o..o.#\r\n#.xx#.o.##\r\n##xx#...##\r\n##########\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.out",
    "chars": 2120,
    "preview": "88\n##########\n##.....###\n##o###...#\n#...Io.o.#\n#.xx#.o.##\n##xx#...##\n##########\n\n89\n##########\n##.....###\n##o###...#\n#.."
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-05.sol",
    "chars": 2120,
    "preview": "88\n##########\n##.....###\n##o###...#\n#...Io.o.#\n#.xx#.o.##\n##xx#...##\n##########\n\n89\n##########\n##.....###\n##o###...#\n#.."
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.in",
    "chars": 176,
    "preview": "13 11\r\n###########\r\n########I.#\r\n########..#\r\n####......#\r\n#...x###.##\r\n#.#.#....##\r\n#.#.o.o#x.#\r\n#.#..O..#.#\r\n#.x#o.o.#"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.out",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-06.sol",
    "chars": 3703,
    "preview": "107\n###########\n########..#\n########..#\n####......#\n#...x###.##\n#.#.#....##\n#.#oI.o#x.#\n#.#..O..#.#\n#.x#o.o.#.#\n##....#."
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.in",
    "chars": 93,
    "preview": "8 9\r\n#########\r\n###..#.I#\r\n##...#..#\r\n##o.o.o.#\r\n##.o##..#\r\n##.o.#.##\r\nxxxxx..##\r\n#########\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-07.sol",
    "chars": 2436,
    "preview": "50\n#########\n###..#..#\n##...#..#\n##o.o.o.#\n##.o##..#\n##oI.#.##\nxxxxx..##\n#########\n\n51\n#########\n###..#..#\n##...#..#\n##o"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.in",
    "chars": 83,
    "preview": "7 10\n##########\n####....##\n##x.o##.##\n#xxo.o..I#\n#xx.o.o.##\n#####...##\n##########\n\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-08.sol",
    "chars": 1215,
    "preview": "29\n##########\n####....##\n##x.o##.##\n#xxooI...#\n#xx.o.o.##\n#####...##\n##########\n\n30\n##########\n####....##\n##x.o##.##\n#xx"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.in",
    "chars": 114,
    "preview": "9 11\n###########\n##..##...##\n##...o...##\n##o.###.o##\n##.#xxx#.##\n##.#xxx#.##\n#.o..o..o.#\n#.....#.I.#\n###########\n\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk01-09.sol",
    "chars": 4520,
    "preview": "130\n###########\n##..##...##\n##...o...##\n##o.###.o##\n##.#xxx#.##\n##.#xOx#.##\n#.o..I..o.#\n#.....#...#\n###########\n\n131\n###"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.in",
    "chars": 75,
    "preview": "7 8\r\n########\r\n#..#...#\r\n#.oxxo.#\r\n#IoxO.##\r\n#.oxxo.#\r\n#..#...#\r\n########\r\n"
  },
  {
    "path": "other-languages/ai/sokoban/sokobanonline/classic/thinkingrabbit/Boxxle/sk02-10.sol",
    "chars": 938,
    "preview": "41\n########\n#..#...#\n#.IOxo.#\n#.oxO.##\n#.oxxo.#\n#..#...#\n########\n\n42\n########\n#..#...#\n#..Oxo.#\n#.oxO.##\n#.IOxo.#\n#..#."
  },
  {
    "path": "other-languages/ai/sudoku/sudoku.cpp",
    "chars": 7871,
    "preview": "/*\n# -*- coding: utf-8 -*-\n\n\"\"\"\nBacktracking e Heurísticas aplicadas para se resolver um sudoku.\nA busca é feita no graf"
  },
  {
    "path": "other-languages/ai/sudoku/test_001.in",
    "chars": 93,
    "preview": "1\n103000509\n002109400\n000704000\n300502006\n060000050\n700803004\n000401000\n009205800\n804000107\n\n"
  },
  {
    "path": "other-languages/array/merge/merge.rb",
    "chars": 1018,
    "preview": "\n=begin\n  Merge\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n    array-opera"
  },
  {
    "path": "other-languages/array/partition/partition.rb",
    "chars": 1513,
    "preview": "\n=begin\n  Partition\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n    array-o"
  },
  {
    "path": "other-languages/bitwise/BitScanForwardDebruijn64.cs",
    "chars": 1190,
    "preview": "//BitScanForward com De Bruijn (64 bits)\n//Autor:\n//    Juan Lopes <juanplopes@gmail.com>\n//Tipo:\n//    bitwise\n//Descri"
  },
  {
    "path": "other-languages/bitwise/HammingWeight64.cs",
    "chars": 1015,
    "preview": "//Hamming Weight (64 bits)\n//Autor:\n//    Juan Lopes <juanplopes@gmail.com>\n//Tipo:\n//    bitwise\n//Descrio:\n//    Conta"
  },
  {
    "path": "other-languages/bitwise/bsf-debruijn/BitScanForwardDebruijn64.cs",
    "chars": 1148,
    "preview": "//BitScanForward com De Bruijn (64 bits)\n//Autor:\n//     Nicolaas Govert de Bruijn\n//Tipo:\n//    bitwise\n//Descrio:\n//  "
  },
  {
    "path": "other-languages/bitwise/dec2hex/dec2hex.c",
    "chars": 634,
    "preview": "/*\nConversor Decimal/Hexadecimal\nAutor:\n    ?\nColaborador:\n    Ramon Caldeira Faria (ramoncaldeira_328@hotmail.com)\nTipo"
  },
  {
    "path": "other-languages/bitwise/hamming-weight/HammingWeight64.cs",
    "chars": 948,
    "preview": "//Hamming Weight (64 bits)\n//Autor:\n//    ?\n//Tipo:\n//    bitwise\n//Descrio:\n//    Conta o nmero de bits ligados\n//    e"
  },
  {
    "path": "other-languages/bitwise/operations/operations.cpp",
    "chars": 828,
    "preview": "/*\nOperações bitwise\nAutor:\n    ?\nColaborador:\n    Ramon Caldeira (ramoncaldeira_328@hotmail.com)\nTipo:\n    bitwise\nDesc"
  },
  {
    "path": "other-languages/bitwise/swap_xor/swap_xor.c",
    "chars": 888,
    "preview": "/*\r\nAlgoritimo de troca de variveis\r\nAutor:\r\n    ?\r\nColaborador:\r\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@ho"
  },
  {
    "path": "other-languages/bitwise/swap_xor/swap_xor.cs",
    "chars": 934,
    "preview": "/*\nAlgoritimo de troca de variveis\nAutor:\n    ?\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hotmail"
  },
  {
    "path": "other-languages/bitwise/swap_xor/swap_xor.php",
    "chars": 814,
    "preview": "<?php\r\n/*\r\nAlgoritimo de troca de variveis\r\nAutor:\r\n    ?\r\nColaborador:\r\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho"
  },
  {
    "path": "other-languages/date/leap-year/leap-year.lisp",
    "chars": 287,
    "preview": "#|\nBissexto\nAutor:\n    ?\nColaborador\n    Daniel Valio <valium97@mail.com>\nTipo:\n    date\nComplexidade:\n    O(1)\nDificuld"
  },
  {
    "path": "other-languages/date/leap-year/leap-year.php",
    "chars": 668,
    "preview": "<?php\n\n/*\nBissexto\nAutor:\n    ?\nColaborador:\n    Sérgio Mandrake <sergio_mandrake@yahoo.com.br>\nTipo:\n    date\nDescrição"
  },
  {
    "path": "other-languages/date/leap-year/leap-year.rb",
    "chars": 556,
    "preview": "=begin\n\nBissexto\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz . at . gmail . com>\nTipo:\n    date\nDescriçã"
  },
  {
    "path": "other-languages/economics/financiamento/financiamento.cs",
    "chars": 705,
    "preview": "/*\nFinanciamento\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nTipo:\n    ?\nDescrição:\n\tCalcula "
  },
  {
    "path": "other-languages/economics/financiamento/financiamento.lisp",
    "chars": 395,
    "preview": "#|\nFinanciamento\nAutor:\n    ?\nColaborador:\n    Daniel Valio <valium97@mail.com>\nTipo:\n    economics\nDescricao:\n    Calcu"
  },
  {
    "path": "other-languages/economics/financiamento/financiamento.php",
    "chars": 582,
    "preview": "<?php\n/**\nFinanciamento\nAutor:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nColaborador:\n    Felipe Djinn <felipe@felipe"
  },
  {
    "path": "other-languages/economics/financiamento/financiamento.rb",
    "chars": 512,
    "preview": "# -*- encoding: utf-8 -*-\n\n=begin\nFinanciamento\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nT"
  },
  {
    "path": "other-languages/economics/juros-compostos/juros-compostos.lisp",
    "chars": 422,
    "preview": "#|\nCalculo de juros compostos\nAutor:\n    ?\nColaborador:\n    Daniel Valio <valium97@mail.com>\nTipo:\n    economics\nDescric"
  },
  {
    "path": "other-languages/geography/haversine/haversine.rb",
    "chars": 1195,
    "preview": "# -*- encoding: utf-8 -*-\n=begin\nHaversine\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz . at . gmail . co"
  },
  {
    "path": "other-languages/graphs/dijkstra/dijkstra.cpp",
    "chars": 3674,
    "preview": "/*\nAlgoritmo de Dijkstra (com matriz de adjacências)\nAutores: \n    Edsger Dijkstra\nColaborador:\n    Luiz Rodrigo (luizro"
  },
  {
    "path": "other-languages/graphs/dijkstra/dijkstra.java",
    "chars": 5978,
    "preview": "/*\nAlgoritmo de Dijkstra\nAutor:\n    Esdger Dijkstra\nColaborador:\n    Filipe Saraiva (filip.saraiva@gmail.com)\nTipo:\n    "
  },
  {
    "path": "other-languages/graphs/floyd-warshall/floyd-warshall.cpp",
    "chars": 1401,
    "preview": "/*\nAlgoritmo de Floyd-Warshall\nAutores: \n    Robert Floyd e Stephen Warshall\nColaborador:\n    Luiz Rodrigo (luizrodri.go"
  },
  {
    "path": "other-languages/graphs/prim/prim.java",
    "chars": 5735,
    "preview": "/*\nAlgoritmo de Prim\nAutor:\n    Vojtěch Jarník(1930) e Robert C. Prim(1957)\nColaborador:\n    Filipe Saraiva (filip.sarai"
  },
  {
    "path": "other-languages/lang/nums2words.c",
    "chars": 4674,
    "preview": "/*\nnums2words\nAutor:\n    ? \nColaborador:\n    Stanislaw Pusep \nTipo:\n    lang\nDescrio:\n    Conversor de nmeros inteiros e"
  },
  {
    "path": "other-languages/math/bhaskara/bhaskara.lisp",
    "chars": 463,
    "preview": "#|\nFormula de Bhaskara \nAutor:\n    Bhaskara Akaria\nColaborador:\n    Daniel Valio\nTipo:\n    math\nDescricao:\n    Calcula a"
  },
  {
    "path": "other-languages/math/bhaskara/bhaskara.php",
    "chars": 622,
    "preview": "<?php\n\t\n/*\nBhaskara\nAutor: \n\tBhaskara Akaria [1]\nColaborador:\n    ?\nTipo: \n\tmath\nDescrio: \n\tCalcula as razes de uma equa"
  },
  {
    "path": "other-languages/math/bhaskara/bhaskara.rb",
    "chars": 628,
    "preview": "# encoding: utf-8\n\n=begin\nBhaskara\nAutor:\n    Bhaskara Akaria [1]\nColaborador:\n\tBruno Lara Tavares <bruno.exz@gmail.com>"
  },
  {
    "path": "other-languages/math/dda/dda.cpp",
    "chars": 1754,
    "preview": "/*\nDDA (Digital Differential Analyzer)\nAutor:\n    ?\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hot"
  },
  {
    "path": "other-languages/math/dda/dda.cs",
    "chars": 1688,
    "preview": "/*\nDDA (Digital Differential Analyzer)\nAutor:\n    ?\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hot"
  },
  {
    "path": "other-languages/math/dda/dda.java",
    "chars": 1498,
    "preview": "/*\nDDA (Digital Differential Analyzer)\nAutor:\n    ?\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2204@hot"
  },
  {
    "path": "other-languages/math/dda/dda.php",
    "chars": 1349,
    "preview": "<?php\n/*\nDDA (Digital Differential Analyzer)\nAutor:\n    ?\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho22"
  },
  {
    "path": "other-languages/math/dda/dda.rb",
    "chars": 1086,
    "preview": "# -*- encoding: utf-8 -*-\r\n\r\n=begin\r\nDDA (Digital Differential Analyzer)\r\nAutor:\r\n    ?\r\nColaborador:\r\n\tBruno Lara Tavar"
  },
  {
    "path": "other-languages/math/determinant/determinant.cpp",
    "chars": 2306,
    "preview": "/*\nDeterminante de matriz (utilizando decomposição LU)\nAutor: \n    Carl Friedrich Gauss\nColaborador:\n    Luiz Rodrigo (l"
  },
  {
    "path": "other-languages/math/determinant/determinant.rb",
    "chars": 1426,
    "preview": "\n=begin\n  Matrix Determinant\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n  "
  },
  {
    "path": "other-languages/math/divisors/divisor.rb",
    "chars": 422,
    "preview": "# * encoding: UTF-8 *\n\n=begin\nDivisors\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nDescricao:"
  },
  {
    "path": "other-languages/math/eratostenes/eratostenes.java",
    "chars": 3768,
    "preview": "/*\nCrivo de Eratóstenes\nAutor:\n    Eratóstenes (285-194 a.C.)\nColaborador:\n    Filipe Saraiva (filip.saraiva@gmail.com)\n"
  },
  {
    "path": "other-languages/math/even/even.c",
    "chars": 1629,
    "preview": "/*\nEncontrando números Pares\nAutor:\n    ???\nColaboradores:\n    Filipe Saraiva (filip.saraiva@gmail.com)\n    Pedro Arthur"
  },
  {
    "path": "other-languages/math/fatorial/fatorial.cs",
    "chars": 562,
    "preview": "/*\nCálculo de fatorial\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nTipo:\n    math\nDescrição:\n"
  },
  {
    "path": "other-languages/math/fatorial/fatorial.lisp",
    "chars": 501,
    "preview": "#|\nFatorial\nAutor\n    ?\nColaborador\n    Daniel Valio <valium97@mail.com>\nTipo\n    math\nDescricao\n    Varias formas difer"
  },
  {
    "path": "other-languages/math/fatorial/fatorial.php",
    "chars": 303,
    "preview": "<?php \n/*\nCálculo de fatorial\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\nTipo:\n    math\nDesc"
  },
  {
    "path": "other-languages/math/fatorial/fatorial.rb",
    "chars": 303,
    "preview": "# -*- encoding: utf-8 -*-\n\n\"\"\"\nCálculo de fatorial\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.c",
    "chars": 1339,
    "preview": "/*\n\tFibonacci recursivo e iterativo\nAutor:\n    Fibonacci\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho220"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.clj",
    "chars": 515,
    "preview": "(comment \nCálculo da sequência de Fibonacci\nAutor \n    ? \nColaborador\n    Guilherme Victal (guilhermevictal em gmail.com"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.cs",
    "chars": 1510,
    "preview": "/*\r\n\tFibonacci recursivo e iterativo\r\nAutor:\r\n    Fibonacci\r\nColaborador:\r\n    Jos Ivan Bezerra Vilarouca Filho (ivanfil"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.java",
    "chars": 1459,
    "preview": "/*\n\tFibonacci recursivo e iterativo\nAutor:\n    Fibonacci\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho220"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.lisp",
    "chars": 482,
    "preview": "#|\nCalculo da sequencia de Fibonacci\nAutor\n    ?\nColaborador\n    Daniel Valio <valium97@mail.com>\nTipo\n    math\nDescrica"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.lua",
    "chars": 1142,
    "preview": "--[[\n\tFibonacci recursivo e iterativo\nAutor:\n    Fibonacci\nColaborador:\n    Jos Ivan Bezerra Vilarouca Filho (ivanfilho2"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.php",
    "chars": 870,
    "preview": "<?php\n/**\n * Sequência de Fibonacci\n *\n * Autor:\n *   ?\n * Colaborador:\n *   Felipe Djinn <felipe@felipedjinn.com.br>\n *"
  },
  {
    "path": "other-languages/math/fibonacci/fibonacci.rb",
    "chars": 914,
    "preview": "# -*- encoding: utf-8 -*-\n=begin\n * Sequência de Fibonacci\n *\n * Autor:\n *   Felipe Djinn <felipe@felipedjinn.com.br>\n *"
  },
  {
    "path": "other-languages/math/gauss/sumgauss.cpp",
    "chars": 722,
    "preview": "/*\n   Soma de Gauus  -  Gauss Sum\nAutores: \n\tCarl Friedrich Gauss    \nColaborador:\n    Kaio Turubia (kaiokot@gmail.com)\n"
  },
  {
    "path": "other-languages/math/geometric-mean/geometric-mean.cpp",
    "chars": 920,
    "preview": "/*\nMédia geométrica\nAutor: \n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTipo:\n    math\nDescrição: \n  "
  },
  {
    "path": "other-languages/math/linear-system/linear-system.c",
    "chars": 1166,
    "preview": "/*\nAlgoritmo para Escalonar Sistemas Lineares\nAutor:\n    ?\nColaborador:\n    ?\nTipo:\n    math\nDescrição:\n    Esta função "
  },
  {
    "path": "other-languages/math/lu-decomposition/lu-decomposition.cpp",
    "chars": 2328,
    "preview": "/*\nDecomposição LU\nAutor: \n    Carl Friedrich Gauss\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTipo: \n    "
  },
  {
    "path": "other-languages/math/lu-decomposition/lu-decomposition.rb",
    "chars": 1419,
    "preview": "\n=begin\n  LU Decomposition\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n    "
  },
  {
    "path": "other-languages/math/matrix-transpose/matrix-transpose.cpp",
    "chars": 900,
    "preview": "/*\nTransposição de matrizes\nAutor: \n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTipo:\n    math\nDescri"
  },
  {
    "path": "other-languages/math/media/media.lisp",
    "chars": 348,
    "preview": "#|\nCalculo de media ponderada\nAutor:\n    ?\nColaborador:\n    Daniel Valio    \nTipo:\n    math\nDescricao:\n    Calcula a med"
  },
  {
    "path": "other-languages/math/media/media.php",
    "chars": 468,
    "preview": "<?php \n\n/*\nClculo da mdia ponderada\nAutor:\n    ?\nColaborador:\n    Karlisson Bezerra\nTipo:\n    math\nDescrio:\n    Calcula "
  },
  {
    "path": "other-languages/math/media/media.rb",
    "chars": 510,
    "preview": "# encoding: utf-8\n\n=begin\nCálculo da média ponderada\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.c"
  },
  {
    "path": "other-languages/math/media-num/media-num.c",
    "chars": 659,
    "preview": "/*\nMedia\nAutor:\n    ?\nColaborador:\n    Guilherme Carlos (@guiessence)\nTipo:\n    math\nDescrição:\n    Calcula a média de n"
  },
  {
    "path": "other-languages/math/media-num/media-num.rb",
    "chars": 444,
    "preview": "# -*- encoding: utf-8 -*-\n\n=begin\nMedia Numerica\nAutor:\n    ?\nColaborador:\n\tBruno Lara Tavares <bruno.exz@gmail.com>\n   "
  },
  {
    "path": "other-languages/math/multiply-matrix/multiply-matrix.cpp",
    "chars": 1360,
    "preview": "/*\nMultiplicação de matrizes (método trivial)\nAutor: \n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTip"
  },
  {
    "path": "other-languages/math/n-root/MetodosNumericos.java",
    "chars": 1367,
    "preview": "/*\nMétodo numérico para resolução de raiz enésima\nAutor:\n    ?\nColaborador:\n    Guilherme de Sales Orioli gui.orioli@gma"
  },
  {
    "path": "other-languages/math/perfect-numbers/perfectnumber.rb",
    "chars": 838,
    "preview": "# encoding: utf-8\n\n=begin\nNúmeros perfeitos\nAutor: \n      ?\nColaborador:\n      Anna Cruz (anna.cruz@gmail.com)\nTipo:\n   "
  },
  {
    "path": "other-languages/math/pow/pow.c",
    "chars": 933,
    "preview": "/*\nExponenciação\nAutor:\n\t?\nColaborador:\n\tDayvid Victor (victor.dvro@gmail.com)\nTipo:\n\tmath\nDescrição:\n\tCalcula a exponen"
  },
  {
    "path": "other-languages/math/stirlings-approximation/stirling.clj",
    "chars": 462,
    "preview": "(defn stirling [n]\n  \"\n  Fórmula de Stirling\n  \n  Autor:\n    Pedro Menezes <eu@pedromenezes.com>\n    DiogoK <diogo@diogo"
  },
  {
    "path": "other-languages/number-theory/euclid/euclid.lisp",
    "chars": 342,
    "preview": "#|\nAlgoritmo de Euclides\nAutor:\n    Euclides de Alexandria\nColaborador:\n    Daniel Valio\nTipo:\n    number-theory\nDescric"
  },
  {
    "path": "other-languages/number-theory/euclid/euclid.rb",
    "chars": 923,
    "preview": "# encoding: utf-8\n\n=begin\nAlgoritmo de Euclides\nAutor:\n    Euclides de Alexandria\nColaborador:\n    Bruno Lara Tavares <b"
  },
  {
    "path": "other-languages/number-theory/inverse/inverse.c",
    "chars": 565,
    "preview": "/*\n\nInverse\nAutor:\n    JoseFernandoTolentino (JoseFernandoTolentino@gmail.com)\nTipo:\n    number-theory\nDescrição:\n    In"
  },
  {
    "path": "other-languages/number-theory/modular-exponentiation/modular-exponentiation.cpp",
    "chars": 1455,
    "preview": "/*\nExponenciação modular (utilizando representação binária)\nAutor: \n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@ho"
  },
  {
    "path": "other-languages/number-theory/odd/odd.c",
    "chars": 1382,
    "preview": "/*\nEncontrando números Ímpares\nAutor:\n    ???\nColaborador:\n    Filipe Saraiva (filip.saraiva@gmail.com)\nTipo:\n    math\nD"
  },
  {
    "path": "other-languages/number-theory/odd-even/odd-even.c",
    "chars": 753,
    "preview": "/*\nPar ou impar\nAutor:\n    ?\nColaboradores:\n    Geraldo Neto email (glnetinho@hotmail.com)\n    Prdro Arthur Duarte (pedr"
  },
  {
    "path": "other-languages/number-theory/sieve/sieve.cpp",
    "chars": 1391,
    "preview": "/*\nCrivo de Eratóstenes\nAutor:\n    Eratóstenes de Cirene\nColaborador:\n    ?\nTipo:\n    number-theory\nDescrição:\n    O Cri"
  },
  {
    "path": "other-languages/number-theory/sieve/sieve.lisp",
    "chars": 1082,
    "preview": "#|\nCrivo de Eratostenes\nAutor:\n    Eratostenes de Cirene\nColaborador:\n    Daniel Valio <valium97@mail.com>\nTipo:\n    num"
  },
  {
    "path": "other-languages/pattern-matching/lcs/lcs.rb",
    "chars": 3219,
    "preview": "# LCS (Longest Common Subsequence)\n# Autor:\n#   ?\n# Colaborador:\n#   Luiz Fernando Oliveira Corte Real <luiz@vidageek.ne"
  },
  {
    "path": "other-languages/physics/ballistic/ballistic.lisp",
    "chars": 623,
    "preview": "#|\nBalistica\nAutor:\n    ?\nColaborador:\n    Daniel Valio <valium97@mail.com>\nTipo:\n    physics\nComplexidade:\n    O(1)\nDif"
  },
  {
    "path": "other-languages/puzzle/hanoi/hanoi.cpp",
    "chars": 1240,
    "preview": "/*\nTorre de Hanói\nAutor:\n    ?\nColaborador:\n    Ramon Caldeira (ramoncaldeira_328@hotmail.com)\nTipo:\n    misc\nDescrição:"
  },
  {
    "path": "other-languages/puzzle/sudoku-validation/sudoku-validation.cpp",
    "chars": 1659,
    "preview": "/*\nValida solução de sudoku\nAutor:\n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTipo:\n    puzzle\nDescr"
  },
  {
    "path": "other-languages/search/binary-search/BuscaBinaria.java",
    "chars": 2204,
    "preview": "/*\n * BuscaBinaria\n * Autor:\n *     Jon Bentley\n * Colaborador:\n *     Fabiano Sobreira\n * Tipo:\n *     search\n * Descri"
  },
  {
    "path": "other-languages/search/linear-search/linear-search.rb",
    "chars": 684,
    "preview": "\n=begin\n  Linear Search\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n    sea"
  },
  {
    "path": "other-languages/search/simul-smaller-higher/simul-smaller-higher.cpp",
    "chars": 1891,
    "preview": "/*\nMenor e maior elemento simultâneo\nAutor: \n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTipo: \n    s"
  },
  {
    "path": "other-languages/sequence/token/token.php",
    "chars": 577,
    "preview": "<?php\n\n/*\nToken\nAutor:\n    Sérgio Mandrake <sergio_mandrake@yahoo.com.br>\nColaborador:\n    Sérgio Mandrake <sergio_mandr"
  },
  {
    "path": "other-languages/sequence/token/token.rb",
    "chars": 475,
    "preview": "# -*- coding: UTF-8 -*-\n\n=begin\nToken\n\nAutor:\n    ?\nColaborador:\n    Bruno Lara Tavares <bruno.exz@gmail.com>\n    Felipe"
  },
  {
    "path": "other-languages/sorting/bozosort/bozosort.lisp",
    "chars": 484,
    "preview": "#|\nBozosort (a.k.a Bogosort)\nAutor:\n    Bozo\nTipo:\n    sorting\nDescricao:\n    Embaralha um vetor indefinidamente, ate' q"
  },
  {
    "path": "other-languages/sorting/bozosort/bozosort.php",
    "chars": 664,
    "preview": "<?php\n\t\n/*\nBozosort (a.k.a Bogosort)\nAutor: \n\tBozo\nColaborador:\n    Maurcio Sipmann (sipmann@gmail.com)\nTipo: \n\tsorting\n"
  },
  {
    "path": "other-languages/sorting/bozosort/bozosort.rb",
    "chars": 678,
    "preview": "=begin\nBozosort\nAutor:\n    Bozo\nColaborador:\n    Caio\nTipo:\n    sorting\nDescrição:\n    Embaralha um vetor indefinidament"
  },
  {
    "path": "other-languages/sorting/bubblesort/bubblesort.lisp",
    "chars": 482,
    "preview": "#|\nBubble sort\nAutor: Desconhecido\nTipo:  Ordenacao de vetores\nDescricao: Compara elementos dois a dois e checa se estao"
  },
  {
    "path": "other-languages/sorting/bubblesort/bubblesort.php",
    "chars": 780,
    "preview": "<?php\n\t\n/*\nBubblesort\nAutor: \n\t?\nColaborador:\n\tMaurcio Sipmann (sipmann@gmail.com)\nTipo: \n\tsorting\nDescrio: \n\tVarre o ve"
  },
  {
    "path": "other-languages/sorting/fisher-yates/fisher-yates.c",
    "chars": 1653,
    "preview": "/*\nFisher–Yates shuffle, Knuth shuffle (Durstenfeld's Solution)\nAutor:\n    Ronald Fisher, Frank Yattes, Donald Knuth, Ri"
  },
  {
    "path": "other-languages/sorting/heapsort/heapsort.c",
    "chars": 1647,
    "preview": "/*\nHeap Sort\nAutor:\n    Robert W. Floyd e J.W.J. Williams.\nColaborador:\n    Ramon Caldeira Faria (ramoncaldeira_328@hotm"
  },
  {
    "path": "other-languages/sorting/insertionsort/insertionsort.cpp",
    "chars": 1776,
    "preview": "/*\nInsertionSort\nAutor:\n    ?\nColaborador:    \n    Willian\nTipo:\n    sorting\nDescrição:\n    Varre o vetor organizando-o "
  },
  {
    "path": "other-languages/sorting/insertionsort/insertionsort.php",
    "chars": 1250,
    "preview": "<?php\n/*\nInsertionSort\nAutor:\n    ?\nColaborador:    \n    Maurcio Sipmann ( sipmann@gmail.com )\nTipo:\n    sorting\nDescrio"
  },
  {
    "path": "other-languages/sorting/insertionsort/insertionsort.rb",
    "chars": 791,
    "preview": "# encoding: utf-8\n\n=begin\nInsertion Sort\nAutor: \n    ?\nTipo:\n    sorting\nColaborador:\n    Bruno Lara Tavares <bruno.exz@"
  },
  {
    "path": "other-languages/sorting/mergesort/mergesort.c",
    "chars": 2573,
    "preview": "/*\nMergesort\nAutor:\n\tJohn von Neumann, em 1945\nColaborador:\n\tLuiz Fernando Oliveira Corte Real (luiz@vidageek.net)\nTipo:"
  },
  {
    "path": "other-languages/sorting/mergesort/mergesort.rb",
    "chars": 1250,
    "preview": "\n=begin\n  Mergesort\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n    sorting"
  },
  {
    "path": "other-languages/sorting/quicksort/quicksort.c",
    "chars": 1379,
    "preview": "/*\nQuicksort\nAutor:\n    C.A.R. Hoare\nColaborador:\n    Dayvid Victor (victor.dvro@gmail.com)\nTipo:\n    sorting\nDescrição:"
  },
  {
    "path": "other-languages/sorting/quicksort/quicksort.php",
    "chars": 1152,
    "preview": "<?php\n/*\nQuicksort\nAutor:\n    Bruno Ricardo Siqueira\nTipo:\n    sorting\nDescrição:\n    Quicksort é um algorítmo de ordena"
  },
  {
    "path": "other-languages/sorting/quicksort/quicksort.rb",
    "chars": 1407,
    "preview": "\n=begin\n  Quicksort\nAutor:\n    ?\nColaborador:\n    José Alberto O. Morais Filho (j.moraisg12@gmail.com)\nTipo:\n    sorting"
  },
  {
    "path": "other-languages/sorting/selectionsort/selectionsort.cpp",
    "chars": 1316,
    "preview": "/*\nSelection Sort\nAutor: \n    ?\nColaborador:\n    Luiz Rodrigo (luizrodri.go@hotmail.com)\nTipo: \n    sorting\nDescrição: \n"
  },
  {
    "path": "other-languages/sorting/selectionsort/selectionsort.php",
    "chars": 1134,
    "preview": "<?php\n/*\nSelection Sort\nAutor: \n    ?\nColaborador:\n    Maurcio Sipmann (sipmann@gmail.com)\nTipo: \n    sorting\nDescrio: \n"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the hacktoon/1001 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 202 files (263.4 KB), approximately 95.4k tokens, and a symbol index with 369 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!