/* Configuration */
var QUESTION_ID = 67554; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 34388; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
else console.log(body);
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();
languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
Lololololololololololol
é um nome oficial :)False
"?Respostas:
Pitão,
161312 bytesAgradeço a @Thomas Kwa por me lembrar sobre o titlecase.
Conjunto de Teste .
fonte
Retina, 13 bytes
Experimente online | Conjunto de teste (a saída
0
significa que nenhuma das seqüências corresponde, o que é esperado.)Quando o Retina é fornecido apenas com uma única linha de código, ele gera o número de vezes que a expressão correspondeu à sequência de entrada, para que ele produza (verdadeiramente) se
1
corresponder e, portanto, for um nome oficial e0
(falso), se não for.Demolir
fonte
TeaScript, 12 bytes
Abusa da
O
função.Experimente online
Suíte de teste
Explicação
A
O
função faz isso:Em seguida, a função O verifica se o regex corresponde
x
.Como alternativa, uma resposta não concorrente do TeaScript 3 com 7 bytes :
fonte
isChar
função que você adicionou. Mas você pode explicar mais detalhadamente para quem não conhece.JavaScript (ES6), 26
Por: Edcsixtyfive
fonte
n=>n.match`^[A-Z][a-z]+$`
/./.test.bind(/^[A-Z][a-z]+$/)
Python,
5958 bytesTenho certeza de que não há uma maneira real de vencer a versão Retina, já que isso é basicamente o Python. Mas acho que esta é minha primeira submissão;)
É um valor de verdade muito estranho :
(E requer
""
strings com espaços, se passado pelo shell)fonte
^
não é necessário, poisre.match()
apenas corresponde ao início da string.lambda s:re.match('[A-Z][a-z]+$',s) import re
Java, 53 bytes
fonte
s->s.matches("[A-Z][a-z]+")
Python,
50454341 bytesRetorna
True
se for um nome oficial ouFalse
se não for.fonte
f=
em consideração, economizando dois bytes. Além disso,(len(s)>1)
economiza 5 bytess[1:].islower()
. :)BotEngine ,
20318029x6 = 174Eu realmente devo adicionar built-in para identificar letras maiúsculas e minúsculas. Isso seria muito mais conciso do que verificar cada letra individualmente.
Tradução aproximada:
fonte
C,
129122121111 bytesExperimente Online
fonte
VB6, 48 bytes
fonte
MATL , 18 bytes
The current version (4.0.0) of the language is used.
This applies the same regular expression as NinjaBearMonkey's answer:
The output is the string (which is truthy) if it's an official name, and nothing (which is falsy) if it's not.
Examples
fonte
Haskell, 61 bytes
fonte
Gema, 17 characters
Sample run:
fonte
Ruby, 28 bytes
-2 bytes( thanks to manatwork )
fonte
p
related tips in Tips for golfing in Ruby.p !!gets[/^[A-Z][a-z]+$/]
IA-32 machine code, 19 bytes
A function that receives the pointer to a null-terminating string in
ecx
and returns 0 or 1 ineax
(according to thefastcall
convention).Hexdump of the code:
In assembly language:
The first byte of the input name has its 5th bit flipped (
xor
with32
) to convert it from capital case to small case. This loads 32 intoeax
, using 3 bytes of code:To check whether the byte is a small letter:
If not, this code falls through. To return 0 in this case, it puts 0 in
al
before doing the conditional jump:The 0 in
al
also serves as a xor-mask (or absence of it) for the following bytes of the input name.A successful exit is when it encounters a zero byte, which stays zero after the
xor
:It assumes that the input name is not empty. I guess it's a reasonable assumption about a name (not an arbitrary string)!
fonte
grep
, 16 bytesThis is the pattern:
If you use the
-E
and-x
and-c
switchesgrep
will print a count of matching input lines. So if you give it one line you get a 1 or a 0. I think that's how this place works.The pattern is 11 chars, the whole command line is 23. I've seen people use
sed
scripts without the command so I don't know what is what. But, it reads stdin, and so you can just type at it. Here'secho
:fonte
grep -Exc
so you don't need to count as many bytes for the switches.Mathematica 10.1, 46 bytes
Uses one less byte than the standard regex solution. It does three checks.
LetterQ@#
ensures that the string is entirely composed of letters, andStringLength@#>1
invalidates single-letter strings.#==ToCamelCase@#
makes less sense, however.ToCamelCase
is an undocumented function I found that takes an input string AndOutputsItLikeThis. Since there is only one word, it will capitalize the first letter, so we check if the string is equal to that.fonte
ToCamelCase
new in 10.3? Doesn't seem to work in 10.2.ToCamelCase["foo bar baz"]
?ToCamelCase[foo bar baz]
). Strange! Maybe someone can check 10.3?bash/zsh/ksh, 25 bytes
To actually use this, make a file with it as the only line and make the file executable; executable files not recognized as a known binary type are treated as shell scripts (for
/bin/sh
specifically).fonte
bash
,ksh
andzsh
, but has no chance to work in standard POSIXsh
or the compatibledash
andyash
. To avoid confusion, I suggest to change the answer's title.printf
instead ofecho
to create the file and you’ll get 25 bytes.C# 4, 89 bytes
My first attempt at Code Golf. Here it comes:
See it in action at Dot Net Fiddle.
fonte
bool o(string i)=>System.Text.RegularExpressions.Regex.IsMatch(i,"^[A-Z][a-z]+$");
Java, 28 bytes
Uses regex to make sure the string consists of an uppercase character followed by at least one lowercase character.
-1 bytes thanks to Benjamin Urquhart
fonte
k4, 39 bytes
First char is upper, all others are lower, count greater than one.
E.g.:
fonte
Seriously, 16 bytes
Hex Dump:
Try It Online
Seriously does not have regex support yet, so the best we can do is:
fonte
Ocaml,
231216197166 bytesExample usage:
Ungolfed (with real function names):
fonte
if … then 0 else
by… ||
. And for that matter by using boolean operators instead ofmatch
and ranges, e.g.n.[0]>'@'&n.[0]<'['&e(l-1)
SpecBAS - 39 bytes
SpecBAS handles regular expressions through the
MATCH
command. Output is 0 for false and 1 if true.fonte
Swift 2, 116 bytes
Regex is so verbose in Swift that doing this is much shorter
This will return
0
or-1
(in the case of no input) for non-official names, and a number> 0
(which is equal to the length of the string - 1) if the name is officialUngolfed
fonte
C#, 188 bytes
Regular expressions would have been the right way to tackle this, but here's an attempt without it.
Longhand
Would love advice on how to make the lowercase check shorter, perhaps without the loop. I just started learning the language, and used this as practice, figured I'd share my result anyway.
fonte
Perl 5
-p
, 18 bytesTry it online!
fonte
PowerShell, 29 bytes
Try it online!
Does the same regex trick everyone else is using. Has to use
c
ase-sensitivematch
to properly do it at the cost of a byte.fonte
Japt, 9 bytes
Returns
1
or0
.Try it
fonte
Perl 6, 17 bytes
Returns a
Match
object if this is an official name andNil
otherwise.Try it online!
fonte
m