问:
Counting Goats to Sleep
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

答:
Python 3. 170 bytes

```<code>lambda n:'\n'.join(map(lambda*l:''.join(l),*map(lambda w:(' '*6+'\ ','  ___/'+(w and'o'or'-')+'>',(w and'-'or',')+'(___)" ',w and" '' ''  "or' `` ``  '),range(n)[::-1])))
</code>```

hmm, apparently constructing the string without doing list manipulation yield shorter code

Title: Counting Goats to Sleep

Body:
Python 3. 170 bytes

lambda n:'\n'.join(map(lambda*l:''.join(l),*map(lambda w:(' '*6+'\ ','  ___/'+(w and'o'or'-')+'>',(w and'-'or',')+'(___)" ',w and" '' ''  "or' `` ``  '),range(n)[::-1])))

hmm, apparently constructing the string without doing list manipulation yield shorter code


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

答:
JavaScript, 189 bytes

```<code>(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\|/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c.length!=2||c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))
</code>```

Same length alternate solution:

```<code>(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\||^.*\|.*\|.*$/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))
</code>```

Defines an anonymous function that takes input as a multiline string.

I'm sure there's more to golf, so let me know if you see any possible improvements.

Explanation:

The function checks for a  number of bad things, and if any of those are true, it returns false (using logical ORs and a NOT)

```<code>(x,y=x.split("\n").map(a=>a.split`|`),          //y is input in pairs of stem and leaves
z=y.map(a=>a[0]))                               //z is stems
=>                                              //defines function
!(                                              //logical not
/[^0-9|\n]|^\|/m.exec(x)                        //checks for invalid chars and blank stems
||/^\d+\|\n|\|$/.exec(x)                        //checks for stems out of range
||y.some((c,i,a)=>c.length!=2                   //checks for multiple |s in a line
||c[1]!=[...c[1]].sort().join``))               //checks if leaves are in wrong order
||z!=z.sort((a,b)=>a-b))                        //checks for stems in wrong order
</code>```

In the alternate solution, checking for multiple |s in a line is done as part of the first regex instead.

ContentLicense: CC BY-SA 3.0

Title: Validate a stem-and-leaf plot

Body:
JavaScript, 189 bytes

(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\|/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c.length!=2||c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))

Same length alternate solution:

(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\||^.*\|.*\|.*$/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))

Defines an anonymous function that takes input as a multiline string.

I'm sure there's more to golf, so let me know if you see any possible improvements.

Explanation:

The function checks for a  number of bad things, and if any of those are true, it returns false (using logical ORs and a NOT)

(x,y=x.split("\n").map(a=>a.split`|`),          //y is input in pairs of stem and leaves
z=y.map(a=>a[0]))                               //z is stems
=>                                              //defines function
!(                                              //logical not
/[^0-9|\n]|^\|/m.exec(x)                        //checks for invalid chars and blank stems
||/^\d+\|\n|\|$/.exec(x)                        //checks for stems out of range
||y.some((c,i,a)=>c.length!=2                   //checks for multiple |s in a line
||c[1]!=[...c[1]].sort().join``))               //checks if leaves are in wrong order
||z!=z.sort((a,b)=>a-b))                        //checks for stems in wrong order

In the alternate solution, checking for multiple |s in a line is done as part of the first regex instead.


问:
Cambridge Transposition
I'm sure most, if not all, of you have come across this at some point or another:

Aoccdrnig to a rscheeachr at Cmabrigde Uinervtisy, it deosn't mttaer
in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is
taht the frist and lsat ltteer be at the rghit pclae. The rset can be
a toatl mses and you can sitll raed it wouthit porbelm. Tihs is
bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the
wrod as a wlohe.

Create a program that inputs any amount of text. For testing purposes, use the unscrambled version of the above text, found below.

The program must then randomly transpose the letters of each word with a length of 4 or more letters, except the first and last letter of each word.

All other formatting must remain the same (capitalization and punctuation, etc.).

Testing text:

According to a researcher at Cambridge University, it doesn't matter
in what order the letters in a word are, the only important thing is
that the first and last letter be at the right place. The rest can be
a total mess and you can still read it without problem. This is
because the human mind does not read every letter by itself but the
word as a whole.

As usual, this is a code-golf. Shortest code wins.

答:
APL, <s>58</s> 49

I believe this works in IBM APL2 (I don't have IBM APL)

```<code>({⍵[⌽∪t,⌽∪1,?⍨t←⍴⍵]}¨x⊂⍨~b),.,x⊂⍨b←' ,.'∊⍨x←⍞,' '
</code>```

If not, then in Dyalog APL, add to the front:

```<code> ⎕ML←3⋄
</code>```

which adds 6 chars

This assumes the only non-word characters are space, comma, and period.

ContentLicense: CC BY-SA 4.0

Title: Cambridge Transposition

Body:
APL, <s>58</s> 49

I believe this works in IBM APL2 (I don't have IBM APL)

({⍵[⌽∪t,⌽∪1,?⍨t←⍴⍵]}¨x⊂⍨~b),.,x⊂⍨b←' ,.'∊⍨x←⍞,' '

If not, then in Dyalog APL, add to the front:

 ⎕ML←3⋄

which adds 6 chars

This assumes the only non-word characters are space, comma, and period.


问:
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!

答:
Perl 6, 39 bytes

```<code>{[Zmax](@_».comb).join.split(' #')[0]}
</code>```

Translation of the Python solution by Dennis.

Takes input as a list of strings, and returns a string.

(try it online)

Body:
Perl 6, 39 bytes

{[Zmax](@_».comb).join.split(' #')[0]}

Translation of the Python solution by Dennis.

Takes input as a list of strings, and returns a string.

(try it online)


Title: Validate a stem-and-leaf plot

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

Body:
Perl, 47 bytes

Includes +2 for -0p

Give input on STDIN

stem.pl:

#!/usr/bin/perl -0p
$"="*";$_=/^((??{$_+$n++})\|@{[0..9,"
"]})+$/


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

答:
Haskell, 186 Bytes

```<code>s=zip(words"7654 6 7632 753 7531 0 421")(words"Read and Write and Execute None only")
m c=mapM_(\(x,y)->putStrLn(x++unwords[b|(a,b)<-s,elem y a]))$zip["User:   ","Group:  ","Others: "]c
</code>```

Example:

```<code>Prelude> :r
[1 of 1] Compiling Main             ( decCh.hs, interpreted )
Ok, modules loaded: Main.
*Main> m "654"
User:   Read and Write
Group:  Read and Execute
Others: Read only
</code>```

Only Prelude used. Am I doing this right?

Ungolfed:

```<code>s = zip (words "7654 6 7632 753 7531 0 421")
        (words "Read and Write and Execute None only")

ps y = unwords [b|(a,b)<-s,elem y a] -- build permissions string
pp (x,y) = putStrLn $ x ++ ps y -- print user + permission

m c =   let up = zip ["User:   ","Group:  ","Others: "] c -- pair user and permission
        in mapM_ pp up --print each
</code>```

Title: Decode the chmod

Body:
Haskell, 186 Bytes

s=zip(words"7654 6 7632 753 7531 0 421")(words"Read and Write and Execute None only")
m c=mapM_(\(x,y)->putStrLn(x++unwords[b|(a,b)<-s,elem y a]))$zip["User:   ","Group:  ","Others: "]c

Example:

Prelude> :r
[1 of 1] Compiling Main             ( decCh.hs, interpreted )
Ok, modules loaded: Main.
*Main> m "654"
User:   Read and Write
Group:  Read and Execute
Others: Read only

Only Prelude used. Am I doing this right?

Ungolfed:

s = zip (words "7654 6 7632 753 7531 0 421")
        (words "Read and Write and Execute None only")

ps y = unwords [b|(a,b)<-s,elem y a] -- build permissions string
pp (x,y) = putStrLn $ x ++ ps y -- print user + permission

m c =   let up = zip ["User:   ","Group:  ","Others: "] c -- pair user and permission
        in mapM_ pp up --print each


问:
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

答:
Perl, 35 bytes

Includes +2 for -0p

Give each keys/value separated by space on a STDIN line

```<code>shuffle.pl
1 5
3 8
9 2
^D
</code>```

shuffle.pl:

```<code>#!/usr/bin/perl -p0
@F=/ .*/g;s//splice@F,rand@F,1/eg
</code>```

Title: Shuffle a mapping

Body:
Perl, 35 bytes

Includes +2 for -0p

Give each keys/value separated by space on a STDIN line

shuffle.pl
1 5
3 8
9 2
^D

shuffle.pl:

#!/usr/bin/perl -p0
@F=/ .*/g;s//splice@F,rand@F,1/eg


答:
Sinclair BASIC - <s>263</s> 257 bytes

I did one version using the same approach as everyone else (load of string variables put into array) in 227 bytes, so going to post this one as a different way of doing it.

EDIT - As pointed out, there were some extraneous "and" appearing, this is now resolved

```<code>1 p=0,z$="and ": INPUT c$
2 FOR EACH a$ IN ["User:   ","Group:  ","Others: "]
3 p+=1,n=VAL c$(p),r=(n & 4)>0,w=(n & 2)>0,x=(n & 1)>0,t=r+w+x
4  ?a$;("Read "*r)+(z$*(r AND (t=2)))+("Write "*w)+(z$*(w AND x))+("Execute "*x)+("only"*(t=1))+("None"*(t=0))
5 NEXT a$
</code>```

Uses bitwise-AND & operation to see if the number has 4,2 or 1 bits set and then prints the different permissions. Adding "and" in between multiple values took up most of the space.

Screenshot shows example for 670 as input

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:
Sinclair BASIC - <s>263</s> 257 bytes

I did one version using the same approach as everyone else (load of string variables put into array) in 227 bytes, so going to post this one as a different way of doing it.

EDIT - As pointed out, there were some extraneous "and" appearing, this is now resolved

1 p=0,z$="and ": INPUT c$
2 FOR EACH a$ IN ["User:   ","Group:  ","Others: "]
3 p+=1,n=VAL c$(p),r=(n & 4)>0,w=(n & 2)>0,x=(n & 1)>0,t=r+w+x
4  ?a$;("Read "*r)+(z$*(r AND (t=2)))+("Write "*w)+(z$*(w AND x))+("Execute "*x)+("only"*(t=1))+("None"*(t=0))
5 NEXT a$

Uses bitwise-AND & operation to see if the number has 4,2 or 1 bits set and then prints the different permissions. Adding "and" in between multiple values took up most of the space.

Screenshot shows example for 670 as input


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

答:
Bash, 178 bytes

```<code>Q='#(8_8)
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4'
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4
</code>```

Pfff, I am not good at quines :/ Any suggestion to golf it more is more than welcome! :-)

Title: Source code GO!

Body:
Bash, 178 bytes

Q='#(8_8)
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4'
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4

Pfff, I am not good at quines :/ Any suggestion to golf it more is more than welcome! :-)


