Random Capitalization

36

2

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!

Brecert

Posted 2017-11-29T19:10:55.007

Reputation: 387

Answers

14

TI-Basic (83 series), 137 bytes

For(I,1,length(Ans
Ans+sub(sub(Ans,I,1)+"ABCDEFGHIJKLMNOPQRSTUVWXYZ",1+int(2rand)inString("abcdefghijklmnopqrstuvwxyz",sub(Ans,I,1)),1
End
sub(Ans,I,I-1

Takes input in Ans, as illustrated in the screenshot below:

enter image description here

(If the screenshot looks scrambled, as it sometimes does for me, try opening it in a new tab?)

TI-Basic (at least the TI-83 version... maybe I should branch out into TI-89 golfing) is a terrible language to try to golf this challenge in, since:

  1. It provides absolutely no support for any arithmetic with characters, knowing the uppercase version of a lowercase character, or even knowing the alphabet.
  2. Every single lowercase character takes 2 bytes to store. (In fact, I had to use an assembly script just to be able to type the lowercase letters.)

The result is that 78 bytes of this program (more than half) are just storing the alphabet, twice.

Anyway, the idea is that we loop through the string, with a chance of turning lowercase characters into uppercase ones as we go, and adding the result onto the end of the string so that both the input and the output are stored in Ans. When we leave the For( loop, I is one more than the length of the original string, so taking the I-1 characters starting at I gives the output.

Misha Lavrov

Posted 2017-11-29T19:10:55.007

Reputation: 4 846

The apps "MirageOS" and "OmniCalc" both allow you to type lowercase letters just by pressing alpha twice. And they also have other nice features. – Fabian Röling – 2017-12-01T07:45:59.533

@Fabian The assembly script, and the apps you mentioned, both work essentially the same way: they set a flag in the operating system that enables "press alpha twice for lowercase". – Misha Lavrov – 2017-12-01T07:51:48.060

11

Python 2, 66 65 bytes

lambda s:`map(choice,zip(s.upper(),s))`[2::5]
from random import*

Try it online!

notjagan

Posted 2017-11-29T19:10:55.007

Reputation: 4 011

11

Japt, 6 bytes

®m`«`ö

Test it online!

Explanation

®m`«`ö   Implicit input
®        Map each char in the input by
 m         mapping each char in this char through
  `«`ö       a random character of "us". (`«` is "us" compressed)
             The u function converts to uppercase, and s is slice, which does nothing here.
         Implicit output

ETHproductions

Posted 2017-11-29T19:10:55.007

Reputation: 47 880

10

C,  47  46 bytes

Thanks to @l4m2 for saving a byte!

f(char*s){for(;*s++-=(*s-97u<26&rand())*32;);}

Try it online!

Would be 42 bytes, if it could be assumed that {|}~ don't appear in the input:

f(char*s){for(;*s++-=(*s>96&rand())*32;);}

Try it online!

Steadybox

Posted 2017-11-29T19:10:55.007

Reputation: 15 798

Worth noting that, given a particular implementation, the capitalization is perfectly deterministic (the C standard provides an implicit srand(1) at the start of the program, so in each execution the sequence of values returned by rand() will be the same). – Matteo Italia – 2017-11-30T11:39:21.433

f(char*s){for(;*s++-=(*s-'a'<26&rand())*32;);} for some compiler (def. -funsigned-char) work – l4m2 – 2018-05-27T16:58:04.530

@l4m2 Thanks! That doesn't work though for some reason. Changing 'a' to 97u works and doesn't even require the -funsigned-char flag. – Steadybox – 2018-05-28T02:29:51.923

It seems that when you subtract 'a' (which is signed int, not unsigned char) from *s (which is unsigned char), *s gets promoted to signed int instead of unsigned int, hence negative values being possible and the comparison not working as intended. – Steadybox – 2018-05-28T02:44:39.497

8

Jelly, 5 bytes

Another one bytes the dust thanks to dylnan.

żŒuX€

Try it online!

Explanation

żŒuX€  main link: s = "Hello world"

żŒu    zip s with s uppercased  ["HH", "eE", "lL", "lL", "oO", "  ", ...]
   X€  map random choice        "HeLLo woRlD"

totallyhuman

Posted 2017-11-29T19:10:55.007

Reputation: 15 378

1I need to use ŒṘ more often to see how things are represented under the hood – dylnan – 2017-11-29T21:55:26.000

7

Perl 5, 23 bytes

22 bytes code + 1 for -p.

s/./rand>.5?uc$&:$&/ge

Try it online!

Dom Hastings

Posted 2017-11-29T19:10:55.007

Reputation: 16 415

7

JavaScript (ES6), 56 bytes

s=>s.replace(/./g,x=>Math.random()<.5?x.toUpperCase():x)

If uniform randomness is not required, we can save 6 bytes by using the current time as the source of randomness:

s=>s.replace(/./g,x=>new Date&1?x.toUpperCase():x)

This tends to either uppercase or leave alone all letters at once.

ETHproductions

Posted 2017-11-29T19:10:55.007

Reputation: 47 880

"there should be a non-zero probability of outputting any of the following combinations: abc, Abc, aBc, abC, ABc, AbC, aBC or ABC", while yours can't output AbC because the time won't change so fast – l4m2 – 2018-05-27T16:52:34.887

@l4m2 if you have a really slow machine, it might ;-) Maybe I should just remove that part though... – ETHproductions – 2018-05-28T03:09:19.393

6

Charcoal, 8 7 bytes

⭆S‽⁺↥ιι

Try it online! Link is to verbose version of code. Explanation:

 S          Input string
      ι     Character
    ↥ι      Uppercase character
   ⁺        Concatenate
  ‽         Random element
⭆           Map over each character and join the result
            Implicitly print

Neil

Posted 2017-11-29T19:10:55.007

Reputation: 95 035

6

Excel VBA, 74 71 64 Bytes

The Randomize call always makes random output costly in VBA :(

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window. Produces a 50% (on average) UCased output.

For i=1To[Len(A1)]:a=Mid([A1],i,1):?IIf(Rnd>.5,a,UCase(a));:Next

Taylor Scott

Posted 2017-11-29T19:10:55.007

Reputation: 6 709

Hello Sir. you can save 2 bytes by removing Randomize: and changing Rnd with [RAND()>.5] . Or just ignore it. :) – remoel – 2017-12-01T09:52:29.930

@remoel, unfortunately, the [Rand()] call is only psuedo-random and has a period length of roughly 10^13, making it functionally identical to the un Randomized Rnd call, in fact the two use the same seed (which the Randomize call sets by using the timer function output).

– Taylor Scott – 2017-12-01T16:20:46.500

@romoel, I do however suppose that given the clarifications on the prompt that I could remove the Randomize call and instead use Rnd>.5 – Taylor Scott – 2017-12-01T16:25:59.633

6

R, 66 bytes

for(i in el(strsplit(scan(,""),"")))cat(sample(c(i,toupper(i)),1))

Try it online!

Another R answer.

djhurio

Posted 2017-11-29T19:10:55.007

Reputation: 1 113

I've been writing too much "regular" R code and didn't even think to try a for-loop! Nice one. – Giuseppe – 2017-11-29T22:36:06.453

4

Ruby, 40 Bytes

Lambda function that takes a string. Saved 1 byte thanks to Arnauld. Saved 5 bytes thanks to Snack.

->s{s.gsub(/./){|x|[x,x.upcase].sample}}

displayname

Posted 2017-11-29T19:10:55.007

Reputation: 151

1Welcome to PPCG! Could you save a byte with <1 instead of ==1? – Arnauld – 2017-11-29T21:57:10.213

140 bytes – Snack – 2017-11-29T22:47:36.000

Nice work @displayname. FWIW when users improve their score, many like to "cross out" the old score with the <s> tag, e.g. "Ruby, <s>46</s> 40 bytes." Of course it's not required. – Jordan – 2017-11-30T15:48:21.360

3

R, 89 88 bytes

outgolfed by djhurio!

cat(sapply(el(strsplit(scan(,""),"")),function(x)"if"(rt(1,1)<0,toupper,`(`)(x)),sep="")

Try it online!

This program takes each character, and with probability 1/2 converts it to uppercase or leaves it alone. It's possible to tweak this probability by playing with different values of df and 0.

rt draws from the Student's t-distribution, which has median 0 with any degree of freedom (I selected 1 since it's the smallest number possible).

Giuseppe

Posted 2017-11-29T19:10:55.007

Reputation: 21 077

1That's a very R way of doing something at random. – Misha Lavrov – 2017-11-29T21:51:06.670

1

66 bytes https://codegolf.stackexchange.com/a/149518/13849

– djhurio – 2017-11-29T22:28:35.943

@djhurio that's brilliant. – Giuseppe – 2017-11-29T22:31:35.673

3

APL+WIN, 37 bytes

⎕av[c-((n÷2)<n?n←⍴s)×32×s←98<c←⎕av⍳⎕]

Prompts for screen input, identifies lower case letters and randomly converts them to upper case.

Graham

Posted 2017-11-29T19:10:55.007

Reputation: 3 184

3

Java 8, 46 bytes

This lambda is from IntStream to IntStream (streams of code points).

s->s.map(c->c>96&c<'{'&Math.random()>0?c-32:c)

Try It Online

Capitalization distribution

Whether to capitalize a letter used to be the quite sensible condition that Math.random()<.5, which was satisfied about half the time. With the current condition of Math.random()>0 (which saves a byte), capitalization occurs virtually every time, which makes a test program kind of pointless. But it does satisfy the randomness requirement.

Acknowledgments

  • -1 byte thanks to Olivier Grégoire

Jakob

Posted 2017-11-29T19:10:55.007

Reputation: 2 428

If you go the stream route, you can use code points and do 41 bytes.

– Olivier Grégoire – 2017-11-30T08:49:54.190

Well, that breaks if the input contains ASCII characters above z. I could throw it in with a qualification though. – Jakob – 2017-11-30T16:04:06.967

1Fix for 6 more bytes. – Olivier Grégoire – 2017-11-30T16:08:39.813

3

05AB1E, 6 5 bytes

Thank you Adnan for -1 byte

uø€ΩJ

Try it online!

Explanation

uø€ΩJ   
u      Upper case of top of stack. Stack: ['zzzAA','ZZZAA']
 ø     Zip(a,b). Stack: ['zZ', 'zZ', 'zZ', 'AA', 'AA']
  €    Following operator at each element of it's operand
   Ω   Random choice. Stack: ['z', 'Z', 'z', 'A', 'A']
    J  Join a by ''. Stack: 'zZzAA'
        Implicit output

Method taken from @totallyhuman's answer

dylnan

Posted 2017-11-29T19:10:55.007

Reputation: 4 993

1Will anyone ever beat 6? :P – ETHproductions – 2017-11-29T23:13:24.683

1@ETHproductions If Jelly had a single byte operator for upper case like 05AB1E we would! – dylnan – 2017-11-29T23:15:04.237

Ooo... New command for random_pick eh? ε„luΩ.V was my attempt, nice one! – Magic Octopus Urn – 2017-11-30T00:55:01.683

3You can leave the duplicate out :) – Adnan – 2017-11-30T09:07:18.257

1Will anyone beat 5? :P – totallyhuman – 2017-11-30T16:26:33.303

3

Swift 4, 86 bytes

s.map{let s="\($0)",u=s.uppercased();return u==s ? u:arc4random()%2==0 ? u:s}.joined()

Au Ris

Posted 2017-11-29T19:10:55.007

Reputation: 131

3Welcome to PPCG! – Martin Ender – 2017-12-01T11:19:02.213

3

Ruby, 39 bytes

->s{s.gsub(/./){[$&,$&.upcase].sample}}

Largely inspired from displayname's answer. (I couldn't comment to suggest this one-byte-less version for lack of reputation, sorry displayname)

Jérémie Bonal

Posted 2017-11-29T19:10:55.007

Reputation: 71

3Welcome to PPCG! – Martin Ender – 2017-12-01T11:19:14.157

I wasn't expecting greetings, how nice! Thank you! – Jérémie Bonal – 2017-12-01T13:39:32.727

3

Funky, 55 bytes

s=>s::gsub("."c=>{0s.upper,s.lower}[math.random(2)](c))

Try it online!

Thanks to optional commas, it's one byte shorter to do 0s.upper in the table definition, which means the math.random will randomly pick either 1 or 2, than to do math.random(0,1) in the random and not have the 0.

ATaco

Posted 2017-11-29T19:10:55.007

Reputation: 7 898

3

R, 60 59 58 57 56 63 bytes

intToUtf8((s=utf8ToInt(scan(,"")))-32*rbinom(s,s%in%97:122,.5))

Try it online!

Different approach from the other two R answers here and here. Improved and fixed thanks to Giuseppe!

JayCe

Posted 2017-11-29T19:10:55.007

Reputation: 2 655

I did not know the sampling functions behaved like that! – Giuseppe – 2018-05-28T18:21:02.850

@Giuseppe Just when I thought this couldn't be golfed down... – JayCe – 2018-05-28T18:27:16.983

57 bytes – Giuseppe – 2018-05-28T18:39:34.570

@Giuseppe Not only is this golfier but also more elegant! Love it! – JayCe – 2018-05-28T18:51:50.697

upon second view, this won't work when printable ascii characters above 90 like [, but this fixes it for +7 bytes which is still golfier than djhurio's answer

– Giuseppe – 2018-06-01T15:31:18.240

2

Alice, 17 15 bytes

Thanks to Leo for saving 2 bytes.

/uRUwk
\i*&o.@/

Try it online!

Explanation

/...
\...@/

This is the usual framework for largely linear programs operating entirely in Ordinal mode.

i    Read all input as a string.
R    Reverse the input.
&w   Fold w over the characters of the string. w is nullary which means it
     doesn't actually use the individual characters. So what this does is that
     a) it just splits the string into individual characters and b) it invokes
     w once for each character in the string. w itself stores the current 
     IP position on the return address stack to begin the main loop which
     will then run N+1 times where N is the length of the string. The one
     additional iteration at the end doesn't matter because it will just
     output an empty string.
