title: Home on the Range of Lists

text:
# Question
Title: Home on the Range of Lists
This challenge is simply to return a list of lists of integers, similar to the Python range function, except that each successive number must be that deep in lists.

**Rules**:

* Create a program or a non-anonymous function
* It should return or print the result
* The result should be returned in a list (of lists) or array (of arrays)
* If the parameter is zero, return an empty list
* This should be able to handle an integer parameter 0 \<= n \< 70.
    + (recursive solutions blow up pretty fast)
* The function should be callable with only the one parameter.
* Other behavior is undefined.
* This is code golf, so shortest code wins.

**Example Call:**

```
rangeList(6)
> [0, [1, [2, [3, [4, [5]]]]]]

```

**Test Cases:**

```
0  => []
1  => [0]
2  => [0, [1]]
6  => [0, [1, [2, [3, [4, [5]]]]]]
26 => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25]]]]]]]]]]]]]]]]]]]]]]]]]]
69 => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

```

**EDIT:** isaacg's answer is the shortest so far. I'll update the accepted answer if anyone finds a shorter one in a language that existed at the posting of the challenge. Thanks for playing!

# Answer
# Pyth, 13 bytes

```
?hu]+HG_UQYQY

```

Try it here.

```
                 Implicit:
                 Q = eval(input())
                 Y = []
?           QY   If Q = 0, print Y
 h               else, print the first element of
  u     _UQY     the reduce, where Y is the initial value, over the list
                 reversed(range(Q))
   ]+HG          The reduce function: The list containing H prepended onto G.
                 The new number is inserted into the accumulated list,
                 then the resultant list is wrapped in another list.

```
> 11 votes

# Answer
# APL (~~13~~ 18)

Assuming `⎕IO=0`:

```
f←{×⍵:⊃,∘⊂∘,/⍳⍵⋄⍬}

```

Explanation:

* `×⍵:` if  is positive,
    + `,∘⊂∘,`: join the left operand to the enclose of the right operand (i.e. `x ,∘⊂∘, y = [x, [y]]`)
    + `/`: reduce
    + `⍳⍵`: the numbers `0..⍵-1`
    + : disclose the result
* : otherwise
    + : return the empty list
    + (this is necessary because `/` fails on , and `⍳0` gives the empty list.)

Addendum:

This function returns a nested array. However, it is a bit hard to tell this from APL's default output. It separates array items by spaces, so you can only tell nesting by double spaces. Here is a function that will take a nested array, and return a string, formatting the nested array in Python style (i.e. `[a,[b,[c,...]]]`).

```
arrfmt←{0=≡⍵:⍕⍵ ⋄ '[',(1↓∊',',¨∇¨⍵),']'}

```
> 10 votes

# Answer
# Haskell, 67 bytes

```
data L=E|I Int|L[L]
1#m=L[I$m-1]
n#m=L[I$m-n,(n-1)#m]
p 0=E
p n=n#n

```

In Haskell all elements of a list have to be of the same type, so I cannot mix integers with list of integers and I have to define a custom list type `L`. The helper function `#` recursively constructs the required list. The main function `p` checks for the empty list and calls `#` otherwise.

As new data types cannot be printed by default (the rules allow just to return the list), I add some more code for demonstration purpose:

```
data L=E|I Int|L[L] deriving Show

```

Now:

```
-- mapM_ (print . p) [0..5]
E
L [I 0]
L [I 0,L [I 1]]
L [I 0,L [I 1,L [I 2]]]
L [I 0,L [I 1,L [I 2,L [I 3]]]]
L [I 0,L [I 1,L [I 2,L [I 3,L [I 4]]]]]

```
> 9 votes

# Answer
# Python, 48 bytes

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

```

Using list multiplication to handle the special case.
> 7 votes

# Answer
# Mathematica, 33

```
f@0={};f@1={0};f@n_:={0,f[n-1]+1}

```
> 6 votes

# Answer
# CJam, 16 bytes

```
Lri){[}%]~;']*~p

```

This is a full program. It takes input via STDIN and prints the final array on to STDOUT.

As with the other CJam entry, `0` input will print `""` as that is the representation of an empty array in CJam.

**How it works**:

```
L                   "Put an empty array on stack. This will be used for the 0 input";
 ri)                "Read the input, convert it to integer and increment it";
    {[}%            "Map over the array [0 ... input number] starting another array";
                    "after each element";
        ]~;         "Now on stack, we have input number, an empty array and the final";
                    "opening bracket. Close that array, unwrap it and pop the empty array";
           ']*~     "Put a string containing input number of ] characters and eval it";
                    "This closes all the opened arrays in the map earlier";
               p    "Print the string representation of the array";
                    "If the input was 0, the map runs 1 time and the ; pops that 1 array";
                    "Thus leaving only the initial empty array on stack";

```

Try it online here
> 5 votes

# Answer
# Java, 88 107 105 104 102 bytes

```
import java.util.*;int o;List f(final int n){return new Stack(){{add(n<1?"":o++);if(o<n)add(f(n));}};}

```

Pretty long compared to the others, though you can't do much better with Java. A check to determine whether to continue recursion is all it takes.
> 3 votes

# Answer
# JavaScript (ES6) 40

Recursive solution, pretty robust, no blows. *Update* Fails near 6500 with 'too much recursion'

```
F=n=>n--?(R=m=>m<n?[m,R(++m)]:[m])(0):[]

```

Iterative solution (45) No limits except memory usage

```
F=n=>{for(s=n?[--n]:[];n;)s=[--n,s];return s}

```

Try F(1000): FireBug console will not show you more than 190 nested arrays, but they are there
> 3 votes

# Answer
# C# - 100

Simple recursion. Check the zero special case and tick up with one variable, down with the other

```
object[]A(int y,int x=0){return y==0?new object[0]:y==1?new object[]{x}:new object[]{x,A(--y,++x)};}

```

# C++ 87

**(Visual C++ 2012)**

```
int*A(int y,int x=0){int*b=new int{x};return!y?new int:--y?(b[1]=(int)A(y,++x))?b:0:b;}

```

This one is great, by which I mean byzantine, but it's the same basic idea as the c# one.

It's a C style array implementation, so it doesn't give you an array, it gives a int pointer, in which I was be storing both ints and other pointers. Like this: `[0,*] *->[1,#] #-> [2,&] &-> etc`, where the symbols are pseudo code for the int value of a pointer and the --\> is where it pointers to in memory.

What an excellent easy to use implementation of c style jagged arrays I've devised (cough), but I maintain it's plausible enough to be within the rules of the question.

There's quite a lot of abusing ternary operators here, and also quite a lot of abusing the implicit cast from int to bool.

**Example:** If we let `int *bar = (int*)A(3);`, we can see:

```
bar
0x003bded8 {0}
((int*)bar[1])[0]
1
((int*)(((int*)bar[1])[1]))[0]
2

```

Which is pointer talk for \[0,\[1,\[2\]\]\].

Okay, fine. It doesn't actually have to be the awful. Here's some test code for running this c++ code:

```
int* GetNext(int* p){
  return (int*)p[1];
}

int main()
{
    auto x = 10;
    auto bar = A(x);

    for (int i = 1; i < x; i++){
        bar = GetNext(bar);
        std::cout << bar[0] << std::endl;
    }

```

}
> 2 votes

# Answer
# Python 2, 56 bytes

I suspect this could be golfed more.

```
f=lambda n,i=0:[i,f(n,i+1)]if i<n-1 else[i]if n>0 else[]

```

Tests:

```
# for n in (0,1,2,6,26,69): print n, '=>', f(n)
0 => []
1 => [0]
2 => [0, [1]]
6 => [0, [1, [2, [3, [4, [5]]]]]]
26 => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25]]]]]]]]]]]]]]]]]]]]]]]]]]
69 => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

```
> 2 votes

# Answer
# Pyth, 15 bytes

```
?u[HG)_UtQ]tQQY

```

Which is really saying, in Python:

```
Q = eval(input())
if Q:
    print reduce(lambda G,H:[H,G], reverse(range(Q-1)), [Q-1])
else:
    print []

```
> 2 votes

# Answer
# CJam, 17 bytes

I know Optimizer has found 16, but here is the best I can do:

```
{:I{[}%;{]}I1e>*}

```

This is a block, the closest thing to a function in CJam, which takes an integer on the stack, and leaves the desired nested array.

Use this program to test it, which puts the input on the stack, then calls the function and inspects the stack. Note that for `0`, the stack output will contain `""` \- this *is* CJam's native representation of an empty array.
> 2 votes

# Answer
# Ruby 46

```
f=->n{r=a=[]
(0...n).map{|i|a<<a=[i]}
r[0]||r}

```

Test it online: http://ideone.com/uYRVTa
> 2 votes

# Answer
# Haskell, ~~65 59 45~~ 41 bytes

These nested lists are the same data-structure as rooted `Tree`s, except that they can also be empty. Hence, we can use a list of them - also called a `Forest` to represent them.

```
(0!)
data T=N[T]Int
m!n=[N((m+1)!n)m|m<n]

```

Try it online!

### Explanation

First of all we need to implement the `Tree` data type:

```
data Tree = Node [Tree] Int

```

From there it's just recursion using two parameters `m` (counting up) and `n` to keep track when to terminate:

```
m ! n= [ Node ((m+1)!n) m| m<n ]

```

## Alternative, 61 bytes

```
import Data.Tree
f n=unfoldForest(\b->(b,[b+1|b<n-1]))[0|n>0]

```

Try it online!

### Explanation

The function `unfoldForest` takes a list of initial values and a function `x -> (y,[x])`. For each initial value `x` it *unfolds* a tree using the function, producing a tuple `(y,xs)` where `y` will become the root and the `xs` are used to repeat the procedure:

```
unfoldForest (\b -> (b, [b+1 | b < 2]) [0]
  ≡ Node 0 [unfoldForest (\b -> (b, [b+1 | b < 2) [1]]
  ≡ Node 0 [Node 1 [unfoldForest (\b -> (b, [b+1 | b < 2) []]]
  ≡ Node 0 [Node 1 []]

```
> 2 votes

# Answer
## Perl - 44

```
sub t{$r=[($t)=@_];$r=[$t,$r]while--$t>0;$r}

```

Will add explanation upon request. You can try it here.
> 1 votes

# Answer
# Ruby - Recursive version - 52

```
r=->(n,v=nil){(n-=1;n<0 ?v:r[n,(v ?[n,v]:[n])])||[]}

```

# Non-recursive version: ~~66~~ ~~62~~ 57

```
r=->i{(i-1).downto(0).inject(nil){|a,n|a ?[n,a]:[n]}||[]}

```

Sample output (same for both versions)

```
p r[0]  # => []
p r[1]  # => [0]
p r[2]  # => [0, [1]]
p r[6]  # => [0, [1, [2, [3, [4, [5]]]]]]
p r[26] # => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25]]]]]]]]]]]]]]]]]]]]]]]]]]
p r[69] # => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

```

The non-recursive version can handle arbitrarily large input.

