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>
Respostas:
Oitava , 44 bytes
Experimente online!
O resultado da função, ao usar cada um dos caracteres na função como entrada:
Todos os outros caracteres de entrada retornam zero.
The fact that I had to escape
'
made this a whole lot longer. In order to account for the 4 parentheses, I just had a duplicate in the string. However, duplicating apostrophes takes apostrophes, so this just takes us further from the correct result. Therefore, I had to count the number of apostrophes with its ASCII-value,39
. This of course meant I had to check for the characters3
and9
too, making it all a lot longer.fonte
Excel, 84 bytes
Find()
will look for the value in cellA1
within the string"123456789,()=MINORFADEOMEN
(the"""
at the beginning is to escape the character and will evaluate to just"
).Based on the result of
Find()
, theMid()
function will return the corresponding character from the string of numbers. This string was created through iteration until it stopped changing.If the character in
A1
is not found,Find()
returns an error so theIfError()
function escapes that to return0
instead.The
OMEN
at the end of the string being searched in theFind()
function are duplicate letters so their position will never be returned but they were needed to adjust the character counts. Without them, there was an endless loop of changing counts. The letter arrangement is stylistic choice.fonte
JavaScript (ES6), 70 bytes
Doesn't read the source of the function, but this is quite long. Takes input as a 1-character string.
Try it online!
fonte
i=>'36335633'[i='\\36=\'i|&()25.>[]Odefx~n'.indexOf(i)]||~i&&2
(8 bytes saved)Retina, 1 byte
This wouldn't be valid if following strictly the quine rules, but the OP explicitely allowed it in a comment.
Try it online!
In retina a single-line program counts the occurrences of that regex in the input. This challenge is solved by any single ASCII character except
`
,.
,+
,*
,?
,[
,(
,)
,^
,$
,\
and newline.fonte
C# (Visual C# Compiler),
8857 bytesTry it online!
Returns 3 if the string contains the passed char, otherwise returns 0. The string contains each character of the code atleast once and exactly the amount required to have the char 3 times in the code.
-31 bytes thanks to Kevin Cruijssen
fonte
(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:
Try it online or test with all characters!*
Alternative without
(<>)
, 72 bytesTry it online 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.
I like this one the best, even though it counts the most bytes. It's computes the character/byte count by as a sum of 2,3 and 7 (note how some characters are in multiple groups):
Try it online or test with all characters!
* imports
(<>)
because TIO's GHC version is 8.0.2fonte
Python 2,
545232 bytes-20 bytes thanks to ovs
Try it online!
fonte
"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
fonte
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.fonte
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
.fonte
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.
fonte
JavaScript, 31 bytes
Try it online
fonte
Python 2, 57 bytes
Try it online!
fonte
05AB1E, 17 bytes
Try it online!
fonte
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.fonte
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).
fonte
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!
fonte
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
.fonte
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 :)
fonte
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.
fonte
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
fonte
Japt, 14 bytes
Try it
Explanation
fonte
V, 12 bytes
Try it online!
Hexdump:
fonte
Jelly, 16 bytes
Try it online!
Every character appears exactly twice.
fonte
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.fonte
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.
fonte
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!
fonte
Pari/GP, 36 bytes
Try it online!
fonte
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.fonte
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!
fonte