title: Split a number in every possible way

text:
# Question
Title: Split a number in every possible way
You task here is very simple:
Given a positive integer `n` without leading zeroes as input, split it in all possible ways

## Examples

**Input-\>Output**

```
111  -> {{111}, {1, 11}, {11, 1}, {1, 1, 1}}

123  -> {{123}, {12, 3}, {1, 23}, {1, 2, 3}}

8451 -> {{8451}, {845, 1}, {8, 451}, {84, 51}, {84, 5, 1}, {8, 45, 1}, {8, 4, 51}, {8, 4, 5, 1}}

10002-> {{10002},{1,2},{10,2},{100,2},{1000,2},{1,0,2},{10,0,2},{100,0,2},{1,0,0,2},{10,0,0,2},{1,0,0,0,2}}

42690-> {{42690}, {4269, 0}, {4, 2690}, {426, 90}, {42, 690}, {426, 9, 0}, {4, 269, 0}, {4, 2, 690}, {42, 69, 0},  {42, 6, 90}, {4, 26, 90}, {42, 6, 9, 0}, {4, 26, 9, 0}, {4, 2, 69, 0}, {4, 2, 6, 90}, {4, 2, 6, 9,  0}}

```

## Rules

Leading zeroes, if they occur, should be removed.
Duplicate partitions in your final list should also be removed.
The order in which the partitions appear in the final list is irrelevant.

This is `code-golf`. Shortest answer in bytes, wins!

Sandbox

# Answer
# Brachylog, 8 bytes

```
ṫ{~cịᵐ}ᵘ

```

Convert to string  and get all unique `{…}ᵘ` reverse concatenations `~c` mapped to integers `ịᵐ` (to remove leading zeros).

Try it online!
> 10 votes

# Answer
# 05AB1E, 4 bytes

```
.œïÙ

```

Try it online!

---

### Explanation

```
.œ      - Partitions of implicit input
  ï     - Converted to integers (will remove leading 0s)
   Ù    - Uniquified
        - Output implicitly

```
> 8 votes

# Answer
# Python 3, 87 bytes

```
f=lambda s:{(int(s),)}|{a+b for i in range(1,len(s))for a in f(s[:i])for b in f(s[i:])}

```

Try it online!
> 7 votes

# Answer
# Pyth, 6 bytes

```
{sMM./

```

Try it online!

## Explanation

```
{sMM./
    ./  # Partitions of implicit input
 sMM    # Convert to integers (to remove leading 0s)
{       # Deduplicate

```
> 6 votes

# Answer
# , ~~136~~ 126 bytes

*Edit: -10 bytes thanks to Giuseppe*

```
function(s,n=nchar(s))unique(lapply(apply(!combn(rep(1:0,n),n-1),2,which),function(i)as.double(substring(s,c(1,i+1),c(i,n)))))

```

Try it online!

Hmm... I suspect that this mayn't be the shortest way... but so far my attempts at recursive solutions have been *even* longer...

**Commented code:**

```
split_number=
function(s,n=nchar(s))                # s=input number (converted to string), n=digits
 unique(                              # output unique values from...
  lapply(                             # ...looping over all...
   apply(                             # ...combinations of breakpoints by selecting all...
    !combn(rep(1:0,n),n-1),           # ...combinations of TRUE,FALSE at each position...
     1,which),                        # ...and finding indices,
   function(i)                        # ...then, for each combination of breakpoints...
    as.double(                        # ...get numeric value of...
     substring(s,c(1,i+1),c(i,n))     # ...the substrings of the input number
 )

```
> 6 votes

# Answer
# Jelly, ~~5~~ 4 bytes

```
ŒṖḌQ

```

Try it online!

-1 byte thanks to Jonathan Allan

## How it works

```
ŒṖḌQ - Main link. Takes an integer as argument (e.g. n = 42690)
ŒṖ   - Get all partitions. Automatically cast to digits  [[4, 2, 6, 9, 0], [4, 2, 6, [9, 0]], [4, 2, [6, 9], 0], [4, 2, [6, 9, 0]], [4, [2, 6], 9, 0], [4, [2, 6], [9, 0]], [4, [2, 6, 9], 0], [4, [2, 6, 9, 0]], [[4, 2], 6, 9, 0], [[4, 2], 6, [9, 0]], [[4, 2], [6, 9], 0], [[4, 2], [6, 9, 0]], [[4, 2, 6], 9, 0], [[4, 2, 6], [9, 0]], [[4, 2, 6, 9], 0], [4, 2, 6, 9, 0]]
  Ḍ  - Convert each list back to digits                  [[4, 2, 6, 9, 0], [4, 2, 6, 90], [4, 2, 69, 0], [4, 2, 690], [4, 26, 9, 0], [4, 26, 90], [4, 269, 0], [4, 2690], [42, 6, 9, 0], [42, 6, 90], [42, 69, 0], [42, 690], [426, 9, 0], [426, 90], [4269, 0], 42690]
   Q - Remove duplicates                                 [[4, 2, 6, 9, 0], [4, 2, 6, 90], [4, 2, 69, 0], [4, 2, 690], [4, 26, 9, 0], [4, 26, 90], [4, 269, 0], [4, 2690], [42, 6, 9, 0], [42, 6, 90], [42, 69, 0], [42, 690], [426, 9, 0], [426, 90], [4269, 0], 42690]
      - Implicit output

```
> 5 votes

# Answer
# Scala, ~~139~~...~~104~~ 94 bytes

```
def f(? :String):Set[_]=Set(?)++(for{< <-1 to?.size-1
x<-f(?take<)
y<-f(?drop<)}yield x+","+y)

```

Try it online!

A recursive method. The input has to be a string.
> 5 votes

# Answer
# Perl 5 `-MList::Util=uniq -F`, ~~108~~ ~~96~~ ~~94~~ 90 bytes

```
say uniq map{@b=(sprintf'%b',$_)=~/./g;$_="@F
";s/ /','x pop@b/ge;s/\d+/$&*1/reg}1..2**$#F

```

Try it online!
> 5 votes

# Answer
# Retina 0.8.2, 59 bytes

```
\G\d
$&$'¶$`,$&
+%)`^.+¶

m`^,|\b0+\B

O`
m`^(.+)(¶\1)+$
$1

```

Try it online! Link includes test cases. Explanation:

```
\G\d
$&$'¶$`,$&

```

Create copies of the line with all possible proper prefixes of the first number on the line.

```
^.+¶

```

If there were any such prefixes, delete the original line.

```
+%)`

```

Repeat until no more prefixes can be generated.

```
m`^,|\b0+\B

```

Remove the leading separator and also leading zeros of any numbers.

```
O`
m`^(.+)(¶\1)+$
$1

```

Sort and deduplicate the results.

For the Retina 1 port, the biggest saving comes from deduplication, which is basically a built-in in Retina 1. The newlines aren't included in the deduplication, so another stage is needed to filter out blank lines, but it's still a saving of 14 bytes. Another 3 bytes can be saved by using `$"` which is a shorthand for `$'¶$``. I also tried using an `L` stage to avoid leaving the original line but then a conditional is required to end the loop which means that the byte count ends up unchanged.
> 3 votes

# Answer
# Python 3, 81 bytes

```
f=lambda g:{(int(g),)}|{b+(int(g[i:]),)for i in range(1,len(g))for b in f(g[:i])}

```

Try it online!
> 3 votes

# Answer
# Japt, 18 bytes

```
ã
cU à f_¬¥NÃ®mnÃâ

```

Try it

* Saved 1 thanks to @Shaggy !

```
    ã                  - substrings of input
      cUã)             - concatenated to substrings of input(repeated)
          à            - combinations
            f_¬¥N      - take combinatons if == input when joined
           ®mn  - deduplicates ( @Shaggy ® )
                    Ãâ    - implicitly returns unique elements

```
> 2 votes

# Answer
# Charcoal, 47 bytes

```
⊞υ⟦Ｓ⟧≔⟦⟧θＦυ«≔⊟ιη¿ηＦＬη⊞υ⁺ι⟦Ｉ…η⊕κ✂η⊕κ⟧¿¬№θι⊞θι»Ｉθ

```

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

```
⊞υ⟦Ｓ⟧

```

Start a breadth first search with the input number.

```
≔⟦⟧θ

```

Start with no results.

```
Ｆυ«

```

Loop over the candidates.

```
≔⊟ιη

```

Get the current suffix.

```
¿ηＦＬη

```

If the suffix is not empty then loop over all of its proper suffixes...

```
⊞υ⁺ι⟦Ｉ…η⊕κ✂η⊕κ⟧

```

... push the next candidate, which is the prefixes so far, the current prefix cast to integer, and the current suffix.

```
¿¬№θι⊞θι

```

But if it is empty and the resulting split is unique then push it to the results.

```
»Ｉθ

```

