title: PronunciationSort™

text:
# Question
Title: PronunciationSort™
We all know of different fancy sorting algorithms, but none of these give us numbers in a way that's easy to pronounce. To remedy this, I propose using PronunciationSort™, the most natural way to sort lists of numbers.

## Pronunciation

The official rules for pronouncing numbers (in this challenge) is that the digits are pronounced one by one, and the resulting string is sorted in lexicographic order. As an example, this means that the number `845` is pronounced `"eight four five"`, and should be sorted accordingly.

### Negative numbers

Negative numbers are pronounced by prepending the word `"minus"`. Thus, `-23` is pronounced as `"minus two three"`. Note that this causes negative numbers to end up in the middle of the output, right between numbers starting with `4` (four) and `9` (nine).

As a guide, the official order of words for PronunciationSort™ is:

* eight
* five
* four
* minus
* nine
* one
* seven
* six
* three
* two
* zero

That is,

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

```

## Input

A list of integers in the range \\$\[-999, 999\]\\$, containing at most 100 elements. Input as a list of strings is not permitted. If your language does not support input as list, it is permissible to give input as separate integers.

The input will not contain any invalid numbers, or any number starting with a 0 (except the number 0 itself). The input will generally not be sorted, it can be given in any order.

## Output

The same integers, in PronunciationSort™ order. Note that the numbers should only be converted to their pronunciations to get the sorting, the output should not contain any strings.

## Examples

For the examples, the middle step (wrapped in parentheses) only serves as a guide, and is not a part of the output.

```
[1, 2, 3] -> (['one', 'two', 'three']) -> [1, 3, 2]
[-1, 0, 1, 2] -> (['minus one', 'zero', 'one', 'two']) -> [-1, 1, 2, 0]
[-100, 45, 96] -> (['minus one zero zero', 'four five', 'nine six']) -> [45, -100, 96]
[11, 12, 13, 134, 135] -> (['one one', 'one two', 'one three', 'one three four', 'one three five']) -> [11, 13, 135, 134, 12]

```

There's also a script for verifying your results.

# Answer
# Haskell, 57 bytes

```
import Data.List
sortOn$map(`elemIndex`"54-9176320").show

```

Try it online!
> 10 votes

# Answer
# Jelly,  ~~15~~  13 bytes

```
ṾV€ị“Þ⁽3Z6»µÞ

```

**Try it online!**

A monadic link accepting a list of integers which yields a list of integers.

### How?

Sorts by the ordinal values of the digits of the integers (where `-` is a "digit" of -1) converted to strings using the characters at their 1-based & modular index in the magic string "murgeon lix".

The sort is effectively alphabetic where a space is considered less than any letter.

The magic string "murgeon lix" was found by inspecting Jelly's dictionaries used in compression. There are no words of 11 letters which satisfy the requirements (and none of more that would upon de-duplication). since a space sorts before letters the next most obvious choice is a word of length seven followed by a space followed by a word of length three. "murgeon" and "lix" is the only satisfying combination, although without a space others may be possible (e.g. `“£Py:ƥ»` is "murgeonalix" which works for the same byte-count)

```
ṾV€ị“Þ⁽3Z6»µÞ - Link: list of integers
            Þ - sort by:
           µ  -   the monadic link: -- i.e. do this for each integer, then sort by that
