答:
Javascript (ES6), 63 bytes

a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')
```
<p>Takes input as an array of strings.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>F=a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')

input.oninput = update;
update();

function update() {
  try {
    output.innerHTML = F(input.value.trim().split`
`);
  } catch(e) {
    output.innerHTML = 'ERROR: INVALID INPUT';
  }
}</code>```

textarea {
  width: 100%;
  box-sizing: border-box;
  font-family: monospace;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Input:</h2>
<textarea id="input" rows="8">
a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</textarea>
<hr />
<h2>Output:</h2>
<pre id="output">
``````

Body:
Javascript (ES6), 63 bytes

a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')

Takes input as an array of strings.

F=a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')

input.oninput = update;
update();

function update() {
  try {
    output.innerHTML = F(input.value.trim().split`
`);
  } catch(e) {
    output.innerHTML = 'ERROR: INVALID INPUT';
  }
}

textarea {
  width: 100%;
  box-sizing: border-box;
  font-family: monospace;
}

<h2>Input:</h2>
<textarea id="input" rows="8">
a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</textarea>
<hr />
<h2>Output:</h2>
<pre id="output">
</pre>


问:
Parse the comments out of my esoteric code
Earlier this week, we learned about how to format esoteric languages for commenting. Today, we're going to do the inverse of that. I need you to write a program or function that parses some well-commented esoteric code and parses the comments out, returning just the code. Using some examples from the previous challenge, here is what well-commented code looks like:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

Here is what you need to do to extract the code out. First, remove the comment character (#), the space before it, and everything after the comment character.

```<code>a
 bc
   d
    e
     fgh
        ij
          k
           l
            mn
              op
</code>```

Then, collapse each line upwards into a single line. For example, since b is in the second column on line two, once we collapse it up, it will be in the second column on line one. Similarly, c will be put in the third column of line one, and d will be put on the fourth. Repeat this for every character, and you get this:

```<code>abcdefghijklmnop
</code>```

Important note: It seems like the trivial solution is to just remove the comments, remove every space, and join every line. This is not a valid approach! Because the original code might have spaces in it, these will get stripped out with this approach. For example, this is a perfectly valid input:

```<code>hello         #Line one
              #Line two
       world! #Line three
</code>```

And the corresponding output should be:

```<code>hello  world!
</code>```

The Challenge:

Write a program or function that takes commented code as input, and outputs or returns the code with all the comments parsed out of it. You should output the code without any trailing spaces, although one trailing newline is permissible. The comment character will always be #, and there will always be one extra space before the comments start. # will not appear in the comment section of the input. In order to keep the challenge simpler, here are some inputs you do not have to handle:

You can assume that the code will not have two characters in the same column. For example, this is an input that violates this rule:

```<code>a  #A character in column one
bc #Characters in columns one and two
</code>```

You can also assume that all comment characters appear in the same column. For example, this input:

```<code>short       #this is a short line
      long        #This is a long line
</code>```

violates this rule. This also means that # will not be in the code section.

And lastly, you do not have to handle code sections with leading or trailing spaces. For example,

```<code>  Hello,          #
         World!   #
</code>```

You may also assume that the input only contains printable ASCII characters.

Examples:

```<code>Input:
hello         #Line one
              #Line two
       world! #Line three

Output:
hello  world!

Input:
E                                                   #This comment intentionally left blank
 ac                                                 #
   h s                                              #
      ecti                                          #
          on is                                     #
                one c                               #
                     haracte                        #
                            r longer                #
                                     than the       #
                                              last! #

Output:
Each section is one character longer than the last!

Input:
4          #This number is 7
 8         #
  15       #That last comment is wrong.
    16     #
      23   #
        42 #

Output:
4815162342

Input:
Hello                     #Comment 1
      world               #Comment 2
           ,              #Comment 3
             how          #Comment 4
                 are      #Comment 5
                     you? #Comment 6

Output:
Hello world, how are you?

Input:
Prepare                               #
        for...                        #
                        extra spaces! #

Output:
Prepare for...          extra spaces!
</code>```

You may take input in whatever reasonable format you like, for example, a list of strings, a single string with newlines, a 2d list of characters, etc. The shortest answer in bytes wins!

答:
sed, 126 bytes

```<code>:a;N;$!ba;s,#[^\n]*\n,#,g;s,^,#,;:;/#[^ ]/{/^# /s,^# *,,;t;H;s,#.,#,g}
t;/#[^ ]/!{H;s,#.,#,g};t;g;s,\n#(.)[^\n]*,\1,g;s,...$,,
</code>```

Requires a newline at the end of the input.

I'm sure I can golf this a little more, but I'm just happy it works for now.

ContentLicense: CC BY-SA 3.0

Body:
sed, 126 bytes

:a;N;$!ba;s,#[^\n]*\n,#,g;s,^,#,;:;/#[^ ]/{/^# /s,^# *,,;t;H;s,#.,#,g}
t;/#[^ ]/!{H;s,#.,#,g};t;g;s,\n#(.)[^\n]*,\1,g;s,...$,,

Requires a newline at the end of the input.

I'm sure I can golf this a little more, but I'm just happy it works for now.


问:
Decode the chmod

Challenge

Given a three digit octal permissions number, output the permissions that it grants.

chmod

On UNIX OSes file permissions are changed using the chmod command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions.

The three digits in the permissions number represent a different person:

The first digit represents the permissions for the user

The second digit represents the permissions for the group

The last digit represents the permissions for others

Next, each digit represents a permission as shown below in:

```<code>Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None
</code>```

Input

The input will be the three digit number as a string, e.g.:

```<code>133
</code>```

or

```<code>007
</code>```

This will be passed either via STDIN or via function arguments.

Output

Your output should be the different permissions for each of the user, the group and the others. You must display this information like so:

```<code>User:   ddd
Group:  ddd
Others: ddd
</code>```

Where there are three spaces after User, two spaces after Group and one space after Others. You replace ddd with the permissions information.

Your output may be to STDOUT or as a returned string.

Examples

Input: 666

Output:

```<code>User:   Read and Write
Group:  Read and Write
Others: Read and Write
</code>```

Input: 042

Output:

```<code>User:   None
Group:  Read only
Others: Write only
</code>```

Input: 644

Output:

```<code>User:   Read and Write
Group:  Read only
Others: Read only
</code>```

Winning

The shortest code in bytes wins.

答:
C# 214 Bytes

```<code>string h(string y){string e="Execute ",r="Read ",w="Write ",O="Only",a="and ";var z=new[]{"None",e+O,w+O,w+a+e,r+O,r+a+e,r+a+w,r+w+a+e};return$"User:   {z[y[0]-'0']}\nGroup:  {z[y[1]-'0']}\nOthers: {z[y[2]-'0']}";}
</code>```

Title: Decode the chmod

Body:
C# 214 Bytes

string h(string y){string e="Execute ",r="Read ",w="Write ",O="Only",a="and ";var z=new[]{"None",e+O,w+O,w+a+e,r+O,r+a+e,r+a+w,r+w+a+e};return$"User:   {z[y[0]-'0']}\nGroup:  {z[y[1]-'0']}\nOthers: {z[y[2]-'0']}";}


问:
Implementing bool() without any conditionals
Title says it all. Given some input, turn it into a boolean value (0 or 1), without using conditional statements (e.x. == > < <= >= != ~=), or any function which uses conditional statements within its implementation, such as if, while and for. Your program must work with floating points, although you get more if it works with other items.

A general rule for determining whether bool(item) is False is if the item is empty ('' is an empty string, [] is an empty list.), or if the function used to turn an item of one type into another is given no input (in Python, str() returns '', list() returns [].)

Here are (some of) the different valid types. Your program is considered to work with one type if it works with one item in the following lists:

Integers, floating points, doubles, longs

Strings

Lists, tuples, arrays (bytearrays)

Dictionaries

Functions

Objects/Classes

Program score will be calculated like this: [# of characters]-(50*[# of types]). The program with the smallest score wins the challenge.

答:
MMIX (8 bytes assembled)

Assembly language has no statements.

```<code>bool    ZSNZ $0,$0,1
        POP  1,0
</code>```

Body:
MMIX (8 bytes assembled)

Assembly language has no statements.

bool    ZSNZ $0,$0,1
        POP  1,0


答:
PHP ,199 Bytes

```<code>foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo str_pad("\n$u:",9).join(" ",$a);}
</code>```

PHP ,189 Bytes with \t

```<code>foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo"\n$u:\t".join(" ",$a);}
</code>```

Title: Decode the chmod

Body:
Challenge

Given a three digit octal permissions number, output the permissions that it grants.

chmod

On UNIX OSes file permissions are changed using the chmod command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions.

The three digits in the permissions number represent a different person:

The first digit represents the permissions for the user

The second digit represents the permissions for the group

The last digit represents the permissions for others

Next, each digit represents a permission as shown below in:

```<code>Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None
</code>```

Input

The input will be the three digit number as a string, e.g.:

```<code>133
</code>```

or

```<code>007
</code>```

This will be passed either via STDIN or via function arguments.

Output

Your output should be the different permissions for each of the user, the group and the others. You must display this information like so:

```<code>User:   ddd
Group:  ddd
Others: ddd
</code>```

Where there are three spaces after User, two spaces after Group and one space after Others. You replace ddd with the permissions information.

Your output may be to STDOUT or as a returned string.

Examples

Input: 666

Output:

```<code>User:   Read and Write
Group:  Read and Write
Others: Read and Write
</code>```

Input: 042

Output:

```<code>User:   None
Group:  Read only
Others: Write only
</code>```

Input: 644

Output:

```<code>User:   Read and Write
Group:  Read only
Others: Read only
</code>```

Winning

The shortest code in bytes wins.

Body:
PHP ,199 Bytes

foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo str_pad("\n$u:",9).join(" ",$a);}

PHP ,189 Bytes with \t

foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo"\n$u:\t".join(" ",$a);}


答:
PHP, <s>169</s> 159 bytes

```<code>foreach([User,Group,Others]as$i=>$u){echo"
$u: ";for($n=[5,33,34,66,35,67,131,531][$i]];$n;$n>>=3)echo["and",Execute,Write,Read,only,None][$n&7]," ";}
</code>```

takes string as command line argument: php -r '' <argument>,

prints a leading newline instead of a trailing one

Thanks to Jörg for pointing out my bugs - and for the \t.

PHP, 169 bytes

with the new restriction: (tab character forbidden)

```<code>foreach(['User:  ','Group: ','Others:']as$i=>$u){echo"
$u";for($n=[5,33,34,66,35,67,131,531][$argv[1][$i]];$n;$n>>=3)echo' ',['and',Read,Write,Execute,only,None][$n&7];}
</code>```

This is 1 byte shorter than with str_pad, because of the additional blank it would require.

breakdown

```<code>foreach([User,Group,Others]as$i=>$u)
{
    echo"\n$u:\t";                      // print newline, who, blanks
    for($n=[5,33,34,66,35,67,131,531]   // octal values for words indexes
        [$argv[1][$i]]                  // (last word=highest digit)
        ;$n;$n>>=3)                     // while value has bits left
        echo['and',Execute,Write,Read,only,None][$n&7]," "; // print that word
}
</code>```

To create the array for $n, use this:

```<code>$b=[[5],[1,4],[2,4],[2,0,1],[3,4],[3,0,1],[3,0,2],[3,2,0,1]];
foreach($b as$i=>$a){for($v=$j=0;$a;$j+=3)$v+=array_shift($a)<<$j;echo"$v,";}
</code>```

Title: Decode the chmod

Body:
PHP, <s>169</s> 159 bytes

foreach([User,Group,Others]as$i=>$u){echo"
$u: ";for($n=[5,33,34,66,35,67,131,531][$i]];$n;$n>>=3)echo["and",Execute,Write,Read,only,None][$n&7]," ";}

takes string as command line argument: php -r '<code>' <argument>,

prints a leading newline instead of a trailing one

Thanks to Jörg for pointing out my bugs - and for the \t.

PHP, 169 bytes

with the new restriction: (tab character forbidden)

foreach(['User:  ','Group: ','Others:']as$i=>$u){echo"
$u";for($n=[5,33,34,66,35,67,131,531][$argv[1][$i]];$n;$n>>=3)echo' ',['and',Read,Write,Execute,only,None][$n&7];}

This is 1 byte shorter than with str_pad, because of the additional blank it would require.

breakdown

foreach([User,Group,Others]as$i=>$u)
{
    echo"\n$u:\t";                      // print newline, who, blanks
    for($n=[5,33,34,66,35,67,131,531]   // octal values for words indexes
        [$argv[1][$i]]                  // (last word=highest digit)
        ;$n;$n>>=3)                     // while value has bits left
        echo['and',Execute,Write,Read,only,None][$n&7]," "; // print that word
}

To create the array for $n, use this:

$b=[[5],[1,4],[2,4],[2,0,1],[3,4],[3,0,1],[3,0,2],[3,2,0,1]];
foreach($b as$i=>$a){for($v=$j=0;$a;$j+=3)$v+=array_shift($a)<<$j;echo"$v,";}


问:
Can the number reach 1 by repeatedly subtracting the largest prime less than it?

Challenge:

Given a number, take the largest prime strictly less than it, subtract it from this number, do this again to this new number with the biggest prime less than it, and continue doing this until it's less than 3. If it reaches 1, your program should output a truthy value, else, the program should output a falsey value.

Examples:

All of these should give a truthy value:

```<code>3
4
6
8
10
11
12
14
16
17
18
20
22
23
24
26
27
29
30
32
34
35
37
38
40
41
42
44
46
47
48
50
</code>```

All of these should give falsey values:

```<code>5
7
9
13
15
19
21
25
28
31
33
36
39
43
45
49
</code>```

Rules:

You can either write a program or function.

You can assume that the input is bigger than 2.

Standard loopholes apply

This is code-golf so the shortest answer wins!

答:
Python 2.7: 88 87 Bytes

```<code>r=lambda n:n>2and r(n-[a for a in range(2,n)if all(a%b for b in range(2,a))][-1])or n<2
</code>```

Thx @TuukkaX for -1 more byte!

Body:
Python 2.7: 88 87 Bytes

r=lambda n:n>2and r(n-[a for a in range(2,n)if all(a%b for b in range(2,a))][-1])or n<2

Thx @TuukkaX for -1 more byte!


问:
Esolang-Comment-Template-Generator
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```<code>abcdefghijklmnop
</code>```

And this languages uses # for comments, they would write an explanation like this:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```<code>a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (|) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```<code>"a|bc|d|e|fgh|ij|k|l|mn|op", "#"
</code>```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```<code>"Hello|World", "/"
</code>```

The first section of code is "Hello" and the second is "World". So it should give the output:

```<code>Hello      /
     World /
</code>```

Here are some more samples:

```<code>Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @
</code>```

Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is code-golf, so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

答:
CJam, 32 bytes

```<code>l'|/_s,)L@{1$,S*\+}%@f{Se]}lN+f+
</code>```

Explanation

```<code>l                                  get code string
 '|/                               split into code parts
    _s,)                           length of all the parts +1
        L@{1$,S*\+}%               left pad spaces to every part for the length of the previous parts
                    @f{Se]}        right pad spaces
                           lN+f+   add comment character and newline
</code>```

Try it online

ContentLicense: CC BY-SA 4.0

Title: Esolang-Comment-Template-Generator

Body:
CJam, 32 bytes

l'|/_s,)L@{1$,S*\+}%@f{Se]}lN+f+

Explanation

l                                  get code string
 '|/                               split into code parts
    _s,)                           length of all the parts +1
        L@{1$,S*\+}%               left pad spaces to every part for the length of the previous parts
                    @f{Se]}        right pad spaces
                           lN+f+   add comment character and newline

Try it online


问:
Source code GO!
Let's use augmented reality to hunt small creatures hidden in source-code. Write a quine program that outputs its own code source, except for 5 consecutive characters that will be modified and that will display a PCG-mon : (^_^)

The 5 consecutive characters can be positioned anywhere in the source code (from position 0 to n-5, n being the source code length). The source code must have a minimum length of 5 characters. The string (^_^) or any of its substring of length >=2 must not appear in initial source code, only in output.

Example of valid submission:

source code my source code, output my (^_^)e code

Invalid:

source code (^_^) copy;, output (^_^) (^_^)

Winning criteria

The shortest code in bytes wins.

答:
Go (golang), 131 bytes

This challenge must have an answer in Go!

```<code>package main;import"fmt";func main(){a:="package main;import\"fmt\";func(%c_%[1]c)(){a:=%q;fmt.Printf(a,94,a)}";fmt.Printf(a,94,a)}
</code>```

Try it online!

Title: Source code GO!

Body:
Go (golang), 131 bytes

This challenge must have an answer in Go!

package main;import"fmt";func main(){a:="package main;import\"fmt\";func(%c_%[1]c)(){a:=%q;fmt.Printf(a,94,a)}";fmt.Printf(a,94,a)}

Try it online!


问:
Shuffle a mapping
We define a map as a set of key-value pairs.  For this challenge, you need to take each of the values and assign them to a randomly chosen key.

You must randomly shuffle the values, and output the resulting map.  This means that each time we run your program, we have a chance of getting a different output

Each possible permutation of the values must have a non-zero chance of appearing.

All of the original keys and original values must appear in the resulting array.  Repeated values must appear the same number of times in the resulting array.

For example, if your map was:

```<code>[0:10, 1:10, 5:5]
</code>```

all of the following must have a chance of appearing:

```<code>[0:10, 1:10, 5:5]  (original map)
[0:10, 1:5,  5:10]
[0:10, 1:10, 5:5]  (technically the same map, but I swapped the two tens)
[0:10, 1:5,  5:10]
[0:5,  1:10, 5:10]
[0:5,  1:10, 5:10]
</code>```

Acceptable input/outputs:

Your languages' native map

You can input an array of key-value pairs.  You may not input 2 arrays, one with keys, the other with values.

You can use a string representation of any the above

If you input an array or a map, you can modify the original object instead of returning

The input type must match the output type

If you input an array, the order of the keys must be maintained.

You can assume that the keys are unique, but you cannot assume that values are unique.

This is a code-golf, so answer as short as possible

答:
Brachylog, <s>13</s> 12 bytes

```<code>zt@~T,?zh:Tz
</code>```

Try it online!

Expects a list of 2-element lists as input.

Explanation

```<code>z              Zip the input to get a list of keys and a list of values
 t@~T,         Take the list of values, and shuffle it ; call that T
      ?zh      Zip the input to get the list of keys
         :Tz   Zip the list of keys with the list of shuffled values
</code>```

Title: Shuffle a mapping

Body:
Brachylog, <s>13</s> 12 bytes

zt@~T,?zh:Tz

Try it online!

Expects a list of 2-element lists as input.

Explanation

z              Zip the input to get a list of keys and a list of values
 t@~T,         Take the list of values, and shuffle it ; call that T
      ?zh      Zip the input to get the list of keys
         :Tz   Zip the list of keys with the list of shuffled values


答:
CJam, 9 bytes

```<code>{z)mra+z}
</code>```

Input is a list of key-value pairs.

Test it here.

Explanation

```<code>z  e# Zip, to separate keys from values.
)  e# Pull off values.
mr e# Shuffle them.
a+ e# Append them to the array again.
z  e# Zip, to restore key-value pairs.
</code>```

Alternative solution, same byte count:

```<code>{[z~mr]z}
</code>```

Title: Shuffle a mapping

Body:
We define a map as a set of key-value pairs.  For this challenge, you need to take each of the values and assign them to a randomly chosen key.

You must randomly shuffle the values, and output the resulting map.  This means that each time we run your program, we have a chance of getting a different output

Each possible permutation of the values must have a non-zero chance of appearing.

All of the original keys and original values must appear in the resulting array.  Repeated values must appear the same number of times in the resulting array.

For example, if your map was:

```<code>[0:10, 1:10, 5:5]
</code>```

all of the following must have a chance of appearing:

```<code>[0:10, 1:10, 5:5]  (original map)
[0:10, 1:5,  5:10]
[0:10, 1:10, 5:5]  (technically the same map, but I swapped the two tens)
[0:10, 1:5,  5:10]
[0:5,  1:10, 5:10]
[0:5,  1:10, 5:10]
</code>```

Acceptable input/outputs:

Your languages' native map

You can input an array of key-value pairs.  You may not input 2 arrays, one with keys, the other with values.

You can use a string representation of any the above

If you input an array or a map, you can modify the original object instead of returning

The input type must match the output type

If you input an array, the order of the keys must be maintained.

You can assume that the keys are unique, but you cannot assume that values are unique.

This is a code-golf, so answer as short as possible

Body:
CJam, 9 bytes

{z)mra+z}

Input is a list of key-value pairs.

Test it here.

Explanation

z  e# Zip, to separate keys from values.
)  e# Pull off values.
mr e# Shuffle them.
a+ e# Append them to the array again.
z  e# Zip, to restore key-value pairs.

Alternative solution, same byte count:

{[z~mr]z}


问:
print 1 to 100 without using recursion and conditions
can we print 1 to 100 without using any if conditions and loops in c&c++?

Conditon:
main point is you must not use recursion...and doesnt hardcode code in it
for e.g

print(1 2 3..etc);

答:
85

C (gcc)

```<code>#define c printf("%d ",i++);
#define b c c c c c
#define a b b b b b
main(i){a a a a}
</code>```

Assuming no command line arguments were passed.

Body:
85

C (gcc)

#define c printf("%d ",i++);
#define b c c c c c
#define a b b b b b
main(i){a a a a}

Assuming no command line arguments were passed.


答:
Python 3, 107 bytes

Uses Python's native dictionary structure.

Thanks to @mbomb007 for saving a byte.

from random import*
def f(d,o={}):
 i=list(d.values());shuffle(i)
 for k in d.keys():o[k]=i.pop()
 return o
```

