title: Score a Cribbage Hand

text:
# Question
Title: Score a Cribbage Hand
This challenge is to score a Cribbage hand. If you don't play Cribbage, you've got some learning to do. We play with a standard poker deck, and a hand consists of four cards plus the "up card". There are two types of hand: normal, and a 'crib hand'.

Cards come in the format `vs` where `v` is one of: `A23456789TJQK` (T for ten) and `s` is one of `SCDH`. A hand will be given in the form (for example)

```
AS 2D 3H JS | 4S

```

where `4S` is the up card. A crib hand will have the format

```
JD 3C 4H 5H | 5S !

```

Face cards have a value of 10, and the ace has a value of 1. Scoring is performed as follows.

* Fifteens: for each subset of five cards whose sum is 15, add two points.
* Pairs: for each pair of cards with the same rank (not value), add two points.
* Runs: for each maximal run of consecutive cards of length longer than 2, add the length of the run in points.
* Flush: if all five cards are the same suit, add five points. Otherwise, if all but the up card are the same suit, add four points. If this is a crib hand, the four-point variant is not counted.
* Nobs: if there is a jack in hand with the same suit of the up card, add one point.

**Notes:**

* Triples and fours of a kind are not special -- there are three pairs in a triple, so a triple is worth 6 points.
* Runs can overlap. For example, `AS AH 2D 3C | 2C` (a double double run) has four runs of length 3 and two pair, so is worth 3+3+3+3+2+2 = 16 points.
* Only maximal runs are counted, so `KS QD JD TC | 9S` is worth 5 points, since it is a run of 5. The sub-runs are not counted.

**House Rule:**

It's impossible to score 19 points in a hand. Instead of zero, report a score of 19.

**Examples:**

```
5S 5H 5D JS | KS
21

AS 2D 3H JS | 4S !
9

JD 3C 4H 5H | 5S
12

9S 8S 7S 6S | 5H !
9

9S 8S 7S 6S | 5H
13

8D 7D 6D 5D | 4D !
14

8D 7D 6D 5D | 4D
14

AD KD 3C QD | 6D
19

```

This is code golf. Shortest solution wins.

# Answer
> 2 votes
### GolfScript, 187 178 174 characters

```
:c"J"c{"SCDH"?)},1/:s-1=+/,([s)-!5*s);)-!4*c"!"?)!*]$-1=+0.14,{c{"A23456789TJQK"?)}%{},:v\{=}+,,.{@*\)}{;.2>**+1 0}if}/;;5-v{{=+}+v\/}/[0]v{.9>{;10}*{1$+}+%}/{15=},,2*+.!19*+

```

Since I never played cribbage I don't know any fancy scoring tricks. Therefore I thought the only way to compete (at least a little bit) is using a golf language. The code is pretty plain GolfScript, the test cases can be found here.

The code in a more readable fashion (*reformatted and ungolfed a little*):

```
# Save cards to <c>
:c;

# Is it a non-crib hand? <r>
c"!"?)!:r;

# Values go to <v>
c{"A23456789TJQK"?)}%{},:v;

# Suits go to <s>
c{"SCDH"?)},1/:s;

# Print score for Fifteens
[0]v{.9>{;10}*{1$+}+%}/{15=},,2* .p

# Print score for Pairs
-5v{{=+}+v\/}/ .p

# Print score for Runs
0..14,{v\{=}+,,.{*\)\}{;\.2>**+0 1}if}/;; .p

# Print score for Flush
[s)-!5*s);)-!4*r*]$-1= .p

# And finally print the score for Nobs
c"J"s-1=+/,( .p

# Sum up the sub-scores and if score is zero set to 19
++++
.!19*+

```

*Edit:* Changed logic for fifteens and flushes.

# Answer
> 7 votes
## C, 364 388 chars

It's big and ugly (though not as big as it once was):

```
char*L="CA23456789TJQKDHS",b[20],p[15],r[5],s[5],v,i=4,t,m,q;
g(j){++p[r[i]=strchr(L,b[j])-L];s[i]=strchr(L,b[j+1])-L;}
f(j,u){u==15?v+=2:++j<5&&f(j,u,f(j,u+(r[j]>9?10:r[j])));}
main(){gets(b);for(g(14);i--;r[i]^11|s[i]^s[4]||++v)g(i*3);
for(f(i,0);++i<15;v+=q?q*q-q:t>2?t*m:0,t=q?t+1:0,m=q?m*q:1)q=p[i];
while(++t<5&&s[t]==*s);v+=t>4-!b[16]?t:0;printf("%d\n",v?v:19);}

```

