Skip to main content
3 of 7
added 257 characters in body
edc65
  • 32.2k
  • 3
  • 36
  • 90

#JavaScript (ES6), 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)

Assuming lowercase input

a=>[...a].some(z=>c(a+=z)>b,c=a=>(k={},a.replace(/[cowbel]/g,x=>k[x]=-~k[x]),k.l>>=1,Math.min(...Object.values(k))),b=c(a))&&a

Less golfed

a=>{
  c=a=>( // cowbell functions - count cowbells
    k={},
    a.replace(/[cowbel]/g, x => k[x] = -~k[x]),
    k.l >>= 1,
    Math.min(...Object.values(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=>(k={},a.replace(/[cowbel]/g,x=>k[x]=-~k[x]),k.l>>=1,Math.min(...Object.values(k))),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)))

edc65
  • 32.2k
  • 3
  • 36
  • 90