Jest to stosunkowo szybki, ale jestem pewien, że ci się spodoba.
Codegolf program, który pobiera dane wejściowe w formie zdania, a następnie podaje w wyniku pierwszą literę pisaną wielkimi literami w każdym słowie.
Zasady:
Zgłoszenia nie mogą mieć formy funkcji. Więc nie:
function x(y){z=some_kind_of_magic(y);return z;}
jako ostateczna odpowiedź ... Twój kod musi pokazywać, że pobiera dane wejściowe i zapewnia dane wyjściowe.Kod musi zachowywać wszelkie inne duże litery, które zawiera. Więc
eCommerce and eBusiness are cool, don't you agree, Richard III?
będą renderowane jako
ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?
Niektórzy z was mogą myśleć: „Spokojnie, po prostu użyję wyrażenia regularnego!” tak więc użycie natywnego wyrażenia regularnego w wybranym języku golfowym spowoduje nałożenie 30 znaków kary, która zostanie zastosowana do ostatecznej liczby kodów. Złowrogi śmiech
„Słowem” w tym przypadku jest wszystko oddzielone spacją. Dlatego
palate cleanser
są dwa słowa, podczas gdypigeon-toed
uważa się je za jedno słowo.if_you_love_her_then_you_should_put_a_ring_on_it
jest uważane za jedno słowo. Jeśli słowo zaczyna się od znaku niealfabetycznego, zostaje zachowane, więc_this
po renderowaniu pozostaje jako_this
. (Podziękowania dla Martina Buttnera za wskazanie tego przypadku testowego).- 4b. Nie ma gwarancji, że słowa w frazie wejściowej zostaną oddzielone pojedynczą spacją.
Przypadek testowy (użyj do przetestowania kodu):
Wkład:
eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye
Wydajność:
ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
To jest kod golfowy, najkrótszy kod wygrywa ...
Powodzenia...
źródło
Odpowiedzi:
CJam,
1513 bajtówWypróbuj online w interpretatorze CJam .
Pseudo kod
Wszystkie zmodyfikowane znaki C zostają na stosie i dlatego są drukowane przy wychodzeniu.
źródło
CSS 2.1, 49
Wyjaśnienie :
attr
Funkcja przyjmuje wejście od At
(tekst) atrybutu HTML.text-transform
nacapitalize
.content
właściwości pseudoelementu .::after
Urywalny fragment kodu :
Uwaga : CSS 2.1 określił pożądane zachowanie:
capitalize
pierwsza litera każdego słowa zawiera dużą literę. Jednak CSS3 drukuje wielkie litery jako pierwsza litera każdego słowa. Dlatego powyższy fragment kodu nie będzie działał poprawnie ani na starym IE, który nie był zgodny z CSS 2.1; ani w nowych zgodnych przeglądarkach zgodnych z CSS3.źródło
_those
problem występuje w przeglądarkach CSS3, ale wciąż jestem entuzjastyczny ze względu na unikalny sposób rozwiązania problemu.)JavaScript ( ES6 ), 77 bajtów
Skomentował
źródło
x&&
. Pusty ciąg jest falsey, więc zwiera&&
i zwraca lewy operand, pusty ciąg. Przestrzenie są zachowane.Perl, 13 bajtów
9 bajtów plus 4 bajty dla
040p
(zakładając, że zinterpretowałem poprawnie zasady dotyczące specjalnych wywołań ).-040
ustawia separator rekordów wejściowych$/
na pojedynczą spację, aby spacje zostały zachowane;\u
sekwencja ucieczki konwertuje następny znak do tytułowej sprawy.źródło
CJam,
1715 bajtówSprawdź to tutaj.
Dość prosta implementacja specyfikacji. Skorzystaj z nowego,
{}&
aby uniknąć błędów dla kolejnych spacji.Dwa bajty zapisane przez Dennisa.
źródło
+
, then that breaks if the input contains trailing spaces.C,
6463 bytesFix: some compilers (such as Clang) don't like an int parameters in place of argv, so I moved it to a global variable. The byte count stays the same. Thanks to squeamish ossifrage for noticing. Down to 63 bytes, thanks Dennis.
Ungolfed:
Pretty straightforward: if a is false, the character is converted to uppercase. It is set after reading a space: c - ' ' is false only if c == ' '. toupper() ignores everything that is not a lowercase letter, so symbols and multiple spaces are fine. -1 has all bits set, so when getchar() returns -1 the NOT operator makes it zero, and the loop stops. a is declared as a global variable, so it is initializd to zero (false). This ensures that the first word is capitalized.
źródło
while(~(c=getchar())
— I like that. Clang won't actually compile this, but you can get the same character count withc;main(a){...}
a
andc
and the order of the ternary operator, you can replace==
with-
to save one byte.while(!(c = getchar()))
, right?~
and the logical!
are not the same. In C anything that is not zero is considered true, so your condition would be likewhile((c = getchar()) == 0)
which of course won't work. The bitwise NOT operator~
negates the value bit-by-bit. To break the loop,~c
must be zero: this means that all bits have to be one, so that when negated they become all zeroes. That value (for a 32bit int) is0xFFFFFFFF
, which, if signed, is-1
(EOF).Python 3,
5956 bytesThanks to @Reticality for 3 bytes.
źródło
print(end=f*c.upper()or c)
? That would save 4 bytesPerl Version < 5.18,
3027262524
characters+1
for-n
.\u
makes the next character in a string uppercase. @ThisSuitIsBlackNot pointed this out to save 1 byte. Before we were using the functionucfirst
.From the perldocs,
Since
$"
evaluates to a space, this will preserve the spaces. Since we want to both set$,
to a space character, and input a space character to the split, @nutki pointed out we can do both as the input to the split. That saves 3 bytes from what we had before, which was first setting$,
and then inputting$"
to the split.Using a
,
for map instead of{}
saves an additional byte, as @alexander-brett pointed out.Run with:
źródło
...map"\u$_",split...
><> (Fish), 39 bytes
Method:
a-z
then print it out. (left-to-right code for this part isi::'backquote')$'{'(*' '*+
)źródło
JAVA, 273 bytes
EDIT
źródło
public
in front of theclass
.. And if you mean he can remove thepublic
in front of thestatic void main(...
, then you are wrong, unless he also changes theclass
tointerface
and uses Java 8+.JavaScript (regex solution) - 104 bytes
Someone has to bite the bullet and post the RegEx solution! 74 characters, plus the +30 character penalty:
Or if you want to read and understand the code in its non-compacted fashion:
źródło
Python 2, 73 bytes
This program capitalises a letter if preceded by a space (with a kludge for the first character in the string). It relies on the
.upper()
string method to capitalise correctly.źródło
raw_input
=>input
, +2print
=>print()
)PHP 64
7677838489bytesDoes
$_GET
count as input in PHP?If so, here is my first CG attempt
Thanks manatwork :)
One could just use the
ucwords
function, which would result in 21 bytes:thanks Harry Mustoe-Playfair :)
źródło
fgets(STDIN)
to read input. But we have no consensus on$_GET
as far as I know.$k=>
. Put it back:foreach(split(' ',$_GET[@s])as$k=>$v)echo$k?' ':'',ucfirst($v);
Haskell, 69
Explanation:
scanl
takes a function(a -> b -> a)
and an initial valuea
, then iterates over a list of[b]
s to make a list of[a]
s:It repeatedly takes the previous result as the left argument of the function passed to it, and a value from the input list as the right argument, to make the next one.
I wrote a function
(!) :: Char -> Char -> Char
that returns the right character you pass it, but capitalizes it if the left char is' '
(space). Forscanl
, this means: return the value from the input list, but capitalize it if the previous result was a space. Soscanl (!) ' ' "ab cd"
becomes:We need the initial value
' '
to capitalize the first letter, but then we chop it off withtail
to get our final result.źródło
scanl
examples: one, two.Pyth, 20 bytes
These multiple spaces really sucks. Otherwise there would have been a really easy 12 bytes solution.
Try it online: Pyth Compiler/Executor
Explanation
edit: 16 chars is possible with @Dennis algorithm.
źródło
CJam, 14 bytes
It's not the shortest, but...
Another answer using similar ideas:
.x
only changes the first item if one of the parameters has only one item.źródło
f
and.
is pretty ingenious. Another 14 bytes variant:qS/Sf.{\eu}S.-
Lua,
646261 bytesLua is a horrendous language to golf in, so I'm pretty proud of myself for this one.
[Try it here]1 Outdated, will update tommorowźródło
abc_def
will giveAbc_Def
. However only letters after spaces should be turning into upper case. The good news is, fixing it saves a byte. ;)JAVA, 204
211226bytesMy first entry on CG, I hope it's fine:
Saved 7 bytes thanks to @TNT
źródło
public class U{public static void main(String[]s){int i=-1,j;char[]r=s[0].toCharArray();for(char c:r)if(++i==0||c==' '&&i>0)r[j=i+(i==0?0:1)]=Character.toUpperCase(r[j]);System.out.print(r);}}
public
modifier isn't necessary so you can save 7 more.PHP:
7674 charactersSample run:
źródło
ucfirst($c)
, use$c^' '
. (Tip: if youbitwise-xor
a letter with a space, it will be converted from uppercase to lowercase, and the oposite applies too)$l=str_split(fgets(STDIN))
, which reduces the code by 2 bytes!C, 74 bytes
Makes no assumptions about the run-time character set (ASCII, EBCDIC, Baudot, ...whatever). Does assume that EOF is negative (I think C guarantees that).
a is the input character; b is true if the last character was space. The only non-obvious bit is that we use the fact that
putchar
returns the character printed if there's no error.źródło
C# Linq - 187
This is nowhere close to winning but I just love Linq too much.
źródło
Vim,
11, 10 bytesExplanation:
Do I get a gold-badge for outgolfing Dennis?
źródło
Bash, 61
Note the colons are simply to make the program display OK here. In reality these can be some non-printable character, such as BEL.
Output
Bash, 12
Sadly this one doesn't preserve leading/mutliple/trailing spaces, but otherwise it works:
Output
źródło
Pip, 15 + 1 for
-s
= 16Explanation:
One interesting feature of Pip that this program draws on is the
:
assignment meta-operator. Most C-like languages have some set of compute-and-assign operators: e.g.x*=5
does the same thing asx=x*5
. In Pip, however, you can tack:
onto any operator and turn it into a compute-and-assign operator. This even goes for unary operators. So-:x
computes-x
and assigns it back tox
, the same asx:-x
would. In this case,UC:
is used (together with Pip's mutable strings) to uppercase the first character of a word.The program takes input from the command-line, requiring an invocation like this:
źródło
C, 125
Not the shortest of solutions, but I really like to golf in C.
ungolfed:
I don't know wheter using regex-like syntax in
scanf
is streching the rules, but it works quite nicely. (Well, technically it's not a full regex)An other thing to consider is that this code only works for words shorter than 99 bytes. But I think this solution will work for most cases.
źródło
Haskell: 127 characters
źródło
PHP, 82
Usage :
źródło
C#,
133131źródło
&&c!=32
? I'm not too fluent in C#, but I would guess that converting a space to uppercase results in a space.Mathematica, 66 bytes
I would use
ToCamelCase
, but it doesn't preserve spacing.źródło
R,
139105 bytesUngolfed + explanation:
R with regex,
4941 + 30 = 71 bytesI'm really bummed; this actually has a better score using regular expressions with the penalty.
This matches any single character at the beginning of the string or following any number of spaces and replaces it with an uppercase version of the capture. Note that applying
\\U
is legit and has no effect for non-letters.pe=T
is interpreted asperl = TRUE
since it takes advantage of R's partial matching of function parameters and the synonym forTRUE
. For whatever reason, R doesn't use Perl-style regular expression by default.Thanks to MickyT for helping save 8 bytes on the regex approach!
źródło
(^.| +.)
. Uppercasing anything is OK.