Print all the results. (This uses Charcoal's default output, whereby lists are double-spaced as their entries are printed on separate lines.)
> 2 votes

# Answer
# , 36 29 bytes

```
[:~.]<@("./.~+/\)"#.2#:@i.@^#

```

Try it online!

*-7 bytes thank to xash!*

Explanation later.
> 2 votes

# Answer
# Raku, 38 bytes

```
{unique +<<m:ex/^(.+)+$/>>[0],:as(~*)}

```

Try it online!
> 2 votes

# Answer
# Mathematica 106 bytes

```
Union@Table[FromDigits/@#~TakeList~i,{i,Join@@Permutations/@IntegerPartitions@Length@#}]&@IntegerDigits@#&

```

Try it online
> 2 votes

# Answer
# JavaScript (ES6), 88 bytes

Expects a string. Returns a Set of comma-separated strings.

```
f=([c,...a],o='',S=new Set)=>c?f(a,o+c,o?f(a,o+[,c],S):S):S.add(o.replace(/\d+/g,n=>+n))

```

Try it online!

### How?

It's important to note that `Set.prototype.add()` returns the set itself. And because the recursion always ends with `S.add(...)`, each call to `f` returns `S`.

### Commented

*NB: alternate slash symbols used in the regular expression to prevent the syntax highlighting from being broken*

```
f = (                // f is a recursive function taking:
  [c,                //   c   = next digit character
      ...a],         //   a[] = array of remaining digits
  o = '',            //   o   = output string
  S = new Set        //   S   = set of solutions
) =>                 //
  c ?                // if c is defined:
    f(               //   do a recursive call:
      a,             //     pass a[]
      o + c,         //     append c to o
      o ?            //     if o is non-empty:
        f(           //       do another recursive call
          a,         //         pass a[]
          o + [, c], //         append a comma followed by c to o
          S          //         pass S
        )            //       end of recursive call (returns S)
      :              //     else:
        S            //       just pass S as the 3rd argument
    )                //   end of recursive call (returns S)
  :                  // else:
    S.add(           //   add to the set S:
      o.replace(     //     the string o with ...
        ∕\d+∕g,      //       ... all numeric strings
        n => +n      //       coerced to integers to remove leading zeros
                     //       (and coerced back to strings)
      )              //     end of replace()
    )                //   end of add() (returns S)

```
> 2 votes

# Answer
# K (ngn/k), ~~32~~ 25 bytes

-4 bytes from not de-listing first result

-3 bytes from @ngn's improvements

```
{?.''(&'+1,!1_2&$x)_\:$x}

```

Try it online!

* `&'+1,!1_2&$x` returns the subset of the (power set of indices of the input) that begin with 0. The original power set index generation code was taken from @JohnE's answer on a different question, and includes improvements from @ngn's comments on this answer.
* `(...)_\:$x` `cut`s the stringified-input on each of the specified indices
* `?.''` converts each slice to integers, taking the `distinct` elements
> 2 votes

# Answer
# Ruby, 127 bytes

```
->(n,f=->(s){s.size.times.map{|i|([f.(s[0...i])].flatten(i>1?1:0).map{|j|[j.flatten<<s[i..-1]]})}.flatten(2)}){f.(n.to_i.to_s)}

```

Try it online!

**Explanation**

1. first lambda takes a number and a function as parameters
2. second parameter defaults to the lambda that computes the partition
3. the second lambda is called with the number stripped of leading zeroes
4. computation starts with a map for each split point in the number
5. recursively call lambda for the substring before the split point
6. append the substring after the split point to each resulting partition array

judicious array creation \[\] and applications of flatten in the code ensure exactly one level of array nesting in the result.
> 1 votes

# Answer
# Perl 5, 87 bytes

```
sub f{$_=pop;/(.)(.+)/?do{my$s=$1;map s/@_\d+/0+$&/ger,map{("$s $_",$s.$_)}f(1,$2)}:$_}

```

Try it online!

Ungolfed:

```
sub f {
  $_ = pop;                     # set $_ to input (last arg)
  if( /(.)(.+)/ ) {             # if input two or more digits, split
                                # into start digit and rest
    my $s = $1;                 # store start digit
    return
      map s/@_\d+/0+$&/ger,     # no @_ => 1st recursive level => trim leading 0s
                                # 0+$& means int(digits matched)
      map { ("$s $_", "$s$_") } # return "start+space+rest" and "start+rest"...
      f(1, $2)                  # ...for every result of rest
                                # (1 marks recursive level below first)
  }
  else {
    return $_                   # if just one digit, return that
  }
}

```

# Perl 5 -MList::Util, 68 bytes

...which is further golfed from the answer from @xcali

```
say uniq map"@F
"=~s| |$_/=2;','x($_%2)|reg=~s|\d+|$&*1|reg,1..2**@F

```

Try it online!
> 1 votes

# Answer
# Husk, 14 bytes

```
ummdf(=d¹Σ)ṖQd

```

Try it online!
> 1 votes

# Answer
# Pip `-p`, 44 bytes

```
YaUQ({(a|>0)RMx}M({y=aRMs?a^sx}M(PMaJs)))RMx

```

Probably my craziest Pip answer. There's definitely a shorter method, but I decided to roll with this.

-p pretty prints the final list for easier verification. Takes a very long time with 5 digit numbers.

Try it online!

## Explanation

```
YaUQ({(a|>0)RMx}M({y=aRMs?a^sx}M(PMaJs)))RMx a → first command line argument
Ya                                           Yank a into variable y
                                 PMaJs       join each element of a with a space, get permutations
                  {y=aRMs?a^sx}M             filter out the permutations that are not in order
     {(a|>0)RMx}M                            Strip leading zeros and empty strings in each split
                                         RMx remove empty strings from the whole result
  UQ                                         print the unique splits

```
> 0 votes

---
Tags: code-golf, set-partitions
---


title: Zero the byte (eventually)

text:
# Question
Title: Zero the byte (eventually)
Given an infinite arithmetically-progressive¹ sequence, compute the minimum length of a prefix with a product divisible by 2^8.

## Sample cases & reference implementation

Here is a reference implementation that I wrote in Io.

```
  1, 1 -> 10
  2, 4 -> 8
  3, 5 -> 10
  2, 6 -> 5
  7, 5 -> 6
  4, 1 -> 9
 10, 9 -> 7
256, 9 -> 1

```

## Spec

* The input will always be provided in a way such that it won't take forever to zero the accumulator.
* ¹ An arithmetically progressive infinite list can be generated by a constant step each time starting from an initial number.
    + For the infinite list input, you're are allowed to simply take the initial number and the step of the infinite list.
* There are only going to be integers in this sequence.

# Examples
* 1\*2\*3\*4\*5\*6\*7\*8\*9\*10 = 3,628,800 = 14,175\*256
* 2\*6\*10\*14\*18\*22\*26\*30 = 518,918,400 = 2,027,025 * 256

# Answer
# Husk, 9 bytes

```
V¦256G*¡+

```

Try it online! Takes first the step, then the initial value.

# Explanation

```
V¦256G*¡+  Implicit arguments: step and start
        +  Function that adds step.
       ¡   Iterate on start to form infinite list [start, start+step, start+2*step..]
     G     Cumulative reduce by
      *    multiplication.
V          1-based index of first value that
 ¦256      is divisible by 256.

```
> 5 votes

# Answer
# Python 2, 39 bytes

```
f=lambda a,d,p=1:p%256and-~f(a+d,d,p*a)

```

Try it online!

Tracks the product `p` of the arithmetic progression until it's divisible by 256.
> 9 votes

# Answer
# APL (Dyalog), 24 bytes

```
{0=256|×/⍵:≢⍵⋄⍺∇⍵,⍨⊃⍺+⍵}

```

Try it online!

is the the sequence (starting with the first item),  the step.

---

`0=256|×/⍵` \- if the product is divisible by 256, `≢⍵` return the length.

`⍺∇⍵` \- else, recurse, `,⍨⊃⍺+⍵` \- and append a new term to the sequence.
> 6 votes

# Answer
## INTERCAL, 471 445 443 bytes

I could have done anything else but I've always wanted to try this language out...

```
DOWRITEIN:5DOWRITEIN:6DO:8<-:5DO:7<-#1PLEASECOMEFROM(9)DO:1<-:6DO:2<-:7DO(1549)NEXTDO:1<-:3DO:2<-:5DO(1509)NEXTDO:1<-:3DO:2<-:8PLEASEDO(1549)NEXTDO:8<-:3DO:1<-:8DO:2<-#256PLEASEDO(1550)NEXTDO:4<-:1DO:1<-:3PLEASEDO(1540)NEXTDO:1<-:4DO:2<-:3PLEASEDO(1510)NEXTDO:1<-:3DO:2<-:3PLEASEDO(1550)NEXTDO:1<-#1DO:2<-:3DO(1509)NEXTDO(1)NEXTDO:1<-:7DO:2<-#1DO(1509)NEXT(9)DO:7<-:3(1)DO(2)NEXTPLEASEFORGET#1DO:1<-:7DO:2<-#1DO(1509)NEXTDO:7<-:3PLEASEREADOUT:7PLEASEGIVEUP(2)DORESUME:3

```

Inspired by Noodle9's C answer.

Formatted version: Try it online!

Explaination based on blocks, blocks seperated by double line breaks.
(if magic) marks code for an If-structure I've found in the manual.

```
Setup vars and input
 - :5 = start value
 - :6 = step size
 - :7 = step count
 - :8 = current cumultative product

Label (99)

:8 *= (:7 * :6) + :5

Calculate :8 % 256

Divide result by itself and add one.
If the result is 0, the division subroutine returns 0, else it returns 1.
We need to add one becase label (0) is invalid.

Store result in :10

Increment :7, store result in :3

(if magic)
If :10 is 2, put :3 in :7 and jump to (99)
(if magic)
If :10 is 1, print :3 and terminate
(if magic)

```

If someone can get rid of that double addition, I'd be *very* grateful.

### EDIT

Found out a way to get rid of it. Also updated the explaination and fixed some formatting.

-2 by using a shorter label
> 6 votes

# Answer
# Raku, ~~38~~ 31 bytes

```
{+($^a,*+$^b...{[*](@_)%%256})}

```

Try it online!

Does pretty much exactly what the description asks for. Generates the arithmetic sequence until the product of elements is divisible by 256 and returns the length of the list.
> 5 votes

# Answer
# JavaScript (ES6), 33 bytes

Takes input as `(step)(init)`.

```
s=>g=(i,p=1)=>p&&g(i+s,p*i%256)+1

```

Try it online!
> 5 votes

# Answer
# , 30 29 bytes

```
[:#(],(+{:))^:(0<256|*/@])^:_

```

Try it online!

*-1 byte thanks to Traws*

Straightforward conversion of the algorithm into J.
> 4 votes

# Answer
# MATL, 17 bytes

```
ha`&G@q*+*8W\t}x@

```

Try it online! Or verify all test cases.

### Explanation

This uses the fact that `mod(a*b, N)` equals `mod(mod(a, N)*b, N)`.

```
h       % Take the two inputs (implicitly): a (initial term), s (step).
        % Concatenate them into a row vector
a       % Any: true (or 1) if there is any nonzero entry. Gives true
`       % Do...while
  &G    %   Push the two inputs again: a, s
  @q    %   Push n-1, where n is the 1-based iteration index
  *     %   Multiply: gives s*(n-1)
  +     %   Add: gives a+s(n-1), which is the n-th term of the sequence
  *     %   Multiply this by the previous result (which was initialized to 1)
  8W    %   Push 8, exponential with base 2: gives 256
  \     %   Modulus
  t     %   Duplicate. This will be used as loop exit condition
}       % Finally (execute this on loop exit)
  x     %   Delete latest result (which is necessarily 0)
  @     %   Push current n. This is the solution
        % End (implicitly). A new iteration is executed if the top of the
        % stack is nonzero
        % Display (implicitly)

```
> 4 votes

# Answer
# brainfuck, ~~80~~ 71 bytes

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

```

Try it online!

Takes two byte values as input (step, initial), output a byte value.

Commented code (Memory layout: `count step init init' prod prod' prod''`)

This language has a slight advantage for this challenge because its cell size value (in the TIO implementation) is 8-bit.

This program has to use ~5 variables, so some other rearrangement might produce a shorter program.

Use a scrolling tape to reduce back-and-forth copying. (after each iteration of the outermost loop the pointer is moved 1 unit to the right)
> 4 votes

# Answer
# K (ngn/k), ~~27~~ ~~25~~  ~~19~~ 18 bytes

-2 bytes thanks to Traws!

-6 bytes thanks to ngn and Traws!

-1 more byte thanks to ngn!

```
{#(`c$*/)(x,y+)/x}

```

Try it online!
> 3 votes

# Answer
# Factor, 105 bytes

```
: f ( n n -- n ) swap 1array
[ dup product 256 mod 0 = ]
[ 2dup last + 1array append ] until
length nip ;

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), 19 bytes

```
{0⍳⍨256|×\⍵+⍺×0,⍳9}

```

Try it online!

Uses `⎕IO←1` and the fact that the highest possible output is `10`.
> 2 votes

# Answer
# Retina 0.8.2, 70 bytes

```
\d+
$*
^
1,
{`^1.*
$&#
\G1(?=1*,(1+))
$1
1{256}

}`1,(1+(,1+))
1$2$1
#

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
^
1,

```

Insert an accumulator.

```
^1.*
$&#

```

Increment the result if the accumulator is not zero.

```
\G1(?=1*,(1+))
$1

```

Multiply the accumulator by the current term.

```
1{256}

```

Reduce modulo 256.

```
1,(1+(,1+))
1$2$1

```

If the accumulator is not zero then calculate the next term. (The conditional is necessary in order for the loop to terminate once the accumulator reaches zero.)

```
{`
}`

```

Repeat the loop until the buffer stops changing. This will happen when the accumulator becomes zero, i.e. the product is a multiple of 256.

```
#

```

Convert the result to decimal.
> 1 votes

# Answer
# Charcoal, 24 bytes

```
⊞υＮＮηＷ﹪ΠＥυΣ…υ⊕λ²⁵⁶⊞υηＩＬυ

```

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

```
⊞υＮ

```

Input the initial number and push it to the predefined empty list.

```
Ｎη

```

Input the step.

```
Ｗ﹪ΠＥυΣ…υ⊕λ²⁵⁶

```

Repeat while the product of the sums of all the nontrivial prefixes of the list is not a multiple of 256...

```
⊞υη

```

... push the step to the list.

```
ＩＬυ

```

Output the length of the list.
> 1 votes

# Answer
# C (gcc), ~~46~~ 44 bytes

Saved 2 bytes thanks to Arnauld!!!

```
c;f(a,d){c=0;for(char p=1;p*=a+d*c++;);d=c;}

```

Try it online!

**Commented code**

```
c;f(a,d){
 c=0;           /* initialise counter */
 for(char p=1   /* initialise 8-bit product */
   p            /* loop until last 8-bits of product are 0 */
    *=a+d*      /* and multiply product by next element in series */
       c++;);   /* and bump counter */
 d=c;           /* return counter */
}

```
> 1 votes

# Answer
# Brachylog, 23 bytes

```
≜;.{|⟨+≡t⟩ⁱ}ᶠ⁽hᵐ×%₂₅₆0∧

```

Try it online!

This took embarrassingly long to write, but at least I was able to shave two bytes off `∧.≜&{|⟨+≡t⟩ⁱ}ᶠ↖.hᵐ×%₂₅₆0∧` once I got that far. Takes `[first term, step]` through the output variable and outputs the prefix length through the input variable.
> 1 votes

# Answer
# Jelly, 16 bytes

```
1µ⁴ẋ³1¦ÄP256ḍµ1#

```

A full program accepting the initial value and the delta which prints the result.

**Try it online!**

### How?

```
1µ⁴ẋ³1¦ÄP256ḍµ1# - Main Link: initial, delta
1                - set the left value (say n) to 1
              1# - increment n finding the first 1 such n which is truthy under:
 µ           µ   -   the monadic chain - i.e. f(n):
  ⁴              -     program argument 4 (delta)
   ẋ             -     repeated (n) times
      ¦          -     sparse application...
     1           -     ...to indices: 1
    ³            -     ...what: program argument 3 (initial)
       Ä         -     cumulative sums
        P        -     product
         256     -     literal 256
            ḍ    -     divides (the product)?
                 - implicit print (a list with a single element prints that element)

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
(t=0;s=#;k=#2;While[Mod[s##&@@Array[s+k#&,t++],256]!=0];t)&

```

Try it online!
> 1 votes

# Answer
# , 43 bytes

```
function(i,s)match(0,cumprod(i+0:9*s)%%256)

```

Try it online!

Outputs 'NA' if sequence goes to infinity without ever being a multiple of 256.

Calculates products of sequences up to length 10. Why is this enough?

If step is an odd number, then the successive factors that make up each element of the sequence will alternate between odd and even, so 10 would be enough to ensure that there are 5 even numbers multiplied together (so the product is a multiple of 2^5). But, the first 5 even numbers are also certain to include at least one multiple-of-4 (every second even number) and one multiple-of-8 (every fourth even number), so in fact their product is certain to be a multiple of 2^8 = 256.

If the step is even and the initial number is even, then (for similar reasons) only a maximum of 4 steps are needed.

If the step is even and the initial number is odd, then all the factors will be odd, so the product will always be odd and the sequence will go to infinity without ever being a multiple of 256.

So, if we didn't find a multiple-of-256 by the 10th element of the sequence, there won't be one, and we can just output the 'infinity' response.

I think.
> 1 votes

# Answer
# 05AB1E, 12 bytes

```
∞<*+ηPÅΔ₁Ö}>

```

Takes the inputs in reversed order, so `step` before `start`.

Try it online or verify all test cases.

**Explanation:**

