# Question
Title: Evaluate Index of Multidimensional Coordinates
A collection of N dimensional coordinates are provided. An example is below:

```
{2,3,4}

```

This can be thought of as a 3 dimensional array with 2x's, 3y's and 4z's; there may be any number of dimensions. In the example, there are 24 total nodes. Each node can be indexed using {x,y,z}. To access the 5th node, the provided indices would be {0, 1, 0} based on the table below.

```
## | x y z
     0 1 2
-----------
0  | 0 0 0
1  | 0 0 1
2  | 0 0 2
3  | 0 0 3
4  | 0 1 0
5  | 0 1 1
6  | 0 1 2
7  | 0 1 3
8  | 0 2 0
...
23 | 1 2 3

```

The purpose of this application is to work backwards to determine an index if given a node number.

If asked for the "y" index of the 8th node, the program should print "2".

With the following input provided:

```
{2,3,4}|8|1
<List of Coordinates>|<Node>|<Index>

```

The following should be printed:

```
2

```

You can assume that the input will be provided in some convenient manner in your language of choice and does not require bounds checking. For example you may assume that the provided index of choice ("y" in the example) is valid with respect to the provided coordinates. You may use 0 or 1 based indexing; the example presumes 0 based.

This is sort of the reverse of this question: Index of a multidimensional array

# Answer
> 4 votes
# MATL, 8 bytes

```
PiX[vPi)

```

This uses 1-based indexing for the node and for the dimensions. So the first nodes are `1`, `2` etc; and the "x" dimension is `1`, "y" is `2` etc.

Try it online!

### Explanation

The key is to use function `X[` (corresponding to `ind2sub` in Matlab or Octave), which converts a linear index into multidimensional indices. However, the order of dimensions if the opposite as defined in the challenge, so `P` (`flip`) is needed before calling the function, and again after concatenating (`v`) its ouputs.

```
P    % Implicit input: size as a row vector. Flip
i    % Input: node (linear) index
X[   % Convert from linear index to multidimensional indices. Produces
     % as many outputs as entries there are in the size vector
v    % Concatenate all outputs into a column vector
P    % Flip
i    % Input: dimension
)    % Index: select result for that dimension. Implicitly display

```

# Answer
> 4 votes
# APL (Dyalog Classic), 5 bytes

```
⎕⌷⎕⊤⎕

```

No, you're not missing a font. That's how it's supposed to look.

This is a REPL program that takes input from STDIN: the node number, the dimensions, and the index (in that order). The latter can be 0- or 1-based, depending on the value of `⎕IO`.

Try it online!

### How it works

Multidimensional array indexing is essentially mixed base conversion, so  does what the first part of the challenge asks for. Each occurrence of  reads and evals a line from STDIN, so

```
      ⎕ ⊤ ⎕
⎕:
      8
⎕:
      2 3 4
0 2 0

```

Finally,  takes the element at the specified index. The leftmost  reads the third and last input from STDIN and

```
      ⎕ ⌷ (0 2 0)
⎕:
      1
2

```

# Answer
> 3 votes
# Haskell, 45 bytes

`(#)` takes three arguments and returns an integer, use as `[2,3,4]#8$1`.

```
l#n=(zipWith mod(scanr(flip div)n$tail l)l!!)

```

Try it online!

# How it works

* `l` is the list of coordinates, `n` the node number. `l#n` is a function that takes the final index `i`.
* Given the example list `[2,3,4]` and node `8`, first the list's tail is taken, giving `[3,4]`. Then this is `scan`ned from the `r`ight, `div`iding the node number by each element consecutively, giving the list `[0,2,8]`.
* Then the list `[0,2,8]` and the original `l=[2,3,4]` are `zip`ped `with` the `mod`ulus operator, giving `[0,2,0]`.
* At last the `!!` list indexing operator is partially applied, with the resulting function ready to be given the final index.

# Answer
> 3 votes
## Haskell, ~~38~~ ~~30~~ ~~29~~ 28 bytes

```
l#n=(mapM(\x->[1..x])l!!n!!)

```

This uses 0-based indices and coordinates starting at 1. Try it online!

Turn each dimension `x` of the input into a list `[1..x]`, e.g. `[2,3,4]` -\> `[[1,2],[1,2,3],[1,2,3,4]]`. `mapM` makes a list of all possible n-tuples where the first element is taken from the first list, etc. Two times `!!` to index the n-tuple and dimension.

Edit: @Ørjan Johansen saved ~~8~~ 9 bytes. Thanks!

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

```
tT&bhH&h{>ℕ}ᵐ:H≜ᶠ⁾t:T∋₎

```

Try it online!

The second argument is 1-indexed, the other 2 are 0 indexed.

### Explanation

```
tT                          Input = [_, _, T]
  &bhH                      Input = [_, H, T]
      &h{>ℕ}ᵐ               Create a list where each element is between 0 and the
                              corresponding element in the first element of the Input
             :H≜ᶠ⁾          Find the first H possible labelings of that list
                  t         Take the last one
                   :T∋₎     Output is the T'th element

```

# Answer
> 1 votes
# Jelly, ~~7~~ 6 bytes

```
Œp⁴ị⁵ị

```

Try it online!

This uses 1-indexing for input and output.

## How it works

```
Œp⁴ị⁵ị
Œp      Cartesian product of the first input
        numbers are converted to 1-based ranges
  ⁴ị    index specified by second input
    ⁵ị  index specified by third input

```

# Answer
> 1 votes
# Mathematica, ~~26~~ 23 bytes

```
Array[f,#,0,Or][[##2]]&

```

Using 1-based indexing for input, and 0-based indexing for output.

Why `Or`? Because it is the shortest built-in function with the attribute `Flat`.

Example:

```
In[1]:= Array[f,#,0,Or][[##2]]&[{2,3,4},9,2]

Out[1]= 2

```

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

To get 0-based indexing, `⎕IO←0`, which is default on many systems. Prompts for dimensions, then enclosed list of (node,coordinate).

```
⎕⊃↑,⍳⎕

```

Try it online!

prompt for dimensions

generate an array of that shape with each item being the **i**ndices for that item

`,` ravel (make into list of indices)

convert one level of depth to an additional level of rank

`⎕⊃` prompt for enclosed list of (node,coordinate) and use that to pick an element from that

# Answer
> 0 votes
# Octave, 63 bytes

```
function z=f(s,n,d)
[c{nnz(s):-1:1}]=ind2sub(flip(s),n);z=c{d};

```

Port of my MATL answer.

Try it online!

# Answer
> 0 votes
# Pyth, 12 bytes

```
@.n]@*FUMQEE

```

Try it online!

## How it works

```
@.n]@*FUMQEE
       UMQ    map each element in the first input to
              [0,1,...,that element]
     *F       reduce by Cartesian product
    @     E   obtain index at second input
 .n]          listify and flatten
@          E  obtain index at third input

```

# Answer
> 0 votes
# R, 52 bytes

```
function(x,y,z,n,i)expand.grid(1:z,1:y,1:x)[n,4-i]-1

```

returns an anonymous function, 1-indexed.

for the example. `expand.grid` generates the list, but the first argument varies the fastest, so we have to input them in reverse order, i.e., `z,y,x`. Then we can simply index `[n,4-i]`, where `4-i` is necessary for the reversed order, and subtract 1 to ensure they run from `0:(x-1)`, etc.

Try it online!

# Answer
> 0 votes
# Java, 77 bytes

```
int f(int[]a,int m,int n){for(int i=a.length-1;i>n;m/=a[i--]);return m%a[n];}

```

Try it online!

# Answer
> 0 votes
## JavaScript (ES6), 44 bytes

```
(a,n,i,g=j=>a[++j]?g(j)/a[j]|0:n)=>g(i)%a[i]

```

Ungolfed:

```
(a,n,i)=>a.reduceRight(([n,...a],e)=>[n/e|0,n%e,...a],[n])[i+1]

```

Sadly `reduce` is two bytes longer:

```
(a,n,i)=>a.reduce((r,d,j)=>j>i?r/d|0:r,n)%a[i]

```

# Answer
> 0 votes
# Python 3, 57 bytes

```
lambda a,m,n:f(a[:-1],m//a[-1],n)if len(a)-n else m%a[-1]

```

Try it online!

Fork of my Java answer.

---
Tags: code-golf, math, array
---


title: Make me a password generator!

text:
# Question
Title: Make me a password generator!
I am making a customizable password generator.

But I (for some reason) thought it'd be better to let you guys do it.

---

# Umm.. then?

You only get one integer. That will include all the information about the customization.

The first 4 bits (1,2,4,8) will be used for choosing which charsets will be used.

Each bit corresponds to:

1: Lowercase alphabet(`qwertyuiopasdfghjklzxcvbnm`)

2: Uppercase alphabet(`QWERTYUIOPASDFGHJKLZXCVBNM`)

4: Numbers(`0123456789`)

8: Special chars(All printable characters except ones stated above and the space)

The length of the password will be shifted 4 bits. In other words, multiplied by 16.

Then generate the password with the charsets and the length.

# Examples

```
175 (10*16 + 15 (1111)): a_U0!/h96%

```

# Answer
> 7 votes
# Python 2, ~~217~~ 203 bytes