Ideone it!

Title: Shuffle a mapping

Body:
Python 3, 107 bytes

Uses Python's native dictionary structure.

Thanks to @mbomb007 for saving a byte.

from random import*
def f(d,o={}):
 i=list(d.values());shuffle(i)
 for k in d.keys():o[k]=i.pop()
 return o

Ideone it!


答:
05AB1E, 5 bytes

Input is a list of key-value pairs.

```<code>ø       # zip into a list of keys and one of values
 `      # flatten
  .r    # randomize the values
    ø   # zip back again into a list of key-value pairs.
</code>```

Try it online!

Title: Shuffle a mapping

Body:
05AB1E, 5 bytes

Input is a list of key-value pairs.

ø       # zip into a list of keys and one of values
 `      # flatten
  .r    # randomize the values
    ø   # zip back again into a list of key-value pairs.

Try it online!


答:
Mathematica, 32 bytes

```<code>{#,RandomSample@#2}&@@(#)&
</code>```

Input is a list of key-value pairs.  is Mathematica's transposition operator, and RandomSample can be used to shuffle a list.

Title: Shuffle a mapping

Body:
Mathematica, 32 bytes

{#,RandomSample@#2}&@@(#)&

Input is a list of key-value pairs.  is Mathematica's transposition operator, and RandomSample can be used to shuffle a list.


答:
Jelly, 5 bytes

```<code>Ṫ€Ẋṭ"
</code>```

Try it online!

Explanation

```<code>Ṫ€Ẋṭ"  Input: list of [k, v] pairs
Ṫ€     Pop and return the last element of each k-v pair (modifies each list)
  Ẋ    Shuffle the list of v's
   ṭ"  Append each v back to a k and return
</code>```

Title: Shuffle a mapping

Body:
Jelly, 5 bytes

Ṫ€Ẋṭ"

Try it online!

Explanation

Ṫ€Ẋṭ"  Input: list of [k, v] pairs
Ṫ€     Pop and return the last element of each k-v pair (modifies each list)
  Ẋ    Shuffle the list of v's
   ṭ"  Append each v back to a k and return


答:
C#, 322 337 348 bytes

That's for sure not the shortest version, but I tried solving this problem using bitwise operators since the chmod values are actually bit flags. Also C# is probably not the best golfing language :D

string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");return a.Count>1?string.Join(" ",a.Take(a.Count-1))+" and "+a.Last():a.Count>0?a.First()+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]-'0')));}
```

<p>ungolfed: (with comments)</p>

<pre class="lang-cs prettyprint-override"><code>string P(string s)
{
    // Function that determines the permissions represented by a single digit (e.g. 4 => "Read only")
    Func<int, string> X = p =>
    {
        var a = new List<string>();         // temporary storage for set permissions
        if ((p & 4) > 0) a.Add("Read");     // Read bit set
        if ((p & 2) > 0) a.Add("Write");    // Write bit set
        if ((p & 1) > 0) a.Add("Execute");  // Execute bit set

        // actually just Output formatting ... Takes a lot of bytes *grr*
        return a.Count > 1
            ? string.Join(" ", a.Take(a.Count - 1)) + " and " + a.Last()
            : a.Count > 0
                ? a.First() + " only"
                : "none";
    };

    // Actual result:
    return string.Join("\n", (new[] { "User:   ", "Group:  ", "Others: " })
        .Select((c, i) => c + X(s[i] - '0'))); // Map "User, .." to its permissions by using above function
}
</code>```

This is my first time code golfing, so please tell me, if I did anyting wrong :)