```
∞             # Push an infinite positive list: [1,2,3,...]
 <            # Decrease each by 1 to let it start at 0: [0,1,2,...]
  *           # Multiply each by the first (implicit) input (step)
   +          # Add the second (implicit) input (start)
    η         # Get all prefixes of this infinite list
     P        # Take the product of each inner prefix-list
      ÅΔ      # Find the first (0-based) index which is truthy for:
        ₁Ö    #  Where the value is divisible by 256
          }>  # After we've found this index: increase it by 1 to make it 1-based
              # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Rust, 58 bytes

```
|s,m|(|mut i,mut a|{while 0<a%256{a*=i;i+=m}(i-s)/m})(s,1)

```

Try it online!

A closure whose first argument is the first element of the sequence and whose second argument is the step.

Ungolfed with comments

```
//Initial element, step
|s,m|
  //i is initial value of s, a is accumulator
  (|mut i,mut a| {
    while 0 < a % 256 {   //while a is not divisible by 2^8
      a *= s;             //Multiply a by the current element of the sequence
      s += m              //Get the next element of the sequence by adding the step
    }
    //Subtract the initial value s to only keep increases of m, divide by m to get how many times it was increased
    (i - s) / m
  )
   (s, 1) //Call with i as s and initial value of accumulator as 1

```
> 1 votes

# Answer
# Scala, 54 bytes

```
LazyList.from(_,_).scanLeft(1)(_*_)indexWhere(_%256<1)

```

Try it in Scastie!

Explanation:

```
LazyList.from(_,_) //Creates a LazyList starting at the first parameter with a step given by the second parameter.
  .scanLeft(1)(_*_) //scanLeft is like foldLeft, but keeps each result in a list
  indexWhere(_%256<1) //Find the index where it's divisible by 256

```
> 0 votes

# Answer
# Haskell, ~~51~~ 49 bytes

```
b#s=findIndex((<1).(`mod`256))$scanl(*)1[b,b+s..]

```

Try it online!

Port of my Scala answer
> 0 votes

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


title: Operational countdown

text:
# Question
Title: Operational countdown
Given a non negative integer number \\$n\\$ output how many steps to reach zero using radicals, divisions or subtractions.

# The algorithm

* Get digits count ( \\$d\\$ ) of \\$n\\$.
* Try the following operations in order:
$$\sqrt\[d\]{n}$$ $$n/d$$ $$n-d$$
* Take the first integer result not equal to \\$n\\$. Floating point errors must be avoided !
* Repeat the process with the value obtained until you reach 0.

# Example

1500 -\> 8

```
1500 -> 4 digits , ( / ) => 375 // step 1
375 -> 3 digits , ( / ) => 125 // step 2
125 -> 3 digits , ( √ ) => 5 // step 3
5 -> 1 digits , ( - ) => 4 // step 4
4 -> 1 digits , ( - ) => 3 // step 5
3 -> 1 digits , ( - ) => 2 // step 6
2 -> 1 digits , ( - ) => 1 // step 7
1 -> 1 digits , ( - ) => 0 // step 8

```

**Input:** a non negative integer number. You don't have to handle inputs not supported by your language (obviously, abusing this is a standard loophole)

**Output:** the number of steps to reach 0

# Test cases

```
n -> steps

0 -> 0
1 -> 1
2 -> 2
4 -> 4
10 -> 6
12 -> 7
16 -> 5
64 -> 9
100 -> 19
128 -> 7
1000 -> 70
1296 -> 7
1500 -> 8
5184 -> 8
10000 -> 133
21550 -> 1000
26720 -> 100
1018080 -> 16
387420489 -> 10

```

# Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT, return it as a function result or error message/s.
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* Answers must not fail due to floating point errors.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

---

Sandbox: https://codegolf.meta.stackexchange.com/a/20518/84844

# Answer
# Brachylog, 19 16 bytes

*-3 thanks to @Unrelated String*

```
Ḋ|⟨ℕ{√₎|/|-}l⟩↰<

```

Try it online!

A recursive function. If `n ≥ 10`, the three operations are tried. For `n < 10` we need `n` steps to `0`. With this we don't have to check that `step(n) ≠ n`, as it only occurs when there is one digit.

```
Ḋ|⟨ℕ{√₎|/|-}l⟩↰<
Ḋ                if n is in 0…9, return n
 |               otherwise
  ⟨f    h   g⟩   [f(n), g(n)] h
   ℕ        l    [n, digits] and n is a natural number
    {√₎|/|-}     try (root, divide, subtract) one after the other
                 (results that are not natural numbers will
                  get filtered in the next step with ℕ)
              ↰  recurse
               < get a number that is strictly larger, thus +1

```
> 7 votes

# Answer
# , ~~77~~ ~~74~~ 73 bytes

-3 bytes thanks to Giuseppe and -1 byte thanks to MarcMush.

```
f=function(n,d=nchar(n),k=1:n)`if`(d<2,n,1+f(match(n,c(k^d,k*d,k+d))%%n))

```

Try it online!

Recursive function; avoids floating point issues. The vector `k` contains all integers from `1` to `n`. Concatenate `k^d`, `k*d` and `k+d` (yielding a vector of length `3n`) and find the position `p` of the first occurrence of `n`. Then \\$f(n)=1+f(p \mod n)\\$. The recursion is initialized by noting that \\$f(n)=n\\$ for all 1-digit integers (hence the conditioning on `d<2`).

Works for all the test cases (although `21550` could require you to increase the stack limit on some machines).
> 7 votes

# Answer
# APL (Dyalog Extended), ~~40~~ ~~36~~ 32 bytes (SBCS)

-6 thanks to ovs.

Anonymous tacit prefix function. Requires zero-based indexing (`⎕IO←0`).

```
0∘{×⍵:(1+⍺)∇⊃⍵(…⍤⊣∩√⍨,÷,-)≢⍕⍵⋄⍺}

```

Try it online!

`0∘{``}` "dfn" bound with 0 as left argument (, initial step count ― right argument, \\$n\\$ is ):

`×⍵:` if \\$n\>0\\$ (lit. "if \\$\text{sgn}(n)\\$")

`⍕⍵` stringify \\$n\\$

tally the number of characters (digits)

`⍵(``)` apply the following tacit function to that, with \\$n\\$ as left argument:

`√⍨`\\$\root d\of n\\$

`,` followed by

`÷`\\$\frac nd\\$

`,` followed by

`-`\\$n-d\\$

intersection of that and

`⍳⍤⊣`\\$\\{1,2,3,…,n-1\\}\\$

the first element

`(``)∇` recurse on that, with the following as new left argument:

`1+⍺` one plus the current step count

---

If `d←≢⍕⍵` we have the expression `⍵(⍳⍤⊣∩√⍨,÷,-)d` which could be written in traditional mathematical notation as:

$$\\{1,2,3,…,n-1\\}∩\Big\\{\root d\of n,\frac nd,n-d\Big\\}≡\Big\\{\root d\of n,\frac nd,n-d\Big\\}\setminus\\{n\\}$$
> 5 votes

# Answer
# JavaScript (ES7),  ~~73~~  68 bytes

```
f=n=>(d=(n+'').length)<2?n:1+f((k=n**(1/d)+.5|0)**d-n?n%d?n-d:n/d:k)

```

Try it online!

Or 60 bytes if floating point errors are acceptable.

### Commented

```
f = n =>                 // f is a recursive function taking the input n
  (d = (n + '').length)  // d is the number of digits in n
  < 2 ?                  //   if there's only one digit:
    n                    //     stop the recursion and return n
                         //     (because only n - 1 is valid at this point)
  :                      //   else:
    1 +                  //     increment the final result
    f(                   //     and do a recursive call:
      (                  //
        k = n ** (1 / d) //       define k as the d-th root of n
        + .5 | 0         //       rounded to the closest integer
      )                  //
      ** d - n ?         //       if k ** d is not equal to n:
        n % d ?          //         if d is not a divisor of n:
          n - d          //           use n - d
        :                //         else:
          n / d          //           use n / d
      :                  //       else:
        k                //         use k
    )                    //     end of recursive call

```
> 4 votes

# Answer
# Python 3.8, ~~112~~ \\$\cdots\\$ ~~97~~ 96 bytes

Saved ~~7~~ a whopping 15 bytes thanks to Arnauld!!!
Saved a byte thanks to Danis!!!

```
f=lambda n:n and-~f([t:=round(n**(1/(d:=len(str(n))))),n//d,t,n-d][(t**d!=n)+2*(n%d>0)|3*(d<2)])

```

Try it online!
> 4 votes

# Answer
# Julia 0.7, ~~68~~ ~~62~~ 57 bytes

inspired by Robin's answer in R

```
!n=n>0&&1+!filter(r->n∈((d=ndigits(n))r,r+d,r^d),0:n)[]

```

Try it online!
> 4 votes

# Answer
# Jelly, 19 bytes

```
*,×;+
ç€DL$œi⁸ḢµƬTL

```

Try it online!

## How it works

```
*,×;+ - Helper link. Takes two integers k and d on the left and right
*     - k * d
  ×   - k × d
 ,    - [k * d, k × d]
    + - k + d
   ;  - [k * d, k × d, k + d]

ç€DL$œi⁸ḢµƬTL - Main link. Takes n on the left
         µ    - Group the previous links into a monad f(n):
    $         -   To n:
  D           -     Cast to digits
   L          -     Length
 €            -   Over each k = 1, 2, 3, ..., n:
ç             -     Call the helper link with k on the left and the digit length on the right
       ⁸      -   n
     œi Ḣ     -   Find the index of the first triple containing n
          Ƭ   - Until reaching a fixed point, repeatedly apply f(n)

                Both 1 and 0 are fixed points of f(n)
                As Ƭ returns [n, f(n), f(f(n)), ..., 1] for n > 0
                and [0] for n = 0, 1 being a fixed point offsets the
                included n at the start. However, taking the length here
                would return 1 for n = 0 instead of 0

           T  - Find the indices of non-zero elements. As every element
                is non-zero unless n = 0, this yields [1, 2, ..., l]
                for n > 0 and [] for n = 0, where l is the output
            L - Length

```
> 3 votes

# Answer
# Retina 0.8.2, 134 bytes

```
.+
,$&,$&$*
+`,(.)*,(1*?)((?=\2+$)(?<=(?=(?<-1>(?=((1*)(?=\2\5+$)1)(\4*$))\6)+1$)\2).*|(?<-1>)(?<-1>\2)+|(?<-1>1)+)$(?(1)1)
1,$.2,$2
1

```

Try it online! Link includes faster test cases. Explanation:

```
.+
,$&,$&$*

```

Create a working area consisting of the result (initially 0), the input, and the input converted to unary.

```
+`

```

Repeat until the input has been reduced to zero ...

```
,(.)*,(1*?)(

```

count the number of digits `d` in the value `n`, and then find the smallest value that satisfies one of ...

```
(?=\2+$)(?<=(?=(?<-1>(?=((1*)(?=\2\5+$)1)(\4*$))\6)+1$)\2).*|

```

... its `d`th power is `n`, or ...

```
(?<-1>)(?<-1>\2)+|

```

... its product with `d` is `n`, or ...

```
(?<-1>1)+)

```

... its sum with `d` is `n`, and ...

```
$(?(1)1)

```

ensure that it was in fact `d` and not some smaller integer, and ...

```
1,$.2,$2

```

increment the output and replace `n` and its unary with the result.

```
1

```

Convert the output to decimal.
> 2 votes

# Answer
# Charcoal, ~~34~~ 31 bytes

```
⊞υＮＷ⌊υ⊞υ⌊Φι№⟦ＸκＬι×κＬι⁺κＬι⟧ιＩ⊖Ｌυ

```

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

```
⊞υＮ

```

Input `n` and push it to the predefined empty list.

```
Ｗ⌊υ

```

Repeat until the list contains zero.

```
⊞υ⌊Φι№⟦ＸκＬι×κＬι⁺κＬι⟧ι

```

For all integers less than `n`, take the `d`th power and the product and sum with `d`, and push the lowest integer where one of the results is `n` to the list.

```
Ｉ⊖Ｌυ

```

Output the final number of iterations, which is one less than the length of the list.
> 2 votes

# Answer
# 05AB1E, 39 bytes

```
[D0Q#DUgVXYzmXY/XY-).Δ©D2.òsòQ®XÊ&}ò¼}¾

```

Try it online!

Why can't you try it online? Because there's a bug with the TIO where raising numbers to floats which are actually whole numbers runs infinitely.

## Explained

```
[D0Q#DUgVXYzmXY/XY-).Δ©D2.òsòQ®XÊ&}ò¼}¾
[                                           # Start an infinite loop with the input already on the stack.
 D0Q#                                       #   End the loop if the result from two lines above is 0
     DU                                     #   Store the top of the stack in variable X
       gV                                   #   And store its length in variable Y
         XYzm                               #   Push the Yth root of X
             XY/                            #   Push X / Y
                XY-                         #   Push X - Y
                   )                        #   And wrap that into a list
                    .Δ                      #   From that list, get the first item where:
                      ©D2.ò                 #       The item, when rounded to 2 decimal places
                           sòQ              #       Equals the item rounded to the nearest integer
                              ®XÊ&          #       And where it doesn't equal variable X
                                  }         #
                                   ò        #   Round that result to the nearest integer
                                    ¼}      #   Increment the counter variable, which keeps track of how many iterations we've gone through
                                      ¾     # Push the counter variable and implicitly print

```
> 2 votes

# Answer
# C (gcc) with `-lm`, ~~121~~ 120 bytes

* -1 thanks to ceilingcat

To get the number of digits, I used the floor of `log10+1` of the value. Each iteration runs through the operations until the result is an integer that doesn't match the current value; when the result is `0` the number of steps is returned.

```
f(i,c,o,l){float a;for(c=0;i;i=a,c++)for(o=0,l=log10(i)+1,a=.1;fmod(a,1)||a==i;)a=o++?o>2?i-l:(i+0.)/l:pow(i,1./l);i=c;}

```

Try it online!
> 1 votes

# Answer
# Stax, 47 bytes

```
Çƒô▄↑"è≈■É↑├µxαêöV*┐┘ÆwaYM╙¿9⌠╛o-ºtΓ⌡╔ΔZj♦○Qæº`

```

Run and debug it

Accomodates for floating point innacuracies.

## Explanation

`,` put input on main stack

`{...w` loop till falsy value

`X` store current interation in register X

`c$%` get number length

`bbbb` duplicate number 4 times

`u#aa` get floating point root

`|N` get integer root

`-Au<{sd}{d}?~` if difference \< 0.1, take the integer root otherwise float

`/~` get n/d

`-~` get n-d

`Lr` convert all those to array, reverse

`{...}j` find first value which satisfies:

`cx=!` not equal to current iteration

`_c1u*@=*` and not equal to its floor

`ciYd` save iteration index in Y

`y^` output final index
> 1 votes

# Answer
# Add++, 82 bytes

```
D,f,@,BDbLddARdV$€*$G$€+@G$€Ω^BcB]A€ΩedbLRz£*bUBZ@B]A$þ=bU
x:?
Wx,`x,$f>x,`y,+1
Oy

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Triangulating Angles

text:
# Question
Title: Triangulating Angles
**Prompt:**

You are given two sets of XY coordinates along with two angles (all are floats): `X1 Y1 A1 X2 Y2 A2`. The angles are relative to world coordinates: 0 being straight up or north and going clockwise.

Your program or function has to return a set of two floats of the XY coordinates the two angles cross at.

**Example:**

In this case, the resulting point is between the two inputted points. For the case `100 500 50 300 600 80` (using degrees), the correct answer is `198 582`. Online representation here

Other examples of edge cases: `1 1 45 4 4 45` returns `NULL` `1 4 45 2 4 45` returns `NULL` https://i.stack.imgur.com/vlmQO.jpg

**Rules:**

* Angles can be in radians or in degrees
* The program should have a separate answer if there is not a valid answer: if the two lines are parallel (zero solutions) or the same line (infinitely many solutions)
* The value returned can be represented in any form: `198;582`, `198 582` and `198_582` are all valid
* The answer can be rounded to a full number
* This is

# Answer
# JavaScript (ES6), 76 bytes

Expects the angles in radians. Returns either `[x,y]` or `0` if the lines are parallel or coincident.

```
(x,y,a,X,Y,A)=>a-A&&[(m=(t=Math.tan)(a))*(X-=(x-=m*y)+t(A)*Y,X/=m-t(A))+x,X]

```

Try it online!

Or **71 bytes** if we can just return `[Infinity,Infinity]` for invalid inputs.
> 3 votes

# Answer
# C (gcc), <sup>~~131~~ \\$\cdots\\$ ~~106~~</sup> 104 bytes

Saved 9 bytes thanks to Arnauld!!!
Saved ~~4~~ a whopping 15 bytes thanks to ceilingcat!!!

```
#define f(x,y,a,X,Y,A)float M=tan(A),m=tan(a),n;printf(a-A?"%f,%f":"0",(n-Y)*M+X,n=(M*Y-m*y-X+x)/(M-m));

```

Try it online!

Either prints the intersection as `%f,%f` or `0` if the lines are parallel or coincident.
> 1 votes

---
Tags: code-golf, geometry
---


# Question
Title: Sum of first row and column, then second row and column ... and so on
Take a non-empty matrix / numeric array containing positive integers as input. Return, in this order, the sums of the first row and column, then the second row and column and continue until there aren't any more rows or columns.

Suppose the input is:

```
2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

```

Then the output should be:

```
45, 33, 16, 17

```

Because: `2+9+1+7+10+10+2+4=45, 7+7+1+7+2+9=33, 6+4+2+4=16, 8+9=17`.

## Test cases:

Test cases are on the following format:

```
Input
---
Output

```

```
5
---
5
..........

1  4
----
5
..........

7
2
---
9
..........

 8    3    7   10    3    7   10    1
10    7    5    8    4    3    3    1
 1    6    4    1    3    6   10    1
 2    3    8    2    8    3    4    1
---
62   40   33   18
..........

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

7   10    1
4    4    2
6    3    4
1    4   10
5    7    6
---
34   20   20

```

As arrays:

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

```

---

This is so the shortest solution in each language wins.

# Answer
> 10 votes
# MATL, 16 bytes

```
&n:w:!XlX:GX:1XQ

```

Try it online! Or verify all test cases.

### Explanation

Consider, as an example, the input

```
2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

```

The code `&n:w:!Xl` builds the column vector `[1; 2; 3; 4]` and the row vector `[1 2 3 4 5]`. Then `Xl` computes the minimum element-wise with broadcast, which gives the matrix

```
1 1 1 1 1
1 2 2 2 2
1 2 3 3 3
1 2 3 4 4

```

`X:` linearizes this matrix (in column-major order) into the column vector `[1; 1; 1; 1; 1; 2; 2; ... ; 4]`. This vector and the linearized input matrix, obtained as `GX:`, are passed as inputs to the `accumarray(... @sum)` function, or `1XQ`. This computes the sum of the second input grouped by values of the first input.

# Answer
> 7 votes
# Jelly, 3 bytes

```
ŒDS

```

Try it online!

## How it works

```
ŒDS

ŒD   diagonals
  S  vectorized sum

```

# Answer
> 5 votes
# CJam, ~~23~~ 18 bytes

```
{[{(:+\z}h;]2/::+}

```

Anonymous block expecting the argument on the stack and leaving the result on the stack.

Try it online!

### Explanation

```
[      e# Begin working in an array.
 {     e#  Do:
  (:+  e#   Remove the first row of the matrix and sum it.
  \z   e#   Bring the matrix back to the top and transpose it.
 }h    e#  While the matrix is non-empty.
 ;     e#  Discard the remaining empty matrix.
]      e# Close the array.
2/     e# Split it into consecutive pairs of elements (possibly with a singleton on the end).
::+    e# Sum each pair.

```

# Answer
> 5 votes
# 05AB1E, ~~14~~ 11 bytes

```
[ćOˆøŽ]¯2ôO

```

Try it online!

**Explanation**

```
[   Ž ]       # loop until stack is empty
 ć            # extract the head
  Oˆ          # sum and add to global list
     ø        # transpose
       ¯      # push global list
        2ô    # split into pairs
          O   # sum each pair

```

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

```
a=>a.map((b,y)=>b.map((c,x)=>r[x=x<y?x:y]=~~r[x]+c),r=[])&&r

```

Naive solution, may be a better way.

# Answer
> 4 votes
# oK, ~~19~~ 18 bytes

-1 byte thanks to coltim.

```
1_--':+//'(1_+1_)\

```

Try it online!

Explanation:

```
          (1_+1_)   /a function that strips the top and leftmost rows of a matrix
                 \  /apply this function as many times as possible,
                    /    saving each result as one element of a list
      +//'          /for each result, get the sum of all numbers
  --':              /subtract every right value from every left value
1_                  /remove the extra 0

```

# Answer
> 4 votes
## Haskell, ~~50~~ 49 bytes

```
f(a@(_:_):b)=sum(a++map(!!0)b):f(tail<$>b)
f _=[]

```

Try it online!

If there's at least one row with at least one element, the result is the sum of the first row and the heads of all other rows followed by a recursive call with the tails of all other rows. In all other cases, the result is the empty list.

Edit: Ørjan Johansen saved a byte. Thanks!

# Answer
> 4 votes
# Octave, ~~64~~ 52 bytes

*Thanks to @StewieGriffin for saving 1 byte!*

```
@(x)accumarray(min((1:size(x))',1:rows(x'))(:),x(:))

```

This defines an anonymous function.

Try it online!

### Explanation

The code is similar to my MATL answer (see explanation there).

Two bytes have been saved using `1:size(x)` instead of `1:size(x,1)`, exploiting the fact that `1:[a b]` behaves the same as `1:a`. Also, one byte has been saved using `1:rows(x')` instead of `1:size(x,2)`, thanks to Stewie.

# Answer
> 4 votes
# Octave, ~~63~~ 60 bytes

```
@(A)(@(L)sum(triu(A,1)')(L)+sum(tril(A))(L))(1:min(size(A)))

```

Try it online!

The answer for this matrix:

```
2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

```

is the vector of row sums of its upper triangular part:

```
0   10   10    2    4
0    0    7    2    9
0    0    0    2    4
0    0    0    0    9

```

plus the vector of column sums of its lower triangular part:

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

```

which is precisely what my answer is computing.

# Answer
> 4 votes
## Mathematica, 60 bytes

*Inspired by Luis Mendo's MATL answer.*

```
Pick[#,Min~Array~d,n]~Total~2~Table~{n,Min[d=Dimensions@#]}&

```

Explanation: `Min~Array~Dimensions@#` constructs a matrix like the following:

```
1 1 1 1 1
1 2 2 2 2
1 2 3 3 3
1 2 3 4 4

```

Then `Pick[#,...,n]~Total~2` picks out the entries of the input matrix corresponding to the number `n` in the weird matrix above, and sums them. Finally `...~Table~{n,Min[d=Dimensions@#]}` iterates over `n`.

This is 1 byte shorter than the naïve approach:

```
{#[[n,n;;]],#[[n+1;;,n]]}~Total~2~Table~{n,Min@Dimensions@#}&

```

# Answer
> 4 votes
# , ~~63~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes

*Edit: -4 bytes, and then -2, and then -1 more, thanks to Robin Ryder*

```
function(m,`+`=sum)while(+m)show(m+-{m=m[-1,-1,drop=F]})

```

Try it online!

Repeatedly removes the first row & column (using negative indexing: `m[-1,-1]` is `m` without the first row & column), prints the difference between the sum of `m` and this, and keeps going if there's anything left.

is very well-suited to this type of vectorized matrix operation, so this approach comes-out significantly shorter than a looping approach.

# Answer
> 3 votes
## Julia, 62 bytes

```
f=x->1∈size(x)?sum(x):(n=f(x[2:end,2:end]);[sum(x)-sum(n);n])

```

Works recursively by summing up the whole matrix and then subtracting off the sum of the next block. Probably not the most effective approach, but nicely intuitive.

# Answer
> 3 votes
# 05AB1E, 16 bytes

```
[ćOsø.g<NQ#])2ôO

```

Try it online! or Try all tests

```
[                # Start loop
 ć               # Extract first element
  O              # Sum
   sø            # Transpose the input array (without the first N rows and columns)
     .g<NQ       # Push if (stack height - 1 == loop count)
          #]     # If they were equal break
            )2ô  # Break stack into chunks of 2
               O # Sum the chunks

```

# Answer
> 2 votes
# Vim, ~~66~~, 52 bytes

```
qq^f j<C-v>}dkV}Jo<esc>p@qq@q:%s/\v> +</+/g|%norm C<C-v><C-r>=<C-v><C-r>"<C-v><cr><cr>

```

Try it online!

The wrong tool for the job...

# Answer
> 2 votes
# Perl 6, ~~63~~ 55 bytes

~~`{($_ Z [Z] $_).kv.map(->\a,\b{b.flatmap(*[a..*]).sum -b[0;a]})}`~~

```
{($_ Z [Z] .skip).kv.map({$^b.flatmap(*[$^a..*]).sum})}

```
* `$_` is the matrix input to the anonymous function
* `.skip` is the input matrix with its first row removed
* `[Z] .skip` is the transpose of the input matrix with its first row removed; that is, the transpose without its first column
* `$_ Z [Z] .skip` zips the input matrix with its transpose-sans-first-column, producing a list `((first-row, first-column-sans-first-element), (second-row, second-column-sans-first-element), ...)`
* `.kv` prefixes each pair with its index
* `map({...})` maps over the the pairs, using a function which takes its first argument (the index) in `$^a` and its second (the row/column pair) in `$^b`
* `$^b.flatmap(*[$^a..*]).sum` strips off the first `$^a` elements of each row/column pair, then sums all the remaining elements

After some thought I realized that stripping off the first column of the transpose before zipping was equivalent to subtracting the doubly-contributing diagonal elements, as in my first solution. That let me delete that subtraction, and using each argument to the mapping function only once made the `{...$^a...$^b...}` method of passing arguments to an anonymous function more efficient than the original `-> \a, \b {...a...b...}`.

# Answer
> 2 votes
# Java 10, ~~248~~ ~~245~~ ~~227~~ ~~223~~ ~~219~~ 218 bytes

```
a->{int l=a.length,L=a[0].length,b[][]=new int[l][L],i,j,x=0,s;for(;++x<l|x<L;)for(i=l;i-->x;)for(j=L;j-->x;)b[i][j]=x;var r="";for(;x-->0;r=s>0?s+" "+r:r)for(s=0,i=l*L;i-->0;)s+=b[i/L][i%L]==x?a[i/L][i%L]:0;return r;}

```

-8 bytes thanks to *@ceilingcat*

Try it online.

**General explanation:**

Let's say the input array has dimensions of 4x6. The first part of the code will create a temp matrix and fills it as follows:

```
// 1. Fill the entire array with 0:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

// 2. Overwrite the inner part with 1 (excluding the first row & column):
0 0 0 0 0 0
0 1 1 1 1 1
0 1 1 1 1 1
0 1 1 1 1 1

// #. Etc. until we are left with this:
0 0 0 0 0 0
0 1 1 1 1 1
0 1 2 2 2 2
0 1 2 3 3 3

```

And in the second part of the code it will loop over this temp matrix, and sums all values of the input-matrix for each of the distinct numbers in the temp matrix.

**Explanation of the code:**

```
a->{                       // Method with int-matrix parameter and String return-type
  int l=a.length,          //  Amount of rows
      L=a[0].length,       //  Amount of columns
      b[][]=new int[l][L], //  New temp matrix to fill as explained above
      i,j,x=0,s;           //  Some temp integers

                           //This is the first part of the code mentioned above:
  for(;++x<l|x<L;)         //  Loop `x` over the rows or columns (whichever is larger):
    for(i=l;i-->x;)        //   Inner loop over the rows:
      for(j=L;j-->x;)      //    Inner loop over the cells of this row:
        b[i][j]=x;         //     Set the value of the current cell to `x`

                           //This is the second part of the code mentioned above:
  var r="";                //  Result-String, starting empty
  for(;x-->0               //  Loop over the unique numbers in the temp matrix:
      ;                    //     After every iteration:
       r=s>0?s+" "+r:r)    //    If the sum is larger than 0: append it
    for(s=0,               //   Reset the sum to 0
        i=l*L;i-->0;)      //   Inner loop over the cells:
      s+=b[i/L][i%L]==x?   //    If the current cell of the temp-matrix contains `x`:
          a[i/L][i%L]:0;   //     Add the input's value at this position to the sum
  return r;}               //  Return the result-String

```

# Answer
> 1 votes
# Jelly, 10 bytes

```
Ḣ;Ḣ€SṄȧßS¿

```

A full program that prints the values

**Try it online!**

### How?

```
Ḣ;Ḣ€SṄȧßF¿ - Main link: list of lists a
Ḣ          - head a (pop the first row and yield it, modifying a)
  Ḣ€       - head €ach (do the same for each of the remaining rows)
 ;         - concatenate
    S      - sum (adds up the list that contains the top row and left column)
     Ṅ     - print that plus a linefeed and yield the result
         ¿ - while:
           - ... condition:
        F  -   flatten (a list of empty lists flattens to an empty list which is falsey)
           - ... body:
       ß   -   call this link with the same arity (as a monad) i.e. Main(modified a)
      ȧ    - logical and (when the sum is non-zero gets the modified a to feed back in)

```

# Answer
> 1 votes
# Python + NumPy, ~~75~~ 66 bytes

Input is a 2D numpy array.

```
lambda L:[sum(L[i,i:])+sum(L[i+1:,i])for i in range(min(L.shape))]

```

**Try it online**

*-9 bytes by Black Owl Kai*

# Answer
> 1 votes
# Python 2, 97 bytes

```
f=lambda m:[reduce(lambda x,y:x+y[i],m[i:],sum(m[i][i+1:]))for i in range(min(len(m),len(m[0])))]

```

Try it online!

# Answer
> 1 votes
# Pyth, ~~16~~ 15 bytes

```
.es+>b+1k>@CQkk

```

Takes a python-style array of arrays of numbers, returns an array of sums.

Try it!

### Explanation

```
.es+>b+1k>@CQkk
.e             Q  # Enumerated map over the implicit input (Q); indices k, rows b
           CQ     # Take the transpose
          @  k    # The kth column
         >    k   # cut off the first k elements
    >b+1k         # cut off the first k+1 elements of the rows, so (k,k) isn't counted twice
  s+              # add the row and column together and sum

```

# Answer
> 1 votes
# GNU APL 1.7, 123 bytes

Solution requires two functions: one creates a global array and the calls the second, which recursively appends the sums to that array.

```
∇f N
R←⍬
g N
R
∇
∇g N
→2+2×0∈⍴N
R←R,(+/N[1;])+(+/N[;1])-N[1;1]
g N[1↓⍳1⊃⍴N;1↓⍳2⊃⍴N]
∇

```

begins and ends the function. Both `f` and `g` take tables as arguments (essentially 2D arrays). These can be created with `X←rows cols ⍴ 1 2 3 4...`.

`R←⍬` assigns an empty vector to global variable `R`.

`g N` calls the second function with the same argument given to the first.

`⍴N` gives the dimensions of `N`; when one of the dimensions is zero, there are no more rows/columns to add up. `0∈⍴N` returns 1 if there is a zero in the dimensions. `→2+2×0∈⍴N` branches to line number 2 plus 2 times the return value of the  function: if there is no zero,  returns 0 and the function branches to line 2 (the next line). If there *is* a zero,  returns 1 and the function branches to line 4 (the end of the function, so `return` essentially).

`/` is the reduce operator. It applies the left argument, which is an operator (`+`) to every element in the list given as the right argument. `N[1;]` gives the entire first row of the table and `N[;1]` gives the first column. `(+/N[1;])+(+/N[;1])-N[1;1]` sums the first row and column and subtracts the value in the upper left corner because it gets added both in the column sum and the row sum. `R←R,...` appends the newly calculated value to the global vector `R`.

The function then calls itself (recurse until no more rows or columns). The  pick operator obtains the specified element from the list. `1⊃⍴N` gives the number of rows, `2⊃⍴N` the number of columns.  gives all numbers from 1 to the specified number. The  drop operator removes elements from the beginning of the list. If you give multiple indices when accessing elements from a table or vector (e.g. `N[1 2 3]`), APL accesses each one. Therefore, `1↓⍳1⊃⍴N` gives the indices of each row excluding the first one (`2, 3, 4, ..., N`) and `1↓⍳2⊃⍴N` gives a similar vector but for the columns. `g N[1↓⍳1⊃⍴N;1↓⍳2⊃⍴N]` calls the function again but without the first row or column.

# Answer
> 0 votes
# PHP, 76 Bytes

```
<?foreach($_GET as$k=>$v)foreach($v as$n=>$i)$r[min($k,$n)]+=$i;print_r($r);

```

Try it online!

# Answer
> 0 votes
## Mathematica, 116 bytes

```
l=Length;If[l@#==1||l@#[[1]]==1,Total@Flatten@#,Total/@Flatten/@Table[{#[[i]][[i;;]],#[[All,i]][[i+1;;]]},{i,l@#}]]&

```

Input form

> \[{{5}}\], \[{{1},{4}}\], \[{{7,2}}\] or \[{{....},{....}...{....}}\]

# Answer
> 0 votes
## Clojure, 98 bytes

```
#(vals(apply merge-with +(sorted-map)(mapcat(fn[i r](map(fn[j v]{(min i j)v})(range)r))(range)%)))

```

Iterates over the input with row and column indexes (in a very verbose manner), creates a hash-map with the minimum of `i` and `j` as the key, merges hash-maps with `+` into a sorted-map, returns values.

# Answer
> 0 votes
# R, 102 bytes

```
function(x)`for`(i,1:min(r<-nrow(x),k<-ncol(x)),{dput(sum(x[,1],x[1,-1]));x=matrix(x[-1,-1],r-i,k-i)})

```

returns an anonymous function; prints the results to the console, with a trailing newline. I probably need a different approach.

Iterates over the minimum of the rows and columns; prints the sum of `x[,1]` (the first column) and `x[1,-1]` the first row except for the first entry, then sets `x` to be a matrix equal to `x[-1,-1]` (i.e., `x` excluding its first row and column). Unfortunately, simply setting `x=x[-1,-1]` causes it to fail in the case of a square matrix, because when `x` is 2x2, the subsetting returns a vector rather than a matrix.

Try it online!

# Answer
> 0 votes
# Java 7, ~~280~~ 276 bytes

```
import java.util.*;String d(ArrayList l){String r="";for(;l.size()>0&&((List)l.get(0)).size()>0;l.remove(0))r+=s(l)+" ";return r;}int s(List<ArrayList<Integer>>l){int s=0,L=l.size(),i=1;for(;l.get(0).size()>0;s+=l.get(0).remove(0));for(;i<L;s+=l.get(i++).remove(0));return s;}

```

Try it here.

Alternative approach compared to my previous answer with arrays, which is still shorter than this one in the end (so I kinda wasted time trying this alternative approach).

**General explanation:**

Inspiration from *@Riley*'s amazing 05AB1E answer
This answer uses a List and after every sum is calculated it removes the first column and first row from the List-matrix, like this:

```
// Starting matrix:
7 10 1
4 4  2
6 3  4
1 4  10
5 7  6

// After first iteration (result so far: "34 "):
4  2
3  4
4  10
7  6

// After second iteration (result so far: "34 20 "):
4
10
6

// After last iteration, result: "34 20 20 "

```

**Explanation of the code:**

```
import java.util.*;                // Required import for List and ArrayList

String d(ArrayList l){             //  Method with ArrayList parameter and String return-type
  String r="";                     //  Return-String
  for(;l.size()>0&&((List)l.get(0)).size()>0;
                                   //  Loop as long as the list still contains anything
       l.remove(0))                //  And remove the first row after every iteration
    r+=s(l)+" ";                   //   Append the sum to the result-String
                                   //  End of loop (implicit / single-line body)
  return r;                        //  Return result-String
}                                  // End of method

int s(List<ArrayList<Integer>>l){  // Separate method with List-matrix parameter and integer return-type
  int s=0,                         //  The sum
      L=l.size(),                  //  The size of the input list
      i=1;                         //  Temp integer
  for(;l.get(0).size()>0;          //  Loop (1) over the items of the first row
    s+=l.get(0).                   //   Add the number to the sum
                remove(0)          //   And remove it from the list afterwards
  );                               //  End of loop (1)
  for(;i<L;                        //  Loop (2) over the rows
    s+=l.get(i++).                 //   Add the first number of the row to the sum
                  remove(0)        //   And remove it from the list afterwards
  );                               //  End of loop (2)
  return s;                        //  Return sum
}                                  // End of separate method

```

# Answer
> 0 votes
# Python, 93 bytes

Similar to mbomb007's answer, but without NumPy

```
f=lambda m:[sum(m[k][k:])+sum(list(zip(*m))[k][k+1:])for k in range(min(len(m),len(m[0])))]

```

# Answer
> 0 votes
# Perl 5 `-MList::Util=sum -n`, 48 bytes

```
@,=eval;say sum@{shift@,},map{shift@$_}@,while@,

```

Try it online!

---
Tags: code-golf, math, matrix
---


title: World Big Dosa

text:
# Question
Title: World Big Dosa
You are a talented young chef who has just been offered the position of sous chef at the world's most prestigious Indian restaurant. You have little experience with preparing Indian cuisine, but you're determined, so you set out to prove yourself. You decide to become the leading dosa expert. To do this, you must not only master the creation of dosas, but you must be able to scale them to be arbitrarily large.

You find a promising recipe for dosa batter:

* 1 cup rice
* 1 cup ukda chawal
* 1/2 cup urad dal
* 1/4 cup poha
* 1/4 tsp methi seeds
* Salt to taste
* Water as needed

This will make a dosa approximately **1/2 meter** in length.

## Challenge

Write a program or function that will tell the restaurant staff exactly what's needed to make a single dosa out of an integer multiple of the given recipe Space is tight in the kitchen, so you want your code to be as short as possible. The shortest code wins, with ties going to the earlier post.

Measuring spoons and cups come in the following standard sizes: 1/4, 1/3, 1/2, 2/3, 3/4, and 1. To avoid angering the kitchen staff, measurements must be reported in the **largest unit** in which the number can be written as mixed numbers using **standard sizes only**.

Measurements propagate to larger sizes per the following convention:

* 3 tsp == 1 tbsp
* 4 tbsp == 1/4 cup

So for a multiple of 12, 1/4 tsp methi seeds becomes 1 tbsp. However, for a multiple of 13, it becomes 3 1/4 tsp. Otherwise it wouldn't be represented in standard sizes.

The wait staff must be able to carry the dosa to the tables. To ensure that the dosa does not break in transit, you instruct them to carry the dosa in teams. **Each person can carry at most one meter of dosa.** So for a single or double recipe, only one person is needed to carry it. The wait staff is less effective if they're cut into fractional pieces, so an **integer number of waiters** is always required.

## Input

Take a positive integer via STDIN (or closest alternative), command line argument, or function argument. This number dictates the scaling factor for the recipe and can be as small as 1 but no larger than 232-1. It can be any integer in that range.

## Output

Print to STDOUT (or closest alternative) the list of ingredients scaled according to the input as well as the number of waiters required to carry the dosa. The ingredients must be listed in the order given above and in the format given below.

## Examples

Input:

```
2

```

Output:

```
2 cups rice
2 cups ukda chawal
1 cup urad dal
1/2 cup poha
1/2 tsp methi seeds
Salt to taste
Water as needed
1 waiter

```

Note that "cup" changes to "cups" when the value is greater than 1. "tsp" does not change. "waiter," like "cup," becomes plural.

Input:

```
5

```

Output:

```
5 cups rice
5 cups ukda chawal
2 1/2 cups urad dal
1 1/4 cups poha
1 1/4 tsp methi seeds
Salt to taste
Water as needed
3 waiters

```

Non-integer values greater than 1 are represented as mixed numbers, i.e. an integer followed by a reduced fraction.

Note: The title comes from a relevant video.

# Answer
# CJam, 214 bytes

```
ri[48_24C.25]{[48ZX]f{:DW$@*\md_D{_@\%}h;:M/iDM/}3/_{W=5<}#:I=[(\'/*]{S+_0e=!*}/["cup"2$2a>'s*+"tbsp"_'b-]I=S}%4/"rice
ukda chawal
urad dal
poha
methi seeds
Salt to taste
Water as needed"N/.+N*N@)2/" waiter"1$1>'s*

```

Try it online in the CJam interpreter.
> 9 votes

# Answer
# Javascript (ES6), 443 chars

This was very fun to golf, but the result is considerably longer than what I was expecting.

```
d=n=>(y=s=>n<s?' cup':' cups',z=s=>n/s|0,A=' 1/4',B=' 1/2',C=' 3/4',n+y(2)+` rice
${n+y(2)} ukda chawal
${(n%2<1?n/2:z(2)+B)+y(3)} urad dal
${((e=n%4)<1?n/4:z(4)+(e<2?A:e<3?B:C))+y(5)} poha
${(n%48<1?z(192)+((c=n/48%4)>2?C:c>1?B:c>0?A:'')+y(193):n%3<1?z(12)+((f=n/3%4)>2?C:f>1?B:f>0?A:'')+' tbsp':(z(4)+(e>2?C:e>1?B:e>0?A:''))+' tsp')} methi seeds
Salt to taste
Water as needed
${(b=Math.ceil(n/2))} waiter`+(b<2?'':'s')).replace(/\n0 /g,'\n')

```

Try it out:

```
d=n=>(y=s=>n<s?' cup':' cups',z=s=>n/s|0,A=' 1/4',B=' 1/2',C=' 3/4',n+y(2)+` rice
${n+y(2)} ukda chawal
${(n%2<1?n/2:z(2)+B)+y(3)} urad dal
${((e=n%4)<1?n/4:z(4)+(e<2?A:e<3?B:C))+y(5)} poha
${n%48<1?z(192)+((c=n/48%4)>2?C:c>1?B:c>0?A:'')+y(193):n%3<1?z(12)+((f=n/3%4)>2?C:f>1?B:f>0?A:'')+' tbsp':(z(4)+(e>2?C:e>1?B:e>0?A:'')+' tsp')} methi seeds
Salt to taste
Water as needed
${(b=Math.ceil(n/2))} waiter`+(b<2?'':'s')).replace(/\n0 /g,'\n')

W=function(){setTimeout(function(){
    (Q=document.getElementById("num").value)&&(document.getElementById("a").innerHTML =d(+Q).replace(/\n/g,'<br>'));
  }, 10);};
document.getElementById("num").addEventListener("keypress", function(){W();});
document.getElementById("num").addEventListener("click", function(){W();});
```

```
<form>How many recipes of dosa batter would you like?
  <input type="number" name="num" id="num" value="1" />
</form>
<p id="a">1 cup rice<br>
1 cup ukda chawal<br>
1/2 cup urad dal<br>
1/4 cup poha<br>
1/4 tsp methi seeds<br>
Salt to taste<br>
Water as needed<br>
1 waiter</p>
```

It accepts values up to and even including `2^32`, or `4294967296`. After that, the 'urad dal' overflows on odd numbers and becomes negative.

Basically, it calculates the correct amounts as it goes. Luckily, only the methi seeds need to have tsp/tbsp/cup measures; otherwise, this would have been a whole lot longer. (The methi seed line alone is 155 chars!)

This also would have been at least 500 chars long in ES5. I ❤ ES6.

As always, suggestions are greatly appreciated!

**Edit 1:** Just realized that according to the rules, `1 tsp` should be replaced with `1/3 tbsp`, same with `2 tsp` and `2/3 tbsp`, as well as `16 tsp` and `1/3 cup`....
> 7 votes

# Answer
# R, ~~602~~ ~~603~~ 526 bytes

Still lots of room to golf this I suspect, but I have run out of time and I really wanted to do an answer for this one.

```
function(i){S=gsub
M=i/c(1,5,60)
A=list(c(2,1),c(4,3),c(64,48))[[I<-max(which(M>=1))]]
B=c(4,12,192)[I]
V=c(' tsp',' tbsp',' cup')[I]
C=i%/%B
C=C+max((i%%B)%/%A*c(.3,.25))
cat(S('([ ]*)0 ','\\1',S('\\.3',' 1/3',S('\\.6',' 2/3',S('\\.5',' 1/2',S('\\.25',' 1/4',S('\\.75',' 3/4',paste0(i,' cup',if(i>1)'s',' rice
',i,' cup',if(i>1)'s',' ukda chawal
',i*.5,' cup',if(i>2)'s',' urad dal
',i*.25,' cup',if(i>4)'s',' poha
',C,V,if(C>1&I>2)'s',' methi seeds
Salt to taste
Water as needed
',ceiling(i*.5),' waiter',if(i>2)'s'))))))))}

```
> 3 votes

# Answer
# Common Lisp, 435

```
(lambda(n)(labels((k(y)(some(lambda(x)(integerp(* y x)))'(1 4/3 3/2 2 3 4)))(h(s m)(multiple-value-bind(q r)(floor m)(format()"~[~:;~:*~A ~]~[~:;~:*~A ~]~@? " q r s m)))(g(o &aux(h(/ o 3))(c(/ h 4)))(cond((k c)(h"cup~P"c))((k h)(h"tbsp"h))(t(h"tsp"o)))))(format t"~&~A rice
~Aukda chawal
~Aurad dal
~Apoha
~Amethi seeds
Salt to taste
Water as needed
~A waiter~:P
"(g(* n 12))(g(* n 12))(g(* n 6))(g(* n 3))(g(/ n 4))(ceiling(/ n 2)))))

```

## Slightly ungolfed

```
(lambda (n)
  (labels ((k (y)
             (some (lambda (x) (integerp (* y x))) '(1 4/3 3/2 2 3 4)))
           (h (s m)
             (multiple-value-bind (q r)
                 (floor m)
               (format nil "~[~:;~:*~A ~]~[~:;~:*~A ~]~@?" q r s m)))
           (g (o &aux (h (/ o 3)) (c (/ h 4)))
             (cond ((k c) (h "cup~P" c)) ((k h) (h "tbsp" h)) (t (h "tsp" o)))))
    (format t "~&~A rice
~A ukda chawal
~A urad dal
~A poha
~A methi seeds
Salt to taste
Water as needed
~A waiter~:P
"
            (g (* n 12)) (g (* n 12)) (g (* n 6)) (g (* n 3)) (g (/ n 4))
            (ceiling (/ n 2)))))

```

All measures are expressed in `tsp`. Based on the `k` function, `g` decides which units to use for printing and call the formatting function `h` with the appropriate arguments.

* `k` returns true when the argument can be expressed as a multiple of 1, 1/4, 1/3, 2/3, 4/3 units
* `g` converts the input as a number of tbsp and the number of tbsp as a number of cups (as given in the question). We try to print by units of cups first, or units of tbsp, or else in tps.
* `h` use a conditional formatting directives to print either `x`, `x y/z` or `y/z` followed by the formatting of `s` with argument `m`: for cups, `s` is `"cup~P"` which plurializes the word according to `m`.

## Exemple (n = 17)

```
17 cups rice
17 cups ukda chawal
8 1/2 cups urad dal
4 1/4 cups poha
4 1/4 tsp methi seeds
Salt to taste
Water as needed
9 waiters

```
> 3 votes

# Answer
# JavaScript (Node.js), 419 bytes

```
a=>(y=g=>a<g?" cup":" cups",z=g=>a/g|0,a+y(2)+` rice
${a+y(2)} ukda chawal
${(1>a%2?a/2:z(2)+(B=" 1/2"))+y(3)} urad dal
${(1>(e=a%4)?a/4:z(4)+(2>e?A=" 1/4":3>e?B:C=" 3/4"))+y(5)} poha
${1>a%48?z(192)+(2<(c=a/48%4)?C:1<c?B:0<c?A:"")+y(193):1>a%3?z(12)+(2<(f=a/3)?C:1<f?B:0<f?A:"")+" tbsp":z(4)+(2<e?C:1<e?B:0<e?A:"")+" tsp"} methi seeds
Salt to taste
Water as needed
${b=-~a/2|0} waiter`+(2>b?"":"s")).replace(`
0 `,`
`)

```

Try it online!
> 1 votes

# Answer
# Stax, ~~122 120~~ 117 bytes

```
Öàu≈9o∞3┴&•ªâ6üòf±Σ§LXâ¢vò╣*/T≥C└ôZüæR-^╦ìóσ∩A←··■☼⌂▌2åH╨bgrp╬3L♫-◙•►]╘═º♀ú♣É±╧○+╧┴Qî¼▼◄I"a≤ΩzH♦╩k╖FΦúZa═q|▬◄┼W╥ßöo29

```

Run and debug it

It was a bit infuriating to start over after closing this program's tab, but now it works, and it's shorter!

-5 bytes from recursive.

## Explanation (Unpacked)

```
3:B244E{um+{x*uuB\"cup"sch1>{s's+}{s}?]+{fJm"rice,ukda chawal,urad dal,poha,methi seeds"',/\{JmN"cup""tsp"R]+{PF"Salt to taste"P"Water as needed"P2:_ecp" waiter"p1>{'sp}*

```

`3:B244E{um+` array `[1,1,1/2,1/4,1/4]`

`{...m` map to:

```
 x*uu product with input,  converted to fraction

 B\                        push fractional part and whole part, and pair them

 "cup"sch1>{s's+}{s}?]+    if whole part <1, append "cup", else cups

 {fJ                       remove zeroes, and join with spaces

```

`"rice,ukda chawal,urad dal,poha,methi seeds"',/` array of ingredients

`\{Jm` zip with the amounts, and jin with spaces

`N` remove last element and push separately(methi seeds)

`"cup""tsp"R]+` replace "cup" with "tsp", add it back in

`{PF` print each ingredient

`"Salt to taste"P"Water as needed"P` print the constant instructions

`2:_ecp` divide input by 2, ceil, duplicate, and print

`" waiter"p` print "waiter"

`1>{'sp}` if number of waiters \> 1, print an s
> 1 votes

---
Tags: code-golf, math, rational-numbers
---


title: Count cyclically self-describing lists

text:
# Question
Title: Count cyclically self-describing lists
# Cyclically self-describing lists

A list \\$L\\$ of positive integers is *cyclically self-describing*, if the following conditions hold.

1. \\$L\\$ is nonempty.
2. The first and last elements of \\$L\\$ are different.
3. If you split \\$L\\$ into runs of equal elements, the element of each run equals the length of the next run, and the element of the last run equals the length of the first run.

For example, consider \\$L = \[1,1,1,2,3,3,1,1,1,3\]\\$. It is nonempty, and the first and last elements are different. When we break it into runs, we get \\$\[\[1,1,1\],\[2\],\[3,3\],\[1,1,1\],\[3\]\]\\$.

* The first run is a run of \\$1\\$s, and the length of the next run, \\$\[2\]\\$, is \\$1\\$.
* The second run is a run of \\$2\\$s, and the length of the next run, \\$\[3,3\]\\$, is \\$2\\$.
* The third run is a run of \\$3\\$s, and the length of the next run, \\$\[1,1,1\]\\$, is \\$3\\$.
* The fourth run is a run of \\$1\\$s, and the length of the next run, \\$\[3\]\\$, is \\$1\\$.
* Finally, the last run is a run of \\$3\\$s, and the length of the first run, \\$\[1,1,1\]\\$, is \\$3\\$.

This means that \\$L\\$ is a cyclically self-describing list.

For a non-example, the list \\$\[3,2,2,2,1,4,1,1,1\]\\$ is not cyclically self-describing, since a run of \\$2\\$s is followed by a run of length \\$1\\$. The list \\$\[2,2,4,4,3,3,3,3\]\\$ is also not cyclically self-describing, since the last run is a run of \\$3\\$s, but the first run has length \\$2\\$.

# The Task

In this challenge, your input is an integer \\$n \geq 1\\$. Your output shall be the number of cyclically self-describing lists whose sum equals \\$n\\$. For example, \\$n = 8\\$ should result in \\$4\\$, since the cyclically self-describing lists whose sum is \\$8\\$ are \\$\[1,1,1,1,4\]\\$, \\$\[1,1,2,1,1,2\]\\$, \\$\[2,1,1,2,1,1\]\\$ and \\$\[4,1,1,1,1\]\\$. The lowest byte count wins, and other standard rules apply.

Here are the correct output values for inputs from \\$1\\$ to \\$50\\$:

```
1 -> 0
2 -> 0
3 -> 0
4 -> 2
5 -> 0
6 -> 2
7 -> 0
8 -> 4
9 -> 0
10 -> 6
11 -> 6
12 -> 12
13 -> 0
14 -> 22
15 -> 10
16 -> 32
17 -> 16
18 -> 56
19 -> 30
20 -> 96
21 -> 56
22 -> 158
23 -> 112
24 -> 282
25 -> 198
26 -> 464
27 -> 364
28 -> 814
29 -> 644
30 -> 1382
31 -> 1192
32 -> 2368
33 -> 2080
34 -> 4078
35 -> 3844
36 -> 7036
37 -> 6694
38 -> 12136
39 -> 12070
40 -> 20940
41 -> 21362
42 -> 36278
43 -> 37892
44 -> 62634
45 -> 67154
46 -> 108678
47 -> 118866
48 -> 188280
49 -> 209784
50 -> 326878

```

# Answer
# Haskell, 75 bytes

Thanks Ørjan for saving one byte!

```
g n=sum[x#n|x<-[1..n],let a#n=sum$[b#(n-a*b)|b<-[1..n],a/=b]++[0^n^2|a==x]]

```

Try it online!

The problem is equivalent to:

How many ways can \\$n\\$ be written as \\$\sum\_{i=0}^ka\_ia\_{i+1}\\$ with \\$a\_i\in\mathbb N,a\_i\neq a\_{i+1},a\_0=a\_k\\$
> 6 votes

# Answer
# Jelly, 18 bytes

```
ṗⱮ¹Ẏ;ḷ/$€IẠ$Ƈ×Ɲ€§ċ

```

Try it online!

Idea: Each cyclically self-describing list can be described as a list of values for each block, and we can deduce the lengths from the values. Note that two adjacent values must be different. Of course there can be at most `n` blocks and the length of each block is at most `n`.
> 2 votes

# Answer
## Haskell, ~~118~~ ~~105~~ 103 bytes

Edit: -13 bytes thanks to @Ørjan Johansen, -2 bytes thanks to @H.PWiz

```
g s=sum[b#a$s|b<-[1..s],a<-[1..s],let(d#l)s|d==a,d/=b,l*d==s=1|n<-s-d*l=sum[i#d$n|i<-[1..s],d/=i,n>=0]]

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 25 bytes

```
Åœεœʒ¬sθÊ}ÙεγĆü‚ε`gå}P]˜O

```

Try it online or verify the first 9 test cases (times out for \\$n\geq10\\$).

**Explanation:**

```
Åœ              # Get all lists of positive integers that sum to the (implicit) input
  ε             # Map over each inner list:
   œ            #  Get all its permutations
    ʒ           #  Filter this list of permutation-lists by:
     ¬          #   Get the first element (without popping the list itself)
      sθ        #   Swap to get the list, and pop and push its last element
        Ê       #   Check that they are NOT equal
    }Ù          #  After the inner filter: uniquify all remaining permutations
      ε         #  Map each permutation to:
       γ        #   Split the list into groups of equal adjacent elements
        Ć       #   Enclose it: add the first group as trailing item
         ü‚     #   Create overlapping pairs of groups
           ε    #   Map over each pair:
            `   #    Pop and push both lists separated to the stack
             g  #    Pop and get the length of the second list
              å #    And check that it's in the first list
           }P   #   After this inner-most map: verify all pairs were truthy (product)
  ]             # Close the two still open nested maps
   ˜            # Flatten the list of lists
    O           # And take the sum
                # (after which this is output implicitly as result)

```

Try it online with a step-by-step output.
> 1 votes

# Answer
# Husk, 27 bytes

```
#§=oṙ1mLm←fo¬εumgfo=¹ΣṖṁḣ´R

```

Try it online!

A direct bruteforce. Struggles for n above 4.
> 0 votes

---
Tags: code-golf, array, counting
---


title: Segmented numbers

text:
# Question
Title: Segmented numbers
The sequence of segmented numbers or prime numbers of measurement (OEIS A002048) is the sequence of numbers such that each member is the smallest positive (greater than zero) number that can't be made of a sum of earlier consecutive numbers, with `a(0) = 1`.

### Example

To calculate `a(7)` we first calculate `a(0->6) = [1, 2, 4, 5, 8, 10, 14]`. we then start from zero and go through numbers until we find one that is not the sum of one or more consecutive numbers in the sequence.

```
1  = 1
2  = 2
3  = 1 + 2
4  = 4
5  = 5
6  = 2 + 4
7  = 1 + 2 + 4
8  = 8
9  = 4 + 5
10 = 10
11 = 2 + 4 + 5
12 = 1 + 2 + 4 + 5
13 = 5 + 8
14 = 14
15 = ????

```

Since fifteen cannot be made by summing any consecutive subsequence and every number smaller can be fifteen is the next number in the sequence. `a(7) = 15`

### Task

Your task is to take a number (via standard methods) and output the nth term in this sequence (via standard output methods). This is code-golf and you will be scored as such.

### Test Cases

```
0 -> 1
1 -> 2
2 -> 4
3 -> 5
4 -> 8
5 -> 10
6 -> 14
7 -> 15
8 -> 16
9 -> 21

```

# Answer
## Haskell, ~~62~~ 58 bytes

-4 bytes thanks to @xnor!

```
(x:y)#z=x:filter(`notElem`scanl(+)x z)y#(x:z)
([1..]#[]!!)

```

Sequence is 0-indexed.
> 13 votes

# Answer
# Perl, ~~50~~ 49 bytes

Includes +1 for `-p`

Run with input on STDIN:

```
segmented.pl <<< 7

```

`segmented.pl`:

```
#!/usr/bin/perl -p
${$_-=$\}++for@F;1while${-++$\};++$#F<$_&&redo}{

```

## Explanation

`@F` contains the list of (negative) sums of consecutive numbers that end with the current last number. When a new number is discovered the list is extended with 0 and then all values are decreased by the new number maintaining the invariant.

Global `%::` is used as a hash mapping all (negative) numbers that have been seen (through `@F`) to a non-zero value.

`$\` is the current number and gets increased until it reaches a value not yet in `%::`.

By being a bit careful about the order in which everything happens no initialization is needed, `1` will automatically become the first number.

Since the size of `@F` is how many numbers have been generated it can be used as a halting condition
> 7 votes

# Answer
# Jelly, ~~14~~ ~~13~~ 11 bytes

```
Ḷß€Ẇ;ḅ1‘ḟ$Ṃ

```

Try it online!

### How it works

```
Ḷß€Ẇ;ḅ1‘ḟ$Ṃ  Main link. Argument: n

Ḷ            Unlength; yield [0, ..., n - 1].
 ß€          Recursively map the main link over the range.
   Ẇ         Window; yield all subarrays of consecutive elements of the result.
    ;        Append n to the array of subarrays.
     ḅ1      Convert all subarrays from base 1 to integer.
             This is equivalent to S€ (sum each), but it allows ; to hook.
         $   Combine the previous two links into a monadic chain.
       ‘       Increment all sums.
        ḟ      Filter; remove the original sums from the incremented ones.
          Ṃ  Compute the minimum.

```
> 5 votes

# Answer
# 05AB1E, ~~17~~ 16 bytes

```
Xˆ$µ>D¯ŒOså_i¼Dˆ

```

**Explanation**

```
Xˆ                # initialize global array to [1]
  $               # push 1 and input to stack
   µ              # while counter != input
    >             # increase variable on stack
      ¯ŒO         # list of all sums of consecutive number in global array
     D   så_i     # if current stack value is not in the list
             ¼    # increase counter
              Dˆ  # add current stack value to global array

```

Try it online!

Saved 1 byte thanks to Adnan
> 4 votes

# Answer
# Pyth - ~~19~~ 17 bytes

Damn off-by one ruining all my implicits. (Same bytes count, literaly incrementing `Q`: `=hQesmaYf!}TsM.:Y`)

```
esmaYf!}TsM.:Y)1h

