There are two new sheriffs in town – Identifying DJMcMego pairs!

60

1

We have some new sheriffs moderators in town, Mego and DJMcMayhem. We need a challenge to properly honour them for their new positions, so there we go.

Here's something that has caught my attention when hovering over their profiles – their user IDs are \$31716\$ and \$45941\$. If you perform digit-wise subtraction, you'll notice something pretty exciting (of course, taking the absolute differences):

3|1|7|1|6
4|5|9|4|1
-+-+-+-+- (-)
1|4|2|3|5

The number generated by the above algorithm is \$14235\$. There is something special about this integer: It consists of consecutive digits only, sorted in ascending order, but exactly one of the digits is not placed correctly — \$4\$.

We will call a pair of positive integers \$(a, b)\$ a DJMcMego pair if the digit-wise absolute differences are consecutive integers, sorted in ascending order, but exactly one of them is not where it belongs. That is, it is possible to move exactly one digit of the result of digit-wise subtraction to another position, such that the integer obtained only has consecutive digits, sorted in ascending order.

In our example above, the pair \$(31716, 45941)\$ is a DJMcMego pair, because if \$4\$ is moved between \$3\$ and \$5\$, the result is \$12345\$, which fulfils the criteria. Note that the digits of the resulting number do not need to start at \$1\$, they just ought to be consecutive. When one is unsure about what decision they should make, they can always rely on the other's help to sort things out.

Your task is to output a truthy/falsy value depending on whether a pair of positive integers given as input is a DJMcMego pair.

  • You are guaranteed that \$a\$ and \$b\$ will have the same number of digits, always at least 4.

  • You can take the integers in any reasonable format (i.e. native integers, strings, lists of digits, etc.)

  • You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for every language wins.

Test cases

a, b -> Output

31716, 45941 -> Truthy
12354, 11111 -> Truthy
56798, 22222 -> Truthy
23564, 11111 -> Truthy
1759,  2435  -> Truthy
12345, 11111 -> Falsy
3333,  2101  -> Falsy
22354, 22222 -> Falsy
31717, 45941 -> Falsy
14325, 11111 -> Falsy
89789, 78865 -> Falsy
14954, 61713 -> Falsy
25631, 11114 -> Falsy

Or, in another format.

Mr. Xcoder

Posted 2018-02-22T23:28:33.583

Reputation: 39 774

Can we output truthy for non-DJMcMego pairs and falsy for DJMcMego pairs? Also do the truthy/falsy values need to be consistent? – dylnan – 2018-02-23T00:20:17.430

Mego can have my upvote if he writes a solution in Actually. – SIGSTACKFAULT – 2018-02-23T00:53:38.530

6

@Blacksilver I think I've beaten him to it :P

– James – 2018-02-23T01:04:26.273

@dylnan 1) They do not have to be from 1 to n, they just have to be consecutive. The test cases already cover that. 2) Swapping the truthy / falsy values is allowed by default 3) The truthy/ falsy values need not to be consistent by default. – Mr. Xcoder – 2018-02-23T06:05:26.493

2@Mr.Xcoder "Swapping the truthy / falsy values is allowed by default" Is that actually a thing? – Martin Ender – 2018-02-23T08:46:14.890

@MartinEnder I lost the count of *Returns False if the input is an X number, True otherwise* I've seen so far. Yes I believe it is allowed, otherwise I'm going to allow it for this challenge anyway – Mr. Xcoder – 2018-02-23T08:50:26.720

2@Mr.Xcoder Sure, many challenges allow it, but saying "it's allowed by default" implies to me that there's a meta post about it somewhere. – Martin Ender – 2018-02-23T08:51:05.120

@MartinEnder I do think there is a meta post about it. I'll try searching for it shortly, and if I don't find anything, I'll just ask myself. – Mr. Xcoder – 2018-02-23T08:52:01.523

Could we output one consistent value for true and a different but inconsistent value for false? For example, 1 for true and any other number for false. – Shaggy – 2018-02-23T10:18:06.883

@Shaggy Your output must satisfy the standard definition of truthy / falsy. If all other numbers except for 1 are falsy in your language (i.e. in 05AB1E, only 1 is truthy), then that is allowed. If that's not the case, I am afraid that's not allowed (that would disadvantage the existing answers). So you need to include ==1 or a variation thereof in your byte count :)

– Mr. Xcoder – 2018-02-23T10:23:20.020

MegoMayhem pairs hehehe... Me Go Mayhem. – Magic Octopus Urn – 2018-02-23T13:59:38.030