Ṿ             -     unevaluate  (e.g. -803 -> ['-','8','0','3'])
 V€           -     evaluate each as Jelly code  (e.g. ['-','8','0','3'] -> [-1,8,0,3])
    “Þ⁽3Z6»   -     "murgeon lix" (compression of words in Jelly's dictionary plus a space)
   ị          -     index into (1-indexed & modular) (e.g. [-1,8,0,3] -> "i xr")

```

---

Previous @ 15 bytes:

```
ṾV€ị“¡Zo⁶’Œ?¤µÞ

```

Here `“¡Zo⁶’Œ?¤` finds the first permutation of natural numbers which would reside at the index 21,340,635 when all permutations of the numbers are sorted lexicographically - which is `[6,10,9,3,2,8,7,1,5,4,11]`. (`“¡Zo⁶’` is a base 250 representation of 21340635, while `Œ?` does the calculation and `¤` groups these instructions together)
> 9 votes

# Answer
# 05AB1E (legacy), 15 bytes

```
Σε•Koéa₃•'-3ǝsk

```

Try it online!

**Explanation**

```
Σ                 # sort by
 ε                # apply to each
             sk   # index of the element in
  •Koéa₃•         # "85409176320"
         '-3ǝ     # with "-" inserted at index 3

```
> 8 votes

# Answer
# Perl 6, 30 bytes

```
*.sort:{TR/0..9-/a5982176043/}

```

Try it online!

Port of G B's Ruby solution.

### Original 35 byte version

```
*.sort: (~*).uninames».&{S/\w*.//}

```

Try it online!

Convert each number to a string, get the Unicode name of each character, strip the first word ("DIGIT" or "HYPHEN"), then sort.
> 7 votes

# Answer
# Python 3, ~~68 bytes~~ ~~67 bytes~~ 64 bytes

```
lambda x:sorted(x,key=lambda y:[*map('54-9176320'.find,str(y))])

```

Uses built-in `sorted` function with an anonymous lambda for the key. Hard-code the sort order and compare each digit in each value in the input list to its position in the sort order list.

*Edit: Saved 1 byte by removing `8` from sort list to take advantage of `str.find` returning `-1` when parameter is not found. Thanks to maxb.*

*Edit2: Saved 3 bytes by using starred unpacking syntax in a `list` literal instead of `list` constructor*

Try it online!
> 7 votes

# Answer
# K (ngn/k), ~~21 20~~ 22 bytes

```
{x@<"54-9176320"?/:$x}

```

Try it online!

`{` `}` function with argument `x`

`$` format as strings

`"`...`"?/:` find indices of individual characters in the given string (or \\$-2^{63}\\$ for not found - note that the `"8"` is missing)

`<` compute sort-ascending permutation

`x@` the argument at those indices
> 6 votes

# Answer
# JavaScript (SpiderMonkey), 69 bytes

```
a=>a.sort((a,b)=>(g=n=>[...n+''].map(c=>':598217604'[c]||3))(a)>g(b))

```

Try it online!
> 6 votes

# Answer
# Pyth, ~~17~~ 16 bytes

```
oxL"54-9176320"`

```

Try it online here, or verify all the test cases at once here.

```
oxL"54-9176320"`NQ   Implicit: Q=eval(input())
                     Trailing N, Q inferred
o                Q   Order the elements of Q, as N, using...
               `N      Convert N to string
 xL                    Get the index of each character of that string...
   "54-9176320"        ... in the lookup ordering
                       (if character missing, returns -1, so 8 is still sorted before 5)

```

*Saved 1 byte thanks to @ngn and their K answer, by omitting 8 from the start of the dictionary string*
> 5 votes

# Answer
# Japt, 19 bytes

```
ñ_s ®n"54-9176320

```

Try it
> 4 votes

# Answer
# Retina 0.8.2, 36 bytes

```
T`-d`3:598217604
O`
T`3:598217604`-d

```

Try it online! Link includes test suite. Explanation:

```
T`-d`3:598217604

```

Translate the minus sign and digits to their position in pronunciation order, using `:` for 10th position.

```
O`

```

Sort in pronunciation order.

```
T`3:598217604`-d

```

Translate the order back to the original minus sign and digits.
> 3 votes

# Answer
# Ruby, 50 bytes

```
->a{a.sort_by{|x|x.to_s.tr('0-9-','a5982176043')}}

```

Try it online!
> 3 votes

# Answer
# Java (JDK 10), 123 bytes

```
l->l.sort(java.util.Comparator.comparing(n->{var r="";for(var c:(""+n).split(""))r+=11+"54-9176320".indexOf(c);return r;}))

```

Try it online!

This is a naive Java implementation. Should be much golfable.

## Credits
> 3 votes

# Answer
# , 58 bytes

```
function(x)x[order(mapply(chartr,"-0-9","dkfjicbhgae",x))]

```

Try it online!

Input is a list of numbers which is implicitly converted as string using `chartr`. `order` then uses lexigographic order to retrieve the order by which the original list should be sorted.
> 3 votes

# Answer
# JavaScript (SpiderMonkey), ~~87~~ 73 bytes

```
a=>a.sort((p,q,F=b=>[...""+b].map(x=>"54-9176320".search(x)))=>F(p)>F(q))

```

Try it online!

Thanks @Arnauld for telling that the sort in SpiderMonkey is stable, so the `||-(F(q)>F(p))` part can finally be dropped.
> 2 votes

# Answer
# Red, 114 bytes

```
func[n][g: func[a][collect[foreach c form a[keep index? find"854-9176320"c]]]sort/compare n func[x y][(g x)< g y]]

```

Try it online!

## More readable:

```
f: func [ n ] [
    g: func [ a ] [
        collect [
            foreach c form a [
                keep index? find "854-9176320" c
            ]
        ]
    ]
    sort/compare n func [ x y ] [ (g x) < g y ]
]

```
> 2 votes

# Answer
# C++, 353 bytes

This is kind of a comedy entry, but I was wasting time and wrote it, so I can't not post it... Enjoy a chuckle, and let me know if there are any space-savers I missed!

```
#include<algorithm>
#include<iostream>
#include<iterator>
#include<numeric>
#include<string>
using namespace std;auto f(int i){auto s=to_string(i);for(auto&c:s)c='A'+"854-9176320"s.find(c);return s;}int main(){int a[100];auto b=begin(a);auto e=end(a);iota(b,e,-50);sort(b,e,[](int l,int r){return f(l)<f(r);});copy(b,e,ostream_iterator<int>(cout," "));}

```

Output:

> 8 5 4 48 45 44 49 41 47 46 43 42 40 -8 -5 -50 -4 -48 -45 -44 -49 -41 -47 -46 -43 -42 -40 -9 -1 -18 -15 -14 -19 -11 -17 -16 -13 -12 -10 -7 -6 -3 -38 -35 -34 -39 -31 -37 -36 -33 -32 -30 -2 -28 -25 -24 -29 -21 -27 -26 -23 -22 -20 9 1 18 15 14 19 11 17 16 13 12 10 7 6 3 38 35 34 39 31 37 36 33 32 30 2 28 25 24 29 21 27 26 23 22 20 0
> 2 votes

# Answer
# Mathematica, 68 bytes

```
SortBy[If[# < 0,"m ",""]<>StringRiffle@IntegerName@IntegerDigits@#&]

```

Function. Takes a list of integers as input and returns the sorted list as output. Just separates the digits of each number with `IntegerDigits`, converts each digit to `"zero"`, `"one"`, etc., with `IntegerName`, converts the list into a space-separated string with `StringRiffle`, prepends an `"m "` if the number is negative, and sorts based on this string. Indeed, this was the shortest approach I can find, since Mathematica only natively uses lexicographic sorting for lists of the same length; thus, an approach based on `854-9176320` ends up taking more bytes since string functions are so expensive.
> 2 votes

# Answer
# 05AB1E, ~~15~~ ~~14~~ 13 bytes

```
Σ•t∍ýJ•(ÁÁsSk

```

-1 byte thanks to *@Emigna*.
-1 byte thanks to *@ovs*.

Try it online or verify all test cases.

**Explanation:**

```
Σ              # Sort by:
 •t∍ýJ•        #  Push compressed integer 917632054
       (       #  Negate it: -917632054
        ÁÁ     #  Rotate it twice towards the right: "54-9176320"
          s    #  Swap so the current number to sort is at the top of the stack
           S   #  Convert it to a list of characters
            k  #  Check for each its index in the string (resulting in -1 for '8')

```

See this 05AB1E tip of mine (section *How to compress large integers*) to understand why `•t∍ýJ•` is `917632054`.
> 1 votes

# Answer
# Nim, 110 109 105 103 bytes

```
import algorithm,sequtils,strutils
func p[S](n:S):S=n.sortedByIt join mapIt($it,$"54-9176320".find(it))

```

Try it online!

For some reason, Nim can't compare `seq`s, so I had to turn the results into a string, which cost quite a lot of bytes.
> 1 votes

---
Tags: code-golf, string, sorting, natural-language
---


# Question
Title: Visually Explain the Pythagorean Theorem
A common visual explanation of the Pythagorean theorem is as such:

The squares are meant to represent the side length's squared, and the areas of `a + b = c`, just like the Pythagorean theorem says.

This part is what you have to show.

# Your task

* You will get two integers as input, meant to represent sides `a` and `b` of a right triangle (ex. `3, 4`).
* You will then make squares out of the lengths `a`, `b`, and `c` out of the `#` character. For example here is 3:

```
###
###
###

```
* You will then format these into a math equation that explains the particular Pythagorean triplet:

```
             #####
      ####   #####
###   ####   #####
###   ####   #####
### + #### = #####

```
* Notice how the `=` and `+` signs have spaces on both sides and how everything is on the bottom.
* You will never get values for `a` and `b` that make `c` non-integral.
* This is so shortest code in **bytes** wins!

# Test Cases

(more coming once I have time, these are really hard to make by hand)

```
3, 4
             #####
      ####   #####
###   ####   #####
###   ####   #####
### + #### = #####

6, 8
                    ##########
                    ##########
         ########   ##########
         ########   ##########
######   ########   ##########
######   ########   ##########
######   ########   ##########
######   ########   ##########
######   ########   ##########
###### + ######## = ##########

4, 3
             #####
####         #####
####   ###   #####
####   ###   #####
#### + ### = #####

5, 12
                       #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
#####   ############   #############
#####   ############   #############
#####   ############   #############
#####   ############   #############
##### + ############ = #############

```

# Answer
# Pyth, 35 32 31 30 bytes

```
j_.ts.i.imm*d\#d+Qs.aQ"+="mk4d

```

Try it online.
> 19 votes

# Answer
# CJam, 49 bytes

```
" +   = "S/3/[q~_2$mh:H]_'#f*:a.*.\:+SH*f.e|zW%N*

```

Try it online in the CJam interpreter.

### How it works

```
" +   = "S/3/ e# Split at spaces, then into chunks of length 3.
              e# This pushes [["" "+" ""] ["" "=" ""]].
[             e#
  q~          e# Read and interpret all input from STDIN.
  _2$         e# Copy both integers.
  mh          e# Calculate the hypotenuse of the triangle with those catheti.
  :H          e# Save the result in H.
]             e# Collect catheti and hypotenuse in an array.
_'#f*         e# Copy and replace each length with a string of that many hashes.
:a            e# Wrap each string in an array.
.*            e# Vectorized repetition. Turns strings into square arrays.
.\            e# Interleave with the string of operators.
:+            e# Concatenate to form an array of strings.
SH*           e# Push a string of spaces of length H.
f.e|          e# Mapped vectorized logical OR; pads all strings with spaces to
              e# length H.
zW%           e# Zip and reverse; rotates the array.
N*            e# Join the strings, separating by linefeeds.

```
> 14 votes

# Answer
# JavaScript ES6, ~~155~~ ~~134~~ ~~140~~ 129 bytes

```
(n,m)=>eval("for(o='',q=(b,s)=>' #'[z<b|0].repeat(b)+(z?'   ':s),z=i=Math.hypot(n,m);z--;)o+=q(n,' + ')+q(m,' = ')+q(i,'')+`\n`")

```

I've rewritten this with `for`. Lots of golfing still...

If something isn't working, let me know. I'll fix it in the morning.

**Tested on Safari Nightly**

## Ungolfed:

```
(n,m)=>
   Array(
     z=Math.hypot(n,m)
   ).fill()
   .map((l,i)=>
      (q=(j,s)=>
        (z-i<=j?'#':' ')
        .repeat(j)+
         (z-i-1?' ':s)
      )
      (n,`+`)+
      q(m,`=`)+
      q(z,'')
   ).join`
   `

```

# Explanation:

(Not updated) but still accurate enough.

```
(n,m)=> // Function with two arguments n,m
   Array( // Create array of length...
    z=Math.hypot(n,m) // Get sqrt(n^2+m^2) and store in z
   ).fill() // Fill array so we can loop
   .map((l,i) => // Loop z times, take l, and i (index)
     (q=j=>( // Create function q with argument j
      z-i<=j? // If z-i is less than or equal to j...
        '#' // Use '#'
      : // OR
        ' ' // Use space
      ).repeat(j) // Repeat the character j times
     )(n) // Run with n
   + // Add to string
   ` ${ // Space
      (b=z-i-1)? // If this isn't the last line...
       ' ' // Return ' '
      : // Otherwise
       '+' // Plus
    } ${ // Space
      q(m) // run function q with arg m
    } ${ // Space
      b? // If b
       ' ' // Return space
      : // Otherwise
        '=' // '='
    }` + // Add to...
    '#'.repeat(z) // Repeat hashtag, z times
  ).join` // Join the new array with new lines
  `

```

# DEMO

ES5 version **Input must be valid sets of numbers**:

```
function _taggedTemplateLiteral(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var _templateObject=_taggedTemplateLiteral(["\n"],["\n"]),t=function(e,t){return Array(z=Math.sqrt(e*e+t*t)).fill().map(function(r,n){return(q=function(e,t){return(z-n<=e?"#":" ").repeat(e)+(z-n-1?" ":t)})(e,"+")+q(t,"=")+q(z,"")}).join(_templateObject)};
// Demo
document.getElementById('go').onclick=function(){
  document.getElementById('output').innerHTML = t(+document.getElementById('input').value,
                                                 +document.getElementById('input2').value)
};
```

```
<div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Visually Explaining the Pythagorean Theorem</h2><div><div  style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Number 1" style="resize:none;border:1px solid #DDD;" id="input"><input placeholder="Number 2" style="resize:none;border:1px solid #DDD;" id="input2"><button id='go'>Run!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div>
```
> 13 votes

# Answer
# Python 2, ~~134~~ 100 bytes

```
a,b=input()
i=c=int(abs(a+b*1j))
while i:print"# "[i>a]*a," +"[i<2],"# "[i>b]*b," ="[i<2],"#"*c;i-=1

```

Try it online.

The program takes input as comma-separated integers, calculates the hypotenuse using Python's built-in complex numbers, then loops down from that value calculating and printing each line as it goes. The main golfing trick is using string indexing in place of conditionals to select `#`/`+`/`=` vs space.

*Edit:* The first version was a victim of some serious over-engineering--this one is both simpler and much shorter.
> 13 votes

# Answer
# Julia, ~~121~~ ~~114~~ 112 bytes

```
f(a,b)=for i=1:(c=isqrt(a^2+b^2)) g(x,t)=(i>c-x?"#":" ")^x*(i<c?"  ":t)" ";println(g(a," +")g(b," =")g(c,""))end

```

Ungolfed:

```
function f(a,b)
    # Compute the hypotenuse length
    c = isqrt(a^2 + b^2)

    # Write the lines in a loop
    for i = 1:c
        # Make a function for constructing the blocks
        g(x,t) = (i <= c - x ? " " : "#")^x * (i < c ? "  " : t) " "

        println(g(a," +") g(b," =") g(c,""))
    end
end

```

Fixed issue and saved 2 bytes thanks to Glen O.
> 12 votes

# Answer
# Pyth, ~~51~~ 49 bytes

```
AQJs.aQLj*b]*b\#;j_MCm_.[d\ Jcj[yJb\=byHb\+byG))b

```

Expects input in the form `[3,4]`.

Try it here

`AQ` \- assigns input to `G, H`

`Js.a,GH` \- calculates hypotenuse as `J`

`Lj*b]*b\#;` \- defines `y(b)` as making a square of size `b` (elsewhere in the code, `b` means newline)

`j_MCm_.[d\ Jcj[yJb\=byHb\+byG))b` \- Creates the squares, pads with spaces, and transposes

Saved two bytes thanks to Maltysen.
> 8 votes

# Answer
# C, 176 bytes

C is not going to win this, but the fun is worth it.

```
#define A(x,y)for(j=x;j--;)putchar("# "[i+1>x]);printf(i?"   ":" "#y" ");
i;j;main(a,b,c){for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c;c++);for(i=c;i--;puts("")){A(a,+)A(b,=)A(c,)}}

```

Pretty printed:

```
#define A(x,y)for(j=x;j--;)putchar("# "[i+1>x]);printf(i?"   ":" "#y" ");
i;j;
main(a,b,c)
{
    for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c;c++);
    for(i=c;i--;puts(""))
    {
        A(a,+)
        A(b,=)
        A(c,)
    }
}

```

gcc enables us to pass third parameter to main (an array of environment variables), so we take advantage of it to use it for our purpose.

The

```
for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c++;);

```

would be equivalent to

```
scanf("%d %d",&a,&b);
for(c=2;a*a+b*b>c*c++;);

```

because `scanf` returns the number of successfully scaned parameters.
> 5 votes

# Answer
# Charcoal, 24 bytes

```
⊞θ₂ΣＸθ²Ｆ =+«←←←ι←Ｇ↑←↓⊟θ#

```

Try it online! Link is to verbose version of code. Takes input as an array of two elements. Explanation:

```
⊞θ₂ΣＸθ²

```

Append the hypotenuse to the inputs.

```
Ｆ =+«

```

Loop over the characters that appear to the right of each square in reverse order.

```
←←←ι←

```

Print that character leftwards with spacing.

```
Ｇ↑←↓⊟θ#

```

Pop the last number from the array and print a square of `#`s of that size.
> 5 votes

# Answer
# Ruby, 134

```
->a,b{c=((a**2+b**2)**0.5).round
c.times{|i|
d=i<c-1?'  ':'+='
puts (c-i>a ?' ':?#)*a+" #{d[0]}  #{(c-i>b ?' ':?#)*b} #{d[1]} "+?#*c}}

```

simple line by line approach.

Below in test program, with symbol changed to @ to help avoid confusting with the syntax `#{....}` ("string interpolation") used to insert expressions into a string. Each input should be given on a different line.

```
f=->a,b{c=((a**2+b**2)**0.5).round
c.times{|i|
d=i<c-1?'  ':'+='
puts (c-i>a ?' ':?@)*a+" #{d[0]}  #{(c-i>b ?' ':?@)*b} #{d[1]} "+?@*c}}

A=gets.to_i
B=gets.to_i
f.call(A,B)

```
> 4 votes

# Answer
# APL (Dyalog Extended), ~~33~~ 29 bytesSBCS

-3 due to my extensions of Dyalog APL.

Anonymous prefix lambda:

```
{⊖⍕,' +=',⍪{⍵ ⍵⍴⍕#}¨⍵,√+/⍵*2}

```

Try it online!

`{``}` "dfn";  is the argument (side lengths)

`⍵*2` square

`+/` sum

square-root

`⍵,` prepend argument

`{` apply the following anonymous lambda to each

`#` root namespace

format as text

`⍵ ⍵⍴` use argument twice to **r**eshape into matrix with those dimensions.

make into column

`' ++=',` prepend these three characters to the three rows

`,` ravel (combine rows into list)

format as text

flip upside-down
> 4 votes

# Answer
# PHP, ~~178~~ ~~170~~ 168 bytes

Input is GET parameters `x` and `y`. Unfortunately I can't seem to golf those repeating strings.

```
<?php for(@$i=$z=hypot($x=$_GET[x],$y=$_GET[y]),@$s=str_repeat;$i;$i--)@print$s($i<=$x?~Ü:~ß,$x).(($l=$i==1)?~ßÔß:~ßßß).$s($i<=$y?~Ü:~ß,$y).($l?~ßÂß:~ßßß).$s(~Ü,$z).~õ;

```
* Saved 8 bytes by inverting all my strings and dropping the quotes.
* Saved 2 bytes by replacing the condition `$i>0` with `$i`

Not sure why PHP doesn't like `@echo` so I had to sacrifice 1 byte with `@print`.

In case SE screws up the encoding, this is meant to be encoded in Windows-1252 (not UTF8).
> 3 votes

# Answer
# PowerShell, ~~139~~ ~~137~~ 135 bytes

-2 thanks to ASCII-only
-2 thanks to Mazzy

```
param($a,$b)($c=[math]::sqrt($a*$a+$b*$b))..1|%{(($m=" ","#")[$_-le$a]*$a)," +"[$_-eq1],($m[$_-le$b]*$b)," ="[$_-eq1],("#"*$c)-join" "}

```

Try it online!

Calculating $c hurt and there's probably a better way to conditionally swap between `#` and . Builds a list of chunks and joins them together while conditionally adding the signs.
> 3 votes

# Answer
# Vyxal, `L`, ~~47~~ ~~43~~ 38 bytes (old codepage)

```
λ\#*wnř;:£f⍎÷ð\+ð?¥f⍎÷ð\=ð??Ķĵ∑√I¥f⍎÷W

```

This was *intense*.

Also, according to code-golf's statistics, only a small percentage of people who see my answers actually upvote them. So if you enjoy this answer, consider upvoting, it's free, and you can change your mind at any time (given you have ≥2k rep). Enjoy the answer.

## Explained

```
λn\#*wnř;:£f⍎ðJ\+JðJ?¥f⍎JðJ\=JðJ??Ķĵ∑√I¥f⍎J

λ                                               # Start a lambda that:
 n\#*                                           #   Repeats the character "#" n times THEN
     w                                          #   Wraps that into a stack AND
      nř                                        #   Repeats the list n times
        ;                                       # Close lambda
         :£f                                    # Assign the lambda to variable 'f' leaving an extra copy
            ⍎                                   # Apply that lambda to the first input
             ðJ\+JðJ                            # Append " ", "+" and " " to the result from above
                    ?¥f⍎                        # Apply the lambda to the second input
                        J                       # Add it to the current list
                         ðJ\=Jð                 # Append " ", "=" and " " to the result from above
                               ??Ķ              # Pair the two inputs into a list
                                  ĵ∑            # Square each number and sum the list (a^2 + b^2)
                                    √I          # Square root that number and convert it to an integer
                                      ¥f⍎       # Apply the lambda to that result (c)
                                         J      # And add it to the big list
                                                # The L flag then auto vertical joins the list and outputs it

```
> 3 votes

# Answer
# CJam, 78 bytes

```
q~_2f#~+mQ+ee_2=~e>f{\~@1$-S*\'#*+_'#e=\a*_0=,S*@"+= "=1$,(S*\+1$a\a@a+++~}zN*

```

It first computes the hypotenuse (H), then, for each side (S), it builds an array of S lines made of: `H-S` spaces + `S` dashes. Finally, it transposes the matrix.

Demo
> 2 votes

# Answer
# Lua5.2, ~~257~~ ~~241~~ ~~227~~ 222 bytes

```
r=io.read
a=r"*n"b=r"*n"c=math.sqrt(a^2+b^2)d=a+b
w=io.write
for i=1,c do
for j=0,d+c+5 do
w((j>d+5 or(i>c-b and j>a+2 and j<d+3)or(i>c-a and j<a))and"#"or(i==c and(j==a+1 and"+"or(j==d+4 and"="or" "))or" "))end
w"\n"end

```
* Edit1: Simplified reading
* Edit2: Removed more whitespaces
* Edit3: aliases abstraction of `io` functions inspired by another answer
> 2 votes

# Answer
# Japt, 28 bytes

Takes input as an array of integers.

```
pUx²¬)ËÆDç'#
í"+="¬ûR3)c ·z3

```

Try it

```
                    :Implicit input of array U=[a,b]
pUx²¬)ËÆDç'#
p                   :Push
 U ²                :  Square each element in U
  x                 :  Reduce by addition
    ¬               :  Square root
     )              :End push
      Ë             :Map each D
       Æ            :  Map the range [0,D)
        Dç'#        :    Repeat "#" D times
í"+="¬ûR3)c ·z3
í                   :Interleave
 "+="¬              :  Split the string "+=" to an array of characters
      û             :  Centre pad each
       R3           :    With newlines to length 3
         )          :End interleave
          c         :Flatten
            ·       :Join with newlines
             z3     :Rotate clockwise 270 degrees

```
> 2 votes

# Answer
# C# (.NET Core), ~~221~~, 194 bytes

This feels way too long. This version just loops to construct the string.

EDIT: Ascii-Only with a nice -27 byte golf using the string constructor for serial char additions! Also, ty for pointing out I was using Math.Sqrt not System.Math.Sqrt. This has been adjusted!

```
(a,b)=>{int c=(int)System.Math.Sqrt(a*a+b*b),j=c;var s="";while(j>0)s+=new string(j>a?' ':'#',a)+(j>1?"   ":" + ")+new string(j>b?' ':'#',b)+(j-->1?"   ":" = ")+new string('#',c)+"\n";return s;}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~38~~ 34 bytes

```
nOtª©Å1'#×ζε®×R„= NĀèð.øý}»R„=+`.;

```

Takes the input as pair of integers (i.e. `[3,4]`).

Try it online or verify all test cases.

**Explanation:**

```
n            # Take the square of each value in the (implicit) input-list
 O           # Take the sum of that list
  t          # Take the square-root of that sum
   ª         # Append it to the (implicit) input-list
             #  i.e. [3,4] → [3,4,5.0]
    ©        # Store it in the register (without popping)
Å1           # Change each value to an inner list of that amount of 1s
  '#×       '# And then each 1 to a "#"
             #  → [["#","#","#"],["#","#","#","#"],["#","#","#","#","#"]]
     ζ       # Zip/transpose; swapping rows/columns, with space as default filler
             #  → [["#","#","#"],["#","#","#"],["#","#","#"],[" ","#","#"],[" "," ","#"]]
ε            # Map the inner lists to:
 ®           #  Push the list from the register
  ×          #  Repeat the characters that many times
             #   i.e. [" ","#","#"] and [3,4,5.0] → ["   ","####","#####"]
   R         #  Reverse this list
 „=          #  Push string "= "
    NĀ       #  Push the map-index truthified (0 remains 0; everything else becomes 1)
             #   i.e. 0 → 0
             #   i.e. 3 → 1
      è      #  Use it to index into the string
       ð.ø   #  Surround it with spaces
             #   → "=" → " = "
             #   → " " → "   "
          ý  #  Join the map-list together with this string as delimiter
             #   → "#####   ####      "
}»           # After the map, join everything by newlines
             #  → "##### = #### = ###\n#####   ####   ###\n#####   ####   ###\n#####   ####      \n#####             "
  R          # Reverse the string
             #  → "             #####\n      ####   #####\n###   ####   #####\n###   ####   #####\n### = #### = #####"
   „=+`.;    # And replace the first "=" with "+"
             #  → "             #####\n      ####   #####\n###   ####   #####\n###   ####   #####\n### + #### = #####"
             # (after which the the result is output implicitly)

```
> 1 votes

# Answer
# Perl 6, 99 bytes

```
{$!=sqrt $^a²+$^b²;flip map({map {[' ','#'][$^d>$_]x$d,' =+ '.comb[!$_*++$ ]},$!,$b,$a},^$!)X"
"}

```

Try it online!

Anonymous code block that takes two numbers and returns the full string with a leading newline and three leading spaces and one trailing on each line.

If we can use other characters instead of `#`, then I can save a byte by replacing `'#'` with `\*`.
> 1 votes

# Answer
# Husk, 36 bytes

```
↔T' `+₁√ṁ□¹`+C1" = "JC1" + "m₁
SRR'#

```

Try it online!

This can be made shorter if I can find a good way to add the symbols in.
> 0 votes

# Answer
# C (gcc), ~~122~~ 119 bytes

-3 thanks to ceilingcat

```
#define P(n);for(i=0;i*i++<n;puts(""))for(j=0;j*j++<n;)putchar(35);puts(
i,j;f(a,b){P(a*a)"+")P(b*b)"=")P(a*a+b*b)"");}

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, geometry
---


# Question
Title: Concentric rings on a snub square tiling
This challenge takes place on the snub square tiling.

Start by choosing any triangle, and color it \\$c\_1\\$. Next, find all tiles which touch this triangle at any vertex, and color them \\$c\_2\\$. Next, find all tiles which share a vertex with any \\$c\_2\\$-colored tile, and color these \\$c\_3\\$. Continue this process ad infinitum.

# Illustration

# Initial terms

The sequence begins

```
  a(1) = 1
  a(2) = 9
  a(3) = 21
  a(4) = 35

```

Notice:

* `a(1) = 1` corresponds to the red triangle;
* `a(2) = 9` corresponds to the number of tiles in the second, orange layer;
* `a(3) = 21` corresponds to the number of tiles in the third, green layer; and so on.

(Note, this sequence is now in the OEIS; OEIS sequence A296368 is closely related.)

# Challenge

Your goal is to write a program that takes in a positive integer `n` and returns the number of tiles that are colored \\$c\_n\\$, (i.e. the number of tiles in the \\$n\\$-th layer.) This is a challenge, so the shortest code in bytes wins.

# Answer
> 8 votes
# Jelly, 8 bytes

```
’3cạ×ʋ12

```

**Try it online!**

### How?

```
’3cạ×ʋ12 - Link: integer, n
’        - decrement              (n-1)                1   2   3   4   5   6   7  ...
      12 - twelve                 12                  12  12  12  12  12  12 12  ...
     ʋ   - dyad:
 3       -   three                3                    3   3   3   3   3   3   3  ...
  c      -   choose               3C(n-1)              1   3   3   1   0   0   0  ...
    ×    -   multiply             (n-1)*12             0  12  24  36  48  60  72  ...
   ạ     -   absolute difference  |3C(n-1)-(n-1)*12|   1   9  21  35  48  60  72  ...

```

# Answer
> 26 votes
# Ruby, 26 bytes

```
->n{~-n*12-496/4**n%4+1/n}

```

Try it online!

Revised version adding `1/n` and subtracting `496/4**n%4` to get the `+1,-3,-3,-1` offset for the first 4 terms.

# Ruby, 32 bytes

```
->n{n>4?~-n*12:[0,1,9,21,35][n]}

```

Try it online!

After 4, the sequence settles down to `(n-1)*12`. See diagram below (the equilateral triangles have been distorted into 45 degree isosceles triangles and the entire diagram rotated 45 degrees, but it remains topologically equivalent.)

# Answer
> 9 votes
# JavaScript (ES6), 23 bytes

Based on Level River St's answer.

```
n=>[1,5,13,7][--n]^n*12

```

Try it online!

### How?

We compute \\$(n-1)\times12\\$ and adjust the first 4 values with a XOR.

$$\begin{array}{c|c} n&1&2&3&4&5&6&7&8&9&10\\ \hline (n-1)\times12&0&12&24&36&48&60&72&84&96&108\\ \hline \text{XOR}&1&5&13&7&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0\\ \hline a(n)&1&9&21&35&48&60&72&84&96&108 \end{array}$$

# Answer
> 9 votes
# 05AB1E, 9 bytes

```
<©12*3®cα

```

Try it online! or try a test suite.

```
<           # input - 1
 ©          # save to register
  12*       # multiply by 12
      ®     # push the register
     3 c    # binomial coefficient(3, input - 1)
        α   # absolute difference

```

With 0-indexing, this would be 7 bytes:

```
12*3Icα

```

# Answer
> 7 votes
# Python, 31 bytes

```
lambda n:n*12-11-(n>4or 5%-n%5)

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Unicode), 14 bytesSBCS