(Line breaks were added to make it easier to read; those aren't included in the above tally.)

The problem description didn't specify if the code needed to check for invalid input, so naturally I assumed that the program was free to misbehave at will if the input, say, contained extra whitespace.

Here's the ungolfed version:

```
#include <stdio.h>
#include <string.h>

/* A-K correspond to values 1-13. Suit values are arbitrary.
 */
static char const *symbols="CA23456789TJQKDHS";

/* Used as both an input buffer and to bucket cards by rank.
 */
static char buf[20];

/* The cards.
 */
static int rank[5], suit[5];

/* The cards broken down by rank.
 */
static int buckets[15];

static int score;
static int touching, matching, i;

/* Read card number i from buf at position j.
 */
static void getcard(int j)
{
    rank[i] = strchr(symbols, buf[j]) - symbols;
    suit[i] = strchr(symbols, buf[j+1]) - symbols;
    ++buckets[rank[i];
}

/* Recursively find all combinations that add up to fifteen.
 */
static void fifteens(int j, int total)
{
    for ( ; j < 5 ; ++j) {
        int subtotal = total + (rank[j] > 9 ? 10 : rank[j]);
        if (subtotal == 15)
            score += 2;
        else if (subtotal < 15)
            fifteens(j + 1, subtotal);
    }
}

int main(void)
{
    fgets(buf, sizeof buf, stdin);
    score = 0;

    /* Read cards from buf */
    for (i = 0 ; i < 4 ; ++i)
        getcard(i * 3);
    getcard(14);

    /* Score fifteens */
    fifteens(0, 0);

    /* Score any runs and/or pairs */
    touching = 0;
    matching = 1;
    for (i = 1 ; i < 15 ; ++i) {
        if (buckets[i]) {
            score += buckets[i] * (buckets[i] - 1);
            ++touching;
            matching *= buckets[i];
        } else {
            if (touching > 2)
                score += touching * matching;
            touching = 0;
            matching = 1;
        }
    }

    /* Check for flush */
    for (i = 1 ; i < 5 && suit[i] == suit[0] ; ++i) ;
    if (i >= (buf[17] == '!' ? 5 : 4))
        score += i;

    /* Check for hisnob */
    for (i = 0 ; i < 4 ; ++i)
        if (rank[i] == 11 && suit[i] == suit[4])
            ++score;

    printf("%d\n", score ? score : 19);
    return 0;
}

```

# Answer
> 5 votes
## Ruby 1.9, 359 356

It's far too long - almost as much as the C solution.

```
R='A23456789TJQK'
y=gets
f=y.scan /\w+/
o=f.map(&:chr).sort_by{|k|R.index k}
s=0
2.upto(5){|i|o.combination(i){|j|t=0
j.map{|k|t+=k==?A?1:k<?:?k.hex: 10}
(t==15||i<3&&j.uniq!)&&s+=2}}
m=n=l=1
(o+[z=?_]).map{|k|k[z]?n+=1:R[z+k]?(m*=n
l+=n=1):(l>2&&s+=l*m*n
l=n=m=1)
z=k}
x=f.take_while{|k|k[y[1]]}.size
x>(y[?!]?4:3)&&s+=x
y[?J+f[4][1]+' ']&&s+=1
p s>0?s:19

```

# Answer
> 5 votes
# Something to begin with.. Ruby, ~~422 365 355~~ 352

```
c=gets
a,b=c.scan(/(\w)(\w)/).transpose
f=->x{x.uniq.size<2}
s=f[b]?5:!c[/!/]&f[b[0,4]]?4:0
c[/J(.).*\1 ?!?$/]&&s+=1
s+=[5,4,3].map{|i|a.permutation(i).map{|x|'A23456789TJQK'[x*'']?i:0}.inject :+}.find{|x|x>0}||0
a.map{|x|s+=a.count(x)-1}
2.upto(5){|i|s+=2*a.map{|x|x.tr(?A,?1).sub(/\D/,'10').to_i}.combination(i).count{|x|x.inject(:+)==15}}
p s<1?19:s

```

Slightly ungolfed:

```
def t(c)
  s=0

  if c.scan(/[SDHC]/).uniq.size<2 # Flush
    s+=5
  elsif c[0..9].scan(/[SDHC]/).uniq.size<2 && c[-1]!=?! # Flush
    s+=4
  end
  s+=1 if c =~ /J(.).*(\1$|\1\s.$)/ # Nobs

  c=c.scan(/[^ \|]+/).map{|x|x[0]}[0..4]
  d = (3..5).map{|i|c.permutation(i).map{|x| 'A23456789TJQK'.include?(x*'') ? i : 0}.inject(:+)}.reverse.find{|x|x>0} || 0# Runs
  s+=d
  c.map{|x|s+=c.count(x)-1} # Pairs
  c.map!{|x|x.tr('A','1').gsub(/[JQK]/,'10').to_i}
  (2..5).map{|i|s+=2*c.combination(i).count{|x|15==x.inject(:+)}} # 15s
  s<1 ? 19 : s
end

```

Unit tests for golfed version:

```
require "test/unit"

def t(c)
c=gets
a,b=c.scan(/(\w)(\w)/).transpose
f=->x{x.uniq.size<2}
s=f[b]?5:!c[/!/]&f[b[0,4]]?4:0
c[/J(.).*\1 ?!?$/]&&s+=1
s+=[5,4,3].map{|i|a.permutation(i).map{|x|'A23456789TJQK'[x*'']?i:0}.inject :+}.find{|x|x>0}||0
a.map{|x|s+=a.count(x)-1}
2.upto(5){|i|s+=2*a.map{|x|x.tr(?A,?1).sub(/\D/,'10').to_i}.combination(i).count{|x|x.inject(:+)==15}}
p s<1?19:s
end

class Test1 < Test::Unit::TestCase
  def test_simple
    assert_equal 21, t("5S 5H 5D JS | KS")
    assert_equal 21, t("JS 5H 5D 5S | KS")
    assert_equal 12, t("JD 3C 4H 5H | 5S")
    assert_equal 13, t("9S 8S 7S 6S | 5H")
    assert_equal 14, t("8D 7D 6D 5D | 4D")
    assert_equal 19, t("AD KD 3C QD | 6D")
    assert_equal 9, t("AS 2D 3H JS | 4S !")
    assert_equal 9, t("JS 2D 3H AS | 4S !")
    assert_equal 14, t("8D 7D 6D 5D | 4D !")
    assert_equal 9, t("9S 8S 7S 6S | 5H !")
  end
end

```

Results:

```
% ruby ./crib.rb
   Run options:

# Running tests:

21
21
12
13
14
19
9
9
14
9
.

Finished tests in 0.014529s, 68.8281 tests/s, 688.2813 assertions/s.

1 tests, 10 assertions, 0 failures, 0 errors, 0 skips

```

# Answer
> 4 votes
# Python, 629 characters

I'm only posting mine because no one else has. It's pretty long :(

```
g=range
i=raw_input().split()
r,u=zip(*[tuple(x)for x in i if x not in'!|'])
v=map(int,[((x,10)[x in'TJQK'],1)[x=='A']for x in r])
z=list(set(map(int,[(x,dict(zip('ATJQK',[1,10,11,12,13])).get(x))[x in'ATJQK']for x in r])))
z.sort()
z=[-1]*(5-len(z))+z
s=p=l=0
for a in g(5):
 for b in g(a+1,5):
    s+=2*(v[a]+v[b]==15)
    p+=2*(r[a]==r[b])
    if z[a:b+1]==g(z[a],z[b]+1)and b-a>1:l=max(l,b+1-a)
    for c in g(b+1,5):s+=2*(v[a]+v[b]+v[c]==15)
for d in g(5):s+=2*(sum(v)-v[d]==15)
n=len(set(u))
s+=4*(n==2 and u[-1] not in u[:4] and i[-1]!='!')+5*(n<2)+('J'+u[4]in i[:4])+2*(sum(v)==15)+p+((l*3,l*p)[p<5]or l)
print(s,19)[s<1]

```

# Answer
> 2 votes
# Python 2, ~~606~~ 584 bytes

Saved 22 bytes due to Jo King's golfing.

```
from itertools import*
s,S,C,E=sum,sorted,combinations,enumerate
def f(a):a=a.split();a.pop(4);e=a.pop(5)if a[-1]<"$"else 0;b=S("A23456789TJQK".index(i)for i,j in a);d=S(set(b));h=[j for i,j in a];z=len([s(k)for r in range(6)for k in C([[10,k+1][k<10]for k in b],r)if s(k)==15])*2+s(2for i,j in C(b,2)if i==j)+[4*(e<1),5][len(set(h))<2]*(len(set(h[:4]))<2)+(a[4][1]in[j for i,j in a[:4]if i=="J"])+s(reduce(lambda x,y:x*y,[b.count(k)for k in m])*len(m)for m in[d[s(x[:i]):s(x[:i])+j]for x in[[len(list(e))for i,e in groupby(j-i for i,j in E(d))]]for i,j in E(x)if j>2]);return z or 19

```

Try it online!

Slightly shorter than grc's answer, and takes a different route to get there.

## Explanation:

```
    # import everything from "itertools" library. We only need "combinations" and "groupby".
from itertools import*
# alias functions to shorter names
s,S,C,E=sum,sorted,combinations,enumerate

# function f which takes the hand+up card+crib string as its argument
def f(a):
    # convert space-separated string into list of items.
    a=a.split()

    # remove the 4th index, which is always "|".
    a.pop(4)

    # change golfed by Jo King
    # if the final item in the list is a "!" (if it is <"$"), remove it from the list and assign it to variable "e".
    # otherwise, assign 0 to variable "e".
    # a non-empty string will evaluate to True and 0 will evaluate to False in IF checks later.
    e=a.pop(5)if a[-1]<"$"else 0

    # for each card in the list, split the identifiers into the value(i) and the suit(j).
    # return the value's index in the string "A23456789TJQK".
    # so, ["5S", "5H", "5D", "JS", "KS"] will return [4, 4, 4, 10, 12].
    # using the aliased built-in function sorted(), sort the list numerically ascending.
    b=S("A23456789TJQK".index(i)for i,j in a)

    # get the unique items in b, then sort the result numerically ascending.
    d=S(set(b))

    # for each card in the list, split the identifiers into the value(i) and the suit(j).
    # return the suits.
    h=[j for i,j in a]

        # fifteens
        # changes golfed by Jo King
        # generate pairs of (10, value + 1) for all cards (since they are zero-indexed)
        # since True and False evaluate to 1 and 0 in python, return 10 if k>=10
        # and reduce all values >10 to 10
        # get all unique combinations of cards for 5 cards, 4 cards, 3 cards, 2 cards, and 1 card
        # add the values of all unique combinations, and return any that equal 15
        # multiply the number of returned 15s by 2 for score
    z=len([s(k)for r in range(6)for k in C([[10,k+1][k<10]for k in b],r)if s(k)==15])*2
        +
        # pairs
        # using itertools.combinations, get all unique combinations of cards into groups of 2.
        # then, add 2 for each pair where both cards have an identical value.
        s(2for i,j in C(b,2)if i==j)
        +
        # flush
        # changes golfed by Jo King
        # using list indexing
        # [4 * (0 if crib else 1), 5], get item at index [0 if more than one suit in hand+up card else 1]
        #    -> 4 if not crib and not all suits same
        #    -> 5 if all cards same
        #    -> 0 otherwise
        # * (0 if more than one suit in hand else 1)
        #    -> 4 * 0 if not crib and not all suits same
        #    -> 4 * 1 if not crib and all suits same
        #    -> 5 * 1 if all cards same
        #    -> 0 otherwise
        [4*(e<1),5][len(set(h))<2]*(len(set(h[:4]))<2)
        +
        # nobs
        # check if the suit of the 5th card (4, zero-indexed) matches the suit of any of the other 4 cards, and if it does is that card a Jack
        (a[4][1]in[j for i,j in a[:4]if i=="J"])
        +
        # runs
        s(reduce(lambda x,y:x*y,[b.count(k)for k in m])*len(m)for m in[d[s(x[:i]):s(x[:i])+j]for x in[[len(list(e))for i,e in groupby(j-i for i,j in E(d))]]for i,j in E(x)if j>2])

    # since only 0 evaluates to false, iff z==0 return 19, else return z.
    print z or 19

```

## Explanation for runs logic specifically:

```
# for each index and value in the list, add the value minus the index
# since the list is sorted and reduced to unique values, this means adjacent values will all be the same value after offset
# ex: "JD 3C 4H 5H | 5S" -> [2, 3, 4, 10] - > [2, 2, 2, 7]
z = []
for i,j in enumerate(d):
    z.append(j-i)

# group the values by unique value
# then add the length of the groups to the list
# ex: [2, 2, 2, 7] -> [2:[2,2,2], 7:[7]]
#     [2:[2,2,2], 7:[7]] -> [[3], [1]]
w = []
for i,e in groupby(z):
    w.append([len(list(e))])

# list is double-nested so that the combined list comprehension leaves "x" available in both places it is needed
z = []
for x in w:
    for i,j in enumerate(x):
        if j>2:
            # if the group length is larger than 2
            # slice the list of unique card values to obtain only run values
            # since the run can be anywhere in the list, sum the preceding lengths to find the start and end index
            a = d[ sum(x[:i]) : sum(x[:i])+j ]
            z.append(a)

w = []
for m in z:
    # get the number of times the value is in the entire hand
    # ex: "JD 3C 4H 5H | 5S" -> [2,3,4,4,10] and (2,3,4) -> [1, 1, 2]
    a = [b.count(k)for k in m]
    # multiply all values together
    # [1, 1, 2] = 1*1*2 = 2
    a = reduce(lambda x,y:x*y, a)
    # length of the run * number of duplicate values
    a *= len(m)
    w.append(a)

# sum the results of the runs
return sum(w)

```

# Answer
> 1 votes
# Stax, 106 bytes

```
Çí╬Δ╓↔╥.L§º♦½┌§└─»◄G≤n▒HJ♀p$¼♥,Q¢▲»Δ÷♠º≈r↑Vo\b■┌4Üé∟]e:┬A½f║J4σ↔└ΓW6O?╧φ¡╫╠├√├ùß5₧k%5ê╜ò/Φ/7w╠█91I◘┬n≥ìk♂╪

```

Run and debug online!

Bonus for CP437: See those suits symbol in the packed Stax? Too bad that the clubs do not appear ...

The ASCII equivalent is

```
jc%7<~6(4|@Y{h"A23456789TJQK"I^mXS{{A|mm|+15=_%2=_:u*+f%HxS{{o:-u1]=f{%mc3+|Msn#*+y{H"SHCD"ImY:uc5*s!yNd:u;**HH++yN|Ixs@11#+c19?

```

## Explanation

```
jc%7<~6(4|@Y...X...Y...c19?
j                              Split on space
 c%7<~                         Is it a crib hand? Put it on input stack for later use
      6(                       Remove "!" if it exists
        4|@                    Remove "|"
           Y                   Store list of cards in y
            ...X               Store ranks in x
                ...            Perform scoring for ranks
                   Y           Store suits in y
                    ...        Perform scoring for suits
                       c19?    If the score is 0, change it to 19

{h"..."I^mX
{        m     Map each two character string to
 h             The first character
  "..."I^      1-based index of the character in the string

S{{A|mm|+15=_%2=_:u*+f%H
S                          Powerset
 {                   f%H   Twice the number of elements that satisfy the predicate
  {A|mm                        Value of card. Take the minimum of the rank and 10
       |+15=                   Sum of values equal 15 (*)
            _%2=               Length is 2 (**)
                _:u            All elements are the same (***)
                   *+          ( (***) and (**) ) or (*)

xS{{o:-u1]=f{%mc3+|Msn#*+
xS                                Powerset of ranks
  {        f                      Filter with predicate
   {o                                 Sort
     :-u                              Unique differences between elements
        1]=                           Is [1]
            {%mc                  Length of all runs
                3+|M              Maximum of all the lengths and 3
                    sn#           Number of runs with maximal length
                       *          Multiplied by its length
                        +         Add to score

y{H"SHCD"ImY
y{        mY    For each two character string
  H"SHCD"I      0-based index of the second character in the string "SHCD"

:uc5*s!yNd:u;**HH++
:uc5*                 5 points if all cards have same suit
     s!               Not all cards have same suit (#)
       yNd:u          First four cards have same suit (##)
            ;         Not a crib hand (###)
             **HH++   4 points if (#) and (##) and (###), add to score

yN|Ixs@11#+
yN|I           Index of cards with the same suit of last card (not including itself)
    xs@        The rank at these indices
       11#     Number of Jacks with the same suit of last card
          +    Add to score

```

---
Tags: code-golf, game
---


title: Jolly Jumper Sequence

text:
# Question
Title: Jolly Jumper Sequence
A sequence of n \> 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1.

So the sequence \[4,1,2,4\] has absolute differences \[3,1,2\] which is equivalent to the set \[1,2,3\] (1 to n-1 where n is the length of original sequence) so it is therefore a jolly jumper.

Sequences have length n\>0.

Assume n=1 is a jolly jumper.

*Easy mode:* Don't worry about stdin/stdout. Just a function that accepts arguments however and returns *something* that indicates jolly or not

*Hard mode:* Input on stdin (space separated), and output is "Jolly" / "Not jolly". Capitalization matters.

This is code golf.

EDIT: Sequences can contain negative integers and input on stdin is space separated.

```
$ jolly 2 -1 0 2
Jolly

$ jolly 19 22 24 25
Jolly

$ jolly 19 22 24 21
Not jolly

```

# Answer
## Haskell

## Easy 4 characters

Returns a list of jolly integers if and only if a list of jolly integers is given as input. This is legal based on "Just a function that accepts arguments however and returns something that indicates jolly or not".

```
j=id

```

Alternative easy solution with 61 characters:

Takes in a list and returns the empty list if the sequence is jolly.

```
import List
j n=zipWith(\x->abs.(x-))n(tail n)\\[1..length n]

```
> 3 votes

# Answer
## Golfscript, easy mode, 21 18 chars

```
{.@-abs\}*;0]$.,,=

```

Accepts arguments as an array of ints on the stack, with nothing else on the stack; leaves 1 on the stack if it's jolly and 0 otherwise. To take input on stdin as a space-separated list of ints, prepend

```
~]

```

and to output "Jolly" / "Not jolly" (assuming that we're turning this into a program) postpend

```
"Not jJ"5/="olly"

```
> 2 votes

# Answer
## Scala, easy mode, 123 characters

```
def j(s:String)={var a=s.sliding(2,1).map(x=>math.abs(x(0)-x(1))).toList
for(c<-1 to a.size)
if(!a.contains(c))false
true}

```

To run or test on ideone.com:

```
object Main
{
   def main(args:Array[String])
   {
      def j(s:String):Boolean=
      {
         var a=s.sliding(2,1).map(x=>math.abs(x(0)-x(1))).toList
         for(c<-1 to a.size)
            if(!a.contains(c)) false
         true
      }
      println(j("4124"))
   }
}

```
> 2 votes

# Answer
### Ruby, 92 93 characters

The hard version with input on STDIN.

```
f=gets.split.each_cons(2).map{|a|eval(a*?-).abs}.sort
$><<(f==[*1..f.size]??J:"Not j")+"olly"

```

If you start it with `-pa` (counts as 4) you can save 5 chars:

```
f=$F.each_cons(2).map{|a|eval(a*?-).abs}.sort
$_=(f==[*1..f.size]??J:"Not j")+"olly"

```
> 2 votes

# Answer
# Java (Hard)

Assumes that input is given through stdin. (not through command line arguments as per example)

**Golfed - 325**

```
class JollyJumper {
public static void main(String[] args) {
String[] in = new Scanner(System.in).nextLine().split(" ");
int[] j=new int[in.length-1],k=j.clone();
for(int i=0;i<in.length-1;i++){j[i]=Math.abs(Integer.parseInt(in[i])-Integer.parseInt(in[i+1]));k[i]=i+1;}
Arrays.sort(j);System.out.println(Arrays.equals(j, k)?"Jolly":"Not jolly");
}
}

```

**Un-Golfed**

```
public class JollyJumper {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] jolly;
    String[] in;

    in = sc.nextLine().split(" ");
    jolly = new int[in.length-1];

    for (int i = 0; i < in.length-1; i++)
        jolly[i] = Math.abs(Integer.parseInt(in[i]) - Integer.parseInt(in[i+1]));

    Arrays.sort(jolly);

    for (int i = 1; i <= in.length-1; i++) {
        if (jolly[i-1] != i) {
            System.out.println("Not jolly");
            return;
        }
    }
    System.out.println("Jolly");
}
}

```
> 2 votes

# Answer
# J (easy), 18

```
(i.@#-:<:/:])|2-/\

```

```
   (i.@#-:<:/:])|2-/\2 _1 0 2
1
   (i.@#-:<:/:])|2-/\19 22 24 25
1
   (i.@#-:<:/:])|2-/\19 22 24 21
0

```

# J (hard), 68

```
2!:55]1!:2&2'olly',~>('Not j';'J'){~(i.@#-:<:/:])|2-/\".@>2}.ARGV_j_

```

```
$ jconsole jumper.ijs 2 -1 0 2
Jolly
$ jconsole jumper.ijs 19 22 24 25
Jolly
$ jconsole jumper.ijs 2 19 22 24 21
Not jolly

```
> 2 votes

# Answer
# Brachylog, 11 bytes (easy)

```
s₂ᶠ-ᵐȧᵐo~⟦₁

```

Try it online!

`s₂ᶠ-ᵐ` \- Consecutive differences

`ȧᵐ` \- Absolute values

`o` \- Sort

`~⟦₁` \- Is the result the range 1 to something?
> 2 votes

# Answer
# D

## easy (~~103~~ 83 chars)

returns sum of 1..i.length on Jolly some other number if not (a bit of rules laywering here)

```
import std.math;auto jolly(I)(I i){int t,l;foreach(r;i){t+=abs(l-r);l=r;}return t;}

```

## hard (142 chars)

input is whitespace delimited and ends on EOF

```
import std.stdio;import std.math; void main(){int i,j,l,t;while(readf("%d ",&i)>0){t+=abs(l-i);l=i;j++;}write(t==j*++j/2?"J":"Not j","olly");}

```
> 1 votes

# Answer
## J, 30 26 easy mode, 81 76 hard mode

*edit:* handle lists shorter than 3, fix stdin reading

First line takes care of easy mode, second adds hard mode.

```
j=:[:*/[:(>:@i.@#=/:~)[:|2-/\]
exit('olly',~[:>('Not j';'J'){~[:j 0".}:)&.stdin''

```

J reads generally right-to-left:

`2-/\` : for every two successive numbers in the list, take the difference

`|` : absolute value

`/:~` : sort in ascending order

`>:@i.@#` : 1 to *n*, for a list of *n* numbers

`=` : compare the sorted differences with the sequence (using a J "fork")

`*/` : multiply all the element-wise booleans; if all the comparisons were 1, their product is 1, so it's jolly
> 1 votes

# Answer
### Scala easy:138  153, 170 (was errornous, improved later)

```
def j(i:String)={
def a(s:Seq[Int])=(s zip s.tail).map(x=>(x._2-x._1))
a(a(i.split(" ").map(_.toInt)).map(math.abs).sorted).toSet.size==1}

```

ungolfed:

```
def jolly (input: String) = {
      val list = input.split (" ").map (_.toInt)

      def stepsize (s: Seq[Int]) =
        (s zip s.tail).map (x=> (x._2 - x._1))

      val first = stepsize (input.split (" ").map (_.toInt))
      val pos = first.map (math.abs)
      val unique = stepsize (pos.sorted).toSet
      (unique.size) == 1
}

```

The idea is, that we build the second derivation:

```
Original: 4 1 2 4
Stepsize:  -3 1 2 (first)
     abs:   3 1 2
  sorted:   1 2 3
Stepsize:     1 1
  to Set:       1
    size:       1

```

### Scala hard 172  182, 205 (was errornous/improved):

```
def j{
def a(s:Seq[Int])=(s zip s.tail).map(x=>(x._2-x._1))
println((if(a(a(readLine.split(" ").map(_.toInt)).map(math.abs).sorted).toSet.size==1)"J"else"Not j")+"olly")}
j

```

more or less the same as above.
> 1 votes

# Answer
## Ruby, 97 102 106 (hard)

Might as well, since everyone else is:

```
h,*t=gets.split
d=t.map{|i|h,i=i,h;eval(i+?-+h).abs}.sort
$><<(d==[*1..d.size]??J:"Not j")+"olly"

```

Input taken on stdin.
> 1 votes

# Answer
# Groovy

## Easy: 78

```
j={m=[];it[1..-1].inject(it[0]){p,n->m<<p-n;n};m*.abs().sort()==1..<it.size()}

assert [[2, -1, 0, 2,], [19, 22, 24, 25], [19, 22, 24, 21]].collect { j(it) } == [true, true, false]

```

## Hard: 151

```
j={m=[];it[1..-1].inject(it[0]){p,n->m<<p-n;n};m*.abs().sort()==1..<it.size()};System.in.eachLine{println "${j(it.split()*.toLong())?'J':'Not j'}olly"}

```
> 1 votes

# Answer
## PowerShell, hard, 117 ~~126~~

```
('Not j','J')["$(($a=-split$input)|%{if($x-ne$0){[math]::abs($x-$_)}$x=$_}|sort)"-eq"$(1..($a.Count-1)|sort)"]+'olly'

```

History:

* 2011-11-18 17:54 (**123**, −3) – Changed `$null` to a non-existent variable
* 2011-11-18 18:02 (**117**, −6) – inlined all variable declarations
> 1 votes

# Answer
# Scala

A quick stab - there are probably improvements possible.

## Easy: 77

```
def j(? :Int*)=(?tail,?).zipped.map(_-_).map(math.abs).sorted==(1 to?.size-1)

```

## Hard: 124

```
val? =args.map(_.toInt)toSeq;print(if((?tail,?).zipped.map(_-_).map(math.abs).sorted==(1 to?.size-1))"Jolly"else"Not jolly")

```
> 1 votes

# Answer
# Q, 64 (hard), 30 (easy)

hard

```
{$[(1_(!)(#)x)~asc abs 1_(-':)x;(-1"Jolly";);(-1"Not jolly";)];}

```

easy

```
{(1_(!)(#)x)~asc abs 1_(-':)x}

```
> 1 votes

# Answer
## J (easy), 19 characters

```
*/(=i.@#)<:/:~|2-/\

```

Usage:

```
    */(=i.@#)<:/:~|2-/\4 2 1 4
1

```

Vary similar to DCharness's answer, and I would have just added it as a comment but for the fact that he hasn't visited since the 23rd of February.

`2-/\` takes the difference between successive pairs of numbers,

`|` gets the absolute value of each number,

`/:~` sorts into ascending order,

`<:` decrements each number by 1,

`(=i.@#)` a J hook which generates the sequence of numbers from 0 to the length of the differences list - 1 (`i.@#`) and compares it with that list `=`.

`*/` multiples the list of `1`s and `0`s generated by the previous verb.
> 1 votes

# Answer
# PHP, easy, 129

For a given array `$s` of integers:

```
for($i=1;$i<count($s);$i++)$a[abs($s[$i]-$s[$i-1])]=1;
for($i=1;$i<count($s);$i++)if(!isset($a[$i]))die('Not Jolly');echo 'Jolly';

```

The ungolfed version:

```
for( $i=1; $i<count( $s ); $i++ )
    $a[ abs( $s[$i] - $s[$i-1] ) ] = 1;

for( $i=1; $i < count($s); $i++ )
    if( !isset( $a[$i] ) )
        die( 'Not Jolly' );

echo "Jolly";

```
> 1 votes

# Answer
# Jelly, 7 6 bytes (easy)

```
IAṢ⁼J$

```

Try it online!

```
IAṢ⁼J$    jolly function on N:
IAṢ       the increment list: get all the Increments, take their Absolute values, and Ṣort them
   ⁼      compare that to...
    J$    range from 1 to len(N) -- this has an extra number, but that's fine because...
          ...the increment list is one shorter, and ⁼ will only compare that many values

```

Takes input as comma-separated numbers in the first argument. Returns 1 if the sequence is jolly, and 0 if it isn't!

**7-byte solution:**

```
LRṖḟIA$

```

Try it online!

Takes input as comma-separated numbers in the first argument. Returns nothing if the list is a jolly jumper sequence, and *something* if it isn't.

Adding this line makes it work with the hard spec:

# Jelly, 27 22 bytes (hard, feedback welcome!)

```
ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»

```

Try it online!

```
ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»
ɠḲV                     read a line, split on spaces and eValuate the numbers
   IAṢ⁼J$               jolly function: see above!
         ị              ịndex the result into (remember Jelly is one-indexed, so 0 wraps around to the back):
          “¢⁼D“          "Jolly" compressed if true,
              ¡KṀȥƘạ»   or, "Not jolly" compressed if false!

```

**27-byte (hard) solution:**

```
LRṖḟIA$
ɠḲVÇ“¡KṀȥƘạ»“¢⁼D»L?

```

Try it online!

Takes space-separated numbers on `stdin`, and outputs "Jolly" or "Not jolly".

Explanation:

```
LRṖḟIA$               jolly function:
LRP                   make a range (R) from 1 to the input length (L), popping off (P) the last number to make it 1 to N-1.
   ḟ                  reverse filter: remove all the elements from that range that are members of...
    IA$               the increment list: get all the increments, take their absolute values (expressed as one monad via '$').
ɠḲVÇ“¡KṀȥƘạ»“¢⁼D»L?    i/o main function:
ɠḲV                   read a line from stdin, split it on spaces and have Python parse each number (handling negative signs)
   Ç             ?    run the above, and use the result on the following conditional:
                L?    if the length of the result is truthy (non-empty):
    “¡KṀȥƘạ»          then, return Jelly compressed string "Not jolly",
            “¢⁼D»     else, return Jelly compressed string "Jolly".

```

Any feedback much appreciated!
> 1 votes

# Answer
# Haskell, ~~59~~ 57 bytes

```
f n=all(`elem`map abs(zipWith(-)n$tail n))[1..length n-1]

```

Easy mode, returns jollyness as a boolean. Thanks to @Laikoni for two bytes.

Try it online!
> 1 votes

# Answer
# Japt, ~~32~~ 30 bytes Hard

*-2 Bytes from @Shaggy*

```
`not jo¥y`s4*Näa n äa e¥1
hUÎu

```

Try it online!
> 1 votes

# Answer
## Python 3, 117 (hard)

```
l=[*map(int,input().split())]
print(["Not j","J"][{abs(a-b)for a,b in zip(l[1:],l[:-1])}=={*range(1,len(l))}]+"olly")

```

Try it online!
> 1 votes

# Answer
## JavaScript: 105 (easy mode)

Golfed:

```
function a(l){for(r=i=1;i<(m=l.length);i++){for(j=t=0;j+1<m;)t+=(d=l[j]-l[++j])*d==i*i;t||(r=0)}return r}

```

Un-golfed:

```
function isJolly(list){
    //Iterate over i to list.length-1
    for(r=i=1;i<(length=list.length);i++){
        //Check the differences between all consecutive elements squared minus i squared.  Set t to true if one was found.
        for(j=t=0;j+1<length;)t+=(diff=list[j]-list[++j])*diff==i*i;

        //if t is not true, return value is 0
        t||(r=0)
    }
    return r
}

```
> 0 votes

# Answer
## Perl, 89 (hard)

86 characters of code + 3 for running with the `-p` option

```
@a=0;$a[abs($1-$2)]=1while s/(\S+) (\S+)/$2/;$_='Jolly';(grep{!defined}@a)&&s/J/Not j/

```
> 0 votes

# Answer
## Javascript (hard): 138

```
a=prompt().split(" ")
i=0;b=[];c=[]
while(b[i]=Math.abs(a[i]-a[++i]),c[i-1]=i,i<a.length-1);b.sort()
alert(b+""==c+""?"Jolly":"Not jolly")

```
> 0 votes

# Answer
## Python, 255 characters

```
r=[19,22,24,25]
i=0
k=[ i+1 for i in range(len(r)-1)]
def jolly(a):
    p=[]
    i=0
    while i<len(a)-1:
       p.append(abs(a[i+1]-a[i]))
       i+=1
    p.sort()
    if p==k:
       return 'jolly'
    else:
       return 'Not jolly'

print(jolly(r))

```
> 0 votes

# Answer
## R, Easy, 110

```
f=function(s){p=NULL;l=length;for (i in 2:l(s))p=c(p,abs(s[i]-s[i-1]));ifelse(all(sort(p)==(1:(l(s)-1))),1,0)}

```

Usage:

```
f(c(2, -1, 0, 2))
[1] 1
f(c(19, 22, 24, 25))
[1] 1
f(c(19, 22, 24, 21))
[1] 0

```
> 0 votes

# Answer
## Python, 72 (easy), 114 (hard)

**Easy:**

```
def f(a):return len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2

```

**Hard**:

```
a=map(int,raw_input().split())
print('Not j','J')[len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2]+'olly'

```
> 0 votes

# Answer
# C, 119(hard), 97(easy)

```
b,c,a[];main(k){while(~scanf("%d",a+c))k=c++;for(c=k;b<c*c;)k-abs(a[b%c]-a[b++%c+1])?:k--;puts(k?"Not jolly":"Jolly");}

```

The easy solution reads the input from the arguments and returns a 0 as exit code if the input is a jolly jumper sequence:

```
i,k;main(int c,char**a){for(k=c-=2,a++;i<c*c;)k-abs(atoi(a[i%c])-atoi(a[i++%c+1]))?:k--;exit(k);}

```
> 0 votes

# Answer
## APL (~~50~~ ~~49~~ 47, hard)

```
'Not jolly' 'Jolly'[1+K[⍋K←¯1↓|Z-1⌽Z]≡¯1↓⍳⍴Z←⎕]

```

Easy (24):

```
{K[⍋K←¯1↓|⍵-1⌽⍵]≡¯1↓⍳⍴⍵}

```

The function takes an array and returns 0 or 1.
> 0 votes

# Answer
# Japt, ~~11~~ 10 bytes

```
Êo1 eUäa n

```

Run it online

*Saved 1 byte thanks to Shaggy*
> 0 votes

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


# Question
Title: The group of sequential positive numbers with the highest sum?
Given the following list of numbers, find the group of sequential positive numbers with the highest sum.

Example input:

```
12 2 35 -1 20 9 76 5 4 -3 4 -5 19 80 32 -1

```

Example output:

```
131

```

The most succinct code wins.

My approach via Perl is 87 chars (with input as command-line args):

```
print((sort { $b <=> $a } do { push @s, $_ > 0 ? pop(@s) + $_ : 0 for @ARGV; @s })[0]);

```

# Answer
> 1 votes
## Perl: 56 53 characters

Thanks to Ilmari Karonen

```
push@s,$_>0?$_+pop@s:0for@ARGV;say+(sort{$b-$a}@s)[0]

```

# Answer
> 6 votes
## APL, 35 characters

```
i←⎕⋄⌈/{{+/⍵/⍨∧\⍵>0}⍵↓i}¨0,(i≤0)/⍳⍴i

```

I used Dyalog APL for this. `⎕IO` should be set to its default of `1`.

Example (note that high-minus, `¯`, must be used instead of regular minus):

```
      i←⎕⋄⌈/{{+/⍵/⍨∧\⍵>0}⍵↓i}¨0,(i≤0)/⍳⍴i
⎕:
      12 2 35 ¯1 20 9 76 5 4 ¯3 4 ¯5 19 80 32 ¯1
131

```

Explanation (roughly right-to-left for each expression):

* First, we get (and evaluate) the input: `i←⎕`. ( separates expressions in a single statement.)
* `(i≤0)/⍳⍴i` is an idiom to get the list of the locations of elements of `i` that are `≤0`.
    + `i≤0` returns a vector of binary values, where each element is `1` if the corresponding element in `i` is `≤0`, and `0` otherwise.
    + `⍳⍴i` returns a list of integers, from 1 to the shape (length) of `i`.
    + The replication function, `/`, replicates each value in its right argument `n` times, where `n` is the corresponding element in its left argument. Because we have a binary list, this just includes or excludes elements (replicating them 0 or 1 times).
    + We tack a `0` on the beginning, using the concatenation operator (`,`).
* Now, using the example input, we have the vector `0 4 10 12 16`. We use the each operator, `¨`, to map a function (its left operand) to each element of this list.
* The function is a *direct* function (basically, an anonymous function), and its definition is surrounded with curly braces. Its right argument is represented by the omega symbol, .
* For each element of our vector:
    + The outermost function, `{{ ... }⍵↓i}`, returns the vector `i`, with  elements dropped () from the beginning. This is then fed to...
    + The innermost function, `{+/⍵/⍨∧\⍵>0}`, in slightly less golfed form is `{+/(∧\⍵>0)/⍵}`.
    + `(∧\⍵>0)/⍵` is similar to the aforementioned idiom. First we generate a list of elements in  that are above `0`. Then, we use the scan operator, `\`, along with the bitwise-AND function, , to return the list (⍵1 , ⍵1 ∧ ⍵2 , ⍵1 ∧ ⍵2 ∧ ⍵3 , ...). In other words, this list consists of 1's up until the first non-positive element, where it is then all 0's. We use replication as before.
    + We now use the *reduction* operator, (also) represented by `/`, along with the addition function, `+`, to fold all positive elements in the current list, up to (but not including) the first non-positive one.
* Lastly, we fold again, this time with the maximum function, .

Here are snapshots showing the results of some stages:

```
      i≤0
0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1

      ⍳⍴i
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

      0,(i≤0)/⍳⍴i
0 4 10 12 16

      {⍵↓i}¨0,(i≤0)/⍳⍴i
 12 2 35 ¯1 20 9 76 5 4 ¯3 4 ¯5 19 80 32 ¯1  20 9 76 5 4 ¯3 4 ¯5 19 80 32 ¯1  4 ¯5 19 80 32 ¯1  19 80 32 ¯1

      {{(∧\⍵>0)}⍵↓i}¨0,(i≤0)/⍳⍴i
 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0  1 1 1 1 1 0 0 0 0 0 0 0  1 0 0 0 0 0  1 1 1 0

      {{(∧\⍵>0)/⍵}⍵↓i}¨0,(i≤0)/⍳⍴i
 12 2 35  20 9 76 5 4  4  19 80 32

      {{+/(∧\⍵>0)/⍵}⍵↓i}¨0,(i≤0)/⍳⍴i
49 114 4 131 0

```

Hopefully some of this makes a bit of sense!

# Answer
> 4 votes
# CJam, 16 byte

This answer is not eligible for the green checkmark, as CJam is much newer than this challenge (and this answer relies on even newer features). However, I thought this was a really neat approach (and hey, I'm beating APL by quite a margin!), so I wanted to post it anyway.

```
l~]0fe>0a%::+$W=

```

Test it here.

## Explanation

```
l~]              "Read input, eval, wrap in array.";
   0fe>          "Map max(0,x) onto the list, turning all non-positive numbers into 0.";
       0a%       "Split the list on zeroes - i.e. split into positive subarrays.";
          ::+    "Map a fold of + onto the array - i.e. compute the sum of each subarray.";
             $W= "Sort and get the last element - i.e. the maximum.";

```

# Answer
> 3 votes
## Python 3, 93 80 79 71 chars

```
a=b=0
for i in map(int,input().split()):b+=i;b*=i>0;a=max(a,b)
print(a)

```

Thanks to D C for pointing out how to save 8(!) characters from this:

```
a=b=0
for i in map(int,input().split()):b+=i;a=[a,b][b>a];b=[0,b][i>0]
print(a)

```

Saved one character by indexing by true/false rather than if statements.

It is much less readable than the equivalent 80 char version:

```
a=b=0
for i in map(int,input().split()):
 b+=i
 if b>a:a=b
 if i<=0:b=0
print(a)

```

The 93 character version converted to int later in the game:

```
print(max(sum(map(int,s.split()[1:]))for s in('-1 '+input().replace(' 0','-1')).split('-')))

```

# Answer
> 2 votes
## Python 3 (92)

Reads the list of numbers from stdin.

```
m,s=0,[]
for x in map(int,input().split()):
 if x<0:s+=[m];m=0
 else:m+=x
print(max([m]+s))

```

# Answer
> 2 votes
## Perl, 45 chars

```
say+(sort{$b-$a}map$p=$_>0?$_+=$p:0,@ARGV)[0]

```

(Uses `say`, so needs to be run with perl 5.10+ and the `-M5.010` (or `-E`) switch.)

# Answer
> 2 votes
# APL, 22 20

```
⌈/∊(+\×{∧\0<⍵})¨,⍨\⎕

```

To test it online:

```
{⌈/∊(+\×{∧\0<⍵})¨,⍨\⍵}

```

Try it here.

### Explanation

```
{                ,⍨\⍵}    ⍝ Get a list of reversed prefixes.
        {  0<⍵}           ⍝ Check if each item is >0.
        {∧\0<⍵}           ⍝ Check if each prefix is all >0.
     +\                   ⍝ Sum of each prefix.
    (+\×{∧\0<⍵})          ⍝ Sum * all>0 for each prefix.
{   (+\×{∧\0<⍵})¨,⍨\⍵}    ⍝ Apply that to each reversed prefixes (So the prefixes of
                          ⍝   reversed prefixes are reversed suffixes of prefixes of
                          ⍝   the original string).
{  ∊(+\×{∧\0<⍵})¨,⍨\⍵}    ⍝ Flatten the array.
{⌈/∊(+\×{∧\0<⍵})¨,⍨\⍵}    ⍝ Find the maximum.

```

# Answer
> 2 votes
# Japt `-hx`, ~~9~~ 6 bytes

*-3 bytes from @Shaggy*

```
ô<0 ñx

```

Try it online!

# Answer
> 1 votes
## Racket, 108 chars

Once golfed, it gives 133 chars with intermediary "f", or 108 if you use "g" directly.

```
(define f
  (λ (l)
    (g l 0 0)))

(define g
  (λ (l M c)
    (cond
      ((null? l) (max M c))
      ((> 0 (car l)) (g (cdr l) (max M c) 0))
      (else
       (g (cdr l) M (+ (car l) c))))))

(f '(12 2 35 -1 20 9 76 5 4 -3 4 -5 19 80 32 -1)) ;-> 131

```

Where "l" is the list of values, "M" is the maximum sum yet encountered, and "c" is the current sum.

Golfed:

```
(define f(λ(l)(g l 0 0)))(define g(λ(l M c)(cond((null? l)(max M c))((> 0(car l))(g(cdr l)(max M c)0))(else(g(cdr l)M(+(car l)c))))))

```

# Answer
> 1 votes
### Scala: 102 chars

```
def s(x:Seq[Int],y:Int=0):Int={
if(x==Nil)y else
if(x(0)<0)math.max(y,s(x.tail))else
s(x.tail,y+x(0))}

val data = List (12, 2, 35, -1, 20, 9, 76, 5, 4, -3, 4, -5, 19, 80, 32, -1)
s(data)

```

ungolfed:

```
def sumup (xs: Seq[Int], sofar: Int=0): Int = {
  if (xs.isEmpty) sofar else
  if (xs.head < 0) sofar + sumup (xs.tail) else
  sumup (xs.tail, sofar + xs.head)
}
sumup (List (12, 2, 35, -1, 20, 9, 76, 5, 4, -3, 4, -5, 19, 80, 32, -1))

```

# Answer
> 1 votes
# K, 20

```
{max@+/'1_'(&x<0)_x}

```

Finds the indices where x\<0, cuts the list at those indices, drops the negative numbers, sums and finds the maximum.

```
k){max@+/'1_'(&x<0)_x}12 2 35 -1 20 9 76 5 4 -3 4 -5 19 80 32 -1
131

```

Equivalent in q:

```
{max sum each 1_'(where x<0)_x}

```

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
Œʒß0›}Oà

```

Try it online.

**Explanation:**

```
Œ           # Get all sub-lists of the input-list
            #  i.e. [2,4,-5,7]
            #    → [[2],[2,4],[2,4,-5],[2,4,-5,7],[4],[4,-5],[4,-5,7],[-5],[-5,7],[7]]
 ʒ   }      # Filter this list of lists by:
  ß         #  Take the smallest value of the inner list
            #   i.e. [4,-5,7] → -5
   0›       #  Check if it's larger than 0
            #   i.e. -5>0 → 0 (falsey)
 O          # Take the sum of each remaining item
            #  i.e. [[2],[2,4],[4],[7]] → [2,6,4,7]
  à         # And take the maximum of the sums
            #  i.e. [2,6,4,7] → 7

```

# Answer
> 0 votes
# **Perl6** with MoarVM, 53 chars

```
@a[$_ <0??++$i-$i!!$i||++$i]+=$_ for lines;@a.max.say

```

# Answer
> 0 votes
# PHP, 56 bytes

```
while(~$n=$argv[++$i])$n<0?$k++:$r[$k]+=$n;echo max($r);

```

Run with `-nr`.

# Answer
> 0 votes
# Java 8, ~~72~~ 62 bytes

```
l->{int c=0,m=0;for(int i:l){c=i>0?c+i:0;m=m<c?c:m;}return m;}

```

Try it online here.

Ungolfed:

```
l -> { // lambda taking a List as argument and returning an int
    int c = 0, m = 0; // two sums: c is the sum of the current run of positive integers; m is the maximum sum found so far
    for(int i : l) { // for each element in the list:
        c = i > 0 ? c + i : 0; // if the number is positive, extend the current run by adding it to the sum; otherwise reset the sum to zero
        m = m < c ? c : m; // if the maximum recorded so far is smaller than the current sum, record the current sum as the new maximum
    }
    return m; // return the maximum
}

```

# Answer
> 0 votes
# C (gcc/tcc), 69 bytes

```
c,m;f(int*a,int*b){c=m=0;for(;a<b;++a){c=*a>0?c+*a:0;m=m<c?c:m;}a=m;}

```

Port of my Java answer. Try it online here.

# Answer
> 0 votes
## Perl 5 +`-pa -MList::Util+(max)`, 28 bytes

```
$_=max map/-/?$-=0:$-+=$_,@F

```

Try it online!

---
Tags: code-golf, number, sequence, subsequence
---


title: Rememebere tehe vowelese!

text:
# Question
Title: Rememebere tehe vowelese!
## Input

A string of printable ASCII characters, for example:

```
This is an example string.

```

## Output

For every consonant (`BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz`) that is not followed by a vowel (`AEIOUaeiou`) add the last vowel before it, in lowercase.
**Consonants before the first vowel are left as-is**:

```
Thisi isi ana examapale seterinigi.

```

## Test cases

```
AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)
=> ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)

And here comes a **TEST** case with 10% symbols/numbers(#)!
=> Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!

This is an example string.
=> Thisi isi ana examapale seterinigi.

abcdefghijklmnopqrstuvwxyz
=> abacadefegehijikiliminopoqorosotuvuwuxuyuzu

A pnm bnn
=> A panama banana

Tell me if you need more test cases!
=> Telele me ifi you neede more tesete casese!

```

## Scoring

As this is , the answer with the lowest byte-count **in each language** wins (no answer will be accepted).

# Answer
# Retina, 48 bytes

```
i`(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])
$l$1

```

Try it online! Explanation: The lookahead searches for a point not followed by a vowel, while the lookbehind searches for an immediately preceding consonant and a previous vowel, which is then inserted in lower case.
> 14 votes

# Answer
# JavaScript (ES6), ~~108~~ 105 bytes

*(Saved 3 bytes thanks to @Shaggy.)*

```
f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s

```

Searches for vowels *or* for consonants with no following vowel:

```
/[aeiou]|[a-z][^aeiou]/ig

```

(We don't need to search for consonants explicitly, because vowels are excluded based on the `/[aeiou]|...`.)

Vowels are stored in `v`, and consonants with no following vowel have `v` inserted:

```
r[1]?r[0]+v.toLowerCase()+r[1]:v=r

```

(If `r[1]` exists, we've matched on a consonant plus non-vowel.)

If nothing has been changed, we return the input. Otherwise, we recurse on the replaced string.

```
f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s

console.log(f('A pnm bnn'));
console.log(f('abc'));
console.log(f('AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)'));
console.log(f('And here comes a **TEST** case with 10% symbols/numbers(#)!'));
console.log(f('This is an example string.'));
console.log(f('abcdefghijklmnopqrstuvwxyz'));
console.log(f('Tell me if you need more test cases!'));
```
> 8 votes

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

```
def f(s,v=''):u=s[:1];return s and u+v*(u.isalpha()-g(u)-g((s+u)[1]))+f(s[1:],[v,u.lower()][g(u)])
g='aeiouAEIOU'.count

```

Try it online!

EDIT: 15 bytes thx to Lynn
> 5 votes

# Answer
# sed 4.2.2, 64 bytes

```
:
s/(([aeiou])[^a-z]*[b-df-hj-np-tv-z])([^aeiou]|$)/\1\l\2\3/I
t

```

Try it online!
> 5 votes

# Answer
# Perl 5, ~~68~~ ~~67~~ 59 bytes

```
perl -pe '$v="[aeiou])";1while s/($v[^a-z]*[b-z]\K(?<!$v(?!$v/\L$1/i'

```

Here's a great example of the usefulness of `\K`, and I can't believe I didn't know about this feature before Dom Hastings pointed it out.

I haven't been able to get the right behavior with just using `s///g`, so an actual loop seems necessary. (It's possible that the right use of a look-behind assertion could work without an explicit `while` -- but I haven't found it.)
> 4 votes

# Answer
# Standard ML, ~~225~~ 223 bytes

```
str o Char.toLower;fun?c=String.isSubstring(it c)"aeiou"fun g(x,l)$d=(fn l=>if Char.isAlpha$andalso not(?d)then if? $then(it$,l)else(x,l^x)else(x,l))(l^str$)fun f$(c::d::r)=f(g$c d)(d::r)|f$[c]= #2(g$c c);f("","")o explode;

```

Try it online!

**Less golfed:**

```
val lower = str o Char.toLower

fun isVowel c = String.isSubstring (lower c) "aeiou"

(* c is the current char, d is the next char, x is the last vowel and l the accumulator
   for the resulting string *)
fun g (x,l) c d =
    if Char.isAlpha c andalso not (isVowel d)
    then if isVowel c
         then (lower c, l^str c)
         else (x, l^str c^x)
    else (x, l^str c)

fun f t (c::d::r) = f (g t c d) (d::r)
  | f t [c] = #2(g t c #"d")

val h = f ("","") o explode;

```

Try it online!
> 4 votes

# Answer
# JavaScript ES6, 115 bytes

*Saves 8 bytes thanks to @ETHProductions*

```
s=>[x="",...s].map((i,j)=>(r=/[aeiou]/i).test(i)?x=i:/[a-z]/i.test(i)&&!r.test(s[j]||1)?i+x.toLowerCase():i).join``

```

I have managed to inflate this more in the process of golfing it O\_o but it also fixes a bug

```
s=>[x="",...s].map(             // Create a new array with x storing last vowel
                                // This also offsets indexes by one so rel to original str refers to next char
   (i,j)=>                      // Going through each char...
      (r=/[aeiou]/i).test(i)?   // If it's vowel, store it in x
          x=i:
      /[a-z]/i.test(i)          // If a letter (thats not a vowel excluded by above)
         &&!r.test(s[j]||1)?    // Test if next char is *not* vowel
         i+x.toLowerCase():i    // If it isn't, then add the most recent vowel after
    ).join``                    // Combine back to string

```
> 3 votes

# Answer
# JavaScript, ~~88~~ 82 Bytes

Done with a single regular expression:

Original Version (88 Bytes):

```
s=>s.replace(/(?<=([aeiou]).*?(?![aeiou])[a-z])(?=[^aeiou]|$)/gi,(_,c)=>c.toLowerCase())

```

Updated Version (82 Bytes) after looking at Neil's regular expression:

```
s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase())

```

```
var tests = {
  "AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)":
    "ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)",
  "And here comes a **TEST** case with 10% symbols/numbers(#)!":
    "Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!",
  "This is an example string.":
     "Thisi isi ana examapale seterinigi.",
  "abcdefghijklmnopqrstuvwxyz":
    "abacadefegehijikiliminopoqorosotuvuwuxuyuzu",
  "A pnm bnn":
     "A panama banana",
  "Tell me if you need more test cases!":
     "Telele me ifi you neede more tesete casese!"
};

for ( test in tests )
{
  var result = (s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase()))(test);
  console.log( result === tests[test], result );
}
```
> 3 votes

# Answer
# Japt `-P`, 28 bytes

```
ó@\ctX ©\VtYÃËè\v ?P=D:D¬qPv

```

Try it online!

### Unpacked & How it works

```
UóXY{\ctX &&\VtY} mD{Dè\v ?P=D:Dq qPv

UóXY{           }  Split the string between any two chars that don't satisfy...
     \ctX &&\VtY     The first char is a consonant and the second is a non-vowel
mD{                And map...
   Dè\v              If this item is a vowel...
       ?P=D            Assign it to P and return as-is
           :Dq qPv     Otherwise, split the item into chars and join with P lowercased
                       (P starts with "", so beginning consonants are not affected)

-P                 Join with ""

```

The `ó` function wins over any kind of regexes.
> 3 votes

# Answer
# JavaScript (Node.js), ~~146~~ ~~143~~ ~~132~~ ~~127~~ 125 bytes

```
(a,v="")=>[...a].map((b,i)=>(w=/[aeiou]/i).test(b)&&(v=b)?b:w.test(a[i+1]||b)||!b.match(/[a-z]/i)?b:b+v.toLowerCase()).join``

```

Try it online!
> 2 votes

# Answer
# Perl 6,  ~~75 73 71~~  69 bytes

```
{({S:i/.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>/$0.lc()/}...*eq*).tail}

```

Try it

```
{({S:i{.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail}

```

Try it

```
{({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail}

```

Try it

```
{({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><(<![aeiou]>}=$0.lc}...*eq*).tail}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  (
    # generate a sequence

    {  # code block used to generate the values

      S               # substitute (not in-place)
      :i              # :ignorecase
      {

          .*              # start at end of string

          ( <[aeiou]> )   # store the previous vowel in $0

          .*

          <:L - [_aeiou]> # letter other than a vowel

          <(              # ignore everything before this

                          # this is where `$0.lc` gets inserted

          # )>            # ignore everything after this

          <![aeiou]>      # not a vowel (zero width lookahead)

      } = $0.lc       # replace with lowercase of the earlier vowel
    }

    ...    # keep generating until:

    * eq * # there are two equal strings (no changes)

  ).tail   # get the last value
}

```
> 2 votes

# Answer
# TSQL, 500 bytes

```
 CREATE TABLE i (i CHAR(999)); INSERT i VALUES ('The rain in Spain stays mainly in the plain')
 DECLARE @w CHAR(999)=(SELECT i FROM i),@r VARCHAR(999)='';WITH d(n,c,i,q)AS(SELECT n,SUBSTRING(@w,n,1),CHARINDEX(SUBSTRING(@w,n,1),'AEIOUaeiou'),CHARINDEX(SUBSTRING(@w,n,1),'BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz')FROM(SELECT DISTINCT number n FROM master..[spt_values]WHERE number BETWEEN 1 AND LEN(@w))D)SELECT @r=@r+f.c+LOWER(COALESCE(CASE WHEN f.q<>0 AND COALESCE(d2.i,0)=0 THEN SUBSTRING(@w,(SELECT MAX(n)FROM d WHERE i<>0 AND n<f.n),1)END,''))FROM d f LEFT JOIN d d2 ON f.n=d2.n-1 SELECT @r

```

Table `i` is used for input
> 2 votes

# Answer
# Haskell, ~~142~~ 130 bytes

```
""&
import Data.Char
v=(`elem`"aeiouAEIOU")
s&(x:y:z)|v y=x:s&(y:z)
s&(x:y)|v x=x:[toLower x]&y|isAlpha x=x:s++s&y|1>0=x:s&y
_&x=x

```

Try it online!

The initial `""&` is a partial application of the `(&)` function defined later on, and is placed so oddly to make TIO count the bytes in `""&`, but not count the bytes that, in a full program, would be needed to assign that to any named value.

---

Less golfed:

```
import Data.Char (isAlpha, toLower)

vowel :: Char -> Bool
vowel = (`elem`"aeiouAEIOU")

replace :: String -> String
replace = go "" -- start by carrying no extra vowel
  where go _ "" = ""
        -- special case for "anything followed by vowel" so later cases can ignore next character
        go s (x:y:more) | vowel y = x : go s (y:more)
        go s (x:xs) | vowel x = x : go [toLower x] xs -- update the vowel we're carrying
                    | isAlpha x = x : s ++ go s xs -- non-vowel letter not followed by a vowel
                    | otherwise = x : go s xs -- some non-letter junk, just include it and carry on

```

There really ought to be a way to do this more concisely with a fold instead of recursion, but I couldn't figure it out.
> 2 votes

# Answer
# Python 3, 125 bytes

```
lambda s,v='[^aeiouAEIOU':sub(f'(?<={v}\W\d])(?={v}]|$)',lambda m:sub(f'{v}]','',s[:m.end()])[-1:].lower(),s)
from re import*

```

Try it online!

Python 3.6 allows us to (ab)use f-strings to reuse our set of vowels (and for four more characters saved, the beginning of an inverted regex character class) cheaply (a `f` prefix on each string, then `{v}` as needed, instead of the `'+v+'` you'd need with concatenation, or the `[^aeiouAEIOU` you'd insert literally.

The regex that matches no characters, just a position, avoids issues with the non-overlapping matches normal regexes require, and removes the need to backreference any part of the match; all we use the match object for is to get the slice index we use to find the prior vowel.

Partially de-golfed, it would be something like:

```
import re

def get_last_vowel(string):
    '''
    Returns the lowercase version of the last vowel in a string if
    the string contains any vowels, otherwise, return the empty string
    '''
    try:
        *restvowels, lastvowel = re.sub(r'[^aeiouAEIOU]', '', string)
    except ValueError:
        lastvowel = ''  # No vowels in string
    return lastvowel.lower()

def rememebere_tehe_vowelese(string):
    '''Inserts the lowercased last vowel seen after any consonant not followed by a vowel'''
    return re.sub(r'(?<=[^aeiouAEIOU\W\d])(?=[^aeiouAEIOU]|$)',
                  lambda match: get_last_vowel(string[:match.end()]),
                  string)

```
> 2 votes

# Answer
# SWI-Prolog, 593 bytes

```
a(S,D):-atom_chars(S,D).
g(_,[],_,-1).
g(E,[E|_],R,R).
g(E,[_|T],I,R):-N is I+1,g(E,T,N,R).
c(A,E):-g(E,A,0,R),R > -1.
v(X):-a('AEIOUaeiou',X).
c(X):-a('BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz',X).
d([_],_,R,R).
d([H|T],_,I,R):-v(V),c(V,H),!,d(T,H,I,[H|R]).
d([H,N|T],V,I,R):-c(C),c(C,H),v(W),c(W,N),!,d([N|T],V,I,[H|R]).
d([H,N|T],V,I,R):-c(C),c(C,H),v(W),\+c(W,N),string_lower(V,LV),!,d([N|T],V,I,[LV,H|R]).
d([H|T],V,I,R):-!,d(T,V,I,[H|R]).
r([],Z,Z).
r([H|T],Z,A):-r(T,Z,[H|A]).
r(S,D):-r(S,D,[]).
m(X,R):-a(X,O),r(O,P),r([''|P],Q),d(Q,'',I,[]),r(I,J,[]),atomic_list_concat(J,R).

```

Used only built-in predicates (without regex or list manipulating library).

Usage:

```
?- m('A pnm bnn').
'A panama banana'
true .

```
> 2 votes

# Answer
# 05AB1E, 34 bytes

```
vyžMylåil©1V}žPylåžM¹N>èå_Y&&i®«}J

```

Try it online!

---

I take that back I can only shave 3 bytes off this monstrosity... I think I could shave the boolean down, but there MUST be 3 cases. 1 for vowels. 1 for consonants. 1 for the case that a digit/symbol exists.

---

```
v                                 # For each...
 y                                # Push current element.
  žM                              # Push lower-case vowels (aeiou).
    ylå                           # Lower-case current element is vowel?
       i©1V}                      # If so, put it in register, set Y to 1.
            žP                    # Push lower-case consonants (b...z)
              ylå                 # Is current char a consonant?
                 žM¹N>èå_         # Push vowels again, is input[N+1] NOT a vowel?
                         Y        # Did we ever set Y as 1?
                          &&      # All 3 previous conditions true?
                            i®«}  # Concat the current vowel to the current char.
                                J # Join the whole stack.
                                  # '}' isn't needed here, b/c it's implied.
                                  # Implicit return.

```
> 1 votes

# Answer
# Powershell, 104 bytes

based on Neil's regular expression.

```
[regex]::Replace($args,'(?i)(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])',{"$($args.Groups[1])".ToLower()})

```

save it as `get-rememebere.ps1`. Script for testing:

```
$test = @"
AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)
And here comes a **TEST** case with 10% symbols/numbers(#)!
This is an example string.
abcdefghijklmnopqrstuvwxyz
A pnm bnn
Tell me if you need more test cases!
"@

$expected = @"
ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)
Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!
Thisi isi ana examapale seterinigi.
abacadefegehijikiliminopoqorosotuvuwuxuyuzu
A panama banana
Telele me ifi you neede more tesete casese!
"@

$result = .\get-rememebere.ps1 $test
$result -eq $expected
$result

```
> 0 votes

# Answer
# Red, 276 bytes

```
func[s][v: charset t:"AEIOUaeiou"c: charset
u:"BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"b:
parse s[collect[any keep[thru c opt v]keep thru end]]p:""foreach
c b[either find t e: last c: to-string c[p: e][parse c[any[copy p v
| skip]]if find u e[append c lowercase p]]prin c]]

```

Try it online!

Readable:

```
f: func [ s ] [
   v: charset t: "AEIOUaeiou"
   c: charset u: "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
   b: parse s [
       collect [ any keep [ thru c opt v ]
       keep thru end ]
   ]
   p: ""
   foreach c b [
       e: last c: to-string c
       either find t e [ p: e ][
           parse c [ any [ copy p v | skip ] ]
           if find u e [ append c lowercase p ]
       ]
       prin c
   ]
]

```
> 0 votes

# Answer
# Yabasic, 180 bytes

A full program which takes input from STDIN and outputs to STDOUT

```
Line Input""s$
x$="AEIOUaeiou"
For i=1To Len(s$)
c$=Mid$(s$,i,1)
?c$;
If InStr(x$,c$)Then
v$=c$
Else
a=Asc(Upper$(c$))
If a>64And a<91And!InStr(x$,Mid$(s$,i+1,1))Then?v$;Fi
Fi
Next

```

Try it online!
> 0 votes

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


title: Angle between the hands on a clock

text:
# Question
Title: Angle between the hands on a clock
Given the time in 24 hour format (`2359` = `11:59pm`) return the angle between the minute and hour hands on a standard clock (*on the face plane, so don't just output 0*).

Angles are to be returned in the unit of your choice, should be the smallest possible, and should be a positive number (negative angle converted to a positive value), i.e. you will never have an answer greater than 180 degrees or pi radians.

Some examples to check against (in degrees)

* `0000` = `0.0`
* `0010` = `55.0`
* `0020` = `110.0`
* `0030` = `165.0`
* `0040` = `140.0`
* `0050` = `85.0`
* `0150` = `115.0`
* `0240` = `160.0`
* `0725` = `72.5`
* `1020` = `170.0`
* `1350` = `115.0`
* `1725` = `12.5`

Note: There are a few that have rounding errors, I'm not sure how that should be handled; if we should force consistency across all values.

# Answer
## Haskell - 78 characters

```
q[h,i,m,n]=abs$((600*h+60*i-110*m-11*n-312)`mod`720)-360
c s=q$map fromEnum s

```

Note: My "unit of choice" is the "half-degree", of which there are 720 to the circle. With these units, the answer to the problem is always integral! :-)

Ex.:

```
> map c $ words "0000 0001 0010 0630 0633 2325 2345 2355 2359"
[0,11,110,30,3,335,165,55,11]
> map c $ words "0930 1845 0315 1742 2359"
[210,135,15,162,11]

```
> 15 votes

# Answer
# Golfscript, 42 bytes

```
2/~~\~60*+55*3600%.3600\-]{}$~;.10/'.'@10%

```

Outputs whole-a-degrees in float format.
> 12 votes

# Answer
## Perl, 58 characters

Perl is fun

```
perl -nlE "/(..)(..)/;$r=abs$1%12*30-5.5*$2;say+($r,360-$r)[$r>180]"

```
> 6 votes

# Answer
## ES6, ~~52~~ 50 bytes

```
t=>(t=(t-t.match`..`*40)*11%720,(t>360?720-t:t)/2)

```

Input string, output in degrees. If half degrees is acceptable, 46 bytes:

```
t=>(t=(t-t.match`..`*40)*11%720,t>360?720-t:t)

```

Edit: Saved 2 bytes by using a template string parameter to `match`.
> 6 votes

# Answer
# TI-BASIC, 22 bytes

```
expr(Ans
sin⁻¹(sin(πfPart(11/6!(Ans-40int(sub(Ans

```

My unit is the "πth of a revolution", equal to 2 radians. The TI-83+ was introduced in 1996, making it much older than this challenge and thus eligible.

First we evaluate the string using `expr(`, then:

```
                                 sub(Ans   input/100. Don't ask why.
                             int(sub(Ans   Number of hours
                           40              Times 40
                       Ans-                Subtract from input. This converts to minutes.
                 11/6!(                    Multiply by 11/720 since 720/11 is the period.
           fPart(                          Take fractional part
sin⁻¹(sin(π                                Map [0,½] to [0,π/2] and [½,1] to [π/2,0].

```

All test cases have been verified.
> 6 votes

# Answer
## Perl, 61 characters:

```
sub f{$a=abs(int($_[0]/200)-($_[0]%60)/5);($a>6?12-$a:$a)*30}

```
> 4 votes

# Answer
## Ruby 1.9.2p136 : 78 74

```
def a(t)m=t[2,2].to_f
180-((m*6-(m/60+t[0,2].to_f%12)*30).abs-180).abs
end

```

Sample output:

```
["0000", "0010", "0020", "0030", "0040",
  "0050", "0150", "0240", "0725", "1020",
  "1350", "1725"].each do |time|
  puts "#{time} = #{a(time)}"
end
# Output
0000 = 0.0
0010 = 55.0
0020 = 110.0
0030 = 165.0
0040 = 140.0
0050 = 85.0
0150 = 115.0
0240 = 160.0
0725 = 72.5
1020 = 170.0
1350 = 115.0
1725 = 12.5

```
> 4 votes

# Answer
# C99, 86 78 bytes

My units are twelfths of revolutions (so `3` corresponds to 90°)

```
#include<math.h>
float f(int t){return fabs(remainder((t+t%100/1.5)*.11,12));}

```

Equivalently, in C++14, for 76 bytes:

```
#include<cmath>
auto f(int t){return fabs(remainder((t+t%100/1.5)*.11,12));}

```

BSD and SVID platforms have `remd` as an alias for `remainder` (to save 5 more), but I'm sticking with standard C and C++.

## Explanation

We convert sexagesimal seconds to centihours by adding `t%100/1.5` (so 0030 becomes 0050 etc), and divide by 100 to get hours. Coincidence of hands occurs 11 times every 12 hours, so multiply by 11 and divide by 12; we take the remainder in the range \[-6,+6\], and return its absolute value.

## Test program

```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
    int i;
    for (i = 1;  i < argc;  ++i)
        printf("%4s: %f\n", argv[i], f(atoi(argv[i])));
    return 0;
}

```

# Test output:

A minimum around 12:00:

```
1150: 1.833333
1151: 1.650000
1152: 1.466667
1153: 1.283333
1154: 1.100000
1155: 0.916667
1156: 0.733333
1157: 0.550000
1158: 0.366667
1159: 0.183333
1200: 0.000000
1201: 0.183333
1202: 0.366667
1203: 0.550000
1204: 0.733333
1205: 0.916667
1206: 1.100000
1207: 1.283333
1208: 1.466667
1209: 1.650000
1210: 1.833333

```

And a maximum around 6:00:

```
0555: 5.083333
0556: 5.266667
0557: 5.450000
0558: 5.633333
0559: 5.816667
0600: 6.000000
0601: 5.816667
0602: 5.633333
0603: 5.450000
0604: 5.266667
0605: 5.083333

```
> 4 votes

# Answer
# Dyalog APL, ~~34~~ ~~32~~ ~~27~~ 25 characters

Full program. Prompts for 4-character string from stdin. Prints radians to stdout.

```
¯2○2○○360÷⍨11×60⊥⍎¨↓2 2⍴⎕

```

Try it online!

The angle changes linearly with the time, going through 22×360° every 1440 minutes, or 5.5°/min.

Method:

1. Take input:
2. Make into 2-by-2 table: `2 2⍴`
3. Split into rows:
4. Evaluate each: `⍎¨`
5. Convert to minutes: `60⊥`
6. Convert to degrees and then to radians (5.5t × π/180 = 11t × π/360): `○360÷⍨11×`
7. arccos cos to invert after π/2: `¯2○2○`

Test cases can be verified by converting the result into degrees:

```
      angle←  {¯2○2○○360÷⍨11×60⊥⍎¨↓2 2⍴⍵}
      rads2degs←{180×⍵÷○1}

      rads2degs angle ¨ '0000' '0010' '0020' '0030' '0040' '0050' '0150' '0240' '0725' '1020' '1350' '1725'
0 55 110 165 140 85 115 160 72.5 170 115 12.5

```

Try it online!
> 4 votes

# Answer
# Perl, 91 chars

```
#!perl -n
($h,$m)=/(..)(..)/;$h=$h%12+$m/60;$h=abs($h*30-$m*6);printf'%f
',$h>180?360-$h:$h

```
> 3 votes

# Answer
# Python, 82 bytes

```
def a(t):
    o=abs(30*(int(t[:1])%12)-5.5*int(t[2:]));return o if o<=180 else 360-o

```

With some help from the python golfing question I've brought it down to 76:

```
def a(t):
    o=abs(30*(int(t[:1])%12)-5.5*int(t[2:]));return [o,360-o][o>180]

```
> 3 votes

# Answer
## PHP, 80 Characters

```
<?=($i=$argv[1])&&($n=abs(($i[0].$i[1])%12*30-($i[2].$i[3])*5.5))>180?360-$n:$n;

```

Can be run from CLI `php /script_name input`

### Explanation:

```
<?=                           // output result to console
    ($i = $argv[1]) && (      // $argv is an array containing CLI parameters (0: script name, 1: first parameter, etc.)
        $n = abs(             // absolute value to deal with negative numbers
            ($i[0] . $i[1])   // get hours - the first two characters from the input (0 and 1)
                % 12 * 30     // modulus 12 to deal with PM hours (13-23) multiplied by 360/12 = 30 degrees
            - ($i[2] . $i[3]) // get minutes - the subsequent characters from the input (2 and 3)
                * 5.5)        // multiply minutes by 5.5 (1 minute is 360/60 = 6 degrees
                              // and the hour hand moves every minute by 30/60 = 0.5 degrees which we subtract)
        ) > 180               // compare obtained result to 180
    ? 360 - $n                // if the result is greater subtract it from 360
    : $n;                     // if it's less - output as it is

```

### Test cases (input output)

```
0000 0
0010 55
0155 87.5
0240 160
1234 173
2155 32.5
2222 179

```
> 3 votes

# Answer
# Matlab/Octave, 56 bytes

An anonymous function accepting a string, output is in degrees.

```
@(i)180-abs(mod((i-48)*[600;60;10;1],720/11)-360/11)*5.5

```
> 3 votes

# Answer
# Python, 106 bytes

Non-golf solution:

```
def angle_24hr(time_str):
    hour, minute = int(time_str[0:1]) % 12, int(time_str[2:3]) % 60
    angle_dist = lambda a, b: ((a + (180 - b)) % 360) - 180
    return angle_dist(((hour * 30) + (minute * 0.5)), minute * 6) * 10

```

In a more obscure/obfuscated form (admittedly, one of my first code golfs):

```
ad=lambda a,b:((a-b+180)%360)-180;x=int;ag=lambda t:10*ad((x(t[0:1])%12)*60+x(t[2:3]),(x(t[2:3]*12)%60)*6)

```

(what's the point of obfuscating Python?)

If it's necessary for the angles to be purely positive you can remove the -180 term.
> 2 votes

# Answer
## c99 -- 204 necessary characters (keeps getting worse as I fix bugs)

```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){char b[5]={0};fgets(b,5,stdin);int a,h,m=atoi(b+2);b[2]=0;
h=(atoi(b)*60+m)%720;m*=12;a=abs((h-m)%720);a=a>360?720-a:a;printf("%i\n",a);}

```

**Discussion:**

The problem turns out to be harder than it looks. The critical issue is what is meant by "smallest positive angle". I've interpreted that the mean a value between \[0,180\] degrees inclusive (because the problem does not specify which hand to start from when measuring).

To validate this behavior look for places when the hands pass the straight-apart position (such as around 00:33-00:35), and places where they cross-over as around 06:33.

I've also chosen to have a steadily sweeping hour hand, as most modern clocks seem to use that method.

I've adopted MtnViewMark clever trick of using half-degrees as the base unit.

I've suffered the usual problem with c: the preprocessor commands to get the libraries eat up a lot of characters.

**Readable and commented:**

```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
  char b[5]={0};
  fgets(b,5,stdin); /* assumes single byte charaters */
/*   printf("'%s'\n",b); */
  int a,h,m=atoi(b+2); /* minutes */
  b[2]=0;
  h=(atoi(b)*60+m)%720;  /* hour had position in hald-degrees */
  m*=12;                 /* minute hand position in half degrees */
/*   printf("%3i\t%3i\n",h,m); */
/*   printf("%i\n", h-m ); */
/*   printf("%i\n",(h-m)%720 ); */
  a=abs((h-m)%720);
/*   printf("%i\n",   a ); */
  a=a>360?720-a:a;
  printf("%i\n",a);
}

```

**Validation:**

```
$gcc -c99 golf_clock_angle.c
$wc golf_clock_angle.c
  5  11 206 golf_clock_angle.c
$!for
for t in $(cat clock_test_times.txt); do echo $t $(echo $t|./a.out); done
0000 0
0001 11
0002 22
0010 110
0015 165
0030 330
0033 357
0034 346
0035 335
0045 225
0630 30
0633 3
0634 14
2324 324
2325 335
2355 55
2359 11

```
> 2 votes

# Answer
# Mathematica

```
Grid@Prepend[
Table[{Row[{Quotient[x, 60] /. {0 -> 12}, ":", If[Mod[x, 60] < 10, "0", ""], Mod[x, 60]}],
x, N[x/2, 3], Mod[6 x, 360],
IntegerPart[Min[Abs[x/2 - Mod[6 x, 360]], 360 - Abs[x/2 - Mod[6 x, 360]]]]},
{x, 0, 12*60}], {"time", "elapsed min", "hourhand deg", "min deg", "diff deg"}]

```

**Partial output in table**

**Graphs**

```
Plot[{ x/2, Mod[6 x, 360], Min[Abs[x/2 - Mod[6 x, 360]], 360 - Abs[x/2 - Mod[6 x, 360]]]}, {x, 0, 12*60},PlotStyle -> {Green, Blue, {Thick, Red}},AxesLabel -> {"time (hs)", "degrees"},GridLinesStyle -> Directive[Dotted, Gray],Ticks -> {Table[{60 k, k}, {k, 0, 12}], Table[30 k, {k, 0, 12}]},GridLines -> {Table[60 k, {k, 0, 12}], None}]

```

The green line shows the angle of the hour hand, as measured in degrees from 12 o'clock, clockwise. The blue line shows the corresponding angle for the minute hand. The red curve shows the difference between the minute and hour hands in degrees; it always uses the interior angle.
> 2 votes

# Answer
# C++, 175 174 166 156 Characters

```
#include <iostream>
#include <cmath>
int main(){int m,h;std::cin>>h;m=h%100;h=(h-m)/100;h=h>11?h=h-12:h;h=std::abs(h*60-m*11);std::cout<<std::min(720-h,h);}

```

Using "half degree's" as my unit of choice :D

Try it Online!
> 2 votes

# Answer
# C# (.NET Core), 87 bytes

```
t=>{var i=int.Parse(t);double d=i/100%12*30-i%100*5.5,r=d<0?-d:d;return r>180?360-r:r;}

```

Try it online!

I'm sure there are possible improvements that I have missed.

### DeGolfed

```
t=>{
    var i = int.Parse(t);
    // The hour angles minus the minute angles
    double d = i / 100 % 12 * 30 -
               i % 100 * 5.5,
    // account for this possibly being a negative angle
           r = d < 0? -d : d;

    // Get the smaller of the two possible rotational angles
    return r > 180? 360-r : r;
}

```
> 2 votes

# Answer
# JavaScript (ES6), 75 bytes

```
x=>Math.min(x=((x=x.match(/\d\d/g))[0]*60+x[1]*1)*5.5%360,360-x).toFixed(1)

```

This question needed a JavaScript solution.
> 1 votes

# Answer
# SmileBASIC, 60 bytes

```
INPUT T
A=ABS(T DIV 100*60-T MOD 100*11)?A/2+(360-A)*(A>360)

```
> 0 votes

# Answer
# 05AB1E, 23 bytes

```
2ôć12%30*s11;*αD360α)˜ß

```

Outputs degrees like the challenge description.

Port of *@Juan*'s Python answer.

Try it online or verify all test cases.

**Explanation:**

```
2ô                  # Split the (implicit) input in pieces of 2
                    #  i.e. "0150" → ['01','50']
  ć                 # Head extracted
                    #  i.e. ['01','50'] → ['50'] and '01' are pushed to the stack
   12%              # Take the hours modulo 12
      30*           # Multiplied by 30
                    #  i.e. '01' → 30
  s                 # Swap so the minutes are now at the top of the stack
   11;*             # And multiple it by 5.5
                    #  i.e. ['50'] → [275.0]
       α            # Calculate the absolute difference between the two values
                    #  30 and [275.0] → [245.0]
        D           # Duplicate this value
         360α       # Calculate the absolute difference between this value and 360
                    #  i.e. [245.0] → [115.0]
             )      # Wrap the entire stack to a list
                    #  i.e. [245.0] and [115.0] → [[245.0],[115.0]]
              ˜     # Flatten this list (necessary due to the head extracted)
                    #  i.e. [[245.0],[115.0]] → [245.0,115.0]
               ß    # And take the smallest value of the two (output implicitly)
                    #  i.e. [245.0,115.0] → 115.0

```
> 0 votes

---
Tags: code-golf, math, geometry, clock
---


title: Help me with my polyrhythms

text:
# Question
Title: Help me with my polyrhythms
I'm a musician, and I need more polyrhythms in my life!

A polyrhythm occurs in music (and in nature) when two events (claps, notes, fireflies flashing etc.) are occurring at two different regular intervals. The two kinds of event happen a different number of times in the same interval.

If I tap with my left hand twice, and with my right hand 3 times, in the same space of time, it looks a little bit like this:

```
  ------
R . . .
L .  .

```

The hyphens at the top denote the length of the polyrthmic pattern, which is the lowest common multiple or 2 and 3. This can be understood as the point at which the pattern repeats.

There's also a 'metarhythm', which is the pattern produced when either hand is tapping:

```
  ------
R . . .
L .  .
M . ...

```

This is a simple, and very common polyrhythm, with a ratio of 3:2.

Let's just say I don't want to do a simple polyrhythm that I can work out in my head, so I need something to work it out for me. I could do it long-form on paper, or...

---

Rules:

* Write some code to generate and display a polyrhythm diagram, as described above.
* Any old language, try for the fewest bytes.
* Your code takes two arguments:
    + Number of taps with the Left hand (positive integer)
    + Number of taps with the right hand (positive integer)
* It will work out the length, which is the lowest common multiple for the two arguments.
* The top line will consist of two whitespace characters followed by hyphens displaying the length (length * '-')
* The second and third lines will show the pattern for the right and left hands:
    + It will start with an R or L, do denote which hand it is, followed by a space.
    + The interval for that hand is the length divided by it's argument.
    + The taps will start at the third character, denoted by any character you choose. From then on it will display the same character 'interval' characters apart.
    + It will not be longer than the length line.
* The fourth line is the metarhythm:
    + It will start with an upper case M, followed by a space.
    + From the third character onwards, it will show a character (any character you choose) in every position where there's a tap on either the right or the left hand.
* Trailing whitespace is irrelevant.

---

Test cases:

r = 3, l = 2

```
  ------
R . . .
L .  .
M . ...

```

r = 4, l = 3

```
  ------------
R .  .  .  .
L .   .   .
M .  .. . ..

```

r = 4, l = 5

```
  --------------------
R .    .    .    .
L .   .   .   .   .
M .   ..  . . .  ..

```

r = 4, l = 7

```
  ----------------------------
R .      .      .      .
L .   .   .   .   .   .   .
M .   .  ..   . . .   ..  .

```

r = 4, l = 8

```
  --------
R . . . .
L ........
M ........

```

---

Happy golfing!

# Answer
> 6 votes
# JavaScript (ES6), 131 bytes

Outputs `0` as the *tap* character.

```
r=>l=>`  ${g=n=>n?s.replace(/./g,(_,x)=>[,a=x%(k/r),x%=k/l,a*x][n]&&' '):++k%l|k%r?'-'+g():`-
`,s=g(k=0)}R ${g(1)}L ${g(2)}M `+g(3)

```

Try it online!

### How?

We use the same helper function \\$g()\\$ for two different purposes.

When \\$g()\\$ is called with no argument or an argument equal to \\$0\\$, it recursively builds the hyphen string of length \\$k=\operatorname{lcm}(l,r)\\$ with a trailing linefeed:

```
g = _ => ++k % l | k % r ? '-' + g() : `-\n`

```

This string is saved in \\$s\\$.

When \\$g()\\$ is called with \\$1 \le n \le 3\\$, it generates a *tap* string by replacing each hyphen at position \\$x\\$ in \\$s\\$ with either a space or \\$0\\$:

```
g = n => s.replace(/./g, (_, x) => [, a = x % (k / r), x %= k / l, a * x][n] && ' ')

```

# Answer
> 4 votes
# Python 2, ~~187~~ ~~185~~ ~~183~~ ~~174~~ ~~166~~ ~~156~~ ~~148~~ ~~147~~ 145 bytes

Uses `-` as the tap character

```
a,b=r,l=input()
while b:a,b=b,a%b
w=r*l/a
for x,y,z in zip(' RLM',(w,r,l,r),(w,r,l,l)):print x,''.join('- '[i%(w/y)!=0<i%(w/z)]for i in range(w))

```

Try it online!

---

Saved:

* -2 bytes, thanks to Jonathan Frech

# Answer
> 4 votes
# Java 11, ~~226~~ ~~234~~ ~~233~~ 219 bytes

```
String h(int r,int l,int m){var s="";for(;m>0;)s+=m%r*(m--%l)<1?'.':32;return s;}

r->l->{int a=r,b=l,m;for(;b>0;b=a%b,a=m)m=b;m=r*l/a;return"  "+repeat("-",m)+"\nR "+h(m/r,m+1,m)+"\nL "+h(m/l,m+1,m)+"\nM "+h(m/r,m/l,m);}

```

Kind of lengthy; too bad Java does not have an `lcm()` function. Try it online here (TIO does not have Java 11 yet, so this uses a helper method instead of `String.repeat()`).

My initial version took the interval between taps instead of the number of taps. Fixed now. Thanks to Kevin Cruijssen for golfing 1 byte.

Ungolfed:

```
String h(int r, int l, int m) { // helper function returning a line of metarhythm; parameters are: tap interval (right hand), tap interval (left hand), length
    var s = ""; // start with an empty String
    for(; m > 0; ) // repeat until the length is reached
        s += m % r * (m-- % l) < 1 ? '.' : 32; // if at least one of the hands taps, add a dot, otherwise add a space (ASCII code 32 is ' ')
    return s; // return the constructed line
}

r -> l -> { // lambda taking two integers in currying syntax and returning a String
    int a = r, b = l, m; // duplicate the inputs
    for(; b > 0; b = a % b, a = m) // calculate the GCD of r,l using Euclid's algorithm:
        m=b; // swap and replace one of the inputs by the remainder of their division; stop once it hits zero
    m = r * l / a; // calculate the length: LCM of r,l using a=GCD(r,l)
    return // build and return the output:
    "  " + "-".repeat(m) // first line, m dashes preceded by two spaces
    + "\nR " + h(m / r, m + 1, m) // second line, create the right-hand rhythm; by setting l = m + 1 for a metarhythm, we ensure there will be no left-hand taps
    + "\nL " + h(m / l, m + 1, m) // third line, create the left-hand rhythm the same way; also note that we pass the tap interval instead of the number of taps
    + "\nM " + h(m / r, m / l, m); // fourth line, create  the actual metarhythm
}

```

# Answer
> 3 votes
# Python 2, ~~185 228 223 234~~ 249 bytes

```
def f(r,l):
     c='.';d=' ';M,R,L=[r*l*[d]for _ in d*3]
     for i in range(r*l):
      if i%r<1:L[i]=M[i]=c
      if i%l<1:R[i]=M[i]=c
      if r<R.count(c)and l<L.count(c):R[i]=L[i]=M[i]=d;break
     print d,i*'-','\nR',''.join(R),'\nL',''.join(L),'\nM',''.join(M)

```

Try it online!

# Answer
> 3 votes
# Perl 6, ~~85~~ ~~80~~ 78 bytes

*-2 bytes thanks to Jo King.*

```
{«'  'R L M»Z~'-'x($!=[lcm] @_),|(@_.=map:{' '~(0~' 'x$!/$_-1)x$_}),[~|] @_}

```

Try it online!

Returns a list of four lines.

# Answer
> 2 votes
# Jelly, 32 bytes

```
æl/Ḷ%Ɱµa/ṭ=0ị⁾. Z”-;ⱮZ“ RLM”żK€Y

```

Try it online!

Takes input as a list `[L,R]`.

```
æl/       Get LCM of this list.
   Ḷ      Range [0..LCM-1]
    %Ɱ    Modulo by-each-right (implicitly the input, [L,R]):
           [[0%L ... (LCM-1)%L], [0%R ... (LCM-1)%R]]
µ         Take this pair of lists, and:
 a/ṭ      Append their pairwise AND to the pair.
    =0    Is zero? Now we have a result like:
              [[1 0 0 1 0 0 1 0 0 1 0 0 1 0 0]
               [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0]
               [1 0 0 1 0 1 1 0 0 1 1 0 1 0 0]]

ị⁾.       Convert this into dots and spaces.
Z”-;ⱮZ    Transpose, prepend a dash to each, transpose. Now we have
              ['---------------'
               '.  .  .  .  .  '
               '.    .    .    '
               '.  . ..  .. .  ']

“ RLM”ż       zip(' RLM', this)
       K€     Join each by spaces.
         Y    Join the whole thing by newlines.

```

# Answer
> 1 votes
# C (gcc), 204 bytes

```
p(s){printf(s);}
g(a,b){a=b?g(b,a%b):a;}
h(r,l,m){for(;m;)p(m%r*(m--%l)?" ":".");}
f(r,l,m,i){m=r*l/g(r,l);p("  ");for(i=m;i-->0;)p("-");p("\nR ");h(m/r,m+1,m);p("\nL ");h(m/l,m+1,m);p("\nM ");h(m/r,m/l,m);}

```

Port of my Java answer. Call with `f(number_of_right_hand_taps, number_of_left_hand_taps)`. Try it online here.

# Answer
> 1 votes
# Pyth, 53 bytes

```
j.b+NYc"  L R M "2++*\-J/*FQiFQKm*d+N*\ t/JdQsmeSd.TK

```

Definitely room to golf. Will do so when I have time.
Try it here

### Explanation

```
j.b+NYc"  L R M "2++*\-J/*FQiFQKm*d+N*\ t/JdQsmeSd.TK
                       J/*FQiFQ                        Get the LCM.
                    *\-                                Take that many '-'s.
                               Km*d+N*\ t/dJQ          Fill in the taps.
                                             smeSd.TK  Get the metarhythm.
                  ++                                   Append them all.
      c"  L R M "2                                     Get the prefixes.
 .b+NY                                                 Prepend the prefixes.
j                                                      Join with newlines.

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 254 bytes

---

**Golfed** Try it online!

```
(r,l)=>{int s=l>r?l:r,S=s;while(S%l>0|S%r>0)S+=s;string q(int a){return"".PadRight(S/a,'.').Replace(".",".".PadRight(a,' '));}string R=q(S/r),L=q(S/l),M="";s=S;while(S-->0)M=(R[S]+L[S]>64?".":" ")+M;return"  ".PadRight(s+2,'-')+$"\nR {R}\nL {L}\nM {M}";}

```

---

**Ungolfed**

```
( r, l ) => {
    int
        s = l > r ? l : r,
        S = s;

    while( S % l > 0 | S % r > 0 )
        S += s;

    string q( int a ) {
        return "".PadRight( S / a, '.' ).Replace( ".", ".".PadRight( a, ' ' ) );
    }

    string
        R = q( S / r ),
        L = q( S / l ),
        M = "";

    s = S;

    while( S-- > 0 )
        M = ( R[ S ] + L[ S ] > 64 ? "." : " " ) + M;

    return "  ".PadRight( s + 2, '-') + $"\nR {R}\nL {L}\nM {M}";
}

```

---

**Full code**

```
Func<Int32, Int32, String> f = ( r, l ) => {
    int
        s = l > r ? l : r,
        S = s;

    while( S % l > 0 | S % r > 0 )
        S += s;

    string q( int a ) {
        return "".PadRight( S / a, '.' ).Replace( ".", ".".PadRight( a, ' ' ) );
    }

    string
        R = q( S / r ),
        L = q( S / l ),
        M = "";

    s = S;

    while( S-- > 0 )
        M = ( R[ S ] + L[ S ] > 64 ? "." : " " ) + M;

    return "  ".PadRight( s + 2, '-') + $"\nR {R}\nL {L}\nM {M}";
};

Int32[][]
    testCases = new Int32[][] {
        new []{ 3, 2 },
        new []{ 4, 3 },
        new []{ 4, 5 },
        new []{ 4, 7 },
        new []{ 4, 8 },
    };

foreach( Int32[] testCase in testCases ) {
    Console.Write( $" Input: R: {testCase[0]}, L: {testCase[1]}\nOutput:\n{f(testCase[0], testCase[1])}" );
    Console.WriteLine("\n");
}

Console.ReadLine();

```

---

**Releases**

* **v1.0** \- `254 bytes` \- Initial solution.

---

**Notes**

* None

# Answer
> 1 votes
# Ruby, ~~130~~ 126 bytes

```
->*a{puts"  "+?-*s=a[0].lcm(a[1])
r,l=a.map!{|e|(?.+' '*(s/e-1))*e}
[?R,?L,?M].zip(a<<r.gsub(/ /){l[$`.size]}){|e|puts e*" "}}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 52 bytes

```
≔θζＷ﹪ζη≧⁺θζζ↙≔⮌Ｅζ⟦¬﹪×ιθζ¬﹪×ιηζ⟧ζＦζ⊞ι⌈ι↓Ｅζ⭆ι§ .λ←↓RLM

```

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

```
≔θζＷ﹪ζη≧⁺θζ

```

Calculate the LCM of the inputs by taking the first multiple of `R` that's divisible by `L`.

```
ζ↙

```

Print the LCM, which automatically outputs the necessary row of `-`s. Then move to print the rhythm from right to left.

```
≔⮌Ｅζ⟦¬﹪×ιθζ¬﹪×ιηζ⟧ζ

```

Loop over the numbers from the LCM down to 0 and create an array of lists representing the beats of the right and left hands.

```
Ｆζ⊞ι⌈ι

```

Loop over the beats and add the metarhythm.

```
↓Ｅζ⭆ι§ .λ

```

Print the reversed beats downwards, but as this is an array they end up leftwards.

```
←↓RLM

```

Print the header.

# Answer
> 1 votes
# Python 2, 117 bytes

```
a,b=input();n=a
while n%b:n+=a
for i in-1,1,2,3:print'_RLM '[i],''.join(' -'[i%2>>m*a%n|i/2>>m*b%n]for m in range(n))

```

Try it online!

# Answer
> 1 votes
# Pyth, 49 bytes

```
J/*FQiFQjC+c2" RLM    "ms@L" -"!M++0d*Fdm%Ld/LJQJ

```

Expects input in the form `[r,l]`. Uses `-` to display taps. Try it online here, or verify all test cases at once here.

```
J/*FQiFQjC+c2" RLM    "ms@L" -"!M++0d*Fdm%Ld/LJQJ   Implicit: Q=eval(input())
 /*FQiFQ                                            Compute LCM: (a*b)/(GCD(a,b))
J                                                   Store in J
                                        m       J   Map d in [0-LCM) using:
                                            /LJQ      Get number of beats between taps for each hand
                                         %Ld          Take d mod each of the above
                                                    This gives a pair for each beat, with 0 indicating a tap
                       m                            Map d in the above using:
                                     *Fd              Multiply each pair (effecively an AND)
                                 ++0d                 Prepend 0 and the original pair
                               !M                     NOT each element
                        s@L" -"                       Map [false, true] to [' ', '-'], concatenate strings
                                                    This gives each column of the output
           c2" RLM    "                             [' RLM','    ']
          +                                         Prepend the above to the rest of the output
         C                                          Transpose
        j                                           Join on newlines, implicit print

```

# Answer
> 1 votes
# , ~~161~~ ~~149~~ 146 bytes

```
function(a,b){l=numbers::LCM(a,b)
d=c(0,' ')
cat('  ',strrep('-',l),'\nR ',d[(x<-l:1%%a>0)+1],'\nL ',d[(y<-l:1%%b>0)+1],'\nM ',d[(x&y)+1],sep='')}

```

Try it online!

I definitely feel like there's room for improvement here, but I tried a few different approaches and this is the only one that stuck. ~~Getting rid of the internal function definition would make me quite happy, and I tried a bunch of restructures of the cat() to make it happen.~~ Nevermind, as soon as I posted I realised what I could do. Still definitely some efficiency savings to be found.

There are other LCM functions in libraries with shorter names, but TIO has numbers and I considered that more valuable at this point.

# Answer
> 1 votes
# C++ (gcc), 197 bytes

```
int f(int a,int b){std::string t="  ",l="\nL ",r="\nR ",m="\nM ";int c=-1,o,p=0;for(;++p%a||p%b;);for(;o=++c<p;t+="-")l+=a*c%p&&++o?" ":".",r+=b*c%p&&++o?" ":".",m+=o-3?".":" ";std::cout<<t+l+r+m;}

```

Try it online!

---
Tags: code-golf
---


title: Display percent battery remaining

text:
# Question
Title: Display percent battery remaining
### Display the remaining battery charge, as a percentage of maximum charge

Remember if you can't run your code on a phone, calculator, etc, you can probably install your environment on a laptop at least. If you absolutely can't run on a device that has a battery, then unfortunately your language isn't eligible since you have no useful value to print.

You must display the results on the screen. This is theoretically supposed to be a handy utility for the user to check the battery. Writing battery percent to a file is too clunky, requiring the user to then check the file. Displaying on-screen is therefore a part of the specification that can't be overridden by default IO. That said, you can assume nothing is preventing things like STDOUT from being displayed on screen in the usual way.

If the battery percent is already displayed on screen all the time by the OS, like on many phones, that does not mean you've got a zero-byte solution. You must assume that built-in display doesn't exist, and display the battery percent again somewhere else.

Edit: The output format is being opened up. You are free to display as little as just the digits of the percent, or the digits with some extra output as well.

Edit2: The digits representing the percent must appear in a known location within the output, not more than 50 lines from the end of the output, and that location shouldn't change between invocations. The digits representing the percent must be separated from other output by at least one non-digit character on each side.

For reference here is the old output format from before the change:

`Remaining battery is ddd%` or `Remaining battery is ddd percent`

# Answer
> 43 votes
# Bash, ~~70~~ ~~67~~ ~~50~~ ~~46~~ ~~43~~ 16 bytes

```
`</*/*/*/B*/c*y`

```

Outputs: `<battery 0-100>: command not found`

Reads the file `/sys/class/power_supply/BAT1/capacity`.

Tested using Ubuntu 18.04 on a LENOVO ideapad 500.

Takes a while (since it searches the entire filesystem) - but it saves a byte!

### Old answer:

```
echo Remaining battery is `</*/*/*/B*/c*y`%

```

# Answer
> 13 votes
# JavaScript (browser), ~~78~~ ~~77~~ 50 bytes

(-1 byte thanks to Benoit Esnard)

(-27 bytes since the output format is flexible now)

```
navigator.getBattery().then(b=>alert(b.level*100))
```

# JavaScript (browser), 46 bytes, by returning a promise

(Suggested by Shaggy, requires a header and footer)

```
f=
_=>navigator.getBattery().then(b=>b.level*100)
f().then(alert)
```

---

**Note:** Only works on Google Chrome \>= 38 (desktop and Android) or any other browser that supports Battery API. FireFox has removed this API due to privacy concerns.

**Example on Android (old output format):**

**Example on a Windows laptop (old output format):**

# Answer
> 12 votes
# PowerShell, 28 bytes

-26 (!) thanks to AdmBorkBork. Previous version -3 thanks to colsw.

```
((gwmi win32_battery)|% e*g)

```

`gwmi` is short for `Get-WmiObject`

`|%` takes the pattern `e*g` and finds the only matching property; `estimatedChargeRemaining`

# Answer
> 10 votes
# Bash+acpi, ~~43~~ 4 bytes

## New rules

```
acpi

```

output on form

```
Battery 0: Charging, 92%, 00:05:37 until charged

```

not sure if the rule change makes things more interesting, couldn't you dump any text that contains all strings 0 to 100 which would be valid output? Seems to lose the original intent if so.

## Old rules

```
set `acpi`;echo Remaining battery is ${4%,}

```

output on form

```
Remaining battery is 92%

```

Don't ask me why set works like this, but it does.

# Answer
> 6 votes
# Python 3.6 \+ `psutil`, 80 bytes

```
import psutil
print(f"Remaining battery is {psutil.sensors_battery().percent}%")

```

Try it online!

If the machine has no battery (like on TIO), the program will throw an error, because `psutil.sensors_battery()` returns `None`.

This requires Python 3.6 for string interpolation.

# Answer
> 5 votes
# C (win32, gcc i686-w64-mingw32), 78 bytes

```
#include<windows.h>
main(s){GetSystemPowerStatus(&s);printf("%hhu",s>>16);}

```

Abuses the win32 API by letting `GetSystemPowerStatus()` write "somewhere" on the stack, the interesting member is in the third byte, according to the `SYSTEM_POWER_STATUS` struct.

Unfortunately, the `#include` seems to be needed, probably because of calling conventions.

Example output:

```
> bat.exe
90

```

Displays `255` on systems without a battery.

# Answer
> 4 votes
# Excel VBA, 150 bytes

Restricted to 32-Bit Windows Installs of office, because the windows Kernel32 call is not 64-bit pointer safe.

Outputs to the cell `A1` on the ActiveSheet.

```
Declare Sub GetSystemPowerStatus Lib"kernel32"(f As t)
Type t
i As Integer
b As Byte
End Type
Sub d
Dim e As t
GetSystemPowerStatus e
[A1]=e.b
End Sub

```

-26 bytes thanks to flexible output

-7 bytes thanks to @Neil for using an Int instead of 2 bytes

# Answer
> 3 votes
# QPython for Android, 133 bytes

```
from androidhelper import*
d=Android()
d.batteryStartMonitoring()
d.dialogCreateAlert(str(d.batteryGetLevel()[1])+"%")
d.dialogShow()

```

The `+"%"` isn't strictly necessary since it uses the newer more flexible output format anyway, but it makes for slightly nicer output at just +4 bytes.

# Answer
> 2 votes
# Emacs Lisp, 9 bytes

```
(battery)

```

Shows current battery status in mini-buffer at the bottom (or to stdout when using `--batch`) in format such as: `Power N/A, battery Unknown (99.1% load, remaining time N/A)`.

Should work on Windows, OSX, BSD , and Linux.

# Answer
> 1 votes
# Japt, 60 bytes

```
Ox`nàÀÓ&.getBÂjry().È(x=>O.q("Rà@°á ßMy  "+L*x.¤vel+"%"))

```

Test it

# Answer
> 1 votes
# Java, 546 bytes (Windows XP or Higher)

The powercfg utility came into play for WindowsXP, I have no idea what utilities were available prior to this. I must also be run as administrator. This is god-awful and I didn't make an extreme golfing attempt...

```
import java.io.*;import java.util.Scanner;public class J {public static void main(String[] args)throws Exception{Process p=Runtime.getRuntime().exec("powercfg energy");p.waitFor();Scanner s=new Scanner(new File("C:\\windows\\system32\\energy-report.html"));String x;double a=0,b=0;while(s.hasNextLine()){x=s.nextLine();if(x.contains("Design Capacity")){s.nextLine();b=Integer.parseInt(s.nextLine().replaceAll("\\D+",""));}else if(x.contains("Last Full Charge")){s.nextLine();a=Integer.parseInt(s.nextLine().replaceAll("\\D+",""));}}System.out.print(a/b*100);}}

```

Formatted / commented...

```
import java.io.*;
import java.util.Scanner;

public class J {
    public static void main(String[] args) throws Exception {
        Process p = Runtime.getRuntime().exec("powercfg energy"); // Run CMD sys32 app.
        p.waitFor();                                              // Wait for it.
        Scanner s = new Scanner(new File(
                "C:\\windows\\system32\\energy-report.html"));    // Read output.
        String x;
        double a = 0, b = 0;
        while (s.hasNextLine()) {
            x = s.nextLine();
            if (x.contains("Design Capacity")) {                   // Find max capacity.
                s.nextLine();
                b = Integer.parseInt(s.nextLine().replaceAll("\\D+", ""));
            } else if (x.contains("Last Full Charge")) {           // Find current capacity.
                s.nextLine();
                a = Integer.parseInt(s.nextLine().replaceAll("\\D+", ""));
            }
        }
        System.out.print(a / b * 100); // Calculate %.
    }
}

```

Honestly I was more interested to see if it was even possible in Java.

---
Tags: code-golf
---


# Question
Title: Map an array of functions to their return values in point-free style
# Introduction

I have some JavaScript code that uses `Array.prototype.map` to map an array of functions `fns` to their return values:

```
const fns = [() => 1, () => 2];
const result = fns.map(
  fn => fn()
);
console.log(result); // => [1, 2]
```

# Challenge

The argument to `map` above is `fn => fn()`. The challenge is to **rewrite this function using point-free style**. Your solution should work when it replaces the third line of the above program:

```
const fns = [() => 1, () => 2];
const result = fns.map(
  /* your solution should work when inserted here */
);
console.log(result); // => [1, 2]

```

`fn => fn()` is not a valid solution because it defines a parameter named `fn`. Writing a function in point-free style requires writing it **without any variable or parameter names**.

Note that `map` will pass three arguments to your solution function: `currentValue: () => T`, `index: number`, and `array: Array<() => T>`. The function for the solution **must return the result of calling** the `currentValue` function, so hard-coding `1` and `2` will not help. The functions being mapped over are guaranteed to ignore their arguments and their `this` value, so calling the function in any way will work.

# Scoring

The **best answer** is the one that is represented by the **fewest tokens** when lexed. The ANTLR 4 JavaScript lexer is the official lexer for the sake of objectivity, but if you know how a lexer works you should be able to estimate how many tokens some JavaScript needs without having to read that link. For example, `fn => fn()` is composed of five tokens: `fn` `=>` `fn` `(` `)`.

However, I personally think that figuring out *any* answer is the fun part, so if this problem interests you, try to solve it yourself before scrolling down and seeing the answer.

# Answer
Based on the answer by Rory O'Kane:

> **10 tokens**: `Number.call.bind(String.call)`

Try it online!

It is trivial, since `Number.call, String.call`, `Object.call`, `Function.call`, `(function () {}).call`, `Function.prototype.call` are all the same.

If Bind Operator Proposal is accepted, this could be simplified to:

> **6 tokens**: `::Function.call.call`

Babel

BTW, if eval is allowed `eval("Number.call.bind(String.call)")` only use 4 tokens.
> 2 votes

# Answer
This combination of `Function.prototype.call` and `Function.prototype.bind` works:

```
Function.prototype.call.call.bind(Function.prototype.call)

```

**16 tokens:** `Function` `.` `prototype` `.` `call` `.` `call` `.` `bind` `(` `Function` `.` `prototype` `.` `call` `)`

```
const fns = [() => 1, () => 2];
const result = fns.map(
  Function.prototype.call.call.bind(Function.prototype.call)
);
console.log(result); // => [1, 2]
```

# Explanation

`Function.prototype.call` is not a solution on its own because `map` will call `call` with its `this` value set to `undefined`. `call`’s purpose is to call the function in `this`, so when `this` is `undefined` a `TypeError` is raised.

Similarly, `Function.prototype.call.bind(Function.prototype)` is insufficient because the `call` function is called with `this` set to `Function.prototype`, and the function you want called set to the first argument. Calling `Function.prototype()` with any arguments returns `undefined`, so the function will return `undefined` instead of `1` or `2`.

My solution works by using the second `call` to make the `fn` argument the `this` of the first `call`, like this:

```
fn => Function.prototype.call.call(fn)

```

Now the first `call` can do what it is made for, calling the argument in its `this` value.
> 1 votes

---
Tags: javascript, programming-puzzle, functional-programming
---


# Question
Title: Python: shortest way to interleave items from two lists
I'm trying to get the shortest way (character possible) to obtain List 3.

List 1 and List 2 are already given to me as arguments and are the same length.

```
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']

```

And List 3 should look like (yes, it needs to be a list):

```
l3 = ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5]

```

# Answer
# Zip and Sum

```
[*sum(zip(l2,l1),())]

```

Try it online!

Zips the two lists together then adds all the tuples to make one combined list. The zip only works if the lists are guaranteed to be the same size, otherwise it truncates the longer list.

Added the surrounding `[* ]` to transform it into a list as FryAmTheEggman suggests.
> 13 votes

# Answer
# Slice assignment

```
c=a*2
c[1::2]=a
c[::2]=b

```

This is three bytes longer than using Jo King’s solution `c=[*sum(zip(b,a),())]`, but it’s nifty. It might be shorter situationally (I can’t think of where, though).
> 7 votes

---
Tags: code-golf, tips, python
---