Longest run of a character in a string
05AB1E, 5 bytes
Code:
SQγOM
Uses the 05AB1E encoding. Try it online!
Explanation:
SQ # Check for each character if it is equal to the second input
γ # Split the list of zeros and ones into groups
O # Sum each array in the arrays
M # Get the maximum
Mathematica, 35 bytes
Max[Tr/@Split@Boole@Thread[#==#2]]&
Pure function taking a list of characters and another character as input and returning a nonnegative integer. Improved upon my first effort using Adnan's observation (go upvote!) that one should test for equaling the special character before splitting the array.
Thread[#==#2]
checks whether each input character in the first argument equals the character given as the second argument. Boole
converts the resulting True
s and False
s to 1
s and 0
s. Split
splits the list into runs of consecutive elements; Tr/@
sums each sublist, and Max
finds the winner. (Because of how Max
works, if the first argument is the empty list, then this function returns -∞
. So, you know, don't do that.)
first submission (51 bytes)
Max[Split@#/.a:{c_String..}:>Boole[c==#2]Length@a]&
Split@#
splits the input into runs of consecutive characters, such as {{"t"}, {"h"}, {"r"}, {"e", "e"}, {" ", " ", " "}, {"s"}, {"p"}, {"a"}, {"c"}, {"e"}, {"s"}}
for the fourth test case. /.a:{c_String..}:>
replaces each subexpression a
that is a list of a repeated character c
by Length@a
multiplied by Boole[c==#2]
, which is 1
if c
equals the input character and 0
otherwise. Then Max
extracts the answer.
Japt, 20 18 15 bytes
fV+Vî+)ª0)n o l
Try it online!
Saved 5 bytes thanks to obarakon and ETHproductions