Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 19 22 24 25

$ jolly 19 22 24 21
Not jolly
share|improve this question
How is the sequence given? As a string? "4124"? – Steven Rumbalski Sep 1 '11 at 14:59
I think space-separated would be the most common convention, so I'll say that. – eternalmatt Sep 1 '11 at 15:56
You say input is on stdin, but your examples take input as command line arguments. Which should we expect? – Gareth Sep 1 '11 at 21:26

25 Answers 25


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".


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]
share|improve this answer
+1 Good rules lawyering. Although I should point out that in GolfScript the empty program would suffice... – Peter Taylor Sep 1 '11 at 22:13
The alternative solution seems to give wrong result. [1,3] is not jolly, is it? I guess you must iterate to length n-1 instead. – Rotsor Jun 20 '12 at 15:48

Ruby, 92 93 characters

The hard version with input on STDIN.

$><<(f==[*1..f.size]??J:"Not j")+"olly"

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

$_=(f==[*1..f.size]??J:"Not j")+"olly"
share|improve this answer
Ah, nice improvement. Didn't realize there was an each_cons method. – migimaru Sep 2 '11 at 15:12
I just realized that this fails when the sequence is a single digit. You'd have to stick with f.size instead f[-1]. – migimaru Sep 4 '11 at 16:12
@migimaru Thank you. – Howard Sep 5 '11 at 18:05
Oh, you can also save 5 characters if you run it with options -pa . – migimaru Sep 5 '11 at 18:17

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(" ");
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");