问:
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

```

答:
Java 8, <s>114</s> 90 bytes

```<code>(c,b)->{b=c[0]<c[1];for(int i=2;i<c.length;i++)if(c[i]>c[i-1]!=(b=!b))return 0;return 1;};
</code>```

Ungolfed test program

```<code>public static void main(String[] args) {
    BiFunction<char[], Boolean, Integer> func = (c, b) -> {
        b = c[0] < c[1];
        for (int i = 2; i < c.length; i++) {
            if (c[i] > c[i - 1] != (b = !b)) {
                return 0;
            }
        }
        return 1;
    };

    System.out.println(func.apply("ABCDEFG".toCharArray(), false));
    System.out.println(func.apply("AZBYCXDGEF".toCharArray(), false));
    System.out.println(func.apply("ZXZXZX".toCharArray(), false));
    System.out.println(func.apply("ZXCYZ".toCharArray(), false));
    System.out.println(func.apply("AAA".toCharArray(), false));
}
</code>```

Title: Is it a Bumpy Word?

Body:
Java 8, <s>114</s> 90 bytes

(c,b)->{b=c[0]<c[1];for(int i=2;i<c.length;i++)if(c[i]>c[i-1]!=(b=!b))return 0;return 1;};

Ungolfed test program

public static void main(String[] args) {
    BiFunction<char[], Boolean, Integer> func = (c, b) -> {
        b = c[0] < c[1];
        for (int i = 2; i < c.length; i++) {
            if (c[i] > c[i - 1] != (b = !b)) {
                return 0;
            }
        }
        return 1;
    };

    System.out.println(func.apply("ABCDEFG".toCharArray(), false));
    System.out.println(func.apply("AZBYCXDGEF".toCharArray(), false));
    System.out.println(func.apply("ZXZXZX".toCharArray(), false));
    System.out.println(func.apply("ZXCYZ".toCharArray(), false));
    System.out.println(func.apply("AAA".toCharArray(), false));
}


答:
php, 84 bytes

```<code><?= serialise(array_combine(array_keys($a=unserialize($argv[1])),shuffle($a)?$a:0));
</code>```

Takes input as a serialised array, outputs the same.

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:
php, 84 bytes

<?= serialise(array_combine(array_keys($a=unserialize($argv[1])),shuffle($a)?$a:0));

Takes input as a serialised array, outputs the same.


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

答:
Python 85 chars - 50*20 types = -915 points

```<code>def b(x=False):
 try:return b(len(x))
 except:return{0:False,None:False}.get(x,True)
</code>```

So it works for all types in the six categories in the question.
The score is therefore 85 - 50*6 = -215, or am I wrong?

Here is also my test code:

```<code>class Test(object):
  def __init__(self):
    pass

for x in [None, NotImplemented, Ellipsis,
    0,1,0L,1L,False,True,0.0,1.0,0.0j,1.0j,
    '','a',u'',u'a',
    (),(1,),[],[1],bytearray(),bytearray('31'),
    set(),set('ab'),frozenset(),frozenset('ab'),
    {},{'a':0},b, Test, Test.__init__,(a for a in 'a')]:
  print b(x), bool(x), type(x)
