15
\$\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!

\$\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

23 Answers 23

8
\$\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\$
6
\$\begingroup\$

COW, 711 519 504 390 387 bytes

moOMooMOOmOoMoOMoOMoOMoOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOoMOoMOoMOomOoMOomoomoOMMMMOOMOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOmOomooMMMMOOMOoMOoMMMmoOMoOMoOmoOMOomOomOoOOOmooMMMMOOmOoMoOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOomOoMOomoomoOMMMmoOMOomoOMoOmOomOoOOOmooMMMMOOMoOMoOMMMmoOOOOMoOMoOMoOmoOMOoMOomOomOoOOOmooMMMMOOmoOmoomoOMOOmoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOomoomoOOOM

Try it online!

I appreciated a lot the previous solution (504 bytes) because it's deducted step by step, if you are interested please take a look at that in the timeline...
Now I furnish the program with a more "sensible" structure that promises to be less expensive (in terms of total byte count) but finding just a working set of values isn't simple...
To find the best, brute force comes in.

The next sections refers to the 390 bytes answer since it's simpler to explain that and then tell what it's done to save 3 bytes.

What it does

\$L = \{M,O,o,m\}\$ is the set of used chars and \$n_1,\dots ,n_4\$ their count.
The program has a structure that allows to form the output number \$n_i\$ as $$ \begin{align} n_i = x_i\times cf+y_i \end{align} $$ Furthermore we don't need to form \$x_i\$ and \$y_i\$ every time from zero, we reach them using the partial sums of 2 sequences occurring in cells [2] and [3] respectively.

[0]: multiplier for [1]     [1]: input-current_char     [2]: x_i     [3]: y_i

[1] = getchar()
if[1] { [1]-=77(M), [2]+=8, [3]+=0, cut[1] } paste[1]  //checks for 'M' and prepares its count
if[1] { [1]-= 2(O), [2]+=2, [3]+=0, cut[1] } paste[1]  //checks for 'O' and prepares its count
if[1] { [1]-=32(o), [2]-=1, [3]-=1, cut[1] } paste[1]  //checks for 'o' and prepares its count
if[1] { [1]+= 2(m), [2]-=6, [3]-=2, cut[1] } paste[1]  //checks for 'm' and prepares its count
if ![1]                                                //input was one of the letters above
    print [2]*13+[3]
else                                                   //input was something else
    print [4] (0)

As long as the input doesn't match any letter in \$L\$, [1] stays ≠ 0 and [2] and [3] hold \$x_i\$ and \$y_i\$ of the last tested letter.
Otherwise, if [1] has become 0, those value are no longer updated and at the end they will form the related \$n_i\$.

