title: Print some JSON

text:
# Question
Title: Print some JSON
This challenge is straightforward, but hopefully, there are plenty of avenues you can approach it:

**You need to print/return a valid JSON *object* of at least 15 characters, not counting unessential whitespace.** Your program should work without any input.

In the interest of clarity, a JSON object starts and ends with curly braces `{}`, and contains zero or more key:value pairs separated by commas. The full JSON specification can be found at json.org, and the output of your code must pass this validator.

Therefore, any of the following would **not** be valid:

```
4                               //Too short, not an object
"really, really long string"    //A string, not an object
["an","array","of","values"]    //An array is not a JSON object
{"this":4      }                //You can't count unessential whitespace
{"1":1,"2":3}                   //Too short
{"a really long string"}        //Not valid JSON, it needs a value
{'single-quoted':3}             //JSON requires double-quotes for strings

```

However, the following *would* be valid:

```
{"1":1,"2":2,"3":3,"4":4}       //Long enough
{"whitespace      ":4}          //This whitespace isn't unessential

```

Non-programming languages are allowed on this challenge. You may return a string from a function, or print it out. This is a , so answer it with as little code as possible!

# Answer
> 75 votes
## Python 2, 14 bytes

```
print{`str`:1}

```

Outputs:

```
{"<type 'str'>": 1}

```

The backticks get the string representation in Python 2. Usually, this outputs inside creates single quotes, which Python recognizes as delimiting a string, but JSON doesn't. But Sp3000 observes that when stringifying a type, the type description already contains single quotes, which forces the outer quotes to be double quotes.

# Answer
> 41 votes
# jq, 6 characters

(3 characters code + 3 characters command-line option.)

```
env

```

CW because I am sure this is not the kind of answer you intended to allow.

Sample run:

```
bash-4.3$ jq -n 'env'
{
  "GIT_PS1_SHOWDIRTYSTATE": "1",
  "TERM": "xterm",
  "SHELL": "/bin/bash",
  "GIT_PS1_SHOWUNTRACKEDFILES": "1",
  "XTERM_LOCALE": "en_US.UTF-8",
  "XTERM_VERSION": "XTerm(322)",
  "GIT_PS1_SHOWSTASHSTATE": "1",
  "GIT_PS1_SHOWUPSTREAM": "auto",
  "_": "/usr/bin/jq"
}

```

(Output obviously shortened.)

# Answer
> 33 votes
# Jelly, 11 bytes

```
“Ɠɼ'ẸẠḌȷżÑ»

```

Try it online!

### Output

```
{"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch":0}

```

# Answer
> 22 votes
# Notepad, 7 keystrokes

If you have a Windows computer with the Notepad program, type this:

`{``"``F5``"``:``0``}`

On my Windows 7 computer, at least, this gives you something like:

```
{"3:42 PM 10/25/2016":0}

```

# Answer
> 17 votes
# Java (JDK 10), 20 bytes

```
v->"{\"\":"+1/.3+"}"

```

Try it online!

## Output

```
{"":3.3333333333333335}

```

# Answer
> 15 votes
# JavaScript, ~~17~~ 15 bytes

Thanks to @Neil for this one. Call with no input.

```
_=>`{"${_}":0}`

```

Outputs `{"undefined":0}`

### Old version, 16 bytes

Thanks to @kamoroso94 for -1 on this version

```
_=>`{"":${9e9}}`

```

Outputs `{"":9000000000}`

# Answer
> 14 votes
# PHP, ~~14~~ 13 bytes

```
{"":<?=M_E?>}

```

Prints a ~~nice~~ mathsy object ~~that one could almost pretend is useful~~:

```
{"":2.718281828459}

```

Uses the fact that php prints anything outside the tags verbatim to save on some quotation marks, `M_E` was the shortest long enough constant I could find.

edit: saved one byte thanks to Lynn. Sadly it's no longer a 'nice' mathsy object.

# Answer
> 13 votes
## Brainfuck, 50 bytes

```
+[+<---[>]>+<<+]>>+.>>>--.<+++<[->.<]>>.<+.-.<<++.

```

Outputs `{"999999999999999999999999999999999999999999999999999999999999999999999999999999999":9}`. Assumes an interpreter that has 8-bit cells and is unbounded on the left. Try it online!

# Answer
> 12 votes
# Pyth - 5 bytes

Prints `{"'abcdefghijklmnopqrstuvwxyz'": 10}`.

```
XH`GT

```

Try it online here.

# Answer
> 11 votes
# Jolf, 9 bytes

```
"{¦q:¦q}"

```

Outputs: `{"{¦q:¦q}":"{¦q:¦q}"}`. Try it here!

```
"{¦q:¦q}"
"{  :  }"  raw string
  ¦q       insert the source code here
     ¦q    and here

```

# Answer
> 10 votes
# Pyth, 7 bytes

```
.d],`G0

```

Creates a dictionary containing a single key `"'abcdefghijklmnopqrstuvwxyz'"` and value `0`:

```
.d         Dictionary from:
  ]         The single-element list containing:
   ,         The two-element list containing:
    `G        The representation of the alphabet (the key)
      0       and 0 (the value)
          Implicitly print the stringification of this.