.    Duplicate the current character.
u    Convert it to upper case (does nothing for characters that aren't
     lower case letters).
*    Join the original character to the upper case variant.
U    Choose a character at random (uniformly).
o    Print the character.
k    If the return address stack is not empty yet, pop an address from it
     and jump back to the w.
@    Terminate the program.

I first tried doing this entirely in Cardinal mode, but determining if something is a letter just based on character code would probably take more bytes.

Martin Ender

Posted 2017-11-29T19:10:55.007

Reputation: 184 808

2

Pyth, 10 7 6 bytes

smO,r1

Saved 3 bytes thanks to ovs and 1 thanks to Steven H.

Try it online

Explanation

smO,r1
 m      Q   For each character in the (implicit) input...
   ,r1dd    ... get the capitalized version and the (implicit) character, ...
  O         ... and pick one at random.
s           Concatenate the result.

user48543

Posted 2017-11-29T19:10:55.007

Reputation:

r1d=rd1, allowing you to implicit-input golf another byte out. – Steven H. – 2017-11-30T19:44:47.150

2

Wolfram Language (Mathematica), 52 49 44 bytes

StringReplace[c_/;Random[]<.5:>Capitalize@c]

Try it online!

Uses the operator form of StringReplace: providing it a rule (or a list of rules) but no string gives a function which applies that rule to any string you give it as input.