(When the input isn't a letter in \$L\$, after the 4 tests [1] is still ≠ 0 so the flow enters a loop ([>]) that sabotages the placement of the head, thus prevents from printing \$n_4\$ (the number of o).)

How

I've first constructed the exoskeleton: the complete program without the info about its char count.
That is without \$cf\$(common factor) and the 2 sequences that form \$x_i\$ and \$y_i\$.

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

    >.
    [  <+++++++[>-----------<-]>  > ? > ? <<  =*]=
    [             --              > ? > ? <<  =*]=
    [     <++++[>--------<-]>     > ? > ? <<  =*]=
    [             ++              > ? > ? <<  =*]=
    [>]
    >[> ? <-]>o

Some of them can be negative but I know that in order to write them I'll spend \$len\$: the sum of their absolute value in MoOs and MOos (+ and -).

Thanks to this condition the comptutation is rather straightforward.

Brute force

  • \$cf>0\qquad\qquad A=\{a_1,\ a_2,\ a_3,\ a_4,\ a_5,\ a_6,\ a_7,\ a_8\}\$

  • \$x_i=\sum_{j=1}^{i} a_j \qquad y_i=\sum_{j=5}^{4+i} a_j\$

  • \$n_i = x_i\times cf+y_i\$

  • \$len = cf + \sum_{j=1}^{8} |a_j|\$

$$ (*)\begin{cases} n_1=|M|+len\\ n_2=|O|+len\\ n_3=|o|+len\\ n_4=|m| \end{cases} $$

Given the letter count in the exoskeleton \$|M|=71,\ |O|=97,\ |o|=85,\ |m|=38\$
we can now search for \$cf\$ and \$A\$ that satisfies \$(*)\$ minimizing \$len\$.

cf = 13, A = [8, 2, -1, -6, 0, 0, 1, -2] is the best for that exoskeleton (\$len=33\$)

Finished program

>.
[  <+++++++[>-----------<-]>  >  ++++++++  >      <<  =*]=
[             --              >     ++     >      <<  =*]=
[     <++++[>--------<-]>     >     -      >   +  <<  =*]=
[             ++              >   ------   >  --  <<  =*]=
[>]
>[>+++++++++++++<-]>o

As you can se when some \$a_i\$ is \$0\$ its relative pair of > < became non-functional. But obviously we can't take them off in retrospect.

-3 bytes, 387 bytes

Juggling with the exoskeleton I've found that there is one configuration slightly different that overall saves 3 bytes (1 instruction). What's different?

  • One * is replaced with [-] that has the same effect (+2 instr.)
  • Using one * \$x_4\$ is detached from the partial sum: \$x_4=a_4\$ (+1 instr.)
  • A pair of > < are saved because \$a_5=0\$ (-2 instr.)

The letter count of this exoskeleton is \$|M|=73,\ |O|=98,\ |o|=86,\ |m|=37\$
cf = 13, A = [8, 2, -1, 3, 0, -1, 1, -2] is the best. (\$len=31\$) (-2 instr.)

| improve this answer | |
\$\endgroup\$
5
\$\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\$ – user92069 May 23 at 1:50
  • \$\begingroup\$ @Λ̸̸ Yep! See this golfing tip \$\endgroup\$ – math junkie May 23 at 1:52
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\$
4
\$\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\$

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\$

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\$

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\$
2
\$\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 May 23 at 17:27
  • \$\begingroup\$ ...cost 12 bytes, so better than worst-case scenario, at least... \$\endgroup\$ – Dominic van Essen May 23 at 18:13
  • \$\begingroup\$ No idea if this would help, but you can use "\x5c" for a backslash `\`. Would require a significant rework, no doubt. \$\endgroup\$ – Giuseppe May 26 at 22:00
2
\$\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\$
2
\$\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 | |
\$\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 May 24 at 23:01
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\$

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\$

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\$
1
\$\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\$
1
\$\begingroup\$

Perl 5 + -plF, 49 bytes

$_=q($_=grep/\Q@F/,qq(\$_=q($_);eval)=~/./g);eval

Try it online!

Explanation

Pretty much the standard quine with some minor changes.

The program itself is stored in $_ which is evaled (eval - along with most other functions - works on $_ by default if no argument is specified. When the program is evaluated, $_ is set to the number of matches (~~grep) against the input char /\Q@F/, which is interpolated at runtime and necessitates \Q to escape any special chars, against the list of chars resulting from the template string $_=q(...);eval with the actual program interpolated in the innermost %_, which is obtained with =~/./g (this returns a list of all the chars that matches the regex, . being match-all).

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

Retina, 1 byte

1

Try it online!

Counts the number of 1s in the input, so the output is always 1 or 0.

Inspired by this answer on a related question.

| improve this answer | |
\$\endgroup\$
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 May 23 at 17:58
  • \$\begingroup\$ @pppery. Agreed. Hence my explanation. \$\endgroup\$ – ouflak May 23 at 20:12
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\$

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\$
0
\$\begingroup\$

Ruby -nl, 40...32 28 bytes

p~/[,-2\[-\]p~,..011?:]/?2:0

Try it online!

Derived from my answer to a related challenge. Each of the 14 distinct characters in the code appears twice. The input is tested against a regexp. The outer [] is a character class containing literal characters plus two character ranges: ,-2 is equivalent to the literal characters ,-./012 and \[-\] is equivalent to the literal characters [\]. The code prints 2 if the regexp matches the input character; 0 is printed otherwise.

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

Your Answer

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.