18
\$\begingroup\$

Challenge

Write a program that, given a string x which is 10 characters long and a character y, outputs the number of times character y occurs in string x.

The shortest program in bytes to do so wins.

Example

Input: tttggloyoi, t
Output: 3

Input: onomatopoe, o
Output: 4
\$\endgroup\$
  • 11
    \$\begingroup\$ This seems almost too easy of a challenge. Also why limit the input to 10, instead of no limit at all? \$\endgroup\$ – Fatalize Sep 2 '15 at 9:37
  • 7
    \$\begingroup\$ Needs a winning condition. \$\endgroup\$ – isaacg Sep 2 '15 at 9:41
  • 2
    \$\begingroup\$ Feel free to rollback my edit if it doesn't agree with you \$\endgroup\$ – Beta Decay Sep 2 '15 at 10:13
  • 8
    \$\begingroup\$ How flexible is the input format? Can we choose a different delimiter, like a space or newline? Can the string be in quotes? Can we take the letter first and the string second? Will the characters always be lower case letters? If not, which other characters can occur? \$\endgroup\$ – Martin Ender Sep 2 '15 at 10:50
  • 5
    \$\begingroup\$ This looks suspiciously like a C interview question... \$\endgroup\$ – Quentin Sep 2 '15 at 20:33

54 Answers 54

1
2
1
\$\begingroup\$

rs, 33 bytes

+(.)(.* (?!\1).)/\2
(.*)../(^^\1)

Live demo and test cases.

This is pretty simple. The first line removes all characters except the ones we're counting. The next line counts the number of characters that are left, excluding the one we're searching for.

Takes input separated by spaces, e.g.:

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

C#, 36 51 48

Debug.Write(args[0].split(args[1][0]).Length-1);
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Well now it will :) - Ofcourse I forgot the cw.. \$\endgroup\$ – Alex Carlsen Sep 2 '15 at 14:22
  • 1
    \$\begingroup\$ You could also use Console.Write instead of Console.WriteLine to save another 4 bytes. \$\endgroup\$ – AdmBorkBork Sep 2 '15 at 14:23
  • \$\begingroup\$ I am such a fool -.- \$\endgroup\$ – Alex Carlsen Sep 2 '15 at 14:23
  • \$\begingroup\$ Doesn't Debug.Write go to STDERR rather than STDOUT? \$\endgroup\$ – Alex A. Sep 3 '15 at 1:51
1
\$\begingroup\$

O, 23 10 bytes

ie\i-e@-_p

Original:

0K;i""/iJ;l{J=K+:K;}dKp

I don't think I can get this any shorter... :/

Ah, I'm stupid. I forgot the traditional method of counting occurrences: subtract the string lengths.

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

STATA, 52 bytes

di _r(a)_r(b)
di 10-length(subinstr("$a","$b","",.))

Gets the two strings as inputs. Replaces all occurrences of the second string (the character) with empty string. Subtract that from 10, since the length of the first string is 10.

Unfortunately functions in STATA can't be shortened the same way that variable names and commands can. Also, this doesn't work in the online interpreter, since it doesn't include these functions.

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

scala, 31 bytes

(x:String,y:Char)=>x.count(y==)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

K, 3 bytes

+/=

K actually beat APL!!! :D Well, now it's a tie... :/

You can call it like this:

+/=["hello";"l"]

Or assign it to a variable first:

f:+/=
f["hello";"l"]

Also note that this does not work in oK. It does work in the official K2 and K5 interpreters, as well as Kona.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The original style of invocation (+/=["hello";"l"]) worked fine in oK. The latter case (f:+/=;f["hello";"l"]) was behaving incorrectly and should be fixed now. \$\endgroup\$ – JohnE Sep 2 '15 at 21:42
  • \$\begingroup\$ @JohnE Uh, yeah. I was going to report that as a bug, but then I ended up entering another code golf challenge. :) \$\endgroup\$ – kirbyfan64sos Sep 2 '15 at 22:33
  • \$\begingroup\$ Nope, K doesn't beat APL this time. See my answer. You could call it a tie, but APL needs less additional chars during actual use. \$\endgroup\$ – Adám Sep 3 '15 at 4:11
1
\$\begingroup\$

Pip, 3 bytes

Joining the 3-byte cavalcade...

bNa

Read as "b in a". a and b are command-line arguments. The N operator, unlike its Python counterpart, doesn't just return a truth value; it returns the count.

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

R, 27 bytes

sum(strsplit(x,"")[[1]]==y)

Usage

