the world is a pixel
Gerando permutações
Muitas vezes para resolver uma única instância de um problema é mais rápido ataca-lo com força bruta do que encontrar um algoritmo geral com uma boa ordem de complexidade. Permutações são de grande utilidade nesse tipo de abordagem.
Permutações em Prolog:
Esse é um código em Prolog que o Wladimir Araujo passou na cadeira de IA.
select(X, [X|Xs], Xs).
select(X, [Y|Ys], [Y|Zs]) :- select(X, Ys, Zs).
permutar([], []).
permutar(Xs, [Z|Zs]) :-
select(Z, Xs, Ys),
permutar(Ys, Zs).
Permutações em Python:
Esse é um código de um certo Michael Davies que eu tirei daqui. Ele gera uma lista com todas as permutações de uma lista. Muito bonitinho. :)
def all_perms(str): if len(str) <=1: yield str else: for perm in all_perms(str[1:]): for i in range(len(perm)+1): yield perm[:i] + str[0:1] + perm[i:]
Um exemplo de uso:
>>> for p in all_perms(['a','b','c']): print p ['a', 'b', 'c'] ['b', 'a', 'c'] ['b', 'c', 'a'] ['a', 'c', 'b'] ['c', 'a', 'b'] ['c', 'b', 'a']
Outras implementações:
Em outras linguagens o código para gerar permutações geralmente é muito grande, então eu preferi deixar alguns links.
No comments yet.
No trackbacks yet.
Java: invoking a method by name
29 April, 2010 - 10:29 am
Tags: Class, Java, method, programming, Reflection
Posted in english | 1 comment
import java.lang.reflect.*; public class Foo { public void bar(int param){ System.out.println(param); } public static void main(String args[]){ Object f = new Foo(); try { Method m = f.getClass().getMethod("bar", int.class); m.invoke(f, 42); } catch (Exception e){ System.err.println(e); } } } $ java Foo 42
baia fria
14 April, 2010 - 10:11 pm
Tags: art, arte, Atlântico, bastos, Gimp, ia
Posted in english | 1 comment
Aquele ali no canto é o Bastos.
calling commands in Java
8 April, 2010 - 1:09 pm
Tags: getruntime, Java, programming, runtime
Posted in english | No comments
I don’t like the approach of calling native shell commands in any language instead of using multi platform libraries, but here is a little prof of concept Java program to call native commands. import java.io.*; import java.util.*; public class Exec { public static void main(String args[]) throws IOException { Process proc = Runtime.getRuntime().e xec(args); BufferedReader [...]
Iterating over a HashMap
8 April, 2010 - 11:22 am
Tags: collections, enhanced loop, foreach, hashmap, iterating, Java, programming
Posted in english | No comments
Iterating over a HashMap using the enhanced loop (foreach) in Java is a good way to keep your code smaller, more legible and usually more semantically coherent. import java.util.HashMap; import java.util.Map; class Foo {} public class Main { public static void main(String args[]){ Map<Byte, Foo> mHash; mHash = new HashMap<Byte, Foo>(); [...]
Getting enviroment information on Android
16 March, 2010 - 10:18 am
Tags: Android, Eclipse, Java, programming, who am i, whoami
Posted in english | 4 comments
This is a simple program I wrote called Who Am I that shows informations about the device which it is running. Which can be useful for developers and maybe advanced users. Download: WhoAmI.tar.bz2 – Eclipse project. It’s configured for Android platform 4 (1.6) but should work without problems in newer Android platform versions. WhoAmI.apk – [...]
The Caps Lock Java Socket Server
27 February, 2010 - 9:39 pm
Tags: caps lock, Java, programming, socket, upcase
Posted in english | 1 comment
Here is a simple server for those who are starting studying sockets or just needs a simple socket server example for reuse while writing your own behavior. Features: A client should enter a string and the server would answer the same string, with each symbol in up case, when possible. Default port at 8080. One [...]
Beware the locale
22 February, 2010 - 5:16 pm
Tags: development, i18n, Java, JUnit, locale, programming, String, teste unitário, toString, unit testing
Posted in english | No comments
Today I was programming a toString method for a class widely used in a application, using the very useful String.format that provides a C’s like printf formatter. @Override public String toString() { return String.format("VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b); } %.1f means a float with one digit precision after the dot separator. [...]
Contando Algarismos Em Um Intervalo
29 January, 2010 - 8:21 pm
Tags: compreensão de lista, Programação, programação funcional, Python
Posted in english | 3 comments
Quantos zeros tem entre um e mil? É mais fácil responder perguntas desse tipo escrevendo pequenos programas usando o suporte a programação funcional e compreensão de lista que algumas linguagens como Python oferecem. Para contar os zeros de um número, transformamos ele em uma string e contamos quantas substrings ’0′ ele contém. Por exemplo o [...]
Easily Sortable Date and Time Representation
20 January, 2010 - 10:55 pm
Tags: date, datetime, ISO 8601, Jochen Voss, Markus Kuhn, programming, Python, representation, sort, sorting, time
Posted in english | No comments
I was looking for a date and time representation useful for registering stock quotes in a simple plain file. I found that the standard ISO 8601 is just the answer for this, it’s called “Data elements and interchange formats — Information interchange — Representation of dates and times”. Here is a example: 2010-01-20 22:14:38 There’s this [...]
Extração de Dados e Fundos de Investimento do Banco do Brasil
11 January, 2010 - 9:02 pm
Tags: ações, aplicações, Banco do Brasil, bolsa de valores, CRON, Data Mining, fundo de investimento, fundos, fundos de investimento, JSON, Mineração de Dados, Python, screen scraping, Web Harvest, web scraping, XML, yaml
Posted in english | 3 comments
Eu não achei onde coletar os dados diários de rentabilidade dos fundos de investimento do Banco do Brasil em formato bem estruturado. Num mundo ideal as coisas seriam assim, você faria uma requisição numa url como esta: http://bb.com.br/apps/rentabilidade?fundo=Siderurgia&saida=xml E ele cuspiria um XML com as informações da rentabilidade diária desse fundo, isso se eu não [...]












