title: Calculate the sum of ILD

text:
# Question
Title: Calculate the sum of ILD
### Input:

An integer

### Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```
nr + nr-length + {sum of digits} = output

```

### Examples:

Input: `99`
Output: `99` (nr) `+ 2` (nr-length) `+ (9 + 9)` (digits) → `119`

Input: `123`
Output: `123 + 3 + (1 + 2 + 3)``132`

### Challenge rules:

* The input can also contain negative input, which are resolved special. The `-`/minus-sign is also `+1` for the length, and is part of the first `digit`.
For example:

Input: `-123`
Output: `-123 + 4 + (-1 + 2 + 3)``-115`
* You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

### Test cases:

```
87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886

```

Semi-related: Count Sum of all Digits

# Answer
# Thunno 2 `s`, 7 bytes

```
Ðls'+jE

```

Try it online! or verify all test cases

#### Explanation

```
Ðls'+jE  '# Implicit input
Ð         # Triplicate input
 l        # Push its length
  s       # Swap to get input
   '+j   '# Join on "+"
      E   # Evaluate as Python
          # Sum the stack
          # Implicit output

```
> 1 votes

# Answer
# Python 2, 39 bytes

```
lambda x:x+len(`x`)+eval("+".join(`x`))

```

Test suite

Using the same eval-trick as in my Pyth-answer.
> 13 votes

# Answer
## 05AB1E, ~~28~~ ~~20~~ ~~18~~ 8 bytes

```
ÐgsS'+ýO

```

**Explanation**

```
Ð           # triplicate input
 g          # get length of input
  sS'+ý     # split input and merge with '+' as separator
       O    # sum and implicitly display

```

Try it online

Saved 10 bytes thanks to @Adnan
> 10 votes

# Answer
# Pyth, ~~11~~ 10 bytes

Thanks to @LeakyNun for a byte!

```
++vj\+`Ql`

```

Test suite

## Explanation

```
++vj\+`Ql`QQ  # Q = input, last two implicitly added

  vj\+`Q      # Join the input on '+' and eval it
        l`Q   # Length of the input
           Q  # The input itself
++            # Add those three values to obtain the result

```
> 9 votes

# Answer
# Brachylog, ~~35~~ 32 bytes

```
~~lL,?:ef+:?:L+I,(0>?h:2*:Ir-:1+.;I.)~~
lL,(0>?h:1--I;I0),?b:ef+:?:L:I+.

```

### Explanation

```
lL,             L is the length of the Input
(
    0>?         Input < 0
       h:1--I   I is (First digit - 1) * -1
;               Or
    I0          I is 0
),
?b:ef+          Sum all digits of the Input
      :?:L:I+.  Output = sum of digits + (Input minus first digit) + L + I

```
> 7 votes

# Answer
# CJam, 18

```
q_,\~__Ab(@g*\~]:+

```

Try it online

**Explanation:**

```
q_      read the input and make a copy
,\      get the string length and swap with the other copy
~__     evaluate the number and make 2 copies
Ab      convert to base A=10 (array of digits), it uses the absolute value
(       take out the first digit
@g*     get a copy of the number, get its sign and multiply with the digit
\~      dump the other digits on the stack
]:+     add everything together

```
> 7 votes

# Answer
# XSLT 1.0 (without EXSLT), 673 bytes

```
<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><param name="i"/><template match="/"><variable name="d"><variable name="s">0<if test="0>$i">1</if></variable><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,$s+2)"/></call-template></variable><value-of select="substring($i,1,$s+1)+$d"/></variable><value-of select="$i+string-length($i)+$d"/></template><template name="d"><param name="i"/>0<if test="$i!=''"><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,2)"/></call-template></variable><value-of select="substring($i,1,1)+$d"/></if></template></transform>

```

Lightly inflated:

```
<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <output method="text"/>
    <param name="i"/>
    <template match="/">
        <variable name="d">
            <variable name="s">0<if test="0>$i">1</if></variable>
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,$s+2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,$s+1)+$d"/>
        </variable>
        <value-of select="$i+string-length($i)+$d"/>
    </template>
    <template name="d">
        <param name="i"/>0<if test="$i!=''">
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,1)+$d"/>
        </if>
    </template>
</transform>

```

Run using xsltproc:

```
xsltproc --param i -87901 ild.xsl ild.xsl

```

Yes, `ild.xsl` is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.
> 6 votes

# Answer
# Dyalog APL, ~~19~~ ~~17~~ 16 bytes

```
≢+#⍎'\d'⎕R'&+',⊢

```

Takes string and returns

length
`+` plus
`#` in root namespace
evaluation of
`'\d'⎕R'&+'` regex append digits with a plus
`,` followed by
the unmodified string

–3 thanks to ngn
> 4 votes

# Answer
# MATL, 20 bytes

```
tVtnw48-PZ}t0<?x_]vs

```

**Try it Online**

All test cases

**Explanation**

```
        % Implicitly grab the input
tV      % Duplicate the input and convert to a string
tn      % Duplicate and find the length of this string
w       % Flip the top two stack elements to get us the string again
48-     % Subtract 48 (ASCII 'O'). Yields a negative number for a negative sign
        % and digits otherwise
P       % Flip the resulting array
Z}      % Break the array up so each element is pushed to the stack
t0<?    % If the first character was a negative sign
  x_    % Pop the negative sign off the stack and negate the first digit
]       % End of if
vs      % Vertically concatenate and sum all stack contents
        % Implicitly display the result

```
> 4 votes

# Answer
# Clojure, 102 bytes

```
(fn[n](load-string(str"(+ "n" "(count(str n))" "(apply str(map #(if(= % \-)%(str %" "))(str n)))")")))

```

Anonymous function which constructs a string that looks like `(+ -123 4 -1 2 3 )` and evals it. Everything pretty verbose as it is, construct string from number, its length, and then map each symbol of string representation of the number except minus to itself plus space and minus remains the same

You can see it running here: https://ideone.com/FG4lsB
> 4 votes

# Answer
## Matlab, ~~76~~ 67 bytes

```
n=input('');t=num2str(n)-48;if(n<0)t(1)=0;t(2)=-t(2);end
n+sum(t+1)

```

9 bytes saved thanks to @Luis Mendo

**Explanation:**

```
n=input('');     -- takes input
t=num2str(n)-48; -- makes it a string and then array of digits with "-" becoming -3 (48 is code for 0)
if(n<0)
t(1)=0;          -- set first element (-3) to 0
t(2)=-t(2);      -- the second element is the most significant digit, so we have to negate it
end
n+sum(t+1)       -- take sum of n, sum of all digits and length of t
                    (guaranteed by +1 of every element)

```
> 3 votes

# Answer
# dc, 57 bytes

```
dc -e"0 1?rdsc*d[1r]s+d0>+dZr[+la10~lc*rdsaZ1<A]sAdsaZ1<Ala+++f"

```

Explained:

```
0 1      # Push 0, then 1 on the stack
?        # Wait for input from stdin
         # If input is negative, the leading minus will subtract 1 from 0
r        # Swap (rotate) top two items on stack.
         # Stack status if input (`$') was...
         #       positive                    negative
         # TOP       1     <- coefficient ->    -1
         #           $                           $
         #           0
dsc      # Store a copy of coefficient in `c'
*        # Multiply input by coefficient:
         #  If input was positive, it stays positive.
         #  If input was negative, it's actually interpreted as positive.
         #   In this case, multiply by -1 to make it negative.
d        # Duplicate signed input
[1r]s+   # Define a function `+': Push 1 and rotate
d 0>+    # If input is negative, push 1 underneath the top of the stack
         # This 1 represents the length of the `-` in the input
         # Note that the stack now has 3 items on it, regardless of input sign
dZ       # Push the length of the input (not including leading minus)
r        # Rotate, moving a copy of the input to the top
[        # Begin function definition
 +       # Add top two items of stack
 la      # Load value from `a' (which holds nothing at time of function definition)
 10~     # Slice the last digit off `a' (spoiler: `a' is going to hold the input while
         #  we gather its digits)
 lc*     # Multiply digit by coefficient
         #  Since the input is signed, the input modulo 10 will have the same sign.
         #  We want all digits to be positive, except the leftmost digit, which should
         #   have the sign of the input.
         #  This ensures that each digit is positive.
 r       # Rotate: move remaining digits to top of stack
 dsa     # Store a copy of the remaining digits in `a'
 Z 1<A   # Count the number of digits left; if more than 1, execute A
]sA      # Store the function as `A'
d sa     # Store a copy of the input in `a'
         #  Props to you if you're still reading this
Z 1<A    # Count the number of digits left; if more than 1, execute A
la       # Load leftmost digit of input (still signed appropriately)
+++      # Add the top four items on the stack
f        # Dump stack