We could do a lot better (RandomChoice@{#,Capitalize@#}&/@#& is 34 bytes) if we decided to take as input (and produce as output) a list of characters, which people sometimes argue is okay in Mathematica because it's the only kind of string there is in other languages. But that's no fun.


-5 bytes thanks to M. Stern

Misha Lavrov

Posted 2017-11-29T19:10:55.007

Reputation: 4 846

Save one byte by using Capitalize – M. Stern – 2017-11-30T18:22:40.743

If you would ignore that Random is deprecated you could save another four bytes by implementing your own RandomChoice: StringReplace[c_/;Random[]<.5:>Capitalize@c], – M. Stern – 2017-11-30T18:48:55.220

@M.Stern I was trying to get Random to work at one point, but I forgot about the /; so I was trying to put into an If statement. Thanks! – Misha Lavrov – 2017-11-30T18:50:27.013

2

Ouroboros, 25 bytes

i.b*)..96>\123<*?2*>32*-o

Try it here

The only fancy part is the control flow, .b*). Let's talk about the rest first.

i..                    Get a character of input, duplicate twice
   96>                 Test if charcode greater than 96
      \                Swap with copy #2
       123<            Test if charcode less than 123
           *           Multiply the two tests (logical AND): test if it is lowercase letter
            ?          Random number between 0 and 1
             2*        Times 2
               >       Is lcase test greater? If test was 1 and rand*2 < 1, then 1, else 0
                32*-   Multiply by 32 and subtract from charcode to ucase lcase letter
                    o  Output as character