EDIT 1:

Saved some bytes by replacing s[i]-'0' by s[i]&7 (at the very end) and saving list count into variable:

string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}
```

<h1>EDIT 2:</h1>

<p>Changed to lambda expression:</p>

<pre class="lang-cs prettyprint-override"><code>s=>{Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}
</code>```

Title: Decode the chmod

Body:
C#, 322 337 348 bytes

That's for sure not the shortest version, but I tried solving this problem using bitwise operators since the chmod values are actually bit flags. Also C# is probably not the best golfing language :D

string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");return a.Count>1?string.Join(" ",a.Take(a.Count-1))+" and "+a.Last():a.Count>0?a.First()+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]-'0')));}

ungolfed: (with comments)

string P(string s)
{
    // Function that determines the permissions represented by a single digit (e.g. 4 => "Read only")
    Func<int, string> X = p =>
    {
        var a = new List<string>();         // temporary storage for set permissions
        if ((p & 4) > 0) a.Add("Read");     // Read bit set
        if ((p & 2) > 0) a.Add("Write");    // Write bit set
        if ((p & 1) > 0) a.Add("Execute");  // Execute bit set

        // actually just Output formatting ... Takes a lot of bytes *grr*
        return a.Count > 1
            ? string.Join(" ", a.Take(a.Count - 1)) + " and " + a.Last()
            : a.Count > 0
                ? a.First() + " only"
                : "none";
    };

    // Actual result:
    return string.Join("\n", (new[] { "User:   ", "Group:  ", "Others: " })
        .Select((c, i) => c + X(s[i] - '0'))); // Map "User, .." to its permissions by using above function
}

This is my first time code golfing, so please tell me, if I did anyting wrong :)

EDIT 1:

Saved some bytes by replacing s[i]-'0' by s[i]&7 (at the very end) and saving list count into variable:

string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}

EDIT 2:

Changed to lambda expression:

s=>{Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}


问:
Is it a Bumpy Word?
(inspired by this challenge over on Puzzling -- SPOILERS for that puzzle are below, so stop reading here if you want to solve that puzzle on your own!)

If a letter in a word occurs alphabetically later than the previous letter in the word, we call that a rise between the two letters. Otherwise, including if it's the same letter, it's called a fall.

For example, the word ACE has two rises (A to C and C to E) and no falls, while THE has two falls (T to H and H to E) and no rises.

We call a word Bumpy if the sequence of rises and falls alternates. For example, BUMP goes rise (B to U), fall (U to M), rise (M to P). Note that the first sequence need not be a rise -- BALD goes fall-rise-fall and is also Bumpy.

The challenge

Given a word, output whether or not it's Bumpy.

Input

A word (not necessarily a dictionary word) consisting of ASCII alphabet ([A-Z] or [a-z]) letters only, in any suitable format.

Your choice if the input is all uppercase or all lowercase, but it must be consistent.

The word will be at least 3 characters in length.

Output

A truthy/falsey value for whether the input word is Bumpy (truthy) or not Bumpy (falsey).

The Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Truthy:

```<code>ABA
ABB
BAB
BUMP
BALD
BALDY
UPWARD
EXAMINATION
AZBYCXDWEVFUGTHSIRJQKPLOMN
</code>```

Falsey:

```<code>AAA
BBA
ACE
THE
BUMPY
BALDING
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

```<code># [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=93005,OVERRIDE_USER=42963;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
05AB1E, 9 bytes

```<code>SÇ¥0›¥_O_
</code>```

Explanation

```<code>SÇ          # convert to list of ascii values
  ¥         # take delta's
   0›       # check if positive, giving a list of 1's and 0's
            # if they alternate, the word is bumpy
     ¥      # take delta's again, if we have any 0's in the list the word is not bumpy
      _     # logical negation, turning 0 into 1 and everything else to 0
       O    # sum, producing 0 for a bumpy word and 1 for a non-bumpy word
        _   # logical negation, inverting the previous 1 into 0 and vice versa
</code>```

Try it online!

Title: Is it a Bumpy Word?

Body:
05AB1E, 9 bytes

SÇ¥0›¥_O_

Explanation

SÇ          # convert to list of ascii values
  ¥         # take delta's
   0›       # check if positive, giving a list of 1's and 0's
            # if they alternate, the word is bumpy
     ¥      # take delta's again, if we have any 0's in the list the word is not bumpy
      _     # logical negation, turning 0 into 1 and everything else to 0
       O    # sum, producing 0 for a bumpy word and 1 for a non-bumpy word
        _   # logical negation, inverting the previous 1 into 0 and vice versa

Try it online!


答:
Mathematica, 211 bytes

```<code>{r,w,e,o,a}={"Read ","Write ","Execute ","only ","and "};""<>Transpose@{{"User:   ","Group:  ","Others: "},"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}][[#]]&/@IntegerDigits[#,10,3],"\n"&~Array~3}&
</code>```

A straightforward implementation (probably easily beatable): doesn't compute anything, just hard-codes each possible output. Input is an integer; outputs each line with a trailing space, and a trailing newline overall.