</code>```

Think I've forgotten some types ;-)

```<code>b(x) bool(x) type(x)
False False <type 'NoneType'>
True True <type 'NotImplementedType'>
True True <type 'ellipsis'>
False False <type 'int'>
True True <type 'int'>
False False <type 'long'>
True True <type 'long'>
False False <type 'bool'>
True True <type 'bool'>
False False <type 'float'>
True True <type 'float'>
False False <type 'complex'>
True True <type 'complex'>
False False <type 'str'>
True True <type 'str'>
False False <type 'unicode'>
True True <type 'unicode'>
False False <type 'tuple'>
True True <type 'tuple'>
False False <type 'list'>
True True <type 'list'>
False False <type 'bytearray'>
True True <type 'bytearray'>
False False <type 'set'>
True True <type 'set'>
False False <type 'frozenset'>
True True <type 'frozenset'>
False False <type 'dict'>
True True <type 'dict'>
True True <type 'function'>
True True <type 'type'>
True True <type 'instancemethod'>
True True <type 'generator'>
</code>```

Body:
Python 85 chars - 50*20 types = -915 points

def b(x=False):
 try:return b(len(x))
 except:return{0:False,None:False}.get(x,True)

So it works for all types in the six categories in the question.
The score is therefore 85 - 50*6 = -215, or am I wrong?

Here is also my test code:

class Test(object):
  def __init__(self):
    pass

for x in [None, NotImplemented, Ellipsis,
    0,1,0L,1L,False,True,0.0,1.0,0.0j,1.0j,
    '','a',u'',u'a',
    (),(1,),[],[1],bytearray(),bytearray('31'),
    set(),set('ab'),frozenset(),frozenset('ab'),
    {},{'a':0},b, Test, Test.__init__,(a for a in 'a')]:
  print b(x), bool(x), type(x)

Think I've forgotten some types ;-)

b(x) bool(x) type(x)
False False <type 'NoneType'>
True True <type 'NotImplementedType'>
True True <type 'ellipsis'>
False False <type 'int'>
True True <type 'int'>
False False <type 'long'>
True True <type 'long'>
False False <type 'bool'>
True True <type 'bool'>
False False <type 'float'>
True True <type 'float'>
False False <type 'complex'>
True True <type 'complex'>
False False <type 'str'>
True True <type 'str'>
False False <type 'unicode'>
True True <type 'unicode'>
False False <type 'tuple'>
True True <type 'tuple'>
False False <type 'list'>
True True <type 'list'>
False False <type 'bytearray'>
True True <type 'bytearray'>
False False <type 'set'>
True True <type 'set'>
False False <type 'frozenset'>
True True <type 'frozenset'>
False False <type 'dict'>
True True <type 'dict'>
True True <type 'function'>
True True <type 'type'>
True True <type 'instancemethod'>
True True <type 'generator'>


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

答:
Python, 93 bytes

import re
lambda w,s:[w for w in re.sub("[^'\w]|\d|_",' ',w).split()if w.lower()not in s]or 1
```

All test cases are at ideone

Preprocessing of the list is to split on | and put it in a set (which I imagine is fine if pre-sorting is allowed). Input words as w and the set as s.

If that's not allowed this becomes 98 bytes with not in s becoming not in set(s).

We could preprocess it to have all permutations of upper and lower case characters too and save 8 bytes, but I think that might be going too far (that would be a huge set).

Title: The ten hundred most common words

Body:
Python, 93 bytes

import re
lambda w,s:[w for w in re.sub("[^'\w]|\d|_",' ',w).split()if w.lower()not in s]or 1

All test cases are at ideone

Preprocessing of the list is to split on | and put it in a set (which I imagine is fine if pre-sorting is allowed). Input words as w and the set as s.

If that's not allowed this becomes 98 bytes with not in s becoming not in set(s).

We could preprocess it to have all permutations of upper and lower case characters too and save 8 bytes, but I think that might be going too far (that would be a huge set).


答:
Python 3.5, 3.6 - 235 232 228 216 bytes

(should work on all Python 3.x)

So the input is on STDIN here (saves an import ☺).

a=input()
r=range
for i in r(3):
 p=int(a[i]);x=[["Read","Write","Execute"][j]for j in r(3)if 4>>j&p]
 if x[1:]:x[-1:-1]="and",
 if len(x)==1:x+="only",
 print(["User:  ","Group: ","Others:"][i]," ".join(x)or"None")
```

<p>Making use of tuples, omitting spaces where possible and operator precedence where you would normally put parentheses to make your intentions clear.</p>

<p>Sample usage:</p>

<pre class="lang-none prettyprint-override"><code>$ echo -n '666' | python3 golf2.py
User:   Read and Write
Group:  Read and Write
Others: Read and Write
$ echo -n '644' | python3 golf2.py
User:   Read and Write
Group:  Read only
Others: Read only
$ echo '042' | python3 golf2.py
User:   None
Group:  Read only
Others: Write only
$ echo '123' | python3 golf2.py
User:   Execute only
Group:  Write only
Others: Write and Execute
$ echo -n '777' | python3 golf2.py
User:   Read Write and Execute
Group:  Read Write and Execute
Others: Read Write and Execute
</code>```

Un-golfed:

input_perms = list(map(int, input()))

entities = ["User", "Group", "Others"]
perm_names = ["Read", "Write", "Execute"]

for i in range(3):
    bits = input_perms[i]
    perms = [
        perm_names[j]
        for j in range(3)
        if (1 << (2-j)) & bits
    ]

    if len(perms) > 1:
        perms.insert(-1, "and")
    if len(perms) == 1:
        perms.append("only")

    print("{:7} {}".format(
        entities[i]+":",
        " ".join(perms) or "None"
    ))
```

Title: Decode the chmod

Body:
Python 3.5, 3.6 - 235 232 228 216 bytes

(should work on all Python 3.x)

So the input is on STDIN here (saves an import ☺).

a=input()
r=range
for i in r(3):
 p=int(a[i]);x=[["Read","Write","Execute"][j]for j in r(3)if 4>>j&p]
 if x[1:]:x[-1:-1]="and",
 if len(x)==1:x+="only",
 print(["User:  ","Group: ","Others:"][i]," ".join(x)or"None")

Making use of tuples, omitting spaces where possible and operator precedence where you would normally put parentheses to make your intentions clear.

Sample usage:

$ echo -n '666' | python3 golf2.py
User:   Read and Write
Group:  Read and Write
Others: Read and Write
$ echo -n '644' | python3 golf2.py
User:   Read and Write
Group:  Read only
Others: Read only
$ echo '042' | python3 golf2.py
User:   None
Group:  Read only
Others: Write only
$ echo '123' | python3 golf2.py
User:   Execute only
Group:  Write only
Others: Write and Execute
$ echo -n '777' | python3 golf2.py
User:   Read Write and Execute
Group:  Read Write and Execute
Others: Read Write and Execute

Un-golfed:

input_perms = list(map(int, input()))

entities = ["User", "Group", "Others"]
perm_names = ["Read", "Write", "Execute"]

for i in range(3):
    bits = input_perms[i]
    perms = [
        perm_names[j]
        for j in range(3)
        if (1 << (2-j)) & bits
    ]

    if len(perms) > 1:
        perms.insert(-1, "and")
    if len(perms) == 1:
        perms.append("only")

    print("{:7} {}".format(
        entities[i]+":",
        " ".join(perms) or "None"
    ))


答:
Batch, 409 bytes

```<code>echo off
set/pp=||exit/b1
set t=
set i=%p:|=&set t=%
if "%t%"=="" exit/b1
for /f "delims=0123456789" %%s in ("%i%")do exit/b1
:l
set t=-
set s=%p:|=&set t=%
if "%s%"=="" exit/b1
if not "%s%"=="%i%" exit/b1
set/ai+=1
for /f "delims=0123456789" %%s in ("%t%")do exit/b1
:m
if "%t:~1,1%"=="" goto n
if %t:~0,1% gtr %t:~1,1% exit/b1
set t=%t:~1%
goto m
:n
set/pp=&&goto l
if "%t%"=="" exit/b1
</code>```

Takes input on STDIN, but exits as soon as it sees an error.

Title: Validate a stem-and-leaf plot

Body:
Batch, 409 bytes

echo off
set/pp=||exit/b1
set t=
set i=%p:|=&set t=%
if "%t%"=="" exit/b1
for /f "delims=0123456789" %%s in ("%i%")do exit/b1
:l
set t=-
set s=%p:|=&set t=%
if "%s%"=="" exit/b1
if not "%s%"=="%i%" exit/b1
set/ai+=1
for /f "delims=0123456789" %%s in ("%t%")do exit/b1
:m
if "%t:~1,1%"=="" goto n
if %t:~0,1% gtr %t:~1,1% exit/b1
set t=%t:~1%
goto m
:n
set/pp=&&goto l
if "%t%"=="" exit/b1

Takes input on STDIN, but exits as soon as it sees an error.


答:
C# 5.0, 715 bytes

I know, this is huge. Just wanted to add a C# solution.

```<code>/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("[4]}}}}",f),w);Console.ReadKey();}}}
</code>```

The output is:

```<code>/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("(^_^)}}",f),w);Console.ReadKey();}}}
</code>```

Available at Ideone.com

Title: Source code GO!

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

Body:
C# 5.0, 715 bytes

I know, this is huge. Just wanted to add a C# solution.

/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("[4]}}}}",f),w);Console.ReadKey();}}}

The output is:

/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("(^_^)}}",f),w);Console.ReadKey();}}}

Available at Ideone.com


问:
Do the auto-super-logarithm
Given a positive integer n and a number a, the n-th tetration of a is defined as a^(a^(a^(...^a))), where ^ denotes exponentiation (or power) and the expression contains the number a exactly n times.

In other words, tetration is right-associative iterated exponentiation. For n=4 and a=1.6 the tetration is 1.6^(1.6^(1.6^1.6)) ≈ 3.5743.

The inverse function of tetration with respect to n is the super-logarithm. In the previous example, 4 is the super-logarithm of 3.5743 with "super-base" 1.6.

The challenge

Given a positive integer n, find x such that n is the super-logarithm of itself in super-base x. That is, find x such that x^(x^(x^(...^x))) (with x appearing n times) equals n.

Rules

Program or function allowed.

Input and output formats are flexible as usual.

The algorithm should theoretically work for all positive integers. In practice, input may be limited to a maximum value owing to memory, time or data-type restrictions. However, the code must work for inputs up to 100 at least in less than a minute.

The algorithm should theoretically give the result with 0.001 precision. In practice, the output precision may be worse because of accumulated errors in numerical computations. However, the output must be accurate up to 0.001 for the indicated test cases.

Shortest code wins.

Test cases

```<code>1    ->  1
3    ->  1.635078
6    ->  1.568644
10   ->  1.508498
25   ->  1.458582
50   ->  1.448504
100  ->  1.445673
</code>```

Reference implementation

Here's a reference implementation in Matlab / Octave (try it at Ideone).

```<code>N = 10; % input
t = .0001:.0001:2; % range of possible values: [.0001 .0002 ... 2]
r = t;
for k = 2:N
    r = t.^r; % repeated exponentiation, element-wise