sum(strsplit("tttggloyoi","")[[1]]=="t")
[1] 3
sum(strsplit("onomatopoe","")[[1]]=="o")
[1] 4

Or, Another one with 42 bytes

f<-function(x,y)length(gregexpr(y,x)[[1]])

Usage

f("tttggloyoi", "t")
[1] 3
f("onomatopoe", "o")
[1] 4
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Javascript

Program, 48 chars

alert(prompt().match(/(.)(?=.*\1$)|$/g).length-1)

Function with 1 argument (ES6), 39 chars

f=s=>s.match(/(.)(?=.*\1$)|$/g).length-1

Function with 2 arguments (ES6), 28 chars

f=(s,c)=>s.split(c).length-1
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jelly, 1 byte (non-competing)

Non-competing since the question predates the language.

ċ

TryItOnline

The obvious implementation would be 3 bytes: s1ċ, which splits a string or list (left argument) into slices of length 1 with s1 and counts occurrences of the character (right argument) with ċ.

However, since the character will only ever be of length 1, we could, instead, inspect all non-empty contiguous slices of a string with ; the character will only ever match those slices that are of length 1.

...and since a string is an array of characters, the function can just be ċ.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ A string is an array of characters. The problem is that "o" is a string, not a character. As a function, plain ċ is enough. \$\endgroup\$ – Dennis Oct 6 '16 at 16:11
  • \$\begingroup\$ Wasn't sure of the rules on input, so made it a clause-1-byte-solution. Thanks! \$\endgroup\$ – Jonathan Allan Oct 6 '16 at 16:15
  • \$\begingroup\$ Do the command line arguments have to be entered as I have done in the TIO link? \$\endgroup\$ – Jonathan Allan Oct 6 '16 at 16:22
  • 1
    \$\begingroup\$ There's no way of entering characters in the CLAs, since i put uses Python's syntax. You'd have to call the link with “onomatopoe”ç”o or similar. \$\endgroup\$ – Dennis Oct 6 '16 at 16:39
1
\$\begingroup\$

Java 7, 69 68 54 52 bytes

int c(String...a){return a[0].split(a[1]).length-1;}

Surprisingly enough there wasn't a Java answer yet..
14 bytes saved thanks to @Geobits!

If a completely flexible input is allowed, we can save an additional byte by having a String-array parameter (51 bytes):

int c(String[]a){return a[0].split(a[1]).length-1;}

Ungolfed & test code:

Try it here.

class M{
  static int c(String... a){
    return a[0].split(a[1]).length-1;
  }

  public static void main(String[] a){
    System.out.println(c("tttggloyoi", "t"));
    System.out.println(c("onomatopoe", "o"));
  }
}

Output:

3
4
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ To get rid of the regex/replace, split on the character and count the resulting length a.split(b+"").length-1; -14 :D \$\endgroup\$ – Geobits Oct 6 '16 at 15:47
  • \$\begingroup\$ @Geobits Ah nice! Thanks. And here I thought I was smart by changing a.length-a.replace(b,"").length with a.replaceAll("[^"+b+"]","").length() to save a byte. xD \$\endgroup\$ – Kevin Cruijssen Oct 6 '16 at 17:19
  • 1
    \$\begingroup\$ That was my original thought too (and I commented that first, but deleted), except I used the fixed 10 instead of a.length() since the length is fixed in the spec ;) \$\endgroup\$ – Geobits Oct 6 '16 at 17:20
  • 1
    \$\begingroup\$ @Geobits Ah, good point. ;D But this is even better. ;) Also, managed to subtract an additional 2 bytes by changing the String+char parameters to String.... \$\endgroup\$ – Kevin Cruijssen Oct 6 '16 at 17:25
  • \$\begingroup\$ Good call. I always forget about the ... \$\endgroup\$ – Geobits Oct 6 '16 at 17:26
1
\$\begingroup\$

APL (Dyalog Extended), 1 byteSBCS

Try it online!

is Count In

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

05AB1E, 1 byte

¢

First input is the character, second the string.

Try it online or verify both test cases at once.

Explanation:

¢  # Count the amount of occurrences of the first (implicit) input-character
   # in the second (implicit) input-string
   # (after which the result is output implicitly)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Zsh, 15 bytes

