New answers tagged

0

Haskell, 88 bytes f=head.filter((0==).sum).concat.iterate(concat.zipWith map[tail,init].replicate 2).(:[]) Try it online!


1

Desmos, 154 139 137 bytes Thanks @fireflame241 for helping me golf a couple of bytes (on Discord) A=length(l) B=[1...A-f] Z=[0...A] h(a,b)=\{\sum_{C=a}^bl[C]=0,0\} f=\max((Z+1)\sign(\sum_{n=1+Z}^Ah(n-Z,n))) g(l)=[f,\max(Bh(B,[f...A]))] Uses Output Format #4. The first element in the outputted list is the length of the subarray, while the second element is ...


1

PHP, 101, 99, 90 for(;$argc>$j=++$i;)for(;$j;)array_sum(array_slice($argv,$j--,$l=$argc-$i))||die("$j,$l"); Try It Online Input is array elements as the command line argument list. Outputs the zero based start position and length of sub array. Does not output anything for the null case.


6

K (ngn/k), 24 22 21 bytes {t@'*<-/t:&x=/:x}0,+\ Try it online! -1 byte thanks to coltim and Traws Unfortunately(?), I found a 2-byte golf that bumps the time complexity to \$\mathcal{O}(n^2 \log n)\$ (and space complexity to \$\mathcal{O}(n^2)\$). This one utilizes "equality table" =/: and "deep where" & to extract all pairs ...


4

Risky, 12 bytes {_*_1?+?:_0{_-+_0+_0+_0 Try it online! Explanation Here's a rough tree diagram of how the program parses: { ? + * : + + { _ + _ _ _ _ _ _ 1 ? 0 - 0 0 0 The left half generates a list of all sublists that sum to zero: {_ List of sublists of the input (ordered ...


2

Brachylog, 13 9 bytes -4 bytes thanks to a clever trick from Unrelated String ⊇.+0&s.∨Ė Try it online! (Note that negative numbers in the input must be indicated with underscores rather than minus signs.) Explanation It would have been nice to use this 6-byte solution: s.+0∨Ė s. A contiguous sublist of the input is the output +0 and its sum ...


1

Haskell, 75 bytes f i=last[(s,l)|l<-[0..length i],s<-[0..length i-l],0==sum(take l$drop s i)] Try it online! Outputs first index and length as a tuple.


1

Perl 5, 73 bytes sub{(sort{@$b-@$a}grep!sum(@$_),map[@_?@_[$_/@_..$_%@_]:()],0..@_**2)[0]} Try it online!


1

Clojure, 98 bytes #(or(first(for[n[(count %)]i(range n)j(range n i -1):when(=(apply +(subvec % i j))0)][i j]))[1 0]) Returns an exclusive range, or [1 0] if no such range is found. For example: [1,2,3,4,5,-4,-3,-2,-1,0] -> [3 8]


0

Charcoal, 26 bytes F⊕LθF⊕⁻Lθι⊞υ✂θκ⁺κι¹I⊟Φυ¬Σι Try it online! Link is to verbose version of code. Explanation: F⊕LθF⊕⁻Lθι⊞υ✂θκ⁺κι¹ Carefully list the subsequences of the input in ascending order of length. I⊟Φυ¬Σι Get those with a zero sum (or no sum at all, in the case of the empty subsequences) and output the last i.e. the longest.


4

Factor + math.unicode, 64 bytes [ [ "1"] when-empty all-subseqs [ Σ 0 = ] filter ?last >array ] Try it online! [ "1"] when-empty Unfortunately necessary to handle the empty sequence. all-subseqs blows up otherwise. "1" is simply the shortest thing you can stick in there that ultimately produces the empty sequence. all-...


5

JavaScript (ES6), 60 bytes f=(b,...a)=>eval(b.join`+`)?f(...a,b.slice(1),b.pop()?b:b):b Try it online! Commented f = ( // f is a recursive function taking: b, // b[] = next array ...a // a[] = list of all other arrays ) => // eval(b.join`+`) ? // if the sum of b[] is not ...


5

Japt -h, 5 bytes ã k_x Try it or run all test cases ã k_x :Implicit input of array ã :Sub-arrays k :Remove elements that return truthy (not 0) _ :When passed through the following function x : Reduce by addition :Implicit output of last element of resulting array (or undefined if empty)


3

Wolfram Language (Mathematica), 37 36 bytes Last@*Select[Tr@#==0&]@*Subsequences -1 byte from att using function composition Try it online! Subsequences generates all contiguous subsequences, sorted by length; Select[Tr@#==0&] selects those whose trace (total) is 0; Last selects the last, and thus longest, of these subsequences. att also shows, in ...


16

Python 3, 47 bytes f=lambda x,*a:f(*a,x[1:],x[:-1])if sum(x)else x Try it online! It's simple breadth-first search, implemented recursively. The if...else is slightly bothering me; it feels like there is an improvement somewhere...


2

Python 3, 85 bytes lambda a:[(s,l)for l in range(len(a))for s in range(len(a)-l)if 0==sum(a[s:s+l])][-1] Try it online! -5 bytes thanks to totallyhuman


6

05AB1E, 7 bytes ŒéʒO_}θ Try it online! Œ # sublists of the input é # sort by length ʒ } # keep those where: O_ # the sum equals 0 θ # take the last one The output of Œ doesn't contain the empty list, but if the result of the filter is empty, θ fails and leaves the empty list on the stack.


4

J, 28 bytes <\\.;@{.@(\:#&>)@#~&,0=+/\\. Try it online! <\\....#~&,0=+/\\. All boxed sublists <\\. filtered by those with 0 sum #~ 0=+/\\. after flattening both &,. (\:#&>)@ Sort down by length ;@{.@ And open the first element.


4

Vyxal, 7 bytes ÞS'∑¬;t # main program ÞS # sublists '∑¬; # filter ∑¬ # by the negated sum t # take the tail Similar to @hyper-neutrino's answer. Try it Online!


6

Jelly, 7 bytes ẆSÐḟṪȯ$ Try It Online! Converted from a full program to a link for the same byte-count thanks to Jonathan Allan. ẆSÐḟṪȯ$ Main Link Ẇ Get all sublists (unfortunately excludes the empty sublist) Ðḟ Filter to remove elements with a non-falsy/non-zero S sum $ Apply monadically to the resulting list of ...


0

Perl 5, 35 bytes $_=pop@F;for$f(@F){s/,$f\b|\b$f,//} Try it online!


2

Jelly, 51 bytes Ẓ&/Ä<5S‘x3ɓBSZḊḣ" O%9Ṭ€;Øỵ¬a"“µ¦¤‘ṁ$+⁴Fṁ⁽½c)ÇċⱮ€LŻ$ A monadic Link that accepts the list of patterns and yields the list of lists of counts. Try it online! How? Ẓ&/Ä<5S‘x3ɓBSZḊḣ" - Link 1: list of lists of colours at each second, L where F=25, C=21, A=19, and off=16 Ẓ - ...


4

Jelly, 55 bytes ŻI»0Ä’%3‘× Ø0œịŻṖÄ<5a O%9ÄṬ;Øỵ¬Ñṁ⁽½c)Zċþ3Sṭ$=þ@LŻ$ṪṭÇƊ§ Try it online! A full program taking a list of strings and printing a list of lists of integers. The first part (converting from Ss and Ls to the sequence dir each lighthouse was derived from @JonathanAllan’s answer to the previous challenge. Explanation Helper link 1 Convert a list ...


0

Python 2, 203 200 bytes E=enumerate l=input() t=eval(`[[0]*-~len(l)]*4`) for i in range(3600): for y,q in E(t):q[sum(y==((sum([~ord(w)%5*[j%3]+[3]for j,w in E(c)],[])+[3]*6)*450)[i]for c in l)^0-y/3]+=y*y|5>t[2][-1] print t Try it online! Building the pattern with strings instead of lists of digits comes out at the same length and is a bit faster: Try ...


3

05AB1E, 52 bytes Based on my answer to the previous challenge. ε€C9%Å10.ý˜7Å0«Dη_O3%>*60n∍}øÐ3QP.¥5‹Ï3LδQøs<dªεOZÝ¢ Try it online! ε€C9%Å10.ý˜7Å0« 60n∍} # see my previous answer Dη # push all prefixes of the signal _O # count the number of 0's (how often the signal was off) ...


4

J, 129 bytes <@(0,#\)(<:@(#/.~@,+/))&>[:(<@(+/),~]<@({.&.|:"2)~[:{:5{.!._[:>:@I.*/@{:)1 2 3=/(3600$(6$0),~&;[:(*&.>1 2 3$~$)19<@#:@|14+3&u:)&> Try it online!


2

Haskell, 87 bytes x?[]=[] x?([c]:d)=(x++[c])?d x?((c:d):e)=(x++c:map head e):x?(d:e) f x=[]?x++[last<$>x] Try it online


3

JavaScript (ES6), 40 bytes a=>a.every(n=>a[a[~n]=-~a[~n],-n]--|n<2) Try it online! Ungolfed: arr => { const count = [Infinity] for (let i = 0; i < arr.length; i++) { const num = arr[i]; count[num] = (count[num] || 0) + 1; count[num - 1] = (count[num - 1] || 0) - 1; if (count[num - 1] < 0) { return false; } }...


4

Jelly, 8 7 bytes Ṭ€+\I’Ȧ Try it online! -1 byte thanks to Jonathan Allan Outputs an empty array (falsey) if it can be the result, and a non-empty array (truthy) if not. How it works Ṭ€+\I’Ȧ - Main link. Takes a list L on the left € - For each integer I in L: Ṭ - Untruth; Generate a list of zeroes of length I, replace the last with 1 \ - ...


2

Japt, 16 15 bytes Quite exhausted so I'm sure I'll improve upon it in the morn'. Less sure that it's actually correct so, mods, please delete if it's not. Shockingly, it was correct! Haven't been able to improve much on my score, though. e1g2Æ=¡YôgU è¶X Try it or run all test cases


1

R, 119 116 bytes Edit: -3 bytes thanks to Giuseppe function(a)table(c(rowSums(sapply(a,function(x)!1:3600%in%cumsum(rep(c(utf8ToInt(x)%%9,!!1:6),999)))),0:sum(a>0)))-1 Try it online!


1

Python 3, 154 bytes Very trivial approach: convert the code strings into sequences of 1s and 0s representing the seconds in which each lighthouse is ON or OFF; then cumulate the sum of seconds depending on how many lighthouses are on at the same time. def f(h): t=[0]*(len(h)+1) for i in range(3600):t[[c[i]for c in[(x.replace('S','10').replace('L','1110')+...


0

Julia 0.7, 41 bytes !a=(q=[];a.|>i->q=i>0?[i;q]:q[1:end-1];q) Try it online!


1

Julia 1.0, 42 bytes !x=(x-=1)<0||(~n=n*2^2x.+!x;[~0 ~1;~2 ~3]) Try it online! (one-indexed)


0

Charcoal, 32 bytes IE⊕Lθ№E³⁶⁰⁰Σ⭆θ§⁺⪫Eν×1∨⁼πS³0×0⁷λι Try it online! Link is to verbose version of code. Explanation: For each number of "on" lighthouses and each second of the hour, calculate the "on" pattern for each lighthouse and count how many of the seconds had that number of lighthouses "on". θ ...


1

JavaScript (ES6), 113 bytes Expects an array of strings. Returns an object. a=>(n=3600,g=L=>n--?g(o[a.map(s=>t+=~~(s=s.replace(/./g,c=>c>g?10:1110))[n%(s.length+6)],t=0),t]=-~o[t]):o)(o={}) Try it online!


2

J, 60 53 52 bytes _1+(0,#\)#/.~@,[:+/(3600$(6$0),~&;19<@#:@|14+3&u:)&> Try it online! -7 after reading Jonathan Allen's idea of doing arithmetic on the character codes, though I use a different method which converts S to 2 and L to 14, and then converts those to binary. idea For each pattern, convert it into a bitmask where 1 is on, 0 is ...


1

Python 2, 125 117 bytes lambda a:map(map(sum,zip(*[sum([2*(c<'S')*[1]+[1,0]for c in C],[0]*6)*500for C in a]))[6:3606].count,range(len(a)+1)) -8 thanks to Jonathan Allan.


5

Jelly,  24 22 21  20 bytes O%9ÄṬ;Øỵ¬ṁ⁽½c)SċⱮLŻ$ A monadic Link that accepts the list of lists of S and/or L characters and yields the ascending list of multiplicity counts. Try it online! Or see the test-suite. How? O%9ÄṬ;Øỵ¬ṁ⁽½c)SċⱮLŻ$ - Link: lighthouse patterns, P ) - for each pattern in P: say, 'SLSL' O - cast to ...


3

05AB1E, 25 bytes ε€C9%Å10.ý˜7Å0«60n∍}øOZÝ¢ Try it online! ε } # for each lighthouse in the implicit input: €C # convert each character from binary 9% # modulo 9: S -> 28 %9 = 1, L -> 21%9 = 3 Å1 # for each number in the resulting list get a list of ...


0

J, 18 bytes (*@[;@{}:@];,)/@|. Try it online! (...)/@|. Reverse and reduce by verb in parens... }:@];, Create the two options (regular vs deque, represented by 0) as a boxed pair: left elm is the deque case (ie, accumlator with tail removed }:@]) and right elm is the normal case (new elm appended as head ,). (*@[...{ Pick the correct case, which is the ...


0

Japt, 11 bytes kȶsÃÍg[TJ] Try it kȶsÃÍg[TJ] :Implicit input of array k :Remove elements that return true È :When passed through the following function as X ¶ : Is strictly equal to s : X converted to a string à :End remove Í :Sort g :Get elements at 0-...


0

Pip, 19 bytes $+{TBg}FB4*^21MC Ea Try it here! Or, here's a 20-byte equivalent in Pip Classic: Try it online! Explanation Inspired by Neil's comment about interleaving bit patterns, we can simply map the x and y coordinates to the right value (example x = 5, y = 9): 5 101 0 1 0 1 9 1001 1 0 0 1 10010011 147 We're not going to use Pip's WV ...


0

Brachylog, 7 bytes ℕˢ⟨⌋≡⌉⟩ Try it online! Explanation ˢ Select the elements of the input list which... ℕ ...are integers >= 0 ⟨ ⟩ Make a list containing... ⌋ ...the minimum element... ⌉ ...and the maximum element... ≡ ...and return it unchanged


0

Vyxal, 6 bytes 0+∩₍gG # main program 0+ # add 0 to each element of input if number, else append 0 ∩ # take the set intersection ₍ # apply the following two operations on top of stack and wrap gG # min and max # implicit output It may be possible to take this down a byte if there is a command that only affects strings but not ...


0

Python 3.8 + numpy, 85 84 bytes import numpy;z=lambda n:n and numpy.block([[m:=z(n-1),m+(k:=4**~-n)],[m+2*k,m+3*k]]) Not as clever as some of the other python ones, but shorter than the other python 3 ones. Also 0 returns a scalar instead of a list, not sure if that's allowed.


0

JavaScript (ES6), 72 bytes f=(n,a=[0])=>n?f(n-1,a.flatMap(x=>[x*=4,x+1])):a.map(y=>a.map(x=>x+2*y)) Try it online! Use the idea from Lynn's Haskell answer which saves many bytes on generating the list for iterate. Using base conversion as what my Python answer do will make it much longer (79 bytes).


1

Vyxal, 10 bytes ≈[1J|g₌ḟ›Ȧ # main program ≈ # all elements in input are equal [1J|g₌ḟ›Ȧ # main if statement 1J # if true, append 1 to input g₌ḟ›Ȧ # if false... g # get the minimum ₌ḟ› # push the index of the min and the increment of the min Ȧ # set that index to the increment # implicit ...


15

Jelly, 5 bytes 4ṗ>2Ġ Try it online! Neil saved a byte. Thanks! 4ṗ n-th Cartesian power of [1,2,3,4] >2 Replace 1,2,3,4 with 0,0,1,1 Ġ Group indices by values For n=2, 4ṗ>2 generates a list of 16 pairs: 1: [0, 0] 2: [0, 0] 3: [0, 1] 4: [0, 1] 5: [0, 0] 6: [0, 0] 7: [0, 1] 8: [0, 1] 9: [1, 0] 10: [1, 0] 11: [1, 1] 12: [1, ...


2

Haskell, 61 bytes f n|r<-iterate(>>= \x->[4*x,4*x+1])[0]!!n=[[x+2*y|x<-r]|y<-r] Try it online! Same idea as tsh's Python, but the list r (e.g. [0,1,4,5,16,17,20,21]) is created in a Haskell-y way.


Top 50 recent answers are included