end
[~, ind] = min(abs(r-N)); % index of entry of r that is closest to N
result = t(ind);
disp(result)
</code>```

For N = 10 this gives result =  1.5085.

The following code is a check of the output precision, using variable-precision arithmetic:

```<code>N = 10;
x = 1.5085; % result to be tested for that N. Add or subtract 1e-3 to see that
            % the obtained y is farther from N
s = num2str(x); % string representation
se = s;
for n = 2:N;
    se = [s '^(' se ')']; % build string that evaluates to iterated exponentiation
end
y = vpa(se, 1000) % evaluate with variable-precision arithmetic
</code>```

This gives:

For x = 1.5085: y = 10.00173...

For x = 1.5085 + .001: y = 10.9075

For x = 1.5085 - .001 it gives y = 9.23248.

so 1.5085 is a valid solution with .001 precision.

Title: Do the auto-super-logarithm

Body:
Haskell, <s>55</s> <s>54</s> 52 bytes

s n=[x|x<-[2,1.9999..],n>iterate(x**)1!!floor n]!!0

Usage:

> s 100
1.445600000000061

Thanks to @nimi for 1 byte!

Thanks to @xnor for 2!


问:
Produce the number 2014 without any numbers in your source code

Note to challenge writers as per meta consensus:
This question was well-received when it was posted, but challenges
like this, asking answerers to Do X without using
Y
are likely to be poorly received. Try using the
sandbox
to get feedback on if you want to post a similar challenge.

It's <s>2017</s> <s>2018</s> <s>2019</s> <s>2020</s> <s>2021</s> <s>2022</s> 2023 already, folks, go home.

So, now that it's 2014, it's time for a code question involving the number 2014.

Your task is to make a program that prints the number 2014, without using any of the characters 0123456789 in your code, and independently of any external variables such as the date or time or a random seed.

The shortest code (counting in bytes) to do so in any language in which numbers are valid tokens wins.

Leaderboard:

var QUESTION_ID=17005,OVERRIDE_USER=7110;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

```

答:
Fourier, 12 bytes

Non-competing: Fourier is newer than the challenge

I know I'm two years too late, but it seemed like a fun challenge to do in Fourier.

```<code>^^ovvo^o^^^o
</code>```

The command ^ increments the value of the accumulator (which starts at zero) and v decrements the value of the accumulator.

Try it online!

Body:
Fourier, 12 bytes

Non-competing: Fourier is newer than the challenge

I know I'm two years too late, but it seemed like a fun challenge to do in Fourier.

^^ovvo^o^^^o

The command ^ increments the value of the accumulator (which starts at zero) and v decrements the value of the accumulator.

Try it online!


答:
MATL, 14 bytes

```<code>')_`_*i't&Dwqh
</code>```

Produces the output ')_`_*i'(^_^)h.

Try it online!

Explanation

```<code>')_`_*i'  % Push this string
t&D       % Duplicate and get string representation (i.e. enclose with quotes)
w         % Swap
q         % Subtract 1. Transforms ')_`_*i' into the code points of '(^_^)h'
h         % Concatenate. Automatically casts code points to chars. Implicitly display
</code>```

Title: Source code GO!

Body:
MATL, 14 bytes

')_`_*i't&Dwqh

Produces the output ')_`_*i'(^_^)h.

Try it online!

Explanation

')_`_*i'  % Push this string
t&D       % Duplicate and get string representation (i.e. enclose with quotes)
w         % Swap
q         % Subtract 1. Transforms ')_`_*i' into the code points of '(^_^)h'
h         % Concatenate. Automatically casts code points to chars. Implicitly display


问:
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);

答:
C++ (<s>159</s> 136)

With templates.

```<code>#include<cstdio>
#define Z(A,B,C,D)template<A>struct P B{P(){C;printf("%d ",D);}};
Z(int N,,P<N-1>(),N)Z(,<1>,0,1)int main(){P<100>();}
</code>```

Body:
C++ (<s>159</s> 136)

With templates.

#include<cstdio>
#define Z(A,B,C,D)template<A>struct P B{P(){C;printf("%d ",D);}};
Z(int N,,P<N-1>(),N)Z(,<1>,0,1)int main(){P<100>();}


答:
Javascript, ES6: 77 bytes / ES7: <s>57</s> 53 bytes

ES6

```<code>n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")
</code>```

ES7

Using ** as suggested by DanTheMan:

```<code>n=>eval("for(x=2;eval('x**'.repeat(n)+1)>n;)x-=.001")
</code>```

Example

let f =
n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")

console.log(f(25));```

Title: Do the auto-super-logarithm

Body:
Given a positive integer n and a number a, the n-th tetration of a is defined as a^(a^(a^(...^a))), where ^ denotes exponentiation (or power) and the expression contains the number a exactly n times.

In other words, tetration is right-associative iterated exponentiation. For n=4 and a=1.6 the tetration is 1.6^(1.6^(1.6^1.6)) ≈ 3.5743.

The inverse function of tetration with respect to n is the super-logarithm. In the previous example, 4 is the super-logarithm of 3.5743 with "super-base" 1.6.

The challenge

Given a positive integer n, find x such that n is the super-logarithm of itself in super-base x. That is, find x such that x^(x^(x^(...^x))) (with x appearing n times) equals n.

Rules

Program or function allowed.

Input and output formats are flexible as usual.

The algorithm should theoretically work for all positive integers. In practice, input may be limited to a maximum value owing to memory, time or data-type restrictions. However, the code must work for inputs up to 100 at least in less than a minute.

The algorithm should theoretically give the result with 0.001 precision. In practice, the output precision may be worse because of accumulated errors in numerical computations. However, the output must be accurate up to 0.001 for the indicated test cases.

Shortest code wins.

Test cases

```<code>1    ->  1
3    ->  1.635078
6    ->  1.568644
10   ->  1.508498
25   ->  1.458582
50   ->  1.448504
100  ->  1.445673
</code>```

Reference implementation

Here's a reference implementation in Matlab / Octave (try it at Ideone).

```<code>N = 10; % input
t = .0001:.0001:2; % range of possible values: [.0001 .0002 ... 2]
r = t;
for k = 2:N
    r = t.^r; % repeated exponentiation, element-wise
