O cenário: você é um designer de software que trabalha para uma empresa administrada pelo governo que cria placas de carros e outros veículos. Você foi solicitado a desenvolver um software que gera placas. Antes de você começar a trabalhar, seus chefes estabeleceram essas regras básicas.
Uma placa de carro não pode conter:
ASS
666
69<any number here>
<any number here>69
KKK
SHT
Regras e requisitos:
- A matrícula deve ser gerada aleatoriamente.
- Depois que uma placa aleatória é gerada, a mesma placa não pode ser gerada novamente.
- Você deve produzir pelo menos 200 matrículas exclusivas . Você pode gerar mais, se quiser .
- Você pode armazenar placas geradas em um arquivo para "lembrá-las" delas.
- A placa do veículo contém 2 seções, uma contendo apenas três letras e uma contendo apenas três números, separadas por um traço, como este:
233-ADF
ouADF-233
. - Você só pode usar números e letras maiúsculas.
- As matrículas podem ser gravadas em stdout ou em um arquivo.
- Cada "lado" de uma placa de carro conterá três números ou letras.
- Este é um código de golfe , a resposta mais curta e mais popular ganha. O vencedor será escolhido após sete dias.
Regras gerais
- A resposta deve incluir, sem limitação, o seguinte.
- Nome do idioma
- Contador de caracteres.
- Tamanho do arquivo.
- Como o código é executado.
- O próprio código.
- Exemplo: caracteres Python 234 ou Python 23mb .
Se eu precisar esclarecer detalhes adicionais, mencione-o nos comentários e eu o adicionarei ao meu post. De qualquer forma, boa sorte, e me dê algumas placas apropriadas!
Atualização 1: O vencedor será escolhido um pouco antes.
Acontece que eu tenho que ir em uma viagem em breve, por isso estarei escolhendo um vencedor por volta das 00:00 UTC de 25 de julho. Depois que o vencedor for escolhido, você ainda poderá enviar inscrições, apenas saiba que um vencedor foi escolhido. Bai.
Atualização 2: Vencedores!
Temos vencedores! Yay! Queijo e vinho para todos que participaram! Aqui está quem ganhou.
- 1º lugar: Àngel - Bash (95 caracteres)
- 2º lugar: Martin Büttner - Mathematica (182 bytes)
- 2º lugar: Emilio M Bumachar - Pyg (92?)
- 2º lugar: Peter Taylor - Golfscript (98 caracteres)
- 3º lugar: Mark Thomas - Ruby (127 caracteres)
Uau, três empates em segundo lugar. Uau. A competição terminou, mas fique à vontade para enviar inscrições, se quiser. Bai!
fonte
AAA-
Respostas:
bash (95 caracteres)
Salve o script como
m
em uma pasta no seu PATH com o conjunto de bits de execução.Run as
bash m
. The plates are stored in file pThis is equivalent to running the following:
Caveat: The final
m
should actually beexec m
(+5 chars) in order to avoid leaving processes waiting for completion (but you can have thousands without much problem)Credit goes to http://www.cyberciti.biz/faq/linux-random-password-generator/ for the idea of using
tr -dc
fonte
grep -v
is excluding both the blacklist and the list of plates we already generated (grep
is expecting p to contain one pattern per line, but as the plates don't contain regular expression metacharacters, they only match themselves). We only generate one or zero plates per iteration, so after each iteration the full (updated) list of plates to exclude will be read by grep. :DPYG - 92
Now able to select uniformly from all unused plates, keeping to OP's specs, while being shorter by 1 more character.
It's theoretically possible that the list of 999 plates will contain enough repetitions so that the trimmed set will be less than 200. But the odds of that are infinitesimally small. In ten trials, the lowest length I got was 994.
EDIT: changed 999 to K (which is pyg for 1000), to save two chars at the advice of bitpwner.
fonte
Mathematica, 182 bytes
Ugh, this is long
Ungolfed
Pretty straight-forward. Generates random plates, and filters out duplicates and forbidden ones until 200 are found.
fonte
GolfScript (98 chars)
This generates all possible licence plates in a random order using some ugly base conversion followed by filtering. There are a lot of them, so don't expect it to execute quickly, but the question didn't place any constraints on execution time.
fonte
JavaScript (ES6) - 213
It can probably be improved. Tested on Firefox Console.
Change that alert to a
console.log()
if you want to testfonte
Ruby —
136133129 charactersHideous. Think there's room for improvement, though. Just drop the code in
irb
orpry
and hit enter to run:fonte
Ruby, 127 chars
My attempt at a "readable" Ruby version:
fonte
Python 2.7 - 258 chars
I'm not a professional programmer or anything, so I'd say I'm satisfied with the result.
Filesize is 4.0 K, run with
python file.py
!fonte
pass
be acontinue
? You can also save some chars by indenting with a 1 space instead of 4.for i in range(0,200):
could be replaced withfor i in range(200):
.continue
.. Butpass
did the trick. Plus, it's shorter. And when I triedfor i in range(200)
, it only did 199 ^^ I counted them afterwards by making aduplicates
variable and puttingduplicates += 1
beforepass
and counting the occurrences for-
in the list/string.\t
and replacing them by 1 space didn't change the character count... Thanks for the suggestions!if k in t: pass
, as it does nothing.Python - 208
Hi heres my stab at license plate generation. This solution is similar to @bitpwner's solution but without the string module and instead of a list for the license plate I chose to use a set and its also allows numbers first.
Sample output:
fonte
Python, 252 bytes
Here's my contribution. I'm impressed with it, but I know others have done better with python.
fonte
Python - 165
Those imports...
If there is a need to begin randomly with either numbers or alphabets, which I don't think is really needed, then 190.
fonte
PHP
341324320Was the best I could do.
To run the code just save as a .php file and browse to it on any web server. It will attempt to create the blacklist file p.txt if it does not exist already. However you may need to define it with a full server path if you do not have root access.
The code itself is here pre golfification:
Was as short as I could get it :-(
Sample Output
EDIT: tidied up a couple of if statements to use short form.
fonte
$string = (rand(1,2)==1) ? "$rand_number-$letters" : "$letters-$rand_number";
Delphi, 161 bytes
Here is my take on this. It outputs license plates to stdout without line feed between them. If LF is needed (not specified in the rules), than that adds extra 4 bytes.
Golfed version:
Ungolfed:
How to run:
fonte
PHP, 267
This is about as short as I can get it.
Plates are stored in file "p".
fonte
R, 229 characters
I'm sure this could be improved:
Run in the console, prints a list of license plates.
fonte
Cobra - 198
fonte
ECMAScript 6 -
155168158Warning: 200 alert dialogs (change
alert
toconsole.log
to test)Edit: Oops. Original version printed duplicates...
Edit 2: Closer to the original score now - switched from a set to an associative array with some fugly duplicate checks allowing it to print as it goes
Tested in Firefox console.
fonte
l=x=>String.fromCharCode(65+r()*26);
. I guess I don't know what's happening withl=x=>...
f=a=>b
is an ES6 feature that's basically shorthand forfunction f(a) { b }
and it's only(?) supported by Firefox at the moment.JavaScript (ES6) 184
As usual, test in FireFox console and change
alert
toconsole.log
or be prepared to pressescape
200 times.fonte
Python3, 257 chars
Sample output:
fonte
;
instead of\n
.PHP,167
that's 100 chars less than current PHP's best :)
hope you like it. In case it is allowed:
is only 141 chars but doesn't shuffle chars and numbers. Any suggestions wellcome :)
fonte
F#, 264 chars
Not really a language designed for golfing, but I'm sure this could be improved. Using Seq.exists with a lambda is pretty annoying, as are the many parens and lack of implicit conversion.
Uses recursion, keeps going forever.
Can be run in FSI.
fonte
Python 203
I'm not sure if this technically counts, but I liked it so I'm posting it anyway. While I do generate the answers pseudo-randomly, as pretty much everyone else did, I strategically picked the random seed such that invalid answers wouldn't end up in the output. So, my answer isn't actually capable of generating the entire set of valid answers, without also generating the invalid ones.
fonte
Perl - 123 Characters
Ungolfed:
If anyone has ideas to golf it further, let me know, I am interested. If you want further explanation of part of the code, leave a comment and I'd be happy to explain more too.
fonte
Javascript - 283
327CharactersEdit:
After implementing the suggestions from Alconja, here's my new version:
1) Remove Variable:s and use literal:"\n" [-4][323]
2) Remove "var o="",i,r,n,l," [-17][306]
3) Remove Variable:t and use literal:"ASS|KKK|SHT|666" [-4][302]
4) Set m=Math.random and use "m" instead [-7][296]
5) Use (m()+"") rather than m().toString() [-6][290]
6) Remove unneeded ";" [-7][283]
Old-version: Javascript - 327 Characters
I'm sure there's some room for improving... I'm pretty inexperienced at Code-golfing:
Here is a formatted, "Ungolfed" version with "un-minified" variable/function names:
Here is a "debug" version that can be pasted into URL of browser favorite/bookmark. Output is placed in a "TEXTAREA" on a new "window" instead of "alert()":
Here is the "debug" version, formatted:
fonte
var
(just assigning will do, 323), you don't need;
s unless there's another statement following (eg. the last character in the line, or before a}
, 316), watch for anything that takes more space to declare/use than just inline (eg. yours
variable, 312), ditto for the reverse if something is used more than once (eg.Math.random(...)
tor=Math.random ... r(...)
, 307,(x+"")
is shorter thanx.toString()
, 300