```

This was far more complicated than I had expected! Good challenge :)
> 3 votes

# Answer
## Bash + coreutils, 36 bytes

```
bc<<<$1+${#1}+$(sed s:\\B:+:g<<<0$1)

```

**Explanation:**

```
     $1+                      # the input number (+)
     ${#1}+                   # the length of the number, the '-' sign included (+)
     $(sed s:\\B:+:g<<<0$1)   # insert '+' between two consecutive word characters
                              #A word character is any letter, digit or underscore.
bc<<<                         # calculate the sum

```

In sed, `\B` also matches between two consecutive non-word characters, so for a negative number it matches between '^' and '-'. Note the `0$1` trick needed for `\B` to give `0-1+2+3`, for example.

**Run example:** 'input.txt' contains all the test cases in the question's statement

```
while read N;do echo "$N -> "$(./ILD_sum.sh "$N");done < input.txt

```

**Output:**

```
87901 -> 87931
123 -> 132
99 -> 119
5 -> 11
1 -> 3
0 -> 1
-3 -> -4
-99 -> -96
-123 -> -115
-900 -> -905
-87901 -> -87886

```
> 3 votes

# Answer
# Java 8, ~~174~~ ~~136~~ ~~122~~ ~~107~~ ~~105~~ ~~93~~ 78 bytes

```
i->{int f=0;for(int j:(i+"").getBytes())i+=j<48?f++:f-->0?50-j:j-47;return i;}

```

-14 bytes thanks to *@LeakyNun*.
-15 bytes thanks to *@cliffroot*.

**Explanation:**

Try it online.

```
i->{                   // Method with integer as both parameter and return-type
  int f=0;             //  Integer-flag, starting at 0
  for(int j:(i+"").getBytes())
                       //  Loop over the digits as bytes
    i+=                //   Increase the input with:
       j<48?           //    If the current byte is '-':
        f++            //     Increase the input with the flag-integer `f` (which is 0),
                       //     and increase the flag-integer `f` by 1 afterwards
       :               //    Else:
        f-->0?         //     If the flag-integer `f` is 1,
                       //     and decrease the flag-integer `f` back to 0 afterwards
         50-j          //      Increase it with 50 minus the current byte
        :              //    Else
         j-47;         //     Increase it with the byte as digit
                       //      + 1 to cover for the length part in ILD
  return i;}           //  Return the modified input as result

```
> 2 votes

# Answer
## C#, 118 bytes

```
int k(int a){var s=a.ToString();for(int i=0;i<s.Length;a+=s[i]<46?-(s[++i]-48)+ ++i-i:(s[i++]-48));return a+s.Length;}

```
> 2 votes

# Answer
# C#, 106 bytes

I beat java my a byte, my life is complete

```
int r(int n){var s=n+"";return n+s.Length+s.Select((k,j)=>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();}

```

Ungolfed (kinda)

```
    public static int r(int n)
    {
            var s = n + "";
            return n + s.Length + s.Select((k, j) =>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();
    }

```
> 2 votes

# Answer
## PowerShell v4, 48 bytes

```
param($n)$n,"$n".length+[char[]]"$n"-join'+'|iex

```

This *should* work in v2+, but I only tested in v4.

Takes input `$n`. Creates a new array with the `,` operator consisting of `$n` and the `.length` when `$n` is converted to a string. Concatenates with that the string `$n` cast as a char-array. Then, that whole array is `-join`ed together with `+` before being piped to `iex` (similar to `eval`). The result is left on the pipeline and output is implicit.

For example, for input `-123`, the array would look like `(-123, 4, -, 1, 2, 3)`, and the string after the `-join` would look like `-123+4+-+1+2+3`. Then the `Invoke-Expression` happens, and the result is `-115` as expected.
> 2 votes

# Answer
# Factor with `load-all`, 175 bytes

Well, this is not very short. The special handling of unary minus is really annoying; I guess I could do it better and I will, maybe.

```
[ dup [ 10 >base length ] [ [ 10 >base >array [ 48 - ] V{ } map-as ] [ 0 < ] bi [ reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip ] [ ] if 0 [ + ] reduce ] bi + + ]

```

Using this substitution regex:

```
s/(-?[\d]+)\s*->\s*(-?[\d]+)/{ $2 } [ $1 calculate-ild ] unit-test/g

```

We can turn the OP's test cases into a Factor test suite.

```
USING: arrays kernel math math.parser sequences ;
IN: sum-ild

: sum-digits ( n -- x )
    [ number>string >array [ 48 - ] V{ } map-as ]
    [ 0 < ]
    bi
    [
      reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip
    ]
    [ ] if
    0 [ + ] reduce ;

: calculate-ild ( n -- x )
  dup
  [ number>string length ]
  [ sum-digits ]
  bi + + ;

USING: tools.test sum-ild ;
IN: sum-ild.tests

{ 87931 } [ 87901 calculate-ild ] unit-test
{ 132 } [ 123 calculate-ild ] unit-test
{ 119 } [ 99 calculate-ild ] unit-test
{ 11 } [ 5 calculate-ild ] unit-test
{ 3 } [ 1 calculate-ild ] unit-test
{ 1 } [ 0 calculate-ild ] unit-test
{ -4 } [ -3 calculate-ild ] unit-test
{ -115 } [ -123 calculate-ild ] unit-test
{ -905 } [ -900 calculate-ild ] unit-test
{ -87886 } [ -87901 calculate-ild ] unit-test

```
> 2 votes

# Answer
# SpecBAS - 147 bytes

```
1 INPUT a$: l=LEN a$: b$="text "+a$+"+"+STR$ l+"+": FOR i=1 TO l: b$=b$+a$(i)+("+" AND i<l): NEXT i: EXECUTE b$

```

Builds up a string which then gets run. Unfortunately `EXECUTE` doesn't work with the `?` shorthand for `PRINT`, but `TEXT` saved 1 character.
> 2 votes

# Answer
# Perl 5, 22 + 1 (-p) = 23 bytes

```
$_+=eval s//+/gr.y///c

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), 38 bytes

```
n=>eval([n+=``,n.length,...n].join`+`)

```

Uses the old join-and-eval trick. Save 4 bytes if I can insist on string input:

```
f=
n=>eval([n,n.length,...n].join`+`)
;
```

```
<input type=number oninput=o.value=f(this.value)><input id=o readonly>
```
> 1 votes

# Answer
# Perl 6 - 30 bytes

As literal as it gets

```
{$^a+$^a.chars+[+]($^a.comb)}

```

Use it as an anonymous function

```
> {$^a+$^a.chars+[+]($^a.comb)}(99)
119

```
> 1 votes

# Answer
**C++, 255 Bytes**

```
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
    string input;
    cin >> input;
    int sum = atoi(input.c_str()) + input.length();
    for(unsigned i = 0; i < input.length(); ++i)
        sum += input.at(i) - 48;
    return 0;
}

```
> 1 votes

# Answer
## Perl 5 - 37 Bytes

```
warn eval(join'+',/./g)+($_+=()=/./g)

```

Input is in $\_
> 1 votes

# Answer
# C, ~~132~~ ~~116~~ ~~113~~ 80

```
t,c;f(char*v){for(c=atoi(v+=t=*v==45);*v;t=0,++v)c+=t?50-*v-2*c:*v-47;return c;}

```

Function `f()` takes the input as a string and returns the result as an integer. Full program version (113 bytes):

```
t;main(int c,char**v){char*p=v[1];c=atoi(p+=t=*p==45);for(c=t?-c:c;*p;++p,t=0)c+=t?50-*p:*p-47;printf("%d\n",c);}

```

Requires one argument.
> 1 votes

# Answer
## Javascript (using external library) (45 bytes)

Using a library I wrote to bring LINQ to Javascript, I was able to write the following:

```
(i)=>i+(i+"").length+_.From(i+"").Sum(x=>x|0)

```
> 1 votes

# Answer
## Perl, 27 bytes

**22 bytes code + 5 for `-paF`.**

```
$"="+";$_+=@F+eval"@F"

```

### Explanation

Uses the `-a` autosplit option with an empty delimiter (`-F`) creating an array of the digits passed in. Uses the magic variable `$"` which controls which char is used to join an array when it's interpolated into a string (we use `"+"` here) and the fact that a list used in scalar context will return the length of the list (the number of digits).

### Usage

```
echo -n 99 | perl -paF -e'$"="+";$_+=@F+eval"@F"'
119

```

---

## Perl, 27 bytes

**22 bytes code + 5 for `-paF`.**

Alternative solution, that's a lot more readable for no more bytes. I prefer the other as it looks more cryptic!

```
$_+=@F+eval join"+",@F

```
> 1 votes

# Answer
## dc, 56 bytes

```
?dZrdd1sa[1+r0r-_1sa]sb0>b[A~rd0<x]dsxxrla*[+z1<y]dsyxp

```

No shorter than Joe's above, but a somewhat different implementation (and one that takes negative numbers as input vs. a subtraction command). Can probably be golfed more, but lunch only lasts so long.

```
?                #input
dZrdd            #find no. of digits, rotate to bottom of stack, dup input twice
1sa              #coefficient for first digit stored in register 'a'
[1+r0r-_1sa]sb   #macro 'b' executes on negative numbers. add one (for the neg. sign)
                 #rotate this value out of the way, leave a positive copy on top
0>b              #run the above macro if negative
[A~rd0<x]dsxx    #create and run macro 'x'; mod 10 to grab least significant digit
                 #keep doing it if quotient is greater than zero
rla*             #a zero remains in the way of our most significant digit, rotate it down
                 #and multiply said digit by our coefficient 'a' from earlier
[+z1<y]dsyx      #add two top stack values (we left that zero there to ensure this always
                 #works), check stack depth and keep doing it while there's stack
p                #print!

```
> 1 votes

# Answer
# RProgN, 30 Bytes

```
] '' . ] '-?.' | sum _ \ L + +

```

## Explination

```
]               # Clone the input
                #
'' . ]          # Convert it to a string, then clone it again.
'-?.' | sum     # Split it into chunks via the pattern '-?.' (A - if there is one, followed by a single character). Sum the resulting array.
_               # Floor the value, purely because I hate floats.
\ L + +         # Swap the top value with the value underneith it, to work with the string again. Get it's length, add the top, middle, and bottom, which is now the length, the sum and the input respectively.

```

Try it Online!
> 1 votes

# Answer
## R, 108 bytes

A bit late to the party again but here it goes:

```
s=strsplit(paste(n<-scan()),"")[[1]];n+nchar(n)+sum(as.integer(if(n<0)c(paste0(s[1],s[2]),s[1:2*-1])else s))

```

In order to generally split the digits of any number (e.g. to sum them), R requires us to first convert to a string and subsequently split the string into a string vector. To sum up the elements, the string vector has to be converted to numeric or integer. This together with the exception with the sum of a the digits of a negative number eats up a lot of bytes.

The exception can be golfed a bit (to 96 bytes) if warning messages are allowed.

```
s=as.integer(strsplit(paste(n<-scan()),"")[[1]]);if(n<0){s[2]=s[2]*-1;s=s[-1]};n+nchar(n)+sum(s)

```

In this case the string vector is converted to integer directly using `as.integer`. However, for negative numbers the first element in the vector will be a minus sign: `"-"`. This causes some trouble, e.g.: `as.numeric(c("-",1,2,3))` will return `NA 1 2 3` and a warning message. To circumvent this, remove the NA and then multiply the first element with `-1` before taking the sum.
> 1 votes

# Answer
# AWK, ~~64 63~~ 61 bytes

```
{s=j=0;for(;j++<n=split($1,a,"");s+=$1>0||j-2?a[j]:-a[j]);$0+=n+s}1

```

Try it online!

TIO link has 6 extra bytes `s=j=0;` to allow for multi-line input. This is the shortest method I could come up with. I'm curious if it can be done shorter in `AWK`.

Saved 2-bytes, thanks Kevin
> 1 votes

# Answer
# Add++, 15 bytes

```
L,bU"+"jvAbLAvs

```

Try it online!

## How it works

```
L,		; Create a lambda function. Takes a string argument
		; Example argument: 	['123']
	bU	; Unpack;	STACK = ['1' '2' '3']
	"+"j	; Join with +;	STACK = ['1+2+3']
	v	; Evaluate;	STACK = [6]
	AbL	; Arg length;	STACK = [6 3]
	Av	; Int argument;	STACK = [6 3 123]
	s	; Sum;		STACK = [132]

```
> 1 votes

# Answer
# C# 77 bytes

Check it here

Golfed:

```
int r(int n){return n+(n+"").Length+(n+"").Select(c=>int.Parse(c+"")).Sum();}

```

Ungolfed:

```
 public int r(int n)
 {
     var t = n + (n+"").Length;
     t += (n + "").Select(c => int.(c + "")).Sum();
     return t;
 }

```
> 0 votes

# Answer
# Pyt, 7 bytes

```
ĐąŁ⇹ĐŚƩ

```

Try it online!

Shortest as of now!

```
Đ         duplicate
 ąŁ       convert to array of digits, pop, and push length
   ⇹Đ     swap top two values and duplicate
     ŚƩ   sum of digits and sum everything on stack

```
> 0 votes

---
Tags: code-golf, number, arithmetic, integer
---


title: Count My Change

text:
# Question
Title: Count My Change
Your task is to sort an array containing the strings "quarter", "dime", "nickel", and "penny" any number of times in no specific order and sort them so that they are in this order: `quarter dime nickel penny` (in other words, greatest to least monetary value).

---

## Rules

1. Your program must take an array as input containing the names of U.S coins and sort them from greatest to least by monetary value.
    * For those who are not from the U.S or don't use change, the values of U.S coins, from greatest to least, are:
        + Quarter: 25 cents
        + Dime: 10 cents
        + Nickel: 5 cents
        + Penny: 1 cent
2. You may sort this array in any way you wish, as long as the output is ordered by the monetary values shown above.
3. Input can be taken in any way, be it command-line arguments or STDIN.
4. An input array would be all lowercase strings, something like this:
    * `quarter dime nickel nickel quarter dime penny penny`
5. The actual format of input and output is up to you.

---

## Test Cases

```
"penny nickel dime quarter"
-> "quarter dime nickel penny"

"nickel penny penny quarter quarter quarter dime dime dime dime"
-> "quarter quarter quarter dime dime dime dime nickel penny penny"

"quarter dime nickel nickel quarter dime penny penny"
-> "quarter quarter dime dime nickel nickel penny penny"

```

---

This is , so standard rules & loopholes apply.

# Answer
> 27 votes
# Japt, ~~5~~ 3 bytes

```
ñg9

```

Test it online!

### Explanation

I, too, have added a sorting function to my language in the last few weeks :-) `ñ` takes in an array and a function and sorts the array as if each item had been mapped through that function.

The `g` function on a string takes in a number `n` and returns the `n`th char in the string, wrapping if `n` is negative or past the end of the string. The strings can thus be aligned as follows:

```
quarterqu**a**rter...
dimedimed**i**medi...
nickelnic**k**elni...
pennypenn**y**penn...

```

The 9th char (0-indexed) of each string has been highlighted in bold. These are in the correct order, so all we have to do is `ñg9`. (Though now that I look back on it, `ñg5` would work as well...)

# Answer
> 8 votes
# , 7 bytes

```
ú/¨qu©¿

```

Try it online!

This uses the spiffy new *sort* command I added to V around a week ago (`ú`). Sweet timing!

The way this works is by sorting every line by default sorting (ASCII values) but ignoring the first match of a certain regex. In this case, the regex is `(qu)?`, although it has some gross non-ASCII stuff to avoid using backslashes. If you ignore the first two letters of "quarter", it starts with 'a', and then all of the coins are already in alphabetical order.

# Non-competing version, 4 bytes

```
ú!/.

```

This feature was already implemented, but I hadn't tested it extensively yet so it had a bug that I only realized because of this challenge. There is no TIO link because TIO is slightly behind.

This works by reverse sorting every line but ignoring the first character on each line.

# Answer
> 8 votes
# Python, 36 bytes

```
lambda a:a.sort(key=lambda x:x[-5:])

```

Unnamed function that sorts the list in-place by the key function given.

The slices of each coin name are then, `arter`, `dime`, `ickel`, and `penny` \- which are in alphabetical (or more importantly, ordinal) order.

# Answer
> 7 votes
# Bash + coreutils, 18

```
tr q b|sort|tr b q

```
* Transliterate q to b
* Sort
* Transliterate b back to q

Try it online.

# Answer
> 6 votes
# Python 3, ~~42~~ ~~41~~ 38 bytes

An unnamed lambda function which takes input as a list of strings, sorts in place.

*(Outgolfed by Jonathan Allan)*

```
lambda x:x.sort(key=lambda s:(s*2)[5])

```

**Try it online!**

Other solutions I messed around with:

```
lambda x:x.sort(key=lambda s:s*(s<'q'))
lambda x:x.sort(key=lambda s:(s+'pi')[5])
lambda x:x.sort(key=lambda s:ord(s[3])%16)

```

# Answer
> 5 votes
# Jelly, 4 bytes

```
6ịµÞ

```

**Try it online!** (the footer, `ÇY`, joins the resulting list with line feeds for a prettier print out.)

### How?

```
6ịµÞ - Main link: list of strings
  µ  - monadic chain separation
   Þ - sort the list of strings by the monadic function:
6ị   - the sixth index - Jelly indexing is modular and 1-based

```

The Nth index of a list in Jelly is the Nth item starting at the left, counting from 1, and looping back to the start when need be. (The 0th is at the right, the -1th one left of that and so on too).

So the sixth character of `['d','i','m','e']` is `'i'` since six is congruent to two modulo four.

The sixth character of the four coins in order are quart`e`r, d`i`me, nicke`l`, `p`enny . These are in alphabetical (or more importantly, ordinal) order.

---

Another way to achieve the same thing would be to sort by the rotated strings with `ṙ5µÞ`, where  rotates to the right, making the strings `erquart`, `imed`, `lnicke`, and `penny`.

# Answer
> 5 votes
# PowerShell, 21 bytes

```
$args|sort{($_*3)[9]}

```

Try it online!

### Explanation

Shamelessly stole the algorithm in ETHproductions's answer (basically). I multiply each string by 3, then sort based on the 9th character of the resulting string.

# Answer
> 5 votes
# Bash (+coreutils) 11 bytes

**Golfed**

```
sort -rk1.2

```

**How It Works**

Reverse sort, with the "sort key" from the second character of the first field (word) till the end of line, i.e.:

```
uarter
ime
ickel
enny

```

**Test**

```
>echo penny nickel dime quarter|tr ' ' '\n'|sort -rk1.2

quarter
dime
nickel
penny

```

Try It Online !

# Answer
> 5 votes
# Python, 32 bytes

```
lambda s:s.sort(key="npr".strip)

```

Try it online! Sorts the list in place.

The idea is to use a sorting key function without a `lambda`. A good candidate was `x.strip`, which takes the string `x` and removes its the left and right edges all characters in the input. For example, `"abcdef".strip("faces") == "bcd"`.

The method `"npr".strip` takes:

```
quarter ->  np
dime    ->  npr
nickel  ->  pr
penny   ->  r

```

which are lexicographically sorted. I found the string `npr` by brute force. `npu` and `npt` also work, and there are none shorter.

# Answer
> 4 votes
# CJam, 8 bytes

```
q~{5=}$p

```

Try it online!

**Explanation**

```
q~        Get and eval all input (array of coin names)
  {5=}$   Sort the array by the 5th index of each element (array indices loop in CJam)
       p  Print the result

```

# Answer
> 3 votes
## Pyke, ~~9~~ ~~7~~ 5 bytes

```
.#5R@

```

Try it here!

```
.#5R@ - sort_by:
  5R@ -  i[5]

```

# Answer
> 3 votes
# Retina, 10

* 6 10 bytes saved thanks to @ETHproductions

```
q
b
O`
b
q

```
* Substitute `q` to `b`
* Sort
* Substitute `b` back to `q`

Try it online.

# Answer
> 3 votes
# , ~~8~~ 7 bytes

*1 byte saved thanks to @DJMcMayhem*

```
Úçq/:m0

```

\[Try it online!\]

See @DJMcMayhem's answer in V (~~1~~ 0 bytes shorter than mine)

Try it online!

```
Ú                    " sort all lines "
 ç                   " globally "
  q/                 "  where there a q is matched, "
    :m0              "  move it to the top of the buffer "

```

Here is an older solution at 1 byte larger, but I really like it.

### , 8 bytes

```
Ú/q
dGHP

```

\[Try it online!\]

Try it online!

### Explanation

```
Ú        " sorts the lines

```

Now the buffer will be in this format:

```
dimes
nickels
pennies
quarters

```

The only thing left to do now is to move the quarters to the top.

```
/q      " search for a q "
dG      " delete everything from the first quarter to the end of buffer "
HP      " and paste it at the top of the buffer

```

# Answer
> 3 votes
# Japt, 3 bytes

```
ñé5

```

Try it online!

---

## A couple other 3-byte solutions:

```
üÅw

```

Try it online!

---

```
ü é

```

Try it onlin!

# Answer
> 1 votes
# T-SQL, ~~41~~ ~~36~~ 34 bytes

```
select*from @ order by right(a,5)

```

### Explanation

Assume the input is pre-loaded in a table variable named `@`, with a single column named `a`, where each value is one coin to be sorted.

The `select * from @` part is boiler-plate 'get all values to return'. The real magic happens in the `order by` clause.

Using the same strategy as Johnathan Allan, I sort by the last five characters (SQL will return the entire string if it's too short): `arter`, `dime`, `ickel`, `penny`.

# Answer
> 1 votes
## JavaScript (ES6), ~~35~~ 33 bytes

```
a=>a.sort(([,...a],[,...b])=>b>a)

```

### Test cases

```
let f =

a=>a.sort(([,...a],[,...b])=>b>a)

console.log(f(['penny','nickel','dime','quarter']).join` `);
console.log(f(['nickel','penny','penny','quarter','quarter','quarter','dime','dime','dime','dime']).join` `);
console.log(f(['quarter','dime','nickel','nickel','quarter','dime','penny','penny']).join` `);
```

# Answer
> 1 votes
# Befunge, 158 bytes

```
~:0`v0v4<~_
9:%8_^>8*`^1p9\+1g
$:!#@_1-0" ynnep">:#,_>
1-0" lekcin">:#,_>$:!#^_
" emid">:#,_>$:!#^_1-0
>:#,_$1>-:!#^_0" retrauq"
*84g9< ^*84g91-*84g94-*84g96-

```

Try it online!

String processing and sorting are not the sorts of things you'd typically want to attempt in Befunge, but this solution is taking advantage of John Kasunich's observation that we don't actually need to sort anything. We just count the number of occurrences of each coin (which can easily be determined from the first character), and then output that many of each coin name in the appropriate order.

It's still not at all competitive with other languages in terms of size, but this approach is at least better than it would have been if we'd tried to handle the challenge as a string sorting exercise.

# Answer
> 1 votes
# Pyth, 3 bytes

```
@D5

```

Demonstration

Based on ETHproductions's answer in Japt.

Explanation:

```
@D5
@D5Q    Variable introduction
 D Q    Sort the input by
@ 5     Its fifth character

```

# Answer
> 1 votes
# APL (Dyalog APL), 11 bytes

Takes and returns list of strings.

```
{⍵[⍋↑5⌽¨⍵]}

```

Try it online!

`{` anonymous function:

`⍵[``]` the argument indexed by

the ascending-making indices of

the matrix whose rows are the padded

`5⌽` five-steps-rotated

`¨⍵` items of the argument

`}`

# Answer
> 1 votes
# Brachylog, 3 bytes

```
↺₉ᵒ

```

Try it online!

Approach stolen from ETHproductions' Japt answer.

```
       The input
  ᵒ    sorted by
↺      its elements rotated left
 ₉     by 9
       is the output.

```

# Answer
> 1 votes
# Husk, 3 bytes

```
Öṙ9

```

Try it online!

Ported from my Brachylog answer, which rips off ETHproductions' Japt answer but isn't an exact translation since it uses rotation instead of simple accessing-the-nth-element. There, I did it because  doesn't let you index past the end of the input (which is probably quite helpful in many circumstances due to the declarative nature of the language). In Husk, `!` *does* let you index past the end of the input, with the same modular wrapping around that Japt `ñg9` uses, but it's from 1 so this program in particular would end up being one byte longer: `Ö!10`.

```
Ö      Sort by
 ṙ     rotation by
  9    9.

```

# Answer
> 1 votes
# Vyxal, 3 bytes

```
µ5i

```

Try it Online! or Run all the test cases

## How?

```
µ5i
µ   # Sort by:
 5i #  Index 5 into the list (zero-indexed, modular)

```

Port of Jelly.

# Answer
> 0 votes
## Batch, 82 bytes

```
@for %%c in (quarter dime nickel penny)do @for %%a in (%*)do @if %%a==%%c echo %%c

```

Takes input as command-line arguments and outputs to STDOUT. Works by concatenating the lists resulting from filtering the original list on each coin.

# Answer
> 0 votes
# Ruby, 34 bytes

```
->m{m.sort_by{|c|c[1..2]}.reverse}

```

input and output as an array of strings

# Answer
> 0 votes
## Ruby, 31 bytes

```
->s{s.sort_by{|i|i[1]}.reverse}

```

# Answer
> 0 votes
# Ruby, 30 bytes

```
->m{m.sort_by{|s|s[3].ord^16}}

```

Magical numbers found by trial and error. A bit clumsy, but shorter than using `.reverse`.

# Answer
> 0 votes
# Perl 6,  ~~40 36~~  34 bytes

```
*.sort: {(<q d n p>Zxx 1..*).Bag{~m/./}}

```

Try it

```
*.sort: {%(<q d n p>Z=>1..*){~m/./}}

```

Try it

```
*.sort: {%(<q d n p>Z=>^4){~m/./}}

```

Try it

## Expanded:

```
*\            # WhateverCode lambda ( this is the parameter )

.sort:        # sort using the following code block

{             # bare block lambda with implicit parameter ｢$_｣

  %(          # treat this list as a hash

    <q d n p> # list of first characters
    Z[=>]     # zipped using pair constructor
    ^4        # Range from 0 up-to 4 ( excludes 4 )

  ){          # get the value associated with this key

    ~m/./     # regex which gets the first character ( implicitly from ｢$_｣ )

  }

}

```

# Answer
> 0 votes
# java 8, ~~128~~ 112 bytes

This is a lambda expression for a `java.util.function.Function<String[],String[]>`

```
s->{String r="";for(String k:"q d c p".split(" "))for(String t:s)if(t.contains(k))r+=" "+t;return r.split(" ");}

```

Explantion: For each of the 4 coins in order, go through the input and append the coin's name to the result every time there is a match for that coin's unique character. Split the result into an array and return it.

# Answer
> 0 votes
# Mathematica, 50 bytes

```
Flatten@{Last@#,Most@#}&@Split@Sort@StringSplit@#&

```

# Answer
> 0 votes
# RProgN, 18 bytes

```
~{3mtt¢\3mtt¢>}$

```

## Explained

```
~               # Zero Space Segment
 {            } # Anonymous Function
  3m            # Repeat the inputted string 3 times
    tt¢         # And take the tenth character of that
       \3mtt¢   # Do the same for the entry underneith
             >  # Compare the ascii value of the two
               $# Sort the input by the anonymous function.

```

Try it online!

# Answer
> 0 votes
## Ruby, 27 bytes

```
->s{s.sort_by{|x|(x*2)[5]}}

```

# Answer
> 0 votes
# Smalltalk, 42 bytes

```
a sort:[:s :t|s allButFirst>t allButFirst]

```

**Explanation**

```
a              input array
sort:          sort message, criterion in the block
[:s :t |       block arguments, represent entries of the input array
allButFirst    copy the receiving string without its first character
>              alphabetic comparison

```

# Answer
> 0 votes
## Perl 6 (19 bytes)

Takes a list of strings.

```
*.sort(*.comb[5%*])

```

In action:

```
my &f = *.sort(*.comb[5%*]);
say f(<quarter dime nickel nickel quarter dime penny penny>);

```

# Answer
> 0 votes
# Thunno 2, 3 bytes

```
Þ9i

```

Try it online!

Port of ETHProductions's Japt answer - sort by 9th character.

---
Tags: code-golf, string, array, sorting
---


title: Reverse and square

text:
# Question
Title: Reverse and square
In this challenge you will compute numbers from a curious sequence.

Your input is a single decimal nonnegative integer. Reverse the bits in this integer and then square the number to get the required output.

When reversing the bits you must not use any leading zeroes in the input. For example:

```
26 (base 10) = 11010 (base 2) -> 01011 (base 2) = 11 -> 11*11 = 121

```

The first 25 inputs/outputs of this sequence:

```
0: 0
1: 1
2: 1
3: 9
4: 1
5: 25
6: 9
7: 49
8: 1
9: 81
10: 25
11: 169
12: 9
13: 121
14: 49
15: 225
16: 1
17: 289
18: 81
19: 625
20: 25
21: 441
22: 169
23: 841
24: 9

```

Your solution should work for arbitrarily sized integers. If your language does not have a convenient built-in method of using those, implement your answer as if it does. You are then excused if your answer breaks for large numbers. However, do not use tricks/bounds that only work for a limited domain (such as a lookup table).

---

Your score is the number of bytes of source code.

**-50% bonus if you never convert the number to/from binary.** This is not limited to builtins, if you loop over the number bit by bit (either by shifting or masking or any other method), it will also count as conversion. *I don't know whether this is actually possible, but it gives an incentive to spot a pattern in the sequence.*

Smallest score wins.

# Answer
> 5 votes
# Par, 5 bytes

```
✶Σ⌐Σ²

```

That's read-binary-reverse-binary-square.

# Answer
> 21 votes
## Mathematica, ~~42~~ 21 bytes

*Thanks to alephalpha for halving the score.*

```
#~IntegerReverse~2^2&

```

The actual reason I did this in Mathematica was because I wanted to look at a plot... it sure looks funny:

# Answer
> 8 votes
# Japt, ~~29~~ ~~28~~ ~~11~~ 7 bytes

(You can save the program as a 7-byte IEC\_8859-1-encoded file, then upload it to the interpreter.)

Japt is shortened JavaScript made by ETHproductions.

```
¢w n2 ²

```

Try it online!

Explanation:

1. `¢` is shortcut to `Us2`, which compiles to `U.s(2)`. `U` is input (implicit), `.s(2)` called by a number, invokes `.toString(2)` (converts to binary, parses as string).
2. `w` compiles to `.w()`, which reverses the string (`.split('').reverse().join('')`).
3. `n2` works as `parseInt(<number>,2)`, i.e. converts binary to decimal.
4. `²` invokes `Math.pow(<number>,2)`, i.e. squares the number.

# Answer
> 7 votes
## Minkolang 0.14, 43 bytes

Thanks to Mego for inspiring this.

```
n1{d1`,2$3*&$z2zd2%-2l$Md1%-;z2%*z2:{+}2;N.

```

Test the code here and check all test cases here.

### Explanation

This uses this recurrence relation:

```
a(0) = 0
a(1) = 1
a(2n) = a(n)
a(2n+1) = a(n) + 2^(floor(log_2(n))+1)

```

If `n` is the input, then `a(n)` is the resulting number after its binary sequence has been flipped. 0 and 1 are obvious. For `a(2n) = a(n)`, consider that `x0` (where `x` is any sequence of binary digits) flipped is `0x`, which is the same as `x`. For `a(2n+1)`, the reasoning is a bit more complicated. `x1` flipped is `1x`, which is equal to `x + 2^k` for some `k`. This `k` is one more than the number of digits in `x`, which is `floor(log_2(n))+1`. The full formula follows, except that it's modified a bit. This is what I actually code:

```
a(0) = 0
a(1) = 1
a(n) = a(n//2) + (n%2) * 2^(floor(log_2(n - n%2)))

```

As Mego and I worked out in chat, `floor(n/2) = (n - n%2)/2`. Thus, `log_2(floor(n/2))+1 = log_2(n - n%2)`. Furthermore, multiplying by `(n%2)` collapses both the odd and even parts into one expression.

Finally, without any further ado, here's the code, explained.

```
n                                              Take number from input
 1{                                            Start recursion that takes only one element
   d1`,                                        1 if top of stack 0 or 1, 0 otherwise
       2$3*                                    26
           &                                   Jump if top of stack is not zero
            $z                                 Store top of stack in register (z)

               zd2%-                           n - n%2
                    2l$M                       log_2(n - n%2)
                        d1%-                   floor(log_2(n - n%2))
              2             ;                  2^floor(log_2(n - n%2))
                             z2%               n%2
                                *              Multiply
                                 z2:           n//2
                                    {          Recurse
                                     +         Add
                                      }        Return
                                       2;N.    Square it, output as number, and stop.

```

# Answer
> 6 votes
# Python, 32 bytes

```
lambda x:int(bin(x)[:1:-1],2)**2

```

Try it online.

The code is pretty straightforward: `bin(6)`, for example, gives `0b110`, the binary representation of 6. `[:1:-1]` reverses the string and removes `0b`. `int` converts the string to an integer from binary, and `**2` squares it.

# Answer
> 5 votes
# Jolf, 7 bytes

Just run it. The input on the page doesn't work.

```
^C_Bj22

```

## Explanation

```
^C_Bj22
    j   numeric input
   B    convert to binary (str)
  _     reverse
 C   2  parse as binary integer to base 10
^     2 square
        implicit output

```

---

I added the `Q` command, which makes this 6 bytes: `QC_Bj2`

# Answer
> 4 votes
# TeaScript, 9 bytes ~~11~~

TeaScript is Javascript for golfing

```
®x÷v¤)**2

```

Will golf more once I get back to my computer

Try it online!

Test all

# Answer
> 4 votes
# J, ~~10~~ 9 bytes

```
2^~|.&.#:

```

This is a tacit, monadic verb. Try it online!

*Thanks to @randomra for golfing off 1 byte!*

### How it works

```
2^~|.&.#:  Right argument: y

       #:  Convert y to binary.
   |.      Reverse the digits.
     &.    Dual; apply the inverse of #:, i.e., convert back to integer.
 ^~        Apply power (^) with reversed argument order (~)...
2          to 2 and the previous result.

```

# Answer
> 4 votes
## Seriously, ~~8~~ 7 bytes

```
2;,¡R¿ª

```

Challenges like these are perfect for Seriously :)

Try it online

Explanation:

```
2;,¡    get a string representing the (decimal) input in binary, with a 2 on the bottom of the stack
R      reverse the string
¿    convert binary string to decimal int (using that extra 2 from earlier)
ª      square it

```

# Answer
> 3 votes
## Perl 6, 21 bytes

```
{:2(.base(2).flip)²}

```

Example usage:

```
say {:2(.base(2).flip)²}(26); # 121

say (0..24).map: {:2(.base(2).flip)²};
# (0 1 1 9 1 25 9 49 1 81 25 169 9 121 49 225 1 289 81 625 25 441 169 841 9)

my &code = {:2(.base(2).flip)²};
say code 3; # 9

say chars code 10¹⁰⁰; # 140

```

# Answer
> 2 votes
# JavaScript, ~~64~~ ~~63~~ ~~56~~ 53 bytes

```
n=>parseInt([...n.toString(2)].reverse().join``,2)**2

```

I realize I'm extra long, but hey, I can do it :P

Demo

# Answer
> 2 votes
# CJam, 10 bytes

```
ri2bW%2b_*

```

Try it online

# Answer
> 2 votes
# Shell, 25

```
dc -e2o?p|rev|dc -e2i?d*p

```

Input/output via STDIN/STDOUT:

```
$ echo 26|dc -e2o?p|rev|dc -e2i?d*p
121
$

```

# Answer
> 2 votes
# PHP, 45 bytes

```
echo pow(bindec(strrev(decbin($argv[1]))),2);

```

# Answer
> 2 votes
# Ruby, 35 bytes

```
->(x){x.to_s(2).reverse.to_i(2)**2}

```

# Answer
> 2 votes
# 05AB1E, 4 bytes

```
bRCn

```

Try it online!

# Explanation

```
     Implicit input
b    Convert to binary
 R   Reverse
  C  Convert from binary
   n Square
     Implicit output

```

# Answer
> 2 votes
# MathGolf, 4 bytes

```
àxå²

```

Try it online.

**Explanation:**

```
à     # Convert the (implicit) input-integer to a binary-string
 x    # Reverse this string
  å   # Convert it from a binary-string back to an integer
   ²  # Take the square of this integer
      # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 2 votes
# Vyxal, 4 bytes

```
bṘB²

```

Try it Online!

```
bṘB²
bṘB  # Convert to binary, reverse, convert back to decimal
   ² # Square

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 40 bytes

```
#+##&~Fold~Reverse@IntegerDigits[#,2]^2&

```

Try it online!

# Answer
> 2 votes
# Desmos, ~~124~~ 72 bytes

```
f(n)=total(mod(floor(n/2^l),2)2^k/2^l)^2
k=floor(log_2(n+0^n))
l=[k...0]

```

Try it on Desmos!

*-52 bytes thanks to Aiden Chow*

# Answer
> 2 votes
# Haskell, 38 bytes

```
(#0)
0#s=s^2
n#s=div n 2#(2*s+n`mod`2)
```

Attempt This Online!

# Answer
> 1 votes
# Pyth - 9 bytes

Straightforward conversions. I actually assigned 2 to a var which is pretty weird.

```
^i_jQK2KK

```

Test Suite.

# Answer
> 1 votes
# , 12 chars / 21 bytes

```
⦅`ᶀ`+ᴙ(ïß2)²

```

`Try it here (Firefox only).`

## Noncompetitive answer, 9 chars / 18 bytes

```
⦅Յ+ᴙ(ïⓑ)²

```

`Try it here (Firefox only).`

# Answer
> 1 votes
## Pyth, 9 bytes

```
^i_.BQ2 2

```

This is a very simple pyth based answer similar to the Python one

# Answer
> 1 votes
# TI-Basic (TI-84 Plus CE), 42 bytes

```
Prompt X
0→S
While X
2S→S
If X/2≠int(X/2
S+1→S
End
S<sup>2</sup>

```

# Answer
> 1 votes
# C (gcc), 38 bytes

```
r;f(n){for(r=n%2;n/=2;r+=r+n%2);r*=r;}

```

Reverse all the bits, square the result. Pretty standard.

*-1 byte thanks to ceilingcat!*

Try it online!

# Answer
> 1 votes
# Splunk (v8.2.6) Search Processing Language, 182 170 bytes:

```
|inputcsv b|foreach *[eval x=<<FIELD>>]|eval p=mvrange(0,floor(log(x,2)+1))|mvexpand p|eval x=floor(x/pow(2,p))%2|stats list(x) as x|eval x=tonumber(mvjoin(x,""),2),x=x*x

```

Big data. Smallish code.

Am learning Splunk for work, and decided to try to have a bit of fun with it.

Input is expected in a file at $SPLUNK\_HOME/var/run/splunk/csv/b.csv. The file must contain the number in base 10 followed by a newline. The output is the search result, which is analogous to an SQL `SELECT`. This is as close to our standard I/O rules as I could reasonably do in SPL, but I'm willing to work something out if this is problematic.

With whitespace:

```
| inputcsv b
| foreach * [eval x=<<FIELD>>]
| eval p=mvrange(0,floor(log(x,2)+1))
| mvexpand p
| eval x=floor(x/pow(2,p))%2
| stats list(x) as x
| eval x=tonumber(mvjoin(x,""),2),x=x*x

```

Explanation (I plan to flesh this out more later):

| inputcsv b                            ``` Read in b ```
| foreach * [eval x=<<FIELD>>]          ``` Get the value into a field "x" (Splunk reads our "CSV" file in as an event with one field, named the value we want, with a value of the empty string.) ```
| eval p=mvrange(0,floor(log(x,2))+1)   ``` Create a multivalue field "p" which contains the numbers 0 to the number of bits required to represent our number, the order here also means we get the reverse for free ```
| mvexpand p                            ``` Expand our single event with a multivalue field "p" into multiple events, each with a certain value of p ```
| eval x=floor(x/pow(2,p))%2            ``` Calculate (x/(2**p))%2, and set that value back to x```
| stats list(x) as x                    ``` Collect the values of x back into a single multivalue event ```
| eval x=tonumber(mvjoin(x,""),2),x=x*x ``` Combine all the bits back into a string, and convert that string back into a numeric value, then square it```
```result is a single event with field x, containing the square of the bit reversed input.```

Edit: forgot how math works (ceil instead of floor + 1 for the bit length calculation), and managed to only check with inputs that worked with my wrong math. Also sort happened to be a leftover from when I was doing the problem more verbosely, we get the reverse sort for free. Nets to -12.

# Answer
> 1 votes
# Perl 5 `-p`, 38 bytes

```
$_=(oct"0b".reverse sprintf"%b",$_)**2

```

Try it online!

# Answer
> 1 votes
# LOLCODE, 192 bytes

```
HAI 1.3
I HAS A s ITZ 0
I HAS A x
GIMMEH x
IM IN YR l
s R SUM OF PRODUKT OF s 2 MOD OF x 2
x R QUOSHUNT OF x 2
BOTH SAEM x 0,O RLY?
YA RLY
GTFO
OIC
IM OUTTA YR l
VISIBLE PRODUKT OF s s
KTHXBYE

```

Try it online!

# Answer
> 0 votes
# cQuents, 10 bytes

```
K\rJ$)))^2

```

Try it online!

First time using cQuents.

## Explanation

```
    $      # Take the index.
   J )     # Convert to (default) base 2.
 \r   )    # Reverse it.
K      )   # Convert from (default) base 2 to base 10.
        ^2 # And square it.