```
from random import*
r=[10]+range(33,127)
r=[r[65:91],r[33:59],r[16:26],r[:16]+r[26:33]+r[59:65]+r[91:]]
x=input()
l=x>>4
print''.join(map(chr,sample(sum([k[1]for k in enumerate(r)if x&2**k[0]],[])*l,l)))

```

Ugh this is horribly long. The part I think could be golfed the most is the part to get the charsets; that part was a pain.

By the way, I am @HyperNeutrino; I'm just getting enough rep to chat. :P

-14 bytes thanks @ValueInk!
Bug fix thanks to @ovs!

# Answer
> 3 votes
# Stacked, ~~80~~ ~~79~~ 78 bytes

```
:2 tb _4 drop ascii'\' 'modI'toarr+match[''#`]map\keep''#`\16/~~:>$randin~2/"!

```

Try it online! Takes input from the top of the stack and leaves output on the top of the stack. TIO link includes test suite (thingy) for convenience.

# Answer
> 3 votes
## Mathematica 175 Bytes

```
""<>RandomChoice[(j=Join)@@Pick[c~j~{Complement[(r=CharacterRange)[1,127],j@@(c=r@@#&/@{{97,122},{65,90},{48,57}})]},(i=IntegerDigits[#,2])[[-4;;]],1],i[[;;-5]]~FromDigits~2]&

```

Coded pretty much as explained in the question. Seems like rearranging the ASCII table was expensive.

Also, there is a bug in CharacterRange which doesn't allow it to accept 0 as an argument (at least in M10.2, which is what I have handy on my laptop), so to fix that would need another 7 bytes to include the ASCII null character.

# Answer
> 3 votes
# PHP, ~~127~~ 113 bytes

Jörg helped my tired brain with 10-2 bytes and I found another 2+4.

```
for(;$i<$argn>>4;$c=chr(rand()))foreach([lower,upper,digit,punct]as$t=>$f)$argn>>$t&(ctype_.$f)($c)&&$i+=print$c;

```

**breakdown**

Run as pipe with `php -nR '<code>'`.

```
// loop while length not reached
for(;$i<$argn>>4;
    // pick random character
    $c=chr(rand())
)
    // loop through bits and functions
    foreach([lower,upper,digit,punct]as$t=>$f)
        // if test is positive, increment length counter and print character
        $argn>>$t&(ctype_.$f)($c)&&$i+=print$c;

```

Neat tricks:
The `ctype` functions return `false` on failure (resulting in `$argn>>$t&0`, so the bit is irrelevant);
`true` on success (resulting in `$argn>>$t&1`, i.e. a test on bit `$t`).
If that test fails, short circuit kicks in and the character is skipped.
If it is positive, `$i` will be increased by the return value of `print` (always `1`).

# Answer
> 2 votes
# Japt, ~~93~~ 78 bytes

*Saved 15 bytes thanks to ETHproductions*

```
;>>4 o_=ApU&1©CU&2©BU&4©9o U&8©Q+"\{|}\\!#$%&'()*+,-.:;<=>?@[]^_`" f q)gMqZlÃq

```

Try it online!

# Answer
> 2 votes
# Python 2, 180 bytes

```
lambda x,r=[10]+range(33,127):''.join(chr(choice(r[65:91]*(x&1)+r[33:59]*(x&2>0)+r[16:26]*(x&4>0)+(r[:16]+r[26:33]+r[59:65]+r[91:])*(x&8>0)))for i in' '*(x>>4))
from random import*

```

Try it online!

# Answer
> 0 votes
# Jelly, 54 bytes

```
ØBUð,ø33r126µFỌQðṁø“ııµþ’b250Rðị@ø³%16b2UTµF
¢XȮµ:⁴’µ¡

```

Try it online!

**Explanation**

```
ØBUð,ø33r126µFỌQðṁø“ııµþ’b250Rðị@ø³%16b2UTµF  - nilad which returns charset
ØB                                            - yield alphanumeric characters
  U                                           - reverse to get proper order
   ð,ø33r126                                  - append char values of printable characters
            µFỌQ                              - flatten and remove repeats to get "z-aZ-A9-0[specials]"
                ðṁø                           - mold this string like ...
                   “ııµþ’b250                 - literal [26,26,10,32]
                             R                - [26R,26R,10R,32R]. All that matters is the length of each sublist.
                              ðị@             - get the elements numbered ...
                                 ³%16b2UT     - those indices we want based on the last 4 bits of the input.

¢XȮµ:⁴’µ¡ - monad with input a
 X        - pick a random element from ...
¢         - the above charset.
  Ȯ       - Print it.
        ¡ - Repeat this ...
    µ:⁴’  - floor(a/16)-1 times. (⁴ is literal 16).

```

---
Tags: code-golf, random
---


title: Triangle and/or Square?

text:
# Question
Title: Triangle and/or Square?
# Explanation of the challenge

Given an input, return what shapes it could be. There are only a couple options.

1. Square
2. Triangle

---

**Square**

A square is in the following format:

```
XXXX
XXXX
XXXX
XXXX

```

So, in this example, the input would be:

```
16

```

And the output would be:

```
1 or "Square"

```

**Triangle**

We are only checking for equilateral triangles:

```
   X
  X X
 X X X
X X X X

```

So, in this example, the input would be:

```
10

```

And the output would be:

```
2 or "Triangle"

```

---

# Rules for input and output

Input must be a number.

Output can be an integer list or string list as long as you specify how your output works in your post. The output will be either a **triangle, square, or both**; never neither.

---

# Test Cases

```
36 ->  1,2 or 3 or ["Square","Triangle"] or "Both"

15 ->  2 or "Triangle"

4  ->  1 or "Square"

```

---

# Leaderboard

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

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

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

# Answer
# Jelly, ~~9~~ 7 bytes

```
×8‘,µÆ²

```

Try it online!

Outputs \[1,1\] for both, \[0,1\] for square, \[1,0\] for triangle, \[0,0\] for neither.

**Explanation**

```
×8‘,µÆ² - main link, input a
   ,    - a list of the following two:
×8‘     - a×8+1 (which is square when a is triangle)
        - (implicit) a
    µÆ² - On the previous, check if each is a square

```
> 4 votes

# Answer
# Japt, ~~18 15~~ 11 bytes

```
[U8*UÄ]®¬v1

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES7), ~~40~~ 32 bytes

Returns 1 for square, 2 for triangle, 3 for both or 0 for neither.

```
n=>!(n**.5%1)+2*!((8*n+1)**.5%1)

```

---

## Try It

Displays "Square/Triangle/Both/Neither" for clarity

```
f=
n=>!(n**.5%1)+2*!((8*n+1)**.5%1)
i.addEventListener("input",_=>o.innerText=["Neither","Square","Triangle","Both"][f(+i.value)])
```

```
<input id=i type=number><pre id=o>
```
> 4 votes

# Answer
# Haskell, ~~49~~ ~~48~~ 37 bytes

EDIT:

* -1 byte: @xnor suggested parametrizing on `k`.
* -11 bytes: And then turned it all inside out...

`f` takes an integer and returns a list: `[3]` for square, `[2]` for triangle, and `[2,3]` for both (or `[]` for neither.)

```
f n=[k|k<-[2,3],0<-scanl(-)n[1,k..n]]

```

Try it online!

This uses that triangular numbers are sums `1+2+3+4+...+i` while square numbers are sums `1+3+5+7+...+i`, thus by starting with `n` and using `scanl(-)` to subtract either the range `[1,2..n]` or the range `[1,3..n]` consecutively, each of those cases will eventually hit 0.
> 3 votes

# Answer
# TI-BASIC, ~~30~~ 23 bytes

-7 for more flexible output requirements.

```
:Prompt X         //Get input
:{√(X),.5+√(2X+.5 //Compute the square root of X, and the inverse of the triangular number function: X(X-1)/2
:Ans=int(Ans      //Create a list of booleans for whether the values are whole or not, then print

```

Takes input as an iteger.

This returns a list of integers, either `0` or `1`, first for being square, then for being triangular.
> 2 votes

# Answer
# Pyth - 16 bytes (possibly 13)

```
+*2sI@Q2sI@h*8Q2

```

Prints 2 if square, 1 if triangle, 3 if both, 0 if neither

Try it

Also, ~~19~~ ~~18~~ 17

```
sI@Q2sI@h*8Q2

```

The first line is 1 if the number is square, 0 if not. The 2nd line is 1 if number is triangle, 0 if not.

Try it
> 2 votes

# Answer
# Ohm, ~~15~~ 7 bytes

```
D8*≥«Æ²

```

Try it online!

**EDIT**: Saved 8 bytes thanks to this Jelly answer.

Outputs `[true, true]` if square and triangle, `[true, false]` for square, and `[false, true]` for triangle.

Explanation:

```
D8*≥«Æ²  Main wire, input integer a

D        Duplicate input
 8*≥     Multiply duplicate by 8, increment
    «    Pair
     Æ²  Check if perfect square

```
> 2 votes

# Answer
# PHP, 67 bytes

Returns 2 for square, 1 for triangle, 3 for both and 0 for none

```
<?=(($q=sqrt($i=$argn))==($q^0))*2+(2*$i==($x=sqrt(2*$i)^0)*$x+$x);

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES7), 52 bytes

Returns `1` for square, `2` for triangle, `3` for both (and `0` for none, although irrelevant).

```
f=(n,t=0,s=(n**.5|0)**2==n)=>t<n?f(n-++t,t,s):2*!n|s

```

### Demo

```
f=(n,t=0,s=(n**.5|0)**2==n)=>t<n?f(n-++t,t,s):2*!n|s

console.log(f(7))
console.log(f(15))
console.log(f(25))
console.log(f(36))
```
> 1 votes

# Answer
# Python 3, ~~49~~ 42 bytes

```
lambda i:(i**.5%1==0)+2*((1+8*i)**.5%1==0)

```

Returns:

* 1 for Triangle
* 2 for Square
* 3 for Both
> 1 votes

# Answer
# MATL, ~~11~~ 10 bytes

```
t:UmGt:Ysm

```

Outputs two values `0` or `1` separated by newline. The first indicates if the input is square, and the second indicates if it is triangular.

Try it online!

### Explanation

Consider input `4` as an example.

```
t     % Implicit input. Duplicate
      % STACK: 4, 4
:     % Range
      % STACK: 4, [1 2 3 4]
U     % Square, elementwise. This gives square numbers
      % STACK: 4, [1 4 9 16]
m     % Ismember
      % STACK: 1
Gt    % Push input again. Duplicate
      % STACK: 1, 4, 4
:     % Range
      % STACK: 1, 4, [1 2 3 4]
Ys    % Cumulative sum. This gives triangular numbers
      % STACK: 1, 4, [1 3 6 10]
m     % Ismember. Implicitly display
      % STACK 1, 0

```
> 1 votes

# Answer
# Python 2, 39 bytes

```
lambda n:[`x**.5%1==0`for x in 8*n+1,n]

```

Try it online!

Outputs like `["True", "False"]` for triangle then square. Probably could be shorter if allowed output format is clarified.
> 1 votes

# Answer
## Batch, 120 bytes

```
@set/ar=i=j=k=0
:g
@if %j%==%1 set/ar+=1
@if %k%==%1 set/ar+=2
@set/aj+=i+=1,k=i*i
@if %j% leq %1 goto g
@echo %r%

```

Outputs 1 for triangular numbers, 2 for squares, 3 for both, 0 for neither.
> 1 votes

# Answer
## Retina, 25 bytes

```
*M`(^1|1\1)+$
(^1|11\1)+$

```

Takes input in unary, outputs `t` and `s` on separate lines, where `t` and `s` are `0` or `1` indicating whether the shape is a triangle and/or square, respectively.

Try it online! (Contains an additional `\` to put both outputs on the same line to make the test cases more easily distinguishable.)

### Explanation

Triangular numbers are the sums of consecutive integers starting from one. Square numbers are the ums of consecutive odd integers starting from one. Both of those are fairly easy to match with forward references.

```
*M`(^1|1\1)+$

```

This prints 0 or 1 depending on whether the given regex matches, but it doesn't actually modify the string (the `*` indicates a dry run). The regex either matches the initial one with `^1` or it matches exactly one more `1` than in the previous iteration with `1\1` (the `\1` refers to what `(^1|1\1)` matched last time).

```
(^1|11\1)+$

```

This is basically the same, except that we don't need a dry run and `M` is implicit. To go up by odd integers instead of all integers, we simply add two `1`s on each iteration with `11\1`.
> 1 votes

# Answer
## C#, 61 bytes

```
s=n=>System.Math.Sqrt(n)%1==0;n=>(s(n)?1:0)+(s((8*n)+1)?2:0);

```

Could be a lot shorter if there was (or I knew) an alternative to `System.Math.Sqrt`.

Formatted version with test cases:

```
Func<int, bool> s = n => System.Math.Sqrt(n) % 1 == 0;

Func<int, int> f = n => (s(n) ? 1 : 0) + (s((8 * n) + 1) ? 2 : 0);

Console.WriteLine(f(36));
Console.WriteLine(f(15));
Console.WriteLine(f(4));
Console.WriteLine(f(2));

```
> 1 votes

# Answer
# Python 3, ~~72~~ 67 bytes

```
x=input()
k=int((x*2)**.5)
print((x==int(x**.5)**2)+2*(2*x==k*k+k))

```

A bit longer than wanted. This is a full program that takes input from STDIN and outputs to STDOUT. STDERR should be empty as long as there isn't an I/O Exception and the input isn't invalid.
> 0 votes

# Answer
# Octave, 38 bytes

```
@(x)~mod(x^.5,1)+2*any(x==cumsum(1:x))

```

Outputs `1` for square, `2` for triangular, `3` for both, `0` for neither.

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Rational decomposition

text:
# Question
Title: Rational decomposition
Write functions \\$x(a)\\$, \\$y(a)\\$ and \\$z(a)\\$ such that for any rational \\$a\\$ **all functions return rational numbers** and

$$x(a) \times y(a) \times z(a) \times (x(a) + y(a) + z(a)) = a$$

You may assume \\$a \ge 0\\$

You do not need to use rational types or operations in your program, as long as your program is mathematically sound. E.g. if you use a square root in your answer you must show that its argument is always a square of a rational number.

You may write three named functions `x`, `y`, `z` or write three programs instead if functions are cumbersome or non-existent for your language. Alternatively you may also write a single program/function that returns three numbers \\$x\\$, \\$y\\$, \\$z\\$. Finally, if you so prefer you may input/output the rational numbers as a numerator/denominator pair. Your score is the total size of the three functions or three programs in bytes. Smallest score wins.

Brute forcing is not allowed. For any \\$a = \frac p q\\$ where \\$p, q \le 1000\\$, your program should run in under 10 seconds.

---

An example (this does not mean your decomposition has to give these numbers):

```
x = 9408/43615
y = 12675/37576
z = 1342/390
x*y*z*(x+y+z) = 1

```

# Answer
> 11 votes
## CJam (59 bytes)

```
{[WZ~C24X8TT]f*[4XGYC6 4Y].+_0=!>2%Z65135Zb+:(3/.f#:.*)W*+}

```

This is an anonymous block (function) which takes an integer or double on the stack and produces an array with three doubles. It has two cases internally to handle all non-negative inputs, since with only one case it would break on either `0.25` or `4`. It still breaks for inputs `-12` and `-1.3333333333333333`, but the spec allows that...

The online demo executes it and then adds up the values, prints all four, and multiplies them to show that it gets the original value (modulo rounding error).

### Mathematical background

Following Noam Elkies we define the auxiliary \\$w = - x - y - z\\$. Then \\$x + y + z + w = 0\\$ and \\$-xyzw = a\\$ or \\$xyzw + a = 0\\$. This has lots of symmetry; any solution will have four formulae and we can pick the three golfiest ones.

Elkies gives four families of sets of solutions. Euler's:

$$\begin{eqnarray\*} x & = & \frac{6ast^3(at^4-2s^4)^2}{(4at^4+s^4)(2a^2t^8 + 10as^4t^4 - s^8)} \\ y & = & \frac{3s^5(4at^4+s^4)^2}{2t(at^4-2s^4)(2a^2t^8+10as^4t^4-s^8)} \\ z & = & \frac{2(2a^2t^8+10as^4t^4-s^8)}{3s^3t(4at^4+s^4)} \\ w & = & \frac{-(2a^2t^8+10as^4t^4-s^8)}{6s^3t(at^4-2s^4)} \end{eqnarray\*}$$

One related to Euler's:

$$\begin{eqnarray\*} x & = & \frac{(8s^8+a^2)(8s^8-88as^4-a^2)}{12s^3(s^4-a)(8s^8+20as^4-a^2)}\\ y & = & \frac{(8s^8+a^2)(8s^8-88as^4-a^2)}{12s^3(8s^4+a)(8s^8+20as^4-a^2)}\\ z & = & \frac{192as^5(s^4-a)^2(8s^4+a)^2}{(8s^8+a^2)(8s^8-88as^4-a^2)(8s^8+20as^4-a^2)}\\ w & = & \frac{-3s(8s^8+20as^4-a^2)^3}{4(s^4-a)(8s^4+a)(8s^8+a^2)(8s^8-88as^4-a^2)}\\ \end{eqnarray\*}$$

A simpler one:

$$\begin{eqnarray\*} x & = & \frac{(s^4-4a)^2}{2s^3(s^4+12a)} \\ y & = & \frac{2a(3s^4+4a)^2}{s^3(s^4-4a)(s^4+12a)} \\ z & = & \frac{s^5+12as}{2(3s^4+4a)} \\ w & = & \frac{-2s^5(s^4+12a)}{(s^4-4a)(3s^4+4a)} \\ \end{eqnarray\*}$$

And one related to that one:

$$\begin{eqnarray\*} x & = & \frac{s^5(s^4-3a)^3}{2(s^4+a)(s^{12}+12as^8-3a^2s^4+2a^3)} \\ y & = & \frac{s^{12}+12as^8-3a^2s^4+2a^3}{2s^3(s^4-3a)(3s^4-a)} \\ z & = & \frac{2a(s^4+a)^2(3s^4-a)^2}{s^3(s^4-3a)(s^{12}+12as^8-3a^2s^4+2a^3)} \\ w & = & \frac{-2s(s^{12}+12as^8-3a^2s^4+2a^3)}{(s^4-3a)(s^4+a)(3s^4-a)} \end{eqnarray\*}$$

Observe that every family has at least two denominators of the form \\$ps^4 - qa\\$ for positive \\$p\\$ and \\$q\\$: since all the terms involved are rational, that means that there's some positive \\$a\\$ for which we get division by zero. Therefore we must use at least two sets of solutions which have their singularities at different values of \\$a\\$. Intuitively it's going to be golfiest to choose two sets from the same family. I've chosen the simplest family (the third one) with parameters \\$s=1\\$ and \\$s=2\\$.

# Answer
> 1 votes
# Axiom, 191 bytes

```
f(s,a)==(b:=s^4-4*a;c:=s^4+12*a;x:=3*s^4+4*a;[b^2/(2*c*s^3),2*a*x^2/(b*c*s^3),s*c/(2*x)])
g(a:FRAC INT):List FRAC INT==(s:=1;repeat(s^4=4*a or s^4=-12*a or 3*s^4=4*a=>(s:=s+1);break);f(s,a))

```

It is the traslation of the formula Peter Taylor report in this page with some code would make the denominators not be 0. one test

```
(7) -> y:=g(1)
          9   98 13
   (7)  [--,- --,--]
         26   39 14
                                              Type: List Fraction Integer
(8) -> y.1*y.2*y.3*(y.1+y.2+y.3)
   (8)  1
                                              Type: Fraction Integer

```

---
Tags: code-golf, math, rational-numbers, open-ended-function
---


title: Implement Euler's method

text:
# Question
Title: Implement Euler's method
The goal of this challenge is to use Euler's method to approximate the solution of a differential equation of the form f(n)(x) = c.

The input will be a list of integers in which the *n*th value represents the value of f(n)(0). The first integer is f(0), the second is f'(0), and so on. The last integer in this list is the constant and will always remain the same.

Also provided as input will be a positive (nonzero) integer *x*, which represents the target value (you are trying to estimate f(x)). The step size for Euler's method will always be 1. Thus, you will need to take *x* steps total.

If you are unfamliar with Euler's method, here is a detailed example with an explanation for the input `[4, -5, 3, -1]`, *x* = 8.

```
x       f(x)      f'(x)     f''(x)    f'''(x)
0          4         -5          3         -1
1   4-5 = -1  -5+3 = -2   3-1 =  2         -1
2  -1-2 = -3  -2+2 =  0   2-1 =  1         -1
3  -3+0 = -3   0+1 =  1   1-1 =  0         -1
4  -3+1 = -2   1+0 =  1   0-1 = -1         -1
5  -2+1 = -1   1-1 =  0  -1-1 = -2         -1
6  -1+0 = -1   0-2 = -2  -2-1 = -3         -1
7  -1-2 = -3  -2-3 = -5  -3-1 = -4         -1
8  -3-5 = -8

```

Essentially, each cell in the generated table is the sum of the cell above it and the cell above and to the right. So, f(a) = f(a-1) + f'(a-1); f'(a) = f'(a-1) + f''(a-1); and f''(a) = f''(a-1) + f'''(a-1). The final answer is f(8) ≈ -8.††

The input list will always contain 2 or more elements, all of which will have absolute values less than 10. *x* ≥ 1 is also guaranteed. The output is a single integer, the approximation of f(x). Input may be taken in either order (the list before *x*, or *x* before the list). *x* may also be the first or last element of the list, if desired.

Test cases:

```
[4, -5, 3, -1], x = 8 => -8
[1, 2, 3, 4, 5, 6], x = 10 => 3198
[1, 3, 3, 7], x = 20 => 8611
[-3, 3, -3, 3, -3, 3, -3, 3, -3], x = 15 => -9009
[1, 1], x = 1 => 2

```

---

†: it is notable that using an approximation method in this situation is, in fact, stupid. however, the simplest possible function was chosen for the purposes of this challenge.

††: the *actual* value happens to be -25⅓, which would qualify this approximation as "not very good."

# Answer
> 3 votes
# Haskell, 38 bytes

```
l%n|n<1=l!!0|m<-n-1=l%m+tail(l++[0])%m

```

Try it online!

Improved from 39 bytes:

```
l%0=l!!0
l%n=l%(n-1)+tail(l++[0])%(n-1)

```

Recursively expresses the output `l%n`. Moving up corresponds to decrementing `n`, and moving right corresponds to taking `tail l` to shift all list elements one space left. So, the output `l%n` is the value above `l%(n-1)`, plus the value above and to the right `(tail l)%(n-1)`

The base case `n==0` is to take the first list element.

Ideally, the input would be padded with infinitely many zeroes to the right, since the derivatives of a polynomial eventually become zero. We simulate this by appending a `0` when we take the `tail`.

Weird alt 41:

```
(iterate(\q l->q l+q(tail l++[0]))head!!)

```

# Answer
> 3 votes
# MATL, 9 bytes

```
:"TTZ+]1)

```

Try it online! Or verify all test cases.

### Explanation

```
:"      % Implicitly input x. Do the following x times
  TT    %   Push [1 1]
  Z+    %   Convolution, keeping size. Implicitly inputs array the first time
]       % End
1)      % Get first entry. Implictly display

```

# Answer
> 3 votes
# Jelly, ~~6~~ 5 bytes

```
Ḋ+$¡Ḣ

```

Try it online!

*-1 byte thanks to @Doorknob*

**Explanation**

```
Ḋ+$¡Ḣ  - Main dyadic link. First input list, second x
       - (implicit) on the previous iteration (starting at input list)
Ḋ      - Dequeue. e.g. [-5,3,-1]
 +     - Add this to
       - (implicit) the previous iteration. e.g. [4+(-5),-5+3,3+(-1),-1+0]
  $¡   - apply this successively x times
    Ḣ  - get the first element from the resultant list

```

# Answer
> 3 votes
# Brachylog, ~~13~~ 12 bytes

```
{,0s₂ᶠ+ᵐ}ⁱ⁾h

```

Try it online!

## How it works

```
{,0s₂ᶠ+ᵐ}ⁱ⁾h
{       }ⁱ⁾   iterate the previous predicate
              to the array specified by first element of input
              as many times as the second element of input
           h  and get the first element

              example input to predicate: [4, _5, 3, _1]
 ,0           append 0: [4, _5, 3, _1, 0]
   s₂ᶠ        find all substrings with length 2:
              [[4, _5], [_5, 3], [3, _1], [_1, 0]]
      +ᵐ      "add all the elements" mapped to each subarray:
              [_1, _2, _2, _1]

```

## Previous 13-byte solution

```
{b,0;?z+ᵐ}ⁱ⁾h

```

Try it online!

### How it works

```
{b,0;?z+ᵐ}ⁱ⁾h
{        }ⁱ⁾   iterate the previous predicate
               to the array specified by first element of input
               as many times as the second element of input
            h  and get the first element

               example input to predicate: [4, _5, 3, _1]
 b             remove the first element: [_5, 3, _1]
  ,0           append 0: [_5, 3, _1, 0]
    ;?         pair with input: [[_5, 3, _1, 0], [4, _5, 3, _1]]
      z        zip: [[_5, 4], [3, _5], [_1, 3], [0, _1]]
       +ᵐ      "add all the elements" mapped to each subarray:
               [_1, _2, _2, _1]

```

# Answer
> 2 votes
## Mathematica, 32 bytes

```
#&@@Nest[#+Rest@#~Append~0&,##]&

```

```
                               &  make a pure function
    Nest[                 &,##]   call inner function as many times as specified
           Rest@#                 drop the first element of the list
                 ~Append~0        and add a 0 to get [b,c,d,0]
         #+                       add original list to get [a+b,b+c,c+d,d]
#&@@                              take the first element after x iterations

```

# Answer
> 2 votes
# Python, 80 58 bytes

Love the math for this challenge.

```
f=lambda a,x:x and f(map(sum,zip(a,a[1:]+[0])),x-1)or a[0]

```

How it works (only works with python 2):

```
f=lambda a,x:                                              - new lambda function
             x and                                         - iterate itself x times
                     map(sum,zip(a,a[1:]+[0]))             - e.g; f(a) = f(a-1) + f'(a-1)
                   f(                         ,x-1)        - iterate new array into itself
                                                   or a[0] - return first element

```

Try it online!

**100 byte alternate with use of pascals triangle**

```
from math import factorial as F
f=lambda a,x:sum([(a+[0]*x)[i]*F(x)/(F(x-i)*F(i))for i in range(x)])

```

How it works (works for python 2 and 3):

```
sum([                                                ]) - take the sum of array
     (a+[0]*x)                                        - append x zeros
              [i]*F(x)/(F(x-i)*F(i))                  - multiply each element by x choose i
                                    for i in range(x) - do this for every element

```

This formula works by mapping the coefficients of row `x` of pascals triangle onto the array. Each element of pascals triangle is determined by the choose function of the row and index. The sum of this new array is equivalent to the output at `x`. It's also intuitive as the iterated process of newtons method (shown in the example) acts exactly as the construction of pascals triangle.

Try it online!

Big thanks to ovs for reducing 22 bytes by converting loop into a recursive function

# Answer
> 1 votes
## Haskell, ~~52~~ 45 bytes

```
l#n=iterate(zipWith(+)=<<tail.(++[0]))l!!n!!0

```

Usage example: `[-3,3,-3,3,-3,3,-3,3,-3] # 15` -\> `-9009`. Try it online!

How it works

```
iterate(      )l          -- apply the function again and again starting with l
                          -- and collect the intermediate results in a list
                          -- the function is
          (++[0])         -- append a zero
  zipWith(+)=<<tail       -- and build list of neighbor sums
                     !!0  -- take the first element from
                  !!n     -- the nth result

```

Edit: @xnor saved 7 bytes. Thanks!

# Answer
> 1 votes
# CJam, 12 bytes

```
q~{_(;.+}*0=

```

Try it online!

### Explanation

The code directly implements the procedure described in the challenge.

```
q~            e# Read input and evaluate. Pushes the array and the number x
  {     }*    e# Do the following x times
   _          e# Duplicate array
    (;        e# Remove first element
      .+      e# Vectorized sum. The last element in the first array, which doesn't
              e# have a corresponding entry in the second, will be left as is
          0=  e# Get first element. Implicitly display

```

# Answer
> 1 votes
# Octave, 42 bytes

```
@(a,x)conv(a,diag(flip(pascal(x+1))))(x+1)

```

This defines an anonymous function. Try it online!

### Explanation

The solution could be computed by repeatedly convolving the input array and the resulting arrays with `[1, 1]`. But convolving twice, or thrice, or ... with `[1, 1]` corresponds to convolving once with `[1, 2 ,1]`, or `[1, 3, 3, 1]`, or ...; that is, with a row of the Pascal triangle. This is obtained as the anti-diagonal of the Pascal matrix of order `x+1`.

# Answer
> 1 votes
# Pyth, 10 bytes

```
s.e*b.cQkE

```

Test suite.

## How it works

```
s.e*b.cQkE
 .e      E   for (b,k) in enumerated(array):
     .cQk        (input) choose (k)
   *b            * b
s            sum

```

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

```
{0=⍺:⊃⍵
(⍺-1)∇(+/¨2,/⍵),¯1↑⍵}

```

Try it online!

This is a recursive dfn, but it turns out to be too verbose. Golfing in progress...

# Answer
> 1 votes
# Actually, 7 bytes

```
;lr(♀█*

```

Try it online!

## How it works

```
;lr(♀█*  input:
         8, [4, -5, 3, -1]
         top of stack at the right
;        duplicate
         8, [4, -5, 3, -1], [4, -5, 3, -1]
 l       length
         8, [4, -5, 3, -1], 4
  r      range
         8, [4, -5, 3, -1], [0, 1, 2, 3]
   (     rotate stack
         [4, -5, 3, -1], [0, 1, 2, 3], 8
    ♀█   map "n choose r"
         [4, -5, 3, -1], [1, 8, 28, 56]
      *  dot product
         -8

```

# Answer
> 0 votes
## JavaScript (ES6), 41 bytes

```
f=(a,x,[b,...c]=a)=>x--?f(a,x)+f(c,x):b|0

```

Port of @xnor's excellent Haskell answer. Previous 47-byte solution.

```
f=(a,x)=>x--?f(a.map((e,i)=>e+~~a[i+1]),x):a[0]

```

# Answer
> 0 votes
# Python 3 with Numpy, 82 bytes

```
import numpy
def f(a,x):
 for n in range(x):a=numpy.convolve(a,[1,1])
 return a[x]

```

Similar to my MATL answer, but using full-size convolution, and thus the result is the `x`-th entry of the final array.

Try it online!

# Answer
> 0 votes
# Python, 51 bytes

```
f=lambda l,n:n and f(l,n-1)+f(l[1:]+[0],n-1)or l[0]

```

Try it online!

This is a port of my Haskell answer.

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


# Question
Title: What would your reputation be without the rep cap?
In this challenge, you will calculate what your reputation would be, if the reputation cap didn't exist on PPCG.

Everyone can access the rawdata for reputation changes on the adress: codegolf.stackexchange.com/reputation. The raw data follows a setup like this (these are the first few lines of my version of the page.

```
total votes: 2955
-- bonuses   (100)
 2     37663 (10)
-- 2014-09-11 rep +110  = 111
 2     41751 (10)
-- 2014-11-23 rep +10   = 121
 2     41751 (10)
 2     41751 (10)
-- 2014-11-24 rep +20   = 141

```

The first line is irrelevant for this challenge (it shows the total number of votes you have received on all your answers and questions). The second line shows the "Association bonus". If you don't have the bonus then that line will not be there at all.

After these two (or one, if no bonus) lines, you'll have a list of reputation changes per question, along with a summary of all the rep gained/lost on each day. You'll also get a list of the total reputation you have at the end of that day. Only days where your reputation changed are shown in this list.

There are identifiers in the beginning of each line (except the daily summary lines). These represent the following potential reputation change reasons:

```
1 : Accept (+2 if you accept, +15 if your answer is accepted)
2 : Upvote (+5 for question, +10 for answer)
3 : Downvote (-1 if you downvote answer, -2 if you get downvoted)
4 : Offensive (-100)
8 : Give bounty
9 : Receive bounty
12: Spam (-100)
16: Approved edit (+2)

```

The missing numbers (`5,6,7,10,11,13,14,15` don't affect reputation).

---

## Your challenge is to calculate the reputation you would have, if it weren't for the reputation cap.

---

**How you'll do this:**

Save the content of `codegolf.stackexchange.com/reputation` as plain text locally, or some other place of your choosing (this is because you need to be logged in to access the information). You may retrieve the data from the website directly if you prefer, although I assume that will be a lot longer.

Sum up all the positive and negative reputation changes. Votes that doesn't result in a reputation change (due to the rep cap) are shown like this (notice the square brackets, instead of regular parentheses):

```
 2    106125 [0]
 2    106125 [0]
 3    106125 [-2]
 2    106088 [2]
 2    106125 [0]
 2    106088 [0]

```

*You must include the rep you would have received if it wasn't for the cap.*

Post number `106125` is a question, while `106088` is an answer. As you can see, there's no way to tell the difference between the two using only the data given in the table. You must therefore access the website (`codegolf.stackexchange.com`) to check whether a post is a question or answer. You may also use the API for this.

---

**Rules:**

* Everyone must be able to run your script so:
    + You must include all the different reputation change types, even if you haven't encountered it yourself.
    + The code must work even if you haven't received the Association bonus (the line won't be there if you haven't)
    + You may use non-free languages (Mathematica, MATLAB etc.), as long as others with a license can run the code.
    + You do not have to provide the raw-data, since everyone can test your code on their own version of the page (it will be interesting if you share the results though, but that's optional).
* You may use the API or access the website directly. url-shorteners are not allowed.
* If there are other ways to find the rep you would have without the rep cap then you can't use it. You have to use the data from the mentioned page.

Note that posts that are answers get a different extension to the url:

```
https://codegolf.stackexchange.com/questions/106088        // Answer: Notice the end of the url
https://codegolf.stackexchange.com/questions/106079/detect-ms-windows/106088#106088

https://codegolf.stackexchange.com/questions/106079/       // Question: Notice the end of the url
https://codegolf.stackexchange.com/questions/106079/detect-ms-windows

```

**Output:**

The output should be:

```
Rep w cap: 15440
Rep w/o cap: 16202

```

The format is optional, `[15440,16202]` is accepted. `Rep w cap` can be taken directly from the line: `** total rep 15440 :)` near the bottom of the page.

---

This is so the shortest code in byte wins.

# Answer
# Perl 5 (+ `curl`), 209 +1 (`-n` flag) = 210 bytes

```
if(/([0-9]+)\s*([0-9]+) \[([0-9]*)/){$_=`curl https://codegolf.stackexchange.com/a/$2`;@p=(2,5,-1);$p[15]=2;@s=(13,5,-1);$x=$1;$r+=($p[--$x]//-100)-$3;$r+=$s[$x]if/#/;};$t=$1 if/([0-9]+) :/;END{say$t,$",$r+$t}

```

Abuses the fact that the url for an answer has a `#` in it. Can add a `-s` flag after `curl` if you don't like stderr being flooded with progress bars. I would appreciate someone with a more varied reputation page testing it- I can't be sure I didn't miss anything.

Mine is 421 and would be 451, by the way.
> 4 votes

---
Tags: code-golf, parsing, internet, stack-exchange-api
---


title: Better late than never!

text:
# Question
Title: Better late than never!
Your program / function, etc. will take 2 inputs. The first will be a list of who came to my party and when. Example:

```
Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12

```

What does that mean? It means that Kevin got to my party first (at 13:02, 24-hour time), then Ruby 5 minutes later, then Sam 3 minutes later, then Lisa 6 minutes later, and last Bob 12 minutes later.

The second input will be when my party started. Example:

```
13:15

```

(24-hour time). Your output must be the list of people who *were late.* (Anyone exactly on time is fine.) Example calculations (just for example, don't output these)

```
Kevin 13:02
Ruby 13:07
Sam 13:10
Lisa 13:16
Bob 13:28

```

Lisa and Bob arrived after `13:15`, therefore this program should print "Lisa,Bob".

# Input assumptions

* Input 1 will always be a name (regex `[A-Z][a-z]*`), then a space, then a 24-hour time in the form `hours:minutes` on the first line, then a name, a space, and a positive integer (number of minutes later) on the next lines. There will always be at least 1 line.
* If you would like, you may take input 1 with any other character instead of a line break.
* Input 2 will be in the format `hours:minutes`.
* You may take your inputs as one string separated by any character if you want. This is optional.
* Don't worry about day crossover. My parties never to after `23:59`.

# Output rules

* Output can be a function return value or a string echoed to STDIN, a file, etc. You must return a string or an array / list.
    + If you return a string, it must be each person who was late (order does not matter), separated by any non-alphanumeric delimiter.
    + If you return an array / list, it must be a list of everyone who was late.

# Answer
# MATL, 31 bytes

```
jYb1L&)1&)XUYs1440/0whwYO+jYO>)

```

The first input uses space instead of line break (allowed by the challenge).

Output uses line break as separator.

Try it online!

### Explanation

```
j       % Input first string
Yb      % Split at spaces. Gives cell array of strings
1L&)    % Separate into subarrays with odd and even indices. Odd are names, even
        % are time and increments in minutes
1&)     % Separate the subarray of even indices into first entry and remaining
        % entries. The first is a string representing the time of first arrival,
        % the rest are strings representing increments in minutes
XU      % Convert strings representing increments into the actual numbers
Ys      % Cumulative sum
1440/   % Divide by 1440 (number of minutes in a day)
0wh     % Prepend a 0
w       % Swap. Bring the string with time of first arrival to the top
YO      % Convert to serial date number. Fractional part indicates time
+       % Add. This gives all arrivals as serial date numbers
j       % Input second string
YO      % Convert to serial date number
>       % Less than?, element-wise
)       % Index: select the names for which the comparison gave true
        % Implicitly display

```
> 2 votes

# Answer
## JavaScript (ES6), ~~98~~ 97 bytes

*Saved 1 byte thanks to Neil*

Takes the list of guests `l` and the party time `h` in currying syntax `(l)(h)`. Expects a trailing linebreak on the list. Returns a space-separated list of names such as `Lisa Bob`.

```
l=>h=>l.replace(/(.* )(.*)\n/g,(_,a,b)=>(t-=T(b))<0?a:'',t=(T=h=>eval(h.replace(/:/,'*60+')))(h))

```

### Formatted and commented

```
l => h =>                         // given a list of guests l and a party time h
  l.replace(                      // for each guest in l:
    /(.* )(.*)\n/g,               //   extract the name a and arrival time b
    (_, a, b) =>                  //   subtract the arrival time from the time counter
      (t -= T(b)) < 0 ?           //   if the result is negative:
        a                         //     the guest is late: keep the name
      :                           //   else:
        '',                       //     the guest is on time: remove this entry
    t = (                         //   initialize the time counter t
      T = h =>                    //   define T():
        eval(                     //     a function that takes either a time
          h.replace(/:/, '*60+')  //     in hh:mm format or an amount of minutes
        )                         //     and returns an amount of minutes
    )(h)                          //   call it with the party time
  )                               // end of replace()

```

### Demo

```
let f =

l=>h=>l.replace(/(.* )(.*)\n/g,(_,a,b)=>(t-=T(b))<0?a:'',t=(T=h=>eval(h.replace(/:/,'*60+')))(h))

console.log(f(`Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
`)('13:15'))
```
> 5 votes

# Answer
# PHP, ~~118 98 95~~ 91 bytes

```
while($n=$argv[++$i])$i&1?$p=$n:($t=($f=strtotime)($n)?:$t+60*$n)<=$f(end($argv))?:print$p;

```

takes input from command line arguments (you may interprete that as lines separated by spaces if you like); prints names without a delimiter. Run with `-r` or test it online.

edit 1: saved 20 bytes with direct printing
edit 2: saved 3 bytes by removing the delimiter
edit 3: saved 4 bytes by exploiting that plain integers are no valid dates for `strtotime`

**breakdown**

```
while($n=$argv[++$i])       # loop through arguments, skip [0]
    $i&1                        # if index is odd
    ?   $p=$n                   # then assign name to $p
    :   ($t=                    # else $t =
        ($f=strtotime)($n)          # if $n is a valid time, parse it
        ?:$t+60*$n                  # else add $n minutes to current $t
        )<=$f(end($argv))           # if $t <= parsed party start
        ?                           # then do nothing
        :print$p;                   # else print name

```
> 5 votes

# Answer
## c, 178 bytes

```
main(c,o,d,e,g,O,l,f,x,y)char**o,d[80],*O,*l,*f;{for(sscanf(o[2],"%d:%d",&e,&g),x=e*60+g,l=";",f=o[1];O=strtok(f,l);f=0)(y=sscanf(O,"%s%d:%d",d,&e,&g)^2?e*60+g:y+e)>x?puts(d):0;}

```

Try it online
> 5 votes

# Answer
# JavaScript ES6, 185 bytes

```
l=>t=>l.split`
`.map(p=>p.split` `).map((p,i,a)=>[p[0],i?d(a[0][1])+a.slice(1,i+1).reduce((a,p)=>a+=+p[1],0)*6e4:(d=x=>Date.parse(`2017T${x}`))(p[1])]).filter(p=>p[1]>d(t)).map(p=>p[0])

```

### Try it online!

```
const f = l=>t=>l.split`
`.map(p=>p.split` `).map((p,i,a)=>[p[0],i?d(a[0][1])+a.slice(1,i+1).reduce((a,p)=>a+=+p[1],0)*6e4:(d=x=>Date.parse(`2017T${x}`))(p[1])]).filter(p=>p[1]>d(t)).map(p=>p[0])

console.log(f('Kevin 13:02\nRuby 5\nSam 3\nLisa 6\nBob 12')('13:15'))
```
> 4 votes

# Answer
# PowerShell, ~~215~~ ~~196~~ 180 bytes

```
param($a,$b)$x,[array]$a=$a-split',';$z=@{};$i,$j=-split$x;$z[$i]=($y=date $j);0..($a.count-1)|%{$i,$j=-split$a[$_];$z[$i]=($y=$y|% *es $j)};($z|% *or|?{$_.value-gt(date $b)}).Name

```

Try it online!

Roughly 1/3rd of this is input parsing, so I'm not sure how much further I can golf it.

Takes input `$a` as a comma-delimited string of names and times/minutes, and `$b` as `hh:mm` as a string. First, we `-split` `$a` on `,`, store the first result into `$x` and the remaining into `$a`, with an explicit re-cast of `$a` as an `array` (so that the loop later works properly). We the initialize our hashtable `$z`, set `$i` and `$j` to be `$x` `-split` on whitespace, and set `$z[$i]` to be the `date` of `$j` (stored into `$y` for use later).

Then we loop through the remaining `$a`. Each iteration, we do similar -- `-split` the string on whitespace, set the appropriate `$z` index to be that many more minutes beyond where we're currently at. This uses a shortened property name trick to save some bytes, using `|% *es $j` instead of `.AddMinutes($j)`.

Finally, we `.GetEnumerator()` (again using the trick) of our hashtable, and `Where-Object` select those entries with a `value` that's `-g`reater`t`han `$b` (i.e., they're late to the party). We then select just the `.Name`s thereof. Output is as an implicit array, which the default `Write-Output` inserts newlines between.

*Saved a bunch thanks to briantist for reminding me that \[array\] is a thing. And a bunch more for shortened property name tip.*
> 3 votes

# Answer
# Python 2, ~~140,148,~~144 bytes

```
t,h,n=map(str.split,input().replace(':','').split(';')),100,0
for a,v in t[:-1]:
 n+=int(v)
 if n%h/60:n=n/h*h+n%h%60+h
 if`n`>t[-1][0]:print a,

```

Try it online!

Input Format:

```
'Kevin 13:02;Ruby 5;Sam 3;Lisa 6;Bob 12;13:15'

```
> 3 votes

# Answer
## CJam, ~~66~~ ~~54~~ ~~58~~ ~~54~~ ~~51~~ ~~49~~ 46 bytes

```
{{':/60b}:K~)rSrKs++q+S/2/z~:i[{1$+}*]2$+$@#>}

```

Input 1 is given through STDIN, input 2 is given as a string on the stack. Output is an array on the stack. Separator for input 1 is a space, e.g. `Kevin 13:02 Ruby 5 Sam 3 Lisa 6 Bob 12`.

### Stack trace:

```
         e# Stack:               | "13:15"
{        e# Define K and run it:
  ':/    e#   Split on colon:    | ["13" "15"]
  60b    e#   From base 60:      | 795
}:K~     e# End def
)        e# Increment:           | 796
r        e# Read token:          | 796 "Kevin"
S        e# Push space:          | 796 "Kevin" " "
r        e# Read another token:  | 796 "Kevin" " " "13:02"
K        e# K()                  | 796 "Kevin" " " 782
s        e# Convert to string:   | 796 "Kevin" " " "782"
++       e# Add together:        | 796 "Kevin 782"
q        e# Read rest of input:  | 796 "Kevin 782" " Ruby 5 Sam 3 Lisa 6 Bob 12"
+        e# Add together:        | 796 "Kevin 782 Ruby 5 Sam 3 Lisa 6 Bob 12"
S/       e# Split on spaces:     | 796 ["Kevin" "782" "Ruby" "5" "Sam" "3" "Lisa" "6" "Bob" "12"]
2/       e# Group by 2:          | 796 [["Kevin" "782"] ["Ruby" "5"] ["Sam" "3"] ["Lisa" "6"] ["Bob" "12"]]
z        e# Transpose:           | 796 [["Kevin" "Ruby" "Sam" "Lisa" "Bob"] ["782" "5" "3" "6" "12"]]
~        e# Unpack:              | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] ["782" "5" "3" "6" "12"]
:i       e# Convert all to int:  | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 5 3 6 12]
[{1$+}*] e# Accumulate:          | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808]
2$       e# Copy back element:   | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808] 796
+        e# Add into array:      | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808 796]
$        e# Sort:                | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 796 808]
#        e# Find index:          | ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] 3
>        e# Slice:               | ["Lisa" "Bob"]

```

Explanation:

* The procedure `K` converts between a time `hh:mm` and a number representing how many minutes that is since midnight.
* We read the first person and replace their time with K(their time). We then add this to the front of the input.
* We then preform some string operations to get a list of names and a list of times, like `[782 5 3 6 12]`.
* By accumulating this list, we get `[782 787 790 796 808]`, which gives the times that everybody came.
* The shortest way to find who is late is to insert the start time into the array and then re-sort it to place it where it should be. We then find the index to figure out where it places, and then slice the list of names from that index.
> 2 votes

# Answer
# Bash, ~~135~~ ~~124~~ 115 bytes

```
a=($1)
for i in `seq 3 2 ${#a[@]}`
do((v+=a[i]))
((`date -d${a[1]} +%s`+v*60>`date -d$2 +%s`))&&echo ${a[i-1]}
done

```

Try it online!
> 2 votes

# Answer
# JavaScript, ~~285~~ 283 bytes

Takes the list of guests `i` and the party time `p` in currying syntax `(i)(p)`. Returns a comma-separated list of names such as `Lisa,Bob`.

```
i=>p=>{n=i.split`
`,a=new Date(0,0,0,...n[0].split` `[1].split`:`),y=new Date(0,0,0,...p.split`:`),t=[a];w=a;n.slice(1).map((j,k,l)=>{h=l[k].split` `[1]*6e4;t.push(new Date(w.getTime()+h));w=new Date(w.getTime()+h)});return n.filter((j,k,l)=>t[k]>y).map(j=>j.split` `[0]).join()}

```

I know it's pretty long and currently at last place by a fair margin, but that's what I could come up with.

```
f=i=>p=>{n=i.split`
`,a=new Date(0,0,0,...n[0].split` `[1].split`:`),y=new Date(0,0,0,...p.split`:`),t=[a];w=a;n.slice(1).map((j,k,l)=>{h=l[k].split` `[1]*6e4;t.push(new Date(w.getTime()+h));w=new Date(w.getTime()+h)});return n.filter((j,k,l)=>t[k]>y).map(j=>j.split` `[0]).join()}

console.log(f(`Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
`)('13:15'))
```
> 1 votes

# Answer
## C#, ~~269~~ 267 bytes

---

### Golfed

```
(l,t)=>{var h=System.DateTime.MinValue;var s=System.DateTime.ParseExact(t,"HH:mm",null);var o="";foreach(var p in l.Split('\n')){var i=p.Split(' ');h=h.Ticks<1?System.DateTime.ParseExact(i[1],"HH:mm",null):h.AddMinutes(int.Parse(i[1]));if(h>s)o+=i[0]+" ";}return o;};

```

---

### Ungolfed

```
( l, t ) => {
   var h = System.DateTime.MinValue;
   var s = System.DateTime.ParseExact( t, "HH:mm", null );
   var o = "";

   foreach( var p in l.Split( '\n' ) ) {
      var i = p.Split( ' ' );

      h = h.Ticks < 1
         ? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
         : h.AddMinutes( int.Parse( i[ 1 ] ) );

      if( h > s )
         o += i[ 0 ] + " ";
   }

   return o;
};

```

---

### Ungolfed readable

```
( l, t ) => {
   // var to check the time of arrival
   var h = System.DateTime.MinValue;

   // var to store the start time of the party
   var s = System.DateTime.ParseExact( t, "HH:mm", null );

   // var with the names of those who arrived late
   var o = "";

   // Cycle through which line
   foreach( var p in l.Split( '\n' ) ) {
      // Split the name and time
      var i = p.Split( ' ' );

      // Check if the time of arrival still has the initial value
      h = h.Ticks < 1

         // If so, grab the time of the first person
         //   Expects to have a time format of 'hh:mm'
         ? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )

         // Otherwise, add the difference to the var
         : h.AddMinutes( int.Parse( i[ 1 ] ) );

      // Check if the current time is later than the party start time
      if( h > s )

         // If so, add the name to the list
         o += i[ 0 ] + " ";
   }

   // Return the names of the persons who arrived late
   return o;
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, String, String> f = ( l, t ) => {
            var h = System.DateTime.MinValue;
            var s = System.DateTime.ParseExact( t, "HH:mm", null );
            var o = "";

            foreach( var p in l.Split( '\n' ) ) {
               var i = p.Split( ' ' );

               h = h.Ticks < 1
                  ? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
                  : h.AddMinutes( int.Parse( i[ 1 ] ) );

               if( h > s )
                  o += i[ 0 ] + " ";
            }

            return o;
         };

         List<KeyValuePair<String, String>>
            testCases = new List<KeyValuePair<String, String>> {
               new KeyValuePair<String, String>(
                  "Kevin 13:02\nRuby 5\nSam 3\nLisa 6\nBob 12",
                  "13:15"
               ),
               new KeyValuePair<String, String>(
                  "Kevin 13:15\nRuby 5\nSam 3\nLisa 6\nBob 12",
                  "13:15"
               ),
            };

         foreach( KeyValuePair<String, String> testCase in testCases ) {
            Console.WriteLine( $" Input:\n{testCase.Key}\n\n{testCase.Value}\n\nOutput:\n{f( testCase.Key, testCase.Value )}\n" );
         }

         Console.ReadLine();
      }
   }
}

```

---

### Releases

* **v1.1** \- `- 2 bytes` \- Thanks to VisualMelon
* **v1.0** \- `269 bytes` \- Initial solution.

---

### Notes

* **Output format:** Outputs the names separated by spaces
> 1 votes

# Answer
# Java, ~~346~~ ~~304~~ ~~284~~ 275 bytes

* -9 bytes, thanks to @KevinCruijssen

```
void g(int m,String[]n,String[]a,int M){for(int i=0;i<n.length;i++)if((M+=i>0?p(a[i]):0)>m)System.out.print(n[i]);}
int p(String n){return new Short(n);}
int h(String t){return p(t.split(":")[0])*60+p(t.split(":")[1]);}
void f(String[]n,String[]a,String b){g(h(b),n,a,h(a[0]));}

```

**Detailed** Live

```
public static void g(int m, String[] n, String[] a, int M)
{
    for(int i = 0; i < n.length; i++)
    {
        if((M += i>0 ? p(a[i]) : 0) > m)
        {
            System.out.println(n[i]);
        }
    }
}

public static int p(String n)
{
    return Integer.parseInt(n);
}

public static int h(String t)
{
    return p(t.split(":")[0])*60+p(t.split(":")[1]);
}

public static void f(String[] n, String[] a, String b)
{
    g(h(b),n,a,h(a[0]));
}

```
> 1 votes

# Answer
# CJam, ~~43~~ 41 bytes

```
q~':/60b:Y;Sf/()':/60b+a\+{)iT+:TY>{;}|}%

```

Try it online!

**Explanation**

```
q~        e# Read and eval all input.

':/       e# Split the start time on colons.
60b       e# Convert the result from base 60, to get the start time in minutes.
:Y;       e# Store this time in variable Y, and discard it from the stack.

Sf/       e# Split each string in the guest list on spaces.
(         e# Pull out the first guest from the list.
)         e# Pull out the time from the guest.
':/60b+   e# Convert the time to a number of minutes (same way as before), then add it back
          e#   to the guest.
a\+       e# Add the guest back to the start of the guest list.

          e# At this point, the first guest has his/her arrival time in minutes, and everyone
          e#  else still has their original number.

{         e# Apply this block to each guest:
 )i       e#  Pull out the number and cast it to an integer.
 T+       e#  Add the value of variable T to it (T is initially 0).
 :T       e#  Store the result back into T.
 Y>{;}|   e#  If the resulting number of minutes is not after the start time, delete the
          e#    guest's name.
}%        e# (end of block)

          e# Implicit output.

```
> 1 votes

# Answer
## Lua, ~~211~~ 206 Bytes

First codegolf of the year for me, should still be golfable.

**Edit: Saved 5 Bytes by using a shorthand for `string.match`**

```
function f(l,T)m=T.match
r=function(X)return
m(X,"^%d+")*3600+60*m(X,"%d+$")end
T=r(T)z={}y=0
for i=1,#l do
h=m(l[i],"%d.*")h=i>1 and y+h*60or r(h)y=h
z[#z+1]=h>T and m(l[i],"%u%l*")or nil
end return z end

```

### Explanations

```
function f(l,T)                         -- declare the function f(list,partyTime)
  r=function(X)                         -- declare a function r that convert hh:mm in seconds
    return X:match("^%d+")*3600         -- return the sum of seconds the hours
          +60*X:match("%d+$")           -- and in the seconds
  end
  T=r(T)                                -- convert the partyTime in seconds
  z={}                                  -- create the shameList for late partygoers
  y=0                                   -- y will keep us updated on the second count
  for i=1,#l                            -- iterate over l
  do
    h=l[i]:match("%d.*")                -- h is a shorthand for the time of arrival
    h=i>1                               -- if we're on the second line at least
        and y+h*60                      -- update h with the time of arrival in second
      or r(h)                           -- else use r()(for the first partygoer only)
    y=h                                 -- update our reference for adding time
    z[#z+1]=h>T                         -- if the last partygoer was late
                and l[i]:match("%u%l*") -- add its name to the shameList
              or nil                    -- else, don't do anything
  end
  return z                              -- return the shameList
end

```

if you want to try this code, you can use the following snippet

```
function f(l,T)r=function(X)return
X:match("^%d+")*3600+60*X:match("%d+$")end
T=r(T)z={}y=0
for i=1,#l do
h=l[i]:match("%d.*")h=i>1 and y+h*60or r(h)y=h
z[#z+1]=h>T and l[i]:match("%u%l*")or nil
end return z end

retour = f({"Kevin 13:02","Ruby 5","Sam 3","Lisa 6","Bob 12"},"13:15")
for i=1,#retour
do
  print(retour[i])
end

```
> 1 votes

# Answer
## Batch, 163 bytes

```
@set/pp=
@set/ap=%p::=*60+%
:l
@set g=
@set/pg=
@if "%g%"=="" exit/b
@set t=%g:* =%
@set/ap-=%t::=*60+%
@for %%g in (%g%)do @(if %p% lss 0 echo %%g)&goto l

```

Takes input on STDIN. First line is the start time of the party, then the list of guests. Uses @Arnauld's trick to convert the hh:mm into minutes.

Batch's preferred input for this would be as a series of command-line parameters (starting with the time of the party, then each guest and time as separate arguments). This would only take 129 bytes:

```
@set p=%1
@set/ap=%p::=*60+%
:l
@set t=%3
@set/ap-=%t::=*60+%
@if %p% lss 0 echo %2
@shift
@shift
@if not "%2"=="" goto l

```
> 0 votes

# Answer
# Groovy, 121 bytes

```
{g,t->y={Date.parse('hh:mm',it)};u=y(t);d=y(g.remove(0)[1]);g.find{z=it[1];use(groovy.time.TimeCategory){d+z.minutes}>u}}

```
> 0 votes

# Answer
## PowerShell, 170 160 bytes

```
select-string '(?m)^((\w*) )?((\d\d):)?(\d?\d)$'-a|% matches|%{,$_.groups[2,4,5].value}|%{}{$b+=($c=60*$_[1]+$_[2]);$a+=,@{n=$_[0];t=$b}}{$a|? n|? t -gt $c|% n}

```

Try it online!
> 0 votes

---
Tags: code-golf, date
---


title: Make Wise Numbers

text:
# Question
Title: Make Wise Numbers
Wise is a simple bitwise language I designed a while back. It is based around Python's bitwise operations. It has several operations most of these are the same or very similar to the equivalent symbol in Python.

* `:` Duplicate the top of the stack
* `?` Rotate the top of the stack to the bottom
* `!` Rotate the bottom of the stack to the top
* `[` `]` loop while the top of the stack is not zero
* `~` not the top of the stack (*`-(n+1)`*)
* `-` negate the top of the stack (*`-n`*)
* `>` bitshift the top of the stack once to the right (*`n//2`*)
* `<` bitshift the top of the stack once to the left (*`n*2`*)
* `^` xor the top two items of the stack (*Same as Python*)
* `|` or the top two items of the stack (*Same as Python*)
* `&` and the top two items of the stack (*Same as Python*)

---

Making an integer in Wise is pretty simple you can make zero with `::^` and increment it with `~-` so you make zero and increment it a bunch of times. However if we remove the `-` things become a little more interesting.

We can still make every number using the remaining operations. For example here is 3

```
~<<~

```

TIO

This works because `~` turns zero, an infinite string of `0` bits, into negative one, an infinite string of `1` bits, each `<` appends a `0` bit to the end, when we are done we do `~` which turns each it into a string of `0`s followed by a two `1`s, or as most people call it 3.

---

# Task

Write a program that when given a positive integer will output a Wise program that will create the number `n` without any `-` in its source (the source of the output, you may use `-` in your own source). You may assume that there is already a zero on the top of the stack.

This is *not* so you should aim to minimize the generating source code *not* necessarily the output.

# Example outputs

*This list is not exhaustive they are simply possible outputs*

```
1  -> ~<~
2  -> ~<~<
3  -> ~<<~
4  -> ~<~<<
5  -> ~<~:<<|
6  -> ~<<~<
7  -> ~<<<~
8  -> ~<~<<<
9  -> ~<~:<<<|
10 -> ~<~:<<|<
11 -> ~<<~:><<<|
12 -> ~<<~<<
13 -> ~<<~:<<<|>
14 -> ~<<<~<
15 -> ~<<<<~
16 -> ~<~<<<<

```

# Answer
# Japt, 10 bytes

```
¤d0'<1"~<~

```

Try it online!

Basic idea: take the binary representation of the number, and map `0` to `<` and `1` to `~<~`. Outputs for 1-10:

```
 1: ~<~
 2: ~<~<
 3: ~<~~<~
 4: ~<~<<
 5: ~<~<~<~
 6: ~<~~<~<
 7: ~<~~<~~<~
 8: ~<~<<<
 9: ~<~<<~<~
10: ~<~<~<~<

```
> 8 votes

# Answer
## JavaScript (ES6), ~~34~~ 33 bytes

```
f=n=>n?f(n&1?~n:n/2)+'<~'[n&1]:''
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```

Works for any 32-bit integer.
> 7 votes

# Answer
# Haskell, 38 bytes

I feel like PPCG is really improving my Haskell. *Strokes white cat.*

```
f n=mapM(["<","~<~"]<$f)[1..n]!!n>>=id

```

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

Try it online!

(I'm referring to that `<$f` by the way. It saves a character over `\_->`.)

> In the `Functor` instance for `(->) a` (functions from type `a`), we have: `x <$ f = fmap (const x) f = const x . f = const x`. The only limitation is that `f` and the final `const x` must use the same source type `a`. The instance is completely lazy so this never even evaluates `f`.

Alternatively, same length but less evil (`(l!!)` is an anonymous function):

```
(l!!)
l=(++)<$>"":tail l<*>["<","~<~"]

```

Try it online!

Both of these use the same representation as @ETHproductions' Japt answer, although especially the first one may give some redundant `<`s at the beginning.

The first one calculates all combinations of `n` `"<"` and `"~<~"` strings, then indexes into the resulting list.

The second one recursively calculates an infinite list formed by starting with `""` and then constructing new elements by appending `"<"` and `"~<~"` strings to each element already in the list (actually it was slightly shorter to also let the `""` get turned into `"<"`.)
> 7 votes

# Answer
# Ruby, ~~118~~ ~~116~~ ~~109~~ ~~107~~ ~~105~~ 91 bytes

Saved 2 bytes thanks to cyoce!

```
->n{o={0=>""}
o.dup.map{|c,k|["~~c","<c*2"].map{|t|o[eval t[1..9]]=k+t[0]}}until o[n]
o[n]}

```

Try it online!

This is a function that takes the integer as input and returns the string that represents that integer in Wise. You can find an ungolfed version **here**, which tests this program on all integers from 1 up.

The basic idea is to record a "pool" of constants. Then, with each "step", constants are added to the pool for each possible function. I have chosen the functions `~`, `<`, and `>`, which I believe are sufficient to represent every number. (At least, every number under 10,000.)
> 3 votes

# Answer
# Python2, ~~54~~ ~~52~~ 51 bytes.

```
lambda x:'<'.join('>~<~'*int(i)for i in bin(x)[2:])

```

Thanks to Wheat Wizard for saving 2 bytes, and Ørjan Johansen for one byte! This uses the same idea as ETHproduction's Japt answer, but with different replacement strings (i.e. using the binary representation)
> 3 votes

# Answer
# 05AB1E, 11 bytes

```
bS'<…~<~‚èJ

```

Try it online!

Similar to ETHproductions' Japt answer.

Saved 4 bytes thanks to @Adnan!
> 2 votes

# Answer
# Python 2, ~~123~~ 110 bytes

```
def w(x):a=map(int,bin(x)[2:]);return x%2*("~<~:<"+"<".join(":"*e for e in a[-2::-1])+"|"*sum(a))or w(x/2)+"<"

```

Try it online!

Also as a `lambda`

```
w=lambda x:x%2*("~<~:<"+"<".join(":"*int(e)for e in bin(x)[-2:2:-1])+"|"*sum(map(int,bin(x)[2:])))or w(x/2)+"<"

```

Try it online!

Could be shorter but here is my solution. It takes the binary representation and turns it into the code.
> 1 votes

# Answer
# Japt, 23 bytes

```
?Uu ?ß~U +'~:ßU/2 +'<:P

```

Try it online!
> 1 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
Bị“~<~“<”F

```

This is a ported version of ETHproductions' Japt answer. Speaking of ETHproductions, they saved me one byte!
> 0 votes

---
Tags: code-golf, number, code-generation, bitwise
---