var QUESTION_ID=162408,OVERRIDE_USER=21034;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}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="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><div id="language-list"> <h2>Winners 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><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>
Respuestas:
Octava , 44 bytes
Pruébalo en línea!
El resultado de la función, cuando se usa cada uno de los caracteres en la función como entrada:
Todos los demás caracteres de entrada devuelven un cero.
El hecho de que tuve que escapar
'
hizo que esto fuera mucho más largo. Para tener en cuenta los 4 paréntesis, acabo de tener un duplicado en la cadena. Sin embargo, duplicar apóstrofes toma apóstrofes, por lo que esto nos lleva más lejos del resultado correcto. Por lo tanto, tenía que contar el número de apóstrofes con su valor ASCII,39
. Por supuesto, esto significaba que tenía que verificar los personajes3
y9
también, lo que lo hacía mucho más largo.fuente
Excel, 84 bytes
Find()
buscará el valor en la celdaA1
dentro de la cadena"123456789,()=MINORFADEOMEN
("""
al principio es para escapar del carácter y evaluará solo"
).Según el resultado de
Find()
, laMid()
función devolverá el carácter correspondiente de la cadena de números. Esta cadena se creó a través de la iteración hasta que dejó de cambiar.Si
A1
no se encuentra el carácter en ,Find()
devuelve un error, por lo que laIfError()
función escapa de eso para devolverlo0
.Al
OMEN
final de la cadena que se busca en laFind()
función hay letras duplicadas, por lo que su posición nunca se devolverá, pero fueron necesarias para ajustar el recuento de caracteres. Sin ellos, había un ciclo infinito de recuentos cambiantes. La disposición de las letras es una elección estilística.fuente
JavaScript (ES6), 70 bytes
No lee la fuente de la función, pero esto es bastante largo. Toma la entrada como una cadena de 1 carácter.
Pruébalo en línea!
fuente
i=>'36335633'[i='\\36=\'i|&()25.>[]Odefx~n'.indexOf(i)]||~i&&2
(8 bytes guardados)Retina , 1 byte
Esto no sería válido si se siguen estrictamente las reglas de quine, pero el OP lo permitió explícitamente en un comentario .
Pruébalo en línea!
En la retina, un programa de una sola línea cuenta las ocurrencias de esa expresión regular en la entrada. Este desafío se resuelve por cualquier carácter ASCII sola excepción
`
,.
,+
,*
,?
,[
,(
,)
,^
,$
,\
y la nueva línea.fuente
C # (compilador de Visual C #) ,
8857 bytesPruébalo en línea!
Devuelve 3 si la cadena contiene el carácter pasado, de lo contrario devuelve 0. La cadena contiene cada carácter del código al menos una vez y exactamente la cantidad requerida para tener el carácter 3 veces en el código.
-31 bytes gracias a Kevin Cruijssen
fuente
(a)=>
and taking the input as string instead of char so the.ToString()
is no longer necessary (anda+""
could have been used as well, for code-golf challenges you'll never need.ToString()
). Also, since.Contains
already contains ana
, you might make the input-variable a different unused character (likex
orq
) to have 3 for each character instead of 4. EDIT: Never mind the last part, I see"
is used 4 times as well now.Haskell, 66 bytes
The first two versions are essentially a quine which filters the required characters and then takes the length:
Pruébalo en línea otest with all characters!*
Alternativa sin
(<>)
, 72 bytesPruébalo en línea or test with all characters!
Non-quine alternative,
8786 bytesMight still be improved, but I'm happy that I got it down to only three different groups.
Este me gusta más, a pesar de que cuenta la mayor cantidad de bytes. Calcula el recuento de caracteres / bytes como una suma de 2,3 y 7 (observe cómo algunos caracteres están en varios grupos):
¡Pruébalo en línea o prueba con todos los personajes!
* imports
(<>)
because TIO's GHC version is 8.0.2fuente
Python 2,
545232 bytes-20 bytes thanks to ovs
Try it online!
fuente
"xxx".count
is equivalent tolambda c:"xxx".count(c)
.f="xxx".count
andf=lambda c:"xxx".count(c)
will be called asf('a')
Husk,
11 108 bytesThanks Leo for -2 bytes!
Try it online!
Explanation
This makes sure that it only uses ASCII (because
show
would mess it up) and that each character is contained twice:Standard quine extension, 11 bytes
Try it online!
Explanation
fuente
Java 10,
1648157 bytesPort of @Hyarus' C# answer, so make sure to upvote him!
Explanation:
Try it online.
Old quine 164-bytes answer:
Explanation:
Try it online.
quine-part:
s
contains the unformatted source code.%s
is used to input this String into itself with thes.format(...)
.%c
,%1$c
and the34
are used to format the double-quotes.s.format(s,34,s)
puts it all togetherChallenge part:
.replaceAll("[^"+c+']',"")
removes all characters except those equal to the input..length()
then takes the length of this String.NOTE:
.split(c).length
(withString
input instead ofchar
) may seem shorter, but has two problems:c
(withc->
as leading part) is input, it will incorrectly return one character too few. This can be fixed by adding+(c==99?1:0)
in both the source code and unformatted source code String (and changing.split(c)
to.split(c+"")
, but then we still have the following problem:$
) is input, the.split
will interpret it as a regex, giving an incorrect result.fuente
Haskell, 58 bytes
Try it online! or verify the solution.
Same byte count alternatives:
Haskell, 90 bytes
Try it online! or verify the solution. Uses the fact that
sum Nothing = 0
and e.g.sum (Just 4) = 4
.fuente
Smalltalk, 112
132bytesSmalltalk isn't exactly known for its golfing suitability :-)
Method defined in class Character (tested in VA Smalltalk and Squeak, should work in other dialects such as VisualWorks and Pharo as well):
Characters occurring in the source are grouped by occurrence count. The groups are tested for the first one which contains the receiver, and the matching occurrence count is returned.
Old method:
Every character that does appear in the method appears exactly 6 times (by being repeated in the string constant), so the method just checks whether the receiver is contained in the string and returns 6 if it is, 0 otherwise.
After defining the method as above, you can validate it using
The result should be empty.
fuente
JavaScript, 31 bytes
Try it online
fuente
Python 2, 57 bytes
Try it online!
fuente
05AB1E, 17 bytes
Try it online!
fuente
Haskell, 96 bytes
Try it online!
Haskell, 109 bytes
Try it online!
Haskell, 122 bytes
Try it online!
Explanations
These answers are not terribly sophisticated. It is a series of declarations, one for each character present in the program. At the end we have a catch all that returns 0 for characters not present in the program.
I use a couple of tricks to minimize the number of characters necessary in the program and from there I fiddled with things until the numbers turned out just right. You can see that I've padded the variable name in the last declaration, in all 3 of them. The difference between the 3 programs is whether I chose to use a new line or
;
for line breaks and whether I chose to take Chars as input or Strings. The;
approach doesn't seem inherently superior to the others it just gets luck and ends up shorter, however it does seem that using Strings is a better idea than Chars because Chars require spaces after the function name an Strings do not.fuente
Whitespace, 140 bytes
Letters
S
(space),T
(tab), andN
(new-line) added as highlighting only.[..._some_action]
added as explanation only.70 spaces, 37 tabs, and 33 new-lines used.
Usually I use the Create Labels in the order
NSSN
,NSSSN
,NSSTN
,NSSSSN
,NSSSTN
,NSSTSN
,NSSTTN
, etc. But because printing a number where the binaryS=0
/T=1
is used affects the number I need to output, I used the labelsNSSN
,NSSSN
,NSSTN
, andNSSSTN
instead, which gave the perfect amount of spaces/tabs to be printed with the binary numbersSSSTSSSSTN
(33; amount of new-lines),SSSTSSTSTN
(37; amount of tabs), andSSSTSSSTTSN
(70; amount of spaces).Explanation in pseudo-code:
Example runs:
Input: space
Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs, and new-lines only).
Input: tab
STDIN will be
\t
(9
) instead, in which case it will be0
at the firstIf 0
check, goes toLABEL_TAB
/NSSSTN
, and will push and print37
instead.Try it online (with raw spaces, tabs, and new-lines only).
Input: new-line
STDIN will be
\n
(10
) instead, in which case it will be0
at the secondIf 0
check, goes toLabel_NEWLINE
/NSSSN
, and will push and print33
instead.Try it online (with raw spaces, tabs, and new-lines only).
Input: anything else
Any other input-character will do
NSTN
(Jump to Label_PRINT) after the thirdIf 0
check, printing the0
that was still on the stack (which we've duplicated at the very beginning).Try it online (with raw spaces, tabs, and new-lines only).
fuente
Japt, 27 bytes
Longer than the existing Japt answer, but uses a different approach.
Has the inherent limitation that all chars need to occur a unique number of times.
Takes input as a string.
Try it online!
fuente
Perl, 130 bytes
Has no newline or other whitespace. Reads a line from the standard output, but only cares about its first bytes, then prints the number of times that byte occurs in its own source code in decimal, without a newline.
The program is straightforward. Most of the source code is occupied by a literal table that gives the answer for the each possible byte. Trailing zeros are omitted, and adjacent zeros are run-time compressed, but there's no special trick other than that. The rest of the program simply reads the input and looks up the answer in the table.
For example, the part
22, 12, 6, 3, 5, 2, 4, 0, 1, 0
in the source code gives the frequency of digits, so there are 22 zeroes, 12 ones, 6 twos etc in the source code. As a result, if you enter0
to the standard input of the program, the program will print22
.fuente
C (gcc), 1033 bytes
Try it online!
This is by NO means a golfed answer, but it was fun to try to accomplish this challenge in a language which I am not familiar with. It wasn't a particularly difficult challenge until it came time to find the occurrences of the digits, now THAT was a challenge. Had to do a little creative balancing :)
fuente
C (gcc), 192 bytes
Try it online!
Probably possible to golf down further. Uses a comment at the end as a 'scratch space' to add extra digits. When I have to change a digit from X to Y, I change one of the Y's in the scratch to an X to compensate. Other than that this is just a function that takes an integer, using the assignment trick to return a value based on a large ternary conditional.
fuente
0*84332211
like in the other C answer, but I can also save bytes by refactoring that to be smaller, so I'm not going to bother just yet.J&1?
to match all odd characters). I may further golf this if I find the time to do so.x86 .COM, 17 bytes, controversial
36 bytes
fuente
Japt, 14 bytes
Try it
Explanation
fuente
V, 12 bytes
Try it online!
Hexdump:
fuente
Jelly, 16 bytes
Try it online!
Every character appears exactly twice.
fuente
x86,
4240 bytesHere I use the same strategy as others: Create a string copy of the program with unique bytes, then return 2 in
al
if the inputal
is in the string. If we allow ourselves to read code that is actually run, we get l4m2's solution.I got to make use of a cool string instruction
scasb
. To the best of my knowledge, there are no duplicate bytes, but this is something I'd easily screw up. Loading the string address takes 5 bytes but I'm not aware of any shorter solution (64-bitlea
ofrip
with offset takes 6 bytes).-2 by jumping backwards to avoid using
02
twice.Hexdump (of binary file format elf32-i386, as obj file unfortunately has
00
bytes forstr
address):x86, 256 bytes
Boring answer that is the equivalent of a giant comment. Input in
cl
, immediately returns 1 inal
. I'll make an actual answer when I have the free time.fuente
APL (Dyalog Classic), 30 bytes
Try it online!
Explanation
In APL, single quotes within strings are escaped by doubling, so
'''''''1''⊢-⍳⍳0'
is the string'''1'⊢-⍳⍳0
, which contain every character used in the program.APL arrays are by default 1-indexed, and the index-of function, interestingly, returns
1 + max index
if the element is not found.So, by using index-of on the string and the input returns
As one can see,
11 - index
gives the count of the character in the program. So, the basic algorithm isThe rest is bloating the character counts to allow them to fit nicely into the slots.
fuente
R, 135 bytes
Inspired by this Python answer.
Previous versions were broken. Thanks to @Giuseppe for pointing out that
paste
was not required it saved 18 bytes or so.lengths(regmatches(z,gregexpr(x,z)))
is from this answer.Try it online!
fuente
Pari/GP, 36 bytes
Try it online!
fuente
Ruby, 48 bytes
%q[str]
is a more convenient way to write a string literal than"str"
because it can be nested inside itself without any escaping. So I just put the entire code except for the copy inside it, then double the count.fuente
Jelly,
1210 bytesTry it online!
Reads a character from STDIN.
12 bytes
Try it online!
Using input from command line argument.
Also 12 bytes:
Try it online!
fuente