```

# Answer
> 0 votes
# Factor, 24 bytes

```
[ >bin reverse bin> sq ]

```

Try it online!

# Answer
> 0 votes
# Jelly, 4 bytes

```
BUḄ²
```

Attempt This Online!

# Answer
> 0 votes
# JavaScript, 39 bytes

```
n=>`0b${(g=n=>n?n%2+g(n>>1):'')(n)}`**2

```

Try it online!

The function must take input as a decimal string. This is because the `f(0)` attempts to coerce `'0b'` to number, which results in `NaN`, but `f('0')` uses `'0b0'`.

Ungolfed and explained

```
n => `0b${      // create a string template literal starting for a binary number
  (g = n =>     // define a function g that creates a reversed binary string
    n ?         // if n is not zero
      n % 2 +   // put least sig. bit to the front
      g(n >> 1) // recursively add the rest
    :           // if n is 0
      ''        // return empty string
  )(n)          // call g with n
}` ** 2         // exponent operation implicitly coerces string to number

```

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
ḃrḂ²

```

Try it online!

#### Explanation

```
ḃrḂ²  # Implicit input
ḃ     # To binary
 r    # Reverse
  Ḃ   # From binary
   ²  # Square
      # Implicit output

```

---
Tags: code-golf, arithmetic, sequence, number-theory, base-conversion
---