We then loop back to the beginning of the line. Control flow involves changing where the end of the line is; if it is moved to the left of the IP, execution terminates. Thus:

 .     Duplicate input charcode
  b*   Push 11 and multiply
    )  Move end of line that many characters to the right

When the charcode is positive, ) is a no-op, since the end of the line is as far right as it can go. But when all characters have been read, i gives -1. Then we move the end of the code -11 characters to the right--that is, 11 characters to the left. It takes a couple iterations, but eventually the IP is past the end of the code and the program halts.

DLosc

Posted 2017-11-29T19:10:55.007

Reputation: 21 213

2

MATL, 12 11 bytes

"@rEk?Xk]v!

Try it online!

Saved 1 byte thanks to @LuisMendo

Cinaski

Posted 2017-11-29T19:10:55.007

Reputation: 1 588

2

Brachylog, 5 bytes

ụᶻṛᵐc

Try it online!

Explanation

Example input: "Test"

ụᶻ        Zip uppercase:      [["T","T"],["e","E"],["s","S"],["t","T"]]
  ṛᵐ      Map random element: ["T","e","S","T"]
    c     Concatenate:        "TeST"

Fatalize

Posted 2017-11-29T19:10:55.007

Reputation: 32 976

2

PowerShell, 57 56 bytes