end
[~, ind] = min(abs(r-N)); % index of entry of r that is closest to N
result = t(ind);
disp(result)
</code>```

For N = 10 this gives result =  1.5085.

The following code is a check of the output precision, using variable-precision arithmetic:

```<code>N = 10;
x = 1.5085; % result to be tested for that N. Add or subtract 1e-3 to see that
            % the obtained y is farther from N
s = num2str(x); % string representation
se = s;
for n = 2:N;
    se = [s '^(' se ')']; % build string that evaluates to iterated exponentiation
end
y = vpa(se, 1000) % evaluate with variable-precision arithmetic
</code>```

This gives:

For x = 1.5085: y = 10.00173...

For x = 1.5085 + .001: y = 10.9075

For x = 1.5085 - .001 it gives y = 9.23248.

so 1.5085 is a valid solution with .001 precision.

Body:
Javascript, ES6: 77 bytes / ES7: <s>57</s> 53 bytes

ES6

n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")

ES7

Using ** as suggested by DanTheMan:

n=>eval("for(x=2;eval('x**'.repeat(n)+1)>n;)x-=.001")

Example

let f =
n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")

console.log(f(25));


答:
Batch, 280 bytes

```<code>@echo off
set/pc=
call:l "User:   " %c:~0,1%
call:l "Group:  " %c:~1,1%
call:l "Others: " %c:~2,1%
exit/b
:l
for %%s in (None.0 Execute.1 Write.2 "Write and Execute.3" Read.4 "Read and Execute.5" "Read and Write.6" "Read Write and Execute.7") do if %%~xs==.%2 echo %~1%%~ns
</code>```

Hardcoding the strings was 47 bytes shorter than trying to piece them together. Would have been 267 bytes if tabs were legal.

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:
Batch, 280 bytes

@echo off
set/pc=
call:l "User:   " %c:~0,1%
call:l "Group:  " %c:~1,1%
call:l "Others: " %c:~2,1%
exit/b
:l
for %%s in (None.0 Execute.1 Write.2 "Write and Execute.3" Read.4 "Read and Execute.5" "Read and Write.6" "Read Write and Execute.7") do if %%~xs==.%2 echo %~1%%~ns

Hardcoding the strings was 47 bytes shorter than trying to piece them together. Would have been 267 bytes if tabs were legal.


答:
Python 2, <s>190</s> 185 bytes

```<code>def f(i):
 r,w,a,x,o,g="Read ","Write ","and ","Execute ","only",["User:  ","Group: ","Others:"];p=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+w+a+x]
 for z in 0,1,2:print g[z],p[int(i[z])]
</code>```

Leaves a trailing space if Execute or Write are at the end of the line but I didn't see that this wasn't allowed.

EDIT Saved 5 bytes by changing range(3) to 0,1,2 and checking byte count on my Linux laptop instead of my Windows one (\n = \r\n or the other way round. I can never remember which).

Title: Decode the chmod

Body:
Python 2, <s>190</s> 185 bytes

def f(i):
 r,w,a,x,o,g="Read ","Write ","and ","Execute ","only",["User:  ","Group: ","Others:"];p=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+w+a+x]
 for z in 0,1,2:print g[z],p[int(i[z])]

Leaves a trailing space if Execute or Write are at the end of the line but I didn't see that this wasn't allowed.

EDIT Saved 5 bytes by changing range(3) to 0,1,2 and checking byte count on my Linux laptop instead of my Windows one (\n = \r\n or the other way round. I can never remember which).


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:
JavaScript (ES6), 89 bytes

a=>a.map((_,i)=>[i,Math.random()]).sort((a,b)=>a[1]-b[1]).map(([i],j)=>[a[j][0],a[i][1]])


问:
Output an upside-down tent
Given an integer, output an upside-down tent.

The input determines both the size of the tent (absolute value) and whether the entrance is on the left side (negative numbers) or the right side (positive numbers).

```<code>If input = -1:
____
\/_/

If input = -2:
________
\  /   /
 \/___/

If input = -3:
____________
\    /     /
 \  /     /
  \/_____/

If input = 1:
____
\_\/

If input = 2:
________
\   \  /
 \___\/

If input = 3:
____________
\     \    /
 \     \  /
  \_____\/

et cetera
</code>```

Note that the top of the tent (i.e. the last line) has 2 * abs(input) - 1 underscores.

There can be no leading spaces, such that the first line directly starts with an underscore.

Assume that the input will never be 0.

Your code should be as short as possible.

This challenge is based on a chat mini challenge by Helka Homba, which is allowed to be used in real challenges under the conditions of Calvin's Hobbies Public License.

答:
PowerShell v2+, <s>217</s> <s>205</s> <s>190</s> <s>187</s> 184 bytes

```<code>param($b)"_"*(($a=[math]::Abs($b))*4);$z,$y='/\'[($b=$b-lt0),!$b]
((($x=1..$a|%{($w=" "*($_-1))+$z+" "*(2*($a-$_))+$y+(' ','_')[$_-eq$a]*($a*2-1)+$y+$w})|%{-join$_[($a*4)..0]}),$x)[$b]
</code>```

Takes input $b as an integer. Note that if $b is negative, you need to explicitly surround it with parens to cast it appropriately (see examples), else PowerShell will think it's a string.

Regardless of which direction the tent is facing, the first line is the same, a bunch of underscores; exactly 4*abs(input) many of them, actually. That number is also stored into $a for use later. Additionally, now that we have the absolute value of $b stored into $a, we turn $b into a Boolean for its sign, and choose our slashes stored into $y and $z.

The next line is constructing and formulating the output, and it's a doozy, so let's break it down.

We're essentially indexing into an array of two elements, (big long calculations saved into $x) or $x, based on $b.

The calculations are where the tent body is constructed. We loop from 1..$a|%{...}. Each iteration we're constructing a line of the tent body. We start with a number of spaces equal to the line # we're on -1, so that it's appropriately left-aligned. That's stored into $w for later, and concatenated with the appropriate slash ($z, based on $b), then the doorframe number of spaces, then the other slash $y, then either underscores or spaces depending upon if we're on the bottom line or not, then another slash $y, and finally the appropriate number of trailing spaces ($w) to construct a rectangular string. That resulting array of strings is stored into $x.

If the left half of the array is selected (i.e., $b is False since the input was positive), then we need to loop through $x and reverse each line item -- this is where the trailing spaces come into play; it allows us to simply reverse the lines rather than re-calculate distances.

If $b is True, then the right half of the array $x is selected instead.

In either case, the pipeline now contains an array of strings. Implicit output via Write-Output happens at program completion, with default newline between elements.

Examples

```<code>PS C:\Tools\Scripts\golfing> .\print-upside-down-tent.ps1 (-5)
____________________
\        /         /
 \      /         /
  \    /         /
   \  /         /
    \/_________/

PS C:\Tools\Scripts\golfing> .\print-upside-down-tent.ps1 (4)
________________
\       \      /
 \       \    /
  \       \  /
   \_______\/
