13
\$\begingroup\$

Write a function or program that accepts one character (or a string of length 1) as input, and outputs the number of times that character occurs inside the code.

  • This program must be a Proper Quine, only in the sense that it cannot, for example, read itself as a file, etc.

Input can be any character, printable or not. Output may be to standard out, or as a return value from a function. This is code golf, so the shortest submission in bytes wins. Good luck!

| improve this question | | | | |
New contributor
Adam Abahot is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • 3
    \$\begingroup\$ @AdamAbahot You can ban returning 1 for every value, but then again someone might just have a solution which prints 2 every time, and have each characters repeat twice. I think it would be a good idea to simply allow all characters, including unprintable. \$\endgroup\$ – dingledooper May 22 at 23:38
  • 1
    \$\begingroup\$ How can the program be a quine and at the same time output the number of times that the input character appears in the code? Those are contradictory output requirements, aren't they? \$\endgroup\$ – Luis Mendo May 23 at 0:18
  • 2
    \$\begingroup\$ @LuisMendo When I made the suggestion above, I meant that solutions should not be allowed to read their own source code. I suppose I worded the suggestion poorly though \$\endgroup\$ – math junkie May 23 at 0:22
  • 1
    \$\begingroup\$ Related, but not a duplicate \$\endgroup\$ – Lyxal May 23 at 0:28
  • 1
    \$\begingroup\$ FYI @mathjunkie's suggestion wasn't necessary because improper quines are a standard loophole \$\endgroup\$ – pppery May 23 at 3:01

20 Answers 20

7
\$\begingroup\$

Python 2, 30 bytes

('%r'%'%(*2).count%r'*2).count

Try it online!

| improve this answer | | | | |
\$\endgroup\$
6
\$\begingroup\$

JavaScript (Node.js), 54 bytes

y=>"3.>=includes(*)\\\"y3.>=includes(*)".includes(y)*3

Try it online!

A bit convoluted but I tried to avoid using f= that would violate the proper quine requirement. The code is written in the way that all characters occur exactly 3 times.

| improve this answer | | | | |
\$\endgroup\$
4
\$\begingroup\$

J, 34 bytes