title: Spell out the Revu'a

text:
# Question
Title: Spell out the Revu'a
Actually *not* inspired neither by Atbash Self Palindromes nor by Generalized Gematria Calculator.

Given a string *s* of length *n*, output the Revu'a sequence, which is the first character of *s*, the first two characters of *s*, ... the first *n*–2 characters of *s*, the first *n*–1 characters of *s*, the entire *s*.

The string will only consist of Unicode (any encoding you want) characters that have strong directionality and are found in the range 0x0000 through 0xFFFF. However, no directionality control characters will occur. All characters in any given string will have the same directionality.

You may return in array notation `["t","te","tes","test"]`, as a space-separated string `"t te tes test"`, as multi-line text
`t`
`te`
`tes`
`test`
, a pre-formatted array

```
t
te
tes
test
```
, or anything similar. Amounts of leading, separating, and trailing spacing is not important, and neither are trailing newline. Ask if in doubt.

Right-to-Left input must result in Right-to-Left output in proper order:
Input: `"נחמן"`
Output: `"נ נח נחמ נחמן"` or

```
נ
נח
נחמ
נחמן

```
, or `["נ","נח","נחמ","נחמן"]`. Among invalid results are `"נחמן נחמ נח נ"` ,`"ן מן חמן נחמן"`, and `"נחמן חמן מן ן"`.