```
12(|×-3!⍨⊢)-∘1

```

Try it online!

Direct translation of Jonathan Allan's Jelly answer. Even the code structure is the same. Jelly is a golfy descendant of APL; if you want to learn Jelly, learn APL first!

### How it works

```
12(|×-3!⍨⊢)-∘1  ⍝ Monadic train, input: n
12(       )-∘1  ⍝ Pass on to the inner function with left←12 and right←n-1
    ×             ⍝ left × right
     -            ⍝ minus
      3!⍨⊢        ⍝ binomial(3, right)
   |              ⍝ absolute value of the above

```

# Answer
> 4 votes
# Jelly, ~~15~~ 9 bytes

```
’3cạ×12$Ʋ

```

Try it online!

A monadic link taking \\$n\\$ as its argument and returning \\$a(n)\\$.

Based on @LevelRiverSt’s clever Ruby answer so be sure to upvote that one too!

Thanks to @Grimmy for saving 6 bytes!

## Explanation

```
 ’       | Subtract 1
       Ʋ | Following as a monad
3c       | - Number of ways of picking (n-1) items from 3
  ạ   $  | - Absolute difference from:
   ×12   |   - Multiply (n-1) × 12

```

# Answer
> 4 votes
# brainfuck, 50 bytes

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

```

Does i/o as raw byte values, like the others here.

# Answer
> 3 votes
# Perl 6, 26 bytes

```
{$_*12-[-1,3,3,1][$_]}o*-1

