36
\$\begingroup\$

The Task

Your task is to create a program or a function that, given an input, outputs the input text with random letters capitalized, while keeping already capitalized letters capitalized.

Every combination of capitalizations of the lowercase letters should be possible. For example, if the input was abc, there should be a non-zero probability of outputting any of the following combinations: abc, Abc, aBc, abC, ABc, AbC, aBC or ABC.

Input

Your input is a string, containing any number of printable ASCII characters, for example Hello World. The outputs for that input include HeLLo WoRlD, HElLO WOrld, etc.

Scoring

This is code-golf, so the shortest answer in each language wins!

\$\endgroup\$

58 Answers 58

1
\$\begingroup\$

Pyth, 5 bytes

sOVr1

Try it here!

A translation of totallyhuman's Jelly answer.

Explanation:

sOVr1QQ  Implicit inputs.
   r1Q   Upper(input)
  V   Q  Zip with itself and map...
 O       Random choices between r1Q and Q.
s        Sum the results back into a string.
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 28 bytes

{S:g/.<?{rand>.5}>/{$/.uc}/}

Try it online!

S:g/./{$/.uc}/ itself would convert every individual character to uppercase. Including the regex assertion <?{rand > .5}> assures that the replacement happens only half of the time.

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog), 16 bytes

Tacit prefix function. Rquires ⎕IO (Index Origin) to be 0, which is default on many systems.

{?2:⍵⋄1(819⌶)⍵}¨

Try it online!