@Mr.Xcoder (1) may have been covered in the examples but it wasn't clear from the challenge specifications. I've had a challenge closed for that before. Not saying this challenge should have been closed I just think all specs should be written explicitly. – dylnan – 2018-02-23T17:11:21.040

1Maybe add 25631, 11114 as example. The differences are 14523 which confuses several of the current programs – Ton Hospel – 2018-02-27T15:27:58.230

Please add 14325, 11111 as a test case. – Dennis – 2018-06-10T20:12:28.330

What you're doing is similar to Ramanujan's "taxicab numbers": he was able to find an interesting property (the smallest number expressible as two cubes in multiple ways) in coincidental data (his taxicab number, 1729). Strangely enough, the OEIS sequence number for the taxicab numbers is 1235, which looks almost like one of these sequences :P

– Esolanging Fruit – 2018-06-11T06:05:15.763

Answers

7

C (gcc), 259 258 254 253 250 248 233 222 bytes

  • Thanks to Stan Strum for inspring a one byte golf.
  • Saved four bytes by juggling some variable initializations.
  • Saved a byte by golfing for(...;l++)b*=B[l]==-~B[l-1]; to for(...;b*=B[l]==-~B[~-l++]); (most likely relying on undefined behaviour, as it requires first evaluating B[l] followed by -~B[~-l++]).
  • Saved three five bytes.
  • Saved fifteen twenty-six bytes thanks to ceilingcat.
j,k,l,L,r,b;f(char*A,char*B){for(j=r=0;k=A[L=j];)A[j++]=-~abs(A[j]-B[j]);for(;k-L;k++)for(j=~0;L-++j;r|=!b)if(k-j)for(bcopy(B-~l,strcpy(B,A)+l,strlen(A+l)),bcopy(B+j,B-~j,L+~j),B[j]=A[k],l=b=0;B[++l];b|=B[l]+~B[~-l]);A=r;}

Try it online!

Explanation (248 byte version)

j,k,l,L,r,b;                            // global variables
f(char*A,char*B){                       // function takes two strings
 for(j=r=0;A[j];L=j)                    // loop through A, compute array length L
  A[j++]=-~abs(A[j]-B[j]);              // set every entry in A to the absolute
                                        // difference of A and B at that position
                                        /* Test out all possible movements of        *
                                         * characters and see if any one             *
                                         * results in a sorted list => DJMcMego pair */
 for(j=0;j-L;j++)                       // loop through array
  for(k=~0;L-++k;r|=!b)                 // loop through array
   if(j-k){                             // j is not equal to k
    for(l=0;A[l];B[l++]=A[l]);          // copy A to B
    for(l=j;A[l];B[~-l]=B[++l]);        // shift part of B
    for(l=L;l-k;B[-~l]=B[--l]);         // shift part of B
    B[k]=A[j];                          // insert character at correct position
    for(l=b=0;B[++l];b|=B[l]+~B[~-l]);} // test if B is sorted
 A=r;}                                  // return if there was a DJMcMego pair found

Try it online!

Jonathan Frech

Posted 2018-02-22T23:28:33.583

Reputation: 6 681

For loops that only run 1 time, you can skip j=0 as in the 41st char – Stan Strum – 2018-02-23T01:12:05.453

@StanStrum I am fairly certain that you then rely on j having the value 0 which is not necessarily the case after several calls. A function, however, should be arbitrarily often callable and still solve the challenge (relevant meta post).

– Jonathan Frech – 2018-02-23T01:18:42.000

@StanStrum You can, however, define j to be zero before the loop and thus save a byte. – Jonathan Frech – 2018-02-23T12:41:04.327