</code>```

Title: Output an upside-down tent

Body:
PowerShell v2+, <s>217</s> <s>205</s> <s>190</s> <s>187</s> 184 bytes

param($b)"_"*(($a=[math]::Abs($b))*4);$z,$y='/\'[($b=$b-lt0),!$b]
((($x=1..$a|%{($w=" "*($_-1))+$z+" "*(2*($a-$_))+$y+(' ','_')[$_-eq$a]*($a*2-1)+$y+$w})|%{-join$_[($a*4)..0]}),$x)[$b]

Takes input $b as an integer. Note that if $b is negative, you need to explicitly surround it with parens to cast it appropriately (see examples), else PowerShell will think it's a string.

Regardless of which direction the tent is facing, the first line is the same, a bunch of underscores; exactly 4*abs(input) many of them, actually. That number is also stored into $a for use later. Additionally, now that we have the absolute value of $b stored into $a, we turn $b into a Boolean for its sign, and choose our slashes stored into $y and $z.

The next line is constructing and formulating the output, and it's a doozy, so let's break it down.

We're essentially indexing into an array of two elements, (big long calculations saved into $x) or $x, based on $b.

The calculations are where the tent body is constructed. We loop from 1..$a|%{...}. Each iteration we're constructing a line of the tent body. We start with a number of spaces equal to the line # we're on -1, so that it's appropriately left-aligned. That's stored into $w for later, and concatenated with the appropriate slash ($z, based on $b), then the doorframe number of spaces, then the other slash $y, then either underscores or spaces depending upon if we're on the bottom line or not, then another slash $y, and finally the appropriate number of trailing spaces ($w) to construct a rectangular string. That resulting array of strings is stored into $x.

If the left half of the array is selected (i.e., $b is False since the input was positive), then we need to loop through $x and reverse each line item -- this is where the trailing spaces come into play; it allows us to simply reverse the lines rather than re-calculate distances.

If $b is True, then the right half of the array $x is selected instead.

In either case, the pipeline now contains an array of strings. Implicit output via Write-Output happens at program completion, with default newline between elements.

Examples

PS C:\Tools\Scripts\golfing> .\print-upside-down-tent.ps1 (-5)
____________________
\        /         /
 \      /         /
  \    /         /
   \  /         /
    \/_________/

PS C:\Tools\Scripts\golfing> .\print-upside-down-tent.ps1 (4)
________________
\       \      /
 \       \    /
  \       \  /
   \_______\/


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&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(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.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(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

 ```

答:
J 4 bytes

I know this competition is probably dead but I wanted to put my answer in.

Just found this by accident

```<code>1 b.
</code>```

J 1 bytes

```<code>0
</code>```

Title: Golf you a quine for great good!

Body:
J 4 bytes

I know this competition is probably dead but I wanted to put my answer in.

Just found this by accident

1 b.

J 1 bytes

0


答:
Python 2, <s>143 141 139 138</s> 137 bytes

-2 bytes thanks to @Sp3000 (no need to parenthesise exec in Python 2)

-1 byte thanks to @Sp3000 (use cmp)

```<code>def f(n):d=cmp(n,0);a,b='\/'[::-d];s=n*d;x=2*s-1;y=4*s;print'_'*y;i=0;exec"print' '*i+(b+' '*(y-3-x-i-i)+a+'_ '[s-i>1]*x+a)[::d];i+=1;"*s
</code>```

Test it at ideone

First we see if n is negative and make d +1 if it is and -1 if not.

Then we select the two slashes, a and b, using d such that a='\', b='/' when n is positive and a='/', b='\' when n is negative.

Next we set s=abs(n) which may be achieved by s=n*d.

Then we calculate the number of _ at the top (bottom of the picture), which is also the number of  in the side of the tent as x=2*s-1.

Then we calculate the number of _ at the base of the tent (top of the picture), and store it as y=4*s since it will be used in the loop to create the rest of the tent.

Now we print the base of the tent using print'_'*y.

Then we print the rest of the tent by executing s print statements with a looping variable i initialised to 0 which increments by 1 for each print statement.

The rest of the tent then has y-3-x-i-i spaces in the door and x spaces in the body until the top is reached, when s-i>1 evaluates to False, picking the _ from '_ '.

For a positive, left-door, tent the whole of the tent, excluding the leading spaces is back-to-front, so it is reversed while the positive, 'right-door', tent is not with [::d].

Title: Output an upside-down tent

Body:
Given an integer, output an upside-down tent.

The input determines both the size of the tent (absolute value) and whether the entrance is on the left side (negative numbers) or the right side (positive numbers).

```<code>If input = -1:
____
\/_/

If input = -2:
________
\  /   /
 \/___/

If input = -3:
____________
\    /     /
 \  /     /
  \/_____/

If input = 1:
____
\_\/

If input = 2:
________
\   \  /
 \___\/

If input = 3:
____________
\     \    /
 \     \  /
  \_____\/

et cetera
</code>```

Note that the top of the tent (i.e. the last line) has 2 * abs(input) - 1 underscores.

There can be no leading spaces, such that the first line directly starts with an underscore.

Assume that the input will never be 0.

Your code should be as short as possible.

This challenge is based on a chat mini challenge by Helka Homba, which is allowed to be used in real challenges under the conditions of Calvin's Hobbies Public License.

Body:
Python 2, <s>143 141 139 138</s> 137 bytes

-2 bytes thanks to @Sp3000 (no need to parenthesise exec in Python 2)

-1 byte thanks to @Sp3000 (use cmp)

def f(n):d=cmp(n,0);a,b='\/'[::-d];s=n*d;x=2*s-1;y=4*s;print'_'*y;i=0;exec"print' '*i+(b+' '*(y-3-x-i-i)+a+'_ '[s-i>1]*x+a)[::d];i+=1;"*s

Test it at ideone

First we see if n is negative and make d +1 if it is and -1 if not.

Then we select the two slashes, a and b, using d such that a='\', b='/' when n is positive and a='/', b='\' when n is negative.

Next we set s=abs(n) which may be achieved by s=n*d.

Then we calculate the number of _ at the top (bottom of the picture), which is also the number of  in the side of the tent as x=2*s-1.

Then we calculate the number of _ at the base of the tent (top of the picture), and store it as y=4*s since it will be used in the loop to create the rest of the tent.

Now we print the base of the tent using print'_'*y.

Then we print the rest of the tent by executing s print statements with a looping variable i initialised to 0 which increments by 1 for each print statement.

The rest of the tent then has y-3-x-i-i spaces in the door and x spaces in the body until the top is reached, when s-i>1 evaluates to False, picking the _ from '_ '.

For a positive, left-door, tent the whole of the tent, excluding the leading spaces is back-to-front, so it is reversed while the positive, 'right-door', tent is not with [::d].


答:
TSQL, 195 bytes

Golfed:

```<code>DECLARE @ INT=-2
DECLARE @b INT=ABS(@),@i INT=0PRINT REPLICATE('_',4*@b)z:SET @i+=1PRINT SPACE(@i-1)+'\'+STUFF(REPLICATE(IIF(@i<@b,' ','_'),4*@b-2*@i),@b*2-IIF(@<0,@i*2-1,0),1,IIF(@<0,'/','\'))+'/'IF @i<@b GOTO z
</code>```

Ungolfed:

```<code>DECLARE @ INT=-2

DECLARE @b INT=ABS(@),@i INT=0

PRINT REPLICATE('_',4*@b)
z:
  SET @i+=1
  PRINT
    SPACE(@i-1)+'\'
    +STUFF(REPLICATE(IIF(@i<@b,' ','_'),
      4*@b-2*@i),@b*2-IIF(@<0,@i*2-1,0),1,IIF(@<0,'/','\'))
    +'/'
IF @i<@b GOTO z
</code>```

Fiddle

Title: Output an upside-down tent

Body:
TSQL, 195 bytes

Golfed:

DECLARE @ INT=-2
DECLARE @b INT=ABS(@),@i INT=0PRINT REPLICATE('_',4*@b)z:SET @i+=1PRINT SPACE(@i-1)+'\'+STUFF(REPLICATE(IIF(@i<@b,' ','_'),4*@b-2*@i),@b*2-IIF(@<0,@i*2-1,0),1,IIF(@<0,'/','\'))+'/'IF @i<@b GOTO z

Ungolfed:

DECLARE @ INT=-2

DECLARE @b INT=ABS(@),@i INT=0

PRINT REPLICATE('_',4*@b)
z:
  SET @i+=1
  PRINT
    SPACE(@i-1)+'\'
    +STUFF(REPLICATE(IIF(@i<@b,' ','_'),
      4*@b-2*@i),@b*2-IIF(@<0,@i*2-1,0),1,IIF(@<0,'/','\'))
    +'/'
IF @i<@b GOTO z

Fiddle


答:
Javascript (ES6), 139 bytes

Builds the tent recursively:

```<code>f=(N,n=N>0?N:-N,i=0,r=(j,i)=>' _'[i||0].repeat(j),a=`\\${r(i)}/`,b=r(n*2+i-1,+!i))=>n--?f(N,n,i+2)+`
`+r(n)+(N<0?a+b+'/':'\\'+b+a):r(i*2,1)
</code>```

Ungolfed and commented

```<code>f = (
  N,                                  // N is the original parameter (remains unchanged)
  n = N > 0 ? N : -N,                 // n is initialized to abs(N)
  i = 0,                              // i is the row counter (*2)
  r = (j, i) => ' _'[i||0].repeat(j), // helper function to repeat ' ' or '_' j times
  a = `\\${r(i)}/`,                   // a = '\ /' pattern
  b = r(n*2+i-1, +!i)                 // b = padding pattern filled with ' ' or '_'
) =>
  n-- ?                               // if we haven't made it yet to the top row:
    f(N, n, i+2) + `\n` +             //   - compute next row(s) / append line break
    r(n) +                            //   - append leading spaces
    (N < 0 ? a+b+'/' : '\\'+b+a)      //   - append a/b patterns according to N sign
  :                                   // else:
    r(i*2, 1)                         //   - return top row, made of '_' characters
</code>```

Examples

var f=(N,n=N>0?N:-N,i=0,r=(j,i)=>' _'[i||0].repeat(j),a=`\\${r(i)}/`,b=r(n*2+i-1,+!i))=>n--?f(N,n,i+2)+`
`+r(n)+(N<0?a+b+'/':'\\'+b+a):r(i*2,1)

console.log(f(3));
console.log(f(-4));```

Title: Output an upside-down tent

Body:
Javascript (ES6), 139 bytes

Builds the tent recursively:

f=(N,n=N>0?N:-N,i=0,r=(j,i)=>' _'[i||0].repeat(j),a=`\\${r(i)}/`,b=r(n*2+i-1,+!i))=>n--?f(N,n,i+2)+`
`+r(n)+(N<0?a+b+'/':'\\'+b+a):r(i*2,1)

Ungolfed and commented

f = (
  N,                                  // N is the original parameter (remains unchanged)
  n = N > 0 ? N : -N,                 // n is initialized to abs(N)
  i = 0,                              // i is the row counter (*2)
  r = (j, i) => ' _'[i||0].repeat(j), // helper function to repeat ' ' or '_' j times
  a = `\\${r(i)}/`,                   // a = '\ /' pattern
  b = r(n*2+i-1, +!i)                 // b = padding pattern filled with ' ' or '_'
) =>
  n-- ?                               // if we haven't made it yet to the top row:
    f(N, n, i+2) + `\n` +             //   - compute next row(s) / append line break
    r(n) +                            //   - append leading spaces
    (N < 0 ? a+b+'/' : '\\'+b+a)      //   - append a/b patterns according to N sign
  :                                   // else:
    r(i*2, 1)                         //   - return top row, made of '_' characters

Examples

var f=(N,n=N>0?N:-N,i=0,r=(j,i)=>' _'[i||0].repeat(j),a=`\\${r(i)}/`,b=r(n*2+i-1,+!i))=>n--?f(N,n,i+2)+`
`+r(n)+(N<0?a+b+'/':'\\'+b+a):r(i*2,1)

console.log(f(3));
console.log(f(-4));


答:
J, <s>39</s> <s>31</s> 28 bytes

```<code>(>./@(]*[>^/@#"0)1+i.%])&1e4
</code>```

Based on the reference implementation. It is only accurate to three decimal places.

Saved 8 bytes using the method from @Adám's solution.

Usage

Extra commands used to format multiple input/output.

```<code>   f =: (>./@(]*[>^/@#"0)1+i.%])&1e4
   (,.f"0) 1 3 6 10 25 50 100
  1      0
  3  1.635
  6 1.5686
 10 1.5084
 25 1.4585
 50 1.4485
100 1.4456
   f 1000
1.4446
</code>```

Explanation

```<code>(>./@(]*[>^/@#"0)1+i.%])&1e4  Input: n
                         1e4  The constant 10000
(                      )      Operate on n (LHS) and 10000 (RHS)
                   i.           The range [0, 10000)
                      ]         Get (RHS) 10000
                     %          Divide each in the range by 10000
                 1+             Add 1 to each
     (          )               Operate on n (LHS) and the range (RHS)
             #"0                  For each in the range, create a list of n copies
          ^/@                     Reduce each list of copies using exponentation
                                  J parses from right-to-left which makes this
                                  equivalent to the tetration
        [                         Get n
         >                        Test if each value is less than n
      ]                           Get the initial range
       *                          Multiply elementwise
 >./@                           Reduce using max and return
</code>```

Title: Do the auto-super-logarithm

Body:
J, <s>39</s> <s>31</s> 28 bytes

(>./@(]*[>^/@#"0)1+i.%])&1e4

Based on the reference implementation. It is only accurate to three decimal places.

Saved 8 bytes using the method from @Adám's solution.

Usage

Extra commands used to format multiple input/output.

   f =: (>./@(]*[>^/@#"0)1+i.%])&1e4
   (,.f"0) 1 3 6 10 25 50 100
  1      0
  3  1.635
  6 1.5686
 10 1.5084
 25 1.4585
 50 1.4485
100 1.4456
   f 1000
1.4446

Explanation

(>./@(]*[>^/@#"0)1+i.%])&1e4  Input: n
                         1e4  The constant 10000
(                      )      Operate on n (LHS) and 10000 (RHS)
                   i.           The range [0, 10000)
                      ]         Get (RHS) 10000
                     %          Divide each in the range by 10000
                 1+             Add 1 to each
     (          )               Operate on n (LHS) and the range (RHS)
             #"0                  For each in the range, create a list of n copies
          ^/@                     Reduce each list of copies using exponentation
                                  J parses from right-to-left which makes this
                                  equivalent to the tetration
        [                         Get n
         >                        Test if each value is less than n
      ]                           Get the initial range
       *                          Multiply elementwise
 >./@                           Reduce using max and return


答:
Racket 187 bytes

```<code>(define(f x n)(define o 1)(for((i n))(set! o(expt x o)))o)
(define(ur y(l 0.1)(u 10))(define t(/(+ l u)2))(define o(f t y))
(cond[(<(abs(- o y)) 0.1)t][(> o y)(ur y l t)][else(ur y t u)]))
</code>```

Testing:

```<code>(ur 1)
(ur 3)
(ur 6)
(ur 10)
(ur 25)
(ur 50)
(ur 100)
</code>```

Output:

```<code>1.028125
1.6275390625
1.5695312499999998
1.5085021972656247
1.4585809230804445
1.4485038772225378
1.4456728475168346
</code>```

Detailed version:

```<code>(define (f x n)
  (define out 1)
  (for((i n))
    (set! out(expt x out)))
  out)

(define (uniroot y (lower 0.1) (upper 10))
  (define trying (/ (+ lower upper) 2))
  (define out (f trying y))
  (cond
    [(<(abs(- out y)) 0.1)
     trying]
    [(> out y)
     (uniroot y lower trying)]
    [else
      (uniroot y trying upper)]))
</code>```

Title: Do the auto-super-logarithm

Body:
Racket 187 bytes

(define(f x n)(define o 1)(for((i n))(set! o(expt x o)))o)
(define(ur y(l 0.1)(u 10))(define t(/(+ l u)2))(define o(f t y))
(cond[(<(abs(- o y)) 0.1)t][(> o y)(ur y l t)][else(ur y t u)]))

Testing:

(ur 1)
(ur 3)
(ur 6)
(ur 10)
(ur 25)
(ur 50)
(ur 100)

Output:

1.028125
1.6275390625
1.5695312499999998
1.5085021972656247
1.4585809230804445
1.4485038772225378
1.4456728475168346

Detailed version:

(define (f x n)
  (define out 1)
  (for((i n))
    (set! out(expt x out)))
  out)

(define (uniroot y (lower 0.1) (upper 10))
  (define trying (/ (+ lower upper) 2))
  (define out (f trying y))
  (cond
    [(<(abs(- out y)) 0.1)
     trying]
    [(> out y)
     (uniroot y lower trying)]
    [else
      (uniroot y trying upper)]))


答:
Swift 2.2 421 bytes

Well... This was an attempt.

Golfed:

```<code>let t={(s:String,n:Int)->String in return String(count:n,repeatedValue:Character(s))};let e={(n:Int)in var w=[String]();w.append(t("_",abs(n)*4));let c = abs(n);let d = n>0 ? "/": "\\";let f = n>0 ? "\\": "/";for var i in 0...abs(n)-1 {w.append(t(" ",i)+d+t(" ",c*2-2-(2*i))+f+(i<c-1 ?t(" ",2*c-1)+f:t("_",2*c-1)+f)+(n>0 ?t(" ",i):""));};w=n<0 ?w:w.map(){String($0.characters.reverse())};print(w.joinWithSeparator("\n"))}
</code>```

UnGolfed:

```<code>let t={(s:String,n:Int) -> String in
    return String(count:n,repeatedValue:Character(s))
};
let e={(n:Int) in
    var w=[String]();
    w.append(t("_",abs(n)*4));
    let c = abs(n);
    let d = n>0 ? "/": "\\";
    let f = n>0 ? "\\": "/";
    for var i in 0...abs(n)-1 {
        w.append(t(" ",i)+d+t(" ",c*2-2-(2*i))+f+(i<c-1 ?t(" ",2*c-1)+f:t("_",2*c-1)+f)+(n>0 ?t(" ",i):""));
    };
    w=n<0 ?w:w.map(){String($0.characters.reverse())};
    print(w.joinWithSeparator("\n"))
}
</code>```

Title: Output an upside-down tent

Body:
Swift 2.2 421 bytes

Well... This was an attempt.

Golfed:

let t={(s:String,n:Int)->String in return String(count:n,repeatedValue:Character(s))};let e={(n:Int)in var w=[String]();w.append(t("_",abs(n)*4));let c = abs(n);let d = n>0 ? "/": "\\";let f = n>0 ? "\\": "/";for var i in 0...abs(n)-1 {w.append(t(" ",i)+d+t(" ",c*2-2-(2*i))+f+(i<c-1 ?t(" ",2*c-1)+f:t("_",2*c-1)+f)+(n>0 ?t(" ",i):""));};w=n<0 ?w:w.map(){String($0.characters.reverse())};print(w.joinWithSeparator("\n"))}

UnGolfed:

let t={(s:String,n:Int) -> String in
    return String(count:n,repeatedValue:Character(s))
};
let e={(n:Int) in
    var w=[String]();
    w.append(t("_",abs(n)*4));
    let c = abs(n);
    let d = n>0 ? "/": "\\";
    let f = n>0 ? "\\": "/";
    for var i in 0...abs(n)-1 {
        w.append(t(" ",i)+d+t(" ",c*2-2-(2*i))+f+(i<c-1 ?t(" ",2*c-1)+f:t("_",2*c-1)+f)+(n>0 ?t(" ",i):""));
    };
    w=n<0 ?w:w.map(){String($0.characters.reverse())};
    print(w.joinWithSeparator("\n"))
}


问:
Sort a list of numbers
About Code-Bowling:

In golf, you try to get the lowest score (smallest application, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.

The Challenge:

Create a program that sorts a list of numbers in ascending order.

Example:

Input: 1, 4, 7, 2, 5

Output: 1, 2, 4, 5, 7

Code: Obviously this wouldn't be a good answer, since there aren't many WTFs in there

```<code>function doSort(array $input) {
    sort($input);
    return $input;
}
</code>```

Rules:

There are no real rules.  As long as the program functions, have at it!

Remember: This is code-bowling, not golf.  The objective is to make the worst, most bastardized code that you can!  Bonus points for code that looks good, but is actually deceptively evil...

答:
```<code>class Array
  def sort
    self.permutation.min
  end
end
</code>```

<p>Ah, the elegance of Ruby...
self.permutation results in an enumerator. No harm done, yet. The innocent looking .min however sucks this enumerator into an array. This array's size explodes when the number of elements rises. Not to mention this ruines a fine pre-existing sort. </p>

ContentLicense: CC BY-SA 2.5

Title: Sort a list of numbers

Body:
class Array
  def sort
    self.permutation.min
  end
end

Ah, the elegance of Ruby...
self.permutation results in an enumerator. No harm done, yet. The innocent looking .min however sucks this enumerator into an array. This array's size explodes when the number of elements rises. Not to mention this ruines a fine pre-existing sort.


问:
Test if given number is a Keith number
Since Fibonacci numbers and sequences seems like a popular subject for code golf I thought that it might be a fun challenge to code golf with Keith numbers.

So I propose a challenge that is to create a function that takes an integer and gives back a true or false depending on the number is a Keith number or not.

More about Keith numbers

In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
  14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, …

Numberphile has a video explaining how to calculate a Keith number. But basically you take the digits of a number. Add them together and then take the last digits of the original number and add them to the sum of the calculation, rinse and repeat. And example to make it clear.

14
1 + 4 = 5

  4 + 5 = 9

  5 + 9 = 14

Input

An integer.

Output

True if the number is a Keith number. False if it's not..

答:
F# - 184 chars

I hope it's ok that I'll participate in my own challenge.

```<code>let K n=
let rec l x=if n<10 then false else match Seq.sum x with|v when v=n->true|v when v<n->l(Seq.append(Seq.skip 1 x)[Seq.sum x])|_->false
string n|>Seq.map(fun c->int c-48)|>l
</code>```

Edit Fixed a bug regarding small numbers.

Title: Test if given number is a Keith number

Body:
F# - 184 chars

I hope it's ok that I'll participate in my own challenge.

let K n=
let rec l x=if n<10 then false else match Seq.sum x with|v when v=n->true|v when v<n->l(Seq.append(Seq.skip 1 x)[Seq.sum x])|_->false
string n|>Seq.map(fun c->int c-48)|>l

Edit Fixed a bug regarding small numbers.


Title: Output an upside-down tent

Body:
Python 2, 121 bytes

def f(n):i=k=abs(n);print'_'*k*4;exec"print' '*(k-i)+r'\\\%%s%\*%c%%*sc/'[n<0::2]%(' _'[i<2]*(2*k-1))%(2*i-1,47);i-=1;"*k

Just a lot of string formatting.