{ apply the following function on each character:

?2: if random 0 or 1:

   return the argument unmodified

 else:

  1()⍵ apply the following function with 1 and the argument as arguments:

   819⌶ case-fold (left argument 1 means uppercase)

\$\endgroup\$
1
\$\begingroup\$

Kotlin, 54 bytes

{it.map{if(Math.random()<.5)it else it.toUpperCase()}}

Try it online!

The type of this function is (List<Char>) -> List<Char>.

\$\endgroup\$
1
\$\begingroup\$

Octave, 44 bytes

@(x)['',x-32*(x<123&x>96&rand(size(x))>.5)];

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor, 70 bytes

Oh, Factor, so awesomely verbose...

USING: sequences ascii random ; [ dup ch>upper 2array random ] map

It's a quotation (lambdas did count as functions, right?), takes a string in the stack, call (or call( a -- b ) does its thing. Its thing is leaving a new string on the stack, with random capitalization.

"Capitalize on my Capitals in the Capital" swap call .
 -> "CaPItALIZe oN mY CAPitaLs iN The CAPiTAl"
"Capitalize on my Capitals in the Capital" swap call .
 ->"CaPItAliZe ON mY CApItAls in ThE CapiTal"
...

As a word with comments (because why not!):

USING: sequences ascii random ; ! import the relevant vocabs (factor does it for you in the
                                ! listener, but the rules)
: random-case ( s -- s' )   ! declaration: string -> string'
   [ dup                    ! make a quotation to:
     ch>upper               !  dup a character and make the dup upper
     2array                 !  put them in an array
     random ]               !  and picks one at random
   map ;                    ! now use that to do the thing

"The confusing case of mixed cases in a case!" random-case
 -> "The coNFUsinG case OF Mixed caSes In A CASE!"
\$\endgroup\$
1
\$\begingroup\$

Python 3, 92 bytes

lambda x:''.join([i.upper() if getrandbits(1) else i for i in list(x)])
from random import*

I tried it out using list comprehension and getrandbits for a random sort. I'm not sure if there is a shorter way to get a random boolean, but I'd love to know because getrandbits looks ugly to me and with the import takes up a lot of bytes.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Hi there and welcome to PPCG! I've added a language flag to the body of your response (to add keyword highlighting), but there are a few things that you should consider adding yourself such as a TIO Link and a description of how your code works. \$\endgroup\$ – Taylor Scott Dec 5 '17 at 4:36
  • 1
    \$\begingroup\$ @taylor Thanks! I'm a longtime lurker but its my first time submitting. \$\endgroup\$ – James Heyes Dec 5 '17 at 7:22
1
\$\begingroup\$

Taxi, 1183 1151 bytes

0 is waiting at Starchild Numerology.2 is waiting at Starchild Numerology.Go to Starchild Numerology: w 1 l 2 r, 1 l, 1 l, 2nd l.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill: w 1 r 2 r 1 l 1 r.Go to Post Office: e 1 r.Pickup a passenger going to Chop Suey.[l]Go to Firemouth Grill: n 1 l.Pickup a passenger going to Cyclone.Go to Cyclone: w 1 l 1 r 2 r.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to The Underground.Go to Zoom Zoom: n.Go to Firemouth Grill: w 3 l 2 l, 1 r.Go to The Underground: e 1 l.Switch to plan "k" if no one is waiting.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge: n 3 l.Go to Chop Suey: e 2 r.Pickup a passenger going to Auctioneer School.Go to Auctioneer School: s 1 r 1 l 3 r 1 l 1 l.Pickup a passenger going to Post Office."\0" is waiting at Writer's Depot.Go to Writer's Depot: n 1 l 1 r.Pickup a passenger going to Chop Suey.Go to Post Office: n 1 r 2 r 1 l.Switch to plan "l".[k]Go to Chop Suey: n, 2 r 1 l.Pickup a passenger going to Post Office.Go to Post Office: south, 1 r 1 l 2 r 1 l.Switch to plan "l".

Errors at end of input.

Try it online!

Ungolfed:

0 is waiting at Starchild Numerology.
2 is waiting at Starchild Numerology.
Go to Starchild Numerology: west, 1st left, 2nd right, 1st left, 1st left, 2nd left.
Pickup a passenger going to Firemouth Grill.
Pickup another passenger going to Firemouth Grill.
Go to Firemouth Grill: west, 1st right, 2nd right, 1st left, 1st right.
Go to Post Office: east, 1st right.
Pickup a passenger going to Chop Suey.
[loop]
Go to Firemouth Grill: north, 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: west, 1st left, 1st right, 2nd right.
Pickup a passenger going to Firemouth Grill.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north.
Go to Firemouth Grill: west, 3rd left, 2nd left, 1st right.
Go to The Underground: east, 1st left.
Switch to plan "don't capitalize" if no one is waiting.
Pickup a passenger going to Riverview Bridge.
Go to Riverview Bridge: north, 3rd left.
Go to Chop Suey: east, 2nd right.
Pickup a passenger going to Auctioneer School.
Go to Auctioneer School: south, 1st right, 1st left, 3rd right, 1st left, 1st left.
Pickup a passenger going to Post Office.
"\0" is waiting at Writer's Depot.
Go to Writer's Depot: north, 1st left, 1st right.
Pickup a passenger going to Chop Suey.
Go to Post Office: north, 1st right, 2nd right, 1st left.
Switch to plan "loop".
[don't capitalize]
Go to Chop Suey: north, 2nd right, 1st left.
Pickup a passenger going to Post Office.
Go to Post Office: south, 1st right, 1st left, 2nd right, 1st left.
Switch to plan "loop".

Tricky things:

  1. Although one cannot declare an empty string waiting, one can declare a null byte waiting, and that gets turned into an empty string, where it gets harmlessly dropped off at Chop Suey.
  2. The whole hack is needed anyway to avoid running out of gas, because Auctioneer School is SO FAR AWAY from the rest of Townsburg.
\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Unicode), 28 bytes

28 bytes (https://github.com/abrudz/SBCS/)
50 bytes (UTF-8)

{1(819⌶)@(?n⍴⍨?n←≢⍸~⍵∊⎕A)⊢⍵}

Inspired by Graham's APL+Win solution

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Japt -m, 5 4 bytes

+u)ö

Try it

\$\endgroup\$
1
\$\begingroup\$

Poetic - 735 bytes

alphabet:a-z
words i say,i spell
i say a letter of ABCs
i do know A,i sorta do
then it begins to turn fuzzy or vague-it was never clear
is the after-A letter B
the thing after B?gosh,i am stupid
i say C
D after C?yes,i nailed it
i keep a tally
if i try,i am great
i say a letter,all in order of a song
i heard it,how a letter is in there:A,B,then C
vowels are not a worry for me
vowels are easy
i wrote a huge E in upper-case,and a letter F
i failed with consonant G
still,i say,i penned a big H,I,and J
after J came K,or maybe L
i almost am half completed with everything
just need this difficult novel to read
o sorry,i am stupid,it is truly quite long
M is after L
N,then O
after O is harder letters
letters which really confused me

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

The point of the language is to allow for programs to be written in free-verse poetry. I made this poem about being confused about the alphabet, because it sounds funny.

There is a command that generates a random byte from 0 to 255, but the hard part was calculating that byte mod 2, and capitalizing or not capitalizing based on the result. This is a slow way of doing it, and it takes a while to run in the online interpreter.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 59 bytes

i=input()
while i:print(end={i,i.upper()}.pop()[0]);i=i[1:]

Try it online!

Uses set.pop() to randomize. Note that this will only be random when used in a full program. Learn more.

The code can be reduced to a 47-byte function, but then it is only randomized once per input per session.

f=lambda i:i and{i,i.upper()}.pop()[0]+f(i[1:])

Try it online!


Or, alternatively, as a reusable function:

Python 3, 70 bytes

from random import*
f=lambda i:i and choice((i,i.upper()))[0]+f(i[1:])

Try it online!

\$\endgroup\$
  • \$\begingroup\$ This doesn't work with mixed case inputs. Additional nitpicking: set.pop() is not necessarily random. It is only guaranteed by the spec to be arbitrary. \$\endgroup\$ – Beefster Oct 18 at 21:38
  • \$\begingroup\$ @Beefster thanks for the feedback! The challenge asks you to keep uppercase characters as they are and to only randomize the lowercase input. That is exactly what my code is doing. Additionally, set.pop() picks an item based on hash value. In Python 3, the hash values for strings are completely randomized for a given session. Since this code qualifies as a full program, it will give a proper random output every time it is run. \$\endgroup\$ – Jitse Oct 19 at 19:00
  • 1
    \$\begingroup\$ @Beefster I did some further research and found that hash randomization for strings was made default in Python 3.3. You may want to check out this answer on Stackoverflow. \$\endgroup\$ – Jitse Oct 20 at 11:52
1
\$\begingroup\$

Python 3, 114 107 bytes

from random import *
for i in input():
	if random()>0.5:
		print(i.upper(),end="")
	else:
		print(i,end="")

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to the site. This answer has a lot of extra whitespace. You might want to play around with python to figure out what whitespace is necessary and what is not. \$\endgroup\$ – Wheat Wizard Oct 18 at 20:57
  • \$\begingroup\$ Also both >1 and <2 are shorter than ==1 and both work just fine. \$\endgroup\$ – Wheat Wizard Oct 18 at 20:59
  • 1
    \$\begingroup\$ Also, you can replace randint(1 2) with random() for - a few bytes. Yes, it has an only one in 2^52 chance of capitalizing, but that does not matter because the challenge only requires that "Every combination of capitalizations of the lowercase letters should be possible" \$\endgroup\$ – pppery Oct 18 at 21:12
0
\$\begingroup\$

SOGL V0.12, 6 bytes

{1ψ⌡Up

Try it Here! - the rest of the code there is the name of the function and calling of the function, as this expects the input on the stack.

Explanation:

{       for each character
 1ψ       push a random number from 0 to 1
   ⌡      that many times
    U       uppercase the letter
     p    print that character
\$\endgroup\$
0
\$\begingroup\$

Pip, 12 bytes

{RR2?aUCa}Mq

Takes input from stdin. Try it online!

Explanation

           q  Read a line of stdin
{        }M   Map this function to its characters:
 RR2           Randrange(2), i.e. 0 or 1 with 50% chance each
    ?a         If truthy, the character as-is
      UCa      If falsey, the character upper-cased
              Autoprint the resulting list, by default joined into a string
\$\endgroup\$
0
\$\begingroup\$

Haskell, 112 bytes

Two really expensive imports and one annoying type annotation :(

import Data.Char
import System.Random
mapM(\(b,c)->(c#)<$>randomRIO b).zip(repeat(0::Int,1))
a#1=toUpper a
a#_=a

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Befunge, 2x21 = 42 Bytes

~:1+!v >-# " "$#?+#_,
    @_::"`"`\"{"\`*^

Try It Online

How it works:

~:1+!v 
    @_

Gets input and ends program if empty.

      ::"`"`\"{"\`*^

Duplicates the input and checks whether it is in-between "`" and "{", i.e the lowercase letter range

       >-# " "$#?+#_,

Randomly chooses between subtracting a " " to make it uppercase, or just printing the character as is before returning to the start

\$\endgroup\$
0
\$\begingroup\$

Scala, 44 bytes

s.map(c=>if(math.random<.5)c.toUpper else c)
\$\endgroup\$
0
\$\begingroup\$

Cubix, 54 bytes

;'aW..@;.'zi?>o....;.;?-/..>;.>D<.\;>^u?-/.W;-;/S.;..u

Try it online!

Watch the interpreter in action!

The cost of checking whether a character is a lowercase letter or not in Cubix is quite high, but I'm happy I finally got to use D in a program!

For each lowercase letter in the input, there is a 50% chance that it will be uppercased, and a 50% chance it will be left alone.

Expands to the following cube:

      ; ' a
      W . .
      @ ; .
' z i ? > o . . . . ; .
; ? - / . . > ; . > D <
. \ ; > ^ u ? - / . W ;
      - ; /
      S . ;
      . . u

And a brief explanation of code flow is as follows:

'z               : push ascii z (122)
i                : read in input as code point, or -1 if end of input
?                : turn left if negative, turn right otherwise
 negative:
  @              : end program
/-               : reflect and subtract, result is negative if input is after z, positive if less, zero otherwise
?                : left if negative, right if positive, straight if zero
 negative:
  \;>^.          : pop top of stack and then head to output step
 positive:
  z              : no-op
  W              : jump left
  ;'a            : pop top of stack and push ascii a (97)
  /-             : reflect and subtract. Result is positive if input is between a-z exclusive, negative if before a and zero if a
  ?              : left if negative, right if positive, straight if zero
   negative:
    \;u;^        : stack manipulation and head to output step
   zero:
    u            : u-turn and head to positive branch
   positive:
    >            : point right
    ;            : pop top of stack
    >            : go right
    D            : D points IP in a random direction
    if D goes left or right it hits > or < respectively and re-enters the random phase
    if D goes down:
     W;          : jump left, pop top of stack
     S-          : push 32 (space) and subtract (convert to uppercase)
     >^          : ip directions to enter the output step
    if D goes up:
     ;           : pop top of stack
     '.;         : push . (46) then pop it immediately, then enter the output step
output:
 o.....;.        : output top of stack as char code and then goto beginning of program.
\$\endgroup\$
0
\$\begingroup\$

Julia, 56 bytes

f(s)=join(map(x->(rand(Bool)?uppercase:lowercase)(x),s))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

><>, 37 bytes

i:0(?;::84*\{?$~-o
+){$({"za" /0~x<0}

Try it online!

This program works by randomly selecting either 32 or 0, which will only be subtracted from the value of the letter if is in the range [a-z].

The program mostly linear, but I have 'folded' it to allow reuse of an $ token. Here it is unfolded:

i:0(?;::84*"az"{(${)+}0>x~0{?$~-o
                        $

The x token causes the instruction pointer to move in one of the four cardinal directions, chosen at random. When the IP reaches the x token, the top of the stack has 0 and 32 on it. If the IP moves left, it hits a > which immediately returns the IP to the x. If it moves up or down, it hits the $, which swaps the 0 and 32 around, then returns to the x. If it moves right, it hits the ~, discarding the value on the top of the stack and continuing with program execution.

To save on lots of wasted characters, the program is split, the middle flipped, and a reflector put inbetween:

i:0(?;::84*"az"{(${)+}0>x~0{?$~-o

i:0(?;::84*                {?$~-o
           "az"{(${)+}0>x~0      

i:0(?;::84*                {?$~-o
           +){$({"za"0~x<0}      

i:0(?;::84*\{?$~-o
+){$({"za" /0~x<0}

This puts a $ directly above the x, recreating the program flow as described in the unfolded version.

\$\endgroup\$
0
\$\begingroup\$

Bash, 65

while IFS= read -N1 L;do((RANDOM%2))&&L="${L^}";echo -n "$L";done

Example:

while IFS= read -N1 L;do((RANDOM%2))&&L="${L^}";echo -n "$L";done<<<"Word string with spaces! and symbols if Desired."

> WoRD stRINg WITh SPacEs! AND SymbOlS IF DESiRed.

\$\endgroup\$
0
\$\begingroup\$

AWK, 100 79 73 bytes

BEGIN{FS="";srand()}{for(;i++<=NF;){rand()>.5?$i=toupper($i):i;printf$i}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

APL NARS 81 77 54 characters

{1<⍴⍴⍵:¯1⋄⍬≡0↑⍵:¯1⋄⍵≡'':⍵⋄{26<c←⎕a⍳⍵:⍵⋄1=?2:c⌷⎕A⋄⍵}¨⍵}

This can run only in NARS, because it has defined both alphabet array ⎕A for 'A..Z' and ⎕a for 'a..z'. It is 90% sure I wrote something wrong because it is the 4 or 5th function I write in APL; if you note some error please report. I like this language, a little too much path idiomatic. Comments:

h←{1<⍴⍴⍵:¯1⋄⍬≡0↑⍵:¯1⋄⍵≡'':⍵⋄{26<c←⎕a⍳⍵:⍵⋄1=?2:c⌷⎕A⋄⍵}¨⍵}

h←          assign to name h its function, h return -1 for error
{1<⍴⍴⍵:¯1   if the argument ⍵ of h is  matrix or tensor return -1
 ⍬≡0↑⍵:¯1   if the argument ⍵ of h is a scalar numeric or vector numeric return -1
 ⍵≡'':⍵     if the argument ⍵ of h is the void string '' return it
  {   define one anonimous function in h with argument ⍵
        find in the vector ⎕a=a..z the index char ⍵, assign it to c
   26<c←⎕a⍳⍵:⍵ 
        if that index not exist [in this case must be c=27]return unchanged ⍵
   1=?2:c⌷⎕A
        now index is in 1..26, ⍵ is in a..z; if rand() in 1..2 is 1, return ⎕A[c] where ⎕A is A..Z
   ⋄⍵   else return the argument unchanged 
¨⍵}         for each character argument ⍵ of h, apply anonimous function 
            for build the result string and return it

results

  h
SYNTAX ERROR
  h
  ∧
  h 1
¯1
  h 1.23
¯1
  h 1 2 3
¯1
  h 2 3⍴1 2 3
¯1
  h ''

  h ' '

  h '  '

  h 'Hello World'      
HElLo WOrlD
  h 'Hello World'      
HELlo WoRlD
  h 'Hello World'      
HELlO WoRLD
  h 'Hello World'      
HeLLO WOrld
  h 'Hello World'      
HEllO WORld

these it seems are scalars chars and some vector

  h 'a'
A
  h 'a'
a
  h 'a'
a
  h 'a'
a
  h ,'a'
A
  h ,'a'
A
  h ,'a'
a
  h ,''
\$\endgroup\$
  • \$\begingroup\$ Woah, NARS allows you to do something like 98..123? \$\endgroup\$ – Zacharý Dec 1 '17 at 15:38
  • \$\begingroup\$ @Zacharý yes it seems one can use range interval \$\endgroup\$ – RosLuP Dec 1 '17 at 16:03
0
\$\begingroup\$

F#, 104 bytes

open System
let r=Random()
let f=Seq.fold(fun a x->a+string(if r.Next 4=0 then Char.ToUpper x else x))""

Try it online!

Pretty straight-forward. Start with an empty string, then keep adding characters to it. Each character has a 1-in-4 chance of being capitalised.

I'm pretty sure I can get it under 100 bytes, but I can't see how...

\$\endgroup\$
0
\$\begingroup\$

Prolog (SWI), 65 bytes

[H|T]-[I|U]:-T-U,(H>97,H<123,random(0,2,1),I is H-32;I=H).
[]-[].

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 112 91 bytes

(defun f(s)(map'string(lambda(c)(if(>(random 2(make-random-state t))0)(char-upcase c)c))s))

Try it online!

:| Lisp's random isn't seeded by default

\$\endgroup\$
0
\$\begingroup\$

Gaia, 6 bytes

⌉,†ṛ¦$

Try it online!

Explanation

⌉       Uppercase the string
 ,†     Vectorize pair the uppercase with the original string (creates pairs of corresponding chars)
   ṛ¦   Randomly choose one character from each pair
     $  Join
        Implicit output
\$\endgroup\$

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.