-join([char[]]"$args"|%{(("$_"|% *per),$_)[(Random)%2]})

Try it online!

-1 byte thanks to briantist

Takes input as a string, explicitly casts the $args array to a string, casts it as a char-array, then feeds the characters through a loop. Each iteration, we 50-50 either output the character as-is $_ or convert it to upper-case "$_".ToUpper() (that's the ("$_"|% *per) garbage). That's chosen by getting a Random integer and taking it mod 2.

Those characters are left on the pipeline and then -joined back together into a single string, which is itself left on the pipeline and output is implicit.

AdmBorkBork

Posted 2017-11-29T19:10:55.007

Reputation: 41 581

You can save a single byte changing "$_".ToUpper() to ("$_"|% *per) :-/ – briantist – 2017-12-03T00:21:21.023

1@briantist Good thing we don't care about readability. ;-) Thanks! – AdmBorkBork – 2017-12-04T15:29:59.853

2

PHP, 63 53 bytes

while($a=$argv[1][$i++])echo rand()%2?ucfirst($a):$a;

Managed to reduce the code with 10 bytes by (partialy) following Titus' suggestion.

RFSnake

Posted 2017-11-29T19:10:55.007

Reputation: 41

1Nice one! No need for a space before $a. Try while(~$a=$argn[$i++]) instead of foreach (run as pipe). – Titus – 2017-12-02T07:47:02.087

Using that code i got a "Uncaught Error: Unsupported operand types" error. And i cant see why it does that, but i suspect the ~. (and maybe because i use PHP7 and the method only works for 5.6) – RFSnake – 2017-12-02T14:07:56.457

2

Julia, 35 bytes

s->map(c->rand([c,uppercase(c)]),s)

Try it online!

Still pretty easy to read as a human. In Julia rand(A) returns a random element from A.

LukeS

Posted 2017-11-29T19:10:55.007

Reputation: 421

Welcome to PPCG! – Steadybox – 2017-12-17T01:47:35.507

1

Rebol, 61 bytes

u:func[t][n: random length? t t/(n): uppercase t/(n) print t]

Test:

>>c: "Test sTring"
>>u c
Test sTriNg

Galen Ivanov

Posted 2017-11-29T19:10:55.007

Reputation: 13 815

1

Jelly, 16 bytes

2ḶXø³L¤Ð¡ḊT
Œu¢¦

Try it online!

Explanation

2ḶXø³L¤Ð¡ḊT    First Link
2Ḷ             The list [0,1]
  X            Random element (1 is truthy, 0 is falsy)
   ø           Begin nilad
    ³L         Length of first input (the string)
      ¤        End nilad
       С      Random([0,1]) for each character in the input string and collect.
         Ḋ     The list had an extra None at the beginning. Don't know why. This removes it (the first element of the list)
          T    Get indices of all truthy 

Œu¢¦           Main Link
Œu             Capitalize
   ¦           At the indices in the list:
  ¢            The first link as a nilad (list of indices)

I couldn't get this to work in a single line. I also don't know why, but 2ḶXø³L¤Ð¡ gives the list [None,1,0,..,1] with 0s and 1s chosen randomly. The None is the reason for the in the first link.

dylnan

Posted 2017-11-29T19:10:55.007

Reputation: 4 993

1

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.

Steven H.

Posted 2017-11-29T19:10:55.007

Reputation: 2 841

1

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.

Sean

Posted 2017-11-29T19:10:55.007

Reputation: 4 136

1

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)