```

Test Suite.
> 2 votes

# Answer
## Javascript, 125 112 110 bytes

Saved 2 bytes thanks to @Neil

```
f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)a.some(b=>b.includes(i))||(a[z+1]=[0,...a[z++]||[]].map(v=>i+v));alert(i-1)}

```

*Previous answers*

112 bytes thanks to @Neil:

```
f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)if(!a.some(b=>b.includes(i))){a[z+1]=[0,...a[z++]||[]].map(v=>i+v)}alert(i-1)}

```

125 bytes:

```
f=n=>{a=[[]];for(i=1,k=z=0;z<=n;i++)if(a.every(b=>b.every(c=>c-i))){a[i]=[i].concat((a[k]||[]).map(v=>i+v));k=i,z++}alert(k)}

```
> 2 votes

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

```
!¡ö←`-NmΣQø

```

Try it online!

returns nth term, 1-indexed.

-1 byte from Dominic Van Essen, using empty list.

## Explanation

```
!¡ö←`-NmΣQø
          ø start with the empty list:
 ¡ö         apply the following infinitely:
         Q  get all subsequences
       mΣ   sum each of them
    `-N     remove the sums from natural numbers
   ←        take the first one
!           get the nth element from this list

```
> 2 votes

# Answer
# Python, ~~113~~ ~~105~~ ~~92~~ 80 bytes