(2*1#.=&'(2*1#.=&)+6*=&')+6*=&''''

Try it online!

how

                             single quote 
         quoted program      adjustment
                |              /     
        vvvvvvvvvvvvvvvv _____/___ 
(2*1#.=&'(2*1#.=&)+6*=&')+6*=&''''
^^^^^^^^                ^^^^^^^^^^
        \               /
         regular program
  • Everything above a ^ is part of the "regular program".
  • The rest is "the program quoted", but with one exception:
    • The quoted program doesn't include the program's single quote characters '
  • 2*1#.=&'...' - Two times 2* the sum of 1#. the total number of times the input char matches a char in "the quoted program". One for the actual program char, one for its quoted twin.
  • +6*=&'''' - Plus six times +6* the 1/0-indicator of whether the input char is equal to a single quote =&''''. This is the hardcoded knowledge that there are 6 single quotes in the program.
| improve this answer | | | | |
\$\endgroup\$
4
\$\begingroup\$

Stax, 12 bytes

".+#H".""+#H

Run and debug it

Takes as input a code point. Those provided in the test are for each character in the program, as well as their immediate predecessors and successors.

Explanation:

".+#H".""+#H
".+#H"          String literal ".+#H"
      .""       String literal "\"\""
         +      Concatenate
          #     Count occurrences of the input
           H    Double

Constructs a string of half the program, permuted somehow. Counts occurrences there, then doubles.

| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Charcoal, 20 bytes

I⊗№⁺´”´””yI⊗№⁺´´yS”S

Try it online! Explanation:

    ´”´”                Literal string `””`
   ⁺                    Concatenated with
        ”yI⊗№⁺´´yS”     Literal string `I⊗№⁺´´yS`
  №                S    Count matches of input character
 ⊗                      Doubled
I                       Cast to string
                        Implicitly print

Charcoal has two ways of quoting non-ASCII characters, ´ (which quotes a single character) and ”y...” (which quotes anything except ). Trying to do everything with ´ is awkward because it uses too many of them; the best I could do was 26 bytes.

| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Pyth, 10 bytes

y/+N"y/+N"

Try it online!

Test cases

y/+N"y/+N"
    "y/+N"    String literal
  +N          Append the string `"`
 /            Count occurrences of the input in that string
y             Multiply by 2
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Pyth has a quote built-in!? \$\endgroup\$ – Λ̸̸ May 23 at 1:50
  • \$\begingroup\$ @Λ̸̸ Yep! See this golfing tip \$\endgroup\$ – math junkie May 23 at 1:52
3
\$\begingroup\$

05AB1E, 14 bytes

Port of the Stax answer. ¢ is order-sensitive, which is fairly annoying here.

"„Js¢·"„""Js¢·

Try it online!

05AB1E, 18 bytes

As for this... I wrote this myself.

„…J…¢s·'„'D''DJs¢·

Try it online!

Explanation

„…J                 2-char string. …, J
   …¢s·             3-char string. ¢, s, ·
       '„           1-char string. „
         'D         1-char string. D
           ''       1-char string. '
             D      Copy this character.
              J     Join the stack.
               s¢   Count occurances of the input in the string.
                 ·  Multiply the count by 2. (Perfectly makes the 0-count still 0.)
| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6),  40  38 bytes

A function made of 19 distinct characters used twice each.

_=>_.match`[\\]chmt[-a.02:=>?^^-]`?2:0

Try it online!

How?

The range going from [ to a allows us to match the backtick and the underscore, which are both already doubled in the code, without explicitly including them in the pattern.

This method comes with two minor drawbacks:

  • Because this range also includes ^, we need to insert it twice in the code as well although it's not part of the payload.
  • We also have to insert a second -.

Character set:

-.02:=>?[\]^_`achmt
| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

COW, 711 519 504 bytes

moOMooMOOmOoMoOMoOMoOMoOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOoMOoMOoMOomOoMOomoomoOMMMOOOmoOMoOMoOMoOMoOMOOmOoMoOMoOMoOMoOmoOMOomoomOoMoOMOOmoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOomooOOOmooMMMMOOMOoMOoMMMOOOMoOMoOMoOMoOMoOMoOMOOmoOMoOMoOMoOMoOMoOMoOMoOmOoMOomooOOOmooMMMMOOmOoMoOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOomOoMOomoomoOMMMOOOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOoMOomOoMOomooOOOmooMMMMOOMoOMoOMMMOOOmoOOOOmOoMoOMoOMoOMoOMOOmoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOomoomoOMOomOoOOOmooMMMMOOmoOmoomoOOOM

Try it online!

The gist

[0]: multiplier for [1]     [1]: input-current_char or     [2]:current_char number
                                 multiplier for [2]

[1] = getchar()
if[1] { [1]-=77(M), cut[1], [2] =136 } paste[1]
if[1] { [1]-=2 (O), cut[1], [2]+=42  } paste[1]
if[1] { [1]-=32(o), cut[1], [2]-=27  } paste[1]
if[1] { [1]+=2 (m), cut[1], [2] =39  } paste[1]
while[x] { x++ }                                 //if [1] is 0    else
print [x+1]                                      //print [2]      print [4] (0)

In detail

moo ]    mOo <    MOo -    OOO *    Moo .
MOO [    moO >    MoO +    MMM =    oom o

>.
[  <+++++++[>-----------<-]>  =*  >++++[<++++>-]<+[>++++++++<-]  *]=
[             --              =*        ++++++[>+++++++<-]       *]=
[     <++++[>--------<-]>     =*         +++[>---------<-]       *]=
[             ++              =*     >*<++++[>++++++++++<-]>-<   *]=
[>]
>o
  • Cutting and pasting the content of [1] allows to use this cell as multiplier of [2]
  • Deleting [1] at the end of each loop is useless (since it's already 0) it's there because COW doesn't handle consecutive parenthesis, I don't know why...

How

I've first constructed the exoskeleton (the complete program without the info about its chars). Then I've noted that it's very simple to maintain under control the differences between M, O and o because many instructions contain all three.

So the program addresses them consecutively leaving m for last.
I've counted the letters in the exoskeleton and begun to hard write their difference and m knowing that in the process they couldn't change (much).

O-M =  42
o-O = -27
 m  =  39  

Inserted these 3 number, the last thing to do was to insert the number of M.
At this point they are \$119\$.
This number, like the others before, already has its structure ready in the exoskeleton that (in Brainfuck notation) is >[<>-]<[><-].
That enables to express a number \$n>111\$ in its minimum form \$n=(ab+c)d\$
With parameters: >a[<b>-]<c[>d<-].

Writing \$a,b,c\$ and \$d\$ costs \$s\$ the sum of their (absolute) value.
In particular, being MoO/MOo the instruction of increment/decrement, writing them adds \$s\$ M (and doesn't affect neither O-M nor o-O nor m).

Ergo, now I had to find a number \$n\$ such that expressed in the above form, \$n=119+s\$.
\$136\$ is the first one.

\begin{align}n=(4\times4+1)\times8=136\end{align} \begin{align}s=4+4+1+8=17\end{align} \begin{align}136=119+17\end{align}

I'll try to shorten it again, using this.

| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

Jelly,  12  10 bytes

“ḤṾċⱮ”ḤṾċⱮ

Try it online!

How?

“ḤṾċⱮ”ḤṾċⱮ - Main Link: list of characters, S
             (A full program with a single character as input gives the main
              Link a list of characters - i.e. S = ['c'])
“ḤṾċⱮ”     - list of characters = ['Ḥ', 'Ṿ', 'ċ', 'Ɱ']
      Ḥ    - double = ["ḤḤ", "ṾṾ", "ċċ", "ⱮⱮ"]  (Python strings)
       Ṿ   - un-eval = ['“', 'Ḥ', 'Ḥ', 'Ṿ', 'Ṿ', 'ċ', 'ċ', 'Ɱ', 'Ɱ', '”']
         Ɱ - map across (c in) S with:
        ċ  -   count occurrences of c (in the un-eval-ed list)
           - implicit print (a list with a single entry just prints that entry)
| improve this answer | | | | |
\$\endgroup\$
1
\$\begingroup\$

perl, 128 bytes, assuming ASCII input only

print 1;#!"$%&'()*+,-./023456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghjklmoqsuvwxyz{|}~...

Replace the trailing ... with the 33 unprintable characters (ASCII 0 .. ASCII 31 + ASCII 127), with the newline at the end. (If anyone knows how to put unprintable characters in a textfield and have them show up here, I'm all ears).

| improve this answer | | | | |
\$\endgroup\$
1
\$\begingroup\$

R, 96 82 126 94 90 bytes

3*sum(unlist(strsplit(c('"',"#'''((()))*,,3=acilmnprsssttu"),''))==scan(,''))##()*,3amprst

Try it online!

Edit1: thanks to math junkie for pointing-out a horrible bug in the original version (the \ character): hence the temporary increase and subsequent decrease in byte-length, as successive patches were added in panic..

Edit2: -4 bytes: Copying the entire program into the 'look-up' string seemed wasteful (94 bytes), so instead added extra characters so that every character was present an even-number of times, and now just include half the program (character-wise) in the look-up string

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Ouch! Good call! I'm working on it... hoping that this won't cost another 41 bytes to resolve... \$\endgroup\$ – Dominic van Essen 2 days ago
  • \$\begingroup\$ ...cost 12 bytes, so better than worst-case scenario, at least... \$\endgroup\$ – Dominic van Essen 2 days ago
1
\$\begingroup\$

Husk, 10 bytes

D#hs"D#hs"

Try it online!

D             Twice
 #            the number of occurrences of the input in
    "D#hs"    "D#hs",
   s          quoted,
  h           without the second quote.

For the same number of bytes:

Husk, 10 bytes

#S+s"#S+s"

Try it online!

Somewhat boring adaptation of the standard S+s"S+s+ quine.

| improve this answer | | | | |
\$\endgroup\$
1
\$\begingroup\$

Brachylog, 18 bytes

∈"∈∈\\\"∧33||"∧3|∧

Try it online!

Brachylog doesn't really have any good way to get quotes without escaping them in a string literal (or using the constant, which came out longer when I tried it), so the approach I came to is to simply triple down on everything else.

(I don't know why the testing header runs out of stack after it's done every test case; I'd think it's something to do with the unbound variable output for 0 but it works fine on individual inputs... so long as an unbound variable is indeed an acceptable way to give 0. If it's not, +3 bytes)

| improve this answer | | | | |
\$\endgroup\$
1
\$\begingroup\$

Python 3, 48 bytes

x="(x+2*chr(34)+'x=;f=eval(x)').count";f=eval(x)

Try it online!

Idea: Store code in string. The stored code returns function that counts characters in the string within which it is contained. Evaluate the string to get the function. Special care for characters wrapping the string.

Python 3 without eval I, 48 bytes

 lambda c:3*(c in" \\\"(())**33::abbcddiillmmnn")

Try it online!

Python 3 without eval II, 124 bytes

And a more creative, but much longer solution:

lambda c:[0o3623>(ord(c)-76)**2>195,' !!""##$$%%&&++,-..//4457889:;;==ZZ\\^^__``beeffgghhiijjkklmnnppqqrssttuuvvwwxx'][0]<<1

Try it online!

Idea: Ensure all characters that satisfy a certain equation (195 < (c-76)² < 1939) appear exactly twice in the code, and return 2 for those characters (0 for all others). Maybe someone can think of a better compression for the long string, but remember expressing it may only use the same character twice.

| improve this answer | | | | |
New contributor
anroesti is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ Hello and welcome to PPCG; nice first post. For testing, I would add an assertion such that one does not have to manually compare all character counts: TIO. \$\endgroup\$ – Jonathan Frech yesterday
0
\$\begingroup\$

Turing Machine Code, 95 bytes

I'm not sure this counts, and if so deemed, I'll make it non-competing (or delete it if you guys think it's too egregious). The reasons why have to do with the Turing Machine Code interpreter I'm using. This affects the space character ( ), asterisk (*), and semi-colon(;).

Space character
Basically it internally converts space characters into underscores '_'. Also, it interprets the lack of any character as a space character, and therefore interprets that as an underscore. Not only this, but it also interprets an actual underscore '_' as an underscore (or space, or lack of a character). Since the input is strictly limited to the text box on the web page, this means there is significant ambiguity as to how to count a space character. So that character will not work with this code. Any attempts at trying to fudge something here could easily and reasonably be discounted as wrong by atleast 3 different valid interpretations that I can come up with off the top of my head.

Asterisk
This character is set aside for a few special uses, depending on where in the code it's used. Most relevantly for this challenge, the asterisk - when used as an input check - acts as a special catch-all character. So any attempt at trying to catch this as input, catches anything and everything, including the aforementioned space character. It does so without any ability to discern an actual asterisk from the infinite possibilities. So that character will not work with this code.

Semicolon
Lastly, the semicolon is a very strict line comment. You put that anywhere in that line of code, and that's it. Everything after it (inclusive) on that line is interpreted as a comment, and is ignored. As a result of this, this Turing Machine interpretor will never be able to 'read' the semicolon character ';'. So that character will not work with this code.

0 0 1 r 0
0 _ 2 * 2
0 r 7 * r
0 7 3 * r
0 2 7 * 2
0 3 5 * r
0 1 2 * r
0 5 3 * r
0 * 0 * 2;3325_

Try it online!

I'm deeply suspicious that there is a two or three line solution to this. I'll probably play around with this for a bit some more. Having to use a comment to pad the numbers really sets off a flag in my head that this code could accomplish this task far more efficiently.

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ FYI, you cannot "make an answer non-competing" to save it from being deleted. Either this answer is valid, or it needs to be deleted, there's no middle ground (I don't understand this programming language well enough to judge) \$\endgroup\$ – pppery 2 days ago
  • \$\begingroup\$ @pppery. Agreed. Hence my explanation. \$\endgroup\$ – ouflak 2 days ago
0
\$\begingroup\$

Japt, 16 bytes

"UèiQÑ )"iQ èU)Ñ

Try it

Takes inspiration from the normal Japt quine. Essentially, counts the number of occurences in the string at the beginning (with a quote), then doubles it.

| improve this answer | | | | |
\$\endgroup\$
0
\$\begingroup\$

J, 24 bytes

2*1#.0 :0=[
2*1#.0 :0=[

Try it online!

The second newline counts too, so it's not 23.

| improve this answer | | | | |
\$\endgroup\$
0
\$\begingroup\$

Retina 0.8.2, 26 bytes

T`Tan[-a\]\n^0__-`2
[^2]
0

Try it online!

I got the idea to use [-a from @Arnauld's JavaScript answer.

Explanation

T`Tan[-a\]\n^0__-`2

Transliterate each of the following characters into a 2:

  • The letters T, a, and n

  • The range [-a which also includes \, ], ^, _, and `

  • Literal ] and literal newline

  • The characters ^, 0, _, and -

[^2]
0

Replace any character that is not a 2 with a 0

| improve this answer | | | | |
\$\endgroup\$
0
\$\begingroup\$

Whitespace, 144 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S N
S _Duplicate][S S S T   S S S S S N
_Push_32][T S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_SPACE][S N
S _Duplicate][S S S T   S S T   N
_Push_9][T  S S T   _Subtract][N
T   S T N
_If_0_Jump_to_Label_TAB][S S S T    S T S N
_Push_10][T S S T   _Subtract][N
T   S S T   N
_If_0_Jump_to_Label_NEWLINE][N
S N
N
_Jump_to_Label_PRINT][N
S S S N
_Create_Label_SPACE][S S S T    S S T   S T T   N
_Push_75][N
S N
N
_Jump_to_Label_PRINT][N
S S T   N
_Create_Label_TAB][S S S T  S S S S T   N
_Push_33][N
S N
N
_Jump_to_Label_PRINT][N
S S S T N
_Create_Label_NEWLINE][S S S T  S S T   S S N
_Push_36][N
S S N
_Create_Label_PRINT][T  N
S T _Print_as_integer_to_STDOUT]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Character c = STDIN as character
If(c == ' '):
  Print 75 to STDOUT
Else-if(c == '\t'):
  Print 33 to STDOUT
Else-if(c == '\n'):
  Print 36 to STDOUT
Else:
  Print 0 to STDOUT

This sounds pretty straight-forward, but it was reasonably tricky to get the correct numbers. Pushing a number in Whitespace is done as follows:

  • S: Enable Stack Manipulation
  • S: Push number
  • S/T: Positive/negative respectively
  • Some T/S followed by a single N: Decimal as binary, where T is 1 and S is 0

So, after I created the template of my program, the amount of newlines were fixed and I could simply print 36 in that case.
But the amount of spaces and tabs are variable. If I correct the count-output of the amount of spaces, the tabs would be incorrect, and vice-versa. This required some tweaking, which I eventually did without wasting any bytes by using a Label ST for the Label_NEWLINE. Usually I create Labels in the following order, based on the amount of times it's used: (empty label); S; T; SS; ST; TS; TT; SSS; etc. In this case, I've skipped the SS and used ST instead, allowing me to print 75 and 33 with the binary pushes of TSSTSTT and TSSSST for the counts of spaces and tabs respectively.

| improve this answer | | | | |
\$\endgroup\$

Your Answer

Adam Abahot is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.