```
p r[1000] # => [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, [16, [17, [18, [19, [20, [21, [22, [23, [24, [25, [26, [27, [28, [29, [30, [31, [32, [33, [34, [35, [36, [37, [38, [39, [40, [41, [42, [43, [44, [45, [46, [47, [48, [49, [50, [51, [52, [53, [54, [55, [56, [57, [58, [59, [60, [61, [62, [63, [64, [65, [66, [67, [68, [69, [70, [71, [72, [73, [74, [75, [76, [77, [78, [79, [80, [81, [82, [83, [84, [85, [86, [87, [88, [89, [90, [91, [92, [93, [94, [95, [96, [97, [98, [99, [100, [101, [102, [103, [104, [105, [106, [107, [108, [109, [110, [111, [112, [113, [114, [115, [116, [117, [118, [119, [120, [121, [122, [123, [124, [125, [126, [127, [128, [129, [130, [131, [132, [133, [134, [135, [136, [137, [138, [139, [140, [141, [142, [143, [144, [145, [146, [147, [148, [149, [150, [151, [152, [153, [154, [155, [156, [157, [158, [159, [160, [161, [162, [163, [164, [165, [166, [167, [168, [169, [170, [171, [172, [173, [174, [175, [176, [177, [178, [179, [180, [181, [182, [183, [184, [185, [186, [187, [188, [189, [190, [191, [192, [193, [194, [195, [196, [197, [198, [199, [200, [201, [202, [203, [204, [205, [206, [207, [208, [209, [210, [211, [212, [213, [214, [215, [216, [217, [218, [219, [220, [221, [222, [223, [224, [225, [226, [227, [228, [229, [230, [231, [232, [233, [234, [235, [236, [237, [238, [239, [240, [241, [242, [243, [244, [245, [246, [247, [248, [249, [250, [251, [252, [253, [254, [255, [256, [257, [258, [259, [260, [261, [262, [263, [264, [265, [266, [267, [268, [269, [270, [271, [272, [273, [274, [275, [276, [277, [278, [279, [280, [281, [282, [283, [284, [285, [286, [287, [288, [289, [290, [291, [292, [293, [294, [295, [296, [297, [298, [299, [300, [301, [302, [303, [304, [305, [306, [307, [308, [309, [310, [311, [312, [313, [314, [315, [316, [317, [318, [319, [320, [321, [322, [323, [324, [325, [326, [327, [328, [329, [330, [331, [332, [333, [334, [335, [336, [337, [338, [339, [340, [341, [342, [343, [344, [345, [346, [347, [348, [349, [350, [351, [352, [353, [354, [355, [356, [357, [358, [359, [360, [361, [362, [363, [364, [365, [366, [367, [368, [369, [370, [371, [372, [373, [374, [375, [376, [377, [378, [379, [380, [381, [382, [383, [384, [385, [386, [387, [388, [389, [390, [391, [392, [393, [394, [395, [396, [397, [398, [399, [400, [401, [402, [403, [404, [405, [406, [407, [408, [409, [410, [411, [412, [413, [414, [415, [416, [417, [418, [419, [420, [421, [422, [423, [424, [425, [426, [427, [428, [429, [430, [431, [432, [433, [434, [435, [436, [437, [438, [439, [440, [441, [442, [443, [444, [445, [446, [447, [448, [449, [450, [451, [452, [453, [454, [455, [456, [457, [458, [459, [460, [461, [462, [463, [464, [465, [466, [467, [468, [469, [470, [471, [472, [473, [474, [475, [476, [477, [478, [479, [480, [481, [482, [483, [484, [485, [486, [487, [488, [489, [490, [491, [492, [493, [494, [495, [496, [497, [498, [499, [500, [501, [502, [503, [504, [505, [506, [507, [508, [509, [510, [511, [512, [513, [514, [515, [516, [517, [518, [519, [520, [521, [522, [523, [524, [525, [526, [527, [528, [529, [530, [531, [532, [533, [534, [535, [536, [537, [538, [539, [540, [541, [542, [543, [544, [545, [546, [547, [548, [549, [550, [551, [552, [553, [554, [555, [556, [557, [558, [559, [560, [561, [562, [563, [564, [565, [566, [567, [568, [569, [570, [571, [572, [573, [574, [575, [576, [577, [578, [579, [580, [581, [582, [583, [584, [585, [586, [587, [588, [589, [590, [591, [592, [593, [594, [595, [596, [597, [598, [599, [600, [601, [602, [603, [604, [605, [606, [607, [608, [609, [610, [611, [612, [613, [614, [615, [616, [617, [618, [619, [620, [621, [622, [623, [624, [625, [626, [627, [628, [629, [630, [631, [632, [633, [634, [635, [636, [637, [638, [639, [640, [641, [642, [643, [644, [645, [646, [647, [648, [649, [650, [651, [652, [653, [654, [655, [656, [657, [658, [659, [660, [661, [662, [663, [664, [665, [666, [667, [668, [669, [670, [671, [672, [673, [674, [675, [676, [677, [678, [679, [680, [681, [682, [683, [684, [685, [686, [687, [688, [689, [690, [691, [692, [693, [694, [695, [696, [697, [698, [699, [700, [701, [702, [703, [704, [705, [706, [707, [708, [709, [710, [711, [712, [713, [714, [715, [716, [717, [718, [719, [720, [721, [722, [723, [724, [725, [726, [727, [728, [729, [730, [731, [732, [733, [734, [735, [736, [737, [738, [739, [740, [741, [742, [743, [744, [745, [746, [747, [748, [749, [750, [751, [752, [753, [754, [755, [756, [757, [758, [759, [760, [761, [762, [763, [764, [765, [766, [767, [768, [769, [770, [771, [772, [773, [774, [775, [776, [777, [778, [779, [780, [781, [782, [783, [784, [785, [786, [787, [788, [789, [790, [791, [792, [793, [794, [795, [796, [797, [798, [799, [800, [801, [802, [803, [804, [805, [806, [807, [808, [809, [810, [811, [812, [813, [814, [815, [816, [817, [818, [819, [820, [821, [822, [823, [824, [825, [826, [827, [828, [829, [830, [831, [832, [833, [834, [835, [836, [837, [838, [839, [840, [841, [842, [843, [844, [845, [846, [847, [848, [849, [850, [851, [852, [853, [854, [855, [856, [857, [858, [859, [860, [861, [862, [863, [864, [865, [866, [867, [868, [869, [870, [871, [872, [873, [874, [875, [876, [877, [878, [879, [880, [881, [882, [883, [884, [885, [886, [887, [888, [889, [890, [891, [892, [893, [894, [895, [896, [897, [898, [899, [900, [901, [902, [903, [904, [905, [906, [907, [908, [909, [910, [911, [912, [913, [914, [915, [916, [917, [918, [919, [920, [921, [922, [923, [924, [925, [926, [927, [928, [929, [930, [931, [932, [933, [934, [935, [936, [937, [938, [939, [940, [941, [942, [943, [944, [945, [946, [947, [948, [949, [950, [951, [952, [953, [954, [955, [956, [957, [958, [959, [960, [961, [962, [963, [964, [965, [966, [967, [968, [969, [970, [971, [972, [973, [974, [975, [976, [977, [978, [979, [980, [981, [982, [983, [984, [985, [986, [987, [988, [989, [990, [991, [992, [993, [994, [995, [996, [997, [998, [999]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

```

Both versions also gracefully accept negative numbers

```
p r[-5] # => []

```
> 1 votes

# Answer
# JavaScript, 93 bytes

This isn't ideal, but I might as well give it a try. I'll try and golf this further later on, though for now I see no obvious way to.

```
function f(n){s='[';i=0;while(i<n-1)s+=i+++',[';s+=i||'';do{s+=']'}while(i--);return eval(s)}

```
> 1 votes

# Answer
# Python, 75 bytes

This is just for show. It's the program I wrote when creating/designing this challenge.

```
f=lambda x,y=[]:y if x<1 else f(x-1,[x-2]+[y or[x-1]])if x>1 else y or[x-1]

```
> 1 votes

# Answer
# Python, 44

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

```

Recursively creates the tree. The `[:n]` at the end is to special-case `n==0` into giving the empty list.
> 1 votes

# Answer
# Joe, 8 bytes

Note: This is a non-competing answer. The first version of Joe was released after this question.

```
F:/+,M]R

```

What do we have here? `F:` defines a function F that is a chain of `/+,`, `M]` and `R`. When you call `Fn`, first `Rn` gets evaluated, returning range from 0 to n, exclusive. `M]` wraps each element to a list. Then the list is applied to `/+,`. `x +, y` returns `x + [y]`. `/` is a right fold. Thus, `/+,a b c d...` returns `[a, [b, [c, [d...]]]`.

Example invocations (code is indented by 3, output by 0):

```
   F:/+,M]R
   F10
[0, [1, [2, [3, [4, [5, [6, [7, [8, [9]]]]]]]]]]
   F2
[0, [1]]
   F1
[0]
   F0
[]
   F_5
[0, [-1, [-2, [-3, [-4]]]]]

```
> 1 votes

# Answer
# PHP 5.4 (67 bytes):

I know, I know.

It's far from being the shortest answer.

But it works!

Here it is:

```
function F($n){for($c=$n?[--$n]:[];~$n&&$n--;$c=[$n,$c]);return$c;}

```

You can test it right here: https://ideone.com/42L35E (ignore the error)

---

# Javascript (57 bytes):

This is the **same** **exact** **code** except that Javascript is picky about the return and I've reduced the variable names:

```
function F(n){for(c=n?[--n]:[];~n&&n--;c=[n,c]);return c}

```

See? Same code!

---

# ES6 (49 bytes):

Basically the same exact code, but reduced for ES6:

```
F=n=>{for(c=n?[--n]:[];~n&&n--;c=[n,c]);return c}

```
> 0 votes

# Answer
# Javascript (114 bytes):

Everybody else was doing recursive, so I wanted to try an iterative solution. I have too many special cases, though.

I hold a master list, and then loop and append new lists with new numbers.

```
function q(n){a=[];if(n==1)a=[0];else if(n!=0){a=[0,b=[]];for(i=1;i<n;){c=[];b.push(c);b.push(i++);b=c}}return a}

```
> 0 votes

# Answer
# Common Lisp (95 bytes):

```
(defun f(n &optional(i 0))(cond((< i(1- n))(cons i(list(f n(1+ i)))))((> n 0)(list i))(t nil)))

```
> 0 votes

# Answer
# JavaScript, ~~35~~ 37 bytes

Recursive solution

```
f=(n,x=[])=>n?f(--n,x[0]?[n,x]:[n]):x

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 11 bytes

```
_i¯ëFNI<α)R

```

Try it online or verify all test cases.

11-bytes alternative:

```
_i¯ëÝ¨Rvy)R

```

Try it online or verify all test cases.

**Explanation:**

05AB1E has no loops that go downwards, so to loop in the range `(input, 0]` I either have to:

* Create that range first (`Ý¨R`; create range `[0, input]`, remove last item, reverse), and then loop over it (`vy`);
* Or loop in the range `[0, input)` instead (`F`), and take the absolute difference between the loop-index and the input-1 (`NI<α`).

```
_i          # If the (implicit) input is 0:
  ¯         #  Push the global array (empty by default)
 ë          # Else:
  F         #  Loop `N` in the range [0, (implicit) input):
   N        #   Push index `N`
    I<      #   Push input-1
      α     #   Take the absolute difference between the two
       )    #   Wrap everything on the stack into a list
        R   #   Reverse the list
            # (output the result implicitly after the if/loop)

```
> 0 votes

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


title: Find the "Recursive Size" of a List

text:
# Question
Title: Find the "Recursive Size" of a List
Inspired by Find the “unwrapped size” of a list.

Define the Recursive Size, `RS`, of a list containing no lists as its length (number of items contained) and the Recursive Size of a list containing any lists as the sum of its length and the Recursive Size of those lists.

### Challenge

Write a program or function that outputs the Recursive Size of any given list in as few bytes as possible.

The input is a list and may contain numbers, strings (if your language has them), and similar lists.

---

For example:

```
RS([]) = 0

RS([[]]) = 1

RS([4, 5, 6]) = 3
RS(["four", "five", "six"]) = 3
RS(["[[[[]]]]", "[][][][][]", "][][[[]]][]["]) = 3

RS([[4, 5, 6]]) = 4
RS([["four", "five", "six"]]) = 4
RS([["[[[[]]]]", "[][][][][]", "][][[[]]][]["]]) = 4

RS([[4], [5], [6]]) = 6
RS([["four"], ["five"], ["six"]]) = 6
RS([["[[[[]]]]"], ["[][][][][]"], ["][][[[]]][]["]]) = 6

RS([[[[[[[[[]]]]]]]]]) = 8

RS([[],[],[],[],[],[],[],[]]) = 8

RS([[],[],[[]],[[[[]]]]]) = 8

RS([0,[-1],[2.3,-4.3],[5,[6]],[7,[8,9,[10,11,[12,13,14]]]]]) = 22

```

Note that if your language has no strings but does have lists of characters, the examples containing `"strings"` above could actually be lists of characters and have larger results. As an example:

```
RS([['f','o','u','r'], ['f','i','v','e'], ['s','i','x']]) = 14

```

This is , so the shortest answer in bytes wins; no funny-business, as always.

A non-list input may produce any output.
I/O is as flexible as usual.

# Answer
# Jelly, 8 bytes

```
ß€-ŒḊ?‘S

```

Try it online!

### How it works

```
ß€-ŒḊ?‘S  Main link. Argument: x

   ŒḊ?    If x has non-zero depth:
ß€          Recursively map the main link over its elements.
  -         Else, yield -1.
      ‘   Increment all integers in the result.
       S  Compute the sum of the result.
          If x is an array, incrementing before adding is equivalent to computing
          the sum of the elements and the length.
          If x is an integer/character, incrementing -1 yields 0, as desired.

```
> 6 votes

# Answer
## Python, 42 bytes

```
f=lambda x:x*0==[]and len(x)+sum(map(f,x))

```

For a non-list, output 0. For a list, output its length plus the sum of the recursive outputs for its elements.

Lists fall above numbers and below strings in the Python 2 ordering, requiring `[]<=x<''`. Instead, we check `x*0==[]`, whereas the result of `0` for a number or `''` for a string.
> 13 votes

# Answer
# JavaScript (ES6), ~~39~~ 37 bytes

*Saved 2 bytes thanks to @edc65*

```
f=a=>a.map&&a.map(x=>a-=~f(x),a=0)&&a

```
> 6 votes

# Answer
# Mathematica, 20 bytes

```
Length@Level[#,∞]&

```

Anonymous function. Takes an expression as input and returns a number as output. The Unicode character is U+221E INFINITY for `\[Infinity]`. `Level[#,∞]` gives a list of the input's subexpressions, and `Length@` counts them.
> 5 votes

# Answer
## Mathematica, 14 bytes

```
LeafCount@#-1&

```

Minor modification of my previous answer. As I explained there, `LeafCount` already takes care of nested atomic values, but it also counts the outermost list, which we need to subtract from the result.
> 5 votes

# Answer
## Perl, 34 bytes

A recursive function! Yep, Perl doesn't only have regex but also have functions!

