# 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  • 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 ## 31 Answers ## 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]  • +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=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"  • 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 • 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(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"); } }  ## 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")) } }  • 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 {.@-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"  • 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 (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  # Brachylog, 11 bytes (easy) s₂ᶠ-ᵐȧᵐo~⟦₁  Try it online! s₂ᶠ-ᵐ - Consecutive differences ȧᵐ - Absolute values o - Sort ~⟦₁ - Is the result the range 1 to something? ## 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 • 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 102106 (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.

• 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

# 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");}


# 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]


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"}  ## 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 # 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")  • 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 stackoverflow.com/q/7656937/770361) 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) hard {$[(1_(!)(#)x)~asc abs 1_(-':)x;(-1"Jolly";);(-1"Not jolly";)];}


easy

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


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

• 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}


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))
j


more or less the same as above.

• 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++)$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";  # 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!

• LR is J. If you write something like IAṢ⁼J$ you get a nice 1/0 result, and you can use that to index into “Not jolly“Jolly”: ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ» – Lynn May 4 '18 at 14:58
• @Lynn Thank you, that's much better! Clever trick with the one-indexed wrapping around, and I learned more about the ⁼ atom too, handy to compare just parts of lists. – Harry May 4 '18 at 17:11

# Haskell, 59 57 bytes

f n=all(elemmap 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! # Japt, 32 30 bytes Hard -2 Bytes from @Shaggy not jo¥ys4*Näa n äa e¥1 hUÎu  Try it online! • 30 bytes. I only noticed the capitalisation requirement at the last second so can probably be improved further. – Shaggy Jul 31 '18 at 16:38 ## 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! • There is an error in your program. Try it online – mbomb007 Jul 31 '18 at 18:25 • This gives the wrong answer for the first test case. Please check your program for the test cases contained in the question. – mbomb007 Jul 31 '18 at 19:15 • Feel ashamed, cause when fixed wrong version forgot to reverse outputs ;( – Андрей Ломакин Jul 31 '18 at 19:21 • Welcome to PPCG!! – Luis felipe De jesus Munoz Aug 1 '18 at 13:48 ## 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 }  ## 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/


## 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()

    #!/usr/bin/env python

def main():
pass

if __name__ == '__main__':
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"
break
if flag == 1:
print "Jolly"

• 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

## 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


## 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'


## 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))

• 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);}


## APL (5049 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.