```
s=F={1}
x=1
exec"while{x}<=s:x+=1\nF={x+j for j in{0}|F};s|=F\n"*input()
print x

```

The final bytes I saved were inspired by Ton’s Perl answer: my `F` does the same thing as his `@F`; my `s` does essentially the same thing as his `%::`.
> 1 votes

# Answer
## JavaScript (ES6), 77 bytes

```
(n,a=[],s=a,i=1)=>s[i]?f(n,a,s,i+1):--n?f(n,[0,...a].map(j=>s[j+=i]=j),s,i):i

```

Basically a recursive port of the algorithm of @TonHospel's Perl answer.
> 1 votes

# Answer
# Scala, 97 bytes

```
n=>{var(r,i)=Seq(1)->1;while(r.size<n+1){i+=1;r++=Set(i)--r.tails.flatMap(_.inits).map(_.sum)};i}

```

Try it online
> 0 votes

---
Tags: code-golf, sequence
---


title: Draw/plot a heart graph

text:
# Question
Title: Draw/plot a heart graph
Your challenge is to draw/plot one of the hearts below. The size must be at least 50x50 pixels (vector graphics is OK). You may choose which of the hearts you want to draw/plot. Axes, grid lines etc. are accepted. There must be **at least** 100 distinct coordinates/points on the graph. The heart can be filled with color if you want to.