```
sub f{@_+f(map ref?@$_:(),@_)if@_}

```

If you want to test it, you can run something like :

```
perl -pE 'sub f{@_+f(map ref?@$_:(),@_)if@_}$_=f@{+eval}' <<< '[["four"], ["five"], ["six"]]'

```
> 4 votes

# Answer
# Mathematica, 32 bytes

```
Length@#+Tr[#0/@#~Select~ListQ]&

```

Unnamed recursive function. The excerpt `#0/@#~Select~ListQ` calls the function again on each element of the input that's a list, and `Tr` sums those values up. Fortunately Mathematica is fine taking the length of the empty list and searching for qualifying elements from the empty list, so no base case is needed.
> 3 votes

# Answer
# Factor, 105 bytes

Recursive function g.

```
: g ( o -- l ) [ dup [ sequence? ] [ string? not ] bi and [ [ g ] map sum 1 + ] [ drop 1 ] if ] map sum ;

```

Ungolfed (kinda):

```
: g ( o -- l )
[ dup
  [ sequence? ]
  [ string? not ]
  bi and
  [ [ g ] map sum 1 + ]
  [ drop 1 ]
  if
] map sum ;

```

You'll find there are no calls to `length` because instead of using the length builtin, it's implemented through `drop 1` on strings and non-sequences.
> 2 votes

# Answer
## Haskell, 52 bytes

```
data L a=E a|N[L a]
r(N n)=1+sum(r<$>n)
r _=1
pred.r

```

Usage example:

```
*Main> pred.r $ N[E 0,N[E(-1)],N[E 2.3,E(-4.3)],N[E 5,N[E 6]],N[E 7,N[E 8,E 9,N[E 10,E 11,N[E 12,E 13,E 14]]]]]
22

```

Haskell doesn't support mixed lists (e.g. Int and list of Int), so I go with a custom list type `L` which is either an element of some type a (-\> `E a`) or a list of other Ls (-\> `N[L a]`). Calculating the RS is a simple recursion where an `E` counts `1` and a `N` one plus the sum of the recursive sizes of its elements. The whole sum is off by 1, so I subtract it via `pred`.

Side note: the exact types and values of the elements are not important for the algorithm, so we could remove the polymorphism an deal with abstract elements only and go with `data L=E|N[L]`.
> 2 votes

# Answer
## Mathematica, 18 bytes

```
(c=-1;++c&//@#;c)&

```

Yet another Mathematica approach. Not as short as using the built-in `LeafCount` but still fairly concise. This makes use of the `MapAll` operator `//@` which calls a function on every node of an expression, and we use that function to increment a counter `c`. As in the `LeafCount` case, this gives one more than we need, because it counts the outer list head as well, so we start the counter from `-1`.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 50 bytes

```
int f(Array a)=>a.Length+a.OfType<Array>().Sum(f);

```

Try it online!

Uses the same technique as the previously submitted Java answer, but leverages LINQ to reduce the answer length.

Explanation:

```
// f is a method that a accepts
// an array of any underlying type
int f(Array a)=>
  // include the length of the
  // current array in the total
  a.Length+
  // filter the current list to elements
  // that are also arrays
  a.OfType<Array>()
    // recursively call f on each child
    // array and add to cumulative total
    .Sum(f);

```
> 2 votes

# Answer
# 05AB1E (legacy), ~~22~~ 17 bytes

```
"ε¼D¸D˜Êi®.V"©.V¾

```

Try it online or verify all test cases.

**Explanation:**

This challenge poses multiple challenges to overcome in 05AB1E:

1. Although 05AB1E does have a recursive function since the Elixir rewrite (`λ`), it's only useful for integer sequences. Here is an answer of mine as example of the 05AB1E recursive function. Because of that, I had to find an alternative to do recursive calls, which I did by putting part of the code in a string, and execute that string as 05AB1E code recursively.
2. There also isn't an `isList` command in 05AB1E, so I had to use some workarounds to check this by utilizing wrapping into a list, deep flattening, and check for equality.
3. And third, there isn't a flatten for just one level of a multi-dimensional list. The flatten function `˜` is a deep flatten that removes all layers and makes a multi-dimensional list a single list with all inner-most values. (i.e. `[[1,2],[[[3]],4]]` becomes `[1,2,3,4]`).

I ended up with the code at the top to overcome all three of the above issues. It's split into three major parts. First we have the following:

```
"..."        # Create a string with 05AB1E code
     ©       # Save this string in the register (without popping)
      .V     # Execute the string as 05AB1E code

```

The string contains the following code:

```
ε            # Map each value in the given list by:
             # (this uses the input-list implicitly with the initial call)
 ¼           #  Increase the counter_variable by 1
 D           #  Duplicate the map-value
             #   i.e. STACK "A" becomes "A","A"
             #   i.e. STACK [["B","C"]] becomes [["B","C"]],[["B","C"]]
  ¸          #  Wrap it into a list
             #   i.e. "A" → ["A"]
             #   i.e. [["B","C"]] → [[["B","C"]]]
   D         #  Duplicate that again
             #   i.e. STACK "A",["A"] becomes "A",["A"],["A"]
             #   i.e. STACK [["B","C"]],[[["B","C"]]]
             #    becomes [["B","C"]],[[["B","C"]]],[[["B","C"]]]
    ˜        #  Flatten it
             #   i.e. ["A"] → ["A"]
             #   i.e. [[["B","C"]]] → ["B","C"]
     Ê       #  Check if the wrapped and wrapped+flattened lists are NOT equal
             #   i.e. ["A"] and ["A"] → 0 (falsey)
             #   i.e. [[["B","C"]]] and ["B","C"] → 1 (truthy)
      i      #  If they are:
       ®     #   Push the string from the register
        .V   #   Execute it as 05AB1E code
             #   (this is basically our recursive call, mapping the current value
             #    we duplicated initially again)

```

A map is used instead of a foreach-loop, because the map has an implicit `y`, and a foreach-loop need an explicit `y`. We only care about the `counter_variable`, though.

And finally, after all the maps and inner maps are done, we'll:

```
¾           # Push the counter_variable (which is output implicitly as result)

```
> 2 votes

# Answer
# , 65 bytes

```
R=function(L,`*`=sapply)"if"(any(L*is.list),sum(1+L*R),length(L))

```

Try it online!

Obvious recursive implementation of the spec.
> 2 votes

# Answer
# C, ~~174~~ ~~167~~ 152 bytes

Recursive function `f`, which leaks memory (**152**):

```
#include"object.h"
size_t f(array_t*a){size_t t=0,i=0;for(;i<array_length(a);i++){object_t*o=array_get_copy(a,i,0);t+=o->type==6?f(o->ary):1;}return t;}

```

Recursive `f` which doesn't leak, using references, at **167**:

```
#include"object.h"
size_t f(array_t*a){size_t t=0,i=0;for(;i<array_length(a);i++){object_t**o=array_get_ref(a,i,0);t+=*o->type==t_array?f(*o->ary):1;}return t;}

```

Ungolfed:

```
size_t get_recursize (const array_t* const a) {
  pfn();

  object_failnull(a);

  size_t out = 0;

  for (size_t i = 0; i < array_length(a); i++) {

    object_t** o = array_get_ref(a, i, NULL);

    if ( (*o)->type == t_array ) {

      out += get_recursize((*o)->ary);

    } else {
      ++out;
    }
  }
  return out;
}

```

"But how," you ask, "can this be answered in C? Surely, there are no managed arrays in C, and you can't really have heterogeneous arrays...?"

"Aha," I reply, "for I have been working on a simple system of "objects" for (GNU-ish) C11 and ISO C++11".

The full demo program for this function is:

```
#include "../calc/object/object.h"

size_t get_recursize (const array_t* const a);

define_array_new_fromctype(ssize_t);

int main (void) {

  size_t len = 6;

  static const ssize_t h[6] = { -1, 3, -5, 7, -9, 11 };

  array_t* a = array_new_from_ssize_t_lit(h, len, t_realint);

  size_t rsize = get_recursize(a);

  printf("Recursive size of a: %zu\n", rsize);

  object_t* asobj = object_new(t_array, a);
  array_destruct(a);

  array_t* b = array_new(NULL, -1);

  for (size_t j = 0; j < 10; j++) {
    array_append(b, asobj);
  }

  object_destruct(asobj);

  rsize = get_recursize(b);

  printf("Recursive size of b: %zu\n", rsize);

  asobj = object_new(t_array, b);
  array_destruct(b);

  array_t* c = array_new(NULL, -1);

  for (size_t i = 0; i < 100; i++) {
    array_append(c, asobj);
  }

  object_destruct(asobj);

  rsize = get_recursize(c);

  printf("Recursive size of c: %zu\n", rsize);

  array_destruct(c);

  return EXIT_SUCCESS;
}

size_t get_recursize (const array_t* const a) {
  pfn();

  object_failnull(a);

  size_t out = 0;

  for (size_t i = 0; i < array_length(a); i++) {

    object_t** o = array_get_ref(a, i, NULL);

    if ( (*o)->type == t_array ) {

      out += get_recursize((*o)->ary);

    } else {
      ++out;
    }
  }
  return out;
}

```

Right now, it lives here and you'll need that repo to use this.

You'll also need the Fowler-Noll-Vo hash library, `libfnv`, compiled for your platform. It's in that repository and you can also grab it here.

Then you can do `cc -DNODEBUG size.c path/to/libfnv.a -o size`.

The implementation isn't necessarily efficient:

```
$ valgrind --leak-check=full --track-origins=yes --show-leak-kinds=all ./size
==24127== Memcheck, a memory error detector
==24127== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==24127== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==24127== Command: ./size
==24127==
Recursive size of a: 6
Recursive size of b: 60
Recursive size of c: 6000
==24127==
==24127== HEAP SUMMARY:
==24127==     in use at exit: 0 bytes in 0 blocks
==24127==   total heap usage: 22,900 allocs, 22,900 frees, 615,584 bytes allocated
==24127==
==24127== All heap blocks were freed -- no leaks are possible
==24127==
==24127== For counts of detected and suppressed errors, rerun with: -v
==24127== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

```

But it does work! The last commit to master (which this program compiled on) was 2 days ago, which means this submission is valid.
> 1 votes

# Answer
**Axiom 118 bytes**

```
RS(a:Union(List(Any),Any)):INT==(a case List(Any)=>(g:List(Any):=a;leaf? g=>0;r:=#g;for i in g repeat r:=r+RS(i);r);0)

```

ungolfed

```
RS(a:Union(List(Any),Any)):INT==
  a case List(Any)=>
          g:List(Any):=a
          leaf? g=>0
          r:=#g
          for i in g repeat r:=r+RS(i)
          r
  0

```

results

```
(25) -> RS([])=0
   (25)  0= 0
                                        Type: Equation NonNegativeInteger
(26) -> RS([[]]) = 1
   (26)  1= 1
                                           Type: Equation PositiveInteger
(27) -> RS([4, 5, 6]) = 3
   (27)  3= 3
                                           Type: Equation PositiveInteger
(28) -> RS(["four", "five", "six"]) = 3
   (28)  3= 3
                                           Type: Equation PositiveInteger
(29) -> RS(["[[[[]]]]", "[][][][][]", "][][[[]]][]["]) = 3
   (29)  3= 3
                                           Type: Equation PositiveInteger
(30) -> RS([[4, 5, 6]]) = 4
   (30)  4= 4
                                           Type: Equation PositiveInteger
(31) -> RS([["four", "five", "six"]]) = 4
   (31)  4= 4
                                           Type: Equation PositiveInteger
(32) -> RS([["[[[[]]]]", "[][][][][]", "][][[[]]][]["]]) = 4
   (32)  4= 4
                                           Type: Equation PositiveInteger
(33) -> RS([[4], [5], [6]]) = 6
   (33)  6= 6
                                           Type: Equation PositiveInteger
(34) -> RS([["four"], ["five"], ["six"]]) = 6
   (34)  6= 6
                                           Type: Equation PositiveInteger
(35) -> RS([["[[[[]]]]"], ["[][][][][]"], ["][][[[]]][]["]]) = 6
   (35)  6= 6
                                           Type: Equation PositiveInteger
(36) -> RS([[[[[[[[[]]]]]]]]]) = 8
   (36)  8= 8
                                           Type: Equation PositiveInteger
(37) -> RS([[],[],[],[],[],[],[],[]]) = 8
   (37)  8= 8
                                           Type: Equation PositiveInteger
(38) -> RS([[],[],[[]],[[[[]]]]]) = 8
   (38)  8= 8
                                           Type: Equation PositiveInteger
(39) -> RS([0,[-1],[2.3,-4.3],[5,[6]],[7,[8,9,[10,11,[12,13,14]]]]]) = 22
   (39)  22= 22
                                           Type: Equation PositiveInteger
(40) -> RS([['f','o','u','r'], ['f','i','v','e'], ['s','i','x']]) = 14
   (40)  14= 14
                                           Type: Equation PositiveInteger

```
> 1 votes

# Answer
**Clojure, ~~79~~ ~~77~~ 51 bytes**

Input has to be a list, not vector. Both would be supported by using `sequential?`.