<<<${#1//[!$2]}

Try it online!

Similar to the bash answer, but more compact thanks to Zsh allowing both ${ //} and ${# } in the same expansion.

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

Retina, 11 bytes

w`^(.)¶.*\1

Try it online!

Takes input as two lines - the first line is the character, the second is the string.

Could be 10 bytes if taking input as the character preprended to the string, but that felt a bit too cheaty.

Explanation

w`^(.)¶.*\1     # (implicit count stage as there is just one line)
w`              # Include overlapping matches for the pattern
   (.)          # Match a single character...
  ^             # ...at the start of the input...
      ¶         # ... and followed by a newline...
       .*       # ...then zero or more arbitrary characters...
         \1     # ...and then the first character again
                # (implicitly output the number of matches)
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure the ^ is unnecessary. If we can assume the string doesn't contain bad characters (seems like we can), ~`^ [\n] K` works (Try it online!). This might be possible to golf using something similar to that. \$\endgroup\$ – my pronoun is monicareinstate Dec 18 '19 at 14:40
1
\$\begingroup\$

naz, 92 bytes

2x1v2a2x2v8a2x3v1r2x4v1x1f3r3x2v3e3x4v2e1f0x1x2f1v1a2x1v1f0x1x3f1v3x3v4e1o0x1x4f9s1o1s1o0x1f

Works for any valid input string terminated with the control character STX (U+0002), with the character to search for appearing first (e.g. t, tttggloyoi).

Explanation (with 0x commands removed)

2x1v                 # Set variable 1 equal to 0
2a2x2v               # Set variable 2 equal to 2
8a2x3v               # Set variable 3 equal to 10
1r2x4v               # Store the first byte of the input string in variable 4
1x1f                 # Function 1
    3r               # Read the 3rd byte of input, then remove it from the input
                     # This has the effect of skipping over the comma and space
      3x2v3e         # Jump to function 3 if it equals variable 2
            3x4v2e   # Jump to function 2 if it equals variable 4
                  1f # Otherwise, jump back to the start of the function
1x2f                 # Function 2
    1v1a2x1v1f       # Load variable 1 into the register, add 1,
                     # and store the new value in variable 1
                     # Then, jump to function 1
1x3f                 # Function 3
    1v3x3v4e1o       # Load variable 1 into the register
                     # Jump to function 4 if the register equals variable 3
                     # Otherwise, output once
1x4f                 # Function 4
    9s1o1s1o         # Subtract 9 and output, then subtract 1 and output
                     # (outputs "10")
1f                   # Call function 1
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 4 bytes

peCN

Try it online!

Takes input as "string" 'i to search string for i.

If special inputs are not allowed:

Burlesque, 6 bytes

pe-]CN

Try it online!

Takes input as two quoted strings.

pe  # Parse and evaluate
CN  # Count
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

I have been outgolfed.

PowerShell, 75 Bytes (Single Run)

nv a (read-host).split(", ");foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|oh

The above will only work once, will error if variables still have values from last run(run twice in same environment).

PowerShell, 82 Bytes (Infinite Use)

$c=0;nv a (read-host).split(", ")-f;foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|oh

The above can be used any number of times in the same environment.

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

C, 55 bytes

t;c(char* i,char z){t=0;for(;*i;)t+=*i++==z;return t;}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Jelly, 2 bytes, non-competing

There is a one-byte Jelly solution, but that takes in the argument in a rather particular way. With 1 byte extra, we can just input test instead of ["t", ...]

fL

Try it online!

f   filter all elements from the first implicit input that are not in the second implicit input
    "onomatopoe" f "o" filters out all non-"o" chars --> oooo
 L  Get the length of the remainder.
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Wren, 29 bytes

Very hard to golf.

Fn.new{|a,b|a.count{|i|i==b}}

Try it online!

Explanation

Fn.new{|a,b|                  // Anonymous function with parameters a & b
            a.count           // Count every item
                   {|i|       // that...
                       i==b}} // is equal to b

Wren, 36 bytes

Fn.new{|a,b|a.trim(a.trim(b)).count}

Try it online!

Explanation

Fn.new{|a,b|                       } // Uninteresting anonymous function
                   a.trim(b)         // Remove all occurences of b in a
            a.trim(         )        // Trim this result with a, keeping the removed occurences
                             .count  // Find the length of this result
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

W, 4 bytes

Basically the same algorithm as my second Wren answer.

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

Ahead, 16 bytes

The first character on stdin is the counted character, and the remainder of stdin is the string.

i&>jlir
 @Or+=t<

Try it online!

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

Fortran (GFortran), 60 bytes

character a(10),b
read('(10a,a)'),a,b
print*,count(a==b)
end

Try it online!

Takes input as an 11 length string, the last char being b.

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

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.