# Answer
# 05AB1E, 1 byte

```
η

```

Builtins ftw ¯\\\_(ツ)\_/¯

Outputs as a list of prefixes.

Try it online or verify all test cases.

**Explanation:**

```
η  # Push a list of prefixes of the (implicit) input-string
   # (and output this list implicitly as result)

```
> 4 votes

# Answer
## Dyalog APL, 2 bytes

```
,\

```

Cumulative reduce by concatenate. Try it here.

The formatting of the output is nicer when you prefix a, but it clearly shows the correct order without.
> 17 votes

# Answer
# JavaScript (ES6), ~~27~~ ~~26~~ 25 bytes

*Saved one byte thanks to @nicael and @MartinBüttner, one thanks to @Neil*

```
x=>x.replace(/.?/g,"$` ")

```

Takes advantage of some built-in features of JS's `.replace` function. Specifically, in the replacement, `$``  becomes everything preceding the matched character. Using the regex `/.?/g` rather than `/./g` means it also matches the empty string at the end.
> 13 votes

# Answer
# Japt, ~~10~~ 4 bytes

I didn't realize that a cumulative reduce would be so useful in this case. :-)

```
U¬å+

```

Outputs as an array, comma-separated by default. If this is not allowed, use this 6-byte code instead:

```
U¬å+ ·

```

Try it online!

### How it works

```
      // Implicit: U = input string
U¬    // Split U into chars.
  å+  // Cumulative reduce: loop through each item in the array, concatenating it to the total.
      // ["t","e","s","t"] => ["t","te","tes","test"].
      // Implicit: output last expression

```
> 6 votes

# Answer
## Retina, ~~11~~ 7 bytes

```
.
 $`$0

```

Output is space-separated, with a leading space and a trailing linefeed.

Try it online!
> 6 votes

# Answer
# Brainfuck, 40 bytes

My console doesn't support Right-to-Left characters, but I don't think it will work :c

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

```

Ungolfed:

```
++++++++++> # Store 10 (Newline)
,[>,]       # Store input
<[<]>       # Goto first character
[           # While next character
  [<+>-]    # Copy character to the left
  <[<]>     # Goto first character
  [.>]      # Print all charaters
  >         # Go to next character
]

```
> 6 votes

# Answer
# Prolog (SWI), ~~60~~ 49 bytes

**Code:**

```
p(X):-findall(S,atom_prefix(X,S),[_|R]),write(R).

```

**Explained:**

**atom\_prefix** with **X** set to input and **S** as a variable gives 1 prefix of the atom **X** starting with the empty atom.

**findall** gets all solutions and puts them in a list.

**\[\_|R\]** throws away the head (the empty atom) and stores the tail in **R**

**Examples:**

```
p('נחמן').
[נ, נח, נחמ, נחמן]

p('test').
[t, te, tes, test]

```

Try it online here

**Edit:** saved 11 bytes by only storing the tail in **R**.
> 4 votes

# Answer
# Python, 35

```
f=lambda s:f(s[:-1])+[s]if s else[]

```

Couldn't find a way to use `and/or` to simplify the recursion because `[]` is falsy.

Recursive solution, returns a list of strings.

Try it online
> 4 votes

# Answer
# Pyth, 3

```
._z

```

Prefix builtin does the trick.

Test Suite
> 3 votes

# Answer
# GNU Sed, 21

Score includes +1 for `-E` option to sed:

```
:
s/^(\S+)\S/\1 &/
t

```

Works for LTR, but not RTL - I missed that bit.. Actually it *does* work, the RTL was just not rendering correctly in my terminal. It works fine with IO viewed in a sensible text editor (e.g. emacs). It also works in Ideone:

Try it online.
> 3 votes

# Answer
# Brachylog, 5 bytes

```
@[@w\

```

Try it online!

### Explanation

```
@[       Take a prefix of the input
  @w     Write this prefix to STDOUT followed by a linebreak
    \    False: try another prefix

```

Right-to-left strings seem to work properly, even though I never even considered them.
> 3 votes

# Answer
## CJam, 9 bytes

```
l{N2$@+}*

```

Output is linefeed-separated.

Test it here.

### Explanation

```
l     e# Read input.
{     e# Fold this block over the input, which is effectively a foreach-loop which skips
      e# the first character...
  N   e#   Push a linefeed.
  2$  e#   Copy the previous string.
  @   e#   Pull up the current character.
  +   e#   Concatenate.
}*

```
> 2 votes

# Answer
## JavaScript, 36 bytes

```
x=>[...x].map((c,i)=>x.slice(0,i+1))

```

Demo:

```
a=x=>[...x].map((c,i)=>x.slice(0,i+1));
document.write(
  a("test")+"<br>"+
  a("נחמן")
)
```

The principle is to map and output the slice of string from the first char to the every char in the word. Surprisingly, this works perfectly for the RTL strings too, no optimization needed.
> 2 votes

# Answer
## TI-BASIC, 18 bytes

```
For(X,1,10^(9
Disp sub(Ans,1,X
End

```

Not technically valid: TI-BASIC doesn't support Unicode.

Name this `prgmA`, and input using `Ans`.

Program recursion would be shorter, but there would be no way to initialize the variables. Therefore, we display a substring of the input at each iteration. The input is never overwritten, since Disp doesn't return a value.

Eventually, the program terminates with an error after printing the whole string.
> 2 votes

# Answer
My console doesn't support Right-to-Left characters, but I don't think it will work :c

**C, 74 bytes (2nd entry)**

```
char m[2<<9];i;main(){do{m[i]=getchar();printf("%s ",m);}while(m[i++]>0);}

```

Ungolfed:

```
#include <stdio.h>

// char, because `printf("%s", str);` expects a array of characters.
char str[2<<9];
int  str_len = 0;
int main(void) {
    do {
        str[str_len]=getchar();
        printf("%s ", str);
    } while(m[i++]>0);
    return 0;
}

```
> 2 votes

# Answer
My console doesn't support Right-to-Left characters, but I don't think it will work :c

**C, 105 bytes (3th entry)**

```
m[2<<9];i;j;k;main(){while((m[i++]=getchar())<0);for(;j<i;j++,putchar(10))for(k=0;k<j;k++)putchar(m[k]);}

```

Ungolfed:

```
#include <stdio.h>

int str[2<<9];
int str_len = 0;
int main(void) {
    do {
        str[str_len] = getchar();
    } while(str[str_len++] != EOF);
    int i;
    for(i=0; i<str_len; i++) {
        int j;
        for(j=0; j<i; j++) {
          putchar(str[j]);
        }
        putchar(10);
    }
}

```
> 2 votes

# Answer
# Python, 54 Bytes

```
b='';y=input()
for a in range(len(y)):b+=y[a];print(b)

```
> 2 votes

# Answer
# Java 8, ~~95~~ ~~92~~ 58 bytes

```
s->{for(int i=0;;)System.out.println(s.substring(0,++i));}

```

Try it online.

**Explanation:**

```
s->{                        // Method with String parameter and no return-type
  for(int i=0;              //  Index-integer, starting at 0
      ;)                    //  Loop indefinitely:
    System.out.println(     //   Print with trailing newline:
      s.substring(0,++i     //    Increase the index by 1 first with `++i`
                       ));} //    And print an input-substring in the range [0,i)

```

Stops the infinite loop with a `StringIndexOutOfBoundsException` after everything has been printed to STDOUT already, which is allowed according to the meta.
> 2 votes

# Answer
# MATL, 8 bytes

Uses current version (8.0.0) of language/compiler

```
jtn1X"YR

```

### Example

```
>> matl
 > jtn1X"YR
 >
> test
t
te
tes
test

```

### Explanation

```
j           % input string
tn          % duplicate and get length, say "N"
1X"         % repeat string N times vertically. Gives a char matrix
YR          % lower triangular part of matrix. Implicitly print

```
> 1 votes

# Answer
# Mathematica, 29 bytes

```
#<>#2&~FoldList~Characters@#&

```

TODO: explanation
> 1 votes

# Answer
# , 7 chars / 16 bytes

```
ᴉⓜᵖ ᵴ˖$

```

`Try it here (Firefox only).`

There's probably a builtin for this somewhere - I just haven't found it.

# Explanation

```
ᴉⓜᵖ ᵴ˖$ // implicit: ᴉ=split input, ᵴ=empty string
ᴉⓜ      // map over ᴉ
   ᵖ ᵴ˖$ // push ᵴ+=(mapped item char)
         // implicit stack output, separated by newlines

```
> 1 votes

# Answer
# Javascript ES6, 29 bytes

```
(a,b='')=>[...a].map(x=>b+=x)

```

This ain't winning anything, but it's a simple solution.
> 1 votes

# Answer
# Pyth, 11 Bytes

```
Vlz=k+k@zNk

```

Try It Out

***Explanation***

```
(z=input)
(k="")
V        for N in Range(
lz       length of z):
=k+k@zN     k=k+z[N]
k           print(k)

```
> 1 votes

# Answer
## Python, 32 bytes

```
f=lambda s:s and f(s[:-1])+" "+s

```

Recursive function that outputs a space-separated string with a leading space.

A 34-byte program (Python 2):

```
s=""
for c in input():s+=c;print s

```
> 1 votes

# Answer
# , 5 bytes

```
òÄ$xh

```

Try it online!

Explanation:

```
ò       " Recursively:
 Ä      "   Duplicate this line
  $     "   Move to the end of this line
   x    "   Delete one character
    h   "   Move one character to the right, which will throw an error when the line is one character long

```
> 1 votes

# Answer
## PowerShell v2+, 28 bytes

```
[char[]]$args[0]|%{($o+=$_)}

```

Takes input `$args[0]`, casts it as a `char`-array, pipes the characters into a loop `|%{...}`. Each iteration, we accumulate onto `$o` via `+=` the current character `$_`. That expression is encapsulated in parens so a copy is placed on the pipeline. At end of execution, the pipeline is flushed via `Write-Output` which puts a newline between elements.

```
PS C:\Tools\Scripts\golfing> .\spell-out-the-revua "נחמן"
נ
נח
נחמ
נחמן

PS C:\Tools\Scripts\golfing> .\spell-out-the-revua "PPCG"
P
PP
PPC
PPCG

```
> 1 votes

# Answer
# jq, 17 bytes

```
.[:range(length)]

```

Try it online!

-10 from ovs.
> 1 votes

# Answer
# PHP, 59 Bytes

```
for(;$i++<mb_strlen($argn);)echo"\n".mb_substr($argn,0,$i);

```

Online Version
> 0 votes

# Answer
# Unwanted, Unnecessary, Opportunistic, 9 bytes

```
E<+S0;*P

```
> 0 votes

# Answer
# .+?, 18 bytes

```
^((.+).)
\2\n\1
$

```

# Explanation

```
^((.+).)   Replace the first line with
\2         The first line missing the last character
  \n       A newline
    \1     The first line
$          Repeat until the regex doesn't match (when first line has 1 character)

```

Try it online! (The second command line argument is input)
> 0 votes

# Answer
# Burlesque, 2 bytes

```
iT

```

Try it online!

```
iT # Generate inits

```
> 0 votes

# Answer
# GolfScript, 10 bytes

Courtesy to a'\_' for saving two bytes by removing redundant bits!

```
:i,,{)i<}/

```

Nice short and cute response :)

```
:i,,{)i>}% #Revu'a Sequence
:i           #Remember the input as i
  ,,         #Array from 0 to i-1
    {   }% #Block, for each element, map this
    {)  }% #Increment the number by 1
    { i }% #Move i to the top of the stack
    {  >}% #Print the characters less than the index i

```

Try it online!
> 0 votes

# Answer
# Vyxal, 1 byte

```
¦

```

Try it Online!

But that's boring, so here's something a bit more interesting:

## 6 bytes

```
żƛw?$i

```

Try it Online!

## Explained

```
żƛw?$i
        # Implicit input of string
żƛ      # Over each integer n in range(1, len(input) + 1):
   ?    #   input[
  w $i  #         :n] (python indexing)
        # Implicitly print the result of the above.

```
> 0 votes

# Answer
# Thunno 2, 1 byte

```
ƒ

```

Try it online!

Try it online!

Built-ins for prefixes.
> 0 votes

---
Tags: code-golf, string, sequence, unicode
---