IntegerDigits[#,10,3] gives the three digits of the input (even if there are leading zeros). Each digit indicates an argument of the "function"

```<code>"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}]
</code>```

with 0 indicating the function name itself. ""<> concatenates all the strings in a list (of lists). "\n"&~Array~3 produces the three newlines.

Title: Decode the chmod

Body:
Mathematica, 211 bytes

{r,w,e,o,a}={"Read ","Write ","Execute ","only ","and "};""<>Transpose@{{"User:   ","Group:  ","Others: "},"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}][[#]]&/@IntegerDigits[#,10,3],"\n"&~Array~3}&

A straightforward implementation (probably easily beatable): doesn't compute anything, just hard-codes each possible output. Input is an integer; outputs each line with a trailing space, and a trailing newline overall.

IntegerDigits[#,10,3] gives the three digits of the input (even if there are leading zeros). Each digit indicates an argument of the "function"

"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}]

with 0 indicating the function name itself. ""<> concatenates all the strings in a list (of lists). "\n"&~Array~3 produces the three newlines.


答:
05AB1E, <s>89</s> 87 bytes

```<code>”‚Ý:‚Ù:ˆ†:”ð¡v”Šª0ÍÃ20‡í20‡í1ÍÃ0‚Ø20‚Ø1ÍÃ0‚Ø1‡í0‚Ø‡í1ÍÃ”2ð'€É«:1ð'€ƒ«:0ð«¡¹Nèèð3N-×ìyì,
</code>```

<s>Summons the Cthulhu encoding.</s> Uses the CP-1252 encoding. Try it online!

Title: Decode the chmod

Body:
Challenge

Given a three digit octal permissions number, output the permissions that it grants.

chmod

On UNIX OSes file permissions are changed using the chmod command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions.

The three digits in the permissions number represent a different person:

The first digit represents the permissions for the user

The second digit represents the permissions for the group

The last digit represents the permissions for others

Next, each digit represents a permission as shown below in:

```<code>Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None
</code>```

Input

The input will be the three digit number as a string, e.g.:

```<code>133
</code>```

or

```<code>007
</code>```

This will be passed either via STDIN or via function arguments.

Output

Your output should be the different permissions for each of the user, the group and the others. You must display this information like so:

```<code>User:   ddd
Group:  ddd
Others: ddd
</code>```

Where there are three spaces after User, two spaces after Group and one space after Others. You replace ddd with the permissions information.

Your output may be to STDOUT or as a returned string.

Examples

Input: 666

Output:

```<code>User:   Read and Write
Group:  Read and Write
Others: Read and Write
</code>```

Input: 042

Output:

```<code>User:   None
Group:  Read only
Others: Write only
</code>```

Input: 644

Output:

```<code>User:   Read and Write
Group:  Read only
Others: Read only
</code>```

Winning

The shortest code in bytes wins.

Body:
05AB1E, <s>89</s> 87 bytes

”‚Ý:‚Ù:ˆ†:”ð¡v”Šª0ÍÃ20‡í20‡í1ÍÃ0‚Ø20‚Ø1ÍÃ0‚Ø1‡í0‚Ø‡í1ÍÃ”2ð'€É«:1ð'€ƒ«:0ð«¡¹Nèèð3N-×ìyì,

<s>Summons the Cthulhu encoding.</s> Uses the CP-1252 encoding. Try it online!


答:
Python 3.5 - <s>370</s> <s>294</s> 243 bytes

Golfed:

```<code>import sys
a=lambda o: [print(('User:  ','Group: ','Others:')[n],('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')[int(o[n])]) for n in range(0,3)]
a(sys.argv[1])
</code>```

Size check:

```<code>$ du -b OctalToHuman.py
243     OctalToHuman.py
</code>```

Un-golfed:

```<code>#!/usr/bin/env python3
from sys import argv as ARGS

types = ('User:  ', 'Group: ', 'Others:')
perms = ('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')

def convert(octal_string):
    for n in range(0,3):
        print(types[n], perms[int(octal_string[n])])

if __name__ == '__main__':
    convert(ARGS[1])
</code>```

Sample output:

```<code>$ python ./OctalToHuman.py 666
User:   Read and Write
Group:  Read and Write
Others: Read and Write
</code>```

```<code>$ python ./OctalToHuman.py 042
User:   None
Group:  Read only
Others: Write only
</code>```

```<code>$ python ./OctalToHuman.py 644
User:   Read and Write
Group:  Read only
Others: Read only
</code>```

Title: Decode the chmod

Body:
Python 3.5 - <s>370</s> <s>294</s> 243 bytes

Golfed:

import sys
a=lambda o: [print(('User:  ','Group: ','Others:')[n],('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')[int(o[n])]) for n in range(0,3)]
a(sys.argv[1])

Size check:

$ du -b OctalToHuman.py
243     OctalToHuman.py

Un-golfed:

#!/usr/bin/env python3
from sys import argv as ARGS

types = ('User:  ', 'Group: ', 'Others:')
perms = ('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')

def convert(octal_string):
    for n in range(0,3):
        print(types[n], perms[int(octal_string[n])])

if __name__ == '__main__':
    convert(ARGS[1])

Sample output:

$ python ./OctalToHuman.py 666
User:   Read and Write
Group:  Read and Write
Others: Read and Write

$ python ./OctalToHuman.py 042
User:   None
Group:  Read only
Others: Write only

$ python ./OctalToHuman.py 644
User:   Read and Write
Group:  Read only
Others: Read only


答:
C 71 70

Assuming the ? operator is allowed.

```<code>#define f(a)a a a a a
int main(i){f(f(f(printf(i<102?"%d ":0,i++);)))}
</code>```

Edit: ""->0

If ? is too similar to an if statement, then use this instead (78)

```<code>#define f(a)a a a a
#define g(a)f(a)a
int main(i){f(g(g(printf("%d ",i++);)))}
</code>```

Title: print 1 to 100 without using recursion and conditions

Body:
can we print 1 to 100 without using any if conditions and loops in c&c++?

Conditon:
main point is you must not use recursion...and doesnt hardcode code in it
for e.g

print(1 2 3..etc);

Body:
C 71 70

Assuming the ? operator is allowed.

#define f(a)a a a a a
int main(i){f(f(f(printf(i<102?"%d ":0,i++);)))}

Edit: ""->0

If ? is too similar to an if statement, then use this instead (78)

#define f(a)a a a a
#define g(a)f(a)a
int main(i){f(g(g(printf("%d ",i++);)))}


答:
C# <s>307</s> <s>241</s> 210 bytes

string X(string s){var z="User:  ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');return string.Join("\n",s.Zip(z,(a,b)=>b+z[a-45].Aggregate("",(x,y)=>x+" "+z[y-37])));}

Formatted

```<code>string X(string s)
{
    var z = "User:  ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');
    return string.Join("\n", s.Zip(z, (a, b) => b + z[a - 45].Aggregate("", (x, y) => x + " " + z[y - 37])));
}
</code>```

Title: Decode the chmod

Body:
C# <s>307</s> <s>241</s> 210 bytes

string X(string s){var z="User:  ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');return string.Join("\n",s.Zip(z,(a,b)=>b+z[a-45].Aggregate("",(x,y)=>x+" "+z[y-37])));}

Formatted

string X(string s)
{
    var z = "User:  ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');
    return string.Join("\n", s.Zip(z, (a, b) => b + z[a - 45].Aggregate("", (x, y) => x + " " + z[y - 37])));
}


答:
Clojure, <s>40</s> 34 bytes

```<code>#(zipmap(keys %)(shuffle(vals %)))
</code>```

Takes the keys and values from m (a map), shuffles the values and zips them up into a map.

Title: Shuffle a mapping

Body:
Clojure, <s>40</s> 34 bytes

#(zipmap(keys %)(shuffle(vals %)))

Takes the keys and values from m (a map), shuffles the values and zips them up into a map.


问:
Bubble sorting in progress
Create a function or program that takes two inputs:

A list of integers that shall be sorted (less than 20 elements)

A positive integer, N, saying how many comparisons you should take

The function shall stop, and output the resulting list of integers after N comparisons. If the list is fully sorted before N comparisons are made, then the sorted list should be outputted.

The Bubble sort algorithm is well known, and I guess most people know it. The following Pseudo-code and animation (both from the linked Wikipedia-article) should provide the necessary details:

```<code>procedure bubbleSort( A : list of sortable items )
   n = length(A)
   repeat
     swapped = false
     for i = 1 to n-1 inclusive do
       /* if this pair is out of order */
       if A[i-1] > A[i] then
         /* swap them and remember something changed */
         swap( A[i-1], A[i] )
         swapped = true
       end if
     end for
   until not swapped
end procedure
</code>```

The animation below shows the progress:

An example (taken directly from the linked Wikipedia article) shows the steps when sorting the list: ( 5 1 4 2 8 ):

First Pass

```<code>1: ( 5 1 4 2 8 ) ->  ( 1 5 4 2 8 ) // Here, algorithm compares the first two elements,
                                   // and swaps since 5 > 1.
2: ( 1 5 4 2 8 ) ->  ( 1 4 5 2 8 ) // Swap since 5 > 4
3: ( 1 4 5 2 8 ) ->  ( 1 4 2 5 8 ) // Swap since 5 > 2
4: ( 1 4 2 5 8 ) ->  ( 1 4 2 5 8 ) // Now, since these elements are already in order
                                   // (8 > 5), algorithm does not swap them.
</code>```

Second Pass

```<code>5: ( 1 4 2 5 8 ) ->  ( 1 4 2 5 8 )
6: ( 1 4 2 5 8 ) ->  ( 1 2 4 5 8 ) // Swap since 4 > 2
7: ( 1 2 4 5 8 ) ->  ( 1 2 4 5 8 )
8: ( 1 2 4 5 8 ) ->  ( 1 2 4 5 8 )
</code>```

Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass

```<code>9: ( 1 2 4 5 8 ) ->  ( 1 2 4 5 8 )
10:( 1 2 4 5 8 ) ->  ( 1 2 4 5 8 )
11:( 1 2 4 5 8 ) ->  ( 1 2 4 5 8 )
12:( 1 2 4 5 8 ) ->  ( 1 2 4 5 8 )
</code>```

Test cases:

Format: Number of comparisons (N): List after N comparisons

```<code>Input list:
5  1  4  2  8
Test cases:
1: 1  5  4  2  8
2: 1  4  5  2  8
3: 1  4  2  5  8
4: 1  4  2  5  8
5: 1  4  2  5  8
6: 1  2  4  5  8
10: 1  2  4  5  8
14: 1  2  4  5  8

Input list:
0: 15  18  -6  18   9  -7  -1   7  19  19  -5  20  19   5  15  -5   3  18  14  19
Test cases:
1: 15  18  -6  18   9  -7  -1   7  19  19  -5  20  19   5  15  -5   3  18  14  19
21: -6  15  18   9  -7  -1   7  18  19  -5  19  19   5  15  -5   3  18  14  19  20
41: -6   9  -7  15  -1   7  18  18  -5  19  19   5  15  -5   3  18  14  19  19  20
60: -6  -7  -1   9   7  15  18  -5  18  19   5  15  -5   3  18  14  19  19  19  20
61: -6  -7  -1   7   9  15  18  -5  18  19   5  15  -5   3  18  14  19  19  19  20
81: -7  -6  -1   7   9  15  -5  18  18   5  15  -5   3  18  14  19  19  19  19  20
119: -7  -6  -1  -5   7   9  15   5  15  -5   3  18  14  18  18  19  19  19  19  20
120: -7  -6  -1  -5   7   9  15   5  15  -5   3  18  14  18  18  19  19  19  19  20
121: -7  -6  -1  -5   7   9   5  15  15  -5   3  18  14  18  18  19  19  19  19  20
122: -7  -6  -1  -5   7   9   5  15  15  -5   3  18  14  18  18  19  19  19  19  20
123: -7  -6  -1  -5   7   9   5  15  -5  15   3  18  14  18  18  19  19  19  19  20
201: -7  -6  -5  -1  -5   3   5   7   9  14  15  15  18  18  18  19  19  19  19  20
221: -7  -6  -5  -5  -1   3   5   7   9  14  15  15  18  18  18  19  19  19  19  20
</code>```

Yes, built-in Bubble sort algorithms are permitted.

No, you can not assume only positive integers, or unique integers.

The sorting must be in the order described above. You can't start at the end of the list

答:
Jelly, 25 bytes

```<code>ḣ©ṫ-Ṣ®ṖṖ¤;;ṫḊ¥
JḊṁ¹³W¤;ç/
</code>```

Based on my answer in J.

Try it online!

Verify number of comparisons.

Explanation

The helper link modifies the list at index [i-1, i] by sorting it which produces the same result as the bubble sort comparison.

```<code>ḣ©ṫ-Ṣ®ṖṖ¤;;ṫḊ¥  Helper link - Input: list A, index i
ḣ               Take the first i values
 ©              Save a copy of it
  ṫ-            Take the last two values
    Ṣ           Sort them
         ;      Append them to
     ®            Get the copy
      ṖṖ¤         Pop the last two values (Ṗ is pop)
          ;     Prepend it to
           ṫ      Take the last i values
            Ḋ¥    Dequeue - remove the head

JḊṁ¹³W¤;ç/  Input: list A and # of comparisons n
J           Enumerate the indices of A
 Ḋ          Dequeue - remove the head
  ṁ         Reshape it cyclically to length n
   ¹        Identity function (Just to avoid parsing rules)
       ;    Append it to
    ³         The list A
     W¤       Wrap it as an array
        ç/  Reduce from left to right using the helper link and return
</code>```

Title: Bubble sorting in progress

Body:
Jelly, 25 bytes

ḣ©ṫ-Ṣ®ṖṖ¤;;ṫḊ¥
JḊṁ¹³W¤;ç/

Based on my answer in J.

Try it online!

Verify number of comparisons.

Explanation

The helper link modifies the list at index [i-1, i] by sorting it which produces the same result as the bubble sort comparison.

ḣ©ṫ-Ṣ®ṖṖ¤;;ṫḊ¥  Helper link - Input: list A, index i
ḣ               Take the first i values
 ©              Save a copy of it
  ṫ-            Take the last two values
    Ṣ           Sort them
         ;      Append them to
     ®            Get the copy
      ṖṖ¤         Pop the last two values (Ṗ is pop)
          ;     Prepend it to
           ṫ      Take the last i values
            Ḋ¥    Dequeue - remove the head

JḊṁ¹³W¤;ç/  Input: list A and # of comparisons n
J           Enumerate the indices of A
 Ḋ          Dequeue - remove the head
  ṁ         Reshape it cyclically to length n
   ¹        Identity function (Just to avoid parsing rules)
       ;    Append it to
    ³         The list A
     W¤       Wrap it as an array
        ç/  Reduce from left to right using the helper link and return


问:
Tips for golfing in Ruby
What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

答:
New features in Ruby 2.3 and 2.4

It's good to stay abreast of new language features that will help your golf game. There are a few great ones in the latest Rubies.

Ruby 2.3

The safe navigation operator: &.

When you call a method that might return nil but you want to chain additional method calls if it's not, you waste bytes handling the nil case:

arr = ["zero", "one", "two"]
x = arr[5].size
# => NoMethodError: undefined method `size' for nil:NilClass

x = arr[5].size rescue 0
# => 0
```

<p>The "safe navigation operator" stops the chain of method calls if one returns <code>nil</code> and returns <code>nil</code> for the whole expression:</p>

<pre class="lang-ruby prettyprint-override"><code>x = arr[5]&.size || 0
# => 0
</code>```

Array#dig & Hash#dig

Deep access to nested elements, with a nice short name:

o = { foo: [{ bar: ["baz", "qux"] }] }
o.dig(:foo, 0, :bar, 1) # => "qux"
```

<p>Returns <code>nil</code> if it hits a dead end:</p>

<pre class="lang-ruby prettyprint-override"><code>o.dig(:foo, 99, :bar, 1) # => nil
</code>```

Enumerable#grep_v

The inverse of Enumerable#grep—returns all elements that don't match the given argument (compared with ===). Like grep, if a block is given its result is returned instead.

(1..10).grep_v 2..5 # => [1, 6, 7, 8, 9, 10]
(1..10).grep_v(2..5){|v|v*2} # => [2, 12, 14, 16, 18, 20]
```

<h3><code>Hash#to_proc</code></h3>

<p>Returns a Proc that yields the value for the given key, which can be pretty handy:</p>

<pre class="lang-ruby prettyprint-override"><code>h = { N: 0, E: 1, S: 2, W: 3 }
%i[N N E S E S W].map(&h)
# => [0, 0, 1, 2, 1, 2, 3]
</code>```

Ruby 2.4

Ruby 2.4 isn't out yet, but it will be soon and has some great little features. (When it's released I'll update this post with some links to the docs.) I learned about most of these in this great blog post.

Enumerable#sum

No more arr.reduce(:+). You can now just do arr.sum. It takes an optional initial value argument, which defaults to 0 for Numeric elements ([].sum == 0). For other types you'll need to provide an initial value. It also accepts a block that will be applied to each element before addition:

[[1, 10], [2, 20], [3, 30]].sum {|a,b| a + b }
# => 66
```

<h3><code>Integer#digits</code></h3>

<p>This returns an array of a number's digits in least-to-greatest significance order:</p>

<pre class="lang-ruby prettyprint-override"><code>123.digits # => [3, 2, 1]
</code>```

Compared to, say, 123.to_s.chars.map(&:to_i).reverse, this is pretty nice.

As a bonus, it takes an optional radix argument:

a = 0x7b.digits(16) # => [11, 7]
a.map{|d|"%x"%d} # => ["b", "7"]
```

<h3><code>Comparable#clamp</code></h3>

<p>Does what it says on the tin:</p>

<pre class="lang-ruby prettyprint-override"><code>v = 15
v.clamp(10, 20) # => 15
v.clamp(0, 10) # => 10
v.clamp(20, 30) # => 20
</code>```

Since it's in Comparable you can use it with any class that includes Comparable, e.g.:

?~.clamp(?A, ?Z) # => "Z"
```

<h3><code>String#unpack1</code></h3>

<p>A 2-byte savings over <code>.unpack(...)[0]</code>:</p>

<pre class="lang-ruby prettyprint-override"><code>"".unpack(?U)    # => [128123]
"".unpack(?U)[0] # => 128123
"".unpack1(?U)   # => 128123
</code>```

Precision argument for Numeric#ceil, floor, and truncate

Math::E.ceil(1) # => 2.8
Math::E.floor(1) # => 2.7
(-Math::E).truncate(1) # => -2.7
```

<h3>Multiple assignment in conditionals</h3>

<p>This raises an error in earlier versions of Ruby, but is allowed in 2.4.</p>

<pre class="lang-ruby prettyprint-override"><code>(a,b=1,2) ? "yes" : "no" # => "yes"
(a,b=nil) ? "yes" : "no" # => "no"
</code>```

Title: Tips for golfing in Ruby

Body:
New features in Ruby 2.3 and 2.4

It's good to stay abreast of new language features that will help your golf game. There are a few great ones in the latest Rubies.

Ruby 2.3

The safe navigation operator: &.

When you call a method that might return nil but you want to chain additional method calls if it's not, you waste bytes handling the nil case:

arr = ["zero", "one", "two"]
x = arr[5].size
# => NoMethodError: undefined method `size' for nil:NilClass

x = arr[5].size rescue 0
# => 0

The "safe navigation operator" stops the chain of method calls if one returns nil and returns nil for the whole expression:

x = arr[5]&.size || 0
# => 0

Array#dig & Hash#dig

Deep access to nested elements, with a nice short name:

o = { foo: [{ bar: ["baz", "qux"] }] }
o.dig(:foo, 0, :bar, 1) # => "qux"

Returns nil if it hits a dead end:

o.dig(:foo, 99, :bar, 1) # => nil

Enumerable#grep_v

The inverse of Enumerable#grep—returns all elements that don't match the given argument (compared with ===). Like grep, if a block is given its result is returned instead.

(1..10).grep_v 2..5 # => [1, 6, 7, 8, 9, 10]
(1..10).grep_v(2..5){|v|v*2} # => [2, 12, 14, 16, 18, 20]

Hash#to_proc

Returns a Proc that yields the value for the given key, which can be pretty handy:

h = { N: 0, E: 1, S: 2, W: 3 }
%i[N N E S E S W].map(&h)
# => [0, 0, 1, 2, 1, 2, 3]

Ruby 2.4

Ruby 2.4 isn't out yet, but it will be soon and has some great little features. (When it's released I'll update this post with some links to the docs.) I learned about most of these in this great blog post.

Enumerable#sum

No more arr.reduce(:+). You can now just do arr.sum. It takes an optional initial value argument, which defaults to 0 for Numeric elements ([].sum == 0). For other types you'll need to provide an initial value. It also accepts a block that will be applied to each element before addition:

[[1, 10], [2, 20], [3, 30]].sum {|a,b| a + b }
# => 66

Integer#digits

This returns an array of a number's digits in least-to-greatest significance order:

123.digits # => [3, 2, 1]

Compared to, say, 123.to_s.chars.map(&:to_i).reverse, this is pretty nice.

As a bonus, it takes an optional radix argument:

a = 0x7b.digits(16) # => [11, 7]
a.map{|d|"%x"%d} # => ["b", "7"]

Comparable#clamp

Does what it says on the tin:

v = 15
v.clamp(10, 20) # => 15
v.clamp(0, 10) # => 10
v.clamp(20, 30) # => 20

Since it's in Comparable you can use it with any class that includes Comparable, e.g.:

?~.clamp(?A, ?Z) # => "Z"

String#unpack1

A 2-byte savings over .unpack(...)[0]:

"".unpack(?U)    # => [128123]
"".unpack(?U)[0] # => 128123
"".unpack1(?U)   # => 128123

Precision argument for Numeric#ceil, floor, and truncate

Math::E.ceil(1) # => 2.8
Math::E.floor(1) # => 2.7
(-Math::E).truncate(1) # => -2.7

Multiple assignment in conditionals

This raises an error in earlier versions of Ruby, but is allowed in 2.4.

(a,b=1,2) ? "yes" : "no" # => "yes"
(a,b=nil) ? "yes" : "no" # => "no"


答:
Haskell, <s>30</s> 37 bytes

```<code>q f=tail>>=zipWith f;k=and.q(/=).q(>)
</code>```

Usage:

```<code>Prelude> k <$> words "ABA ABB BAB BUMP BALD BALDY UPWARD EXAMINATION AZBYCXDWEVFUGTHSIRJQKPLOMN"
[True,True,True,True,True,True,True,True,True]

Prelude> k <$> words "AAA BBA ACE THE BUMPY BALDING ABCDEFGHIJKLMNOPQRSTUVWXYZ"
[False,False,False,False,False,False,False]
</code>```

Title: Is it a Bumpy Word?

Body:
(inspired by this challenge over on Puzzling -- SPOILERS for that puzzle are below, so stop reading here if you want to solve that puzzle on your own!)

If a letter in a word occurs alphabetically later than the previous letter in the word, we call that a rise between the two letters. Otherwise, including if it's the same letter, it's called a fall.

For example, the word ACE has two rises (A to C and C to E) and no falls, while THE has two falls (T to H and H to E) and no rises.

We call a word Bumpy if the sequence of rises and falls alternates. For example, BUMP goes rise (B to U), fall (U to M), rise (M to P). Note that the first sequence need not be a rise -- BALD goes fall-rise-fall and is also Bumpy.

The challenge

Given a word, output whether or not it's Bumpy.

Input

A word (not necessarily a dictionary word) consisting of ASCII alphabet ([A-Z] or [a-z]) letters only, in any suitable format.

Your choice if the input is all uppercase or all lowercase, but it must be consistent.

The word will be at least 3 characters in length.

Output

A truthy/falsey value for whether the input word is Bumpy (truthy) or not Bumpy (falsey).

The Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Truthy:

```<code>ABA
ABB
BAB
BUMP
BALD
BALDY
UPWARD
EXAMINATION
AZBYCXDWEVFUGTHSIRJQKPLOMN
</code>```

Falsey:

```<code>AAA
BBA
ACE
THE
BUMPY
BALDING
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

```<code># [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=93005,OVERRIDE_USER=42963;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Haskell, <s>30</s> 37 bytes

q f=tail>>=zipWith f;k=and.q(/=).q(>)

Usage:

Prelude> k <$> words "ABA ABB BAB BUMP BALD BALDY UPWARD EXAMINATION AZBYCXDWEVFUGTHSIRJQKPLOMN"
[True,True,True,True,True,True,True,True,True]

Prelude> k <$> words "AAA BBA ACE THE BUMPY BALDING ABCDEFGHIJKLMNOPQRSTUVWXYZ"
[False,False,False,False,False,False,False]


答:
PowerShell v2+, 52 bytes

```<code>param($a)$a|%{$_[1]}|sort {random}|%{$a[$i++][0],$_}
</code>```

Takes input as an array of tuples, which is significantly shorter than using a hash (which would require .GetEnumerator() and whatnot to work).

We loop the input array |%{...}, each iteration pulling out the second element $_[1]. Those are piped into Sort-Object with the {Get-Random} as the sorting key. This will assign a random weight from 0 to [Int32]::MaxValue to each element for sorting. Those are piped into another loop |%{...}, with each iteration outputting a tuple of the corresponding first element of the tuple and the sorted number.

Examples

The examples here have an additional -join',' on the tuple output so it's shown better on the console, as the default output for multi-dimensional arrays is hard to read.

```<code>PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 ((0,10),(1,10),(5,5))
0,10
1,5
5,10

PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 ((0,10),(1,10),(5,5))
0,10
1,10
5,5

PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 ((1,1),(2,2),(3,3),(4,4),(5,5))
1,2
2,4
3,3
4,5
5,1
</code>```

This works for non-integer values as well with no modifications.

```<code>PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 (('one','one'),('two','two'),('three','three'),('four','four'))
one,four
two,three
three,two
four,one
</code>```

Title: Shuffle a mapping

Body:
We define a map as a set of key-value pairs.  For this challenge, you need to take each of the values and assign them to a randomly chosen key.

You must randomly shuffle the values, and output the resulting map.  This means that each time we run your program, we have a chance of getting a different output

Each possible permutation of the values must have a non-zero chance of appearing.

All of the original keys and original values must appear in the resulting array.  Repeated values must appear the same number of times in the resulting array.

For example, if your map was:

```<code>[0:10, 1:10, 5:5]
</code>```

all of the following must have a chance of appearing:

```<code>[0:10, 1:10, 5:5]  (original map)
[0:10, 1:5,  5:10]
[0:10, 1:10, 5:5]  (technically the same map, but I swapped the two tens)
[0:10, 1:5,  5:10]
[0:5,  1:10, 5:10]
[0:5,  1:10, 5:10]
</code>```

Acceptable input/outputs:

Your languages' native map

You can input an array of key-value pairs.  You may not input 2 arrays, one with keys, the other with values.

You can use a string representation of any the above

If you input an array or a map, you can modify the original object instead of returning

The input type must match the output type

If you input an array, the order of the keys must be maintained.

You can assume that the keys are unique, but you cannot assume that values are unique.

This is a code-golf, so answer as short as possible

Body:
PowerShell v2+, 52 bytes

param($a)$a|%{$_[1]}|sort {random}|%{$a[$i++][0],$_}

Takes input as an array of tuples, which is significantly shorter than using a hash (which would require .GetEnumerator() and whatnot to work).

We loop the input array |%{...}, each iteration pulling out the second element $_[1]. Those are piped into Sort-Object with the {Get-Random} as the sorting key. This will assign a random weight from 0 to [Int32]::MaxValue to each element for sorting. Those are piped into another loop |%{...}, with each iteration outputting a tuple of the corresponding first element of the tuple and the sorted number.

Examples

The examples here have an additional -join',' on the tuple output so it's shown better on the console, as the default output for multi-dimensional arrays is hard to read.

PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 ((0,10),(1,10),(5,5))
0,10
1,5
5,10

PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 ((0,10),(1,10),(5,5))
0,10
1,10
5,5

PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 ((1,1),(2,2),(3,3),(4,4),(5,5))
1,2
2,4
3,3
4,5
5,1

This works for non-integer values as well with no modifications.

PS C:\Tools\Scripts\golfing> .\shuffle-a-mapping.ps1 (('one','one'),('two','two'),('three','three'),('four','four'))
one,four
two,three
three,two
four,one


答:
Python 2, 77 bytes

Uses this option: If you input an array or a map, you can modify the original object instead of returning. Input is a dictionary literal like {0: 10, 1: 10, 5: 5}.

from random import*
D=input()
k=D.keys()
shuffle(k)
D=dict(zip(k,D.values()))
```

Try it online

Inspiration taken from this SO answer.

Title: Shuffle a mapping

Body:
Python 2, 77 bytes

Uses this option: If you input an array or a map, you can modify the original object instead of returning. Input is a dictionary literal like {0: 10, 1: 10, 5: 5}.

from random import*
D=input()
k=D.keys()
shuffle(k)
D=dict(zip(k,D.values()))

Try it online

Inspiration taken from this SO answer.


问:
The ten hundred most common words
This question is written because "Thing Explainer" is fun to read, and gave me an idea.

Write "stuff that makes computer do things" that reads/takes a set of letters, numbers and things like this "#%|? and returns True / 1 if all words are part of this set.

If all words are not part of that set, return the words that were not a part of it.

This website can be considered correct in all cases. The rules are written to follow the specs on that site.

Examples:

Truthy:

The code should return a truthy value if the entire text above the first horizontal line is pasted as input.

The following lines should return a truthy value (input is separated by ###)

```<code>This returns "Hello, World!"
###
tHiS rEtUrNs TrUe...
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
This set of stuff "#!^{>7( must return true
</code>```

Falsey:

In the following examples, input and output are separated by ***. Different test cases are separated by ###.

```<code>This code doesn't return "Hello, World!"
***
code
###
tHiS rEtUrN"s false...
***
s
false
</code>```

More detailed rules:

You can use this to test your code.

Non-letters are interpreted as spaces by the code, except for words like 'wasn't'. The words with apostrophes that returns true are included in the list

For instance: foo123bar should return foo and bar, since they are not part of the list, and 123 can be interpreted as spaces

The input will only contain printable ASCII code points [10, 32-126].

Words can contain mixed case letters. See second test case.

The list of words

should be taken as input (STDIN, function argument or equivalent)

can be modified (words can be separated by newline, comma etc., and you might sort the list)

Note that you can not use this list (it's not identical)

The output can be on any format you like

The output can be upper, lower or mixed case (optional)

There shall be no symbols in the output

For the record, Jonathan Allan found a strange corner case:  the implementation on XKCD will actually ignore any letters after an apostrophe up to the next non-[A-Z][a-z]['] - for example find's found, and find'qazxswedc found' both return nothing, whereas find'qazx.swedc found returns swedc.

You can choose if you want to return nothing for find'qazxswedc found', or return qazxswedc. Returning qazx, swedc for find'qazx.swedc is also OK.

答:
PowerShell v3+, <s>105</s> 92 bytes

```<code>param($a,$b)$x=@();-split($b-replace"[^a-zA-Z']",' ')|%{if($_-notin$a){$x+=$_}};($x,1)[!$x]
</code>```

Takes simple words like $a, and words like $b. Makes helper $x. Take each word in $b and get rid of any bad not letters, then check each one |{...}. If that word is not in $a, then we add it to $x. At the end, we choose $x or 1 by not $x. That is sent out, either words or 1.

Some words to try

```<code>PS C:\Tools\Scripts\golfing> ('This returns "Hello, World!"','tHiS rEtUrNs TrUe...','Thing Explainer is a book written by a man.
The man writes books with simple words.','This set of stuff "¤!^¤>7\ must return true'|%{"$_";(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This returns "Hello, World!"
###
1
###
tHiS rEtUrNs TrUe...
###
1
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
1
###
This set of stuff "¤!^¤>7\ must return true
###
1

PS C:\Tools\Scripts\golfing> ("This code doesn't returns Hello, World!",'tHiS rEtUrN"s false...'|%{"$_`n***`n"+(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This code doesn't returns Hello, World!
***
code
###
tHiS rEtUrN"s false...
***
s false
</code>```

Title: The ten hundred most common words

Body:
PowerShell v3+, <s>105</s> 92 bytes

param($a,$b)$x=@();-split($b-replace"[^a-zA-Z']",' ')|%{if($_-notin$a){$x+=$_}};($x,1)[!$x]

Takes simple words like $a, and words like $b. Makes helper $x. Take each word in $b and get rid of any bad not letters, then check each one |{...}. If that word is not in $a, then we add it to $x. At the end, we choose $x or 1 by not $x. That is sent out, either words or 1.

Some words to try

PS C:\Tools\Scripts\golfing> ('This returns "Hello, World!"','tHiS rEtUrNs TrUe...','Thing Explainer is a book written by a man.
The man writes books with simple words.','This set of stuff "¤!^¤>7\ must return true'|%{"$_";(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This returns "Hello, World!"
###
1
###
tHiS rEtUrNs TrUe...
###
1
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
1
###
This set of stuff "¤!^¤>7\ must return true
###
1

PS C:\Tools\Scripts\golfing> ("This code doesn't returns Hello, World!",'tHiS rEtUrN"s false...'|%{"$_`n***`n"+(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This code doesn't returns Hello, World!
***
code
###
tHiS rEtUrN"s false...
***
s false


答:
GoRuby, 19 - 50*(number of types in Ruby)

```<code>def bool(o)
   [1,[o].fle.j.sz].mi
end
</code>```

Returns 0 if the passed object converts to the empty string, 1 otherwise.  Of course, Ruby doesn't treat 0 as false, so this isn't a very useful function...in fact, bool(bool(x)) is always 1.  Objects that do convert to 0 include nil,false,[], and lists containing only objects that convert to 0.

Title: Implementing bool() without any conditionals

Body:
Title says it all. Given some input, turn it into a boolean value (0 or 1), without using conditional statements (e.x. == > < <= >= != ~=), or any function which uses conditional statements within its implementation, such as if, while and for. Your program must work with floating points, although you get more if it works with other items.

A general rule for determining whether bool(item) is False is if the item is empty ('' is an empty string, [] is an empty list.), or if the function used to turn an item of one type into another is given no input (in Python, str() returns '', list() returns [].)

Here are (some of) the different valid types. Your program is considered to work with one type if it works with one item in the following lists:

Integers, floating points, doubles, longs

Strings

Lists, tuples, arrays (bytearrays)

Dictionaries

Functions

Objects/Classes

Program score will be calculated like this: [# of characters]-(50*[# of types]). The program with the smallest score wins the challenge.

Body:
GoRuby, 19 - 50*(number of types in Ruby)

def bool(o)
   [1,[o].fle.j.sz].mi
end

Returns 0 if the passed object converts to the empty string, 1 otherwise.  Of course, Ruby doesn't treat 0 as false, so this isn't a very useful function...in fact, bool(bool(x)) is always 1.  Objects that do convert to 0 include nil,false,[], and lists containing only objects that convert to 0.


答:
Haskell, 52 bytes

```<code>f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y
</code>```

I suspect I could get this a chunk smaller if I managed to get rid of the "where" construct, but I'm probably stuck with zipWith.

This works by making a list of the rises (True) and falls (False), then making a list of if the ajacent entries in this list are different

This is my first attempt at one of these, so I'll go through my thought process in case I've gone horribly wrong somewhere.

Ungolfed Version (168 bytes)

```<code>isBumpy :: [Char] -> Bool
isBumpy input = and $ areBumps $ riseFall input
  where
    riseFall ax@(x:xs) = zipWith (>) xs ax
    areBumps ax@(x:xs) = zipWith (/=) xs ax
</code>```

Shorten names, remove type information (100 bytes)

```<code>f x = and $ g $ h x
  where
    h ax@(x:xs) = zipWith (>) xs ax
    g ax@(x:xs) = zipWith (/=) xs ax
</code>```

Move h into the main function as it is only used once (86 bytes)

```<code>f ax@(x:xs) = and $ g $ zipWith (>) xs ax
  where
    g ax@(x:xs) = zipWith (/=) xs ax
</code>```

Realise that areBumps and riseFall are similar enough to abstract (73 bytes)

```<code>f x  = and $ g (/=) $ g (>) x
  where
    g h ya@(y:ys) = zipWith h ys ya
</code>```

Note that (tail y) is shorter than ya@(y:ys) (70 bytes)

```<code>f x  = and $ g (/=) $ g (>) x
  where
    g h y = zipWith h (tail y) y
</code>```

Tidy up; remove unneeded spaces (52 bytes)

```<code>f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y
</code>```

Title: Is it a Bumpy Word?

Body:
Haskell, 52 bytes

f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y

I suspect I could get this a chunk smaller if I managed to get rid of the "where" construct, but I'm probably stuck with zipWith.

This works by making a list of the rises (True) and falls (False), then making a list of if the ajacent entries in this list are different

This is my first attempt at one of these, so I'll go through my thought process in case I've gone horribly wrong somewhere.

Ungolfed Version (168 bytes)

isBumpy :: [Char] -> Bool
isBumpy input = and $ areBumps $ riseFall input
  where
    riseFall ax@(x:xs) = zipWith (>) xs ax
    areBumps ax@(x:xs) = zipWith (/=) xs ax

Shorten names, remove type information (100 bytes)

f x = and $ g $ h x
  where
    h ax@(x:xs) = zipWith (>) xs ax
    g ax@(x:xs) = zipWith (/=) xs ax

Move h into the main function as it is only used once (86 bytes)

f ax@(x:xs) = and $ g $ zipWith (>) xs ax
  where
    g ax@(x:xs) = zipWith (/=) xs ax

Realise that areBumps and riseFall are similar enough to abstract (73 bytes)

f x  = and $ g (/=) $ g (>) x
  where
    g h ya@(y:ys) = zipWith h ys ya

Note that (tail y) is shorter than ya@(y:ys) (70 bytes)

f x  = and $ g (/=) $ g (>) x
  where
    g h y = zipWith h (tail y) y

Tidy up; remove unneeded spaces (52 bytes)

f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y


答:
Dyalog APL, 22 bytes

Inspiration.

(⎕UCS¯2↓⍳∘35↑⊢)⌈⌿∘⎕UCS
```

(

 ⎕UCS character representation of

 ¯2↓ all but the last two of

 ⍳∘35↑ up until the position of the first 35 ("#"), in that which is outside the parenthesis, taken from

 ⊢ that which is outside the parenthesis

) namely...

⌈⌿ the columnar maximums

∘ of

⎕UCS the Unicode values

TryAPL online!

Title: Parse the comments out of my esoteric code

Body:
Earlier this week, we learned about how to format esoteric languages for commenting. Today, we're going to do the inverse of that. I need you to write a program or function that parses some well-commented esoteric code and parses the comments out, returning just the code. Using some examples from the previous challenge, here is what well-commented code looks like:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

Here is what you need to do to extract the code out. First, remove the comment character (#), the space before it, and everything after the comment character.

```<code>a
 bc
   d
    e
     fgh
        ij
          k
           l
            mn
              op
</code>```

Then, collapse each line upwards into a single line. For example, since b is in the second column on line two, once we collapse it up, it will be in the second column on line one. Similarly, c will be put in the third column of line one, and d will be put on the fourth. Repeat this for every character, and you get this:

```<code>abcdefghijklmnop
</code>```

Important note: It seems like the trivial solution is to just remove the comments, remove every space, and join every line. This is not a valid approach! Because the original code might have spaces in it, these will get stripped out with this approach. For example, this is a perfectly valid input:

```<code>hello         #Line one
              #Line two
       world! #Line three
</code>```

And the corresponding output should be:

```<code>hello  world!
</code>```

The Challenge:

Write a program or function that takes commented code as input, and outputs or returns the code with all the comments parsed out of it. You should output the code without any trailing spaces, although one trailing newline is permissible. The comment character will always be #, and there will always be one extra space before the comments start. # will not appear in the comment section of the input. In order to keep the challenge simpler, here are some inputs you do not have to handle:

You can assume that the code will not have two characters in the same column. For example, this is an input that violates this rule:

```<code>a  #A character in column one
bc #Characters in columns one and two
</code>```

You can also assume that all comment characters appear in the same column. For example, this input:

```<code>short       #this is a short line
      long        #This is a long line
</code>```

violates this rule. This also means that # will not be in the code section.

And lastly, you do not have to handle code sections with leading or trailing spaces. For example,

```<code>  Hello,          #
         World!   #
</code>```

You may also assume that the input only contains printable ASCII characters.

Examples:

```<code>Input:
hello         #Line one
              #Line two
       world! #Line three

Output:
hello  world!

Input:
E                                                   #This comment intentionally left blank
 ac                                                 #
   h s                                              #
      ecti                                          #
          on is                                     #
                one c                               #
                     haracte                        #
                            r longer                #
                                     than the       #
                                              last! #

Output:
Each section is one character longer than the last!

Input:
4          #This number is 7
 8         #
  15       #That last comment is wrong.
    16     #
      23   #
        42 #

Output:
4815162342

Input:
Hello                     #Comment 1
      world               #Comment 2
           ,              #Comment 3
             how          #Comment 4
                 are      #Comment 5
                     you? #Comment 6

Output:
Hello world, how are you?

Input:
Prepare                               #
        for...                        #
                        extra spaces! #

Output:
Prepare for...          extra spaces!
</code>```

You may take input in whatever reasonable format you like, for example, a list of strings, a single string with newlines, a 2d list of characters, etc. The shortest answer in bytes wins!

Body:
Dyalog APL, 22 bytes

Inspiration.

(⎕UCS¯2↓⍳∘35↑⊢)⌈⌿∘⎕UCS

(

 ⎕UCS character representation of

 ¯2↓ all but the last two of

 ⍳∘35↑ up until the position of the first 35 ("#"), in that which is outside the parenthesis, taken from

 ⊢ that which is outside the parenthesis

) namely...

⌈⌿ the columnar maximums

∘ of

⎕UCS the Unicode values

TryAPL online!


答:
Java 7, 278

Golfed:

String f(String i){String o="";for(int n=0;n<i.length();)o+=(n<1?"User:   ":n<2?"Group:  ":"Others: ")+new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i.charAt(n++)-48]+"\n";return o;}
```

<p>Ungolfed:</p>

<pre class="lang-java prettyprint-override"><code>  String f(String i) {
    String o = "";
    for (int n = 0; n < i.length();)
      o += (n < 1 ? "User:   " : n < 2 ? "Group:  " : "Others: ")
        + new String[] { "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute",
            "Read and Write", "Read Write and Execute" }[i.charAt(n++) - 48]
        + "\n";
    return o;
  }
</code>```

Output:

User:   Read and Write
Group:  Read and Write
Others: Read and Write

User:   None
Group:  Read only
Others: Write only

User:   Read and Write
Group:  Read only
Others: Read only
```

Title: Decode the chmod

Body:
Challenge

Given a three digit octal permissions number, output the permissions that it grants.

chmod

On UNIX OSes file permissions are changed using the chmod command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions.

The three digits in the permissions number represent a different person:

The first digit represents the permissions for the user

The second digit represents the permissions for the group

The last digit represents the permissions for others

Next, each digit represents a permission as shown below in:

```<code>Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None
</code>```

Input

The input will be the three digit number as a string, e.g.:

```<code>133
</code>```

or

```<code>007
</code>```

This will be passed either via STDIN or via function arguments.

Output

Your output should be the different permissions for each of the user, the group and the others. You must display this information like so:

```<code>User:   ddd
Group:  ddd
Others: ddd
</code>```

Where there are three spaces after User, two spaces after Group and one space after Others. You replace ddd with the permissions information.

Your output may be to STDOUT or as a returned string.

Examples

Input: 666

Output:

```<code>User:   Read and Write
Group:  Read and Write
Others: Read and Write
</code>```

Input: 042

Output:

```<code>User:   None
Group:  Read only
Others: Write only
</code>```

Input: 644

Output:

```<code>User:   Read and Write
Group:  Read only
Others: Read only
</code>```

Winning

The shortest code in bytes wins.

Body:
Java 7, 278

Golfed:

String f(String i){String o="";for(int n=0;n<i.length();)o+=(n<1?"User:   ":n<2?"Group:  ":"Others: ")+new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i.charAt(n++)-48]+"\n";return o;}

Ungolfed:

  String f(String i) {
    String o = "";
    for (int n = 0; n < i.length();)
      o += (n < 1 ? "User:   " : n < 2 ? "Group:  " : "Others: ")
        + new String[] { "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute",
            "Read and Write", "Read Write and Execute" }[i.charAt(n++) - 48]
        + "\n";
    return o;
  }

Output:

User:   Read and Write
Group:  Read and Write
Others: Read and Write

User:   None
Group:  Read only
Others: Write only

User:   Read and Write
Group:  Read only
Others: Read only


答:
Pyth, 11 bytes

```<code>PhceCSMCQ\#
</code>```

A program that takes input of a list of strings on STDIN and prints a string.

Try it online

How it works

```<code>PhceCSMCQ\#  Program. Input: Q
       CQ    Transpose Q
     SM      Sort each element of that lexicographically
    C        Transpose that
   e         Yield the last element of that, giving the program ending with ' #' and some
             parts of the comments
  c      \#  Split that on the character '#'
 h           Yield the first element of that, giving the program with a trailing space
P            All but the last element of that, removing the trailing space
             Implicitly print
</code>```

Body:
Pyth, 11 bytes

PhceCSMCQ\#

A program that takes input of a list of strings on STDIN and prints a string.

<a href="https://pyth.herokuapp.com/?code=PhceCSMCQ%5C%23&test_suite=1&test_suite_input=%5B%27hello+++++++++%23Line+one%27%2C+%27++++++++++++++%23Line+two%27%2C+%27+++++++world%21+%23Line+three%27%5D%0A%5B%27E+++++++++++++++++++++++++++++++++++++++++++++++++++%23This+comment+intentionally+left+blank%27%2C+%27+ac+++++++++++++++++++++++++++++++++++++++++++++++++%23%27%2C+%27+++h+s++++++++++++++++++++++++++++++++++++++++++++++%23%27%2C+%27++++++ecti++++++++++++++++++++++++++++++++++++++++++%23%27%2C+%27++++++++++on+is+++++++++++++++++++++++++++++++++++++%23%27%2C+%27++++++++++++++++one+c+++++++++++++++++++++++++++++++%23%27%2C+%27+++++++++++++++++++++haracte++++++++++++++++++++++++%23%27%2C+%27++++++++++++++++++++++++++++r+longer++++++++++++++++%23%27%2C+%27+++++++++++++++++++++++++++++++++++++than+the+++++++%23%27%2C+%27++++++++++++++++++++++++++++++++++++++++++++++last%21+%23%27%5D%0A%5B%274++++++++++%23This+number+is+7%27%2C+%27+8+++++++++%23%27%2C+%27++15+++++++%23That+last+comment+is+wrong.%27%2C+%27++++16+++++%23%27%2C+%27++++++23+++%23%27%2C+%27++++++++42+%23%27%5D%0A%5B%27Hello+++++++++++++++++++++%23Comment+1%27%2C+%27++++++world+++++++++++++++%23Comment+2%27%2C+%27+++++++++++%2C++++++++++++++%23Comment+3%27%2C+%27+++++++++++++how++++++++++%23Comment+4%27%2C+%27+++++++++++++++++are++++++%23Comment+5%27%2C+%27+++++++++++++++++++++you%3F+%23Comment+6%27%5D%0A%5B%27Prepare+++++++++++++++++++++++++++++++%23%27%2C+%27++++++++for...++++++++++++++++++++++++%23%27%2C+%27++++++++++++++++++++++++extra+spaces%21+%23%27%5D&debug=0" rel="nofollow noreferrer">Try it online

How it works

PhceCSMCQ\#  Program. Input: Q
       CQ    Transpose Q
     SM      Sort each element of that lexicographically
    C        Transpose that
   e         Yield the last element of that, giving the program ending with ' #' and some
             parts of the comments
  c      \#  Split that on the character '#'
 h           Yield the first element of that, giving the program with a trailing space
P            All but the last element of that, removing the trailing space
             Implicitly print


问:
Validate a stem-and-leaf plot
A stem and leaf plot displays a bunch of numerical values in groups, which are determined by all but the last digit. For example, suppose we have this set of data:

```<code>0, 2, 12, 13, 13, 15, 16, 20, 29, 43, 49, 101
</code>```

We could produce this stem and leaf plot:

```<code>0|02
1|23356
2|09
3|
4|39
5|
6|
7|
8|
9|
10|1
</code>```

The first row's stem is 0, so its "leaves" - the digits after the | - represent the values between 0 inclusive and 10 exclusive. The leaves on each stem are sorted. Stems with no leaves (like 3) still appear in the plot. The value of 101 is between 100 inclusive and 110 exclusive, so its stem is 10 (100 divided by 10).

Your challenge is to check whether a piece of text is a valid stem and leaf plot. A valid plot satisfies these rules:

Has exactly one row for every stem (i.e. 10-wide group) in the range of the data (including stems in the middle of the range with no leaves)

Has no stems outside the range

All leaves are sorted ascending to the right

All stems are sorted ascending down

Has only numeric characters (besides the separator |)

You do not have to deal with numbers that have fractional parts. You may approve or reject extra leading zeros in the stems, but a blank stem is not allowed. There will be at least one value. You may only assume extra spaces after the leaves on each row. You may assume a leading and/or trailing newline. All characters will be printable ASCII.

Your function or program should return or output (to screen or the standard output) a truthy value for a valid plot, or a falsy value for an invalid plot. You may take input from the standard input, from a file, as one big string, as an array of strings - whatever is most convenient.

Here are some test cases that are valid plots (separated by blank lines):

```<code>2|00003457
3|35
4|799
5|3

99|3
100|0556
101|
102|
103|8

0|0
</code>```

Here are some test cases that are invalid plots, with commentary to the right:

```<code>|0               Blank stem

5|347            Missing a stem (6) in the range
7|9

4|               Has a stem (4) outside the range
5|26
6|7

11|432           Leaves aren't sorted correctly
12|9989

5|357            Stems aren't sorted correctly
4|002
6|1

4|5              Duplicate stem
4|6
4|6
5|1

51114            No stem and leaf separator
609

1|2|03           Multiple separators
2|779|

4|8abcdefg9      Invalid characters
5|1,2,3

75 | 4 6         Invalid characters (spaces)
76 | 2 8 8 9
</code>```

This is code golf, so the shortest code wins! Standard loopholes are disallowed.

答:
Pip, <s>60</s> 58 + 1 = 59 bytes

First stab at the problem, probably could use more golfing. Uses the -r flag to read lines of input from stdin. Truthy output is 1, falsy output is 0 or empty string.

```<code>g=a+,#g&a@vNE'|NEg@v@v&$&{Y(a^'|1)a@`^\d+\|\d*$`&SNy=^y}Mg
</code>```

Explanation and test suite pending, but in the meantime: Try it online!

Title: Validate a stem-and-leaf plot

Body:
Pip, <s>60</s> 58 + 1 = 59 bytes

First stab at the problem, probably could use more golfing. Uses the -r flag to read lines of input from stdin. Truthy output is 1, falsy output is 0 or empty string.

g=a+,#g&a@vNE'|NEg@v@v&$&{Y(a^'|1)a@`^\d+\|\d*$`&SNy=^y}Mg

Explanation and test suite pending, but in the meantime: Try it online!


答:
Ruby, 77 bytes

```<code>puts File.readlines("stack.txt").join('').gsub(/\s{1}#.*\n/,'').gsub(/\s/,'')
</code>```

Body:
Ruby, 77 bytes

puts File.readlines("stack.txt").join('').gsub(/\s{1}#.*\n/,'').gsub(/\s/,'')