```
(defn f[i](if(seq? i)(apply +(count i)(map f i))0))

```

Previous:

```
(defn f[i](if(seq? i)(if(some seq? i)(apply +(count i)(map f i))(count i))0))

```
> 1 votes

# Answer
# APL(NARS), 24 chars, 48 bytes

```
{⍬≡⍵:0⋄×≡⍵:(≢⍵)++/∇¨⍵⋄0}

```

This would be the litteral traslation of 'my' Axiom answer here... In APL the void list would be ´⍬´ Zilde, that you indicate with ´\[\]´, ´⊂⍬´ is ´\[\[\]\]´, ´1 2 3´ is ´\[1,2,3\]´ ecc Some test:

```
  RS←{⍬≡⍵:0⋄×≡⍵:(≢⍵)++/∇¨⍵⋄0}
  RS ⍬
0
  RS ⊂⍬
1
  RS  4 5 6
3
  RS ("four")("five")("six")
14
  RS ('f' 'o' 'u' 'r') ('f' 'i' 'v' 'e') ('s' 'i' 'x')
14
  RS ("(((())))")("()()()()()")(")()((()))()(")
33
  RS (⊂4 5 6)
4
  RS (⊂("four")("five")("six"))
15
  RS (⊂("(((())))")("()()()()()")(")()((()))()(") )
34
  RS (,4) (,5) (,6)
6
  RS ⊂¨("four")("five")("six")
17
  RS ⊂¨("(((())))")("()()()()()")(")()((()))()(")
36
  RS ⊂⊂⊂⊂⊂⊂⊂⊂⍬
8
  RS ⍬⍬⍬⍬⍬⍬⍬⍬
8
  RS ⍬⍬(⊂⍬)(⊂(⊂(⊂⍬)))
8
  RS 0(,¯1)(2.3 ¯4.3)(5 (,6))(7 (8 9 (10 11 (12 13 14))))
22

```

for print the other type of results the exercise propose we need one other function (both functions RS and Rs should be ok for the exercise)

```
  Rs←{⍬≡⍵:0⋄(''≡0↑⍵)∨0=≡⍵:0⋄(≢⍵)++/∇¨⍵}
  Rs ("four")("five")("six")
3
  Rs ("(((())))")("()()()()()")(")()((()))()(")
3
  Rs (⊂("four")("five")("six"))
4
  Rs (⊂("(((())))")("()()()()()")(")()((()))()(") )
4
  Rs ⊂¨("four")("five")("six")
6
  Rs ⊂¨("(((())))")("()()()()()")(")()((()))()(")
6
  Rs 0(,¯1)(2.3 ¯4.3)(5 (,6))(7 (8 9 (10 11 (12 13 14))))
22
  Rs ('f' 'o' 'u' 'r') ('f' 'i' 'v' 'e') ('s' 'i' 'x')
3

```

for see how appear some input we use the o function:

```
  o←⎕fmt
  o 0(,¯1)(2.3 ¯4.3)(5 (,6))(7 (8 9 (10 11 (12 13 14))))
┌5─────────────────────────────────────────────────────────┐
│  ┌1──┐ ┌2────────┐ ┌2─────┐ ┌2──────────────────────────┐│
│0 │ ¯1│ │ 2.3 ¯4.3│ │  ┌1─┐│ │  ┌3──────────────────────┐││
│~ └~──┘ └~────────┘ │5 │ 6││ │7 │    ┌3────────────────┐│││
│                    │~ └~─┘2 │~ │8 9 │      ┌3────────┐││││
│                    └∊─────┘ │  │~ ~ │10 11 │ 12 13 14│││││
│                             │  │    │~~ ~~ └~────────┘2│││
│                             │  │    └∊────────────────┘3││
│                             │  └∊──────────────────────┘4│
│                             └∊──────────────────────────┘5
└∊─────────────────────────────────────────────────────────┘

```

this print Zilde, and one 8 Zilde list:

```
  o ⍬
┌0─┐
│ 0│
└~─┘
  o ⍬⍬⍬⍬⍬⍬⍬⍬
┌8──────────────────────────────────────┐
│┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐│
││ 0│ │ 0│ │ 0│ │ 0│ │ 0│ │ 0│ │ 0│ │ 0││
│└~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘2
└∊──────────────────────────────────────┘

```
> 1 votes

# Answer
# Java, 96 bytes

```
int c(Object[]a){int r=a.length;for(var i:a)r+=i instanceof Object[]?c((Object[])i):0;return r;}

```

Try it online.

**Explanation:**

```
int c(Object[]a){  // Recursive method with Object-array parameter and integer return-type
  int r=a.length;  //  Result-sum, starting at the size of the input-array
  for(var i:a)     //  Loop over the input-array:
    r+=            //   Increase the result-sum by:
       i instanceof Object[]?
                   //    If the current item is an array:
        c((Object[])i)
                   //     A recursive call with this item
       :           //    Else:
        0;         //     0 (so leave the result-sum the same)
  return r;}       //  Return the result-sum

```
> 1 votes

# Answer
# Attache, 21 bytes

```
{#_+Sum!$=>IsArray\_}

```

Try it online!

Turns out the C# approach is pretty short in Attache.

## Alternatives

**25 bytes** `f[x]:=#x+Sum!f=>IsArray\x`

**26 bytes** `f[x]:=#x+Sum[f=>IsArray\x]`

**35 bytes** `f:=Sum##{If[IsArray@_,1+f@_,1]}=>Id`

**35 bytes** `f:=Sum@Map[{If[IsArray@_,1+f@_,1]}]`

**37 bytes** `f[x]:=Sum[{If[IsArray@_,1+f@_,1]}=>x]`
> 1 votes

# Answer
# Python, 72 bytes

```
l=lambda a:0if len(a)==0else len(a)+sum(l(i)for i in a if type(i)==list)

```
> -1 votes

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


title: Setting the time

text:
# Question
Title: Setting the time
Imagine the following 24-hour clock that can be controlled by arrow keys:

```
╔══╗ ┌──┐
║00║:│00│
╚══╝ └──┘
 HH   mm

```

Pressing the up arrow twice (`↑↑`) will increase the currently focused hour input:

```
╔══╗ ┌──┐
║02║:│00│
╚══╝ └──┘
 HH   mm

```

Pressing the right arrow () will focus the other input.

```
┌──┐ ╔══╗
│02│:║00║
└──┘ ╚══╝
 HH   mm

```

Pressing the down arrow thrice (`↓↓↓`) will now decrease this input.

```
┌──┐ ╔══╗
│02│:║57║
└──┘ ╚══╝
 HH   mm

```

Shortly put:

* The up arrow () will increase the currently active input.
* The down arrow () will decrease the active input.
* The right arrow () will move focus to the right input.
* The left arrow () will move focus to the left input.
* Up and down movement will loop around as expected for a time input.
* Left and right movement don't loop around.

## The challenge

The clock starts out at `00:00` with the hour input active (see first schematic). Given a list of input commands, output the resulting time in `HH:mm` format.
Input can be either a string or a list (or your language equivalent), where the different input directions can be one of the below options:

* `↑↓←→`
* `udlr`
* `^v<>`
* actual arrow key presses if your program has a GUI

Standard loopholes apply.

## Test cases

```
↑↑→↓↓↓ = 02:57
↓→↑←↑→↓ = 00:00
↓→→↓ = 23:59
←←←←→↑ = 00:01
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓→↓ = 23:59

```

# Answer
# HTML on Google Chrome 67 in Chinese (Simplified), 39 bytes

```
<input type=time value=00:00 autofocus>
```

Chrome show different UI component in different language. Even a simple time input: AM/PM will be shown if you are using English (US). If you want test this by changing your Chrome's language. Do not mass up how to change it back.
> 40 votes

# Answer
# C (gcc), ~~117~~ 107 bytes

* Saved ten bytes thanks to l4m2.

```
t,i,m[8];e(char*_){for(*m=i=2[m]=0;t=*_++;t<63?i=t%4:(i[m]+=t&8?1:'w'));printf("%02d:%02d",*m%24,2[m]%60);}

```

Try it online!
> 13 votes

# Answer
# Stax, ~~36~~ ~~35~~ ~~33~~ 32 bytes

```
áXò↑─↨√▓|êóÇiU&≡Q#┤Æ⌡⌠╟C▐╜√⌡∟▄╩╠

```

Run and debug it

Uses `lrud`.

Explanation:

```
'l/{'r/Bs$2lmM{${:14-m|+i36*24+%2|zm':* Full program,
'l/                                     Split the string on "l"
   {        m                           Map over the resulting array
    'r/                                   Split at "r"
       B                                  Uncons left, first on TOS (top of stack)
        s                                 Swap to get tail to top
         $                                Flatten; this removes multiple 'r's
          2l                              Listify two items, BOS (bottom of stack) is first element
             M                          Transpose: get [hour commands, minute commands]
              {                    m    Map:
               $                          Flatten
                {    m                    Map over single commands:
                 :1                         Number of set bits: 5 for 'u', 3 for 'd'
                   4-                       Subtract 4: u -> 1, d -> -1
                      |+                  Sum
                        i                 Iteration index: hours -> 0, minutes -> 1
                         36*24+           Multiply by 36, add 24: 0 -> 24, 1 -> 60
                               %          Modulo, this does -5 % 60 = 55
                                2|z       Stringify, left-padding with "0" to length 2
                                    ':* Join on ":"
                                        Implicit output

```
> 6 votes

# Answer
# Python 2, 105 bytes

```
h=m=p=0
for c in map(' ^<>'.find,input()):w=1/c;m+=w*p;h+=w-w*p;p=[c-2,p][w]
print'%02d:%02d'%(h%24,m%60)

```

Try it online!
> 6 votes

# Answer
# C# (.NET Core), 149 132 bytes

```
s=>{var p=0;int[]h={0,0};foreach(var c in s)h[p=c<63?c/2%2:p]+=c>62?c>95?-1:1:0;return$"{(h[0]%24+24)%24:D2}:{(h[1]%60+60)%60:D2}";}

```

Try it online!

Using `^v<>`.

This one made me realize that the modulo operator in C# does not work as expected, because in C# `-1 % 60 = -1`, so I need to do that weird operation at the end.
> 5 votes

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

Takes input as a string, using `udlr`.

```
s=>(Buffer(s).map(n=>n%6?s%4?m+=n%2||59:h+=n%2||23:s=n,h=m=0),g=n=>('0'+n).slice(-2))(h%24)+':'+g(m%60)

```

Try it online!
> 5 votes

# Answer
**Lua (love2d framework),311 308 bytes**

```
l,b,d,t,f,a=love,{24,60},{1,-1},{0,0},1,{"left","right","up","down"}function c(n,i)t[f]=(n+d[i])%b[f]end function l.draw()h,m=t[1],t[2]l.graphics.print((h<10 and 0 ..h or h)..":"..(m<10 and 0 ..m or m),0,0)end function l.keypressed(k)for i,n in pairs(a)do f=k==n and(i>2 and(c(t[f],i-2)or f)or i)or f end end

```

Unscrumbeled version:

```
--initialize all needed values
l,b,d,t,f,a=love,{24,60},{1,-1},{0,0},1,{"left","right","up","down"}

--increase the numbers depending on the focus and up or down
function c(n,i)
  t[f]=(n+d[i])%b[f]
end

--draw the time to the screen
function l.draw()
  h,m=t[1],t[2]
  l.graphics.print((h<10 and 0 ..h or h)..":"..(m<10 and 0 ..m or m),0,0)
end

--get the keys and check if it is an arrow key
function l.keypressed(k)
  for i,n in pairs(a)do
    f=k==n and(i>2 and(c(t[f],i-2)or f)or i)or f
  end
end

```

Probably still not 100% easy to read because all the ifs are interchanged with an trinary statement ( ..and ..or) :)

if started in an main.lua with love then it will pop up a window and you can press the arrowkeys to change the numbers
> 5 votes

# Answer
# PHP, ~~145~~ ~~134~~ 133 bytes

(-11 bytes by more golfing)