title: Generate a pronounceable word

text:
# Question
Title: Generate a pronounceable word
The challenge is simple:

## generate a word.

Specifications:

* Word must be pronounceable.
    + This is defined as "alternating between a consonant and a vowel."
    + A consonant is one of the following letters: `bcdfghjklmnpqrstvwxz`
    + A vowel is one of the following letters: `aeiouy`
* Word must be randomly generated.
* Words must be able to contain every consonant and vowel. (You can't just use `bcdf` for consonants and `aei` for vowels.)
* Word must contain 10 letters.
* Shortest code (in character count) wins.

# Answer
### GolfScript, 32 characters

```
['aeiouy'.123,97>^]5*{.,rand=}%+

```

Run it online.
> 8 votes

# Answer
# COBOL, 255

So I'm learning COBOL at the moment. Used this question as some practice. Tried to golf it.

It's 255 without the leading whitespace, and 286 bytes with.

For what it's worth, this runs in Microfocus COBOL for VS2012, and I have no idea if it will run anywhere else.

```
       1 l pic 99 1 s pic x(26) value'aeiouybcdfghjklmnpqrstvwxz' 1 r
       pic 99 1 v pic 9 1 q pic 99. accept q perform test after varying
       l from 1 by 1 until l>9 compute v=function mod(l,2) compute r=1+
       function random(q*l)*5+v*15+v*5 display s(r:1)end-perform exit

```
> 9 votes

# Answer
## Python, 81

```
from random import*
print''.join(map(choice,["bcdfghjklmnpqrstvwxz","aeiouy"]*5))

```

Good luck pronouncing them.
> 8 votes

# Answer
# Ruby: 56 characters

```
([v=%w(a e i o u y),[*?a..?z]-v]*5).map{|a|$><<a.sample}

```

Example outputs:

* itopytojog
* umapujojim
* ipagodusas
* yfoqinifyw
* ebylipodiz
> 8 votes

# Answer
## APL (34)

```
,⍉↑(V[5?6])((⎕A~V←'AEIOUY')[5?20])

```
> 6 votes

# Answer
# JavaScript, 74

```
for(a=b=[];a++-5;)b+="bcdfghjklmnpqrstvwxz"[c=new Date*a%20]+"aeiouy"[c%6]

```

Does not generate all combinations, but I think that all consonants and vowel appear.

**JavaScript, 79**

```
for(a=b=[];a--+5;)b+="bcdfghjklmnpqrstvwxz"[c=Math.random()*20^0]+"aeiouy"[c%6]

```

More "random" version.
> 6 votes

# Answer
# Ruby: ~~70~~ 66 characters

```
10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}

```

Sample run:

```
bash-4.1$ ruby -e '10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}'
izogoreroz

bash-4.1$ ruby -e '10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}'
onewijolen

bash-4.1$ ruby -e '10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}'
amilyfilil

```
> 4 votes

# Answer
# **Processing, 100 99 93 87**

```
int i=10;while(i-->0)"aeiouybcdfghjklmnpqrstvwxz".charAt((int)random(i%2*6,6+i%2*i*2));

```

Upon closer inspection of the question, I see it doesn't require any output. I've adjusted this accordingly.
> 4 votes

# Answer
## R: 105 characters

```
a=c(1,5,9,15,21,25)
l=letters
s=sample
cat(apply(cbind(s(l[-a],5),s(l[a],5)),1,paste,collapse=""),sep="")

```
> 4 votes

# Answer
## J (51)

```
,|:>(<"1[5?6 20){&.>'aeiouy';'bcdfghjklmnpqrstvwxz'

```
> 4 votes

# Answer
# Unix tools: 73 bytes

And not guaranteed running time :)

```
</dev/urandom grep -ao '[aeiouy][bcdfghjklmnpqrstvwxz]'|head -5|paste -sd ''

```

Only problem is that the generated string will start with a "vowel" every time.

(edit: changed `' '` to `''` in the args of paste) (another edit: removed -P from grep options, thanks to manatwork)
> 4 votes

# Answer
## PHP 79 bytes

```
<?for($c=bcdfghjklmnpqrstvwxz,$v=aeiouy;5>$i++;)echo$c[rand()%20],$v[rand()%6];

```

Fairly concise.
> 3 votes

# Answer
## Javascript, 85

```
for(r=Math.random,s="",i=5;i--;)s+="bcdfghjklmnpqrstvwxz"[20*r()|0]+"aeiouy"[6*r()|0]

```

If run from the console, output is shown. Explicit display would add `alert(s)` at 8 chars, still shorter than the other JS solutions.

Thanks C5H8NNaO4 and Howard!
> 3 votes

# Answer
**Java AKA the most verbose language ever created, 176** with help of Doorknob, Daniero and Peter Taylor (thanks guys!)

```
class w{public static void main(String[]a){int i=11;while(--i>0)System.out.print((i%2==0?"aeiouy":"bcdfghjklmnpqrstvwxz").charAt(new java.util.Random().nextInt(6+(i%2)*14)));}}

```

Ungolfed:

```
    class w {

        public static void main(String[] a) {
            int i = 11;
            while (--i > 0) {
                System.out.print((i % 2 == 0 ? "aeiouy" : "bcdfghjklmnpqrstvwxz").charAt(new java.util.Random().nextInt(6 + (i % 2) * 14)));
            }
     }

```

}
> 3 votes

# Answer
**Objective-C, 129**

```
main(){int i=10;while(i-->0)printf("%c",[(i%2==0)?@"aeiouy":@"bcdfghjklmnpqrstvwxz"characterAtIndex:arc4random()%(6+(i%2)*14)]);}

```

With the help of Daniero

(I love to use the *tends to* operator (--\>)
> 3 votes

# Answer
## PHP, 100 Characters

```
<?while($i<6){echo substr('bcdfghjklmnpqrstvwxz',rand(0,20),1).substr('aeiouy',rand(0,5),1);$i++;}?>

```
> 3 votes

# Answer
## APL ~~30~~ 26

```
,('EIOUY'∪⎕A)[6(|,+)⍪5?20]

```

Explanation is very similar to the past version below, just reordered a bit to golf the solution.

Note: ⎕IO is set to 0

---

```
('EIOUY'∪⎕A)[,6(|,(⍪+))5?20]

```

Explanation:

```
'EIOUY'∪⎕A    puts vowels in front of all letters.
5?20            for the indexes we start choosing 5 random numbers between 0 and 19
6(|,(⍪+))        then we sum 6 and the random numbers, convert to 5x1 matrix (⍪), add a column before this one containing 6 modulo the random numbers.
                [[[ this one can be rewritten as: (6|n) , ⍪(6+n)  for easier understanding]]]
,6(|,(⍪+))5?20  the leading comma just converts the matrix to a vector, mixing the vowel and consonants indexes.

```

Tryapl.org
> 3 votes

# Answer
# Pyth, 26 characters

```
J-G"aeiouy"VT=k+kOJ=J-GJ;k

```

You can try it in the online compiler here.

Someone posted a very similar challenge but it was closed after I had made a solution. I didn't realize it, but this question actually predates the creation of Pyth. Anyway, here is the breakdown:

```
J                             Set string J equal to:
  G                            the entire alphabet (lowercase, in order)
 - "aeiouy"                    minus the vowels
           VT                 For n in range(1, 10):
             =k                   Set string k to:
                k                  k (defaults to empty string)
               + OJ                plus a random character from J
                   =J             Set J to:
                      G            the entire alphabet
                     - J           minus J
                        ;     End of loop
                         k    print k

```

Every time the loop is run, J switches from being a list of consonants to a list of vowels. That way we can just pick a random letter from J each time.
There may be a way to initialize J in the loop or remove the explicit assignments from the loop, but I have not had success with either yet.
> 3 votes

# Answer
# K, 40 bytes

```
,/+5?/:("bcdfghjklmnpqrstvwxz";"aeiouy")

```

`5?"abc"` will generate 5 random letters from the given string.

`5?/:` will generate 5 random letters from each of the strings on the right, producing two lists.

`+` transposes those two lists, giving us a list of tuples with one random character from the first list and then one from the second list.

`,/` is "raze"- fuse together all those tuples in sequence.

K5 can do this in 33 bytes by building the alphabet more cleverly and then using "except" (`^`) to remove the vowels, but K5 is much too new to be legal in this question:

```
,/+5?/:((`c$97+!26)^v;v:"aeiouy")

```
> 3 votes

# Answer
# Javascript, ~~104~~ 87

```
a="";for(e=10;e--;)a+=(b=e&1?"bcdfghjklmnpqrstvwxz":"aeiouy")[0|Math.random()*b.length]

```

*golfed a whole lot of simple unnecessary stuff, still not nearly as nice as copys' one*

*Oh, and that one just opped up during golfing: **"dydudelidu"***

<sub>Now I tried one using the 2 characters at once approach. Turns out it's almost the same as copys' second one, so I can't count it, also at 79. `a="";for(e=5;e--;)a+="bcdfghjklmnpqrstvwxz"[m=0|20*Math.random()]+"aeiouy"[m%6]`</sub>
> 2 votes

# Answer
# C: 101

```
main(){int x=5;while(x-->0){putchar("bcdfghjklmnpqrstvwxyz"[rand()%21]);putchar("aeiou"[rand()%5]);}}

```
> 2 votes

# Answer
# Brachylog, 9 bytes

```
Ḍ;Ẉṣᵐzh₅c

```

Try it online!

Gives output as a list of letters through the output variable.

```
   ṣ         Randomly shuffle
 ;  ᵐ        both
Ḍ            the consonants without y
  Ẉ          and the vowels with y,
     z       zip them into pairs,
      h₅     take the first five pairs,
             and output
        c    their concatenation.

```
> 2 votes

# Answer
# "Random Word Generator", 70 +2 = 72 bytes

```
C=b c d f g h j k l m n p q r s t v w x z
V=a e i o u y
syllable:$C$V

```

Set minimum and maximum number of syllables settings to `5` (which I'm counting as flags, so 1 byte each).

This is written in a (WIP) tool I wrote for generating words from a sound inventory for conlanging (making constructed languages). I made the tool due to the other word generators (that I know of) having flaws (in my opinionated opinion).

The above code sets two categories `C` and `V`, and defines a syllable as a `C` followed by a `V`. The flags (minimum and maximum syllables) define how many syllables will be generated for a given word.

### No changed settings, 86 bytes

```
C=b c d f g h j k l m n p q r s t v w x z
V=a e i o u y
syllable:$C$V$C$V$C$V$C$V$C$V

```

Due to a bug in my implementation, this solution is extremely slow due to the large syllable size.
> 2 votes

# Answer
**F#**, 166 characters

```
open System;String.Join("",(Random(),"aeiouybcdfghjklmnpqrstvwxz")|>(fun(r,s)->[0..5]|>List.collect(fun t->[s.Substring(6+r.Next()%20,1);s.Substring(r.Next()%6,1)])))

```
> 1 votes

# Answer
# R, 83 bytes

```
cat(outer((l<-letters)[a<-c(1,5,9,15,21,25)],l[-a],paste0)[sample(1:120,5)],sep="")

```

Generate all possible vowel-consonant sequences in a matrix, then randomly sample 5 of them, yielding a 10-letter word.
> 1 votes

# Answer
# 05AB1E, 10 bytes

```
5FžPΩ?žOΩ?

```

Try it online or output \\$n\\$ amount of random words.

**Explanation:**

Pretty straight-forward:

```
5F      # Loop 5 times:
  žP    #  Push string "bcdfghjklmnpqrstvwxz"
    Ω   #  Pop and push a random character from this string
     ?  #  Output it without newline
  žOΩ?  #  Do the same with string "aeiouy"