```

# Answer
> 9 votes
# ///, ~~15~~ 14 characters

```
/a/{":1234}/aa

```

(At least the output is ~~1~~ 2 characters longer than the code.)

Try it online!

Thanks to:

* ETHproductions for reusing the object delimiters as part of key (-1 character)

Sample run:

```
bash-4.3$ slashes.pl <<< '/a/{":1234}/aa'
{":1234}{":1234}

```

Just to make it more readable:

```
bash-4.3$ slashes.pl <<< '/a/{":1234}/aa' | jq ''
{
  ":1234}{": 1234
}

```

# Answer
> 9 votes
## Batch, 16 bytes

Prints `{"Windows_NT":0}`.

```
@echo {"%OS%":0}

```

# Answer
> 7 votes
# 05AB1E, 9 bytes

Unfortunately, 05AB1E doesn't have a dictionary object so we have to construct our own.

```
’{"èÖ":7}

```

Try it online!

**Output**

```
{"dictionaries":7}

```

# Answer
> 7 votes
# R, 19 bytes

```
cat('{"',lh,'":1}')

```

Becomes a bit longer because the need to escape quotes `\"`. Furthermore, `lh` is one of the built-in datasets in `R` and is (to my knowledge) the object with the shortest name that contains the 9 characters needed to fill the length of the key. (edit: turns out `pi` does the trick as well with the standard option and I was beaten by @JDL who was clever enough to escape using single quotes rather than the extra backslashes)

The description of `lh` in the R-documentation is:

> A regular time series giving the luteinizing hormone in blood samples at 10 mins intervals from a human female, 48 samples.

which is a rather unexpected name of a key, but hey, it works and produces the output:

```
{" 2.4 2.4 2.4 2.2 2.1 1.5 2.3 2.3 2.5 2 1.9 1.7 2.2 1.8 3.2 3.2 2.7 2.2 2.2 1.9 1.9 1.8 2.7 3 2.3 2 2 2.9 2.9 2.7 2.7 2.3 2.6 2.4 1.8 1.7 1.5 1.4 2.1 3.3 3.5 3.5 3.1 2.6 2.1 3.4 3 2.9 ":1}

```

The answer can be compared to just padding the key with "random" letters to make the output at least 15 characters (24 bytes):

```
cat("{\"HeloWorld\":1}")

```

# Answer
> 7 votes
## PowerShell ~~22~~ ~~20~~ 14 Bytes

```
'{"":'+1tb+'}'

```

Output

```
{"":1099511627776}

```

Using the constant defined for 1TB in bytes to reach the character limit and the value of a static integer to make for valid json. Thanks to TimmyD for reducing the characters by 5 by removing some redundancy.

---

### Earlier Post 40 Bytes

```
"{$((1..9|%{'"{0}":{0}'-f$_})-join",")}"

```

Output

```
{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}

```

Takes a integer array and creates a key-value pair for each. Join with commas and wrap with a set of curly braces.

# Answer
> 6 votes
# , 9 bytes

```
i{"¹*":0}

```

Try it online!

Very straightforward. Enters insert mode, enters the following text:

```
{"*********":0}

```

The reason this is so short is because `¹` repeats the following character 9 times.

# Answer
> 6 votes
## Retina, 11 bytes

```

{"9$*R":1}

```

### Output

```
{"RRRRRRRRR":1}

```

**Note:** the leading newline is significant as nothing is replaced with the resultant output, I've used a non-breaking space to illustrate this!

Try it online!

# Answer
> 6 votes
# Dyalog APL, 9 bytes

```
⎕JSON⎕DMX

```

Try it online!

In a clean workspace on my PC the result is

`{"Category":"","DM":[],"EM":"","EN":0,"ENX":0,"HelpURL":"","InternalLocation":["",0],"Message":"","OSError":[0,0,""],"Vendor":""}`

`⎕JSON` convert to JSON

`⎕DMX` the (universally available) **D**iagnostic **M**essage E**x**tended object

# Answer
> 6 votes
# Japt `-Q`, 1 byte

```
M

```

Try it online!

The output is `{"P":3.141592653589793,"Q":1.618033988749895,"T":6.283185307179586}`.

### How it works

`M` is a shorthand for JS's `Math` object, with one-char aliases to existing functions/constants and some extra functions/constants. The constants shown here are:

* `M.P = Math.PI`
* `M.Q = Golden Ratio = (Math.sqrt(5)+1)/2`
* `M.T = Math.PI * 2`

And the boring part: the `-Q` flag applies `JSON.stringify` to the output value. Some of the properties are lost (e.g. `Math.E` and `Math.SQRT2`), but we still have the above three values and the result is well over 15 characters.

# Answer
> 5 votes
## Ruby, 19 bytes

```
puts'{"1":'+9**9+?}

```

Output:

```
{"1":387420489}

```

# Answer
> 5 votes
# brainfuck, 83 bytes

```
--[-->+++++<]>.+[---->+<]>+++.>-[>+<-----]>.........<<.[----->+<]>.>.>--[-->+++<]>.

```

Outputs `{"333333333":3}`

There is likely another shorter solution, but I have not yet found it.

Explanation:

```
--[-->+++++<]>. {
+[---->+<]>+++. "
>-[>+<-----]>.  3
........
<<.             "
[----->+<]>.    :
>.              3
>--[-->+++<]>.  }

```

Try it online

# Answer
> 5 votes
# R, 19 bytes

This works in British English locale; it may require +2 bytes in others. (Edit: it probably doesn't --- see comments.)

```
cat('{"',pi,'":1}')

```

I was hoping for something clever (perhaps plucking a line of code out of a pre-existing function like `q`) but couldn't find anything. The result:

```
{" 3.141593 ":1}

```

Note that you don't have to escape double quotes in R if you use single quotes to quote the string (and vice-versa). This behaviour is locale-dependent though. I would expect it to work in a US English locale as well though.

This also requires that your default `digits` option is at least six (which is the factory-fresh default) and that `scipen` is at least `-digits` (the factory-fresh default is zero).

# Answer
> 5 votes
# Java 7, 36 bytes

```
String c(){return"{\"a\":"+1e6+"}";}

```

# Java 8, 21 bytes

```
()->"{\"a\":"+1e6+"}"

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(){
    return "{\"a\":" + 1e6 + "}";
  }

  public static void main(String[] a){
    System.out.println(c());
  }
}

```

**Output (length 15):**

```
{"a":1000000.0}

```

# Answer
> 5 votes
### PHP, 19 bytes

```
<?='{"'.(9**9).'":1}';

```

Output: `{"387420489":1}`

https://eval.in/665889

Thanks to manatwork for the tips!

# Answer
> 5 votes
# Perl 5, 16 15 bytes

Uses the unix timestamp of the moment the program was started as the content of a one-element object. **It gives valid output if you run it later than 10:46:39 on 3rd of March 1973**. But since we can't go back in time that seems legit.

```
say"{\"$^T\":1}"

```

Uses the FORMAT\_TOP\_HANDLE variable `$^` which defaults to `STDOUT_TOP`.

```
say"{\"$^\":1}";

```

Run with `-E` flag at no additional cost.

```
perl -E 'say"{\"$^\":1}";'

```

Outputs is 16 bytes long.

```
{"STDOUT_TOP":1}

```

# Answer
> 5 votes
# JavaScript (ES6) + jQuery, 15 bytes

Because jQuery.

```
_=>`{"${$}":0}`

```

Outputs `{"function (a,b){return new n.fn.init(a,b)}":0}` when called. Try it here:

```
f=_=>`{"${$}":0}`
alert(f())
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```

# Answer
> 5 votes
# Windows batch, 10 bytes

```
{"%OS%":5}

```

The environment variable `OS` contains the string `Windows_NT` (On all Windows operating systems since 2000, according to this question on Stack Overflow)

# Answer
> 5 votes
# HQ9+, 15 bytes

```
{"Quineland":0}

```

Outputs itself. I thought an 8-byte answer would be possible, like so:

```
{":11QQ}

```

This outputs `{":11QQ}{":11QQ}`, which is *almost* valid JSON, but `11QQ` is not a valid value.

HQ9+ is not a valid programming language by PPCG standards, but the OP has allowed non-programming languages.

# Answer
> 5 votes
# Bash, 18 bytes

`echo {\"$PATH\":1}`

This works on Mac and Linux, unless your $PATH isn't set.

# Answer
> 3 votes
# Jelly, ~~13~~ 12 bytes

```
“{"":}”s2jȷ4

```

**TryItOnline!**

### How?

```
“{"":}”s2jȷ4 - Main link: no arguments
“{"":}”      - literal ['{','"','"',':','}']
       s2    - split into twos -> [['{','"'],['"',':'],['}']]
         j   - join with
          ȷ4 - literal 10000 -> ['{','"',10000,'"',':',10000,'}']
             - implicit print -> {"10000":10000}

```

---

previous (13):

```
“"11”m0“{:}”j

```

# Answer
> 3 votes
# Element, 18 bytes

```
\{\"a\"\:`9 9^`\}`

```

Try it online! Outputs `{"a":387420489}`

This is only three bytes shorter than the naive solution. The first half of the output is hard-coded (too many escape characters to make any other approach feasible), while the value is calculated as `9^9` to make a number long enough.

# Answer
> 3 votes
# Cheddar, ~~17~~ 14 bytes

*Saved 3 bytes thanks to @ConorO'Brien*

```
->'{":1234}'*2

```

An anonymous function that returns `{":1234}{":1234}`, which is a valid JSON object:

```
{
  ":1234}{": 1234
}

```

**Try it online!**

# Answer
> 3 votes
## Charcoal, 7 bytes

```
{"⁹":9}

```

Try it online!

Runs of printable ASCII characters in Charcoal form literal strings, and expressions lacking any explicit command are printed. So `{"` and `":9}` are just output verbatim. , however, is an integer literal, and when you print an integer, you get an ASCII-art line that many characters long. The character used for horizonal lines is the hyphen, so the result is:

```
{"---------":9}

```

Conveniently, this is exactly 15 characters.

# Answer
> 2 votes
# IBM/Lotus Notes @Formula, ~~24~~ 23 bytes

Computed value in a Notes field.

```
"{\"\":"+@Text(@Pi)+"}"

```

Outputs:

```
{"":3.14159265358979}

```

Nothing clever - just uses the shortest possible function that outputs a number then converts it to text for display.

# Answer
> 2 votes
# q, 14 bytes

Prints memory usage information about the current process

```
-1@.j.j .Q.w`;

```

Sample output:

```
q)-1@.j.j .Q.w`;
{"used":127392,"heap":67108864,"peak":67108864,"wmax":0,"mmap":0,"mphy":16735457280,"syms":585,"symw":18925}

```

# Answer
> 2 votes
# Japt, 11 bytes

There are a multitude of 11-byte programs:

```
`\{"{O}":1}  // {"[object Object]":1}
`\{"{M}":1}  // {"[object Math]":1}
`\{"{@}":1}  // {"function (X,Y,Z){return }":1}
`\{"{_}":1}  // {"function (Z){return Z}":1}
`\{"{Ð}":1}  // {"Tue Oct 25 2016 12:15:24 GMT-0400 (Eastern Standard Time)":1}
`\{"":{+Ð}}  // {"":1477412000095}

```

The last two use the Date object; thus, they are non-constant, but always output more than 15 bytes. Explanation:

```
`\{"   ":1}` // Take this string,
    {O}      // inserting variable O here.
             // O is an Object, which stringifies to "[object Object]".
             // Implicitly output.

```

**Test it online!**

More interesting 12-byte version:

```
`\{":{L²}}`²

```

Prints `{":10000}{":10000}`. Explanation:

```
`\{":    }`   // Take this string,
     {L²}     // inserting 100 squared (10000) here,
              // (this yields {":10000})
           ²  // and double.
              // Implicitly output.

```

**Test it online!**

# Answer
> 2 votes
## Common Lisp, 24 bytes

```
(format t"{~S:~f}""p"pi)

```

Prints the following to standard output (23 characters long):

```
{"p":3.141592653589793}

```

This is a simple string format which uses the predefined constant `PI`.

# Answer
> 2 votes
# CoffeeScript, ~~18~~ 16 bytes

*Saved 2 bytes thanks to @Caffeinated.tech*

```
->'{"":'+1/3+'}'

```

Outputs `{"":0.3333333333333333}`. Sadly, because of the required double-quotes, string interpolation is a byte longer:

```
->"{\"\":#{1/3}}"

```

# Answer
> 2 votes
**Actionscript 3, 27 bytes**

`trace(JSON.stringify(int));`

outputs

`{"MAX_VALUE":2147483647,"length":1,"MIN_VALUE":-2147483648,"prototype":{}}`

# Answer
> 2 votes
**TSQL(2016 only), 50 BYTES**

```
SELECT*FROM(VALUES(GETDATE()))AS A(a)FOR JSON PATH

```

# Answer
> 2 votes
# Java 8 (Full Program), 125 Bytes 123 Bytes 116 Bytes

Yes, I know there are shorter ways in Java, as posted above. I just wanted to approach it from a looping perspective.

Thanks to ais523 for saving 2 bytes.
Thanks to Manatwork for saving 7 bytes.

```
interface C{static void main(String[]a){for(int i=0;i++<9;)System.out.print(i<2?"{":"\""+i+"\":"+i+(i>8?"}":","));}}

```

Ungolfed

```
interface C{
    static void main(String[]a){
        //Loop from 0-8, add one to i at start of loop instead of end though
        for(int i=0;i++<9;)
            //If it is a start case simply print { otherwise print "i":i
            //If it is an end case also print } otherwise also print :
            System.out.print(i<2?"{":'"'+i+"\":"+i+(i>8?"}":","));
        }
}

```

# Answer
> 2 votes
## PowerShell, 17 bytes

Slightly unclear on how strict the 'no input' thing is, if it's just no user input or of system input is also disallowed. While my best answer isn't shorter than the other PowerShell answer I think it is novel.

```
ps|ConvertTo-Json

```

Gets running processes (default return is an object) and converts that object to a json. Several other two and three letter aliases commands work.

Sample output omitted because it's 34115 lines long and trying to redact my username and computername was a pain.

```
gl|ConvertTo-Json

```

Gets your current filesystem location (as an object) and converts that object to a json

```
gci|ConvertTo-Json

```

Gets the files in your current path (as an object) and converts that object to a json

You can also take things like inherent type definitions (which are part of the language itself) and pipe them into the conversion function.

```
[xml]|ConvertTo-Json

```

Gets the definition of the xml datatype and converts that object to a json

```
[int]|ConvertTo-Json

```

Gets the definition of the 32bit integer datatype and converts that object to a json

# Answer
> 2 votes
# Vim, 13 keystrokes

```
a{"<esc>9aa<esc>a":0}

```

Outputs

```
{"aaaaaaaaa":0}

```

# Answer
> 2 votes
# K (ngn/k), 12 bytes

```
`0:`j@`a!1e9

```

Try it online!

# Answer
> 2 votes
# Go, 47 bytes

```
import."fmt"
func f(){Print(`{"X":10,"Y":20}`)}

```

Attempt This Online!

### To STDERR, 32 bytes

```
func(){print(`{"X":10,"Y":20}`)}

```

Attempt This Online!

# Answer
> 2 votes
# jq `-n`, 12 bytes

```
""|match("")

```

Try it online!

`env` does not always satisfy the requirement. It depends on the environment, which could even be empty, outputting `{}`. This solution yields the same result every time:

```
{
  "offset": 0,
  "length": 0,
  "string": "",
  "captures": []
}

```

# Answer
> 2 votes
# x86-64 machine code, 16 bytes

```
B8 7B 22 3A 20 AB AB AB AB C7 07 30 7D 7D 00 C3

```

Try it online!

Produces `{": {": {": {": 0}}`.

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI a memory address at which to place the result, as a null-terminated byte string.

In assembly:

```
f:  mov eax, '{' | '"'<<8 | ':'<<16 | ' '<<24
            # Put this value in EAX.
    stosd   # Write it to the output string, advancing the pointer.
    stosd   # Again.
    stosd   # Again.
    stosd   # Again.
    mov DWORD PTR [rdi], '0' | '}'<<8 | '}'<<16 | 0<<24
            # Add this value to the output string.
    ret     # Return.

```

# Answer
> 1 votes
# Turtlèd, 15 bytes

```
'{r'"10:'"r":3}

```

### Try it online

outputs `{" ":3}`

## Explanation

```
'{               write {
  r              move right, off {
   '"            write "
     10          put 10 in register
       :         move right that many characters (puts spaces in)
        '"r       write ", move right of that character
           ":3}   write :3}

```

# Answer
> 1 votes
# Groovy, 43 Bytes

```
{groovy.json.JsonOutput.toJson([i:1..9])}

```

It gives the range 1-9 in JSON stored for i:

```
{"i":[1,2,3,4,5,6,7,8,9]}

```

# Groovy on Grails, 31 Bytes

```
def v(){render(params as JSON)}

```

Controller method, renders the parameters which always include action, controller and a few other meta parameters which results in:

```
{"action":"v","format":null,"controller":"<Controller Name>"}

```

When you visit the URL:

```
http://localhost:8080/<Controller Name>/v

```

# Answer
> 1 votes
# Myth, ~~28~~ 26 bytes

```
{"a":"{\":3141}","_":"aa"}

```

Saved 2 bytes by adapting the solution given by the `///` answer.

Myth is a language similar to Thue, contained in a valid JSON object. How appropriate! Here, `_` is the initial state, and replaces `a` with `"****"`. Output:

```
{":3141}{":3141}

```

For clarity, I added some spaces:

```
{
  ":3141}{"  :  3141
}

```

## Previous solutions

28 bytes: `{"a":"\"****\"","_":"{a:a}"}`. Outputs: `{"****":"****"}`

## Running

I found the interpreter here:

```
function(m,y,t,h){m=JSON.parse(m);for(y=m._;h=1;){for(t in m)if(t!="_"&&~y.indexOf(t)){y=y.replace(t,m[t]);h=0;break}if(h)break}return y}

```

Test it out right here:

```
function myth(m,y,t,h){m=JSON.parse(m);for(y=m._;h=1;){for(t in m)if(t!="_"&&~y.indexOf(t)){y=y.replace(t,m[t]);h=0;break}if(h)break}return y}
b.onclick=function(){o.innerHTML="";o.appendChild(document.createTextNode(myth(q.value)));}
```

```
textarea {
  width: 90%;
}
*{font-family:Consolas,monospace;}
```

```
<textarea id=q>{"a":"\"****\"","_":"{a:a}"}</textarea>
<br>
<button id=b>execute myth code</button>
<br>
<textarea id=o disabled>output</textarea>
```

# Answer
> 1 votes
# Addict, ~~200~~ 167 bytes

Addict is a Turing tarpit where the only control flow is user-defined commands.

```
a A
 i 1
 i 1
 d
a B
 A 1
 A 1
 d
a C
 B 1
 B 1
 d
a D
 C 1
 C 1
 d
D b
D b
D b
D b
D b
D b
D b
C b
B b
d b
D q
D q
A q
c b
c q
c q
D q
C q
c q
n b
n q
n b
n q
A b
c b

```

This outputs `{"":1235812358}`. Try it in the online interpreter!

## How it works

To golf answer space, I'm going to refer you to the sections **Primer on Addict** and **Act I** on **"Hello, World!" in Addict**. If you already know how that works, feel free to skip this part.

## Act II

The rest of the program is devoted to outputting a valid JSON object in as few bytes as possible. In order to minimize the code, we can use the variables that are already set to output a number with the `n` command. The first step is then to set three variables to the two chars we need at first:

* `b` to 123, the char code of `{`
* `q` to 34, the char code of `"`

After these have been set, we output `{""` one char at a time, then increment `q` by 24, resulting in 58, the charcode of `:`. We output that, then output the values of `b` and `q` twice, printing `1235812358`. The last step is to increment `b` by 2 to change it to `}`, and then output it to finish.

If you can find any way to golf this program, please let me know!

# Answer
> 1 votes
# Crystal, 23 bytes

```
puts %Q({"#{"a"*9}":0})

```

You can also avoid using `%Q` (and keep the same character count):

```
puts "{\"#{"a"*9}\":0}"

```

The above return:

```
{"aaaaaaaaa":0}

```

Which has exactly 15 characters.

# Answer
> 1 votes
# Actually, 10 bytes

```
'}Qè;':@'{

```

Try it online!

Explanation:

```
'}Qè;':@'{
'}          push "}"
  Q         push this program's source code
   è        call Python's repr function (essentially just wraps the string in double-quotes)
    ;       duplicate
     ':@    push ":", swap with one copy of double-quoted source code
        '{  push "{"
            implicitly print each stack item, separated by newlines, starting with the top

```

Output:

```
{
"'}Qè;':@'{"
:
"'}Qè;':@'{"
}

```

# Answer
> 1 votes
# Javascript, 14 bytes

```
'{"":'+1e9+'}'

```

Gives:

```
{"":1000000000}

```

I know that this doesn't actually print out anything, it merely returns. But so do all other Javascript solutions here.

# Answer
> 1 votes
# RAGE!!!, 41 bytes

```
<rant>SCREAM"{\"12345\":54321}"!!!</rant>

```

Since the interpreter compiler transpiler on the esolangs page converts the code to Python 2 via mere string substitution, escaping double quotes should be okay.

# Answer
> 1 votes
# ECMAScript 2015, 16 bytes

```
_=>`{"":${9e9}}`

```

*It will run in most modern ECMAScript environments (eg. Firefox, Chrome, MS Edge, Opera, Node…).*

# Answer
> 1 votes
**JavaScript, 17 bytes**

```
_=>'{"'+{}+'":0}'

```

outputs

> {"\[object Object\]":0}

passes validator at jslint

This works because `{}` will implicitly be cast to string with the `+` concatenation, and calling `toString` on an object returns "\[object Object\]".

# Answer
> 1 votes
**C#, 39 bytes**

```
string j(){return"{\""+1.0/0+"\":42}";}

```

In C#, division of 0 with a double (hence the inclusion of .0), will result in Infinity.

Output:

> {"Infinity":42}

# Answer
> 1 votes
# Python 2, 13 bytes

```
print{"'":.1}

```

Outputs:

```
{"'": 0.10000000000000001}

```

Since tenths can't be stored exactly in binary Python outputs a 1 followed by 15 zeros followed by a 1 after the decimal point. Need double quotes around the single quote to not have the double quotes converted to single quotes (thanks to @JonathanAllan's comment to @xnor's answer).

# Answer
> 1 votes
# Rust, 21 bytes

```
||"{\"a\":0.1234567}"

```

String substitution would be too verbose, but at least there's always terse lambdas with implicit returns.

With "test code":

```
fn main(){
    let f=||"{\"a\":0.1234567}";
    println!("{}", f());
}

```

# Answer
> 1 votes
# SmileBASIC, 27 bytes

```
?"{
?CHR$(34)*2;":
?PI();"}

```

Printing quotation marks is a huge pain in BASIC. 8 bytes wasted!

### Output:

```
{
"":
3.14159265}

```

Exactly 15 characters, without the whitespace.

# Answer
> 1 votes
# Pushy, 12 bytes

```
`{"`A`":1}`"

```

**Try it online!**

This produces the output:

```
{"ABCDEFGHIJKLMNOPQRSTUVWXYZ":1}

```

Any text wrapped in backticks is a string literal. The `A` injects the whole uppercase alphabet. Then, the final `"` command prints it all.

# Answer
> 1 votes
# 05AB1E, ~~15~~ 13 bytes

```
„{"A„":Jû¨'}J

```

Try it online!

`{"abcdefghijklmnopqrstuvwxyz":"zyxwvutsrqponmlkjihgfedcba"}`

# Answer
> 1 votes
# Tcl, 18 bytes

```
puts \{"[pwd]"\:4}

```

Try it online!

# Answer
> 1 votes
# Prolog (SWI), 19 bytes

```
?-writeq({"":1e7}).

```

Try it online!

# Answer
> 1 votes
# Nim, 21 bytes

```
echo "{\"\":",4/9,"}"

```

Try it online!

Boooring.

# Answer
> 1 votes
# Brachylog, 14 bytes

```
"{~k:~k}"gj₃w₁

```

Try it online!

# Answer
> 1 votes
# GNU nano, 9 keystrokes

```
{"              ":0}

```

`{` `"` `META`+`o` `Tab` `Tab` `"` `:` `0` `}`

`{` `"`: literal `{"`

`META`+`o`: switch to tabs-to-spaces mode

`Tab` `Tab`: Tab to the second tab stop (tab stops are 8 by default). Since we enabled tabs to spaces, these will be converted to 14 spaces.

`"` `:` `0` `}`: literal `":0}`

It is a very interesting JSON string with a very interesting input method, if you ask me.

Video demo done in Termux to visualize keystrokes (`ALT` is `META`)

# Answer
> 1 votes
# Vyxal, 8 bytes

```
`{"‹":0}

```

Try it Online!

Outputs `{"https://www.google.com":0}`.

# Answer
> 1 votes
# Thunno `KJ`, \\$ 13 \log\_{256}(96) \approx \\$ 10.70 bytes

```
":0}"'"AZ'"'{

```

Attempt This Online!

Prints `{"ABCDEFGHIJKLMNOPQRSTUVWXYZ":0}`

#### Explanation

Since Thunno's stack is reversed, we'll go right to left:

```
":0}"'"AZ'"'{  #                      STACK:
           '{  # Push "{"             {
         '"    # Push '"'             { "
       AZ      # Push the alphabet    { " ABCDEFGHIJKLMNOPQRSTUVWXYZ
     '"        # Push '"'             { " ABCDEFGHIJKLMNOPQRSTUVWXYZ "
":0}"          # Push ":0}"           { " ABCDEFGHIJKLMNOPQRSTUVWXYZ " :0}
               # Flags: join stack    {"ABCDEFGHIJKLMNOPQRSTUVWXYZ":0}
               # Implicit output

```

# Answer
> 1 votes
# Trilangle, 26 bytes

```
"{"o:o"o,S"!So"o"o*}@o,o!o

```

Try it on the online interpreter.

Most of this is just spent shuffling punctuation around. Prints out

```
{"":58
,"":1972
}

```

Which, while not particularly useful, is accepted by `JSON.parse`. The first number is the value of `':'` and the second number is `'"' * ':'`.

## Trilangle, no duplicate keys, 30 bytes

```
"{:ooS"!oo""SS!o,oo"oooS*}@.",

```

Prints out:

```
{"":58
,":":1972
}

```

# Answer
> 0 votes
# Perl, 18 bytes

```
say"{'".[2]."':1}"

```

Prints an array reference in quotes as the name and 1 as the value. Sample output:

```
{'ARRAY(0x60002b5c0)':1}

```

# Answer
> 0 votes
# C++11, 30 bytes

As unnamed lambda, port of jrich's answer, -1 byte thanks to ETHproductions

```
[](){printf("{\"\":%f}",9e9);}

```

Usage:

```
int main(){
 [](){printf("{\"\":%f}",9e9);}();
}

```

# Answer
> 0 votes
## Pyke, ~~11~~ ~~10~~ 8 bytes

```
~C`0]]1Y

```

Try it here!

# Answer
> 0 votes
# C#, 76 bytes

```
using System;public class P{public void Main(){Console.Write("{\"\":"+1/3d+"}");}}

```

Output:

```
{"":0.333333333333333}

```

# Answer
> 0 votes
## Ruby (cheap), 22 bytes

```
->{'{"aaaa":"bbbbb"}'}

```

Lambda function that returns the `String` object `'{"aaaa":"bbbbb"}'`

# Answer
> 0 votes
## JavaScript (REPL)

10 chars:

```
{"":{}+''}

```

Output:

> `{"": "[object Object]"}`

Well, maybe. If it doesn't like the bare object:

12 chars:

```
({"":{}+''})

```

If it doesn't print returned objects the way we need:

This is cleaner (ES2015, 13 chars, borrowing from another solution):

```
`{"":${9e9}}`

```

> `{"": 9000000000}`

# Answer
> 0 votes
# Text, 15 Bytes

I'm pretty sure you know that language, and non-programming languages are allowed...

```
{"hi ":"world"}

```

# Answer
> 0 votes
# ShellSoccar-jpn/Parsrs makrj.sh, ~~6~~ ~~5~~ 4 bytes

Tested with version `Wed Sep 14 22:19:55 JST 2016`, which is the latest version before this problem was created.

```
.../

```

outputs (18 bytes w/o LFs)

```
{
"":{
"":{
"/":""
}
}
}

```

# Explained

makrj.sh is a POSIXism utility to generate a JSON object from a list of JSONPath-indexed values developed by ShellShoccar-jpn. The input shall be lines of `<key> <value>`.

```
.../  # define an implicit value "" with 3-level key whose
.     # 1st-level key name is ""
 .    # 2nd-level key name is ""
  ./  # and 3rd-level key name is "/"

```

## Try this (bash+curl)

```
printf '.../' | sh <(curl https://raw.githubusercontent.com/ShellShoccar-jpn/Parsrs/666042eddeb41406ee4a1e4831a01b0aac5af211/makrj.sh)

```

# Answer
> 0 votes
# Thunno 2, 10 bytes

```
ẠṘ"{%:0}"Œ

```

Attempt This Online!

#### Explanation

```
ẠṘ"{%:0}"Œ  # Full program
  "{%:0}"   # Template string "{%:0}"
         Œ  # With the "%" replaced by
 Ṙ          # A quoted version of
Ạ           # The lowercase alphabet
            # Implicit output

```

# Answer
> -1 votes
# Boring answers with literals

## Emotinomicon, 32 bytes

```
}1:"        r"{⏪⏬⏩

```

## Minecraft, 19 bytes

```
say {"           ":0}

```

### Or not so boring, but not guaranteed

```
say @p

```

And just use the JSON as username

## Any texteditor, 15 bytes

Couldn't get it any shorter with copy-pasting

```
{"123456789":0}

```

## Notepad, 7 keystrokes

`{``"``F5``"``:``1``}`

Thanks to @ETHProductions

---
Tags: code-golf, open-ended-function, json
---


title: How to randomize letters in a word

text:
# Question
Title: How to randomize letters in a word
According to some controversial story, the odrer of ltteres in a wrod deos not mttaer much for raednig, as lnog as the frist and lsat lteter macth with the orignial wrod.

So, for fun, what would be the shortest function to randomize letter order in a word while keeping the first and the last letter in place?

Here's my stab at it with JavaScript. All whitespace removed it's at 124 130 characters.

```
function r(w) {
  var l=w.length-1;
  return l<3?w:w[0]+w.slice(1,l).split("").sort(function(){return Math.random()-.5}).join("")+w[l];
}

```

Shorter JavaScript always welcome.

---

* Edit: length check added. Function should not fail for short words.

# Answer
# Haskell, ~~110~~ ~~120~~ 107 characters

```
import Random
s l=randomRIO(1,length l-2)>>=g.($l).splitAt
g(a:b,c:d)=fmap(a:).s$c:b++d
g(a,b)=return$a++b

```

An example of a program using this function:

```
main = getLine >>= s >>= putStrLn

```
> 21 votes

# Answer
## J, 26 24 23 characters

```
r=:{.,({~?~@#)&}.&}:,{:

```
> 19 votes

# Answer
### Ruby, 44 characters

```
r=->w{w[h=1..-2]=[*w[h].chars].shuffle*"";w}

```

Works also for short words, i.e. words with one, two or three characters are returned unaltered.

*Edit:* Using the array-splat idea of Ventero saves another char.
> 15 votes

# Answer
## Ruby 1.9, 46 characters

```
r=->w{w[0]+[*w[1..-2].chars].shuffle*""+w[-1]}

```
> 11 votes

# Answer
## C++, 79 characters (*with range check*)

```
string f(string s){if(s.size()>3)random_shuffle(&s[1],&s.end()[-1]);return s;}

```

## C++, ~~81~~ 65 characters (*without range check*)

```
string f(string s){random_shuffle(&s[1],&s.end()[-1]);return s;}

```

Using pass by reference instead of returning the result shaves off another 10 characters from either solution.

Full program, reading a string of words and shuffling converting them:

```
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <ctime>
#include <string>

using namespace std;
string f(string s){if(s.size()>3)random_shuffle(&s[1],&s.end()[-1]);return s;}

int main() {
    std::srand(std::time(0));
    std::string s;
    while(std::cin >> s)
        std::cout << f(s) << " ";
    std::cout << std::endl;
}

```

Morale: don’t build what’s already there. ~~Oh, and overflow checks are for wusses.~~
> 11 votes

# Answer
## Python, ~~87~~ ~~79~~ ~~75~~ ~~93~~ 92 chars

```
from random import*
f=lambda w:w if 4>len(w)else w[0]+''.join(sample(w[1:-1],len(w)-2))+w[-1]

```

EDIT: Originally thought it was supposed to split string words (which it did at 128 chars; now at 87 chars does requirement). Argh, my bad at reading comprehension.

EDIT 2: Change from def to lambda function from def to save 6 chars. Assuming sample is already imported to the namespace (`from random import sample`) could bring this down to ~60).