public class JollyJumper {
public static void main(String[] args) {
    Scanner sc = new Scanner(;
    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]));


    for (int i = 1; i <= in.length-1; i++) {
        if (jolly[i-1] != i) {
            System.out.println("Not jolly");
share|improve this 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)

To run or test on

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
share|improve this answer
The name could be j instead of jump. – user unknown Sep 1 '11 at 20:52
@user unknown Yes, I know. I realised about half an hour after I posted it that a) I could shorten the method name, and b) I need to use a List instead of a Set, or it won't work properly. :-S – Gareth Sep 1 '11 at 21:08
And the updated rules expect the numbers to be divided by space, 4124 could be one, two, three or 4 numbers. – user unknown Sep 1 '11 at 21:18
@user unknown Oh great. Another person posting a question and then changing the rules half way through. – Gareth Sep 1 '11 at 21:23
I removed return type Boolean, a literal 'return' before `false' and changed Math to math. Saving from 137 to 123. – user unknown Mar 26 '12 at 14:28

Golfscript, easy mode, 21 18 chars


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"
share|improve this answer
I was wondering how this could possibly work -- it took me a moment to realize that when you write "a list of ints on the stack", you really do mean a list of ints (i.e. [4 1 2 4], not 4 1 2 4). – Ilmari Karonen Mar 26 '12 at 23:14
@IlmariKaronen, not sure now why I wrote "list". I've edited to "array" to make it clearer. – Peter Taylor Mar 27 '12 at 8:36

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.

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

share|improve this answer
Consider input 1 3. – Peter Taylor Sep 1 '11 at 17:34
Thanks, @Peter. Fixed...and still not competitive with your Golfscript. Well done. – DCharness Sep 2 '11 at 5:49

Ruby, 97 102 106 (hard)

Might as well, since everyone else is:

$><<(d==[*1..d.size]??J:"Not j")+"olly"

Input taken on stdin.

share|improve this answer
You can replace (1..d.size).to_a by [*1..d.size]. Switching operands is now possible, saves another one (total -5 chars). – Howard Sep 2 '11 at 14:34
@Howard Oh, so that's how you do it! I've been trying to figure out a golf way to convert ranges to arrays for a while now. Thanks! – migimaru Sep 2 '11 at 14:47
You're welcome. – Howard Sep 2 '11 at 14:49


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");}
share|improve this answer


Easy: 78


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()};{println "${j(it.split()*.toLong())?'J':'Not j'}olly"}
share|improve this answer


A quick stab - there are probably improvements possible.

Easy: 77

def j(? :Int*)=(?tail,?) to?.size-1)

Hard: 124

val?;print(if((?tail,?) to?.size-1))"Jolly"else"Not jolly")
share|improve this answer
Ok - we're lost, Luigi found us! :) Welcome on CodeGolf. Immediately I start learning something. Question mark as identifier? Whooo - who allowed that? :) – user unknown Mar 26 '12 at 16:28
Yes, and all to shave 1 character off! It's the difference between an alphanumeric characters and operator characters (see which means you can sometimes omit spaces (but sometimes need extra ones) and dots. Code golf is great for learning though - a bit like aerobatics for flying. – Luigi Plinge Mar 26 '12 at 16:45

Q, 64 (hard), 30 (easy)


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


{(1_(!)(#)x)~asc abs 1_(-':)x}
share|improve this answer

J (easy), 19 characters



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

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 1s and 0s generated by the previous verb.

share|improve this answer
Didn't realize until after I submitted my answer: we took the same approach, but I used x-:y instead of */x=y to save a character. – ephemient Apr 1 '12 at 0:49

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}


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 = (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")}

more or less the same as above.

share|improve this answer
Input 4 1 2 5 returns true. Still haven't managed to get my head around that left fold though... – Gareth Sep 1 '11 at 22:32
Oh yes, I found my error. Need to correct it. – user unknown Sep 1 '11 at 23:03
readLine takes input from the console, not the stdin... (but you can use args instead) – Luigi Plinge Nov 19 '11 at 2:31
And j("1") throws UnsupportedOperationException: empty.max – Luigi Plinge Nov 19 '11 at 17:03
Pardon - how do you define the difference between stdin and "input from the console"? – user unknown Nov 19 '11 at 23:15

PHP, easy, 129

For a given array $s of integers:

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";        
share|improve this answer

J (easy), 18

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

J (hard), 68

2!:55]1!:2&2'olly',~>('Not j';'J'){~(i.@#-:<:/:])|2-/\".@>2}.ARGV_j_
$ jconsole jumper.ijs 2 -1 0 2
$ jconsole jumper.ijs 19 22 24 25
$ jconsole jumper.ijs 2 19 22 24 21
Not jolly
share|improve this answer

JavaScript: 105 (easy mode)


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}


function isJolly(list){
    //Iterate over i to list.length-1
        //Check the differences between all consecutive elements squared minus i squared.  Set t to true if one was found.

        //if t is not true, return value is 0
    return r
share|improve this 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/
share|improve this answer

Javascript (hard): 138

a=prompt().split(" ")
alert(b+""==c+""?"Jolly":"Not jolly")
share|improve this answer
    #!/usr/bin/env python

def main():

if __name__ == '__main__':

numbers = []
jolly_list = []

numbers = raw_input("Enter Numbers: ").split()
for count in range ( len(numbers)-1 ) :
    jolly_list.append ( abs( int(numbers[count]) - int(numbers[count+1]) ) )

jolly_list = sorted(jolly_list)
for count in range(len(jolly_list)) :
    flag = 0
    if count+1 == jolly_list[count] :
        flag = 1
    else :
        flag = 0
        print "Not Jolly"
if flag == 1:
    print "Jolly"
share|improve this answer
Hello John and welcome. The idea of code golf is, to reduce the size as far as you can. I'm not a pyhtonian, but "Enter Numbers" is definetly superflous. – user unknown Mar 26 '12 at 16:06

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'


  • 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
share|improve this 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)}


f(c(2, -1, 0, 2))
[1] 1
f(c(19, 22, 24, 25))
[1] 1
f(c(19, 22, 24, 21))
[1] 0
share|improve this answer

Python, 72 (easy), 114 (hard)


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


print('Not j','J')[len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2]+'olly'
share|improve this answer

Python, 255 characters

k=[ i+1 for i in range(len(r)-1)]
def jolly(a):
    while i<len(a)-1: 
    if p==k:
       return 'jolly'
       return 'Not jolly'

share|improve this answer
I've added the language name and character count to your answer (it runs as Python so that's what I assume it is). The character count I've given is the one give by the userscript. You could probably cut down the first indentation level to one space to save some characters here. – Gareth Oct 27 '12 at 16:58

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);}
share|improve this answer

APL (50 49 47, hard)

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

Easy (24):


The function takes an array and returns 0 or 1.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.