```

Try it online!

If this could be zero-indexed the `o*-1` at the end can be removed. Returns `(n-1)*12`, offsetting the first 4 values.

# Answer
> 3 votes
# Python 3, 40 36 bytes

```
lambda n:~-n*12-(*n*[0],1,3,3,-1)[4]

```

Try it online!

# Answer
> 2 votes
# Python 3, 39 bytes

```
lambda n:n>4and~-n*12or[1,9,21,35][n-1]

```

Try it online!

Total rip of Level River St's answer so upvote him.

# Answer
> 2 votes
# Python, 38 bytes

```
lambda n:n*12-11-([1]*n+[2,4,4,0])[-n]

```

**Try it online!**

# Answer
> 2 votes
# , 14 bytes

```
12(*|@-3!~])<:

```

Try it online!

A  port of Bubbler's APL answer, so it's also a port of Jonathan Allan's Jelly answer.

# Answer
> 2 votes
# C (gcc), ~~34~~ ~~33~~ 32 bytes

Saved a byte thanks to Grimmy!!!

```
f(n){n=--n<4?"!)5C"[n]-32:n*12;}

```

Try it online!

# Answer
> 1 votes
# brainfuck, 78 bytes

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

```

You can try it online over at TIO (the input is a line-feed (ascii 10) and the output is an `l` (ascii 108))

You can also try the verbose code at this online interpreter where input can be inserted as decimals, e.g. `\6` gives 6 as input. After running, you can hit the "view memory" button and check the value of the output cell in bold, to ensure the result is right.

# Answer
> 1 votes
# brainfuck, 61 bytes

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

```

Input/output as character codes (meta).

Try it online! or try it with decimal I/O.

# Answer
> 1 votes
# Stax, 10 bytes

```
Å²@8Ω@╩vä3

```

Run and debug it

# Answer
> 0 votes
# Rust - 52 bytes

```
let m=|n|(match n{1=>1,2=>9,3=>21,4=>35,_=>n}-1)*12;

```

oh gosh.. it loses even to Brainf\***

---
Tags: code-golf, sequence, combinatorics, tiling
---


title: Divisor skyline

text:
# Question
Title: Divisor skyline
For any positive integer \\$k\\$, let \\$d(k)\\$ denote the number of divisors of \\$k\\$. For example, \\$d(6)\\$ is \\$4\\$, because \\$6\\$ has \\$4\\$ divisors (namely \\$1, 2, 3, 6\\$).

Given a positive integer \\$N\\$, display a "skyline" in ASCII art using a fixed character, such that the height of the "building" located at horizontal position \\$k\\$ is \\$d(k)\\$ for \\$k = 1, ..., N\\$. See test cases below.

# Rules

* Any non-whitespace character may consistently be used, not necessarily `#` as shown in the test cases.
* The algorithm should theoretically work for arbitrarily high \\$N\\$. In practice, it is acceptable if the program is limited by time, memory, data-type size or screen size.
* Horizontally or vertically leading or trailing spaces or newlines are allowed.
* Input and output can be taken by any reasonable means.
* Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
* Shortest code in bytes wins.

# Test cases

`N = 10`:

```
     # # #
   # # ###
 #########
##########

```

`N = 50`:

```
                                               #
                                   #           #
                       #     #     #   # #     #
                       #     #     #   # #     #
           #     # #   #   # # #   #   # # ##  # #
           #   # # #   #   # # #   #   # # ##  # #
     # # # # ### # ### # ### # ##### ### # ### # #
   # # ### # ### # ### ##### # ##### ### # ### ###
 #################################################
##################################################

```

`N = 200`:

```
                                                                                #
                                                                                #
                                                                                #                                               #           #
                                                                                #                       #                       #           #
                                                                                #                       #                       #           #           #
                                                                                #                       #                       #           #           #
                                                           #           #           #     #     #           #           #     #     #       #   #     #     #   #       #           #           #     # #
                                                           #           #           #     #     #           #           #     #     #       #   #     #     #   #       #           #           #     # #
                                               #           #           #       #   #     #     #           #   #       #     #     #       #   #     #     #   # #     #       #   #           #     # #
                                   #           #           #           #       #   #     #     #   #       #   #       #     #     #       #   #     #     #   # #     #       #   #           #   # # #
                       #     #     #   # #     #     # #   #     #   # #     # #   #   # #     #   # # ##  # # # #     #     # # # #  ## # #   #     # # # #   # #  #  # #   # #   # # # #  ## #  ## # #
                       #     #     #   # #     #     # #   #   # #   # #     # #   #   # #     #   # # ##  # # # #     #     # # # #  ## # #   #     # # # #   # #  #  # #   # #   # # # #  ## #  ## # #
           #     # #   #   # # #   #   # # ##  # # # # #   #  ## # # # #  ## # #   #   # # #   # ### # ##  # # # # ##  #   # # # # #  ## # #   #  ## # ### #   # # ##  # ### ###   # # # # ### #  ## # #
           #   # # #   #   # # #   #   # # ##  # # # # #   #  ## # # # #  ## # ##  #   # # #   # ### # ##  # # # # ##  #   # # # # #  ## # #   #  ## # ### #   # # ##  # ### ###   # # # # ### #  ## # #
     # # # # ### # ### # ### # ##### ### # ### # ### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ####### ##### ### ##### # ######### # ##### ##### ### # ### ##### # ######### # ### # #
   # # ### # ### # ### ##### # ##### ### # ### ##### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ############# ### ##### # ######### # ##### ##### ### ##### ##### # ######### # ### # #
 #######################################################################################################################################################################################################
########################################################################################################################################################################################################

```

# Answer
# Jelly, 9 bytes

Uses `0` instead of `#`.

```
RÆD0ṁz⁶ṚY

```

Try it online!
> 12 votes

# Answer
# Octave, ~~41~~ ~~40~~ 32 bytes

Thanks to @StewieGriffin saved 8 bytes.

```
@(N)" #"(sort(~mod(k=1:N,k'))+1)

```

Try it online!

Previous answers:

```
@(N)" #"(sort(~bsxfun(@mod,k=1:N,k')+1))

```

Try it online!

```
@(N)" #"(sort(ismember((k=1:N)./k',k))+1)

```

Try it online!

Explanation:

```
N=5;
d = (1:N)./(1:N)'    %divide each of numbers from 1 to N by 1 to N
                     %a [N by N] matrix created
d =

   1.00   2.00   3.00   4.00   5.00
   0.50   1.00   1.50   2.00   2.50
   0.33   0.66   1.00   1.33   1.66
   0.25   0.50   0.75   1.00   1.25
   0.20   0.40   0.60   0.80   1.00

m = ismember(d,1:N)      %find divisors of each number
m =

  1  1  1  1  1
  0  1  0  1  0
  0  0  1  0  0
  0  0  0  1  0
  0  0  0  0  1

idx = sort(m)                  %sort the matrix

idx =

  0  0  0  0  0
  0  0  0  0  0
  0  0  0  1  0
  0  1  1  1  1
  1  1  1  1  1

" #"(idx+1)     %replace 0 and 1 with ' ' and '#' respectively

   #
 ####
#####

```
> 8 votes

# Answer
## C, ~~99~~ ~~95~~ ~~92~~ ~~91~~ 90 bytes

```
c,l,i,j;f(n){for(j=n;j--;puts(""))for(i=0;i<n;c=!putchar(32|c>j))for(l=++i;l;c+=i%l--<1);}

```

See it work here.
> 7 votes

# Answer
# Haskell, 71 bytes

`f` takes an `Int` and returns a `String`.

```
f m|l<-[1..m]=unlines[[last$' ':drop(m-i)['#'|0<-mod n<$>l]|n<-l]|i<-l]

```

Try it online!

* `m` is the `N` of the OP (Haskell variables must be lowercase.)
* The abbreviation `l=[1..m]` is used in the nested list comprehensions for iterating through all of rows, columns, and potential divisors. This means some extra initial rows filled with whitespace.
* `n` is column (also number checked), `i` is row.
* `['#'|0<-mod n<$>l]` is a list of `'#'` characters with length the number of divisors of `n`.
> 6 votes

# Answer
# Python 3, 111 bytes

```
lambda n:'\n'.join([*map(''.join,zip(*['#'*sum(x%-~i==0for i in range(x))+n*' 'for x in range(1,n+1)]))][::-1])

```

Try it online!

---

This produces some leading vertical whitespace
> 6 votes

# Answer
# Octave, 61 bytes

```
for i=1:input(''),p(1:nnz(~rem(i,1:i)),i)=35;end,[flip(p),'']

```

**Explanation:**

```
for i=1:input('')         % Loop, for i from 1 to the input value
 p(1:nnz(~rem(i,1:i)),i)=35;end,[flip(p),'']
% Breakdown:
         ~rem(i,1:i)      % Return true if the remainder of i divided by any of the values
                          % in the vector 1 - i
     nnz(~rem(i,1:i))     % Check how many of them are non-zero
 p(1:nnz(~rem(i,1:i)),i)=35;end   % Assign the value 35 (ASCII for #) to rows 1
                                  % to the number of divisors of i, in column i
end,              % End loop
[flip(p),'']      % Flip the matrix, and concatenate it with the empty string

```

---

A few things I wish to highlight

* Takes the input directly into the loop
    + Doesn't assign the input value to any variable
* Doesn't initialize any array
    + It creates it on the fly, adding columns and rows as necessary
* Automatically casts ASCII-value 0 to whitespace (ASCII-32)

---

What happens inside the loop (suppose input `6`)

```
p =  35
p =
   35   35
    0   35
p =
   35   35   35
    0   35   35
p =
   35   35   35   35
    0   35   35   35
    0    0    0   35
p =
   35   35   35   35   35
    0   35   35   35   35
    0    0    0   35    0
p =
   35   35   35   35   35   35
    0   35   35   35   35   35
    0    0    0   35    0   35
    0    0    0    0    0   35

```
1. Starts of as a single 35
2. Expands one column and one row, to make room for the two divisors of 2
3. Expands one column, to make room for 3 (only two divisors)
4. Expands one column and one row, to make room for the 3 divisors (`1,2,4`)
5. Expands one column, to make room for 5
6. Expands one column and one row, to make room for the 4 divisors (`1,2,3,6`)

Finally we flip it, and converts it to a string, implicitly changing the `0` to `32`:

```
warning: implicit conversion from numeric to char
ans =
     #
   # #
 #####
######

```
> 6 votes

# Answer
# C#, 333 281 Bytes

```
using System.Linq;using C=System.Console;class P{static void Main(){var n=int.Parse(C.ReadLine());var v=new int[n];for(var k=2;k<=n;k++)for(var i=1;i<k;i++)if(k%i==0)v[k-1]++;for(var i=0;i<v.Length;i++)for(var u=v.Max()-v[i];u<v.Max();u++){C.SetCursorPosition(i,u);C.Write("#");}}}

```

With line breaks:

```
using System.Linq;
using C = System.Console;

class P
{
    static void Main()
    {
        var n = int.Parse(C.ReadLine());
        var v = new int[n];
        for (var k = 2; k <= n; k++)
            for (var i = 1; i < k; i++)
                if (k % i == 0)
                    v[k - 1]++;
        for (var i = 0; i < v.Length; i++)
            for (var u = v.Max() - v[i]; u < v.Max(); u++)
            {
                C.SetCursorPosition(i, u);
                C.Write("#");
            }
    }
}

```

While I'm sure this is possible shorter as well, I hope we'll achieve a shorter solution together ;)

*Saved 52 Bytes with the help of raznagul*
> 6 votes

# Answer
## Mathematica, 99 bytes

```
{T=DivisorSigma[0,Range@#];Row[Column/@Table[Join[Table[,Max[T]-T[[i]]],$~Table~T[[i]]],{i,1,#}]]}&

```

for N=50
> 6 votes

# Answer
## Mathematica, ~~59~~ 57 bytes

```
Rotate[Grid@Map[X~Table~#&,0~DivisorSigma~Range@#],Pi/2]&

```
> 6 votes

# Answer
# APL (Dyalog), 19 bytes

```
⊖⍉↑'#'⍴¨⍨+⌿0=∘.|⍨⍳⎕

```

Try it online!

get evaluated input (*N*)

1...*N*

`∘.|⍨` division remainder table with 1...*N* both as vertical and as horizontal axis

`0=` where equal to zero (i.e. it divides)

`+⌿` sum the columns (i.e. gives count of divisors for each number)

`'#'⍴¨⍨` use each number to reshape the hash character (gives list of strings)

mix (list of strings into table of rows)

transpose

flip upside down
> 5 votes

# Answer
# Charcoal, ~~23~~ ~~22~~ 20 bytes

```
Ｆ…·¹Ｎ«Ｊι⁰Ｆι¿¬﹪ι⁺κ¹↑#

```

Try it online! Link is to verbose version of code. Edit: Saved 1 byte by looping `k` from `0` to `i-1` and adding `1` inside the loop. Saved a further two bytes by not storing the input in a variable. Explanation:

```
Ｆ…·¹Ｎ       for (i : InclusiveRange(1, InputNumber()))
«           {
 Ｊι⁰         JumpTo(i, 0);
 Ｆι          for (k : Range(i))
  ¿¬﹪ι⁺κ¹     if (!(i % (k + 1)))
   ↑#          Print(:Up, "#");
            }

```

Edit: This 18-byte "one-liner" (link is to verbose version of code) wouldn't have worked with the version of Charcoal at the time the question was submitted: Try it online!

```
↑Ｅ…·¹Ｎ⪫Ｅι⎇﹪ι⁺¹λω#ω

```
> 5 votes

# Answer
# Japt, ~~34 33 16~~ 14 bytes

*Saved 17 bytes thanks to @ETHproductions*

```
õ@'#pXâ lÃ·z w

```

Try it online!
> 4 votes

# Answer
# Python 2, 101 bytes

```
N=input();r=range
for i in r(N,0,-1):print''.join('# '[i>sum(x%-~p<1for p in r(x))]for x in r(1,1+N))

```

Try it online!

This produces (a lot of) vertically leading whitespace. It prints a total of `N` lines, the great majority of which will typically be blank.
> 4 votes

# Answer
# SOGL V0.12, 8 bytes

```
∫Λ⁄╗*}⁰H

```

Try it here!
> 4 votes

# Answer
# 05AB1E, 12 bytes

Code:

```
LÑ€g'#×.BøR»

```

Explanation:

```
L             # Create the range 1 .. input
 Ñ            # Get the list of divisors of each
  €g          # Get the length of each element
    '#        # Push a hash tag character
      ×       # String multiply
       .B     # Squarify, make them all of equal length by adding spaces
         ø    # Transpose
          R   # Reverse the array
           »  # Join by newlines

```

Uses the **05AB1E** encoding. Try it online!
> 3 votes

# Answer
# R, ~~83~~ 82 bytes

*-1 byte thanks to MickyT*

```
N=scan();m=matrix('#',N,N);for(i in 1:N)m[i,1:sum(i%%1:N>0)]=' ';write(m,'',N,,'')

```

Reads `N` from stdin.

```
N=scan()                        # read N
m=matrix('#',N,N)               # make an NxN matrix of '#' characters
for(i in 1:N)                   # for each integer in the range
    m[i,1:sum(i%%1:N!=0)]=' '   # set the first n-d(n) columns of row i to ' '
write(m,'',N,,'')               # print to console with appropriate formatting

```

Try it online!
> 3 votes

# Answer
# PowerShell, 101 bytes

```
((($d=1.."$args"|%{($x=$_)-(1..$_|?{$x%$_}).Count})|sort)[-1])..1|%{$l=$_;-join($d|%{' #'[$_-ge$l]})}

```

Less golfed test script:

```
$f = {

$d=1.."$args"|%{
    ($x=$_)-(1..$_|?{$x%$_}).Count
}                                     # $d is the Divisor count array
$maxHeight=($d|sort)[-1]
$maxHeight..1|%{
    $l=$_
    -join($d|%{' #'[$_-ge$l]})
}

}

@(
    ,(10,
    "     # # #",
    "   # # ###",
    " #########",
    "##########")

    ,(50,
    "                                               #  ",
    "                                   #           #  ",
    "                       #     #     #   # #     #  ",
    "                       #     #     #   # #     #  ",
    "           #     # #   #   # # #   #   # # ##  # #",
    "           #   # # #   #   # # #   #   # # ##  # #",
    "     # # # # ### # ### # ### # ##### ### # ### # #",
    "   # # ### # ### # ### ##### # ##### ### # ### ###",
    " #################################################",
    "##################################################")

    ,(200,
    "                                                                                #                    ",
    "                                                                                #                    ",
    "                                                                                #                                               #           #                    ",
    "                                                                                #                       #                       #           #                    ",
    "                                                                                #                       #                       #           #           #        ",
    "                                                                                #                       #                       #           #           #        ",
    "                                                           #           #           #     #     #           #           #     #     #       #   #     #     #   #       #           #           #     # #",
    "                                                           #           #           #     #     #           #           #     #     #       #   #     #     #   #       #           #           #     # #",
    "                                               #           #           #       #   #     #     #           #   #       #     #     #       #   #     #     #   # #     #       #   #           #     # #",
    "                                   #           #           #           #       #   #     #     #   #       #   #       #     #     #       #   #     #     #   # #     #       #   #           #   # # #",
    "                       #     #     #   # #     #     # #   #     #   # #     # #   #   # #     #   # # ##  # # # #     #     # # # #  ## # #   #     # # # #   # #  #  # #   # #   # # # #  ## #  ## # #",
    "                       #     #     #   # #     #     # #   #   # #   # #     # #   #   # #     #   # # ##  # # # #     #     # # # #  ## # #   #     # # # #   # #  #  # #   # #   # # # #  ## #  ## # #",
    "           #     # #   #   # # #   #   # # ##  # # # # #   #  ## # # # #  ## # #   #   # # #   # ### # ##  # # # # ##  #   # # # # #  ## # #   #  ## # ### #   # # ##  # ### ###   # # # # ### #  ## # #",
    "           #   # # #   #   # # #   #   # # ##  # # # # #   #  ## # # # #  ## # ##  #   # # #   # ### # ##  # # # # ##  #   # # # # #  ## # #   #  ## # ### #   # # ##  # ### ###   # # # # ### #  ## # #",
    "     # # # # ### # ### # ### # ##### ### # ### # ### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ####### ##### ### ##### # ######### # ##### ##### ### # ### ##### # ######### # ### # #",
    "   # # ### # ### # ### ##### # ##### ### # ### ##### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ############# ### ##### # ######### # ##### ##### ### ##### ##### # ######### # ### # #",
    " #######################################################################################################################################################################################################",
    "########################################################################################################################################################################################################")

) | % {
    $n,$expected = $_
    $result = &$f $n
    "$result"-eq"$expected"
    #$result    # uncomment this to enjoy the view of the Divisor skyline
}

```

Output:

```
True
True
True

```
> 3 votes

# Answer
# Husk, <sup>~~13~~</sup> 11 bytes

```
↔T' †K'#mḊḣ

```

Try it online!

-2 bytes from Ko King(No, not JoKing).
> 3 votes

# Answer
## , 28 bytes

```
[:|:&.|.[('#',@$~1+_&q:)@-i.

```

Defines a monadic verb. Try it online!

## Explanation

```
[:|:&.|.[('#',@$~1+_&q:)@-i.  Input is y.
                          i.  Range from 0 to y-1
        [                -    subtracted from y (gives range from y to 1).
         (             )@     For each of the numbers:
                   _&q:         Compute exponents in prime decomposition,
                 1+             add 1 to each,
          '#'  $~               make char matrix of #s with those dimensions,
             ,@                 and flatten into a string.
                              The resulting 2D char matrix is padded with spaces.
[:|:&.|.                      Reverse, transpose, reverse again.

```
> 2 votes

# Answer
# Brachylog, 34 bytes

```
⟦fᵐlᵐgDh⌉⟦↔gᵐ;D↔z{z{>₁∧0ṫ|∧Ṣ}ᵐcẉ}ᵐ

```

Try it online!
> 2 votes

# Answer
# PHP, 126 Bytes

```
for(;$n++<$argn;)for($c=$d=0;$d++<$n;)$n%$d?:$r[$n]=++$c;for($h=max($r);$h--;print"
")for($n=0;$n++<$argn;)echo$h<$r[$n]?:" ";

```

Try it online!
> 2 votes

# Answer
## Alice, 33 bytes

```
I.!.t&w?t!aot&wh.Bdt.?-ex' +o&;k@

```

Try it online!

Input is (unfortunately) in the form of a code point. At least it reads a UTF-8 character, so you can use larger inputs than 255, but they're still limited and it's a pretty painful input format. For three additional bytes, we can read a decimal integer:

```
/
ki@/.!.t&w?t!aot&wh.Bdt.?-ex' +o&;

```

Try it online!

The non-whitespace character in the output is `!`.

Note that the solution also prints a ton of leading whitespace (it always starts with an empty line and then prints an `NxN` grid so for larger `N`, there will be many lines of spaces before the first `!`s.)

### Explanation