EDIT 3: "len(w\[1:-1\])" (12 chars) to "len(w)-2" (8 chars) per gnibbler's nice suggestion.

EDIT 4: JBernando saved one char (had considered `from random import *` and saw it was equivalent -- not realizing the space in `import *` is unnecessary).; user unknown added 19 chars `w if len(w)<4 else` to handle 0 and 1 char strings correctly.

EDIT 5: Saved another char per boothby's code golf trick. `if len(w)<4 else` to `if 4>len(w)else`.
> 7 votes

# Answer
# **C (K&R) - 88 ~~86~~ ~~87~~ chars**

```
r(char*s){int m,j,l=strlen(s)-2,i=l;while(--i>0){j=rand()%l+1;m=s[j];s[j]=s[1];s[1]=m;}}

```

There's no build-in swap or shuffle function in C, so I had to do it manually :(

Sample Program with Ungolfed r():

```
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

// -----------------------------------------------------------------------
r( char *s )
{
    int m, j, l=strlen(s)-2, i=l;

    while (--i>0)
    {
        j = rand() % l + 1;

        m = s[j];
        s[j] = s[1];
        s[1] = m;
    }

}
// -----------------------------------------------------------------------
int main()
{
    char s[] = "anticipated";

    srand( time(0) );
    r( s );
    puts( s );

    return 0;
}

```