```
> 1 votes

# Answer
# K (ngn/k), ~~57~~ ~~47~~ ~~46~~ 54 bytes

```
{`prng@0;,/{(1?"bcdfghjklmnpqrstvwxz"),1?"aeiouy"}'!5}

```

Try it online!

*Down 1 byte thanks to ngn*

Takes inspiration from the PHP answer. This one now outputs random words at each call, with the cost of 8 extra bytes.

Explanation:

```
{`prng@0;,/{(1?"bcdfghjklmnpqrstvwxz"),1?"aeiouy"}'!5} Main function. Takes no input
                                                   !5  Generate a array with range from 0 to 4 ([0..4])
                                                  '    For each number...
           {                                     }     Execute a function that...
            (1?"bcdfghjklmnpqrstvwxz"),1?"aeiouy"      Chooses one random consonant, followed by one random vowel
         ,/                                            Joined each of these strings together
 `prng@0;                                              Use current time to set state of randomness (Thus allow random words)

```
> 1 votes

# Answer
# Japt `-P`, ~~20~~ 17 bytes

```
;`Á<`
5Æö iCkU ö

```

Test it

Note that there is an unprintable character in front of the `Á`

```
;          # C = "abcdefghijklmnopqrstuvwxyz"
 `ŒÁ<`     # U = "oueayi"

5Æ         # Do this 5 times:
  ö        #  Pick a random letter from U
    i      #  Prepend:
     CkU   #   Remove the letters in U from C
         ö #   Get a random letter from the result

-P         # Print all the pairs with no separator

```
> 1 votes

# Answer
# Japt `-P`, 14 bytes

```
;Cü_èyi%Ã®ö5ÃÕ

```

Test it

```
;Cü_èyi%Ã®ö5ÃÕ
;C                 :Lowercase alphabet
  ü                :Group by
   _               :Passing each character through the following function
    è              :  Count
     yi%           :    "y" prepended with "%", giving the Japt RegEx "%y"=/[aeiouy]/i
        Ã          :End grouping
         ®         :Map
          ö5       :  5 random characters
            Ã      :End map
             Õ     :Transpose
                   :Implicitly join & output

```
> 1 votes

# Answer
# JavaScript (V8), 89 bytes

```
for(;a=Math.random().toString(36).match(/([bcdfghj-np-tvwxz][aeiouy]){5}/g),!a;);print(a)

```

Try it online!

`/g` makes the result without an extra appearance of pair
> 1 votes

# Answer
# Thunno 2 `J`, 9 bytes

```
5ıkykz,€ɼ

```

Try it online!

#### Explanation

```
5ıkykz,€ɼ  # Implicit input
5ı         # Repeat 5 times:
  ky  , ɼ  #  Random vowel
    kz €ɼ  #  Random consonant
           # Join into a string
           # Implicit output

```
> 1 votes

# Answer
# Vyxal `s`, 8 bytes

```
k¹k∪"5ƈ∩

```

Try it Online!

```
    "    # Pair
k¹       # Consonants
  k∪     # And vowels
     5ƈ  # Choose 5 random items from each
       ∩ # Interleave

```
> 1 votes

# Answer
# Jelly, 13 bytes

```
Øy,ØYẊ€Zs5ḢŒl

```

**Explanation:**

```
Øy,ØYẊ€Zs5ḢŒl
Øy,ØY         Makes a list of two lists of characters: [[list-of-vowels-with-y], [list-of-consonants-without-y]]
     Ẋ€       Shuffle €ach.
       Z      Zip those two lists together. [[random-vowel, random-consonant],...]
        s5    Split them into chunks of five (because each pair contains two letters, this splits them into chunks of 10 letters)
          Ḣ   Take the list of 5 pairs.
           Œl Make each of the characters in it lowercase
              Implicit concatenation and print.

```

Try it online!
> 0 votes

# Answer
# C (gcc), 63 bytes

```
c;f(n){for(n=10;n;81192%c-n&1||putchar(c,n--))c=97+clock()%26;}

```

Try it online!
> 0 votes

# Answer
# Zsh `--braceccl`, 57 bytes

Try it Online!

```
shuf -n5 <(echo {bcdfghj-np-tvwxz}{aeiouy}|rs 0 1)|rs -g0

```

Alternates: 67b using `jot` ; 77b using arrays
> 0 votes

---
Tags: code-golf, random, natural-language, generation
---


# Question
Title: Print a meter of numbers to a specified limit
Given a positive integer `n`, output a number meter formatted like this:

```
                  0 1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 2

```

The input number is 20 in this example.

More formally, the decimal representations of the numbers are arranged vertically, from most significant digits on the last row to least significant digits at the top, using space-padding.

All numbers should be printed, and any size of number is allowed.

An example solution in Python 3 follows:

```
def meter(top: int):
    initial = list(str(str(n).ljust(len(str(top + 1)))) for n in range(1, top + 1))
    rotated = list(zip(*initial))[::-1]

    return "\n".join(" ".join(n) for n in rotated)

```

This is Code Golf! Make the answer with the lowest bytes to win.

# Answer
> 14 votes
# Canvas, 4 bytes

```
Ｒ↶ ＊

```

Try it online.

**Explanation:**

```
Ｒ     # Push a list in the range [1, (implicit) input-integer],
       # and implicitly print each integer on a separated newline to the Canvas
 ↶    # Rotate the entire Canvas 90 degrees counterclockwise
   ＊  # Join each character on each line of the Canvas with a space delimiter

```

# Answer
> 5 votes
# K (ngn/k), 40 30 20 bytes

```
{" "/'|+(#$x)$$1+!x}

```

Try it online!

-10 : more straightforward (less fun?)
-10 : Actual golfing courtesy of @coltim and @bstrat

# Answer
> 4 votes
# JavaScript (ES6), 69 bytes

Expects the input number as a string.

```
f=(n,d=0,i=n)=>i?f(n,d,i-1)+(`${i}`[d]||' ')+' ':n[++d]?f(n,d)+`
`:''

```

Try it online!

# Answer
> 3 votes
# Vyxal, 40 bitsv2, 5 bytes

```
ɾ∩Ṙ⁋øɽ

```

Try it Online!

I honestly don't know how people find these obscure string overloads that I can never seem to remember.

## Explained

```
ɾ∩Ṙ⁋øɽ
ɾ∩      # Transpose the range [1, input], treating digits as columns.
  Ṙ⁋    # Reverse that, and join each sublist on spaces. Then, join that on newlines.
    øɽ  # Right align that. I honestly don't know why this works. It just does.

```

Created with the help of Luminespire.

# Answer
> 3 votes
# Thunno 2 `N`, 7 bytes

```
RðƬrðȷj

```

Try it online!

#### Explanation

```
RðƬrðȷj  # Implicit input
RðƬ      # Transpose [1..input], filling with spaces
   rðȷj  # Reverse and join each on spaces
         # Implicit output, joined on newlines

```

# Answer
> 3 votes
# Charcoal, 7 bytes

```
↑ＩＥＮ⟦⊕ι

```

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

```
   Ｎ    Input as a number
  Ｅ     Map over implicit range
      ι Current value
     ⊕  Incremented
    ⟦   Make into sublist (causes the output to be double-spaced)
 Ｉ      Cast to string
↑       Print rotated 90°

```

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
L€SζR»

```

Try it online.

**Explanation:**

```
L       # Push a list in the range [1, (implicit) input-integer]
 €S     # Map each integer to a list of digits
   ζ    # Zip/transpose; swapping rows/columsn,
        # with a space character to fill unequal length rows
    R   # Reverse this list of lists
     »  # Join each inner list by spaces, and then each string by newlines
        # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Python, 72 bytes

```
n=input()
*map(print,*(f'{j+1:<{len(n)}}'[::-1]for j in range(int(n)))),

```

Attempt This Online!

-1 thanks to *@Arnauld* (by switching to Python 3.8)
-5 thanks to *@c--* (by using f-strings)
-12 thanks to *@loopy walt* (by using map rather than a for loop)

# Answer
> 3 votes
# sclin, 55 bytes

```
;1+ I>a10X>b tpose _`"_`\" \"rep +` ; tk _` w>< n>o"map

```

Try it here! Takes input from the second line.

For testing purposes:

```
;1+ I>a10X>b tpose _`"_`\" \"rep +` ; tk _` w>< n>o"map
20

```

## Explanation

Prettified code:

```
; 1+ I>a 10X>b tpose _` ( _` " "rep +` ; tk _` w>< n>o ) map

```

Assuming input *n*:

* `; 1+ I>a` range `[1, n]`
* `10X>b` digitize (literally "convert each to base-10 digits")
* `tpose _`` transpose, reverse resulting lines
* `(...) map` map over each line...
    + `_` " "rep +` ; tk _`` left-pad with spaces to length *n*
        - `_`` reverse
        - `" "rep +`` concatenate to infinite list of spaces
        - `; tk` take first *n* elements
        - `_`` reverse again
    + `w>< n>o` join with space and output

The (current) lack of string manipulation commands present in sclin makes it a tad unwieldy for string challenges...

# Answer
> 2 votes
# Ruby, 79 bytes

```
->n{(1..n).map{d=_1.digits
[" "]*(n.to_s.size-d.size)+d}.transpose.map{_1*" "}}

```

Attempt This Online!

# Answer
> 2 votes
# Japt `-R`, 8 bytes

```
õs ÕÔË¬¸

```

Try it

# Answer
> 2 votes
# , 82 bytes

```
\(n)write(t(Reduce(cbind,strsplit(format(paste(1:n),j="l"),""))[nchar(n):1,]),1,n)

```

Attempt This Online!

# Answer
> 2 votes
# , ~~25 23~~ 20 bytes

```
1j1#"#.0|.@|:1":@+i.

```

Try it online!

*-3 thanks to doug!*

* `1 ... +i.` 1...n
* `":@` Each of them formatted as a string
* `0|.@|:` Transposed and reversed
* `1j1#"#.` Add the space padding

# Answer
> 2 votes
# Ruby, 68 bytes

```
->n{(0...s=n.to_s.size).map{|i|(0..n).map{_1.digits[i-s]||" "}*" "}}

```

Attempt This Online!

Inspired by Jordan's ruby answer, but different enough to merit a new post.

# Answer
> 1 votes
# Jelly, 6 bytes

```
Ṿ€z⁶ṚG

```

Try it online!

-2 thanks to *@UnrelatedString*

#### Explanation

```
Ṿ€z⁶ṚG  # Main link - argument n
 €      # To each number in the range [1..n]:
Ṿ       #  Convert it to a string
  z⁶    # Transpose using filler space
    Ṛ   # Reverse this list of lists
     G  # Format as a grid
        # (join each on spaces, then newlines)

```

# Answer
> 1 votes
# Retina, 57 bytes

```
.+
*¶
¶
$^$.>`#¶#¶
P^`.+
N$`.
$.%`
¶

~L$`#+
L`.{$.&}
A`#

```

Try it online! Explanation: Based on my golf to @TwiNight's answer to Enklactify these strings to transpose the text.

```
.+
*¶
¶
$^$.>`#¶#¶

```

Create a range from `1` to the input, but with the digits reversed, and each line padded with a `#`, and the lines separated by a line with just a `#`.

```
P^`.+

```

Left pad everything with spaces so that it lines up.

```
N$`.
$.%`

```

Sort all characters by their column index.

```
¶

~L$`#+
L`.{$.&}

```

Complete the transposition by joining everything together and then splitting by the number of `#`s.

```
A`#

```

Remove the final line, which will always be the `#`s.

# Answer
> 1 votes
# Excel, 49 bytes

```
=MID(SEQUENCE(,A1),1+LEN(A1)-SEQUENCE(LEN(A1)),1)

```

Input in cell `A1`.

# Answer
> 1 votes
# jq, ~~68~~ 66 bytes

***-2 bytes** with a better use of `range`*

```
[range(.)+1|@sh/""]|transpose|map(map(.//" ")|join(" "))|reverse[]

```

Attempt This Online!  ~~Attempt This Online!~~

```
[
  range(.) + 1   # `range` generates 0 to n - 1; add 1
  | @sh / ""     # Since numbers do not have spaces or special characters,
                     # `@sh` behaves the same as `@text`/`tostring`.
                     # `/ ""` splits into an array of characters
]                # `[ ... ]` collects values into an array
| transpose      # transpose, filling missing values with null.
| map(
    map(.//" ")  # replace null with space
    | join(" ")  # join on spaces
  )
| reverse[]      # most-significant digits last.

```

---
Tags: code-golf, string, number, ascii-art
---


# Question
Title: Count N-Rich Permutations of an Integer Sequence
Given a sequence of integers with length \\$L\\$ and an integer \\$1 \le N \le L\\$, an "\\$N\\$-rich" permutation is one whose the longest **strictly** increasing **contiguous** subsequence has length exactly \\$N\\$.

For example, let our sequence be `[0, 1, 2, 3]`. There is exactly one \\$1\\$-rich permutation, given by `[3, 2, 1, 0]`. By contrast, there are sixteen \\$2\\$-rich permutations:

```
[0, 2, 1, 3] [0, 3, 1, 2] [0, 3, 2, 1]
[1, 0, 3, 2] [1, 2, 0, 3] [1, 3, 0, 2] [1, 3, 2, 0]
[2, 0, 3, 1] [2, 1, 0, 3] [2, 1, 3, 0] [2, 3, 0, 1] [2, 3, 1, 0]
[3, 0, 2, 1] [3, 1, 0, 2] [3, 1, 2, 0] [3, 2, 0, 1]

```

Note that `[0, 1, 3, 2]` is \\$3\\$-rich and NOT \\$2\\$-rich, because even though it contains a strictly increasing subsequence of length 2, it also contains a *longer* strictly increasing subsequence.

## The Challenge

Your challenge is to write a function which takes in an integer sequence S with some length \\$L\\$, and an integer \\$1 \le N \le L\\$, and returns the number of N-rich permutations of S.

This is code golf, so the shortest valid answer wins.

## Test cases

Each row is a sequence along with the expected output for all possible values of L. For example, the first row says that if your function is called `f`, then `f([1, 2, 3, 4, 5], 3) = 41`

```
[1, 2, 3, 4, 5] => 1, 69, 41, 8, 1
[1, 2, 2, 3, 3, 4, 5] => 4, 2612, 2064, 336, 24, 0, 0
[1, 1, 1, 1, 1, 1, 1] => 5040, 0, 0, 0, 0, 0, 0
[1, 2, 3, 1, 2, 3, 4] => 8, 2976, 1864, 192, 0, 0, 0

```

# Answer
# Husk, 9 bytes

