83
\$\begingroup\$

We say a string is non-discriminating if each of the string's characters appears the same number of times and at least twice.

Examples

  • "aa!1 1 !a !1" is non-discriminating because each of the characters , !, a and 1 appear three times.
  • "abbaabb" is not non-discriminating because b appears more often than a.
  • "abc" is also not non-discriminating because the characters don't appear at least twice.

Task

Write a non-discriminating program or function which returns a truthy value if a given string is non-discriminating, and a falsy value otherwise.

That is, the program run on its own source code should return a truthy value.

Each submission must be able to handle non-empty strings containing printable ASCII, as well as all characters appearing in the source code of the submission.

Test Cases

Truthy:

<your program's source code>
"aaaa"
"aa!1 1 !a !1"
"aabbccddeeffgg"
"1Q!V_fSiA6Bri{|}tkDM]VjNJ=^_4(a&=?5oYa,1wh|R4YKU #9c!#Q T&f`:sm$@Xv-ugW<P)l}WP>F'jl3xmd'9Ie$MN;TrCBC/tZIL*G27byEn.g0kKhbR%>G-.5pHcL0)JZ`s:*[x2Sz68%v^Ho8+[e,{OAqn?3E<OFwX(;@yu]+z7/pdqUD"

Falsy:

"a"
"abbaabb"
"abc"
"bQf6ScA5d:4_aJ)D]2*^Mv(E}Kb7o@]krevW?eT0FW;I|J:ix %9!3Fwm;*UZGH`8tV>gy1xX<S/OA7NtB'}c u'V$L,YlYp{#[..j&gTk8jp-6RlGUL#_<^0CCZKPQfD2%s)he-BMRu1n?qdi/!5q=wn$ora+X,POzzHNh=(4{m`39I|s[+E@&y>"
\$\endgroup\$
18
  • 4
    \$\begingroup\$ @Laikoni are we able to abuse comments to get this to work? \$\endgroup\$ Mar 1, 2018 at 14:36
  • 8
    \$\begingroup\$ As a side note, I love challenges where I can use other entries to test my entry's validity. \$\endgroup\$ Mar 1, 2018 at 14:38
  • 3
    \$\begingroup\$ @MagicOctopusUrn I think that he did say in the sandbox that's allowed, since it can't be observably determined. \$\endgroup\$ Mar 1, 2018 at 14:38
  • 12
    \$\begingroup\$ Exactly. Even if you somehow manage to ban comments in an objective fashion, then what about unused string literals ect? Anyway, I think the scoring gives incentive to avoid comments as much as possible. \$\endgroup\$
    – Laikoni
    Mar 1, 2018 at 14:42
  • 4
    \$\begingroup\$ I get it's just a puzzle, but the conflation of "non-discriminating" with "all identifiable labeled member types existing in exactly equal parts" is mildly disturbing... To "discriminate" means "to tell the difference between", and to unfairly do this means to treat or judge someone unfairly based on seeing them as different from another class of people. Of course, keep going with the fun! \$\endgroup\$
    – ErikE
    Mar 1, 2018 at 22:06

42 Answers 42

40
\$\begingroup\$

Brachylog, 10 bytes

=ᵍbᵐbᵐlᵍ=l

Try it online!

Explanation

=ᵍ                Group all equal elements together
  bᵐbᵐ            Remove the first element of each group twice. This fails if
                  there are fewer than 2 elements
      lᵍ          Group elements together that have the same length
        =         Are all elements of that list equal? This only succeeds if the
                  list has one element
         l        Length. This will always succeed
\$\endgroup\$
27
\$\begingroup\$

Java 8, 198 192 186 174 168 165 160 bytes (char-count 6 5)

o->{byte x[]=new byte[+333-3|2],u=-0,i,fe,fi,w; s:w:no0r3sswwyyy:for(int s:o){{u=++x[s];}};for(int b:x){if(!!!(2>b||u==b)|2>u|2>2){x[0]++;}}return!!(0>--x[0]);}

Try it online.
Code used to verify the occurrences of the characters, which was my answer for this challenge.

-5 bytes thanks to @OlivierGrégoire again by getting rid of the comment and making a mess. ;)

Old 168 bytes (char-count 6) answer:

o->{int w[]=new int[2222],u=0,f=0;for(int r:o)u=++w[r];for(int e:w)if(!(2>e|u==e)|2>u)f++;return!(f>0);}//[[[]]]  !!!!e(i)++,,,,-----oo////000tuww::::{{{{{;;||||}}}}}>>

Try it online.
Code used to verify the occurrences of the characters excluding comment, which was my answer for this challenge.

-6 bytes thanks to @OliverGrégoire removing < by swapping the checks to >.

Explanation of the base golfed program (98 bytes):
Try it online.

s->{                     // Method with character-array parameter and boolean return-type
  int a[]=new int[256],  //  Occurrences integer-array containing 256 zeroes
      t=0,               //  Temp integer, starting at 0
      f=0;               //  Flag integer, starting at 0
  for(int c:s)           //  Loop over the input
    t=++a[c];            //   Increase the occurrence-counter of the current character
                         //   And set the temp integer to this value
  for(int i:a)           //  Loop over the integer-array
    if(i>1               //   If the value is filled (not 0) and at least 2,
       &i!=t             //   and it's not equal to the temp integer
       |t<2)             //   Or the temp integer is lower than 2
      f++;               //    Increase the flag-integer by 1
  return f<1;}           //  Return whether the flag integer is still 0

