#JavaScript (ES6), 106 107 113 126 141
A porting to javascript of the Pip answer by @DLosc. I needed some time to fully understand it, and it's genius.
Edit -15 bytes following the hint by @Titus, directly appending chars to the input string a
and avoiding early return (so no for/if
)
Edit 2 enumerating the 6 value for the Min function saves other 13 bytes
Edit 3 changed c function again. I thought the verbose length
and split
would be too lengthy. I was wrong.
Assuming lowercase input
a=>[...a].some(z=>c(a+=z)>b,c=a=>Math.min(...[...'lcowbe'].map((c,i)=>~-a.split(c).length>>!i)),b=c(a))&&a
Less golfed
a=>{
c=a=>{ // cowbell functions - count cowbells
k = [... 'lcowbe'].map((c,i) =>
(a.split(c).length - 1) // count occurrences of c in a
/ (!i + 1) // divide by 2 if first in list ('l')
);
return Math.min(...k);
};
b = c(a); // starting number of cowbells
[...a].some(z => ( // iterate for all chars of a until true
a += z,
c(a) > b // exit when I have more cowbells
));
return a;
}
Test
f=
a=>[...a].some(z=>c(a+=z)>b,c=a=>Math.min(...[...'lcowbe'].map((c,i)=>~-a.split(c).length>>!i)),b=c(a))&&a
;["christopher walken begs for more cowbell!"
,"the quick brown fox jumps over the lazy dog"
,"cowbell"
,"cowbell cowbell cowbell"
,"cowbell cowbell cowbel"
,"bcelow"
,"abcdefghijklmnopqrstuvwxyz"
,"cccowwwwbbeeeeelllll"
,"be well, programming puzzles & code golf"
,"lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!"
,`c-c-b-c
i have a cow, i have a bell.
uh! bell-cow!
i have a cow, i have a cowbell.
uh! cowbell-cow!
bell-cow, cowbell-cow.
uh! cow-cowbell-bell-cow.
cow-cowbell-bell-cow!
`].forEach(x=>console.log(x+'\n\n'+f(x)))