Adám

Posted 2017-11-29T19:10:55.007

Reputation: 37 779

1

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>.

ovs

Posted 2017-11-29T19:10:55.007

Reputation: 21 408

1

Octave, 44 bytes

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

Try it online!

ಠ_ಠ

Posted 2017-11-29T19:10:55.007

Reputation: 430

1

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!"

fede s.

Posted 2017-11-29T19:10:55.007

Reputation: 945

1

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!

James Heyes

Posted 2017-11-29T19:10:55.007

Reputation: 11

1

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.

– Taylor Scott – 2017-12-05T04:36:21.850

1@taylor Thanks! I'm a longtime lurker but its my first time submitting. – James Heyes – 2017-12-05T07:22:28.880

1

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.

pppery

Posted 2017-11-29T19:10:55.007

Reputation: 3 987

1

Japt -m, 5 4 bytes

+u)ö

Try it

Shaggy

Posted 2017-11-29T19:10:55.007

Reputation: 24 623

1

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!

Richard Park

Posted 2017-11-29T19:10:55.007

Reputation: 21

1

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!

Jitse

Posted 2017-11-29T19:10:55.007

Reputation: 3 566

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. – Beefster – 2019-10-18T21:38:05.160

@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. – Jitse – 2019-10-19T19:00:07.450

1

@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.

– Jitse – 2019-10-20T11:52:55.633

1

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!

pythonier500

Posted 2017-11-29T19:10:55.007

Reputation: 11

2Welcome 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. – Post Rock Garf Hunter – 2019-10-18T20:57:08.283

Also both >1 and <2 are shorter than ==1 and both work just fine. – Post Rock Garf Hunter – 2019-10-18T20:59:23.867

1Also, 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" – pppery – 2019-10-18T21:12:00.237

1

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.

JosiahRyanW

Posted 2017-11-29T19:10:55.007

Reputation: 2 600

0

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

dzaima

Posted 2017-11-29T19:10:55.007

Reputation: 19 048

0

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

DLosc

Posted 2017-11-29T19:10:55.007

Reputation: 21 213

0

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!

ბიმო

Posted 2017-11-29T19:10:55.007

Reputation: 15 345

0

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

Jo King

Posted 2017-11-29T19:10:55.007

Reputation: 38 234

0

Scala, 44 bytes

s.map(c=>if(math.random<.5)c.toUpper else c)

AmazingDreams

Posted 2017-11-29T19:10:55.007

Reputation: 281

0

AWK, 100 79 73 bytes

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

Try it online!

Noskcaj

Posted 2017-11-29T19:10:55.007

Reputation: 421

0

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.

Giuseppe

Posted 2017-11-29T19:10:55.007

Reputation: 21 077

0

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 ,''

RosLuP

Posted 2017-11-29T19:10:55.007

Reputation: 3 036

Woah, NARS allows you to do something like 98..123? – Zacharý – 2017-12-01T15:38:17.247

@Zacharý yes it seems one can use range interval – RosLuP – 2017-12-01T16:03:23.870

0

Julia, 56 bytes

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

Try it online!

Hlaaftana

Posted 2017-11-29T19:10:55.007

Reputation: 41

0

><>, 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.

Sok

Posted 2017-11-29T19:10:55.007

Reputation: 5 592

0

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.

philcolbourn

Posted 2017-11-29T19:10:55.007

Reputation: 501

0

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...

Ciaran_McCarthy

Posted 2017-11-29T19:10:55.007

Reputation: 689

0

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!

ASCII-only

Posted 2017-11-29T19:10:55.007

Reputation: 4 687

0

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

ASCII-only

Posted 2017-11-29T19:10:55.007

Reputation: 4 687

0

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

Business Cat

Posted 2017-11-29T19:10:55.007

Reputation: 8 927