The equations are either:

**or**

`t` is in the range `[-1, 1]`.

**or**

**or**

This is so the shortest code (in each language) in bytes wins. Please provide the output (or link to an online interpreter).

# Answer
> 68 votes
# TI-80 BASIC, ~~45~~ ~~43~~ ~~41~~ 39 bytes

```
LBL 1
RAND4-2->X
RAND4-2
IF (X²+ANS²-1)³<X²ANS³
PT-ON(X,ANS
GOTO 1

```

This took a while, and my battery is low so I didn't want to keep going.

I tried to use the second equation, but ~~couldn't get it to work~~ it actually turned out to be longer, so I just adapted the other answer I had.

EDIT: I just noticed the 50x50 pixel requirement, unfortunately the screen is only 47 pixels high so this isn't possible.

# Answer
> 47 votes
## Perl, 86 bytes

```
$y=1-$_/25,say+map$y**3*($_*=$_/1e3)-($_+$y**2-1)**3>0?$|--?v60:3:$",-40..40for-6..50

```

Run with `perl -E`.

Plots a filled ASCII heart, using the first equation. Note that the x-axis is stretched by a factor of ~1.265: this is to counteract the fact that terminal fonts are usually much bigger vertically than horizontally.

Output:

```
                3<3<3<3<3<3<3<                   3<3<3<3<3<3<3<
              3<3<3<3<3<3<3<3<3<3<           3<3<3<3<3<3<3<3<3<3<
            3<3<3<3<3<3<3<3<3<3<3<3<       3<3<3<3<3<3<3<3<3<3<3<3<
          3<3<3<3<3<3<3<3<3<3<3<3<3<3<   3<3<3<3<3<3<3<3<3<3<3<3<3<3<
         3<3<3<3<3<3<3<3<3<3<3<3<3<3<3< 3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
        3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3 <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
       3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
      <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
      3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
     <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
     3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
    <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
    3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
    <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
    3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
    <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
   3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
   <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
    3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
    <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
    3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
    <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
    3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
     <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
     3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
     <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
      3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
      <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
       3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
       <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
        3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
         <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
         3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
          <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
           3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
            <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
             3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
              <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
               3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
                <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
                 3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
                  <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
                   3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
                     <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
                      3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
                       <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<
                         3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
                           <3<3<3<3<3<3<3<3<3<3<3<3<
                            3<3<3<3<3<3<3<3<3<3<3<3
                              <3<3<3<3<3<3<3<3<3<
                                3<3<3<3<3<3<3<3
                                  <3<3<3<3<3<
                                    3<3<3<3
                                     <3<3<
                                       3

```