```
#mȯ▲mLġ>P

```

Try it online! or Try the test lists with N=2

```
#mȯ▲mLġ>P
        P  # get all permutations of arg1
 m         # map over each permutation:
  ȯ        #   these 3 composed functions:
      ġ>   #   - group by pairwise greater-than
    mL     #   - get the length of each group
   ▲       #   - maximum
#          # how many times is arg2 present?

```
> 7 votes

# Answer
# Ruby, ~~85~~ ~~79~~ 77 bytes

Misread the prompt at first and was returning the permutations themselves instead of the amount, whoops.

```
->a,n{a.permutation.count{|r,*b|m=c=1;b.map{m=c if m<c=r<(r=_1)?c+1:1};m==n}}

```

Attempt This Online!

```
->a,n{                                 # Lambda definition
  a.permutation                        # Permutations
   .count{                             # Count instances that match the given condition
          |r,*b|                       #  Extract first element as r (pRevious element)
                m=c=1;                 #  Initialize variables
                                       #   (m = max subsequence length)
                                       #   (c = current subsequence length)
                b.map{                 #  Iterate over the rest of the permutation
                      c=r<(r=_1)?c+1:1 #   If prev. element < current, add 1 to c
                                       #    Otherwise, reset c to 1
                                       #   Also reset r here to save bytes
                      m=c if m<c       #   Set max if needed
                     };                #  End map call
          m==n}                        # Match if max == N
}                                      # End lambda

```
> 5 votes

# Answer
# JavaScript (ES6), 87 bytes

Expects `(n)(array)`.

```
n=>g=(a,s,m,p)=>a.map((v,i)=>t+=g(a.filter(_=>i--),q=v>p?s+1:1,q<m?m:q,v),t=0)+a?t:m==n

```

Try it online!

### Commented

```
n =>                 // outer function taking n
g = (                // inner recursive function g taking:
  a,                 //   a[] = input array
  s,                 //   s = size of the strictly increasing sequence
  m,                 //   m = maximum size so far
  p                  //   p = previous value from the permutation
) =>                 //
a.map((v, i) =>      // for each value v at index i in a[]:
  t +=               //   add to t the result of ...
    g(               //     ... a recursive call to g:
      a.filter(_ =>  //       remove from a[]:
        i--          //         the i-th element
      ),             //
      q =            //       q = new value of s, defined as follows:
        v > p ?      //         if v is greater than p:
          s + 1      //           increment s
        :            //         else:
          1,         //           reset to 1
      q < m ? m : q, //       m = max(m, q)
      v              //       pass v as the previous value
    ),               //     end of recursive call
  t = 0              //   start with t = 0
)                    // end of map()
+ a ?                // if a[] is empty:
  t                  //   return t
:                    // else:
  m == n             //   return 1 if the maximum size is n

```
> 5 votes

# Answer
# Thunno 2 `L`, 10 bytes

```
qæƑœØ^ḷG¹=

```

Try it online! or verify all test cases

#### Explanation

```
qæƑœØ^ḷG¹=  # Implicit input
q           # All permutations of the first input
 æ          # Filtered by:
  Ƒ         #  All sublists of this list
   œØ^      #  Only keep strictly ascending ones
      ḷG    #  Get the maximum length
        ¹=  #  Equals the second input?
            # Implicit output of length

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~62~~ 57 bytes

Port of @chunes's Factor code in Mathematica.

Saved 5 bytes thanks to the comment of @ZaMoC

---

Golfed version. Try it online!

```
Count[Permutations@#,x_/;Max[Length/@Split[x,#<#2&]]==2]&

```

Ungolfed version. Try it online!

```
(* Define function to split a sequence into increasing subsequences *)
SplitIncreasing[list_] := Split[list, #1 < #2 &];

(* Generate all permutations of the sequence *)
perms = Permutations[{1, 2, 3, 4, 5}];

(* Find and count the permutations where the longest increasing subsequence has length 2 *)
Count[perms, perm_ /; Max[Length /@ SplitIncreasing[perm]] == 2] //Print

```
> 5 votes

# Answer
# Python, 126 bytes

*-19 bytes thanks to @ValueInk and @TheThonnu*

*+2 bytes, index was off by one*

```
lambda l,i:sum(i==1+max(sum(b)for(_,b)in groupby(a>b for(a,b)in zip(p[1:],p)))for p in permutations(l))
from itertools import*

```

Attempt This Online!
> 4 votes

# Answer
# Factor \+ `math.combinatorics`, ~~83~~ 72 bytes

```
[ <permutations> [ [ < ] monotonic-split longest length = ] with count ]

```

Attempt This Online!

* `<permutations> [ ... ] with count` Count permutations of the input sequence using `[ ... ]` (a predicate quotation/lambda).
* `[ < ] monotonic-split` Split into increasing subsequences.
* `longest length` Get the length of the longest one.
* `=` Is this equal to the numeric input?
> 3 votes

# Answer
# Jelly, 13 bytes

```
Œ!ẆIRẠƊƇẈṀƲ€ċ

```

Try it online!

-1 byte thanks to Jonathan Allan!

Footer runs each sequence test case over a provided \\$N\\$

# Jelly (fork), 10 bytes

```
Ẇ<ɲƇẈṀƲÐ!ċ

```

Try it online! (or, rather, don't as it isn't implemented on TIO)

## How they work

```
Œ!ẆIRẠƊƇẈṀƲ€ċ - Main link. Takes S on the left, N on the right
Œ!            - All permutations of S
          Ʋ€  - Over each permutation P:
  Ẇ           -   All contiguous sublists
      ƊƇ      -   Filter sublists on:
   I          -     Increments
     Ạ        -     all
    R         -     have a non-zero range
        Ẉ     -   Lengths
         Ṁ    -   Maximum
            ċ - Count N

```

```
Ẇ<ɲƇẈṀƲÐ!ċ - Main link. Takes S on the left and N on the right
      ƲÐ!  - Over the permutations of S:
Ẇ          -   Contiguous sublists
   Ƈ       -   Keep those such that:
  ɲ        -     All neighbours are:
 <         -       In ascending order
    ẈṀ     -   Maximum length
         ċ - Count N

```
> 3 votes

# Answer
# Jelly, 13 bytes

```
Œ!Ẇ<ƝẠ$ƇṪLƲ€ċ

```

A dyadic Link that accepts the list of elements, \\$L\\$, on the left and the number, \\$n\\$, on the right and yields the count of \\$n\\$-rich permutations of \\$L\\$.

**Try it online!**

Or see the test-suite (count, `ċ`, has been moved out to the footer to make it more efficient, and so finish within the TIO timeout).

### How?

```
Œ!Ẇ<ƝẠ$ƇṪLƲ€ċ - Link: L, n
Œ!            - all permutations of {L}
           €  - for each:
          Ʋ   -   last four links as a monad:
  Ẇ           -     sublists (from shortest to longest)
       Ƈ      -     filter keep those for which:
      $       -       last two links as a monad:
    Ɲ         -         for neighbouring pairs:
   <          -           less than?
     Ạ        -         all?
        Ṫ     -     tail
         L    -     length
            ċ - count occurrences of {n}

```
> 3 votes

# Answer
# Nekomata \+ `-n`, 10 bytes

```
↕∆±ĉᵐ∑çṀ→=

```

Attempt This Online!

```
↕∆±ĉᵐ∑çṀ→=
↕           Find a permutation of the first input
 ∆          Delta
  ±         Sign
   ĉ        Split into runs of equal elements
    ᵐ∑      Sum each run
      ç     Prepend 0 to handle the case with no nonnegative runs
       Ṁ    Maximum
        →   Increment
         =  Check if equal to the second input

```

`-n` counts the number of solutions.
> 2 votes

# Answer
# 05AB1E, 10 bytes

```
œʒü‹γOà-}g

```

Try it online or verify all test cases.

**Explanation:**

```
œ         # Push all permutations of the first (implicit) input-list
 ʒ        # Filter it by:
  ü       #  For each overlapping pair:
   ‹      #   Check whether the first is smaller than the second
    γ     #  Group the 0s and 1s into adjacent equal groups
     O    #  Sum each inner group
      à   #  Pop and push the maximum
       -  #  Subtract it from the second (implicit) input-integer
          #  (only 1 is truthy in 05AB1E)
 }g       # After the filter: pop and push the length
          # (which is output implicitly as result)

```
> 2 votes

# Answer
# Arturo, 100 bytes

```
$=>[n:&enumerate permutate&'x[i:0n=1+??max
map select chunk chop x'y['i+1y<x\[i]]=>sorted?=>size 0]]

```

Try it!

```
$=>[                        ; a function where successive inputs are assigned to &
    n:&                     ; assign first input (number) to n
    enumerate permutate&'x[ ; count each permutation x of input seq
        i:0                 ; assign 0 to i
        n=1+                ; does n equal 1 plus
        ?? ... 0            ; if ... is null, evaluate to 0, else to ...
        max                 ; maximum value of
        map...=>size        ; lengths of
        select...=>sorted?  ; sorted blocks of
        chunk chop x'y[     ; split x-sans-last-elt into contiguous blocks by...
            '1+1            ; increment i in place
            y<x\[i]         ; is y less than x[i]? (is it increasing?)
        ]                   ; end chunk
    ]                       ; end enumerate
]                           ; end function

```
> 1 votes

# Answer
# Vyxal `l`, 71 bitsv2, 8.875 bytes

```
Ṗ'ÞS~Þ⇧@G⁰=

```

Try it Online!

## Explained

```
Ṗ'ÞS~Þ⇧@G⁰=
Ṗ'           # Filter permutations where:
  ÞS         #   All sublists
    ~Þ⇧      #   that are strictly increasing
       @G    #   has maximum sublist length
         ⁰=  #   equals N
# The l flag gets the length of all the permutations.

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Charcoal, 45 bytes

```
⊞υ⟦⟧Ｆθ≔ΣＥυＥ⁻Ｅθνκ⁺κ⟦μ⟧υＩ№ＥυＬ⌈⪪⭆Φιμ‹§θλ§θ§ιμ0⊖η

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
⊞υ⟦⟧Ｆθ≔ΣＥυＥ⁻Ｅθνκ⁺κ⟦μ⟧υ

```

Generate all of the permutations from `0` to `L-1`. This is based on my answer to 1 to N column and row sums but uses the indices of the input rather than an explicit range.

```
Ｉ№ＥυＬ⌈⪪⭆Φιμ‹§θλ§θ§ιμ0⊖η

```

For each permutation, create a binary string representing strictly increasing consecutive values of the input array, then split that string on `0`s and take the length of the longest resulting contiguous substring of `1`s. Count the number for which that is `N-1`.
> 1 votes

# Answer
# Desmos, 189 bytes

```
f(L,n)=∑_{k=0}^{l^l-1}0^{(I.unique.length-l)^2+([S.length0^{0^{max(0,S[2...]-S)}.total}forb=[1...l],d=[0...l]].max-n)^2}
l=L.length
I=mod(floor(kl/l^{[1...l]}),l)+1
S=L[I][b...min(l,b+d)]

```

Try It On Desmos!

Try It On Desmos! - Prettified

Probably some of the most horrendous and inefficient Desmos code I have ever written, but at least it gets the job done (disregarding runtime lmao). It is so inefficient that I don't think it can even run a list of length 7 any time soon.

I might write a longer explanation later, but the gist of it is that I iterate through all base-\\$l\\$ numbers of length \\$l\\$ where \\$l\\$ is the length of the input list \\$L\\$, then check if the resulting digits form a valid permutation of \\$0,\ldots,l-1\\$, then add \\$1\\$ to the digits because of 1-indexing. This digit list is then used to permute \\$L\\$. Then for each permutation I check for the "richness" by further iterating through all sublists of the permutation. Finally with that, I can count the number of permutations that are "\\$n\\$-rich".
> 1 votes

# Answer
# Perl 5, 131 bytes

```
sub{($r,%s)=pop;$"=",";0+grep{my($l,$f,$m);$m+=($l=$_>$f?$l+1:1)>$m,$f=$_ for@_[/./g];$m==$r}grep!/(.).*\1/,glob"{@{[0..$#_]}}"x@_}

```

Try it online!
> 0 votes

# Answer
# sclin, 48 bytes

```
perm";"map = +/
2%`",_ <"map"="pack0"+/ |"fold1+

```

Try it here! Takes number first, then sequence.

For testing purposes:

```
3 [1 2 3 4 5] ;
perm";"map = +/
2%`",_ <"map"="pack0"+/ |"fold1+

```

## Explanation

Prettified code:

```
perm \; map = +/
2%` ( ,_ < ) map \= pack 0 ( +/ | ) fold 1+

```

Assuming number *n* and sequence *s*.

* `perm \; map` map over each permutation of *s*...
    + `2%` ( ,_ < ) map` pairwise map with "less than" to get booleans indicating increases
    + `\= pack` group consecutive runs of booleans
    + `0 ( +/ | ) fold 1+` get maximum sum + 1
        - sum implicitly converts true to 1 and false to 0
* `= +/` vectorized equals to *n*, sum
    + i.e. count occurrences of *n*
> 0 votes

---
Tags: code-golf, permutations, counting
---