Some things I did to reduce the amount of characters used:

  • Variable names o, w, u, f, r, and e were chosen on purpose to re-use characters we already had (but not exceeding 6).
  • 2222 is used instead of 256.
  • Changed the if-check e>0&u!=e|u<2 to !(e<2|u==e)|u<2 to remove 6x &.
  • Removed the two separated returns and used a flag f, and we return whether it is still 0 in the end (this meant I could remove the 6x by from byte now that we only use n in int 6 times instead of 8).
  • e<2 and u<2 changed to 2>e and 2>u to remove 6x <.

What I did to reduce the char-count 6 to 5:

  • 2x int to byte so the amount of n used is 4 instead of 6.
  • Used x[0] instead of a new variable f=0 so the amount of = used is 5 instead of 6.
  • Changed 2222 to 3333 so the amount of 2 used is 2 instead of 6.
  • Changed variables f and r again so they aren't 6 anymore either.

What @OlivierGrégoire did to get rid of the comment, and therefore the 5x /:

  • Adding unused variables ,i,fe,fi,w;.
  • Adding unused labels: s:w:no0r3sswwyyy:.
  • Adding unused |2>2
  • Adding {} around the for-loops and ifs, and added an unused {}-block.
  • Changing ! to !!!.
  • Changing | to ||.
  • Changing 333 to +333-3|2to get rid of leftover arithmetic operators +-| and the 2.
  • Changing !(x[0]>0) to !!(0>--x[0]).
\$\endgroup\$
11
17
\$\begingroup\$

Jelly, 18 16 12 10 bytes

Ġ¬zḊḊ¬zĠȦȦ

Try it online!

How it works

Ġ¬zḊḊ¬zĠȦȦ  Main link. Argument: s (string)

