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

#JavaScript (ES6), 141

A porting to javascript of the Pip answer by @DLosc. I needed some time to fully understand it, and it's genius.

Assuming lowercase input

a=>{c=a=>(k={},a.replace(/[cowbel]/g,x=>k[x]=-~k[x]),k.l>>=1,Math.min(...Object.values(k)));for(b=a,i=0;z=a[i++];)if(c(b+=z)>c(a))return b}

Less golfed

a=>{
  c=a=>(
    k={},
    a.replace(/[cowbel]/g, x => k[x] = -~k[x]),
    k.l >>= 1,
    Math.min(...Object.values(k))
  );
  for(b = a, i = 0; z = a[i++];)
    if (c(b += z) > c(a))
      return b
}

Test

f=a=>{c=a=>(k={},a.replace(/[cowbel]/g,x=>k[x]=-~k[x]),k.l>>=1,Math.min(...Object.values(k)));for(b=a,i=0;z=a[i++];)if(c(b+=z)>c(a))return b}

;["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