I've used and explained the `&w...k` construction before (for example here). It's a neat little idiom that pops an integer **n** and then runs a piece of code **n+1** times (consequently, it's usually used as `t&w...k` to run a loop **n** times, with `t` decrementing the input value). This is done by working with the *return address stack* (RAS). `w` pushes the current IP address to the RAS, and if we repeat it with `&` then the address gets pushed **n** times. `k` pops one address from the RAS and jumps back there. If the RAS is empty, it does nothing at all and the loop is exited.

You might notice that it's not trivially possible to nest these loops, because at the end of the inner loop, the stack isn't empty, so the `k` doesn't become a no-op. Instead, the IP would jump back to the beginning of the outer loop. The general way to fix this involves wrapping the inner loop in its own subroutine. But if we can arrange the nested loop such that the outer loop *ends* with the inner loop, we can actually make use of this behaviour and even save on one `k`!

So this construction:

```
&wX&wYk

```

Is a working nested loop which runs the `XYYYXYYYXYYY...` (for some number of `Y`s in each iteration). It's pretty neat that we can end both loops with a single `k`, because it will consume an outer address from RAS each time the inner addresses have been depleted.

This idiom is used in the program to run the loop over the output grid.

```
I         Read a character and push its code point as input N.
.!        Store a copy on the tape.
.         Make another copy.
t&w       Run this outer loop N times. This loops over the lines of the
          output, so the current iteration corresponds to a divisor count
          no more than i (i counting down from N).
  ?t!       Decrement the value on the tape. That means we'll actually have
            i-1 on the tape during the iteration.
  ao        Print a linefeed. Doing this now leads to the weird leading linefeed,
            but it's necessary for the &w...&w...k pattern.
  t&w       Remember that we still have a copy of N on the stack. We'll also
            ensure that this is the case after each loop iteration. So this
            also runs the inner loop N times. This iterates over the columns
            of the output grid so it's j that goes from 1 to N and corresponds
            to the number whose divisors we want to visualise.
              At this point the stack will always be empty. However, operating
              on an empty stack works with implicit zeros at the bottom of
              the stack. We'll use the top zero to keep track of j.
    h         Increment j.
    .B        Duplicate j and push all of its divisors.
    dt        Push the stack depth minus 1, i.e. the divisor count of j.
    .         Duplicate the divisor count.
    ?-        Retrieve i-1 from the tape and subtract it. So we're computing
              d(j)-i+1. We want to output a non-whitespace character iff this
              value is positive (i.e. if i is no greater than d(j)).
    ex        Extract the most significant bit of this value. This is 1 for
              all positive values and 0 for non-positive ones. It's the shortest
              way (I believe) to determine if a value is positive.
    ' +       Add this to the code point of a space. This gives a 33, or '!',
              if the cell is part of the skyline.
    o         Output the character.
    &;        We still have all the divisors and the divisor count on the stack.
              We pop the divisor count to discard that many values (i.e. to
              get rid of the divisors again).
k         Return to the appropriate loop beginning to run the continue the
          nested loop.
@         Terminate the program.

```
> 2 votes

# Answer
# Actually, 25 bytes

```
R♂÷♂l;M' *╗⌠'#*╜@+⌡M┬♂ΣRi

```

Try it online!

## 22-byte version with a lot of leading newlines

```
;╗R⌠÷l'#*╜' *@+⌡M┬♂ΣRi

```

Try it online!
> 2 votes

# Answer
# PHP, 99 bytes

```
for(;$d<$k?:$k++<$argn+$d=$n=0;)$k%++$d?:$r[--$n]=str_pad($r[$n],$k).H;ksort($r);echo join("
",$r);

```

prints one leading space; run as pipe with `php -nr '<code>'` or try it online.

**breakdown**

```
for(;$d<$k?:                    # inner: loop $d from 1 to $k
    $k++<$argn+$d=$n=0;)        # outer: loop $k from 1 to $argn, reset $d and $n
    $k%++$d?:                       # if $d divides $k
        $r[--$n]=str_pad($r[$n],$k).H;  # add one store to building $k
ksort($r);echo join("\n",$r);   # reverse and print resulting array

```
> 2 votes

# Answer
# SpecBAS - 149 bytes

```
1 INPUT n: DIM h(n)
2 FOR i=1 TO n
3 FOR j=1 TO i
4 h(i)+=(i MOD j=0)
5 NEXT j
6 NEXT i
7 FOR i=1 TO n
8 FOR j=51-h(i) TO 50
9  ?AT j,i;"#"
10 NEXT j
11 NEXT i

```

An array keeps track of number of divisors, then prints the right number of characters down to screen position 50.
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~46~~ 44 bytes

```
Grid[PadLeft[0Divisors@Range@#-" "]+" "]&

```

Try it online! But maybe try it online! with ColumnForm instead of Grid, since `Grid` doesn't work in TIO. In Mathematica, it looks better:

A third Mathematica solution... `Divisors@Range@#` finds all the divisors in the range we want, and then we multiply by `0` and subtract `" "`, making every divisor equal to `-" "`.

`PadLeft` adds zeroes on the left, creating a sideways skyline, whose orientation we fix with =`\[Transpose]`. Finally, adding `" "` to everything makes all entries either `0` or `" "`.

As an alternative, the 59-byte `""<>Riffle[PadLeft["X"-" "+0Divisors@Range@#]+" ","\n"]&` produces string output.
> 2 votes

# Answer
# Add++, 58 bytes

```
D,g,@,FL1+
D,k,@~,J
L,R€gd"#"€*$dbM€_32C€*z£+bUBcB]bR€kbUn

```

Try it online!

## How it works

Our program consists of two helpers functions, `g` and `k`, and the main lambda function. `g` iterates over each integer, \\$x\\$, between \\$1\\$ and \\$n\\$ and returns \\$d(x)\\$ as defined in the challenge body, while `k` takes a list of characters and concatenates them into a single string.

The main lambda function generates \\$A = \[d(1), d(2), d(3), ..., d(n)\]\\$, then repeats the `#` character for each element of \\$A\\$. We then take \\$\max(A)\\$, and subtract each element in \\$A\\$ from this maximum, before yielding this number of spaces for each element and concatenating the spaces to the repeated hashes. Next, we transpose and reverse the rows, before joining each line on newlines. Finally, we output the skyline.
> 2 votes

# Answer
# Vyxal, `L`, ~~6~~ 5 bytes

```
ƛKL×*

```

Try it Online!

## Explained

```
ƛKL×*
ƛ       # Over the range [1, input] do the following:
 KL     #   Push the length of the list of that number's divisors
   ×    #   Push '*'
    *   #   And multiply the two together, repeating the "*"
        # Automatically close the map and then use the L flag to vertically join that list

```
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
LÑ_ζRJ»

```

Uses `0` (or `1`) instead of `#`.

Try it online.

**Explanation:**

```
L        # Push a list in the range [1, (implicit) input]
 Ñ       # Convert each value to a list of its divisors
  _      # Convert each inner integer to 0
   ζ     # Zip/transpose; swapping rows/columns, with space as default filler
    R    # Reverse the list of lists
     J   # Join each inner list together
      »  # And then join the list of strings by newlines
         # (after which the result is output implicitly)

```

The `_` (==0) has some a few alternatives to get distinct values: `a` (is\_alphabetic); `Ā` (!=0); `d` (\>=0):
try it online.
> 2 votes

# Answer
# Pyth, 16 bytes

```
j_.tm*\#/%LdSQ0S

```

Try it online!
> 1 votes

# Answer
# Japt `-R`, 10 bytes

Uses `1` instead of `#`.

```
õ_â mÎ¬ÃÕÔ

```

Try it

```
õ_â mÎ¬ÃÕÔ     :Implicit input of integer U
õ              :Range [1,U]
 _             :Map
  â            :  Divisors
    m          :  Map
     Î         :    Sign
      ¬        :  Join
       Ã       :End map
        Õ      :Transpose
         Ô     :Reverse
               :Implicit output joined with newlines

```
> 1 votes

# Answer
# Stax, 11 bytes

```
ñ┌½♠å←ⁿ╨║x╦

```

Run and debug it
> 1 votes

---
Tags: code-golf, math, ascii-art, number-theory, integer
---


title: Is it truthy or falsy?

text:
# Question
Title: Is it truthy or falsy?
There are so many different ways to express whether something is true or not! The goal of this challenge is to produce a standardized output of `truthy` or `falsy` for various input truthy and falsy values.

For the purposes of this challenge, the following inputs are considered truthy:

1. A string representing a signed integer with a non-zero value (contains only the digits `[0-9]`, with an optional `-` at the beginning). Note that the string `-0` will never be given as input. A non-zero integer will never be preceded by a `0` (i.e. `01` will never be given as input, similarly `-01` will never be gien as input).
2. The case-insensitive strings equivalent to one of `defined`, `found`, `nonnil`, `non-nil`, `on`, `success`, `t`, `true`, `y`, and `yes`

For the purposes of this challenge, the following inputs are considered falsy:

1. The string `0`. Repeated zeros (`00`, `00...`) will never be given as input.
2. An empty string
3. The case-insensitive strings equivalent to one of `f`, `failure`, `false`, `n`, `nan`, `nil`, `no`, `notfound`, `not-found`, `null`, `nullptr`, `off`, and `undefined`

# Input

The input is a string representing a truthy/falsy value. The string may come from any source desired (stdio, function parameter, etc.). There is no leading/trailing whitespace.

The input is guaranteed to match one of the allowed truthy/falsy values above (i.e. you do not need to provide any error handling).

# Output

Your program/function must output a truthy/falsy value which represents the "truthy-ness" or "falsy-ness" of the input. You are only allowed to specify exactly 1 truthy and 1 falsy value which your output must convert the input to (these are your "standardized" truthy/falsy value). The output may be written to any sink desired (stdio, return value, output parameter, etc.).

Please specify what `truthy` and `falsy` value you chose in your answer.

Ex.: If you choose the string `true` as a truthy value, you cannot also have the integer `1` for truthy.

# Test Cases

Test cases are formatted as the first line is the input, and the second line is the output.

```
-1
true

1
true

1234
true

-4321
true

defined
true

deFined
true

Found
true

nonnil
true

non-nil
true

ON
true

SuCCess
true

T
true

true
true

y
true

YeS
true

0
false

'' (empty string)
false

faLSE
false

f
false

Failure
false

n
false

NaN
false

nil
false

no
false

notfound
false

not-Found
false

NULL
false

nullptr
false

OFF
false

unDefined
false

```

# Scoring

This is code-golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.

# Answer
# MATL, 20 bytes

```
U|sG36ZA13\[BID1]m+g

```

Input is a string enclosed in single quotes. Output is `1` for truthy or `0` for falsy.

Try it online! Or verify all test cases.

### How it works

```
U|s      % Take input implicitly. Interpret as number, absolute value, sum
G36ZA    % Push input again. Convert from base-36
13\      % Modulo 13
[BID1]   % Push array [6 3 8 1]
m        % True if member: gives 1 iff the result from modulo 13 is in the array
+g       % Add, convert to logical. Display implicitly

```

This performs two tests on the input:

1. Try to interpret the input as a number, and detect if it is nonzero. The function used to interpret a string as a number outputs an empty array if it's not possible; and the sum of the entries of an empty array is `0`. So it suffices to try the conversion, take the absolute value, and sum. This gives a positive value if the input contains a nonzero number, and `0` otherwise.
2. Assuming the input string doesn't represent a number, we need to classify it into one of the two given sets. To do this, the input is interpreted as the digits of a number expressed in base-36, using alphabet `'01...9ab...z'`. The base conversion function is case-insensitive and ignores digits not present in the alphabet (in our case, `'-'`). It turns out that the modulo 13 of the resulting number is `1`, `3`, `6` or `8` for the truthy strings, and doesn't give any of those values for the falsy strings. So it can be used as a signature. We thus perform modulo 13 and see if the result is any of those four values. This gives `1` if it is, or `0` otherwise.

The final result should be truthy if any of the two conditions is met, and falsy otherwise. So we add the two numbers resulting from 1 and 2 above and convert to logical, which gives `1` or `0` as standardized truthy/falsy values.
> 18 votes

# Answer
## Retina, ~~22~~ ~~24~~ 23 bytes

*Saved 1 byte thanks to edc65*

```
i`^([-1-9sdty]|fo|n?on)

```

The whole code is just a regex. The `i`` at the start makes the regex case insensitive.

Outputs `1` for truthy, `0` for falsey.

Try it online!
> 9 votes

# Answer
## Batch, 142 bytes

```
@goto l%1 2>nul
:l
:l0
:lfailure
:lfalse
:ln
:lnan
:lnil
:lno
:lnotfound
:lnot-found
:lnull
:lnullptr
:loff
:lundefined
@echo 1

```

Outputs 1 for falsy, nothing for truthy.
> 8 votes

# Answer
# JavaScript (ES6), 35 ~~39~~

*Edit* using the `n?on` trick, stolen from BusinessCat's answer

*Edit 2* OP clarified, no leading 0s, saved 4 bytes

```
v=>/^([-1-9dsty]|fo|n?on)/i.test(v)

```

Simply returns `true` or `false`

**Test**

```
f=v=>/^([-1-9dsty]|fo|n?on)/i.test(v)

trues=[-1,1,1234,-4321,'defined','deFined','Found',
'nonnil','non-nil','ON','SuCCess','T','true','y','YeS']
falses=[0,'','faLSE','f','Failure','n','NaN','nil',
'no','notfound','not-Found','NULL','nullptr','OFF','unDefined']

console.log('TRUE: '+trues.map(x=>f(x)))

console.log('FALSE:' +falses.map(x=>f(x)))
```
> 6 votes

# Answer
# Python, ~~129~~ ~~79~~ 78 bytes

Gotta submit fast!

```
lambda n:n.lower()[:3]in" 0 f n no nil fai fal nan not nul off und".split(" ")

```

True is false and false is true; I have a nice rhyme for this, I really do (not)
> 4 votes

# Answer
# Python, 111 bytes

```
def b(s):s=s.lower();return s!='no'and not sum(map(ord,s))in[0,48,323,744,523,877,110,785,443,922,315,317,946]

```

Tests on sum of ASCII values, extra check for `no` since `on` has the same value.

* Edit1: forgot to test on integer values. Now checking for false inputs
> 4 votes

# Answer
# Python, ~~83~~ 75 bytes

```
import re
def f(s):return re.search(r'^([-1-9dsty]|fo|n?on)',s.lower()).pos

```

Returns 0 on success, AttributeError on failure.

Now using edc85's regex to save 8 bytes.
> 3 votes

# Answer
## PowerShell v2+, ~~39~~ 37 bytes

```
$args[0]-match'^([-1-9dsty]|fo|n?on)'

```

Presumes that the answer to @feersum's question is "No, truthy integers may not start with a `0`."

Port of @edc65's regex JavaScript answer, with my own `1-9` substitution instead of `\d`. Uses @BusinessCat's `n?on` trick to golf further.

Outputs literal Boolean `$true` or `$false` values, which when left on the pipeline and sent through an implicit `Write-Output` at the end of execution results in `True` or `False` being printed to the console.

---

If the answer is "Yes, truthy integers can start with `0`," then the following changes need to be made for **~~51~~ 49 bytes**

```
param($n)$n-ne0-and$n-match'^([-\ddsty]|fo|n?on)'

```

---

If you don't like regex, go for PowerShell v3+ and the following at **107 bytes**

```
param($n)$n-and$n-notin-split'0 f failure false n nan nil no notfound not-found null nullptr off undefined'

```

This takes the string of falsey values, `-split`s them on whitespace, and uses the `-notin` operator to check the input `$n` against that array of strings (which is, by default, case-insensitive). Requires the `$n-and` to check against the empty string.
> 2 votes

# Answer
# PHP, 50 bytes

```
<?=preg_match('%^([-1-9dsty]|fo|n?on)%i',$argv[1])

```

prints `1` for truthy, nothing for falsy

tried to come up with a different solution, but the shortest regex for falsy is 3 bytes longer than that for truthy: `%^(0|fa|f?$|n(?!on)|of|u)%i`
> 1 votes

# Answer
# Zsh, 32 bytes

```
grep -Pi '^([-1-9dsty]|fo|n?on)'

```

Try it online!

Outputs via exit code; 0 is truthy, 1 is falsey
> 1 votes

# Answer
## Python, 83 bytes

```
lambda x:x.lower()[:3]in['fou','non','on']or x[:1].lower()in'dsty-123456789'and''<x

```

https://repl.it/ClgO/1
> 0 votes

---
Tags: code-golf, string, decision-problem, classification
---


title: Counter-Fibonacci Sequences

text:
# Question
Title: Counter-Fibonacci Sequences
Given three numbers ***m***,***n*** and ***p***, your task is to print a list/array of length ***p*** starting with ***m*** and ***n*** and each element after ***p*** represents the difference of the 2 numbers before it, ***m-n*** (Counter-**Fibonacci Sequence**)

For this challenge you can either use a function to return or print the result or a full program.

### Input

Three integers, ***m***,***n*** and ***p***, separated by newlines/spaces/commas, whatever your language supports, but you should specify your input format. Code insertion is disallowed.

### Output

The numbers contained by the Counter-Fibonacci Sequence, in any of the following formats (this example: `m = 50, n = 40, p = 6`):

* `50,40,10,30,-20,50` (or with spacing after commas)
* `[50,40,10,30,-20,50]` (or with spacing after commas)
* `50 40 10 30 -20 50` (or with `\n`(newlines) instead of spaces)
* `{50,40,10,30,-20,50}` (or with spaces instead of commas)

---

### Examples

```
Input => Output

50,40,10 => 50,40,10,30,-20,50,-70,120,-190,310
-100,-90,7 => -100,-90,-10,-80,70,-150,220
250,10,8 => 250,10,240,-230,470,-700,1170,-1870

```

### Rules

* You are guaranteed that ***p*** is higher than 1
* You should provide a way to test your program, if possible
* Take note that this loopholes are forbidden and code insertion is disallowed, as mentioned above

### Scoring & Leaderboard

Your code must be as short as possible, since this is . **No answer will be accepted**, because this challenge is meant to find the shortest answer by language, avoiding an unfair advantage to golfing languages.

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

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

---

Related Question by ETHproductions: Monday Mini-Golf #1: Reverse Fibonacci Solver

# Answer
> 9 votes
## Haskell, 29 bytes

```
a#b=a:b#(a-b)
(.(#)).(.).take

```

Length `p` is the first parameter. Usage example: `( (.(#)).(.).take ) 10 50 40` -\> `[50,40,10,30,-20,50,-70,120,-190,310]`. Try it online!.

Shortening the list to `p` elements takes more bytes than producing it.

# Answer
> 6 votes
# Python 2, 39 bytes

*-2 bytes thanks to ETHproductions*

*-1 byte thanks to Dennis*

```
f=lambda m,n,p:p*[0]and[m]+f(n,m-n,p-1)

```

Try it Online!

# Answer
> 6 votes
# Jelly, 6 bytes

```
_@Ð¡+Ṗ

```

Try it online!

### How it works

```
_@Ð¡+Ṗ  Main link. Left argument: m. Right argument: n. Third argument: p

    +   Yield (m + n), the term that comes before m.
  Ð¡    Execute the link to the left p times, starting with left argument m and
        right argument (m + n). After each execution, replace the right argument
        with the left one and the left argument with the previous return value.
        Yield all intermediate values of the left argument, starting with m.
_@          Subtract the left argument from the right one.
        This yields the first (p + 1) terms of the sequence, starting with m.
    Ṗ   Pop; discard the last term.

```

# Answer
> 5 votes
# JavaScript (ES6), 33 bytes

```
f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

```

Returns a string of the format `1,2,3,` — without using strings!

### Test snippet

```
f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

console.log(f(50,40,10))
console.log(f(-100,-90,7))
console.log(f(250,10,8))
```

# Answer
> 5 votes
# CJam, 15 bytes

```
q~2-{1$1$-}*]S*

```

1 extra byte because CJam doesn't naturally use one of the allowed output formats \>\_\<

Try it online!

**Explanation**

```
q~               e# Read and eval the input
  2-             e# Subtract 2 from p (to account for m and n being in the list)
    {            e# Run this block p-2 times:
     1$1$-       e#   Copy the top values and subtract
          }*     e# (end of block)
            ]    e# Wrap the stack in an array
             S*  e# Join with spaces

```

# Answer
> 5 votes
# Perl 6, 25 bytes

```
{($^m,$^n,*-*...*)[^$^p]}

```

Try it

## Expanded:

```
{  # bare block lambda with placeholder parameters ｢$m｣ ｢$n｣ ｢$p｣
  (
    $^m, $^n,  # declare first two params, and use them

    * - *      # WhateverCode lambda which subtracts two values

    ...        # keep using that to generate values

    *          # never stop (instance of type Whatever)

  )[ ^ $^p ]   # declare last param, and use it to grab the wanted values
               # ｢^ $^p｣ is short form of range op
               # ｢0 ..^ $^p｣ which excludes the ｢$p｣
}

```

# Answer
> 4 votes
# 05AB1E, ~~9~~ 7 bytes

```
ÍFÂ2£¥«

```

Try it online!

**Explanation**

```
ÍF          # p-2 times do
  Â         # create a reversed copy of the current list
   2£       # take the first 2 elements of the list
     ¥      # calculate delta
      «     # append to the list

```

# Answer
> 3 votes
# Röda, 38 bytes

```
f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}

```

Try it online!

Explained:

```
f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}
f i,a,b{                             } /* Function declaration */
        seq 1,i                        /* Push numbers 1..i to the stream */
               |{|_|               }_  /* For each number in the stream: */
                    [a];               /*   Push the current value of a */
                        b=a-b;         /*   Set b = the next number */
                              a=a-b    /*   Set a = the previous value of b */

```

# Answer
> 3 votes
# Haskell, 33 bytes

```
(m!n)0=[]
(m!n)p=m:(n!(m-n))(p-1)

```

Call using `(m!n)p`. Works by defining `!` as an infix function that takes in `m` and `n` and returns a function that takes `p` and returns the desired result.

# Answer
> 2 votes
# PHP, 76 Bytes

```
[,$a,$b,$c]=$argv;for($r=[$a,$b];$c---2;)$r[]=-end($r)+prev($r);print_r($r);

```

## PHP, 84 Bytes

```
[,$a,$b,$c]=$argv;for($r=[$a,$b];$c>$d=count($r);)$r[]=$r[$d-2]-end($r);print_r($r);

```

# Answer
> 2 votes
# Ruby, 31 bytes

```
->m,n,p{p.times{m,n=n,(p m)-n}}

```

The straightforward solution

# Answer
> 2 votes
# Pyth, 18 bytes

```
JEKEVEJ=N-JK=JK=KN

```

Try it online!

Input and output are both delimited by newlines.

How it works:

```
JEKE                Read two lines of input to J and K
    VE              Read another line and loop that many times:
      J               Print J
       =N-JK          Set N to J - K (Pyth uses prefix notation)
            =JK       Set J to K
               =KN    Set K to N

```

# Answer
> 1 votes
# Mathematica, 26 bytes

```
{-1,1}~LinearRecurrence~##

```

Lovin' the builtin. Takes input in the form `{{m, n}, p}`. `LinearRecurrence` wants the know the coefficients of the linear combination of previous elements to use to generate new elements, which in this case is `{-1,1}`.

# Answer
> 1 votes
## QBIC, ~~35~~ 33 bytes

```
:::?'a;b;`[c-2|e=a-b?e';`┘a=b┘b=e

```

*Saved 2 bytes by placing the first `PRINT` into one code literal.*

Explanation (35 byte version):

```
:::         Get parameters a, b, c from the cmd-line
  ';`       This suppresses a newline when printing
?a   b';`   PRINT a and b
[c-2|       FOR x=1; x<=(c-2); x++
  e=a-b       calculate the next term of the sequence
  ?e';`       Print it, suppressing newline
  ┘a=b        ┘ denotes a syntactic linebreak; shove the numbers one over
  ┘b=e        dito
            FOR-loop is auto-closed

```

# Answer
> 1 votes
# C, 128 bytes

```
m,n,p,z;main(c,v)char**v;{m=atoi(v[1]);n=atoi(v[2]);p=atoi(v[3])-2;printf("%d,%d",m,n);while(p--)z=m,m=n,n=z-m,printf(",%d",n);}

```

This program parses the three arguments `m`, `n` and `p` from the command-line, and prints the output as specified.

Modern C compilers allow you to omit basic imports, and thus we can use `printf` and `atoi` without the `#include`s.

Global variables are `int` by default when declared without a type - this saves a lot of space.

# Answer
> 1 votes
# Java, 66 bytes

For once, lambdas are the inefficient approach to golfing due to the *very* roundabout way of applying recursion to them that requires a lot of extra bytes.

Golfed:

```
String f(int m,int n,int p){return""+m+(p>1?","+f(n,m-n,p-1):"");}

```

Ungolfed:

```
public class CounterFibonacciSequences {

  private static final int[][] INPUTS = new int[][] { //
      { 50, 40, 10 }, //
      { -100, -90, 7 }, //
      { 250, 10, 8 } };

  private static final String[] OUTPUTS = new String[] { //
      "50,40,10,30,-20,50,-70,120,-190,310", //
      "-100,-90,-10,-80,70,-150,220", //
      "250,10,240,-230,470,-700,1170,-1870" };

  public static void main(String[] args) {
    for (int i = 0; i < INPUTS.length; ++i) {
      final int m = INPUTS[i][0];
      final int n = INPUTS[i][1];
      final int p = INPUTS[i][2];
      System.out.println("M: " + m);
      System.out.println("N: " + n);
      System.out.println("P: " + p);
      System.out.println("Expected: " + OUTPUTS[i]);
      System.out.println("Actual:   " + new CounterFibonacciSequences().f(m, n, p));
      System.out.println();
    }
  }

  String f(int m, int n, int p) {
    return "" + m + (p > 1 ? "," + f(n, m - n, p - 1) : "");
  }
}

```

# Answer
> 1 votes
# AHK, 68 bytes

```
m=%1%
n=%2%
3-=2
Send %m%`n%n%`n
Loop,%3%
{
n:=m-n
m-=n
Send %n%`n
}

```

Getting' really tired of not knowing how / being able to use passed arguments (`%1%`, `%2%`, ...) directly in any math functions

# Answer
> 1 votes
# Python 2, ~~93~~ 90 bytes

```
u,t=int,input;m,n,p=u(t()),u(t()),u(t());l=[m,n]
for i in range(p-2):l.append(l[-2]-l[-1])

```

Try it online!

Saved 3 bytes thanks to @Mr.Xcoder

It works by taking the numbers as input and formatting them correctly, then using a for loop to generate a list based on the inputted numbers.

# Answer
> 1 votes
# Husk, 7 bytes

```
↑¡o→Ẋ`-

```

Try it online!

## Explanation

```
↑¡o→Ẋ`-
 ¡o     create an infinite list using the array:
        the next element is:
   →    the last element of
    Ẋ`- overlapping pairs reduced by subtraction.
↑       take n elements

```

# Answer
> 0 votes
# Swift - 85 bytes

```
func y(x:Int,y:Int,z:Int){var m=x,n=y,p=z,c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

```

Usage: `y(x:50,y:40,x:6)`

# Swift - 84 bytes

```
func z(l:[Int]){var m=l[0],n=l[1],p=l[2],c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

```

*Usage:* `z(l: [50,40,6])`

---

*Output:*

```
50
40
10
30
-20
50

```

# Answer
> 0 votes
# Python - 55 bytes

```
def s(m,n,p):
 for i in range(p):print(m);c=m;m=n;n=c-n

```

**Try it online!** & Usage: `s(50,40,6)`

Note: Solution without lambda

---
Tags: code-golf, math, number, sequence, fibonacci
---