Ġ           Group the indices of s by their corresponding elements.
            "abcba" -> [[1, 5], [2, 4], [3]]

 ¬          Take the logical NOT of each 1-based(!) index.
            [[1, 5], [2, 4], [3]] -> [[0, 0], [0, 0], [0]]

   Ḋ        Dequeue; yield s without its fist element.
            "abcba" -> "bcba"

  z         Zip-longest; zip the elements of the array to the left, using the
            string to the right as filler.
            ([[0, 0], [0, 0], [0]], "bcba") -> [[0, 0, 0], [0, 0, "bcba"]]

    Ḋ       Dequeue; remove the first array of the result.
            This yields an empty array if s does not contain duplicates.
            [[0, 0, 0], [0, 0, "bcba"]] -> [[0, 0, "bcba"]]

    ¬       Take the logical NOT of all zeros and characters.
            [[0, 0, "bcba"]] -> [[1, 1, [0, 0, 0, 0]]]

      Ġ     Group.

     z      Zip-longest. Since all arrays in the result to the left have the same
            number of elements, this is just a regular zip.
            [[1, 1, [0, 0, 0, 0]]] -> [[1], [1], [[0, 0, 0, 0]]

       Ȧ    Any and all; test if the result is non-empty and contains no zeroes,
            at any depth. Yield 1 if so, 0 if not.
            [[1], [1], [[0, 0, 0, 0]] -> 0

        Ȧ   Any and all.
            0 -> 0
\$\endgroup\$
0
15
\$\begingroup\$

Brachylog, 14 12 bytes

ọtᵐℕ₂ᵐ==tℕ₂ọ

Try it online!

Explanation

ọ   Occurrences. Gives a list of [char, count] pairs for the entire input.
tᵐ  Map "tail" over this list, giving each character count.
ℕ₂ᵐ Make sure that each count is at least 2.
=   Make sure that all counts are equal.
    At this point we're done with the actual code, but we need another copy
    of each character (except ᵐ). We can just put them after this, as long as
    we make sure that they can never cause the predicate to fail.
=   Make sure that all counts are equal, again...
t   Extract the last count.
ℕ₂  Make sure that it's at least 2, again...
ọ   Get the digit occurrences in that count, this can't fail.

Alternative 12-byte solution that reuses t instead of :

ọtᵐ==tℕ₂ℕ₂ọᵐ
\$\endgroup\$
0
14
\$\begingroup\$

T-SQL, 320 bytes (32 chars x 10 each)

Input is via pre-existing table FILL with varchar field STEW, per our IO standards.

WITH BUMPF AS(SeLeCT GYP=1
UNION ALL
SeLeCT GYP+1FROM BUMPF
WHeRe GYP<=1000)SeLeCT
IIF(MIN(WAXBY)<MAX(WAXBY)OR
MAX(WAXBY)<=1,+0,+1)FROM(SeLeCT
WAXBY=COUNT(1),WHICH=+1+0,HEXCHANGE=+01,HUNG=+0+1,CHLUB=+0,GEFF=+0FROM
BUMPF,FILL WHERE
GYP<=LEN(STEW)GROUP BY
SUBSTRING(STEW,GYP,1))CHEXX
OPTION(MAXRECURSION 0)----------<<<<<<

I have never been more pleased, yet horrified, by a piece of code.

Must be run on a server or database set to a case-sensitive collation. There are 10 each of 32 different characters, including upper and lowercase E (SQL commands are case-insensitive, so flipped a few as needed), spaces and tabs (tabs are shown as line breaks in the code above, for readability).

I found ways to include 10 each of the other symbols + = , in the code, but unfortunately couldn't find a way to do that with <, so I had to add the comment character -.

Here is the formatted code before I crammed in all the extra filler:

WITH b AS (SELECT g=1 UNION ALL SELECT g+1 FROM b WHERE g<1000)
SELECT IIF(MIN(w)<MAX(w) OR MAX(w)<1+1,0,1)
FROM(
    SELECT w=COUNT(1), --extra constant fields here are ignored
    FROM b, fill
    WHERE g < 1+LEN(stew)
    GROUP BY SUBSTRING(stew,g,1)
)a OPTION(MAXRECURSION 0)

The top line is a recursive CTE that generates a number table b, which we join to the source string to separate by character. Those characters are grouped and counted, and the IIF statement returns 0 or 1 depending on whether the input string is non-discriminating.

\$\endgroup\$
13
\$\begingroup\$

C (gcc),  333  168 bytes

Thanks to @Kevin Cruijssen for saving 9 bytes and thanks to @Laikoni for saving 45 bytes!

f(r,h,a){char*o=r,c[222]={!o};for(a=!o;*o;)++c[*o++];for(h=!o;222/++h;c[h]&&c[h]!=a&&(a=!*c))!a&&c[h]&&(a=c[h]);r=!(2/2/a);}/////!(())****++,,,,,[[]]fffffrr{{{{{{}}}}}}

Try it online!

C, 333 bytes

i,v;f(S){char*s=S,L[128]={0};for(v=0;*s;)++L[*s++];for(i=-1;++i<128;L[i]&&L[i]-v?v=-1:0)!v&&L[i]?v=L[i]:0;return-v<-1;}/////////!!!!!!!!&&&&&(((((())))))******+++,,,,,,,----00000111122222228888888:::::::<<<<<<<===???????LLLSSSSSSS[[[]]]aaaaaaaacccccccceeeeeeeeffffffhhhhhhhhiinnnnnnnnooooooorrrrssssssttttttttuuuuuuuuvv{{{{{{{}}}}}}}

Even the bytecount is non-discriminating!

Try it online!

\$\endgroup\$
7
  • \$\begingroup\$ Awwhh... I wanted to be the first comment abuser. Nice one though, I like how you sorted the chars for the comment ^_^ \$\endgroup\$ Mar 1, 2018 at 14:38
  • 1
    \$\begingroup\$ You can lower it to 324 bytes by changing both the 128 to 222 so the 8 can be dropped. \$\endgroup\$ Mar 1, 2018 at 16:44
  • 1
    \$\begingroup\$ 279 bytes by renaming i, v, S, s and L to characters which already appear in the keywords char, for and return: Try it online! \$\endgroup\$
    – Laikoni
    Mar 2, 2018 at 11:24
  • \$\begingroup\$ @Laikoni Thanks! I didn't have the time to properly golf this yesterday. \$\endgroup\$
    – Steadybox
    Mar 2, 2018 at 20:10
  • \$\begingroup\$ @MagicOctopusUrn They are sorted because I was too lazy to add them by hand. \$\endgroup\$
    – Steadybox
    Mar 2, 2018 at 20:16
12
\$\begingroup\$

05AB1E, 20 18 16 14 bytes

S¢Z≠sË*sZ¢≠SË*

Try it online!

The program is essentially divided into 2 parts where the goal of the first part is to do the actual task and the goal of the second part is to use the same functions as the first part without altering the result.

Explanation (first part)

S          # push input split into list of chars
 ¢         # count the occurrence of each char in input
  Z≠       # check that the max count is not 1
    sË     # check if all counts are equal
      *    # multiply

Explanation (second part)

s          # swap input to top of stack
 Z¢        # count the number of occurrences of the largest element
   ≠       # check that the count isn't 1
    SË     # split into list and check that each element are equal (always true)
      *    # multiply (as it is with 1, the original result is left unchanged)
\$\endgroup\$
4
  • \$\begingroup\$ {γ€gDË*P≠qq{γ€gDË*P≠ is another for 20 ;). \$\endgroup\$ Mar 1, 2018 at 14:34
  • 1
    \$\begingroup\$ @MagicOctopusUrn: Nice! I had a couple of others at 20 as well. I do have one at 18 now as well :) \$\endgroup\$
    – Emigna
    Mar 1, 2018 at 14:34
  • 2
    \$\begingroup\$ WITCHCRAFT! No other explanation! \$\endgroup\$ Mar 1, 2018 at 14:36
  • 1
    \$\begingroup\$ ¢... good idea man, also I'm glad to see was as useful as I thought it may be haha! \$\endgroup\$ Mar 1, 2018 at 16:03
11
\$\begingroup\$

Husk, 14 bytes

§<ε#εu§m#u
m
<

Try it online!

Explanation

The two short lines are no-ops, since the main function never calls them.

§<ε#εu§m#u  Implicit input, say S = "asasdd"
         u  Remove duplicates: "asd"
      §m#   For each, get number of occurrences in S: [2,2,2]
     u      Remove duplicates: L = [2]
   #ε       Number of elements in L that are at most 1: 0
  ε         1 if L is a singleton, 0 otherwise: 1
§<          Is the former value smaller than the latter?
\$\endgroup\$
4
  • \$\begingroup\$ But this has ‘u’ more than ‘m’, so it doesn’t meet the requirements. \$\endgroup\$
    – WGroleau
    Mar 2, 2018 at 12:34
  • \$\begingroup\$ @WGroleau m also occurs twice: on the first line and on the second line. The explanation doesn't include the two short lines because they don't affect the behavior of the program. \$\endgroup\$
    – Zgarb
    Mar 2, 2018 at 12:39
  • \$\begingroup\$ I guess the OP should clarify whether an explanation of the program can be scanned along with the program.but actually, if you include that, then you have four ‘u’ and two ‘m’ \$\endgroup\$
    – WGroleau
    Mar 2, 2018 at 12:41
  • \$\begingroup\$ Never mind; this confused me the same way another answer did. \$\endgroup\$
    – WGroleau
    Mar 2, 2018 at 12:50
11
\$\begingroup\$

Python 2, 75 69 bytes

def f(s):len({2<<s.count(c)-2for c,in s})<2or{{e.dil:-tu,r.dil:-tu,}}

Output is via presence or absence of an error. The error is either a ValueError (one or more characters occur only once) or a NameError (the character counts are unequal).

Try it online!

\$\endgroup\$
8
  • \$\begingroup\$ The negative shift error trick is neat! I like how it takes advantage of the shift operator low precedence. \$\endgroup\$
    – Vincent
    Mar 2, 2018 at 14:55
  • 1
    \$\begingroup\$ {{e.dil:-tu,r.dil:-tu,}} Good lord what is that? \$\endgroup\$ Mar 5, 2018 at 14:45
  • 1
    \$\begingroup\$ @AdamBarnes Syntactically valid gibberish that throws a NameError if evaluated. \$\endgroup\$
    – Dennis
    Mar 5, 2018 at 14:53
  • \$\begingroup\$ I don't get it. I tried swapping it out for a and everything broke. Could you explain further please? \$\endgroup\$ Mar 5, 2018 at 15:01
  • \$\begingroup\$ @AdamBarnes That should work, as long as you leave a space after the or. I'll add an explanation when I'm at a computer. \$\endgroup\$
    – Dennis
    Mar 5, 2018 at 16:19
9
\$\begingroup\$

Brachylog v2, 8 bytes (in Brachylog's character set)

oḅ\k\koḅ

Try it online!

Looks like there's been a golfing war going on on this question in Brachylog, so I thought I'd join in, saving a couple of bytes over the next best answer.

This is a full program that takes input as a list of character codes. (This is partly because Brachylog appears to have some very bizarre bugs related to backslashes in strings, and partly because the \ command doesn't work on lists of strings.)

Explanation

oḅ\k\koḅ
o          Sort {standard input}
 ḅ         Group identical adjacent values
  \        Assert rectangular; if it is, swap rows and columns
   k       Delete last element
    \      Assert rectangular; (rest of the program is irrelevant)

The koḅ at the end is irrelevant; k will always have an element to act on and o and cannot fail if given a list as input.

The reason for the starting oḅ should be clear; it partitions the input list by value, e.g. [1,2,1,2,4,1] would become [[1,1,1],[2,2],[4]]. In order for each character to appear the same number of times, each of these lists must be the same length, i.e. the resulting list is a rectangle. We can assert this rectangularity using \, which also transposes the rows and columns as a side effect.

We now have a current value consisting of multiple copies of the character set, e.g. if the input was [4,2,1,2,4,1] the current value would be [[1,2,4],[1,2,4]]. If we delete a copy, the resulting matrix is still rectangular, so we can turn it back using \. However, if the reason the matrix was rectangular was that all the input characters were distinct, the resulting matrix will have no elements left, and \ does not treat a "0×0" matrix as rectangular (rather, it fails). So oḅ\k\ effectively asserts that each character that appears in the input appears the same number of times, and that number of times is not 1.

That's the entire functionality of our program (as a full program, we get true if no assertion failures occurred, false if some did). We do have to obey the source layout restriction, though, so I added an additional koḅ that has no purpose but which cannot fail (unlike \, o and are happy to act on empty lists).

\$\endgroup\$
1
8
\$\begingroup\$

Python 2, 84 80 bytes

x=input()
c=map(x.count,x)
print max(c)==min(c)>1
1. or our>ram>>utopia,
1., 1.,

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ +1 for non-error-producing short Python code and our ram utopia ;) \$\endgroup\$ Mar 5, 2018 at 4:40
8
\$\begingroup\$

JavaScript (Node.js), 144 ... 100 96 bytes

o=>!(a=o.split``.map(i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1)).some(g=>![g>1][-!1]||a[-!1]-g)

Try it online!

24 different characters * 6 times each

28 different characters * 5 times each

27 different characters * 5 times each

27 different characters * 4 times each

26 different characters * 4 times each

25 different characters * 4 times each

24 different characters * 4 times each

Explanation

o=>!(
 a=o.split``.map(                            // Split the input into character array and
  i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1 // count the occurrences of each character.
 )
).some(                                      // Then check
 g=>![g>1][-!1]                              // If each character appears at least twice
 ||a[-!1]-g                                  // and the counts are all the same number.
)                                            

More to add:
1. Using {s.split``} instead of {[...s]} is to reduce the number of {.} that dominates
   the count.
2. Using {!c.some} instead of {c.every} to reduce the number of inefficient characters 
   (v,r,y in every)
3. Still one unavoidable inefficient character left ({h}).

Update:
1. Got rid of one {.} by replacing {.length} by {["length"]}.
2. Got rid of one {=} by replacing {c[-!1]!=g} by {c[-!1]-g}.
3. Got rid of one {()} by replacing {!(g>1)} by {![g>1][-!1]}.
4. Finally, because count per character is now 4, the backslashes can be taken out.

Update:
1. Got rid of all {"} by replacing {"length"} by {`length`} and exploiting shortcut
   evaluation. 
   {aaaeehhhlmmnnnpst} is not defined but is not evaluated either because of {c} which
   must be evaluated to true.

Update:
1. Got rid of all {c} by shortcutting the undefined variable at {split(i)} and replacing 
   all {c} by {a}.
   Since {i} is never an empty string, it is always evaluated true (except compared 
   directly to true).

Update:
1. Got rid of all {,} by moving the assignment after the argument list. The {()} at the
   front can therefore be moved to the assignment, retaining same number of {()}s.
\$\endgroup\$
2
  • \$\begingroup\$ what on golf's green is "aaaeehhhlmmnnnpst"? \$\endgroup\$ Feb 6, 2022 at 0:27
  • 1
    \$\begingroup\$ @thejonymyster a dummy filler that's never evaluated \$\endgroup\$ Feb 13, 2022 at 8:19
6
\$\begingroup\$

Brachylog, 18 bytes

oḅlᵐ=h≥2
oḅlᵐ=h≥2

Try it online!

Unfortunately, I can't remove the linefeeds, since on a number triggers a fail.

\$\endgroup\$
2
  • \$\begingroup\$ It is definitely possible to do something shorter that doesn't require linefeeds (but you might need to change some things) ;) \$\endgroup\$
    – Fatalize
    Mar 1, 2018 at 14:20
  • \$\begingroup\$ @Fatalize No time to currently, and yes I did read that discussion. :) \$\endgroup\$ Mar 1, 2018 at 14:20
6
\$\begingroup\$

PowerShell, 104 bytes

($qe=$args[0]| group |sort count|% count)[0]-eq$qe[-1]-and$qe[0]-gt1####((()))%%%pppddd===aaccss11nu|0gr

Try it online!

This was great fun to golf. The limitation was $, which we need four of at minimum (one for the input $args, one for assigning the computation result $qe, one for checking the last character $qe[-1] and one for checking the first character $qe[0], so that was the working maximum number of characters.

From there, it was a matter of golfing (and not-golfing, like having a two-letter variable name) to get the program nicely divisible by four. Note that we have a small comment (everything following the #) to account for some missing elements, but I tried to keep the comment as small as possible.

\$\endgroup\$
6
\$\begingroup\$

Haskell, 90 75 72 bytes

a[i]|d:n<-[[i|n<-i,n==a]|a<-i]=and[[i]<d,[d|i<-n]==n]--aadd,,,,:::::<=||

Each character appears 6 times. The input string is taken as a singleton list.

Try it online!

For reference, old versions:

75 bytes, each char 5 times

n(l)|d<-[[0|n<-l,n==a]|a<-l]=and[[0]<d!!0,all(==d!!0)d]--an!((())),,,0<[]||

Try it online!

90 bytes, each char 3 times:

a x|h:u<-[sum[1|d<-x,not(d/=c)]|c<-x],"  \"\\&,../1::>acdlmmnosst">[]=h>1&&all(not.(/=h))u

Try it online!

\$\endgroup\$
6
\$\begingroup\$

Python 2, 108 104 92 88 bytes

-12 bytes thanks to Rod
-4 bytes thanks to Kevin Cruijssen

s=input();c=s.count;print[all(c(s[[]>[1]])==c(o)>1. for o in s)];aaafffillpprrtuu>1.>1.;

Try it online!

\$\endgroup\$
7
6
\$\begingroup\$

MATL, 12 bytes

q&=sqt&=tsvv

The input is a string enclosed in single quotes. Single quotes in the string are escaped by duplicating.

The output is a non-empty matrix, which is truthy if it doesn't contains zeros, and is falsy if it contains at least a zero.

Try it online! Or verify all test cases, including the standard truthiness/falsiness test for convenience.

How it works

Statements marked with (*) are neither necessary nor harmful, and have been included only to make the source code non-discriminating.

q     % Implicit input. Convert chars to code points and subtract 1 from each (*)
&=    % Square matrix of all pairwise equality comparisons
s     % Sum of each column. Gives a row vector
q     % Subtract 1 from each value. An entry equal to 0 indicates the input string
      % is discriminating because some character appears only once
t     % Duplicate
&=    % Square matrix of all pairwise equality comparisons. An entry equal to 0
      % indicates the input string is discriminating because some character is
      % more repeated than some other
t     % Duplicate (*)
s     % Sum of each column (*) (all those sums will be positive if the previous
      % matrix doesn't contain zeros)
v     % Vertically concatenate the matrix and the vector of its column sums
v     % Vertically concatenate the resulting matrix with nothing (*)
      % Implicit display
\$\endgroup\$
5
\$\begingroup\$

Ruby, 87 78 bytes

c=->m{y=m.chars;x=y.map{|d|y.count d}|[];x[-1]>1and not x[1]};->{pushrortpush}

26 characters repeated 3 times each

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ @nimi Thanks for pointing it out, I think that was some weirdness with gets and ;. Changed it, it's shorter as a lambda anyway \$\endgroup\$ Mar 1, 2018 at 18:00
5
\$\begingroup\$

Perl 5, -p 57 bytes

Each character appears 3 times. Only a single 1 doesn't do anything

12 bytes added to a basic 45 character solution to make in non-discriminating

s{.}[@m[@1{$&}+=$.].=g]eg;$\=s()(e@m;1)&&m[e(\sg+)\1+;]}{

Try it online!

\$\endgroup\$
5
\$\begingroup\$

R, 90 bytes

"?"=`u\164f8ToI\x6Et`;'!'=prod;!{y<-xtabs(~?readLines())}%in%{z<-y[1]}&z>T##&[]>~48bEfILpu

Try it online!

Outputs TRUE for a non-discriminating string, and FALSE for a discriminating string. I have written a lot of ugly code for challenges on this site, but I think this is the ugliest so far.

45 characters, used twice each (including a few in a comment). The previous best R answer was 116 bytes, with 29 characters used 4 times each; I am posting this separately since it is substantially different.

The code is equivalent to

y = table(utf8ToInt(readLines()))
z = y[1]
all(y == z) & (z > 1)

which converts the input to a vector of integers, computes a contingency table y of the values, then checks that all counts in that table are equal to the first count, and that the first count is greater than 1.

The initial difficulty was in using only 2 pairs of brackets. This is achieved by redefining the unary functions ! and ? to be utf8ToInt and prod respectively. (I can't use all because I need the a). There are four assignments: two with = and two with <-. This means that the equality test between y and z cannot use y==z nor y-z; y%in%z comes to the rescue.

Defining these functions uses up all the possible quotes: two double quotes, two single quotes, and I'll need the two backticks in the next paragraph, so I had to resort to readLines() instead of scan(,""). (The other options, such as scan(,letters) or scan(,month.abb) all used a precious t which I couldn't spare.)

At this point, I had most of the building blocks: utf8ToInt, prod, table, readLines, %in%. Three characters appear three times in those names: ent. First, I discovered that table(foo) is equivalent to xtabs(~foo), saving the e. I can rescue the n and the t with the hex/octal code trick; the golfiest solution is to use u\164f8ToI\x6Et (in backticks) for utf8ToInt.

\$\endgroup\$
4
  • \$\begingroup\$ It's impressive you can discriminate the two cases in 90 bytes (and nice abuse of the help operator), but alas NA is not considered a truthy value (in R, if(NA) x else y causes an error, so NA is neither truthy nor falsey) \$\endgroup\$
    – JDL
    Sep 5, 2019 at 16:03
  • 1
    \$\begingroup\$ @JDL Thanks, you're right. The latest edit fixes this issue. \$\endgroup\$ Sep 6, 2019 at 3:57
  • 1
    \$\begingroup\$ @JDL the comments suggest that consistent, distinct answers are ok for truthy and falsy. \$\endgroup\$
    – Giuseppe
    Sep 6, 2019 at 3:57
  • \$\begingroup\$ @Giuseppe Actually, I solved this issue seconds ago (see new version, which is quite different but same byte count); now outputs TRUE and FALSE. \$\endgroup\$ Sep 6, 2019 at 3:58
4
\$\begingroup\$

R, 132 116 bytes

crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;"";{1<{f<<-table(strsplit(b,"",,,)[[1]])}}&&!!!sd(-f)}}

It doesn't contain any comments or superfluous strings, either, though this will probably be my only time in code golf calling a function crudcardounenforceableuploads. There's probably a great anagram in there somewhere for the function name!Thanks to John Dvorak for pointing out a nice anagram solver, which I used for the name.

Character table:

- , ; ! " ( ) [ ] { } & < 1 a b c d e f i l n o p r s t u 
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4

examples:

> crudcardounenforceableuploads("aaabbbccc")
[1] TRUE
> crudcardounenforceableuploads("aaabbbcc")
[1] FALSE
> crudcardounenforceableuploads("abc")
[1] FALSE
> crudcardounenforceableuploads("crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;\"\";{1<{f<<-table(strsplit(b,\"\",,,)[[1]])}}&&!!!sd(-f)}}")
[1] TRUE
\$\endgroup\$
9
  • \$\begingroup\$ don't know if byte count is important but we can probably remove the 2s and the >s, by switching round the comparison with f. Also can use = instead of <<-. strsplit is probably unavoidable though, which is the source of most of the other characters. \$\endgroup\$
    – JDL
    Mar 1, 2018 at 17:25
  • \$\begingroup\$ do you need the spaces? you could also try utf8ToInt instead of strsplit, but not sure if that'll help. Also maybe include a link to TIO? \$\endgroup\$
    – Giuseppe
    Mar 1, 2018 at 17:59
  • \$\begingroup\$ also all the . seem to be superfluous. \$\endgroup\$
    – Giuseppe
    Mar 1, 2018 at 18:02
  • \$\begingroup\$ This is code-golf, so byte count is important, per your comment. \$\endgroup\$
    – Giuseppe
    Mar 1, 2018 at 18:09
  • 2
    \$\begingroup\$ some possible anagrams: no pip-bonded cupboard bureaucracies; RIP carbonaceous barbecued pound dip. Found using wordplays.com/anagrammer \$\endgroup\$ Mar 2, 2018 at 8:32
4
\$\begingroup\$

C (gcc), 153 bytes

f(h,a,c,f){{{{{{{char*o=f=h,*r;for(a=!h;*o;o++){for(c=!h,r=h;*r;c+=!(*r++^*o)){}f*=!!(c^!!h)*(!a+!(a^c));a=c;}(a^c^c^f^f^h)+o,a+r,o,o,+h^*r;(a=f);}}}}}}}

Try it online!

Returns address of string as truthy value, and zero as falsy.

f(
h,                              Address of string.
a,                              # instances of previous character
c,                              # instances of current character
f                               Return value
){{{{{{{                        
char*o=f=h,*r;                  Point o to string, while giving f a non-zero value.
for(a=!h;*o;o++){               Set previous char count to 0, and then traverse the string.
for(c=!h,r=h;*r;                Set current char count to 0 and r to string,
                                and start counting instances of current character.
c+=!(*r++^*o))                  Add to counter if current character matches.
{}                              Lower the amount of semi-colons
f*=                             Multiply (AND) return value with:
   !!(c^!!h)                    Is current count not 1? (Must be 2 or above.)
            *(!a+!(a^c));       AND, is previous count valid (meaning this is not the first
                                character counted), and matches current count?
a=c;}                           Previous count = current count.
(a^c^c^f^f^h)+o,a+r,o,o,+h^*r;  Spend surplus characters to make source code valid.
(a=f);}}}}}}}                   Return value.
\$\endgroup\$
2
\$\begingroup\$

BASH 144 bytes

grep -o .|sort|uniq -c|awk '{s=$1}{e[s]=1}END{print((s>1)*(length(e)==1))}##>>>#|'#wwwuuutrqqqppooNNNnlllkkkiihhhggEEEDDDcccaaa1***{}[[[]]]...--''

This line of code takes an stdin string as input. "grep -o ." puts each character on a new line. "uniq -c" counts each chacter's usage. The awk script creates an array with each usage as a different element, and outputs true when there is only 1 array index and the value is at least 2. Each character is used 4 times, so this source returns true

\$\endgroup\$
0
2
\$\begingroup\$

Stax, 26 24 18 bytes

:u{m*_{y#m:u_hy#h*

Try it online!

Shortest solution so far that only uses printable ASCIIs Beaten by MATL.

Guess I was approaching the problem the wrong way. Repeating a working block is neither golfy nor interesting. Now at least it looks better ...

Explanation

:u{m* produces some garbage that does not affect the output.

_{y#m:u_hy#h*
_{y#m           map each character to its number of occurences in the string
     :u         all counts are equal (result 1)
       _hy#     get the count of appearance for the first character
           h    halve it and take the floor, so that 1 becomes 0(result 2)
            *   multiply the two results
\$\endgroup\$
4
  • \$\begingroup\$ @WGroleau which characters appear once? Did you read my answer carefully enough? \$\endgroup\$ Mar 2, 2018 at 12:41
  • \$\begingroup\$ ‘#’ appears more often than ‘:’ (just one example). Oops, misreading (see other comment) \$\endgroup\$
    – WGroleau
    Mar 2, 2018 at 12:44
  • \$\begingroup\$ @WGroleau There are exactly two #'s and two :s, did you read my answer on the second line? Did you just skip the first paragraph in my "Explanation"? \$\endgroup\$ Mar 2, 2018 at 12:45
  • \$\begingroup\$ Sorry, thought the line above the explanation was the whole thing. \$\endgroup\$
    – WGroleau
    Mar 2, 2018 at 12:48
2
\$\begingroup\$

Pip, 22 18 bytes

^1>=Y^aNaYMNy=My>1

Attempt This Online!

Explanation

Each character occurs twice.

^1>=Y^aNaYMNy=My>1
      a             First command-line argument (a string)
     ^              Split into a list of characters
       Na           Count occurrences of each character in a
    Y               Yank the result into y
^1>=                No-op: compare with [1]
          MNy       Minimum of y
             =      is equal to
              My    Maximum of y
                >1  which is also greater than one
         Y          No-op: yank that result 
                    Autoprint the result of the last expression

Alternate 18-byters:

Y^!1Y^aNaMNy=My!=1
Y_<=1Y_NaMa1<Ny=My
\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 164 152 148 140 bytes

DeF M(X)DIM W[#R]WHILE""<X
INC w[ASC(x)]X[n]=""wEND
FOR F=e#TO--nOT-LEN(W)U=w[F]H=H||U&&U<MAx(W)neXT-!!!AASSS#&&Oxx||CCLL<<wIM#
RETURN!H
enD

35 different characters, repeated 4 times each.

No comments were used (but the expression after neXT is never actually evaluated)

Script to check answers:

//javascript is a convenient language that I love using!
var input=document.getElementById("input");
var button=document.getElementById("button");
var output=document.getElementById("output");

button.onclick=function(){
  var text=input.value;
  var freqs={};
  for(var i=0;i<text.length;i++){
    var letter=text.charAt(i);
    if (freqs[letter]==undefined) freqs[letter]=0
    freqs[letter]++
  }
  sorted=Object.keys(freqs).sort(function(a,b){return freqs[b]-freqs[a]})
  var out="";
  var min=Infinity,max=0;
  for (var i in sorted) {
    var letter=sorted[i];
    var count=freqs[letter];
    if(count<min)min=count;
    if(count>max)max=count;
    out+="\n"+letter+":"+count;
  }
  output.textContent="min:"+min+"\nmax:"+max+"\nunique:"+sorted.length+"\nlength:"+text.length+out;
}
<textarea id="input" placeholder="code here"></textarea>
<button id="button"butt>count</button>
<pre id="output">...</pre>

\$\endgroup\$
1
\$\begingroup\$

Retina 0.8.2, 168 90 bytes

The output will be empty if false, or non-empty if true.

***???;;;;```!!$$$$MMMMOOOO..1111ssss222{{{{\^^^^

s;{O`.
M!*\`^((.)\2(?!\2))*$
(.)(?!\1)

Try it online

Core program (39 bytes)

s;{O`.
M!*\`^((.)\2(?!\2))*$
(.)(?!\1)

Explanation

The entire core program is in a silent loop. The first stage sorts the input. The second stage will print the current string if it consists of successive pairs of different characters. The third stage removes the last occurrence of every character (removing one of each character in the string).

About the junk at the top: the order is important. In addition to needing to be syntactically valid, a semicolon must be after the asterisks and before the backticks, so long as * is in the config string, in order for it to not print.

\$\endgroup\$
4
  • \$\begingroup\$ Nice, my answer is shorter but I'm not sure it scales well to being fixed for 0/1 as output, so I'm just going to add it here in case it helps you: tio.run/##K0otycxLNPz/… \$\endgroup\$ Mar 2, 2018 at 4:40
  • \$\begingroup\$ @FryAmTheEggman I was looking for a pure regex solution to match character groups of same lengths all in a row, but I couldn't figure it out. \$\endgroup\$
    – mbomb007
    Mar 2, 2018 at 14:26
  • \$\begingroup\$ @FryAmTheEggman Made a big improvement! I didn't really use what you had, but I started from scratch trying to think of a better method. \$\endgroup\$
    – mbomb007
    Mar 2, 2018 at 15:30
  • \$\begingroup\$ Nicely done! And I hadn't thought enough about my program it seems, but at least you found a better one :) \$\endgroup\$ Mar 2, 2018 at 19:18
1
\$\begingroup\$

CoffeeScript 1, 96 93 90 bytes

(q,a=q.split(h).length-1for h in[q][0])->a.every (w,s,pplitnggffoorsvvyy)->w>1&&a[0&10]==w

Try it online!

Started from my ES6 answer but walked back to using Array.every. 32 31 30 tokens @ 3 each

\$\endgroup\$
1
\$\begingroup\$

Whispers v2, 1750* 1305 bytes

> 1
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
>> 6>1
>> 12⋅13
>> Output 14














           ###########################00000000000000000000000000001111111111111111111112222222222222222222222222333333333333333333333333334444444444444444444444444445555555555555555555555555555666666666666666666666666666777777777777777777777777777788888888888888888888888888889999999999999999999999999999============================AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEEEEEEEEEEEEEEEEEEEEEEEEEEEIIIIIIIIIIIIIIIIIIIIIIIIIIIILLLLLLLLLLLLLLLLLLLLLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOOOOOOaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccccccccchhhhhhhhhhhhhhhhhhhhhhhhhhhhlllllllllllllllllllllllllllnnnnnnnnnnnnnnnnnnnnnnnnnnnnpppppppppppppppppppppppppppttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuu÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷ᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺ∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋

Try it online!

* Golfs made while explaining it. You can see the original here

Interesting task, fairly boring restriction.

Unfortunately, due to the fact that every line must start with either >> or >, this forces the number of each character to be disproportionately large. Luckily, Whispers ignores every line that doesn't match one of its regexes, all of which require the line to begin with >. Therefore we just have a large character dump at the end of the program. In addition to this, Whispers, being designed for mathematical operations, struggles when applied to a question. Overall, this means that the task is interesting to attempt, but the source code requirements are a bit boring.

If we strip all the unnecessary characters from the program, we end up with

> 1
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
>> 6>1
>> 12⋅13
>> Output 14

Try it online!

which is the part of the code we're actually interested in.

How that works

Here we conduct two key tests: the count of each is the same and the counts are greater than 1. However, the code for these two tests are shared between them, so a complete walkthrough of the program is a more effective method of explaining this.

We start with the shared code:

> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5

Here, we take the input and store it on line 2 (> InputAll). We then create a nique version of that string (i.e. the input without duplicate characters). With our next two lines, we take the length of the untouched input (>> #2) and the number of unique characters in the input (>> #3). Finally, we divide the former by the latter.

Why? Let's have a look at the two inputs of aabbcc and abbaabb. With the first string, the division becomes 6÷3 = 2, and the second results in 7÷2 = 3.5. For non-discriminating strings, the result of this division is a) An integer and b) Greater than 1. Unfortunately, this also applies to some non-discriminating strings, such as abbccc, so we have to perform one more test.

>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11

Note: line 6 is the result of the division.

First, we take the floor of the division, because Python strings cannot be repeated a float number of times. Then we reach our Each statement:

>> L⋅7
>> Each 8 3

3 is a reference to line 3, which contains our deduplicated input characters, so we map line 8 (>> L⋅7) over this list. Line 8 multiplies the character being iterated over by the floor of our division (>> ⌊6⌋). This creates an array of the deduplicated characters, repeated n times.

The results from our two previous strings, aabbcc and abbaabb, along with abcabc, would be aabbcc, aaabbb and aabbcc respectively. We can see that the first and last two are identical to their inputs, just with the letters shuffled around, whereas the middle one isn't (it has one less b). Therefore, we simply sort both the input and this new string, before comparing for equality:

>> 9ᴺ
>> 2ᴺ
>> 10=11

Finally, we need to check that the number of characters in the string is 2 or greater. Luckily, the division we performed earlier will always result in a value greater than 1 if a character repeats more than once, meaning we just need to assert that line 6 is greater than 1:

>> 6>1

Now we have two booleans, one for each test. They both need to be true, so we perform a logical AND (boolean multiplication) with >> 12⋅13, before finally outputting the final result.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 30 bytes

  "&8<MQSlqr{"&q1lJ{hMrSz8<1hJ

Leading spaces necessary.

Try it online!

The actual program is just &q1lJ{hMrSz8<1hJ. I just prepended the string "&8<MQSlqr{" to make it non-discriminating. But to make the string not print itself, I had to add a space, so I added 2 spaces.

&q1lJ{hMrSz8<1hJ

 q1l                (1 == len(
    J{                  J = deduplicate(
      hM                  map(lambda a: a[0],
        r  8                length_encode(
         Sz                   sorted(input())
                            )
                          )
                        )
                    )
&                     and
            <1hJ    (1 < J[0])

length_encode here (r <any> 8) takes a sequence and outputs the length of each run of the same character, ex. "aaabbcc" becomes [[3, "a"], [2, "b"], [2, "c"]].

So this takes the input, sorts it to put in length encode, and takes the first element of each list in the resulting list (e.g. the earlier example would become [3, 2, 2]). This gives a count of how many times characters occur. Then it's deduplicated (the earlier example would become [3, 2]), and J is set to that.

Then it checks if the length is 1, i.e. there is only 1 unique number of times a character occurs, and if that is > 1, i.e. >= 2.

There might be a built-in to replace rSz8 or hMrSz8 but I can't find one.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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