You can shave a byte with f(char*A,char*B){ -> f(A,B)char*A,*B;{. – LambdaBeta – 2018-06-11T18:54:31.447

@LambdaBeta Those two snippets are of equal length. – Jonathan Frech – 2018-06-11T18:57:03.563

@ceilingcat Thank you a lot! – Jonathan Frech – 2019-10-25T08:52:41.263

@ceilingcat Thank you. – Jonathan Frech – 2019-10-30T09:56:15.930

7

05AB1E, 18 bytes

αDæIg<ùʒD{Q}gĀ*{¥P

Try it online!

Emigna

Posted 2018-02-22T23:28:33.583

Reputation: 50 798

You should probably add a note that 1 is the only truthy number in 05AB1E; had Mr. Xcoder not informed me on this fact, I would have questioned the validity of this solution. Could you add an explanation, as well, when you have time? – Shaggy – 2018-02-23T16:30:21.130

@Shaggy You can take a look at my solution's explanation in the meantime: it's not as efficient as Enigma's but we're mostly using the same functions. – Kaldo – 2018-02-23T16:36:46.423

@Shaggy: Didn't have time to add an explanation when I posted this, buty it's done now :) – Emigna – 2018-02-23T20:19:06.663

This fails for the new test case, 14325, 11111 (falsy). – Dennis – 2018-06-11T04:38:07.603

@Dennis: Thanks, should be fixed for now (at the cost of too many bytes). Will have to try and golf this later. – Emigna – 2018-06-11T06:04:48.510

4

JavaScript (ES6), 130 bytes

Takes input as two arrays of digits in currying syntax (a)(b). Returns a boolean.

a=>b=>a.some((_,i)=>a.some((_,j)=>i-j&&!(A=a.map((v,i)=>Math.abs(v-b[i]))).some(v=>v-A[~k--]-1,A.splice(i,0,A.splice(j,1)[k=0]))))

Try it online!

Arnauld

Posted 2018-02-22T23:28:33.583

Reputation: 111 334

4

J, 27 bytes

−8 bytes thanks to FrownyFrog

1"0(-:(2-/\|\:|),1#.2>/\|)-

Try it online!

Initial solution:

J, 35 bytes

[:((1=[:*/2-/\\:~)*1=1#.0<2-/\])|@-

Try it online!

Explanation

Takes lists of digits as input

|@- finds the absolute difference between the digits of the lists

1=1#.0<2-/\] Checks if only one digits is out of its place. First I find the differences between all pairs of adjacent digits and check to see if only one of them is positive.

* Multiply the result from the above test (1 or 0) with the following test:

1=[:*/2-/\\:~ Are all digits consecutive? I sort the list down, take the differences for all pairs of adjacent digits, multiply them and check if it equals 1

Galen Ivanov

Posted 2018-02-22T23:28:33.583

Reputation: 13 815

Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T16:09:50.190

@ Ton Hospel - Yes, you are right. I'll check how ti fix it. – Galen Ivanov – 2018-02-28T18:31:21.477

I didn’t fix it, just golfed. – FrownyFrog – 2018-06-10T19:34:47.880

@FrownyFrog Thank you! I have forgotten this problem. – Galen Ivanov – 2018-06-11T06:15:24.147

4

SWI-Prolog, 157 bytes

Not very short but the problem seemed particularly well-suited for declarative predicates, variable binding and recursion, i.e., Prolog :)

n(T,Y):-s(T,Q,I,J),s(Y,W,I,J),m(Q,W).
s(T,Q,I,J):-nth0(I,T,X,R),nth0(J,Q,X,R),I\=J.
m([A,B|T],[C,D|Y]):-1 is abs(B-D)-abs(A-C),m([B|T],[D|Y]).
m([_],[_]).

Call with, e.g., n([3,1,7,1,6],[4,5,9,4,1]).

Explanation: move an element in both lists to a new position (using the SWI-Prolog nth0 built-in) and check if the difference of the new lists is consecutive.

s(T,Q,I,J)    % switch (yet unbounded) index I and J in list T, store in Q
s(Y,W,I,J)    % switch (now bounded) I and J in list Y
m(Q,W)        % check new lists
s(T,Q,I,J) :- nth0(I,T,X,R) % X (unbounded) is the I-th (unbounded) element 
                            % of list T with rest R (=prefix+postfix) 
nth0(J,Q,X,R) % the same X is the J-th element in list Q with the same rest R
I\=J          % I and J are unequal
m([A,B|T],[C,D|Y]) :-  % consider first two elements of both lists
1 is abs(B-D)-abs(A-C) % check if differences are consecutive                          
m([B|T],[D|Y])         % recursion starting with the second element
m([_],[_]).            % stop recursion at last element in the list

Marijn

Posted 2018-02-22T23:28:33.583

Reputation: 161

4

Jelly, 14 bytes

ạµṢ_JEċ@Œ¿-Ƥ%L

Try it online!

How it works

ạµṢ_JEċ@Œ¿-Ƥ%L  Main link. Arguments: A, B (digit arrays)

ạ               Take the elementwise absolute difference. Call the result R.
 µ              New chain. Argument: R
  Ṣ             Sort R.
    J           Indices; yield [1, ..., len(R)].
   _            Take the elementwise difference.
     E          Test if all differences are equal.
                The result is 1 if R consists of consecutive digits, 0 otherwise.
          -Ƥ    For all outfixes of R, generated by dropping one of its elements:
        Œ¿        Get its permutation index (1 if sorted, higher if not).
      ċ@        Count the number of times the Boolean from the left appears in the
                array to the right. If the Boolean is 1, the count represents the
                number of ways a single digit can be deleted to yield a sorted
                array. The count has to be positive for a DJMcMego pair, but less
                than the length of R, since R may not be sorted.
            %L  Take the result modulo len(R), mapping len(R) to 0.

Dennis

Posted 2018-02-22T23:28:33.583

Reputation: 196 637

3

Japt, 18 bytes

Been debating whether I should post this or not for a couple of hours. Came up with it quickly late last night but didn't have time to test it properly (and I thought it might be too long!). Oliver has since posted a similar solution (which was, when this one was originally posted, invalid) so if he, or the community, feels this is too similar, I'll happily delete it.

Takes input as 2 digit arrays, outputs 0 for true or any other number for false.

íaV
ä> x*Un än × É

Try it or check all test cases


Explanation

                   :Implicit input of digit arrays U and V               :[3,1,7,1,6],[4,5,9,4,1]
í V                :Interleave V with U                                  :[[3,4],[1,5],[7,9],[1,4],[6,1]]
 a                 :Get the absolute difference of each pair             :[1,4,2,3,5]
\n                 :Assign that new array to variable U
ä>                 :Is each element greater than the next?               :[false,true,false,false]
     Un            :Sort U                                               :[1,2,3,4,5]
        än         :Get the deltas                                       :[1,1,1,1]
           ×       :Reduce by multiplication                             :1
    *              :Multiply each element in the boolean array by that   :[0,1,0,0]
   x               :Reduce by addition                                   :1
             É     :Subtract 1                                           :0

And, to walk through that process on a few more test cases:

---------------------------------------------------------------
| U   | [2,3,5,6,4] | [1,2,3,4,5] | [3,1,7,1,7] | [1,4,9,5,4] |
| V   | [1,1,1,1,1] | [1,1,1,1,1] | [4,5,9,4,1] | [6,1,7,1,3] |
|-----|-------------|-------------|-------------|-------------|
| íaV | [1,2,4,5,3] | [0,1,2,3,4] | [1,4,2,3,6] | [5,3,2,4,1] |
|-----|-------------|-------------|-------------|-------------|
| ä>  | [F,F,F,T]   | [F,F,F,F]   | [F,T,F,F]   | [T,T,F,T]   |
|-----|-------------|-------------|-------------|-------------|
| Un  | [1,2,3,4,5] | [0,1,2,3,4] | [1,2,3,4,6] | [1,2,3,4,5] |
| än  | [1,1,1,1]   | [1,1,1,1]   | [1,1,1,2]   | [1,1,1,1]   |
| ×   | 1           | 1           | 2           | 1           |
|-----|-------------|-------------|-------------|-------------|
| *   | [0,0,0,1]   | [0,0,0,0]   | [0,2,0,0]   | [1,1,0,1]   |
| x   | 1           | 0           | 2           | 3           |
| É   | 0           | -1          | 1           | 2           |
---------------------------------------------------------------

Shaggy

Posted 2018-02-22T23:28:33.583

Reputation: 24 623

2Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T16:08:32.897

2

Perl, 121 118 bytes

($a,$b)=map[split//],@ARGV;
$s+=$l>$_,$l=$_ for@c=map abs($$a[$i]-$$b[$i++]),@$a;
@c=sort@c;
say$s==1&&$c[-1]-$c[0]==$#$a

Test in bash:

function golf {
   perl -E'($a,$b)=map[split//],@ARGV;$s+=$l>$_,$l=$_ for@c=map abs($$a[$i]-$$b[$i++]),@$a;@c=sort@c;say$s==1&&$c[-1]-$c[0]==$#$a' $1 $2
}
golf 31716 45941       #says 1, true
golf 12354 11111       #says 1, true
golf 56798 22222       #says 1, true
golf 46798 22222       #says nothing, false
golf 22354 22222       #says nothing, false
golf 1759 2435         #says 1, true
golf 12345 11111       #says nothing, false
golf 89789 78865       #says nothing, false
golf 14954 61713       #says nothing, false

Kjetil S.

Posted 2018-02-22T23:28:33.583

Reputation: 1 049

Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T16:13:45.283

2

Java 8, 245 227 223 194 188 Bytes

Thanks to Kevin for saving ~29 bytes

Thanks to Kevin again for another 6 bytes

 z->{int l=z.length/2,c[]=new int[l],i=0,j=0;for(;i<l;)c[i]=Math.abs(z[i]-z[i+++l]);java.util.Arrays.sort(z=c.clone());for(i=0;i<l-1;j+=z[i]-z[i-1]!=1?1:0)j+=c[i]-c[++i]>0?1:0;return j==1;}

Followed the same pattern Galen came up with for his J answer.

Try it online!

DevelopingDeveloper

Posted 2018-02-22T23:28:33.583

Reputation: 1 415

1

You can golf a few more things like this (194 bytes): z->{int l=z.length/2,c[]=new int[l],i=0,j=0,d[];for(;i<l;)c[i]=Math.abs(z[i]-z[i+++l]);java.util.Arrays.sort(d=c.clone());for(i=0;i<l-1;j+=d[i+1]-d[i++]!=1?1:0)j+=c[i]-c[i+1]>0?1:0;return j==1;} I combined the int and int[] at the start; used l=z.length/2 once and reuse l instead of 4 times; changed the if(...)j++ to j+=...?1:0 so they can be placed inside the loops and the brackets and second semi-colon can be removed; removed the i++ and do ++ directly on the last i in the loop; etc.

– Kevin Cruijssen – 2018-02-23T16:35:35.393

1188 bytes: z->{int l=z.length/2,c[]=new int[l],i=0,j=0;for(;i<l;)c[i]=Math.abs(z[i]-z[i+++l]);java.util.Arrays.sort(z=c.clone());for(i=0;i<l-1;j+=z[i]-z[i-1]!=1?1:0)j+=c[i]-c[++i]>0?1:0;return j==1;}. Removed d[] and re-used the input z you no longer need; Changed j+=c[i]-c[i+1]?1:0; and j+=d[i+1]-d[i++]!=1?1:0 to j+=c[i]-c[++i]?1:0; and j+=z[i]-z[i-1]?1:0. +1 from me, though. Nice answer! :) – Kevin Cruijssen – 2018-02-23T16:42:50.903

1Thanks @Kevin, Everytime you commented I had only found one or two of the many ways you had already golfed it down :P You are much faster than me! Thanks so much for the help! – DevelopingDeveloper – 2018-02-23T16:47:44.903

2

Hehe :) It all comes with experience, I guess. I'm already golfing in Java for almost two years now. The more you do it, the easier you see these kind of things. And even my answers get golfed down by OlivierGrégoire, Nevay, and some others all the time as well. Oh, you've probably already seen them, but Tips for Golfing in Java and Tips for golfing in <all languages> are pretty interesting to read through.

– Kevin Cruijssen – 2018-02-23T18:31:33.313

2Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T16:06:26.050

Suggest c[i]>c[++i] instead of c[i]-c[++i]>0 – ceilingcat – 2019-10-24T03:03:26.793

2

Retina, 102 bytes

+`(.)(.*¶)(.)(.*)
$2$4;$1,$3
\d
*
(_*),\1
_
L$w`(;_+\b)(.*)(;_+\b)
$%`$2$3$1$%"$3$1$2$'
m`(^;_+|\1_)+$

Try it online! Link includes test cases. Returns the number of ways digits can be moved to achieve an ascending sequence, which is 2 for a straight swap since either digit can be moved past the other in that case. Explanation:

+`(.)(.*¶)(.)(.*)
$2$4;$1,$3

Pair up the digits.

\d
*

Convert to unary.

(_*),\1
_

Take the difference, but then add 1 because working with zero in Retina is hard™.

L$w`(;_+\b)(.*)(;_+\b)
$%`$2$3$1$%"$3$1$2$'

List all the sequences of digits obtained by moving exactly one digit.

m`(^;_+|\1_)+$

Check for consecutive digits.

Neil

Posted 2018-02-22T23:28:33.583

Reputation: 95 035

2

Ruby, 124 113 99 95 bytes

->l,b,d=-1{m=l.map!{|i|(i-b[d+=1]).abs}.sort;l.any?{|*i|m-i==l-i}&&m!=l&&/#{m*''}/=~[*0..9]*''}

Try it online!

Asone Tuhid

Posted 2018-02-22T23:28:33.583

Reputation: 1 944

Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T15:37:02.263

@TonHospel fixed it, thanks – Asone Tuhid – 2018-02-27T17:41:47.340

Awesome rebound. Have a +1 :-) – Ton Hospel – 2018-02-27T19:40:05.237

2

Perl 5, -F 87 84 83 bytes

Old style counting: 86 bytes (+3 for -F)

Give he numbers as 2 lines on STDIN, the last line without a trailing newline.

Prints the difference string up to 2 times for true, nothing for false

The long A0123456789 string is really annoying.

#!/usr/bin/perl -F
$_=<>;s%.%abs$&-$F[pos]%eg;s%%"'$`$''=~s:|:A0123456789=~/\$`$&\$'/>//&&say:reg"%eeg

Try it online!

I'm usure if this 79 counts as valid:

$_=<>;s%.%abs$&-$F[pos]%eg;s,,$a=$&;"$`$'"=~s:|:A0123456789=~/$`$a$'/%//:reg,eg

It crashes for a valid pair, so you get a non zero exit code. It does nothing if not a pair and exits with exit code 0. I know returning the result via exit code is allowed, but are they properly truthy and falsy or in fact reversed (for the shell 0 is true) ?

Ton Hospel

Posted 2018-02-22T23:28:33.583

Reputation: 14 114

1

Pyt, 20 18 bytes

ą←ą-ÅĐʁ>Ʃ1=⇹ş₋Π1=∧

Try it online!

Explanation:

       Implicitly get the first number
ą      Convert to list of digits
←      Get the second number
ą      Convert to list of digits
-Å     Take the absolute value of the differences of the lists element-wise
Đ      Duplicate the list of differences
ʁ>     Reduce by greater than
Ʃ1=    Is the sum of that array equal to 1
⇹      Swap the top two items on the stack
ş      Sort the top of the stack ascending
₋      Reduce by subtraction (from the right)
Π1=    Is the product of the array equal to 1
∧      bitwise-AND (in this case, also logical AND) the top two items on the stack
       Implicit print

mudkip201

Posted 2018-02-22T23:28:33.583

Reputation: 833

2Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T15:50:39.397

1

Add++, 105 bytes

D,w,@~,Ñ_€|BSVcGbU1b]2b]+º=
D,k,@,BPB*
L,BcB_€|B]dBkbUBSVcGbU£>sVcGB]VBKB#BKBcB_0º>b]GBK{w}b]++b*1=BK{k}*

Try it online!

Defines a lambda function that takes two lists of digits as input. Outputs a positive integer divisible by 241 for DJMcMego pairs, 0 otherwise.

1: If this is too restrictive, it also outputs a positive integer for DJMcMego pairs, and 0 otherwise

How it works

Here we perform 4 checks to determine if the input is valid. The parts of the code that do those checks are

BcB_€|B]dBkbUBSVcGbU£>sVcGB]V

Here, we take the list of absolute digit differences, then count the number of overlapping pairs which are sorted in descending order. Every DJMcMego pair produces a result of 1, but they are not unique in this aspect. We also store the inputs' absolute digit differences, to save bytes later. This array will be referred to as A throughout.

BKB#BKBcB_0º>b]

Next, we take the elementwise differences between A and A sorted, before asserting that at least one of those differences is negative.

D,w,@~,Ñ_€|BSVcGbU1b]2b]+º=
GBK{w}b]

Third, we check if the pair [1, 2] is contained in the forward increments of A. This checks that, in at least one position of A, it is sorted, which is a criterion for DJMcMego pairs.

D,k,@,BPB*
BK{k}

As our last check, we assert that the second element of A is never 0. In order for a pair, X and Y, to be a DJMcMego pair, we can assume that their A is always unique, as an array with duplicates in it can never be made consecutive by swapping a single value with another.

Finally, we check that the first three of these tests returned 1, and that the fourth returned a value x such that x ≠ 0

A step for step walk through of the code is as follows

D,w,		; Define a function w;
		;   This takes an array of integers
		;   Returns whether the pair [1, 2] appears in the absolute forward differences
		;
	@	; Take one argument
	~,	; Splat that argument to the stack
		;   Example argument:		[1 4 2 3 5]
		;
	Ñ_	; Increments;		STACK = [3 -2 1 2]
	€|	; Magnitudes;		STACK = [3 2 1 2]
	BSVcGbU	; Overlapping pairs;	STACK = [[3 2] [2 1] [1 2]]
	1b]2b]+	; Push [1 2];		STACK = [[3 2] [2 1] [1 2] [1 2]]
	º=	; Any equal [1 2];	STACK = [1]

; ============= ;

D,k,		; Define a function k;
		;   This function takes an array of integers
		;   Returns whether the second element is 0;
		;
	@,	; Take one argument and push to the stack
		;   Example argument:		[[1 4 2 3 5]]
		;
	BP	; Behead;		STACK = [[4 2 3 5]] 
	B*	; Product;		STACK = [120]
		;
		; In DJMcMego pairs, A may begin with a 0
		; For example, 12354 and 11111, so we need to remove the first element
		; Taking the product yields 0 if any element is 0
		; However, in order to be a DJMcMego pair, two digits at the same index
		;   cannot be the same, otherwise their digit-wise difference will be 0

; ============= ;

L,		; Define a lambda function
		;
		; This lambda function takes two arrays of digits as input
		; Returns an integer to determine if those digits represent a DJMcMego pair
		;
		; A lambda function is shorter to define than a normal function
		; However, when called inside functions with the ] command,
		;   they consume the entire stack as arguments, meaning that using functions
		;   allows us to preserve important values
		;
		; Example arguments:		[[3 1 7 1 6] [4 5 9 4 1]]
		;
		; First check:
		;
	BcB_	; Digit differences;	STACK = [-1 -4 -2 -3 5]
	€|	; Magnitudes;		STACK = [1 4 2 3 5]
	B]dBkbU	; Save a copy, A	STACK = [1 4 2 3 5]			A: [1 4 2 3 5]
	BSVcGbU	; Overlapping pairs;	STACK = [[1 4] [4 2] [2 3] [3 5]]
	£>	; Sorted descendingly?	STACK = [0 1 0 0]
	sVcG	; How many?		STACK = [1]
	B]V	; Save a copy;		STACK = []				Register: [1]
		;
		; Second check:
		;
	BK	; Retrieve A;		STACK = [[1 4 2 3 5]]
	B#	; Sort;			STACK = [[1 2 3 4 5]]
	BK	; Retrieve A;		STACK = [[1 2 3 4 5] [1 4 2 3 5]]
	BcB_	; Element differences;	STACK = [0 -2 1 1 0]
	0º>b]	; Any negatives;	STACk = [[1]]
		;
		; Third and fourth checks:
		;
	G	; Retrieve register;	STACK = [[1] [1]]
	BK	; Retreive A;		STACK = [[1] [1] [1 4 2 3 5]]
	{w}b]	; Run w;		STACK = [[1] [1] [1]]
	++	; Concatenate;		STACK = [[1 1 1]]
	b*1=	; Product = 1;		STACK = [1]
	BK{k}	; Run k;		STACK = [1 120]
	*	; Multiply;		STACK = [120]

		; To force output as 1 and 0 values,
		;   append a ? to the end, to output the sign (forces boolean conversion)

user79861

Posted 2018-02-22T23:28:33.583

Reputation:

1

R, 110 106 84 bytes

function(x,y,z=abs(x-y),w=z-min(z)+1)adist(p(1:max(w)),p(w),c("s"=9))==2
p=intToUtf8

Try it online!

@JayCe with a ridiculous 22 byte save!

The workhorse here is adist, which gives a "generalized Levenshtein edit distance" between two strings. By default the distance is the count of the minimal number of insertions, deletions, and substitutions required to transform one string into another. But adist allows you to weight things how you like - so I've weighted each substitution to add 9 to the distance rather than 1. This effectively forces the algorithm to look for insertions and deletions only.

This code accepts vectors of integers, computes the absolute elementwise differences, and translates the result to begin at 1, calling it w.

Then the custom weighted Levenshtein distance is computed between w pasted together to make a string and the string "1234..." (actually utf-8 "\001\002\003\004..." but adist doesn't care.) with the same number of characters as w.

The only way the string can have exactly one digit out of place is if you make one deletion and one insertion, giving a distance of 2.

ngm

Posted 2018-02-22T23:28:33.583

Reputation: 3 974

This fails for the new test case, 14325, 11111 (falsy). – Dennis – 2018-06-11T18:06:42.607

I think paste0 can be just paste since there's only one input. – Giuseppe – 2018-06-11T18:59:58.193

p=intToUtf8 ? – JayCe – 2018-06-11T21:46:15.223

I thought I had a golf replacing w=z-min(z)+1)adist(p(1:max(w)) with w=z-min(z))adist(p(0:max(w)) but it doesn't work since intToUtf8(\000) is NULL. – JayCe – 2018-06-13T15:02:44.637

This is an interesting solution that deserves more upvotes.... I think predicting the upvotes in Codegolf is the next frontier for AI :) – JayCe – 2018-06-13T15:08:30.137

@JayCe everyone's just jealous because their languages don't have approximate string matching built-ins. – ngm – 2018-06-13T17:26:37.207

Do you think calculating Levenshtein's distance would make a good codegolf question? (with a 5-byte answer in R hehe) - nvmd I checked there are plenty of such questions !! – JayCe – 2018-06-13T19:26:09.677

@JayCe it seems like https://codegolf.stackexchange.com/questions/67474/levenshtein-distance is still awaiting its R solution!

– ngm – 2018-06-13T21:01:25.687

True! it's not allowing built-ins so I will have to think harder :)...it will involve utf8ToInt for sure :D – JayCe – 2018-06-13T21:04:52.450

0

Python 2, 116 119 106 bytes

Thanks Mr. Xcoder for the 116->84 cut, but I found I have missed the "consecutive number" criteria, so 26 bytes are added for that purpose :(

After that, -1 more Thanks Mr. Xcoder, and -13 Thanks ovs

def m(a,b):l=[abs(x-y)for x,y in zip(a,b)];print sum(e>f for e,f in zip(l,l[1:]))==1==len(l)-max(l)+min(l)

Try it online!

That one below fixes 25634 - 11111 problem but with double length (211 206 145 142B)... Golfing...

def m(a,b):l=[abs(x-y)for x,y in zip(a,b)];r=[l[i]-i-min(l)for i in range(len(l))];print(sum(r)==0)&(len([x for x in r if abs(x)>1])<2)&any(r)

Try it online!

And congratulations to new moderators :)

Explanation:

l=[abs(x-y)for x,y in zip(a,b)]

Generates the list of absolute differences of the digits.

r=[l[i]-i-min(l)for i in range(len(l))]

Calculates the offset from the proper position.

sum(r)==0

If the sequence is not continuous, then offset sum will "usually" not be 0. But even if it equals 0, the next ones will block them out.

len([x for x in r if abs(x)>1])<2

Only 0 or 1 item will have absolute offset larger than 1 (the one with wrong position, and 0 is in the case like 1,2,3,5,4)

any(r)

Blocks the case when the numbers are all in correct positions

Shieru Asakoto

Posted 2018-02-22T23:28:33.583

Reputation: 4 445

It seems to fail for m([3,3,3,3],[2,1,0,1]) (returns True) Tio

– Asone Tuhid – 2018-02-26T00:01:44.220

@AsoneTuhid I have fixed the problem based on his golf because when I submitted the answer and he golfed my answer I forgot that case. – Shieru Asakoto – 2018-02-26T00:32:57.363

2Fails for 25634 11111 (as do many other submissions) – Ton Hospel – 2018-02-27T15:38:11.020

@TonHospel Oh, that's tricky. I'm thinking of methods to fix it but seems it will add quite a bunch of bytes to the answer – Shieru Asakoto – 2018-02-27T23:57:03.557

0

JavaScript, 137 136 135 134 132 123 bytes

Takes input as two arrays of digits in currying syntax, outputs 0 for true and any other number for false.

a=>b=>(c=a.map((x,y)=>(x-=b[y])<0?-x:x)).map(x=>t+=x>c[++j]&(d=[...c].sort()).slice(i=0,-1).every(x=>d[++i]-x&1),t=j=0)|t^1

Test Cases

f=
a=>b=>(c=a.map((x,y)=>(x-=b[y])<0?-x:x)).map(x=>t+=x>c[++j]&(d=[...c].sort()).slice(i=0,-1).every(x=>d[++i]-x&1),t=j=0)|t^1
o.innerText=`${l=`-`.repeat(21)}\n|   #1  |   #2  | f |${m=`\n|${`|`.padStart(8,`-`).repeat(2)}---|\n`}${[[31716,45941],[12354,11111],[56798,22222],[23564,11111],[1759,2435],[12345,11111],[3333,2101],[22354,22222],[31717,45941],[89789,78865],[14954,61713]].map(([x,y])=>`| ${JSON.stringify(x).padEnd(6)}| ${JSON.stringify(y).padEnd(6)}| ${f([...``+x])([...``+y])} |`).join(m)}\n`+l
<pre id=o></pre>

Shaggy

Posted 2018-02-22T23:28:33.583

Reputation: 24 623

1[...u].sort(y=0) is invalid javascript, the argument for the sort must be a function – edc65 – 2018-02-23T15:01:48.993

@edc65, that's long since been edited out. Invalid as it may be, though, it worked! ;) – Shaggy – 2018-02-23T15:08:07.010

2"Fails for 25634 11111 (as do many other submissions)" - Ton Hospel – Asone Tuhid – 2018-02-27T18:55:26.000

0

Haskell, 182 163 162 132 bytes

(#)=zipWith(-)
a&b|s<-abs<$>a#b=or[all(==1)$tail a#a|(x,h:y)<-p s,(q,r)<-p$x++y,a<-[q++h:r],a/=s]
p l=[splitAt k l|k<-[0..length l]]

Takes input as a list of digits. Helper function p that gives all possible ways to split a list into two parts is used to take an element out and again to insert it elsewhere.

Try it online!

Angs

Posted 2018-02-22T23:28:33.583

Reputation: 4 825