(-1 byte by using Davіd's loop method)

```
<?for($h=$m=0,$a=h;$c=$argv[++$i];)$c<l?$$a--:($c>r?$$a++:$a=$c<r?h:m);$h%=24;$m%=60;printf('%02d:%02d',$h<0?$h+24:$h,$m<0?$m+60:$m);

```

To run it:

```
php -n -d error_reporting=0 <filename> <command_1> <command_2> ... <command_n>

```

Example:

```
php -n -d error_reporting=0 time_setter.php u u r d d d l d

```

Or Try it online!

**Notes:**

* To save some bytes, I have used strings without single/double quotations as the string wrapper. Thus, the `error_reporting=0` option is used to not output warnings.
* Input commands: `u d l r`
> 4 votes

# Answer
# JavaScript, ~~104~~ 103 bytes

Takes input as an array of characters, using `<>^v`.

```
a=>(a.map(z=>z<"^"?a=z<">":a?x+=z<"v"||23:y+=z<"v"||59,x=y=0),g=n=>`0${n}`.slice(-2))(x%24)+`:`+g(y%60)

```

Try it online
> 4 votes

# Answer
# MATL, ~~57~~ ~~56~~ 55 bytes

```
1Oi9\"@5<?y@3-ZS*+}wx7@-X^w]]wx&Zjh24 60h\'%02d:%02d'YD

```

Try it online!

Represents hour and minutes using complex numbers, with the real part being hours and the imaginary part minutes.

### With comments:

```
1     % Push 1 on the stack
      % represents which timer box we're in, starts at hour box
      % imaginary number j would represent minutes box
O     % Push initial hour and minutes 0+0j
i9\   % Fetch input, mod each character's ASCII value by 9.
      % Gives 4 1 8 6 for ^ v > < respectively
"     % iterate through (modded) input
  @5<?     % Push current input, see if it's < 5
           % if so, it's an up or down time change
    y        % so copy out the box indicator (1 or j)
    @3-      % Subtract 3 from the current input
    ZS       % Take the result's sign (-1 for v, 1 for ^)
    *        % Multiply indicator with that
    +        % Add the result to the time value
  }        % else, it's a right or left arrow
    wx       % so bring out the box indicator and delete it
    7@-      % Subtract current input from 7. 1 for < and -1 for >
    X^       % Take the square root of that. 1 for < and j for >
    w        % switch stack to bring time value on top again
  ]       % end if
]     % end loop
wx    % bring box indicator out, delete it
&Zj   % split the complex time value to real and imaginary
h     % then concatenate them into an array
24 60h\ % mod hour and minute values by 24 and 60 respectively
'%02d:%02d'YD % sprintf the time array with 0-padding

```
> 4 votes

# Answer
# Haskell, 236 bytes

```
f=u 0 0
k _ _ _ _ _ h m[]=z h++':':z m
k a b c d e h m(q:s)=case q of{'^'->e(a h)(b m)s;'v'->e(c h)(d m)s;'>'->v h m s;'<'->u h m s}
u=k(o(+)24)id(o(-)24)id u
v=k id(o(+)60)id(o(-)60)v
o f m x=mod(f x 1)m
z n|n<10='0':show n
z n=show n

```

`f` is the main function, and has type `String -> String`:

```
*Main> f "^^>vvv"
"02:57"
*Main> f "v>^<^>v"
"00:00"
*Main> f "v>>v"
"23:59"
*Main> f "<<<<>^"
"00:01"
*Main> f "vvvvvvvvvvvvvvvvvvvvvvvvv>v"
"23:59"

```

Essentially `u` and `v` are mutually recursive functions of type `Integer -> Integer -> String -> String`. They take the hour, the minute and a list of characters over the set `{v,^,<,>}`, and return the time string. `u` acts as if the hour dial is highlighted, recursively calling `u` if the head of the list is in `{v,^}`, and `v` if the head of the list is in `{<,>}`. `v` is similar but for the minute dial.

Everything else is just saving characters.
> 3 votes

# Answer
# Lua, 132 bytes

```
loadstring's,t,m=1,{0,0},{24,60}for c in(...):gmatch"."do t[s]=(t[s]+(("d u"):find(c)or 2)-2)%m[s]s=("lr"):find(c)or s end return t'

```

Try it online!

---

### Explanation

This is an anonymous function (a way to use it is shown on the link).

```
s=1 -- s will control the selection (1 is hour and 2 min)
t={0,0} -- is the time itself
m={24,60} -- is the maximum for each 'box' (hour or min)
-- I've actually used Lua's multiple variable assignment: s,t,m=1,{0,0},{24,60}

for c in (...):gmatch(".") do -- go through each character of the input
  t[s] = (t[s] + (("d u"):find(c) or 2)-2) % m[s] -- set the current 'box' as
          t[s] +   -- itself plus ...
                  ("d u"):find(c) or 2   -- it's index on the string "d u" (that means it's going to be 1 or 3)
                                         -- or 2 if it wasn't found (if the current character doesn't sum or subtract from the box)
                                       -2   -- this adjusts the result 1, 2 or 3 to being -1, 0 or 1
                                            -- making the inputs 'd' and 'u' as -1 and +1 respectively, and an input different from both as 0
         (                               ) % m[s]   -- modulo of the maximum of the selected 'box'

  s=("lr"):find(c) or s
    ("lr"):find(c)   -- if the current input character is l or r, then set 's' (the 'box' selection) to being 1 or 2.
                   or s   -- else let it as is
end
return t -- returns 't', a table with hour and minutes respectively

```
> 3 votes

# Answer
# Perl 6, ~~101 91 89~~ 86 bytes

```
{$/=[];$!=0;$_>2>($!=$_-3)||($/[$!]+=$_-1)for .ords X%5;($0%24,$1%60).fmt("%02d",":")}

```

Try it online!

Anonymous code block that takes a string of `uldr` characters and returns in the given format
> 2 votes

# Answer
# QBasic, 229 bytes

A script that takes input as keystrokes and outputs to the console.

*Note: terminal `"` are included for syntax highlighting only, and do not contribute to the bytecount*

```
z$=CHR$(0)
DO
x=0
y=0
SELECT CASE INKEY$
CASE z$+"K"
r=0
CASE z$+"M"
r=1
CASE z$+"H"
x=1
y=1
CASE z$+"P"
x=23
y=59
END SELECT
IF r THEN m=(m+y)MOD 60ELSE h=(h+x)MOD 24
CLS
?RIGHT$("00000"+LTRIM$(STR$(h*1000+m)),5)
LOCATE 1,3
?":"
LOOP

```

### Commented

```
z$=CHR$(0)                                      ''  Set var to null char
DO                                              ''
    x=0                                         ''  Set Hours Shift to 0
    y=0                                         ''  Set Minutes Shift to 0
    SELECT CASE INKEY$                          ''  Take keystroke input
        CASE z$+"K"                             ''  If is Left Arrow
            r=0                                 ''    Bool to modify right (minutes)
        CASE z$+"M"                             ''  If is Right Arrow
            r=1                                 ''    Bool to modify left (hours)
        CASE z$+"H"                             ''  If is Up Arrow
            x=1                                 ''    Set Hours Shift to 1
            y=1                                 ''    Set Minutes Shift to 1
        CASE z$+"P"                             ''  If is Down Arrow
            x=23                                ''    Set Hours Shift to 23
            y=59                                ''    Set Minutes Shift to 23
    END SELECT                                  ''
    IF r THEN m=(m+y)MOD 60ELSE h=(h+x)MOD 24   ''  Shift Minutes If `r=1` Else Shift Hours
    CLS                                         ''  Clear Screen
    ?RIGHT$("00000"+LTRIM$(STR$(h*1000+m)),5)   ''  Use math to concat Hours and Minutes
                                                ''  then Convert to String and prepend 0s
                                                ''  to a length of 5
    LOCATE 1,3                                  ''  Cursor to the the third digit
    ?":"                                        ''  Overwrite that digit with a `:`
LOOP                                            ''  Loop

```
> 2 votes

# Answer
# Java 8, 121 bytes

```
c->{int i=0,m[]={0,0,0};for(int t:c)if(t<63)i=t%4;else m[i]+=(t&8)>0?1:119;return"".format("%02d:%02d",m[0]%24,m[2]%60);}

```

Port of Jonathan Frech's C answer. Accepts `^v<>`. Try it online here.
> 2 votes

# Answer
# Jelly, 36 bytes

I believe `O%5;4ṣ3œṡ€4Z%3’§§%"“ð<‘DŻ€ṫ€-j”:` should work for 32, but `œṡ` seems to currently have a bug.

```
O%5;4ṣ3i€4$œṖ"$Z%3’§§%"“ð<‘DŻ€ṫ€-j”:

```

A full program printing the result to STDOUT (as a monadic link it actually returns a mixed list of integers (albeit single digit ones) and characters (the `:`).

Uses the `udlr` option for input.

**Try it online!** Or see a test-suite.

### How?

```
O%5;4ṣ3i€4$œṖ"$Z%3’§§%"“ð<‘DŻ€ṫ€-j”: - Link: list of characters (in 'udlr')
O                                    - to ordinals
 %5                                  - modulo five  ...maps u:2, d:0, l:3, r:4
   ;4                                - concatenate a 4 (to always end up with both hrs & mins - even when no r is ever pressed)
     ṣ3                              - split at threes (the l presses)
       i€4$œṖ"$                      - a replacement for œṡ€4 (split each at first occurrence of)...
              $                      - | last two links as a monad:
          $                          - |   last two links as a monad:
         4                           - |     literal four
       i€                            - |     for €ach get first index of (4) else yield 0
             "                       - |   zip with:
           œṖ                        - |     partition at indices
               Z                     - transpose (to get a list of two lists of lists)
                %3                   - modulo by three. To replace any 4(r) with 1
                                     -  ...while keeping any 0(d) as 0, or 2(u) as 2
                  ’                  - decrement. All r are now 0, d are -1 and u are 1
                   §                 - sum each
                    §                - sum each. Now we have the total increase value as
                                     -    ...integers for each of hrs and mins
                       “ð<‘          - code-page indices list = [24,60]
                      "              - zip with:
                     %               -   modulo
                           D         - to decimal lists
                            Ż€       - prepend each with a zero (to cater for values less than ten)
                              ṫ€-    - tail each from index -1. Keeps rightmost two digits of each only)
                                  ”: - literal character ':'
                                 j   - join
                                     - as full program implicit print (smashes the digits and characters together)

```
> 2 votes

# Answer
# APL (Dyalog Classic), ~~97~~ 84 bytes

```
5↑∊{¯3↑'0',':',⍨⍕⍵}¨24 60|A⊣⍎¨'⎕IO←1' '⎕IO←0' 'A[1]+←1' 'A[1]-←1'['←→↑'⍳⍞,'←']⊣A←0 0

```

Try it online!

Requires `⎕IO←1`
> 2 votes

# Answer
# Powershell, ~~109~~ 103 bytes

-6 byte thanks AdmBorkBork

```
$t=0,0
$args|%{$t[+$i]+=. @{l={$i=0};r={$i=1};u={1};d={119}}.$_}
"{0:00}:{1:00}"-f($t[0]%24),($t[1]%60)

```

Test script:

```
$f = {

$t=0,0
$args|%{$t[+$i]+=. @{l={$i=0};r={$i=1};u={1};d={119}}.$_}
"{0:00}:{1:00}"-f($t[0]%24),($t[1]%60)

}

@(
    ,('02:57',('u','u','r','d','d','d'))
    ,('00:00',('d','r','u','l','u','r','d'))
    ,('23:59',('d','r','r','d'))
    ,('00:01',('l','l','l','l','r','u'))
    ,('23:59',('d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','d','r','d'))
) | % {
    $e, $c = $_
    $r = &$f @c
    "$($r-eq$e): $r"
}

```

Output:

```
True: 02:57
True: 00:00
True: 23:59
True: 00:01
True: 23:59

```

## Explanation

Basic idea is to use a `[hashtable]`, which `keys` are control commands and `values` are scriptblocks. The code execute the scriptblock for each command from arguments.
> 2 votes

# Answer
# perl -F// -E, 72 bytes

```
$x=H;/u/?$$x++:/d/?$$x--:($x=/l/?H:M)for@F;printf"%02d:%02d",$H%24,$M%60

```
> 1 votes

# Answer
## Python, 120 bytes

```
o,i=[0,0],0
for s in list(input()):i=(i+(s=='r')-(s=='l')>=1);o[i]+=(s=='u')-(s=='d')
print'%02d:%02d'%(o[0]%24,o[1]%60)

```
> 1 votes

# Answer
# Haskell, 186 bytes

```
f(0,0)'<'
f t i('^':r)=f(i#t$1)i r
f t i('v':r)=f(i#t$ -1)i r
f t i(x:r)=f t x r
f(h,m)_ _=s h++':':s m
('<'#(h,m))n=(mod(24+n+h)24,m)
(_#(h,m))n=(h,mod(60+n+m)60)
s n=['0'|n<10]++show n

```

Try it online!
> 1 votes

# Answer
# R, ~~368~~ 355 bytes

```
f=function(){C=as.character
i=ifelse
p=paste0
r=1:10
h=C(0:23);m=C(0:59)
h[r]=p(0,h[r])
m[r]=p(0,m[r])
x=y=z=1
while(T){print(p(h[x],":",m[y]))
v=1
n="[UDLRS]"
while(!grepl(n,v))v=toupper(readline(n))
if(v=="L")z=1 else if(v=="R")z=0
if(v=="S")T=F
if(v=="U")if(z)x=i(x==24,1,x+1)else y=i(y==60,1,y+1)
if(v=="D")if(z)x=i(x==1,24,x-1)else y=i(y==1,60,y-1)}}

```

Definitely not the best approach, but works.

Functionality: Run function, type each letter to (in/de)crease or move left/right, typing "s" ends the "game". The catch is that it will accept one and only one letter at a time.

**-13 bytes** Consolidated some values into one row, overwrote T as F instead of using break, found several spaces to eliminate, and a string stored in a variable instead

```
f=function(){C=as.character                             # Abbreviate functions
i=ifelse
p=paste0
r=1:10                                                  # Initialize and format values
h=C(0:23);m=C(0:59)
h[r]=p(0,h[r])
m[r]=p(0,m[r])
x=y=z=1
while(T){print(p(h[x],":",m[y]))                        # Begin while loop and print time
v=1                                                     # Initial value reset each iteration to retrieve a new direction
n="[UDLRS]"                                             # Used for verification and request
while(!grepl(n,v))v=toupper(readline(n))                # Will only accept proper directions or stopping rule
if(v=="L")z=1 else if(v=="R")z=0                        # Evaluate for hour or minute
if(v=="S")T=F                                           # Stopping rule, overwrite True to False
if(v=="U")if(z)x=i(x==24,1,x+1)else y=i(y==60,1,y+1)    # Rules for Up
if(v=="D")if(z)x=i(x==1,24,x-1)else y=i(y==1,60,y-1)}}  # Rules for Down

```

I am also editing an alternate format to accept an R string and/or vector, will post next week.
> 1 votes

# Answer
# SmileBASIC, 123 bytes

```
@L
B=BUTTON(2)D=(B==1)-(B==2)S=S+!S*(B>7)-S*(B==4)H=(H+D*!S+24)MOD 24WAIT
M=(M+D*S+60)MOD 60?FORMAT$("%02D:%02D",H,M)GOTO@L

```

`BUTTON()` returns an integer where each bit represents a button

```
1 = up
2 = down
4 = left
8 = right
...

```

`BUTTON(2)` returns only the buttons that were just pressed (not being held)

`WAIT` is required because `BUTTON` only updates once per frame (1/60 of a second). Otherwise the same button press would be detected multiple times.

This can definitely be shorter
> 1 votes

# Answer
# 05AB1E, ~~38~~ ~~37~~ 32 bytes

```
'l¡'rδ¡0ζć‚R€S„0uskOŽ9¦2ä%T‰J':ý

```

Uses `udlr` for the directions, but could also use `^v<>` for the same byte-count (the characters `↑↓←→` are not part of 05AB1E's codepage, so using those would increase the byte-count by a lot, since the encoding should be changed).

Try it online or verify all test cases.

**Explanation:**

```
'l¡          '# Split the (implicit) input on "l"
              #  i.e. "lllrurulddd" → ["","","","ruru","ddd"]
     δ        # Map each item to:
   'r ¡      '#  Split the item on "r"
              #   → [[""],[""],[""],["","u","u"],["ddd"]]
       0ζ     # Zip/transpose; swapping rows/columns, with 0 as filler
              #  → [["","","","","ddd"],[0,0,0,"u",0],[0,0,0,"u",0]]
ć             # Head extracted: pop and push the remainder and head-item to the stack
              #  → [[0,0,0,"u",0],[0,0,0,"u",0]] and ["","","","","ddd"]
 ‚R           # Pair the head and remainder back together, and reverse the pair
              # (so the remainder portion is basically wrapped in a list now)
              #  → [["","","","","ddd"],[[0,0,0,"u",0],[0,0,0,"u",0]]]
   €S         # Convert each item to a list of characters
              # (implicitly flattens and removes empty strings)
              #  → [["d","d","d"],[0,0,0,"u",0,0,0,0,"u",0]]
      „0usk   # Index each character into the string "0u"
              # (0 remains 0; "u" becomes 1; "d" becomes -1 since it's not in this string)
              #  → [[-1,-1,-1],[0,0,0,1,0,0,0,0,1,0]]
           O  # Then take the sum of each inner list
              #  → [-3,2]
Ž9¦           # Push compressed integer 2460
   2ä         # Split into two parts: [24,60]
     %        # Modulo the two lists
              #  → [21,2]
      T‰      # Divmod each with 10
              #  → [[2,1],[0,2]]
        J     # Join each inner list together
              #  → ["21","02"]
         ':ý '# Join the list with ":" delimiter
              #  → "21:02"
              # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž9¦` is `2460`.
> 1 votes

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


# Question
Title: Work out \$x^y\$ using only addition and subtraction
The challenge is to implement a function or program that takes two numbers, \\$x\\$ and \\$y\\$ and return the result of \\$x^y\\$.

The program cannot use any other mathematical operation other than \\$+\\$ or \\$-\\$, so no multiplication or division. Functions built into languages are also not allowed.

The code in the least amount of bytes wins.

# Answer
> 1 votes
# APL (Dyalog Unicode), 7 bytesSBCS

Anonymous tacit infix function. *y* is left argument and *x* is right argument.

```
(+/⍴)/⍴

```

Try it online!

cyclically reshape (gives *y* copies of *x*)

`(``)/` reduce by the following function:

cyclically reshape to left argument copies of right argument

`+/` sum

# Answer
> 1 votes
# Python 2, 53 bytes

```
lambda x,y:y>1and sum(x for _ in range(f(x,y-1)))or x

```

Try it online!

---
Tags: code-golf, math, number, arithmetic, restricted-source
---


title: Name of Frankenstein's Monster

text:
# Question
Title: Name of Frankenstein's Monster
## Introduction:

Since it's almost Halloween, I was just thinking of some random Halloween-themed challenges. Eventually I was reading through Frankenstein's wikipedia page, and came across the following text:

> ### The creature
>
> Part of Frankenstein's rejection of his creation is the fact that he does not give it a name, which causes a lack of identity. Instead it is referred to by words such as "wretch", "monster", "creature", "demon", "devil", "fiend", and "it". When Frankenstein converses with the creature in Chapter 10, he addresses it as "vile insect", "abhorred monster", "fiend", "wretched devil", and "abhorred devil".

source

## Challenge:

Given two integers (year and chapter), output a string based on the following rules:

1. If the year is less than 1818: output an empty string
2. If the year is exactly 1818 and the chapter is below 10: output a random string from the list `["wretch", "monster", "creature", "demon", "devil", "fiend", "it"]`
3. If the year is exactly 1818 and the chapter is 10 or higher: output a random string from the list `["vile insect", "abhorred monster", "fiend", "wretched devil", "abhorred devil"]`
4. Is the year above 1818 (and thus the book was published), return `"Frankenstein's Monster"`.

## Challenge rules:

* You can choose whether to output in lowercase, uppercase, or a combination.
* The year will always be in the range `1500-2017`
* The chapter will always be in the range `1-24` (if I googled correctly, the book has 24 chapters)
* Instead of outputting an empty string for option 1, you are also allowed to output `null`, `undefined`, `false`, `0`, or any other value of your choice not part of the other three options (please specify what you've used in your answer).
* The output may not contain any leading or trailing spaces/tabs, nor any leading new-lines. It may contain one optional trailing new-line.

## General rules:

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

## Test cases:

```
year,chapter possible outputs:

1700,1       ""; null; undefined; false; 0; etc.
1700,12      ""; null; undefined; false; 0; etc.
1817,10      ""; null; undefined; false; 0; etc.
1818,1       "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it"
1818,9       "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it"
1818,10      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1818,11      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1818,18      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1819,1       "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"
1819,18      "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"
2017,24      "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"

```

# Answer
## Perl 5, ~~156~~ ~~153~~ 151 bytes

*-3 bytes thanks to DomHastings.*

Run with `-p`

```
$_=($d=devil,$m=monster,$w=wretch,<"{creature,demon,it,fiend,vile insect,{abhorr,$w}ed {$d,$d,$m},Frankenstein's $m}">)[/818/?6*/,../+rand 7:$_/606-5]

```

This output distribution is non-uniform, which is accepted by default. Specifically, if the date is 1818 and the chapter is ≥10, the names “abhorred devil” and “abhorred monster” are weighted twice as much. This lets me use `rand 7` for both cases, even though the lists are of different sizes.

The output for years before 1818 is “wretched monster”. Despite some similarities, this string is *not* part of any of the other three options, making it okay to use.

This fails for years outside of the 1212—2424 range, but luckily the year is guaranteed by the rules to be in the 1500—2017 range.

Try it online!
> 3 votes

# Answer
# Python 2, ~~227~~ ~~220~~ 214 bytes

```
lambda y,c:[[choice([["wretch",m,"creature","demon",d,F,"it"],["vile insect",a+m,F,"wretched "+d,a+d]][c>9]),"Frankenstein's "+m][y>1818],0][y<1818]
from random import*
m,d,F,a='monster','devil','fiend',"abhorred "

```

Try it online!
> 9 votes

# Answer
## Perl 5, 172 bytes

**171 bytes code + 1 for `-p`.**

```
@a=<><10?($}=wretch,$M=monster,creature,demon,$D=devil,fiend,it):("vile insect",($A="abhorred ").$M,fiend,"$}ed $D",$A.$D);$_=($a[rand@a],"frankenstein's $M",0)[$_<=>1818]

```

Try it online!

### Explanation

Pretty standard, only slightly unsual thing is using the 'spaceship operator' (`<=>`) with `1818` to return `-1`, `0`, or `1`, if the input `$_` is less than, equal to, or greater than `1818` to return the last, first, or second index of the source data. Also, I like the fish operator!
> 6 votes

# Answer
# C# (Visual C# Compiler), ~~225~~ 209 bytes

```
y=>c=>y<1818?"":y>1818?"frankenstein's monster":"wretch,monster,creature,demon,devil,it,fiend,vile insect,abhorred monster,wretched devil,abhorred devil".Split(',')[new System.Random().Next(c>9?6:0,c>9?11:7)];

```

Try it online!

-16 thanks to Kevin Cruijssen

Not particularly concise, but I would expect C# to take more space to declare and use any repeated strings the way the Python answer does than to just repeat them. The included test runner has a `Thread.Sleep(1)` inside the enumeration of test cases because default seeding for `Random()` uses the current time and the actual function runs fast enough to end up with the same seed on subsequent runs without a delay.

Calls to the func use currying syntax, `f(year)(chapter)` (or whatever name the function is stored in instead of f)
> 4 votes

# Answer
# Bash, ~~229~~, ~~206~~, ~~197~~, 179 bytes

```
m=monster
a=("Frankenstein's $m" wretch $m creature demon devil it fiend vile\ insect {abhorr,wretch}ed\ {devil,$m})
echo "${a[$1>1818?0:$1<1818?13:RANDOM%($2>9?5:7)+($2>9?7:1)]}"

```

the explanation about brace/variable expansions

```
m=monster
{abhorr,wretch}ed\ {devil,$m}

```

is first expanded to

```
abhorred\ {$m,devil} wretched\ {devil,$m}
abhorred\ $m abhorred\ devil wretched\ devil wretched\ $m

```

then variable m is expanded

```
abhorred\ monster abhorred\ devil wretched\ devil wretched\ monster

```

however following doesn't work because `$w` will be first joined with `ed` and `wed` is not defined and will be expanded to empty string.

```
m=monster
w=wretch
{abhorr,$w}ed\ {devil,$m}

```

it can be done adding explicit braces arround w but will be longer

```
m=monster
w=wretch
{abhorr,${w}}ed\ {devil,$m}

```

TIO
> 4 votes

# Answer
# Java (OpenJDK 8), ~~275~~ ~~269~~ ~~255~~ ~~207~~ 203 bytes

```
y->c->y<1818?0:y>1818?"Frankenstein's monster":"wretch;monster;creature;demon;devil;it;fiend;vile insect;abhorred monster;wretched devil;abhorred devil".split(";")[c+=Math.random()*(c>9?5:7)+(c>9?6:0)-c]

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 189 bytes

```
m←'monster'
a←'abhorred ',⊢
f←'fiend'
d←'devil'
{⊃⍵=1818:{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵⋄{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵}

```

Try it online!

To test, just append the test case to the last curly bracket like so:

```
{⊃⍵=1818:{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵⋄{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵}1818 10

```

Huge thanks to @ngn for helping out with the leading whitespace issue.

### How it works:

It's worth noting that APL interprets strings as arrays (*vectors*) of characters, so `'wretch' 'creature'` would be interpreted in other languages as `[[w,r,e,t,c,h],[c,r,e,a,t,u,r,e]]`

These are helper functions:

```
m←'monster'      #These are pretty self explanatory, variables m, f and d are being set to 'monster', 'fiend' and 'devil respectively.
f←'fiend'
d←'devil'
a←'abhorred ',⊢  # a is being set to 'abhorred ' concatenated with the argument to it's right.

```

This is the main function, which will be broken in 3 parts for better understanding:

```
{⊃⍵=1818:{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵⋄{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵}

```

Part 1:

```
{⊃⍵=1818:{Part2}⍵⋄{Part3}⍵} # First conditional
        :                   # If
 ⊃                          # the first element
  ⍵                         # of the argument ⍵
   =1818                    # Equals the literal 1818
         {Part2}⍵           # Executes part 2 with argument ⍵
                 ⋄          # Else
                  {Part3}⍵  # Executes part 3 with argument ⍵

```

Part 2:

```
{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄ # Second conditional
(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵
       :                                         # If
 ⊃                                               # the first element
  ⌽                                              # of the inverse
   ⍵                                             # of the argument ⍵
    <10                                          # is less than 10
           ⊃                                     # pick the nth
       (?7)                                      # random element between [1,7]
            'wretch'm'creature' 'demon'd f'it'   # from this string array
                                              ⋄  # Else
    ⊃                                            # pick the nth
(?5)                                             # random element between [1,5]
     'vile insect'(a m)f('wretched ',⊢d)(a d)    # from this string array
                                             }⍵  # using argument ⍵

```

Part 3:

```
{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵ # Third conditional
        :                           # If
 ⊃                                  # the first element
  ⍵                                 # of the argument ⍵
   >1818                            # is greater than 1818
         'frankenstein''s ',⊢m      # print the string "frankenstein's" concatenated with m (which prints monster)
                              ⋄     # else
                               ''   # print an empty string
                                 }⍵ # with argument ⍵

```
> 2 votes

# Answer
# PHP, ~~184~~ 176 bytes

```
<?=strtr([0,1,2,Creature,Demon,It,Fiend,30,31,"2ed 1","Vile Insect","Frankenstein´s 0"][[rand(6*$x=$argv[2]>9,6+4*$x),11][$argv[1]<=>1818]],[Monster,Devil,Wretch,"Abhorred "]);

```

Run with `-n` and give year and chapter as command line arguments or try it online.

index and thus result evaluate to `NULL` for year\<1818, leading to empty output.
> 2 votes

# Answer
# Javascript (ES6), 205 bytes

```
a="abhorred ",d="devil",f="fiend",m="monster"
y=>c=>y<1818?0:y>1818?"frankenstein's "+m:(l=c<10?[f,"wretch",m,"creature","demon",d,f,"it"]:["vile insect",a+m,f,"wretched "+d,a+d])[0|Math.random()*l.length]

```

Returns `0` if the year is less than 1818

```
a="abhorred ",d="devil",f="fiend",m="monster"
n=y=>c=>y<1818?0:y>1818?"frankenstein's "+m:(l=c<10?[f,"wretch",m,"creature","demon",d,f,"it"]:["vile insect",a+m,f,"wretched "+d,a+d])[0|Math.random()*l.length]
```

```
<div oninput="o.innerText=n(y.value)(c.value)"><input id=y type=number value=1817 /><input id=c type=number value=10 /></div><p id=o>0
```
> 1 votes

# Answer
# C, 380 BYTES

```
void ok(int *year, int* chapter){char*below_10[] = {"wretch", "monster", "creature", "demon", "devil", "fiend", "it"}; char*at_10[] = {"vile insect", "abhorred monster", "fiend", "wretched devil", "abhorred devil"}; year < 1818?printf("0"):(year == 1818?(chapter<10 printf("%s",below_10[rand()%8]):printf("%s",at_10[rand()%7])):printf("Frankenstein's Monster"));}

```
> 1 votes

# Answer
# Javascript 199 bytes

```
M="monster"
A=(y,c)=>y<1818?"":y^1818?"Frankenstein's "+M:[W="wretch",M,"creature","demon",D="devil",F="fiend","it","vile insect",(H="abhorred ")+M,F,W+"ed "+F,H+D][Math.random()*(c>9?5:7)+7*(c>9)|0]

console.log(A(1700,1))
console.log(A(1700,12))
console.log(A(1817,10))
console.log(A(1818,1))
console.log(A(1818,9))
console.log(A(1818,10))
console.log(A(1818,11))
console.log(A(1819,1))
console.log(A(1819,18))
console.log(A(2017,24))
```
> 1 votes

# Answer
## MBASIC, 288 bytes

```
1 DIM R$(12):FOR I=1 TO 12:READ R$(I):NEXT:INPUT Y,C:IF Y<1818 THEN 5
2 IF Y>1818 THEN O$="Frankenstein's Monster":GOTO 5
3 IF C>9 THEN O=7
4 O$=R$(O+INT(RND(1)*N+1))
5 PRINT O$:DATA wretch,monster,creature,demon,devil,fiend,it,vile insect,abhorred monster,fiend,wretched devil,abhorred devil

```
> 1 votes

# Answer
# 05AB1E, ~~114~~ 110 bytes

```
0…ë¢¼–±¹.•ʒ¦Ë"ìËM₂G¶тá≠•ì#.•1ÏiT¥Ƶʒ“T¡Äg… 5ÀΘO¼™Ãí?ιË%4₄‡‡λYιi¾н••Jtm•17в£‚…'s 'ì³R7£R’¡¬ÿÿ±¹’¸¸)sŽ7X.S>èsT@èΩ

```

Outputs `0` when the year is below `1818`.

Try it online or verify all test cases.

**Explanation:**

```
0                    # Push a 0
…ë¢¼–±¹              # Push dictionary string "creature devil monster"
 .•ʒ¦Ë"ìËM₂G¶тá≠•   "# Push compressed string "demon fiend it wretch "
  ì                  # Prepend it: "demon fiend it wretch creature devil monster"
   #                 # Split by spaces: ["demon","fiend","it","wretch","creature","devil","monster"]
.•1ÏiT¥Ƶʒ“T¡Äg… 5ÀΘO¼™Ãí?ιË%4₄‡‡λYιi¾н•
                     # Push compressed string "abhorred devilabhorred monsterfiendvile insectwretched devil"
 •Jtm•               # Push compressed integer 1249548
      17в            # Converted to Base-17 as list: [14,16,5,11,14]
         £           # Split the string into parts of that size: ["abhorred devil","abhorred monster","fiend","vile insect","wretched devil"]
‚                    # Pair both string-lists together
…'s                 '# Push string "'s "
   'ì³              '# Push dictionary string "liechtenstein"
      R7£R           # Leave the last 7 characters: "enstein"
          ’¡¬ÿÿ±¹’   # Push dictionary string "frankÿÿmonster", where the "ÿ" are automatically
                     # replaced with the strings at the top of the stack: "frankenstein's monster"
                  ¸¸ # Wrap it twice into a list: [["frankenstein's monster"]]
)                    # Wrap everything on the stack into a list
                     # (We now have: [0,[["demon","fiend","it","wretch","creature","devil","monster"],["abhorred devil","abhorred monster","fiend","vile insect","wretched devil"]],[["frankenstein's monster"]]])
 s                   # Swap to get the first (implicit) input
  Ž7X                # Push compressed integer 1818
     .S              # Compare it with the input (-1 if below; 0 if equal; 1 if above)
       >             # Increase it by 1 (0 if below; 1 if equal; 2 if above)
        è            # Use it to index into the list
         s           # Swap to get the second (implicit) input
          T@         # Check if it's larger than or equal to 10 (results in 0 for falsey; 1 for truthy)
            è        # Use it to index into the inner list
             Ω       # And finally get a random value from that list (which is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?*; *How to compress strings not part of the dictionary?*; *How to compress large integers?*; and *How to compress integer lists?*) to understand why:

* `…ë¢¼–±¹` is `"creature devil monster"`;
* `.•ʒ¦Ë"ìËM₂G¶тá≠•` is `"demon fiend it wretch "`;
* `.•1ÏiT¥Ƶʒ“T¡Äg… 5ÀΘO¼™Ãí?ιË%4₄‡‡λYιi¾н•` is `"abhorred devilabhorred monsterfiendvile insectwretched devil"`;
* `•Jtm•` is `1249548` and `•Jtm•17в` is `[14,16,5,11,14]`;
* `'ì³` is `"liechtenstein "`;
* `’¡¬ÿÿ±¹’` is `"frankÿÿmonster"`;
* `Ž7X` is `1818`.
> 0 votes

# Answer
# JavaScript, 194 B

```
e=Math.random,f=Math.floor;x=(a,b,c=`insect,monster,wretch,creature,demon,devil,fiend,it`.split`,`,d=[`vile `,`abhorred `])=>a<1818||a-1818?`Frankenstein's `+c[1]:(b<10||c[f(e()*2)])+c[f(e()*8)]

```
> -1 votes

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


title: Encrypted In Numbers!

text:
# Question
Title: Encrypted In Numbers!
# The Problem:

Two enemy secret agents have devised a wonderful (for you) method of communication!

Here’s how the encryption process works:

1) Take the ascii equivalents of each letter. (No spaces, numbers, or punctuation are sent)

2) For each letter in the message, the ascii equivalent of it and the letter after it (If it exists, if it doesn’t, it should be considered 0), are multiplied (this product is stored in an array/list) and summed (this number is also stored in a different list).

3) The two lists (of sums and products) are joined together (the sums list, then the multiples list, into the same array) and transmitted.

You need to write the smallest program able to reverse this process and decrypt messages sent in this format!

# Example Input and Output Pairs:

```
[173, 209, 216, 219, 198, 198, 225, 222, 208, 100, 7272, 10908, 11664, 11988, 9657, 9657, 12654, 12312, 10800, 0] -> “HelloWorld”
[131, 133, 164, 195, 197, 99, 4290, 4422, 6499, 9506, 9702, 0] -> “ABCabc”

```

# This is , so the smallest solution in bytes wins.

Error messages are allowed.

Your program can be given either a list/1-dimensional array or a comma-separated string, if you specify in your submission. The default is an array/list.

# Answer
> 5 votes
# Husk, ~~7~~ 6 bytes

```
mcĠ≠←½

```

Try it online! According to the documentation the leading `m` should not be needed, but there seems to be a bug currently.

*Edit: -1 byte thanks to Zgarb!*

### Explanation:

```
     ½ -- split input list into half
    ←  -- take first list
  Ġ≠   -- subtract each list element from the previous one
mc     -- convert list of code points to string

```

# Answer
> 8 votes
# brainfuck, 66 bytes

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

```

Input is the encrypted string. Assumes infinite sized cells and 0 on EOF.

### How it Works:

```
,[>>>+<[-<+>>-<]<[->+<],] Gets input and the number of characters divided by 2
>[<<,>>[-<+>]<-]<<< Remove the second half of the string (the multiplication part)
[>[-<->>+<]<<] Subtract each character from the previous one, while keeping a copy of the previous one.
>.>>[.>] Print the characters

```

# Answer
> 5 votes
# Haskell, ~~45~~ 35 bytes

```
map toEnum.scanr1(-).fst.span(<245)

```

Try it online!

### Explanation

* `fst.span(<245)` takes all numbers from the beginning of the list that are smaller than 245. Those are only the numbers from the summation part, because the largest possible summation is `z + z = 122 + 122 = 244`, and the smallest possible product is `A * A = 65 * 65 = 4225`.
* `scanr1(-)` takes the last value of the list and uses it as initial accumulator. Then from back to front each element of the list is subtracted by the current accumulator, and the result is used as the next accumulator and and added to a list.
* `map toEnum` replaces each number in the list with the corresponding character to recreate the string.

# Answer
> 3 votes
# Jelly, 9 bytes

```
œs2ḢUạ\ỌU

```

Try it online! or Check both test cases.

Alternative.

### Explanation

```
œs2ḢUạ\ỌU || Full program.

œs2       || Split into two parts, with the first one being longer if necessary.
   Ḣ      || Get the head (first element).
    U     || Reverse.
     ạ\   || Cumulative reduce by subtraction.
       Ọ  || Convert from code points to characters.
        U || And reverse again.

```

# Answer
> 3 votes
# Python 2, 72 bytes

```
a=input();p=0;r=''
for v in a[len(a)/2-1::-1]:r=chr(v-p)+r;p=v-p
print r

```

Try it online!

# Answer
> 2 votes
# Python 2, 92 bytes

```
lambda C:"".join(chr(sum((-1)**i*C[j+i]for i in range(len(C)/2-j)))for j in range(len(C)/2))

```

Try it online!

# Answer
> 2 votes
# Jelly, 11 bytes

```
œs2Ḣḅ-$ÐƤAỌ

```

A monadic link taking a list of integers and returning a list of characters.

**Try it online!**

### How?

```
œs2Ḣḅ-$ÐƤAỌ - Link: list of integers     e.g. [210,211,201,101,10989,11100,10100,0]
  2         - literal two                     2
œs          - split into equal parts          [[210,211,201,101],[10989,11100,10100,0]]
   Ḣ        - head                            [210,211,201,101]
       ÐƤ   - for postfixes:                  [210,211,201,101],[211,201,101],[201,101],[101]
      $     -   last two links as a monad:
     -      -     literal minus one           -1
    ḅ       -     convert from base           -99              ,111          ,-100      ,101
         A  - absolute value (vectorises)     [99,111,100,101]
          Ọ - convert to ordinal (vectorises) "code"

```

# Answer
> 1 votes
# Pyt, 60 bytes

```
←ĐĐŁ₂⁻⦋⇹ĐŁřĐŁ₂>*ž0`ŕĐĐŁ⁻⦋3ȘĐ4Ș3Ș4Ș÷⇹ĐŁřĐŁ<*žĐŁ⁻łŕ⇹Đ3Ș⇹÷Á↔áƇǰ

```

Takes a list of integers and returns a string of characters.

Explanation:

```
←ĐĐŁ₂⁻⦋⇹          Gets the ASCII code of the last character
ĐŁřĐŁ₂>*ž         Gets the list of products and removes the 0 from the end of the list
0`ŕ ...  ł        Loops (0 is there so that the length can be removed from the stack)
ĐĐŁ⁻⦋              Gets the last product
3ȘĐ4Ș3Ș4Ș÷        Divides by the last ASCII code obtained
⇹ĐŁřĐŁ<*ž         Removes the last element from the array
ĐŁ⁻ł              Gets the length of the array - 1 (if 0, then exit loop - the last entry still has to be processed)
ŕ⇹Đ3Ș⇹÷           Divides the remaining product by the last ASCII code obtained
Á↔á               Converts to array of ints
Ƈǰ                Converts to string of ASCII characters

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 80 bytes

```
a=>String.fromCharCode(...eval(`for(a.splice(i=a.length/2);--i;a[i-1]-=a[i])a`))

```

```
f=

a=>String.fromCharCode(...eval(`for(a.splice(i=a.length/2);--i;a[i-1]-=a[i])a`))

console.log(
    f([173, 209, 216, 219, 198, 198, 225, 222, 208, 100, 7272, 10908, 11664, 11988, 9657, 9657, 12654, 12312, 10800, 0]),
    f([131, 133, 164, 195, 197, 99, 4290, 4422, 6499, 9506, 9702, 0])
)
```

# Answer
> 1 votes
# C (gcc), ~~90~~ 89 bytes

* Saved a byte thanks to ceilingcat; `s+=(i%2?-1:1)*...` \<~\> `s-=~(i%2*-2)`.

```
D(C,l,j,s,i)int*C;{for(j=~0;++j<l/2;putchar(s))for(s=i=0;i+j<l/2;)s-=~(i%2*-2)*C[i+++j];}

```

Try it online!

# Answer
> 1 votes
## VB Script - ~~74~~ 71 bytes

( I managed to reduce from 74 to 71 by using While..Wend instead of Do..Loop)

The input is in an array a(), the output is in string d

```
d="":p=0:n=(UBound(a)+1)/2:While n>0:n=n-1:t=a(n)-p:d=Chr(t)&d:p=t:Wend

```

Explanation

```
d=""          '// initialize the output string
p=0          '// initialize the ansii of following char (working back from last char)
n=(Ubound(a)+1)/2 '// the index of the last summed pair + 1 (base 0)
While n>0    '// begin loop working back from last summed pair
n=n-1        '// move back 1 char
t=a(n)-p     '// calculate the ansii by subtracting the ansii of following char
d=Chr(t)&d   '// prepend the char to output
p=t          '// this char becomes the following char for next
Wend         '// repeat etc.

```

I tested this in a vbscript file with the above code wrapped as a function:

```
dim s
Dim arr()
s = Split("173, 209, 216, 219, 198, 198, 225, 222, 208, 100, 7272, 10908, 11664, 11988, 9657, 9657, 12654, 12312, 10800, 0", ",")
ReDim arr(UBound(s))
Dim x
For x = 0 To UBound(s)
    arr(x) = cint(s(x))
Next

msgbox "=" & d(arr)

Private Function d(a())
d="":p=0:n=(UBound(a)+1)/2:While n>0:n=n-1:t=a(n)-p:d=Chr(t)&d:p=t:Wend
End Function

```

# Answer
> 1 votes
# Clean, ~~96~~ ~~81~~ ~~78~~ 77 bytes

`zero` is the null character.
I could save another byte if Clean wasn't so picky about literal nulls in the source file.

```
import StdEnv
f=init o foldr(\a t=[toChar a-t!!0:t])[zero]o takeWhile((>)245)

```

Try it online!

# Answer
> 1 votes
# Perl 5, 39 + 2 (`-ap`) = 41 bytes

```
$#F/=2;$\=chr($p=-$p+pop@F).$\while@F}{

```

Try it online!

# Answer
> 0 votes
# Standard ML (MLton), ~~85~~ ~~84~~ 82 bytes

```
fun!(x::r)=if x>244then[]else(fn z::s=>x-z::z::s|_=>[x])(!r);implode o map chr o!;

```

Try it online!

### Ungolfed:

```
fun g (x::r) =
   if   x > 244
   then []
   else case g r of
          z::s => x-z :: z :: s
        |  []  => [x]

val f = implode o map chr o g

```

Try it online!

# Answer
> 0 votes
# Perl 6,  ~~43 39~~  35 bytes

```
{[~] [R,](produce *R-*,[R,] .[^*/2])».chr}

```

Test it

```
{[~] [R,]([\[&(*R-*)]] [R,] .[^*/2])».chr}

```

Test it (does the same as above)

```
{[~] [R,]([\R[&(*R-*)]] .[^*/2])».chr}

```

Test it

```
{[R~] [\R[&(*R-*)]](.[^*/2])».chr}

```

Test it

## Explanation:

```
{[R~] [\R[&(*R-*)]](.[^*/2])».chr}

{                                }      # block lambda with parameter `$_`

      [\R[&(*R-*)]](.[^*/2])            # turn sums back into ordinals (reversed)

                    .[^*/2]             # first half of `$_` (implicit method call)
            *R-*                        # lambda, reverse of *-*
         [&(    )]                      # use it as an infix operator
                                        # (same as R- except left associative)
        R                               # reverse arguments and associativity
                                        # (same as - except right associative)
      [\          ](       )            # produce values `[\+] 1,2,3` => `(1,3,6)`
                                        # uses associativity to determine direction
                                        # `[\**] 1,2,3` => `(3,8,1)`

                            ».chr       # call `.chr` method on all values
                                        # (possibly concurrently)

 [R~]                                   # concatenate in reverse
                                        # (shorter than `join '', reverse …`)

```

# Answer
> 0 votes
# 05AB1E, 9 bytes

```
2ä¬Å«-}çJ

```

Try it online!

## Explanation

```
2ä        # Split input list in two (equal if possible) parts.
  ¬       # Push head(a).
   Å«-}   # Cumulative reduce the list by subtraction (from the right).
       ç  # Convert each integer in the list to its corresponding ASCII char.
        J # Join list together to string.

```

# Answer
> 0 votes
# Japt, 12 bytes

There has to be a shorter way to get the first half of the array ...

```
¯UÊz)Ôån Ômd

```

Try it

# Answer
> 0 votes
# Python 2, 70 bytes

```
l,j,s=input(),0,'';n=len(l)/2
while n:n-=1;j=l[n]-j;s=chr(j)+s
print s

```

Try it online!

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


# Question
Title: Pair-golfing Twin primes and the Collatz sequence
*This is a new kind of challenge inspired by the Recover the mutated source code problem.*

You should write two programs or functions both in the same language. The first one should solve Task #1 and the second one should solve Task #2.

**Your score will be the sum of the longer program and the Levenshtein distance between the two programs source code.** Lower score is better so you should try to make the two solutions similar while keeping the lengths of the programs short.

## Task #1

You are given a positive integer `N` and you should output the Collatz sequence of `N` separated by spaces or newline. Trailing separator is allowed.

The first element of the Collatz sequence is `N`. The rest of the elements are generated based on their successor \\$a\_{i-1}\\$:

$$ a\_i = \begin{cases} \frac{a\_{i-1}}{2} & \text{ if } a\_{i-1} \text{ is even} \\ 3a\_{i-1} + 1 & \text{ if } a\_{i-1} \text{ is odd} \end{cases} $$

As soon as the sequence reaches `1` no new elements are generated.

Input =\> Output examples:

```
6 => 6 3 10 5 16 8 4 2 1
8 => 8 4 2 1
1 => 1

```

## Task #2

A pair of twin primes is a pair of positive integer whose difference is 2 and they are both primes.

You are given a positive integer `N` and you should output the smallest pair of twin primes where both primes are bigger than `N` The first number should be the smaller one and the two primes should be separated by spaces or newline. Trailing separator is allowed.

Input =\> Output examples:

```
6 => 11 13
42 => 59 61
1 => 3 5

```

## Snippet for calculating the score

(Modification of the one in the Recover the mutated source code problem.)

```
var f=document.getElementById("f"),g=document.getElementById("s");function h(){var a=f.value,e=g.value,m=Math.max(a.length,e.length);if(10000<a.length)a="<span style='color:red'>First program is too long!</span>";else if(10000<e.length)a="<span style='color:red'>Second program is too long!</span>";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = "+a+"   Longer length = "+m+"   Score = <strong>"+(a+m)+"</strong>"}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h;
```

```
First program<textarea id=f rows=2 cols=80 style="width:100%"></textarea>Second program<textarea id=s rows=2 cols=80 style="width:100%"></textarea><p id=d></p>
```

## Edit

In the answers' header let's use the format

`[Language], [longer length] + [distance] = [final score]`.

E.g.

`Python 2, 60 + 32 = 92`

# Answer
# Pyth, 18 + 13 = 31

Collatz Sequence:

```
QWtQ=Q@,/Q2h*Q3QQ

```

Twin Primes:

```
=Qf!ttP*T+T2hQQ+Q2

```

Try it here.

Some ideas thanks to FryAmTheEggman.
> 3 votes

# Answer
# CJam, 24 + 17 = 41 ~~42~~

**Collatz program**:

```
ri2*{:N2%N3*)N2/?__p(}g;

```

**Twin primes program**:

```
ri_2+]{:)_{mp}/&_+((}gS*

```

Both take input from STDIN and print space/newline separated numbers to STDOUT

Try them online here
> 4 votes

# Answer
# CJam, 25 + 16 = 41

**Collatz program:**

```
l~2*{_2%{3*)}{2/}?_p_(}g;

```

**Twin primes program:**

```
l~_2+]{:)_{mp}/&!_&}gS*

```

Test it here.

I just golfed both of them for now. I'll see if I can reduce the score somehow.
> 3 votes

# Answer
## Pyth, 20 + 14 = ~~40~~ 34

### Collatz:

```
QWtQ=Q@,/Q2h*3QQQ

```

### Prime Pairs:

```
~Q1WttP*Q+Q2~Q1;Q+Q2

```

Both are programs that take input from STDIN and output the numbers on newlines. Just golfed both answers while using the same looping primitive for now. This could probably be improved quite a bit.

Edit: Added better condition checking stolen from @isaacg. Seems like using filter is still shorter than using a while loop for the prime pairs.

Try it online here.
> 2 votes

# Answer
# 05AB1E, 14 + ~~13~~ ~~10~~ 9 = ~~27~~ ~~24~~ 23

-4 score thanks to ASCII-only

## Collatz sequence (14 bytes):

```
[DÉi3*>ë2÷}Ð,#

```

Try it online!

## Twin primes (14 bytes):

```
[DÅND>>Dp#}s,,

```

Try it online!

---

### Golfed Twin primes (11 bytes):

```
[ÅNDÌp#]DÌ»

```

Try it online!
> 2 votes

# Answer
# Java 8, 118 + 84 = 202

Collatz:

```
n->{for(System.out.println(n);n>1;System.out.println(n=n%2<1?n/2:3*n+1));}

```

Twin primes:

```
n->{t:for(int p,z;;n++){for(z=n;z<n+3;z=z+2)for(p=2;p<z;p++)if(z%p<1)continue t;System.out.print(n+" "+(n+2));break;}}

```
> 1 votes

# Answer
# \>\<\>, 116 + 86 = 202

**Collatz program** (46):

```
0i:0(?v$a*$'0'-+!
?v6,>:>~:nao:1=?;3*:2%
 >1+^

```

**Twin primes program** (116):

```
0i:0(?v$a*$'0'-+!
v&2+1~<:-2
<v!?%&+1:&:v?=&:&:
 >&~0$2&2+v>&~143.
:&:1+&%?!v>:&:&=?v
0v?*r$0~&< .561~&<.1
:<;noan-2

```

Ouch. Both programs start with the same `atoi` function, but after that twin primes goes downhill. The same piece of code is repeated twice for primality check — it might be slightly shorter to somehow reuse the piece, but the setup for it wouldn't save many bytes.

Could do a lot better by throwing the back half of twin primes into the unused spots of the Collatz program, but I'm not sure if that's allowed.
> 1 votes

# Answer
# Mathematica, 53 + 29 = 82

Collatz Sequence:

```
Print/@(NestWhileList[If[OddQ@#,3#+1,#/2]&,#,#>1&]);&

```

Twin primes program:

```
Print/@(NestWhile[NextPrime,#,!PrimeQ[#+2]&]+{0,2});&

```
> 1 votes

# Answer
## C++ Distance = 114 Longer length = 155 Score = 269

Task 1

```
void c(int N){while(N>1){cout<<N<<' ';N=(N%2==0)?N/2:N*3+1;}cout<<N;}

```

Task 2

```
int p(int x){int z=0;for(int i=2;i<x;i++){if(x%i==0){z=1;break;}}return z;}
void c(int N){N=(N%2==0)?N+1:N+2;int M=N+2;while(p(N)+p(M)>0){N=M;M+=2;}cout<<N<<' '<<M;}

```

Task 2 improved

```
int p(int N){int z=0;for(int i=2;i<N;i++){if(N%i==0){z=1;break;}}return z;}
void c(int N){N=(N%2==0)?N+1:N+2;while(p(N)+p(N+2)>0){N+=2;}cout<<N<<' '<<N+2;}

```
> 0 votes

---
Tags: code-golf, number, sequence, primes, multiple-holes
---