Explanation (since OP asked for it):

```
condition := $y**3*($_*=$_/1e3)-($_+$y**2-1)**3>0

```

This is simply the first equation, slightly rearranged to make it shorter. $y directly represents the y in the formula. $\_ is initially proportional to x, but is multiply-assigned with itself (`$_*=$_/1e3`), making it proportional to x². Since x² is used twice in the formula, this saves a few bytes.

`1e3` means 1000, and was picked because it’s short and the result looks good. `**` is Perl’s power operator. I use `>0` rather than `==0` because I want a filled heart.

```
flip_flop := $|--?v60:3

```

v60 is an abuse of the archaic version-string syntax to denote the character with ASCII code 60: '\<'.

$| is a magical variable that can only ever be 0 or 1. Decrementing when it’s already 0 sets it to 1. Decrementing when it’s 1 naturally sets it to 0. Thus, $|-- is often used as a flip-flop: each time it’s evaluated, it alternates between true and false.

As a whole, this expression returns alternatively '\<' and 3.

```
inner_loop := <condition> ? <flip_flop> :$"

```

Nested ternaries. If condition is false (→ we’re outside the heart), evaluates to $", which is a magical variable that defaults to " " (a single space). If condition is true (→ we’re inside the heart), it evaluates flip\_flop.

```
outer_loop := say+map <inner_loop> ,-40..40

```

