| Bytes | Lang | Time | Link |
|---|---|---|---|
| 013 | MathGolf | 211202T091319Z | Kevin Cr |
| 102 | Red | 250513T125039Z | Galen Iv |
| 010 | Japt | 241020T054515Z | Shaggy |
| 055 | Juby | 250512T180553Z | Jordan |
| 090 | Swift 6 | 240313T185524Z | macOSist |
| 095 | PHP | 250128T171816Z | lukas.j |
| 125 | Kotlin | 250128T164604Z | lukas.j |
| 056 | Zsh | 250126T064333Z | roblogic |
| 1135 | ☾ | 250124T173437Z | noodle p |
| 008 | Uiua | 250125T003951Z | janMakos |
| 006 | Vyxal | 250124T214920Z | lyxal |
| 008 | Uiua | 240313T175906Z | noodle p |
| 072 | JavaScript Node.js | 240410T091825Z | tsh |
| 452 | Scratch | 240410T075737Z | Patric |
| nan | In true Perl spirit | 211201T223610Z | Xcali |
| 100 | YASEPL | 240313T184550Z | madeforl |
| 086 | JavaScript V8 | 211204T181718Z | noodle p |
| 073 | Julia 1.0 | 220217T174410Z | amelies |
| 033 | x86_64 machine code | 220217T140018Z | xiver77 |
| 142 | Clojure | 211205T035356Z | Bob Jarv |
| 142 | TSQL | 211203T085209Z | t-clause |
| 051 | C clang | 211202T011547Z | att |
| 119 | Python 2 | 211201T200610Z | Riker |
| 009 | APL Dyalog Extended | 211201T200643Z | Adá |
| 041 | Raku | 211202T234930Z | Sean |
| 013 | ayr | 211202T231539Z | ZippyMag |
| 160 | TIBasic | 211202T224336Z | Youserna |
| 043 | Perl 5 pF | 211202T102653Z | Dom Hast |
| 145 | C# | 211202T165148Z | Finn Raw |
| 076 | JavaScript Node.js | 211201T224615Z | Arnauld |
| 089 | Excel | 211202T160555Z | Axuary |
| 059 | Ruby | 211202T142849Z | G B |
MathGolf, 14 13 bytes
hr¥áÅ;v^mÉ~╛δ
I/O as a list of characters.
Explanation:
h # Push the length of the (implicit) input (without popping)
# → 5
r # Pop and push a list in the range [0,length)
# → [0,1,2,3,4]
¥ # Mod-2 on each
# → [0,1,0,1,0]
áÅ;v # Randomly shuffle it:
á # Sort it by,
Å # using the following 2 characters as inner code-block:
; # Discard the value
v # Push a random integer in the range [-2147483648,2147483647]
# e.g. [0,1,0,0,1]
^ # Zip these shuffled 0s/1s with the input-characters
# → [['a',0],['b',1],['c',0],['d',0],['e',1]]
m # Map over each,
É # using 3 characters as inner code-block:
~ # Dump the pair and bits separated to the stack
╛ # If the integer is truthy:
δ # Uppercase the character
# → ['a','B','c','d','E']
# (after which the entire stack is output implicitly as result)
Red, 102 bytes
func[s][v: make vector! d:(length? s)/ 2 append/dup v 32 d random v
forall s[s/1: s/1 - v/(index? s)]]
Japt, 10 bytes
I/O as a character array
ímUîuiv)ö¬
ð ö¬ígUËpu
ímUîuiv)ö¬ :Implicit input of array U
í :Interleave with
Uî : Mould the following the following to length of U
uiv : Literal "v" prepended to literal "u"
) : End moulding
ö¬ : Random permutation
m : Reduce each pair my mapping, where u is Japt's uppercase method and v is the lowercase method
ð ö¬ígUËpu :Implicit input of array U
ð :Truthy indices (all non-empty strings are truthy)
ö¬ :Random permutation
í :Interleave with
UË : Map U
p : Append
u : Uppercase
g : Reduce each pair by modular indexing
Swift 6, 103 90 bytes
let f={zip($0+"",(0..<$0.count).shuffled()).map{$1%2<1 ?$0.uppercased():"\($0)"}.joined()}
PHP, 95 chars
while($s[$i])$k[]=$i++%2==0;shuffle($k);while($i>=0)$s[$i]=$k[--$i]?chr(ord($s[$i])-32):$s[$i];
Explanation:
$s = 'hamburgers';
while ($s[$i]) {
$k[] = $i++ % 2 == 0;
}
// $k is: [ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 ]
shuffle($k);
// $k might be: [ 0, 1, 0, 1, 1, 1, 1, 0, 0, 0 ]
while ($i >= 0) {
$s[$i] = $k[--$i] ? chr(ord($s[$i]) - 32) : $s[$i];
}
print_r($s); // hAmBURGers
Kotlin, 125 chars
val f={s:String->s.indices.map{it%2==0}.shuffled().let{s.mapIndexed{i,c->if(it[i])c.uppercaseChar()else c}}.joinToString("")}
Converted into a function:
val f = fun(s: String): String {
return s
.indices
.map { it % 2 == 0 }
.shuffled()
.let {
s.mapIndexed { i, c -> if (it[i]) c.uppercaseChar() else c }
}
.joinToString("")
}
println(f("hamburgers"))
Test on Kotlin Playground: https://pl.kotl.in/TFsL13VNS
Zsh, 175 160 144 56 bytes
w=$1;for q (`seq $#w|shuf -n$[$#w/2]`)w[q]=$w[q]:u;<<<$w
w is the input word. The loop for q is a shuffled index into w, so that half of w is randomly uppercased. Then print the adjusted string w.
☾, 16 11 chars (35 bytes)
ᐵᣆ²⫰ᐛ⭥⟞
To each character, uppercase it if the corresponding element of the shuffled indices is odd.
Uiua, 8 bytes
⍥⌵◿₂°⍆°⊏
Explanation
⍥⌵◿₂°⍆°⊏
°⊏ # List of indices
°⍆ # Random permutation
◿₂ # Modulo 2
⍥⌵ # Uppercase at `1`s
Vyxal, 6 bytes
yNYÞ℅•
This approach is slightly different to the other ones because instead of using indices, it uses the actual input.
It works by uppercasing half of the input, shuffling that, and transferring the capitalisation. Effectively it's an uppercase mask like thing.
Explained
yNYÞ℅•
yNY # Uppercase every second letter in the input
y # Uninterleave
N # Negate case (= uppercase because guaranteed lowercase). This could have been an uppercase element, but I chose N out of preference
Y # Re-interleave the now uppercase string and the lowercase string
Þ℅ # Shuffle that
• # And transfer the capitalisation to the original input
💎
Created with the help of Luminespire.
Uiua, 12 10 8 bytes
⍥⌵◿2⍏≡⊸⚂
Try it: Uiua pad
Convert to uppercase where numbers are odd in a random permutation of the indices in the string.
JavaScript (Node.js), 72 bytes
s=>Buffer(s).map(c=>Math.random()<n/l--/2?(n-=2,c-32):c,n=l=s.length)+''
Basic idea: To Choose \$n\$ items from \$l\$ candidates, each item have \$\frac{n}{l}\$ probability to be chosen. And once the first item is chosen, we need to choose \$n-1\$ items from remaining \$l-1\$ candidates. If the first item is not chosen, we need to choose \$n\$ items from remaining \$l-1\$ candidates.
Scratch,452 bytes
Although Scratch functions do not distinguish between uppercase and lowercase, still the letters in the different cases can be stored and outputted. We assume that every position in the string has equal chances to be capitalized.
ask and wait
set L to ABCDEFGHIJKLMNOPQRSTUVWXYZ
set i to
repeat until length of R>(length of answer)/2-1
set t to pick random 1 to length of answer
if not R contains t? then
add t to R
repeat length of answer
if R contains i? then
set j to 1
repeat 26
if letter i of answer = letter j of L then
set a to letter j of L
change j by 1
else
set a to letter i of answer
set C to join C a
change j by 1
say C
Input:
abcdefghijklmnopqrstuvwxyz
Output:
In true Perl spirit, TMTOWTDI:
Perl 5 -MList::Util=shuffle -F, 35 bytes
map$_=uc,(shuffle@F)[1..@F/2];say@F
Perl 5 -F, 49 bytes
@k{0..$#F}=1;map$_=uc,@F[(keys%k)[1..@F/2]];say@F
YASEPL, 100 bytes
=1'±""=a®1=b$a/=i`1=r¢1,a-=c¥r,1=u$32`2!t$u»}3,c,3!u+|2`3!u}2,91-32»!¤r,u!i+}2,b=i`4=c¥i,1~!i+}2,a,4
explanation:
=1'±""=a®1=b$a/=i`1=r¢1,a-=c¥r,1=u$32`2!t$u»}3,c,3!u+|2`3!u}2,91-32»!¤r,u!i+}2,b=i`4=c¥i,1~!i+}2,a,4 packed
=1' get user input and set it to var1
±"" split it every character (to bypass a bug in the yasepl code)
=a®1 A = length of var1
=b$a/ B = length of var1 divided by 2
=i increment variable
`1 !i }2,b do while I < B...
=r¢1,a-=c¥r,1 C = character from var1 at random position
=u$32`2!t$u»}3,c,3!u+|2`3!u}2,91 if C is uppercase then continue loop, do not increment. if not, continue
-32»!¤r,u make character at the position lowercase in list
+ increment I
=i`4=c¥i,1~!i+}2,a,4 join list together once done and print it
JavaScript (V8), 88 86 bytes
f=s=>(r=s.replace(/./g,c=>Math.random()>.5?c:c.toUpperCase(a+=2),a=0)).length-a?f(s):r
This was my first submission on the site! I got my second Yearling badge today so I thought I'd come back and golf some of my earliest submissions.
Explanation:
f=s=> // function f taking string argument s
(r= // assign variable r to
s.replace(/./g,c=> // s with each character c mapped to:
Math.random()>.5 // random true/false
?c // if true, leave c unchanged
:c.toUpperCase(a+=2), // else, uppercase c, and add 2 to a
a=0 // a defaults to 0
)) // end assignment
.length-a // (length of r) - a
?f(s) // if nonzero, start over
:r // else, return r
Julia 1.0, 73 bytes
!s=(E=length(s);v=rand(E);prod(i->s[i]-32*(i∈sortperm(v)[1:E÷2]),1:E))
x86_64 machine code, 33 bytes
\x89\xf1\x0f\xc7\xf0\x73\xfb\x31\xd2\xf7\xf6\xf6\x04\x17
\x20\x74\xf1\x80\x24\x17\xdf\x83\xe9\x02\x75\xe8\xc3
It uses the hardware random generator rdrand, which is very slow BTW.
original assembly (nasm)
f: ; rdi = string, rsi = number of characters, SysV calling convention
mov ecx, esi
.loop:
rdrand eax
jnc .loop
xor edx, edx
div esi
test byte [rdi + rdx], 0x20
jz .loop
and byte [rdi + rdx], 0xdf
sub ecx, 2
jnz .loop
ret
Clojure, 142 bytes
(defn r[s](let[l(count s)z(apply str(update(vec s)(rand-int l)clojure.string/upper-case))](if(<(count(re-seq #"[A-Z]" z))(/ l 2))(recur z)z)))
Un-golfed version:
(defn randomly-capitalize-half-of [s]
(let [v (vec s) ; convert string s to a vector of characters - e.g. "abcd" becomes [\a \b \c \d]
l (count s) ; length of string s
i (rand-int l) ; choose a random index from 0 to (length of s)-1
v2 (update v i clojure.string/upper-case) ; convert character at index i in v to upper case
s2 (apply str v2) ; collapse vector-of-characters to a single string
c (count (re-seq #"[A-Z]" s2)) ] ; count number of upper-case letters in s2
(if (< c (/ l 2)) ; if count of upper-case letters < 1/2 of length of s
(recur s2) ; then recursively invoke randomly-capitalize with partially-upcased string as input
s2))) ; else return half-uppercased string
T-SQL, 142 bytes
SELECT top(len(@)/2)@=stuff(@,number+1,1,upper(substring(@,number+1,1)))FROM
spt_values WHERE number<len(@)and'P'=type
ORDER BY newid()PRINT @
This will always give return the same result. In Microsoft SQL Server Management Studio, the result is randomized. The reason could be the explanation below by Fmbalbuena
C (clang), 58 51 bytes
-1 thanks to AZTECCO
-6 with wide string and clang
i;f(*s,l){for(i=l/2;rand()%l--<i?s[l]^=32,--i:i;);}
Outputs by modifying the input string.
Each letter has a \$\frac in\$ chance of being capitalized, where \$i\$ is the number of remaining capital letters and \$n\$ is the number of remaining letters (including this one).
Python 2,127 119 bytes
Not super happy with this, I'll probably come back to it after class (or not, we'll see). Takes input from stdin using Python 2 input() rules - aka "test" rather than test.
Requires Python 2 for range returning a list, since that would require *x, instead of x otherwise, and would lose a byte on the print statement and I don't think you can gain more than 2 from inline variable assignments.
Using chr/ord is shorter than [s[i],s[i].upper()][i in x[::2]], I think that's optimal as well.
Thanks to enzo for -8, from switching from using a while loop to just str.join.
from random import*
s=input()
n=len(s)
r=range(n)
x=sample(r,n)
print''.join(chr(ord(s[i])-32*(i in x[::2]))for i in r)
APL (Dyalog Extended), 14 9 bytes
−5 bytes thanks to ovs.
Anonymous tacit prefix function
⌈@(2|≢?≢)
⌈ uppercase
@(…) at the positions indicated by the following mask:
≢?≢ shuffle the indices 1 through the tally of elements in the argument (lit. take n random elements from 1…n, without replacement)
2| division remainders when divided by 2
Raku, 41 bytes
{[~] {@_[pick @_/2,^@_]».=uc;@_}(.comb)}
.combsplits the input string into a list of characters, which is then fed to the brace-delimited anonymous function, which takes the list in the@_array. This is just a short way to get an array with writeable elements without having to declare one explicitly.pick @_ / 2, ^@_randomly selects half of the indices in the character array.@_[...]».=ucslices into the array of characters with the random selection of indices, and uppercases the characters at those indices. The original array is then returned.[~]concatenates the characters into a single string.
ayr, 13 bytes
(];-){:2|#?.#
Explained
#?.# Roll N-sided die N times, where N is len of y
2| Convert this to a length-N boolean vector (half 1s, half 0s)
{: Use this to catalogue..
];- A matrix of the string and the string with inverted caps
TI-Basic, 160 bytes
Input Str1
length(Str1
Ans/2≥randIntNoRep(1,Ans→S
"abcdefhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2
".
For(I,1,dim(ʟS
Ans+sub(Str2,inString(Str2,sub(Str1,I,1))+26ʟS(I),1
End
sub(Ans,2,dim(ʟS
Output is stored in Ans and displayed. Only works on calculators that support randIntNoRep(.
Perl 5 -pF, 43 bytes
1 byte saved thanks to @Kjetil S!
$F[rand@F]&=_,$_=join"",@F
while@F/2>y;A-Z;
Perl 5 + -pa, 38 bytes
-5 bytes using a space separates string (Thanks @Kjetil S!)
$F[rand@F]&=_,$_="@F"
while@F/2>y;A-Z;
C#, 145 bytes
Hey! I'm completely new to this and my answer will make that apparent. I thought I'd post so that I can refer back to later to see my progress. Let me know if I anything is incorrect involving my answer.
didn't include logging, output is the t string
string t="";int p=0;while(p!=s.Length/2){t="";p=0;foreach(char c in s){char l=c;if(new Random().Next(2)==0){l=char.ToUpper(l);p++;}t=$"{t}{l}";}}
JavaScript (Node.js), 76 bytes
f=s=>(S=Buffer(s).map(c=>c^=Math.random(n++)<.5?32:--n-n--,n=0),n?f(s):S)+''
Commented
f = s => // s = input string
( S = // S = output
Buffer(s) // turn s into a buffer
.map(c => // for each ASCII code c in s:
c ^= // update c:
Math.random(n++) // increment n
< .5 ? // with 1/2 probability:
32 // turn c into uppercase
: // or:
--n - n--, // leave c unchanged and decrement n twice
n = 0 // start with n = 0
), // end of map()
n ? f(s) // try again if we haven't capitalized exactly
// half of the letters
: S // otherwise, stop and return S
) //
+ '' // coerce the output buffer back to a string
Excel, 89 bytes
=LET(x,LEN(A1),y,RANDARRAY(x),CONCAT(CHAR(CODE(MID(A1,SEQUENCE(x),1))-(y>MEDIAN(y))*32)))
This breaks the string into an array of characters. Then generates an array of random numbers of the same length. For each number in the random array that is greater that the median of the array, the corresponding letter is changed to upper case (ASCII value reduced by 32). Then all of the characters are concatenated.