**EDIT**: fixed the bug when s consists of less than 3 chars (thanks to user-uknown for noticing it! )
> 7 votes

# Answer
# C++, 111 97 chars

```
std::string f(std::string s){for(int i=s.size()-1;i>1;std::swap(s[rand()%i+1],s[--i]));return s;}

```

Here is a full program for those who wish to test it:

```
#include<string>
#include<iostream>

std::string f(std::string s){for(int i=s.size()-1;i>1;std::swap(s[rand()%i+1],s[--i]));return s;}

int main(){
    for(int i = 0; i<100; ++i)
    std::cout<<f("letters")<<std::endl;
}

```

# Edit

Realised there is no need to random both swap indexes, saved a variable and a few more characters.
> 6 votes

# Answer
## Perl - 96 (or 71) characters 84 (or 59) characters

This is what I came up with in Perl. Went through a few different ways to do it but this seemed shortest from what I can think of so far, at 97 characters.

```
use List::Util 'shuffle';sub r{($b,@w)=split//,$_[0];$e=pop(@w);return$b.join('',shuffle@w).$e;}

```

Though, if you cut out the 'use' line (which I guess is valid, since others excluded #include lines in their C programs) I can cut it down further to **71 characters**:

```
sub r{($b,@w)=split//,$_[0];$e=pop(@w);return$b.join('',shuffle@w).$e;}

```

**EDIT** It was suggested that I try doing this implementing @tobius' method. This way I got it down to **84 characters**, or by removing the *use* line, **59 characters**:

```
use List::Util 'shuffle';sub r{$_[0]=~m/(.)(.+)(.)/;$1.join'',shuffle split//,$2.$3}

```
> 6 votes

# Answer
# php (68 characters)

```
$r=preg_replace('/^(\w)(\w+)(\w)$/e','$1.str_shuffle($2).$3',trim($w));

```

# shorter (60 characters)

```
$r=preg_replace('/(.)(.+)(.)/e','$1.str_shuffle($2).$3',$w);

```
> 6 votes

# Answer
**Ruby 1.9, 77 48 46 44 chars**

```
r=->w{w[h=1..-2]=[*w[h].chars].shuffle*"";w}

```

Disclaimer: I tuned this based on the highest ranked answer - noticed the exact same answer later on. You can check the history that I have kept true to my original idea but changed from ruby 1.8 to ruby 1.9 for short lambdas and `shuffle`.

If empty words are allowed then 56 54 chars

```
r=->w{w.empty?||w[h=1..-2]=[*w[h].chars].shuffle*"";w}

```
> 5 votes

# Answer
## Ruby, 77 75 characters

```
def r(s);f=s.size-2;1.upto(f){|i|x=rand(f)+1;t=s[i];s[i]=s[x];s[x]=t};s;end

```

My Scala solution in a slightly less verbose language. I'm not a Ruby expert by any means, so there's probably room for improvement.
> 5 votes

# Answer
# Python 3, ~~94~~ ~~93~~ 91 characters

Using a different technique. Might also work in Python 2.

```
from random import*
s=lambda x:x[0]+''.join(sample(x[1:-1],len(x)-2))+x[-1]if x[0:-1]else x

```

The `... if x[0:-1] else x` gives `x` if its length is 1 (otherwise it would be duplicated). The function thereby works for strings of length 0 and 1.

The `sample()` is from https://stackoverflow.com/questions/2668312/shuffle-string-in-python/2668366#2668366.

Since it's one expression, we can use a `lambda` (eliminating `return`, `def`, and a pair of parentheses).

**Edit:** `from random import*` to save 1 character, after the other Python submission.
> 5 votes

# Answer
# JavaScript - 118 122 125 chars

Uses approximately the same algorithm as the OP, but with less chaining. I tried a lot of recursion, and I tried some iteration, but they all tend to get bogged down in some way or another.

```
function s(w){w=w.split('');var a=w.shift(),z=w.pop();return z?a+(w.sort(function(){return Math.random()-.5}).join(''))+z:a;}

```

Ungolfed:

```
function s(w)
{
    w = w.split('');
    var a = w.shift(),
        z = w.pop();
    return z?a + (w.sort(function() { return Math.random() - .5}).join('')) + z:a;
}

```
> 4 votes

# Answer
## D, 62 chars

```
import std.random;void s(char[] s){randomShuffle(s[1..$-1]);}

```

okay I cheated with a normal char array instead of a real string (which is immutable char\[\] so no in-place shuffling)

**edit** with a length check it requires 14 more

```
import std.random;void s(char[] s){if(s.length>1)randomShuffle(s[1..$-1]);}

```
> 4 votes

# Answer
## php 5.3 (60 chars)

```
$r=!$w[2]?:$w[0].str_shuffle(substr($w,1,-1)).substr($w,-1);

```

**Improved to 56 chars and no longer requires version 5.3:**

```
$r=substr_replace($w,str_shuffle(substr($w,1,-1)),1,-1);

```
> 4 votes

# Answer
**Python, 86 chars**

Slnicig is safe, so no bnouds ckhnceig is neeacrssy. Wkros on all leghtns.

```
from random import*
def f(x):x=list(x);t=x[1:-1];shuffle(t);x[1:-1]=t;return''.join(x)

```
> 4 votes

# Answer
## Scala, 135 139 142 156 characters

```
def r(s:String)={var(x,o,t,f)=(0,s.toArray,' ',s.size-2)
for(i<-1 to f){t=o(i)
x=util.Random.nextInt(f)+1
o(i)=o(x)
o(x)=t}
o.mkString}

```

-7: removed ':String' (return type can be inferred)
-7: removed 'return ' (last expression is the return value)
-3: factored `s.size-2` out
-4: `toCharArray` -\> `toArray`
> 3 votes

# Answer
**Perl - 111 characters (without using any library function)**

```
sub r{($f,@w)=split//,shift;$l=pop@w;while(@w){if(rand(9)>1){push@w,shift@w}else{push@t,pop@w}}join'',$f,@t,$l}

```

Usage:

```
$in="randomizethis";
$out = &r($in);
print "\nout: $out";
sub r{($f,@w)=split//,shift;$l=pop@w;while(@w){if(rand(9)>1){push@w,shift@w}else{push@t,pop@w}}join'',$f,@t,$l}

```
> 3 votes

# Answer
# Python

It's 90 89 112 characters of python!

## Edit 1: as a function this time!

(thanks gnibbler)

## Edit 2: now handles short words

(thanks user unknown)
```
import random as r
def q(s):
 a=list(s)
 b=a[1:-1]
 r.shuffle(b)
 if len(s)<4:
  return s
 return a[0]+''.join(b)+a[-1]

```
> 3 votes

# Answer
# C++11: - 68 66 chars

```
auto f=[&](){if(s.size()>2)random_shuffle(s.begin()+1,s.end()-1);};

```

full program:

```
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[]){

  string s = "SomestrinG";
  auto f=[&](){if(s.size()>2)random_shuffle(s.begin()+1,s.end()-1);};

  f();
  cout << s << endl;
  return 0;
}

```
> 3 votes

# Answer
# Python - 76 characters

```
import random as r
def f(w):m=list(w)[1:-1];r.shuffle(m);return w[0]+''.join(m)+w[-1]

```
> 3 votes

# Answer
## R, 104 (126)

```
f=function(w){s=strsplit(w,"")[[1]];paste(c(s[1],sample(s[2:(length(s)-1)]),s[length(s)]),collapse="")}

```

Usage:

```
for (i in 1:10) print(f("parola"))
[1] "plraoa"
[1] "prolaa"
[1] "praola"
[1] "parloa"
[1] "plaora"
[1] "palroa"
[1] "porlaa"
[1] "ploraa"
[1] "porlaa"
[1] "ploraa"

```

the below function works with words with length less than 3:

```
f=function(w){s=strsplit(w,"")[[1]];ifelse(length(s)<3,w,paste(c(s[1],sample(s[2:(length(s)-1)]),s[length(s)]),collapse=""))}

f("pl")
[1] "pl"
f("a")
[1] "a"

```
> 3 votes

# Answer
# R, ~~95~~ ~~92~~ 91 characters

```
f=function(w,a=el(strsplit(w,'')),b=length(a))cat(a[1],sample(a[c(1,b)],b-2),a[b],sep="")

```

Makes use of R's lazy evaluation to compute a and b as function parameters, saving space with re-use later on. Also unlike other R answer this works for all words \>1 char long. Example below:

```
> f("hippopotamus")
hpuoopaitmps

> f("dog")
dog

> f("az")
az

```

Edit:  ~~Replaced `unlist()` with `[[]]`~~  Replaced \[\[1\]\] with el()
> 3 votes

# Answer
# Erlang, 188 172 132 chars

```
f([H|C=[_|_]])->T=[lists:last(C)],[H|s(C--T,T)];f(X)->X. s([],N)->N;s(D,N)->E=[lists:nth(random:uniform(length(D)),D)],s(D--E,E++N).

```

I'm still learning Erlang so any tips on making this shorter are appreciated.

full code(string\_shuffle module):

```
-module(string_shuffle).
-export([f/1]).

f([H|C=[_|_]])->
    T=[lists:last(C)],
    [H|s(C--T,T)];f(X)->X.
f(X)->X.

s([],N)->N;
s(D,N)->
    E=[lists:nth(random:uniform(length(D)),D)],
    s(D--E,E++N).

```

## Edit

Took the shuffle part out as a seperate function which no longer requires the head and tail of the list to be passed around.

## Edit 2

Restructured to remove one of the `f`function patterns, changed the shuffle function to accept only two parameters, changed `lists:delete` for `--[]`, swapped a `lists:reverse` call for a `lists:last`
> 2 votes

# Answer
# D: 55 characters

```
void f(T)(T s){if(s.length>2)randomShuffle(s[1..$-1]);};

```

full program:

```
import std.stdio, std.random, std.conv;

void f(T)(T s){if(s.length>2)randomShuffle(s[1..$-1]);};

void main(){

  char[] s = to!(char[])("SomestrinG");

  f(s);
  writeln(s);
}

```
> 2 votes

# Answer
## PowerShell, 93

```
filter x{if($_.length-lt3){$_}else{$_[0,-1]-join-join($_[1..($a=$_.Length-2)]|random -c $a)}}

```

Look, double-join~~t~~ed code!
> 2 votes

# Answer
# C#, 128

```
static string r(string w){var t="";while(w.Length>1){int n=new Random().Next(1,w.Length-1);t+=w[n];w=w.Remove(n,1);}return w+t;}

```
> 2 votes

# Answer
## Scala: 94

```
def r(w:String)=if(w.size<2)w else w(0)+util.Random.shuffle(w.tail.init.toSeq).mkString+w.last

```

This is a riff on "user unknowns" answer. Since a String can be implicitly cast to a Seq of chars, we can leverage Seq methods to access the middle and end of the String.
> 2 votes

# Answer
# Groovy, 75

```
r={w->w.size()<3?w:w[0]+w[1..-2].toList().sort{Math.random()}.join()+w[-1]}

assert r('a') == 'a'
assert r('it') == 'it'
assert r('cap') == 'cap'

for(x in 1..10) {
    def w = r('Honorificabilitudinitatibus')
    println w
    assert w.size()==27 && w[0]=='H' && w[26]=='s'
}

```
> 2 votes

# Answer
# Q, 38 48

{((*:)x),((-1*(#:)a)?a:-1\_1\_x),last x}

Had to change it for words \<=3 letters

```
{$[3<(#)x;((*:)x),((-1*(#:)a)?a:-1_1_x),-1#x;x]}

```
> 2 votes

# Answer
## MATLAB (46 Characters)

```
f=@(x)[x(1) x(randperm(length(x)-2)+1) x(end)]

```

Sample Usage:

```
>> f('elephant')

ans =

eplhnaet

>> f('imawesomebutyousuck')

ans =

iouesutuoeswbamycmk

```

Works with words size two or greater.
> 2 votes

# Answer
## APL (Dyalog), 34 Charachters

Still trying to golf it a bit more, new to APL. Tips appreciated.

```
y←(⍴x←⍞)-2⋄x[1],x[1+⍳y][y?y],x[⍴x]

```

Here is an attempt to explain it, I also simplified it a bit (no charachter improvement, though)

is a statement separator, think of it as a new line.

That leaves us with 2 statements. `y←(⍴x←⍞)-2` and `x[1],x[1+⍳y][y?y],x[⍴x]`

APL works from right to left in statements, but follows parentesis still, so `(⍴x←⍞)` is executed first.  takes charachter input.  assigns that to `x` and  gives the length of `x`. Then the `-2` is executed, which subtracts 2 from the length of `x`. Finally, the length-2 is assigned to `y` and we move on to the next statement.

`x[⍴x]` takes the last character of `x`, think of it as `x[x.length]` (using the length as the index of the last character).

`,` is catenate.

So we concatenate the last character of `x` with `x[1+⍳y][y?y]` which takes the middle indices of `x` using `2+⍳y` and applies a randomization using `[y?y]`.

`⍳y` generates `1 2 3 ... y` and `1+` turns this into `2 3 4 ... y+1` which are the middle indices of x, for example, this returns `bcdef` from `abcdefg`.

`[y?y]` "deals" y values from 1 to y.

So, `x[1+⍳y][y?y]` grabs the middle of the word and randomizes it.

Finally, we concatenate the first charachter of `x` using `x[1],` to the rest of the string, and that is the output of the program.

Hopefully that was understandable...
> 2 votes

# Answer
# J, 25

```
(]/:0,((2-~#)?1-~#),1-~#)

```

Example:

```
      (]/:0,((2-~#)?1-~#),1-~#) 'order'
oedrr
      (]/:0,((2-~#)?1-~#),1-~#) 'order'
oerdr
      (]/:0,((2-~#)?1-~#),1-~#) 'order'
oderr
      (]/:0,((2-~#)?1-~#),1-~#) 'order'
odrer
      (]/:0,((2-~#)?1-~#),1-~#) 'order'
oerdr
      (]/:0,((2-~#)?1-~#),1-~#) 'order'
oerdr

```
> 2 votes

# Answer
# CJam, 15 bytes

CJam is younger than this challenge, so this submission is not eligible for being accepted. This submission assumes that a "word" contains at least one character (I've requested clarification from the OP).

```
{(\_W>\W<mr\++}

```

This defines a block, the equivalent of an unnamed function in CJam.

Test it here.

If full programs (STDIN to STDOUT) are also acceptable, it can be solved in 12 bytes:

```
l(\_W>\W<mr\

```

Test it here.

## Explanation

```
(             "Slice off first character and push it on the stack.";
 \            "Swap with remaining string.";
  _W>         "Duplicate and truncate to last character.";
     \W<      "Swap with other copy and slice off last character.";
        mr    "Shuffle.";
          \   "Swap with last character.";
           ++ "Concatenate the three parts back together.";

```

Note that `_W>\W<` could in principle be shortened to `)\` (which I had originally). However, this fails when the string is empty at that point, i.e. when it originally contained less than 2 characters.

For the full program, we read the input with `l` first, and we can omit the `++` since the contents of the stack are printed at the end of the program automatically, back to back.
> 2 votes

# Answer
# Python 3, 80 chars

This is an improvement on Ashley Grenon's answer. By removing variable assignments and using `random.sample` instead of `random.shuffle`, so you don't have to explicitly call `list()`, I saved 4 characters. This one still fails on strings less than 2 characters.

```
import random as r
def f(w):return w[0]+''.join(r.sample(w[1:-1],len(w)-2))+w[-1]

```
> 2 votes

# Answer
# Ruby, 39 characters

```
->s{a,*b,c=s.chars;[a,*b.shuffle,c]*''}

```
> 2 votes

# Answer
## Python, 102 characters

```
def f(x):t=list(x)[1:-1];k='';exec'k+=t.pop(id(7)%len(t));'*len(t);return[x[0],x[0]+k+x[-1]][len(x)>1]

```

No imports! Works for words 1 character and above. This is my first golf entry and I was inspired by BlueEyedBeast's entry from Shortest code to produce non-deterministic output for the idea of using **id(Object)**.

---

**Explanation:** It makes a list of letters from the input excluding the first and last, and repeatedly pops from this list and appends to a new one until empty. The index it pops from is id(7) % len(list we're popping from). Since id(7) is the memory address of the object 7, it is essentially random. So now we have a list of randomly scrambled letters from the center of the original input. All we do now is append the first and last letters of the original output accordingly and we got the output we want: (first letter)+(scrambled middle)+(last letter).
> 2 votes

# Answer
## Perl, 41 bytes

**40 bytes code + 1 for `-n`.**

```
$\=chop;s/.//;print"$&",sort{rand 2}/./g

```

Requires input to be supplied without a newline (`echo -n ...`) as we use `chop` to move the last char into `$\` (which is appended after all arguments to `print`) and we `sort`, applying `0` or `1` (`rand 2`) to each character. This appears to result in all permutations given enough time. The `$&` has to be in quotes, as it changes after the `/./g` is executed, interpolating into a string works around this. Also `print` has to be used instead of `say` to utilise `$\` :(.

### Usage

```
echo -n 'stringified' | perl -ne '$\=chop;s/.//;print"$&",sort{rand 2}/./g'
sifirgtined

for i in `seq 1 20`; do echo -n 'stringified' | perl -ne '$\=chop;s/.//;print"$&",sort{rand 2}/./g'; echo; done
segfiiintrd
sitnrigfied
stringified
srtinigfied
sginitrefid
strnigieifd
seriftniigd
sifertniigd
siirtngfied
sintrgieifd
snitrigefid
sfgieinirtd
sigitrnifed
sefiirtingd
sirtnigifed
sifgenritid
srtingiifed
siignrteifd
sefiigtrind
sifneirtigd

```
> 2 votes

# Answer
# Taxi, 1344 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Pickup a passenger going to Post Office.[B]Switch to plan C if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Narrow Path Park.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n.Go to Sunny Skies Park:w 2 l.Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan B.[C]Go to Narrow Path Park:n 1 l 1 r 1 l.Switch to plan H if no one is waiting.Pickup a passenger going to Joyless Park.Go to Joyless Park:e 1 r 3 l.Go to Narrow Path Park:w 1 r 3 l.[D]Switch to plan E if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 l 1 r 2 l.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n.Go to Firemouth Grill:w 1 l 2 r 3 r.Go to Sunny Skies Park:w 1 l 1 r 1 r.Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.Switch to plan D.[E]Go to Firemouth Grill:e 1 r 4 r.[F]Switch to plan G if no one is waiting.Pickup a passenger going to Post Office.Go to Fueler Up:e 1 l.Go to Post Office:s 1 r 1 l.Go to Firemouth Grill:n 1 l.Switch to plan F.[G]Go to Joyless Park:e 1 l 3 r.Pickup a passenger going to Post Office.Go to Post Office:w 1 l 1 r 1 l.[H]Go to Post Office:e 1 r 4 r 1 l.

```

Try it online!

Try it online with linebreaks!

Errors out by having the boss fire me if the string is 1 character, and by being unable to drive in the current direction otherwise. Don't you just love programs that exit uncleanly like that?

`Firemouth Grill` is one of two destinations in Townsville that offer randomness. It is like any of the three parks in that any number of passengers can be dropped off for later, but they are picked up in a random and unspecified order. This destination alone does the main part of our job, so the only other thing to do is make sure we're only doing this to the characters in the middle.
> 2 votes

# Answer
# Powershell, 81 bytes

Inspired by Joey: I like her double join.

```
$args|%{($_,($_[0,-1]-join-join($_[1..($a=$_.Length-2)]|random -c 2e9)))[$a-ge2]}

```

Notable changes:

1. `if else` replaced with a Fake ternary operator.
2. `$_.Length` is written once.
3. Other golf to compact the script
4. The script gets `Random` for the word length \>= 4 only.
5. `random -c $a` replaced with `random -c 2e9`. It need to avoid an exception with word length \<= 2. I think the length = `2000000000` is enough for a word.

Test script:

```
$f = {

$args|%{($_,($_[0,-1]-join-join($_[1..($a=$_.Length-2)]|random -c 2e9)))[$a-ge2]}

}

&$f ""
&$f a
&$f ab
&$f abc
&$f abcd
&$f randomize
&$f reading
&$f Hello
&$f world

```

Output:

```
a
ab
abc
acbd
rmaniodze
rniedag
Hlelo
wrlod

```
> 2 votes

# Answer
# Vyxal, 5 bytes

```
ÞẇṖ℅j

```

Try it Online!

```
Þẇ    # Push (first+last, rest)
  Ṗ℅  # Shuffle (rest)
    j # Join (first+last) by (rest)

```
> 2 votes

# Answer
# C# w/Linq - 152 non-whitespace chars.

It's terrible compared to other languages on char count, but elegant:

```
public string Shuf(string i)
{
    return new String(i.Take(1)
        .Concat(i.Skip(1).Take(i.Length-2).OrderBy(x=>Guid.NewGuid()))
        .Concat(new[]{i.Last()})
        .ToArray());
}

```
> 1 votes

# Answer
# FSharp, ~207 177

Count includes whitespace since its significant for f#

```
let f w=
 let r=System.Random()
 let e = Seq.length w
 (w|>Seq.mapi(fun i l->if i=0||i=e-1 then i,l else r.Next(1,e-1),l)|>Seq.sortBy fst|>Seq.map snd|>List.ofSeq).ToString()

```

Run with:

```
printfn "%s" (f "apples")

```
> 1 votes

# Answer
## Java, 194 charcters

```
String r(String s){String[]c=s.split("");if(c.length>2)java.util.Collections.shuffle(java.util.Arrays.asList(c).subList(2,c.length-1));return(""+java.util.Arrays.asList(c)).replaceAll("\\W","");}

```

If you can assume `java.util.*` is imported, then you can shave off a fair amount of characters. Might be able to squeeze in a `List` variable to save a few more. If the class the `r` function is implemented in derives from `java.util.Arrays`, then even more characters can be saved.
> 1 votes

# Answer
## Scala: 112  123

```
def v(s:String)=if(s.size<4)s else s(0)+util.Random.shuffle(s.substring(1,s.size-1).toList).mkString+s(s.size-1)

```

Incorporated hints from the comments (length-\>size (I need this hint every time), `mkString` without `("")`) and size-1, not -2). Thanks.
> 1 votes

# Answer
## Lua, 173 chars

Does what it needs to do.

```
function(a)return(a:gsub('(%w)(%w*)(%w)',function(a,b,c)t={}for l in b:gmatch'.'do t[#t+1]=l end while #t>0 do i=math.random(#t)a=a..table.remove(t,i)end return a..c end))end

```
> 1 votes

# Answer
## Haskell, 195

```
import Random
import Data.List
r l=fmap(f l.g l)newStdGen
f l n=map snd$head$filter(\l->map fst l==n)$permutations$zip[0..]l
g l=take(n+2).(0:).(++[n+1]).take n.nub.randomRs(1,n)where n=length l-2

```

Hacked this into existence while Rotsor was making his post. This will cover all possible permutations, and I believe it does so uniformly.

The function `r` is the function that the user uses.

The algorithm is fairly straightforward. It generates a random list of unique numbers from 1 to n-2. Then it tacks on 0 to the front and n-1 to the end of the list. The `take(n+2)` is there to handle the case where the input is a single character (or an empty string for that matter). Then it searches for the corresponding permutation and returns that.

The list is generated by generating an infinite list of random numbers from 1 to n-2. Then it picks out the first occurance of each number in that range.
> 1 votes

# Answer
## Javascript, 202 characters

```
function r(s){var s=s.split(""),h=[-1],n=s.length-1,t,i;h[-1]=s[0];for(i=0;++i<n;){do{t=Math.random()}while(t in h);h[t]=s[i];h[i]=t;}h.sort();for(i=0;i<n;++i)h[i]=h[h[i]];return n?h.join("")+s[n]:s[0]}

```

This solution has an unbiased distribution.

### Algorithm:

Split input string into an array `s`. Consider another array `h` that is doubly used as a dictionary. For each letter in `s` at index 0 \< `i` \< `s.length-1`, assign a unique random number to `h` at `i`. Also map the random number in the range \[0, 1) in `h` to the letter. The first and last letters are handled specially. Before assigning the random numbers as described above, do the analogous thing for the first letter, but hard code the number as -1 (guaranteed to be less than the smallest random number generated, which can be 0). Ignore the last letter for now. Sort `h`. Map `h`'s random value to the corresponding letter. Join the array into a string and tack on the last letter. Special case for 1 character input, where we return the first character (we still crunch `h` because the logic is shorter that way).
> 1 votes

# Answer
## Perl - 76 chars

Pure Perl implementation that requires no external modules. Also correctly handles one-letter, two-letter word edge cases.

```
sub r{@a=split//,pop;@a>1?join'',@a[0,(sort{rand()<=>rand}1..$#a-1),$#a]:@a}

```

---

### Usage

```
say r('stringified') for 1 .. 20;

# Example output

srfgiietnid
sgfnieiitrd
seiifgrtnid
siigrfeintd
sgiirntiefd
siigerniftd
sifiitgnred
sftrneiiigd
sfieirtngid
sfeitirgnid
sfiertnigid
sigteifrind
sgieftirnid
sieitfrnigd
stnigirfeid
sfietrniigd
siigfrenitd
stefrniiigd
setrfiniigd
sifgtiernid

```

---

**N.B.** I'm not entirely convinced that the letter randomization still renders the word readable in the example above
> 1 votes

# Answer
# JavaScript 132 characters:

```
function r(w){return w.substr(0,1)+w.substr(1,w.length-2).split('').sort(function(){return Math.random()-.5}).join('')+w.substr(-1)}

```

You don't need to go through point by point. If provided a function which returns something where Math.round will return a random 0,1,-1, that will be sufficient (because of how sort works).
> 1 votes

# Answer
# VBA, 128 177 151 chars

I know this is an older puzzle, but I wanted to add my two cents from

```
Sub o(s)
n=Left(s,1)
p=Len(s)-1
s=Right(s,p)
For i=1 To p-1
p=p-1
r=Int(p*Rnd()+1)
n=n & Mid(s,r,1)
s=Left(s,r-1) & Right(s,p-r+1)
Next
s=n & s
End Sub

```

Example Usage:

```
a = "According"
o a ' a is assigned by the passing of the reference to the 'o' sub.
a = "to"
o a ' see above...
a = "some"
o a
a = "controversial"
o a
a = "story"
o a

```

I was actually happily surprised to see it fare as well as it did against some of the other, more typical CG languages. After improving, this is still not the shortest, but I was happy to do it.
> 1 votes

# Answer
## MATLAB, 65 47 characters

```
r=@(s)s([3-min(end,2):1 randperm(end-2)+1 end])

```

Works for strings of positive length, but fails on the empty string. Improved by using `end` as in jazzkingrt's solution.

This use of `end` can further improve jazzkingrt's solution by substituting `end` for `length(x)`. However, that solution doesn't handle strings of length one correctly. (I'm not allowed to comment, so I write here instead.)
> 1 votes

# Answer
## Q (42 Characters)

```
{(x[0]),((neg count 1_-1_x)?1_-1_x),-1#x}

```

Sample Usage:

```
q){(x[0]),((neg count 1_-1_x)?1_-1_x),-1#x} "elephant"
"eeahlnpt"
q){(x[0]),((neg count 1_-1_x)?1_-1_x),-1#x} "ant"
"ant"

```
> 1 votes

# Answer
# Mathematica 98 chars

Not the most economical code but fun to write.

`s` holds the input sentence (as a string).

```
Row[StringJoin @@@ (Characters@# /. {f_, m___, e_} :>
   Flatten@{f, RandomSample@{m}, e} & /@ StringSplit@s), " "]

```

For example, when \`s = "This sentence is fairly easy to read.",
> 1 votes

# Answer
## TinyMUSH, 102

```
&_ me=left(%0,1)[ifelse(eq(strlen(%0),1),,scramble(mid(%0,1,sub(strlen(%0),2)))[right(%0,1)])]
\u(_,X)

```

Replace "X" with the input word. The user-defined _ attribute uses the built-in scramble() function to scramble letters between the first and last letters.
> 1 votes

# Answer
# Clip, 24

```
?<lxWx],*R>%Ox{(x)x`(x)x

```

Here's an effective translation in pseudocode:

```
x = input by stdin
if len(x) < 2:
  output x
else:
  y = rotate_right(x, 1)
  y.remove_first_occurrence(first(x), last(x))
  # y is now the characters between the first and last of the input.
  shuffle(y)
  output place_at_end(last(x), place_at_beginning(first(x), y))

```
> 1 votes

# Answer
# Rebol - 63

```
f: func[s][e: take/last s ajoin trim reduce[take s random s e]]

```

Ungolfed:

```
f: func [s] [
    e: take/last s
    ajoin trim reduce [take s random s e]
]

```

Usage example:

```
>> f "1"
== "1"

>> f "12"
== "12"

>> f "123"
== "123"

>> f "1234"
== "1324"

```

NB. An alternative (but unfortunately not shorter) version would be:

```
f: func [s] [
    change/part next s random copy/part next s back tail s back tail s
    s
]

```

With golfing and minor shavings this would come out at 73 chars.
> 1 votes

# Answer
# MATLAB, 48 bytes

```
function t=f(t)
t(2:end-1)=t(randperm(end-2)+1);

```

Too bad the spec says 'function', using `input()` would be 43 bytes. Another version, that will fail slightly on a one-length word (`a` becomes `aa`), is 34 bytes:

```
f=@(t)t([1 randperm(end-2)+1 end])

```
> 1 votes

# Answer
# Pyth - 11 bytes

Pyth is younger than this challenge so it doesn't count.

```
pez+hz.SPtz

```

Gets middle, shuffles it, then adds the rest. Takes I/O from stdout/stdin.

```
pez+hz      Print First letter of input, something else, and last letter of input
 .S         Shuffle
  P         All but the last
   t        All but the first
    z       The input

```
> 1 votes

# Answer
# Coffee-script: 76 91 Bytes

```
f=(a)->a.length>1&&a[0]+(a.split('')[1..-2].sort ()->.5-Math.random()).join('')+a[-1..]||a

```

Wow, I like this language already.
> 1 votes

# Answer
## \>\<\>, 40 bytes

```
_5l)?vl1-[&r02.
} .32<
x{|$!
/r]&
>l?!;o

```

Try it here!
> 1 votes

# Answer
# PHP 7.1, 54 bytes

If the word has less than 4 letters, don´t shuffle:

```
$r=$w[3]?$w[0].str_shuffle(substr($w,1,-1)).$w[-1]:$w;

```
> 1 votes

# Answer
# \>\<\>, 19 bytes

```
{o&v
?vo>xl2(
&<oo{

```

Try it online!

Works for words of less than 3 length.
> 1 votes

# Answer
# , ~~93~~ 79 bytes

```
function(x,l=nchar(x))"if"(l<4,x,intToUtf8(utf8ToInt(x)[c(1,sample(l-2)+1,l)]))

```

Try it online!

Wroks for any ipnut szie dwon to zero, by frsit ckciheng the lgnteh of the sintrg and rneturing it if `nchar(x)<4`

-14 bytes thanks to Giuseppe!
> 1 votes

# Answer
# Python 3, 75 73 bytes

Thanks to @WW for saving me 2 bytes

```
lambda x:x[0]+''.join(sample(x[1:-1],len(x)-2))+x[-1]
from random import*

```

Try it online!
> 1 votes

# Answer
## JavaScript, 102 bytes

```
(_,a=[..._].slice(1,-1))=>_.replace(/./g,(m,i)=>(l=a.length,!i||!l?m:a.splice(~~(Math.random()*l),1)))

```

Try it online!

Using spread syntax and `.slice()` create array from input string beginning at index `1` through `-1`, `.splice()` elements from array within `.replace()` callback function, return string.
> 1 votes

# Answer
# APL(NARS), 52 chars, 104 bytes

```
∇r←s w;x
r←,w⋄→0×⍳3≥⍴w⋄r←(↑w),x[?⍨⍴x←¯1↓1↓w],¯1↑w
∇

```

This 'solution' is based to the fact that 3?3 return a random permutation of 1 2 3;
6?6 a random permutation of 1 2 3 4 5 6 ecc n?n a random permutation of 1 2 .. n so if B is a string B\[(⍴B)?⍴B\] would be a string random permutation of B. The function 's' has to have as input one string and return one string or ''. If someone see some error, please to say, thank you.

test:

```
  ⎕fmt s¨'' 'w' 'my' 'the' 'this' 'this' 'this'
┌7────────────────────────────────────────────┐
│┌0┐ ┌1─┐ ┌2──┐ ┌3───┐ ┌4────┐ ┌4────┐ ┌4────┐│
││ │ │ w│ │ my│ │ the│ │ tihs│ │ this│ │ this││
│└¯┘ └──┘ └───┘ └────┘ └─────┘ └─────┘ └─────┘2
└∊────────────────────────────────────────────┘
  s¨'random' 'random' 'random' 'random'
rdonam rodanm raodnm rodnam
  s 'permutation'
ptaemutroin

```
> 1 votes

# Answer
## JavaScript, 93 bytes

```
(_,[a,[...b],c,d=b.sort(_=>Math.random()-.5).join``]=_.match(/(^.)|[^\1]+(?=.$)|.$/g))=>a+d+c

```

Try it online!

Using `.match()` with regular expression `/(^.)|[^\1]+(?=.$)|.$/g` to match first character, one or more characters that at not the first character followed by one character and end of string, and character followed by end of string and `.sort()` approach used at the question.
> 1 votes

# Answer
# Javascript 98 bytes

```
a=>{c=l=a.length-1;for(b=[a[0]];--c;)d=Math.random()*99|0,b[d]?c++:b[d]=a[c];return b.join``+a[l]}

```

Try it online!

This assigns each letter other than the first and last to a random array index, and then joins the array into a string. `99` can be changed to `9e9` to work on (much!) longer words at the cost of a byte, but then join takes almost a minute. Besides, there aren't many words that even approach 100 characters.

Because of that, this is 12 bytes shorter (86 bytes) and works almost every time:

```
a=>{c=l=a.length-1;for(b=[a[0]];--c;)b[Math.random()*9e9|0]=a[c];return b.join``+a[l]}

```
> 1 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

```
g≠ićs¨.rIθJ

```

Try it online or verify some more inputs.

Fun **~~12~~ 11 bytes** alternative:

```
gÍ¸1.ø£€.rJ

```

Try it online or verify some more inputs.

Both version also work for strings with less than 3 characters. The first one could be just `ćs¨.rIθJ` (**8 bytes**), but then it doesn't work for single-character strings (`"a"` becomes `"aa"`).

**Explanation:**

```
g              # Take the length of the (implicit) input
               #  i.e. "howaboutthis" → 12
               #  i.e. "a" → 1
 ≠i            # If this length is not 1:
               #   i.e. 12 → 1 (truthy)
               #   i.e. 1 → 0 (falsey)
   ć           #  Extract the head of the (implicit) input
               #   i.e. "howaboutthis" → "owaboutthis" and "h"
    s          #  Swap so the list (minus head) is at the top of the stack again
     ¨         #  Remove the last character
               #   i.e. "owaboutthis" → "owaboutthi"
      .r       #  Randomly shuffle the characters
               #   i.e. "owaboutthi" → "oohbtwtiua"
        Iθ     #  Take the last character of the input
               #   i.e. "howaboutthis" → "s"
          J    #  Join the values on the stack together (and output implicitly)
               #   i.e. "h", "oohbtwtiua", "s" → "hoohbtwtiuas"
               # (Implicit else)
               #  (Output the input as is implicitly)
               #   i.e. "a"

```

---

```
g              # Take the length of the (implicit) input
               #  i.e. "howaboutthis" → 12
               #  i.e. "a" → 1
 Í             # Subtract 2
               #  i.e. 12 → 10
               #  i.e. 1 → -1
  ¸            # Wrap it into a list
               #  i.e. 10 → [10]
               #  i.e. -1 → [-1]
   1.ø         # Surround it with 1s
               #  i.e. [10] → [1,10,1]
               #  i.e. [-1] → [1,-1,1]
      £        # Split the (implicit) input into parts of that size
               #  i.e. "howaboutthis" and [1,10,1] → ["h","owaboutthi","s"]
               #  i.e. "a" and [1,-1,1] → ["a","",""]
       €       # Map each value to:
        .r     #  Randomly shuffle the characters
               #   i.e. ["h","owaboutthi","s"] → ["h","oohbtwtiua","s"]
               #   i.e. ["a","",""] → ["a","",""]
          J    # Join the values in the list together (and output implicitly)
               #  i.e. ["h","oohbtwtiua","s"] → "hoohbtwtiuas"
               #  i.e. ["a","",""] → "a"

```
> 1 votes

# Answer
# Pyth, 18 bytes

```
KhQ=Z>1Q++KO.pPtQZ

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 22 bytes

```
{,/0N?'(0 1,1|#1_x)_x}

```

Try it online!

hat-tip ovf from the array programming discord / matrix for this answer!

Takes a single word to shuffle/randomize.

* `(...)_x` `cut` `x` (the input) on the indices from `(...)`, returning a three-item list containing the first element, the middle element(s), and the last element
    + `(0 1,1|#1_x)` generate a three-item list equivalent to `[0, 1, max(1, len(x)-1)]`. taking the max with 1 ensures single-character strings (e.g. `,"a"`) are handled as well.
* `0N?'` `shuffle` each slice; this is a no-op on empty and one-character strings
* `,/` flatten the shuffled slices into a single string and (implicitly) return it
> 1 votes

# Answer
# APL, 27 bytes

```
{3≥⍴⍵:⍵⋄⍵[⍋0,(?⍨2-⍨⍴⍵),⍴⍵]}

```
> 1 votes

# Answer
# JavaScript, 81 bytes

```
s=>s.length<4?s:s[0]+[...s.slice(1,-1)].sort(_=>Math.random()>.5).join``+s.at(-1)

```

Try it:

```
f=s=>s.length<4?s:s[0]+[...s.slice(1,-1)].sort(_=>Math.random()>.5).join``+s.at(-1)

;[
  '',
  '1',
  '12',
  '123',
  '1234',
  '12345',
  '123456',
  '1234567',
  '12345678',
  '123456789',
].forEach(s=>console.log(f(s)))
```

# JavaScript, 4 bytes

```
s=>s

```

It is funny but in real the chance to randomly sort the symbols position in string and get the same string is equal to get the another string. And this is not depend on how many times we will randomize the symbols in string. It may seem like something unreal, but that's the way it is :)

To understand it more easy way imagine that we must generate a number by generating random digits. Let's say we have to get a number of length `n`. We have `10` digits, so in each position the chance of any digit is \\$\frac{1}{10}\\$ so the total chance to get the any number with length of `n` is \\$(\frac{1}{10})^n\\$. So the chance to get the number `8888888888888888...8888` randomly is the same as the chance to get `9872346897621449...0467`. It is important to understand that the probability of the next digit is independent of the previous generated digit
> 1 votes

# Answer
# C (gcc), 71 bytes

Look mom, I beat python!

```
f(s,d)char*s;{for(;s[2];)if(d=rand()%~-strlen(++s))*s^=s[d]^=*s^=s[d];}

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `j`, 10 bytes

```
Dḣ?Ṫsḣµr$h

```

Attempt This Online!

#### Explanation

```
Dḣ?Ṫsḣµr$h  # Implicit input
D           # Duplicate the input
 ḣ          # Pop one copy and check if it's length is more than 1
  ?         # If that's true:
   Ṫ        #  Remove the last character and push it separately
    s       #  Swap so the last character is below the rest of the string
     ḣ      #  Discard the first character from this string
      µr    #  Randomly shuffle the string
        $h  #  Push the first character of the input again
            # Implicit output of joined stack

```
> 1 votes

# Answer
# Python - ~~103~~ ~~96~~ ~~90~~ ~~88~~ ~~85~~ 109 characters

```
import random as r
def s(x):
 if len(x)>3:y=list(x[1:-1]);r.shuffle(y);return x[0]+''.join(y)+x[-1]
 return x

```

props to @dr jimbob for the "import as" bit and for catching my non-conformance with the spec. props also to @user unknown for getting the spec clarified.

**Edit**: updated to conform to short-words spec.
> 0 votes

# Answer
# Go, ~~154~~ 132 bytes

```
import."math/rand"
func f(S string)(e string){k:=S[1:len(S)-1]
for _,i:=range Perm(len(k)){e+=k[i:i+1]}
return S[:1]+e+S[len(S)-1:]}

```

Attempt This Online!

* -22 bytes from `rand.Perm`, using string slices, and named return.
> 0 votes

# Answer
# , 18 bytes

```
({~>:,~0,1+?~)_2+#

```

Try it online!

Constructs random indexes for the interior, prepends 0, appends n-1, then uses all those to index into the input.
> 0 votes

# Answer
# GolfScript, 26 bytes

```
(:f;):l;{;9rand}$f l@\]''+

```

Try it online!
> 0 votes

# Answer
# Zsh +coreutils, 73 bytes

```
for n;printf $n[1]$(fold -1<<<${n:1:-1}|shuf|tr -d \\n)${n:$#n-1:$#n-1}\

```

Try it online! ~~78bytes~~ ~~85bytes~~ ~~92bytes~~

Incidentally, the Zsh documentation mixes up the descriptions of flags. `F` splits, `f` joins.
> 0 votes

---
Tags: code-golf, string, random
---