Evaluates inner\_loop repeatedly, with $\_ (Perl’s “default” variable) going from -40 to 40, in increments of 1. It collects the results of those evaluation in a temporary list, then prints them all, concatenated, ending with a new line.

```
$y=1-$_/25, <outer_loop> for-6..50

```

This runs outer\_loop repeatedly, with $y going from 1.24 (1 - (-6 / 25)) to -1 (1 - 50 / 25), in decrements of 0.04.

Note that y is divided by 25, while x² is divided by 1000, which is the same as dividing x by sqrt(1000). The ~1.265 factor I mentioned is sqrt(1000) / 25.

# Answer
> 34 votes
# Mathematica WolframAlpha, 17 15 13 11 bytes

Shaved off 2 bytes thanks to Martin Ender (1st heart curve -\> heart curve 1)

Shaved off another 2 bytes thanks to Martin Ender (heart curve 1 -\> heartcurve1)

This is probably cheating (the obvious solution), but here goes.

```
heartcurve1

```

Try it here!

I'm sure there's a way to shorten 1st, heart or curve such that Wolfram still accepts it.  Well it's free of spaces now, maybe some sort of abbreviation for heart?

Do I get bonus points for plotting 2 of them?

```
heartcurves

```

Try that here!

# Answer
> 29 votes
## Mathematica, 52 bytes

```
RegionPlot[(x^2+y^2-1)^3-x^2y^3<0,{x,-2,2},{y,-2,2}]

```

We could save one more byte with `ContourPlot` but then the background gets a bit trippy:

```
ContourPlot[(x^2+y^2-1)^3-x^2y^3,{x,-2,2},{y,-2,2}]

```

For one *additional* byte we could use the fourth formula and `PolarPlot` instead:

```
PolarPlot[(x=Sin@t)Abs@Cos@t^.5/(x+7/5)-2x+2,{t,0,7}]

```

# Answer
> 26 votes
# Casio fx-7700GH, 21 bytes

```
sin θ √ Abs cos θ ÷ ( sin θ + 7 ÷ 5 ) - 2 sin θ + 2

```

Unnamed graph function to be entered into one of the polar coordinate graphing function slots, then does what it says on the tin.

The graphing range must be manually set (unless it happens to fit to the current set range), I set it to `Xmin=-2.75, Xmax=2.75, Ymin=-4, Ymax=1`.

Should work on other Casio Power Graphic Series calculators too, and quite possibly later Casio graphic calculators.

(yep ~~I'm~~ pretty old and dusty)

# Answer
> 18 votes
# MATLAB / Octave, 31 bytes

```
ezplot('(x^2+y^2-1)^3-x^2*y^3')

```

# Answer
> 10 votes
## Desmos, 20 16 15 bytes

V 2:

```
xx)<sup>.3</sup>y=xx+yy-1
```

( = `xx)^.3y=xx+yy-1`)

V 1:

```
xx+yy-1)<sup>3</sup>=xxy<sup>3</sup>
```

V 0:

```
(x<sup>2</sup>+y<sup>2</sup>-1)<sup>3</sup>=x<sup>2</sup>y<sup>3</sup>
```

# Answer
> 9 votes
# SmileBASIC, ~~85~~ 81 bytes

```
X=RNDF()*4-2Y=RNDF()*4-2GPSET X*50+99,Y*50+99,-(-X*X*Y*Y*Y>POW(X*X+Y*Y-1,3))EXEC.

```

# Answer
> 8 votes
# MATL, 36 bytes

```
1e4t:w/EqXJX,JY,J|Yl**JX,X^J|.3^*&XG

```

Try it at MATL Online

# Answer
> 7 votes
# Python, ~~119~~ 116 bytes

```
from turtle import*
from math import*
t=1
while-t<1:a=abs(t);c=cos(t);goto(sin(t)*c*log(a)*99,c**.5*a**.3*99);t-=.01

```

**Try it online**

# Answer
> 7 votes
# Jelly, 31 bytes

```
*3×
²+’*3<çị⁾*
25µNr÷21µ²ç@þUY

```

**Try it online!**

or **35 bytes** with a , rather than `*` fill: change middle line to `²+’*3<ç×9829Ọ»⁶`.

```
          ♥♥♥♥♥♥♥♥♥♥           ♥♥♥♥♥♥♥♥♥♥
        ♥♥♥♥♥♥♥♥♥♥♥♥♥♥       ♥♥♥♥♥♥♥♥♥♥♥♥♥♥
      ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥   ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
     ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
     ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
    ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
   ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
   ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
   ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
   ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
   ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
    ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
    ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
     ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
     ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
      ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
      ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
       ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
        ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
        ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
         ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
          ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
           ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
            ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
             ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
              ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
               ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
                 ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
                  ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
                   ♥♥♥♥♥♥♥♥♥♥♥♥♥
                     ♥♥♥♥♥♥♥♥♥
                      ♥♥♥♥♥♥♥
                        ♥♥♥
                         ♥

```

### How?

Implements:  over a 51 by 51 line feed separated grid of characters.

```
*3× - Link 1: y, xSquared
*3  - cube y
  × - multiply the result by xSquared

²+’*3<çị⁾*  - Link 2: y, xSquared
²           - square y
 +          - add xSquared to the result
  ’         - subtract one
   *3       - cube the result
     <      - less than? (1 if True, 0 if False)
      ç     -     the result of the last link (1) as a dyad: f(y, xSquared)
       ị    - index into (1-based):
        ⁾*  - the string "* " (there is a trailing space on this line)

       ×9829Ọ»⁶ - alternative ending of link 2
       ×9829    - multiply (vectorises) by 9829
            Ọ   - cast to character (vectorises) (9829 is the ♥, 0 is the null-byte)
             »  - maximum (vectorises) of that and:
              ⁶ -     space character (ordinal of space is 32, greater than the null-byte, less than ♥)

25µNr÷21µ²ç@þUY - Main link: no arguments
25              - 25
  µ             - monadic chain separation call that i
   N            - negate i
    r           - inclusive range(negated i, i) -> [-25, -24, ..., 24, 25]
     ÷21        - divide by 21 (vectorises) -> [-1.1904761904761905, -1.1428571428571428, ..., 1.1428571428571428, 1.1904761904761905]
        µ       - monadic chain separation call that r
         ²      - square r (vectorises) (make the xSquared values, left to right)
             U  - upend r (make the y values, top to bottom)
            þ   - outer product using:
          ç@    -     last link (2) as a dyad with reversed arguments: f(y, xSquared)
              Y - join with line feeds
                - implicit print

```

# Answer
> 6 votes
## SageMath, 66 bytes

```
polar_plot(sin(x)*abs(cos(x))^.5/(sin(x)+7/5)-2*sin(x)+2,(0,2*pi))

```

Try it online

Unfortunately, the long names of `implicit_plot` and `parametric_plot` (plus the need to define a variable other than the implicitly-defined `x` for the former) make the first three options much too long to be considered.

Thanks to busukxuan and Andrea Lazzarotto for a byte

# Answer
> 6 votes
# C, ~~137~~ 133 bytes

```
p;float x,y,f;v(){for(p=4e3;p;x=(float)(p%99-50)/35,y=(float)(p/40-45)/40,f=x*x+y*y-1)putchar(p--%99?f*f*f-x*x*y*y*y<1e-3?35:32:10);}

```

http://codepad.org/zqqYUui8

Thanks @AlbertRenshaw, I also changed the 100s to 99s for 2 more bytes

# Answer
> 5 votes
## JavaScript (ES6), ~~151~~ 147 bytes

```
document.write`<canvas id=c>`;for(i=0;x=2-i/24,i<97;i++)for(j=0;y=2-j/24,z=x*x+y*y-1,j<97;j++)z*z*z-x*x*y*y*y<0&&c.getContext`2d`.fillRect(i,j,1,1)
```

Edit: Saved 4 bytes thanks to @user2428118. ES7 version for 143 bytes:

```
document.write`<canvas id=c>`;for(i=0;i<97;i++)for(x=2-i/24,j=0;j<97;j++)x*x*(y=2-j/24)**3-(x*x+y*y-1)**3>0&&c.getContext`2d`.fillRect(i,j,1,1)
```

# Answer
> 5 votes
## Ruby, 80 bytes

Show Ruby some love.

```
-2.step(2,0.2){|y|-2.step(2,0.1){|x|$><<'. O'[(y*y-1+x*=x)**3+x*y**3<=>0]};puts}

```

### Output:

```
         OOOOO     OOOOO
      .OOOOOOOOO.OOOOOOOOO.
     OOOOOOOOOOOOOOOOOOOOOOO
     OOOOOOOOOOOOOOOOOOOOOOO
     OOOOOOOOOOOOOOOOOOOOOOO
      OOOOOOOOOOOOOOOOOOOOO
      .OOOOOOOOOOOOOOOOOOO.
        OOOOOOOOOOOOOOOOO
         OOOOOOOOOOOOOOO
           OOOOOOOOOOO
              OOOOO
                .

```

with some empty lines above and below

# Answer
> 4 votes
# BBC BASIC, 80

Will finish golfing tomorrow.

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

```
ORIGIN99,99F.u=-56TO56x=u/50b=x^2^.33/2r=(b^2-x^2+1)^.5*50L.u,b*50-r,u,r+b*50N.

```

Draws a filled heart using the first equation, which we rearrange and take the cube root of (there are 3 cube roots of a real number, one real and 2 complex but we only interested in the real root here.) We then rearrange again to get a quadratic in `y`

```
x^2+y^2-1=(x^0.66)y

y^2-(x^0.66)y+x^2-1=0

```

Using the standard quadratic formula for expressions of the type `ay^2+by+c=0`, and taking advantage of the fact that `a`=1 we get

```
y = -b/2 +/- sqrt((b/2)^2-c)

y = -b/2 +/- sqrt((b/2)^2-x^2+1)

```

where `-b/2 = (x^0.66)/2` (represented by `b` in the program.)

We simply scan through the values of `x` from left to right, drawing a vertical line between each pair of valid values for `y` to build up a solid shape.

```
ORIGIN99,99F.u=-56TO56x=u/50b=x^2^.33/2r=(b^2-x^2+1)^.5*50L.u,b*50-r,u,r+b*50N.

```

**ungolfed**

```
ORIGIN99,99
FORu=-56TO56
  x=u/50
  b=x^2^.33/2
  r=(b^2-x^2+1)^.5*50
  LINEu,b*50+r,u,b*50-r
NEXT

```

# Answer
> 2 votes
# TI-84 Basic, ~~40~~ 38 bytes

Similar to @12Me21's answer & output, but for the TI-83/84 series instead.

```
While 1:2rand-1→A:2rand-1:If (A²+Ans²-1)³>A²Ans³:Pt-On(A,Ans:End

```

# Answer
> 2 votes
## Processing.js: ~~123~~ 119 bytes

ungolfed:

```
t = 0;

void setup() {
    size(99, 300);
}

void draw() {
    point(59+99*sin(t)*cos(t)*log(t),350-400*sqrt(cos(t))*pow(t,0.3));
    t+=0.01;
}

```

---

golfed:

```
t=0;void setup(){size(99,300);}void draw(){point(59+99*sin(t)*cos(t)*log(t),350-400*sqrt(cos(t))*pow(t,0.3));t+=0.01;}

```

this one is quite cheaty as it plots #2 from 0 to infinity instead of from -1 to 1 as shown in the picture to save on the two abs(t). But it's technically correct as there are more than 100 points.

---

130 bytes "correctier" one

```
t=-1;void setup(){size(99,300);}void draw(){point(59+99*sin(t)*cos(t)*log(abs(t)),350-400*sqrt(cos(t))*pow(abs(t),0.3));t+=0.01;}

```

---

try it online

note : there's probably a way to get 100 points on the default 100x100 canvas and shave the setup off.

# Answer
> 1 votes
# BBC BASIC (BBC Micro) (126 bytes)

This is a variation of Level River Street's answer, but for the original BBC Micro's iteration of BBC BASIC.

You can copy and paste either of the following into JSBeeb's new paste functionality at https://bbc.godbolt.org/ (A JavaScript powered BBC Micro emulator), once it has pasted, press Enter inside the 'screen' to show a new prompt, then type RUN, then press Enter to run either version.

golfed. (126 bytes)

```
1MO.1:V.29,64;64;:MOVE-57,20:GC.0,1:F.U=-56TO56:X=U/50:IFX<>0TH.B=X^2^.33/2
2R=(B^2-X^2+1)^.5*50:DRAWU,B*50+R:DRAW U,B*50-R:N.

```

ungolfed. (176 bytes)

```
1 MODE 1
2 VDU 29,64;64;
3 MOVE -57,20
4 GCOL 0,1
5 FOR U = -56 TO 56
6 X = U/50
7 IF X <> 0 THEN B = X^2^.33/2
8 R = (B^2-X^2+1)^.5*50
9 DRAW U,B*50+R
10 DRAW U,B*50-R
11 NEXT

```

Line 7 requires a check for X, to prevent a "Log range" error when X becomes 0 half way through the loop. Other than this, it's pretty much the same. It's a lot slower to draw on a real machine, which JSBeeb emulates pretty well.

# Answer
> 1 votes
# Google Sheets (Conditional Formatting), 73

Set conditional formatting on range A1:CV100:

```
=(2500/9-(Column()-25)^2-(ROW()-25)^2)^3>(Column()-25)^2*(ROW()-25)^3/.06

```

You'll have to adjust your columns/rows so that 100x100 cells fit on your screen. (10 pixels is a good value.) Colors the cells in the cardioid.

---
Tags: code-golf, math, graphical-output
---