14
\$\begingroup\$

TASK

print integers n, where 12 <= n <= 123456789, and all pairs of consecutive digits in n have the same positive difference between them (e.g. 2468 but not 2469).

NO INPUT.

Output:

12
13
14
15
16
17
18
19
23
24
25
26
27
28
29
34
35
36
37
38
39
45
46
47
48
49
56
57
58
59
67
68
69
78
79
89
123
135
147
159
234
246
258
345
357
369
456
468
567
579
678
789
1234
1357
2345
2468
3456
3579
4567
5678
6789
12345
13579
23456
34567
45678
56789
123456
234567
345678
456789
1234567
2345678
3456789
12345678
23456789
123456789

Rules

  1. Standard loopholes apply.
  2. no input

shortest code wins.

Credits anarchy golf

\$\endgroup\$
  • 8
    \$\begingroup\$ This problem is from anarchy golf. You should give it credit (even if you were the one who submitted it) \$\endgroup\$ – xnor Oct 17 '17 at 18:18
  • 5
    \$\begingroup\$ Do they have to be printed in order? \$\endgroup\$ – H.PWiz Oct 17 '17 at 18:22
  • 11
    \$\begingroup\$ I submitted this problem on anagol :) \$\endgroup\$ – Lynn Oct 17 '17 at 20:46
  • 2
    \$\begingroup\$ Why isn’t every integer 0≤n<100 on this list? \$\endgroup\$ – DonielF Oct 17 '17 at 21:26
  • 3
    \$\begingroup\$ @DonielF Because the integer has to be larger than or equal to 12, and because the forward differences must be positive. \$\endgroup\$ – Dennis Oct 17 '17 at 21:29

25 Answers 25

11
\$\begingroup\$

Jelly, 12 11 bytes

9œcḊẎIE$ÐfY

Try it online!

How it works

9œcḊẎIE$ÐfY  Main link. No arguments.

9            Set the argument and return value to 9.
   Ḋ         Dequeue; yield [2, ..., 9].
 œc          Take all k-combinations of [1, ..., 9], for each k in [2, ..., 9].
    Ẏ        Concatenate the arrays of k-combinations.
        Ðf   Filter the result by the link to the left.
     IE$         Compute the increments (I) of the combination / digit list and
                 tests if all are equal (E).
          Y  Join the results, separating by linefeeds.
\$\endgroup\$
  • \$\begingroup\$ ìà Find fastest route between two points using Dykstra's Algorithm \$\endgroup\$ – Neil Oct 18 '17 at 13:51
7
\$\begingroup\$

Python 2, 81 bytes

k=71
exec"k+=1;r=range(k/8%9+1,10,k%8+1)\nif r[k/72:]:print`r`[1:k/24+2:3]\n"*576

Try it online!

My solution from anarchy golf. The idea is to iterate over all possible triples of length, start value, and step, which gives sorted outputs. The triple is encoded as a value r from 72 to 647, and the components are extracted as k/72, k/8%9, and k%8. Starting k high enough avoids single-digit numbers from being output.

xsot saved two bytes off this by replacing the range with a hardcoded string of digits '123456789'.

This was written under the constraint of a two second runtime limit. A slower strategy that filters numbers rather than generating these may be shorter.

\$\endgroup\$
  • 1
    \$\begingroup\$ Fun fact: this problem is actually “designed for” the anarchy golf runtime limit, which is why I didn’t submit it to PPCG. I wanted to disqualify submissions looping from 1 to 123456789, instead forcing answers to come up with some clever way to generate the right numbers in the right (sorted) order. \$\endgroup\$ – Lynn Oct 17 '17 at 20:53
6
\$\begingroup\$

C, 166 152 Bytes

p,l,d,i=11;main(){for(char s[10];i<=1e9;){sprintf(s,"%d",++i);p=0;for(l=strlen(s);--l>0;){d=s[l]-s[l-1];if(!p)p=d;if(p^d|d<1)break;p=d;}if(!l)puts(s);}}

6 bytes saved thanks to @KevinCruijssen!

8 bytes saved thanks to @JonathanFrech!

Try it online

The fully formatted version of the above code can be seen below.

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

int main( void )
{
int prev_diff, diff, len;
int num = 11;
char str[10];

while(num<123456789)
    {
    prev_diff = 0;
    sprintf(str,"%d",++num);
    len = strlen(str)-1;
    for( ; len > 0; len-- )
        {
        diff = str[len] - str[len-1];
        if( prev_diff == 0 )
            {
            prev_diff = diff;
            }
        if( prev_diff != diff || diff < 1 )
            {
            break;
            }
        prev_diff = diff;
        }
    if ( len == 0 )
        {
        puts(str);
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ Unless I'm missing something, shouldn't while(i<123456789) be while(i<=123456789) instead according to the challenge range? Also, you can golf it by 6 bytes: p,l,d,i=11;main(){for(char s[10];i<=123456789;){sprintf(s,"%d",++i);p=0;for(l=strlen(s);--l>0;){d=s[l]-s[l-1];if(p<1)p=d;if(p^d|d<1)break;p=d;}if(l<1)puts(s);}} \$\endgroup\$ – Kevin Cruijssen Oct 18 '17 at 7:13
  • \$\begingroup\$ @KevinCruijssen I would agree, although one can most likely keep using the one-byte comparison by choosing a higher value; i<1e9. \$\endgroup\$ – Jonathan Frech Oct 18 '17 at 7:22
  • \$\begingroup\$ @KevinCruijssen Also, if I am not mistaking, l<1 can be golfed to !l, as l never reaches a negative value. \$\endgroup\$ – Jonathan Frech Oct 18 '17 at 7:28
  • \$\begingroup\$ @JonathanFrech Good point about the i<1e9. And !l when l is always >=0 sounds reasonable for C I guess (I've never programmed in C myself). \$\endgroup\$ – Kevin Cruijssen Oct 18 '17 at 8:19
  • \$\begingroup\$ @KevinCruijssen "i" is incremented in sprintf(), allowing us to reach allowing us to enter the loop when i == 123456788, and leave it with 123456789. I'll add those multi-purpose for loops and (l ==0) -> (l < 1) optimizations in, thanks :) \$\endgroup\$ – Jacobinski Oct 18 '17 at 18:31
5
\$\begingroup\$

Jelly, 14, 13 bytes

DIµEȧ>0Ȧ
Ç77#

Try it online!

One byte saved thanks to @MrXcoder!

This is extremely inefficient, so it'll time out on TIO, but if it ever finishes, it will produce the correct output. You can try it with smaller numbers here: Try it online!

Explanation:

            # Helper link:
            #
D           # The Digits of 'n'
 I          # The increments (deltas, differences) between digits
  µ         # Give that array as an argument to the rest of this link:
   E        # Are all elements equal?
    ȧ       #   AND
     >0     # Are all elements greater then 0?
       Ȧ    # And is there at least one element?
            # (in the differences, so that numbers < 10 are false)
            #
            # Main link:
            #
 77#        # Return the first 77 'n's for which
Ç           #   The helper link is truthy
\$\endgroup\$
  • 1
    \$\begingroup\$ Ugh. Beat me to it. +1 \$\endgroup\$ – caird coinheringaahing Oct 17 '17 at 17:51
  • \$\begingroup\$ You do not need the $ at the end of your helper link. \$\endgroup\$ – Mr. Xcoder Oct 17 '17 at 17:54
  • \$\begingroup\$ A way clearer way to do this is DIµ>0ȦȧE¶Ç77# \$\endgroup\$ – Erik the Outgolfer Oct 17 '17 at 18:13
4
\$\begingroup\$

05AB1E, 23 bytes

•7=›ζ•FNS¥DËs0›PN11›&&–

Try it online!


Replace •7=›ζ• with 7000 to have it finish on TIO, or just hit the "terminate" button before it times out, resulting in the numbers printed up until that point.

\$\endgroup\$
  • \$\begingroup\$ Try using this: žh \$\endgroup\$ – Okx Oct 17 '17 at 18:18
  • \$\begingroup\$ @Okx I don't think that would work, it's not just a substring of '0123456789', 1357 for example is also a valid number you need to output. \$\endgroup\$ – Erik the Outgolfer Oct 17 '17 at 18:20
  • \$\begingroup\$ @EriktheOutgolfer I meant replacing •7=›ζ• \$\endgroup\$ – Okx Oct 17 '17 at 18:22
  • \$\begingroup\$ @Okx that's what I had originally, but it causes some weird stuff (?). No idea why, so I ended up with this, which worked consistently. \$\endgroup\$ – Magic Octopus Urn Oct 17 '17 at 18:30
  • \$\begingroup\$ @MagicOctopusUrn Why don't you try removing the 0 at the start? \$\endgroup\$ – Okx Oct 17 '17 at 18:34
4
\$\begingroup\$

Mathematica, 79 bytes

Select[Range@123456789,Min[s=Union@Differences@IntegerDigits@#]>0&&Tr[1^s]==1&]

Try it online! with a lower number because it is very slow

here is another approach that constructs all the numbers in 1sec

Mathematica, 123 bytes

Union[FromDigits/@(F=Flatten)[Table[Partition[#,i,1],{i,2,9}]&/@Select[F[Table[Range[j,9,k],{j,9},{k,9}],1],Tr[1^#]>1&],2]]   


Try it online! all numbers in a sec

\$\endgroup\$
4
\$\begingroup\$

Husk, 14 13 bytes

ÖifȯεuẊ≠Ṗ…"19

Prints newline-separated numbers to STDOUT. Try it online!

-1 byte due to inspiration from H.PWiz.

Explanation

ÖifȯεuẊ≠Ṗ…"19
         …"19  The string "19" rangified: "123456789"
        Ṗ      Powerset: ["","1","2","12","3",...,"123456789"]
  fȯ           Filter by function: (input is sublist, say "2469")
      Ẋ≠        Consecutive codepoint differences: [2,2,3]
     u          Remove duplicates: [2,3]
    ε           Is it a one-element list? No, so "2469" is dropped.
Öi             Sort the result by integer value, implicitly print separated by newlines.
\$\endgroup\$
4
\$\begingroup\$

Wolfram Language (Mathematica), 76 bytes

Differences@IntegerDigits@#~MatchQ~{a_?Positive..}&&Print@#&~Array~123456789

Try it online!

\$\endgroup\$
3
\$\begingroup\$

APL (Dyalog), 37 28 bytes

⍪x/⍨{1=≢∪2-/⍎¨⍕⍵}¨x←11+⍳1E9

Try it online! (with shorter range, due to time-out)

How?

x←11+⍳123456789 - 11, 12... 1e9 into x

¨ - for each

    ⍎¨⍕⍵ - break into digits

    2-/ - get differences list

     - get unique elements

    1=≢ - length == 1?

x/⍨ - use this as a mask on the range created

- and columnify

\$\endgroup\$
3
\$\begingroup\$

Husk, 14 bytes

ÖifoEẊ≠ftṖ…"19

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I stole your . :P I had forgotten it works for characters too \$\endgroup\$ – Zgarb Oct 17 '17 at 18:33
3
\$\begingroup\$

Batch, 210 200 bytes

No optimizations, so very slow - takes about 25 seconds until 12345, so for the complete output you'd have to wait about 3 days.

@set z=@set/a
%z%c=12
:a
@echo %c%
:c
%z%c+=1&if %c%==123456790 exit/b
%z%n=c
%z%d=n%%10-n/10%%10
@if %d% leq 0 goto c
:d
%z%n=n/10
@if %n% leq 9 goto a
%z%e=n%%10-n/10%%10
@if %e%==%d% goto d
@goto c
\$\endgroup\$
3
\$\begingroup\$

Java 8, 169 168 145 bytes

v->{byte[]a;for(int i=9,d,l;++i<1e9;System.out.print(l<1?i+"\n":""))for(a=(i+"").getBytes(),d=0,l=a.length;--l>0&&d*(d^(d=a[l]-a[l-1]))<1&d>0;);}

Port of @Jacobinski C answer (after I golfed it a bit).
-23 bytes thanks to @Nevay.

Explanation:

Try it here. (It's a bit too slow near the end, so doesn't print the final number on TIO. It prints the final number locally in about 20 seconds, though.)

v->{                         // Method with empty unused parameter and no return-type
  byte[]a;                   //  Byte-array
  for(int i=9,               //  Index integer, starting at 9
          d,                 //  Difference-integer
          l;                 //  Length integer
      ++i<1e9;               //  Loop (1) from 10 to 1,000,000,000 (exclusive)
      System.out.print(      //    After every iteration: print:
        l<1?                 //     If `l` is 0:
         i+"\n"              //      The current integer + a new-line
        :                    //     Else:
         ""))                //      Nothing
    for(a=(i+"").getBytes(), //   Convert the current item as String to a byte-array
        d=0,                 //   Reset the previous integer to 0
        l=a.length;          //   Set `l` to the length of the byte-array
        --l>0                //   Inner loop (2) from `l-1` down to 0 (exclusive)
        &&d*(d^(d=a[l]-a[l-1]))<1
                             //    As long as the previous difference is either 0
                             //    or the current diff is not equal to the previous diff
        &d>0;                //    and the current diff is larger than 0
    );                       //   End of inner loop (2)
                             //  End of loop (1) (implicit / single-line body)
}                            // End of method
\$\endgroup\$
  • 1
    \$\begingroup\$ 145 bytes: v->{byte[]a;for(int i=9,p,l;++i<1e9;System.out.print(l<1?i+"\n":""))for(a=(i+"").getBytes(),p=0,l=a.length;--l>0&&p*(p^(p=a[l]-a[l-1]))<1&p>0;);} \$\endgroup\$ – Nevay Oct 18 '17 at 22:43
  • \$\begingroup\$ @Nevay I knew it should be able to drop that break somehow and add it to the for-loop check, but this I wouldn't have come up with myself. ;) Thanks! \$\endgroup\$ – Kevin Cruijssen Oct 19 '17 at 7:23
2
\$\begingroup\$

05AB1E, 14 bytes

TžhŸʒS¥D0›PsË&

Try it online!

\$\endgroup\$
  • \$\begingroup\$ That's what I originally had, except I had 12žhŸʒS¥D0›PsË&, I can't get it to run locally. Can you get this to actually execute? \$\endgroup\$ – Magic Octopus Urn Oct 17 '17 at 18:43
  • \$\begingroup\$ @MagicOctopusUrn If I try replacing the numbers before Ÿ, it works fine \$\endgroup\$ – Okx Oct 17 '17 at 19:03
  • \$\begingroup\$ I got my other one to run locally without replacing numbers, but this I still can't. Idk why, I just really want to know what's so different. \$\endgroup\$ – Magic Octopus Urn Oct 18 '17 at 13:27
2
\$\begingroup\$

Python 2, 103 97 95 bytes

-2 bytes thanks to @JonathanFrech

n=11
while n<1e9:
 n+=1;Q=`n`[1:]
 if`n`<Q>1==len({int(a)-int(b)for a,b in zip(`n`,Q)}):print n

Try it online!

\$\endgroup\$
  • \$\begingroup\$ 108 bytes or a 106 bytes that runs out of memory, but can be tested with lower numbers \$\endgroup\$ – Rod Oct 17 '17 at 17:57
  • \$\begingroup\$ 95 bytes; using a variable for the repeated `n`[1:]. \$\endgroup\$ – Jonathan Frech Oct 17 '17 at 20:27
2
\$\begingroup\$

Python 2, 76 75 bytes

n=9
while n<2e8:
 n+=1
 if`n`in`range(n%10,0,~n%100%11-11)`[-2::-3]:print n

Takes about 3 minutes locally.

Try it online! (modified to print all numbers but the last)

\$\endgroup\$
2
\$\begingroup\$

JavaScript (Firefox 30-57), 105 bytes

document.write(`<pre>`+(

_=>[for(x of s=`123456789`)for(y of s)for(z of s)if(x*z<10-y)s.replace(/./g,c=>c<y|(c-y)%z|c-y>x*z?``:c)]

)().join`\n`+`</pre>`);

Loops over lengths from 2 to 10 (x is the index of the last character and therefore 1 less than the length), starting digits from 1 to 9 and step from 1 to 9, then filters on the end digit being less than 10 and if so generates the result by filtering out digits from the digit string.

\$\endgroup\$
  • \$\begingroup\$ "Run code snippet" leads to an error: Uncaught SyntaxError: Unexpected token for \$\endgroup\$ – schnaader Oct 18 '17 at 12:02
  • 2
    \$\begingroup\$ @schnaader Are you running it in Firefox 30+? This answer uses the non-standard array comprehension syntax which only Firefox supports. \$\endgroup\$ – Birjolaxew Oct 18 '17 at 13:05
  • \$\begingroup\$ Ah, didn't see the remark, sorry for that. Was running in Chrome, runs fine in Firefox \$\endgroup\$ – schnaader Oct 18 '17 at 13:07
1
\$\begingroup\$

Pyth, 21 bytes

Port of Dennis' clever approach.

jjLkf!t{.+Tsm.cS9dtS9

Try it here!

Pyth, 23 bytes

j.f&!tl{K.+jZT*F>R0K77T

This times out on the online interpreter, but works if given enough time and memory.

Try it online with a lower number.

\$\endgroup\$
1
\$\begingroup\$

MATL, 17 16 bytes

1e9:"@Vdu0>TX=?@

Try it online! with 1e9 replaced by 1e3 so that it doesn't time out in the online compiler.

\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 121 bytes

Not nearly as short as Neil's answer, but I thought it was still worth posting.

Works by building a powerset of '123456789' where all non-matching entries are truncated and prefixed with 0, sorting the results in numerical order and keeping only the 77 relevant ones.

_=>[...'123456789'].reduce((a,x)=>[...a,...a.map(y=>y[1]-y[0]+(y.slice(-1)-x)?'0':y+x)],['']).sort((a,b)=>a-b).slice(-77)

Demo

let f =

_=>[...'123456789'].reduce((a,x)=>[...a,...a.map(y=>y[1]-y[0]+(y.slice(-1)-x)?'0':y+x)],['']).sort((a,b)=>a-b).slice(-77)

console.log(f().join` `)

\$\endgroup\$
1
\$\begingroup\$

C (gcc), 106 bytes

main(i,j,k,l){for(i=1;i<9;i++)for(j=8;j;j--)for(k=0;k<j/i;puts(""))for(l=0*k++;l<=i;)putchar(57-j+k*l++);}

Try it online!

The ungolfed (prettified) version:

int main() {
  int length, start_with, max_step, step, nth;
  for (length = 2; length <= 9; length++) {
    for (start_with = 1; start_with < 9; start_with++) {
      max_step = (9 - start_with) / (length - 1);
      for (step = 1; step <= max_step; step++) {
        for (nth = 0; nth < length; nth++) {
          putchar('0' + start_with + step * nth);
        }
        puts("");
      }
    }
  }
  return 0;
}
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 109 104 bytes

Works by generating all possible numbers: loops through each increment from 8 to 1 (variable i), loops through each starting digit from 8 to 1 (variable j), loops through each digit between j and 10-i (variable k) and generates a string t by appending k to the current t. At each step t is added to the output array.

(o=[],i=9)=>{while(--i){j=9;while(k=--j){t=""+k;while(k<10-i)o.push(t+=k+=i)}}return o.sort((a,b)=>a-b)}

Try it online!

f=

(o=[],i=9)=>{while(--i){j=9;while(k=--j){t=""+k;while(k<10-i)o.push(t+=k+=i)}}return o.sort((a,b)=>a-b)}

;
console.log(f().join("\n"))

\$\endgroup\$
1
\$\begingroup\$

Wolfram Language (Mathematica), 71 bytes

Flatten@Array[If[(x=#2+#3 #)<10,FromDigits@Range[#2,x,#3],{}]&,{8,8,8}]

Try it online!

Lightning fast due to constructing rather than selecting the output.

\$\endgroup\$
0
\$\begingroup\$

Java (OpenJDK 8), 228 174 170 163 bytes

o->{int i=11,x,y,z,l;for(;i++<1e9;){char[]w=(""+i).toCharArray();for(x=w[1]-w[0],y=1,z=0;y<w.length;z+=l>0&l==x?0:1)l=w[y]-w[y++-1];if(z<1)System.out.println(i);}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 145 bytes

A straight-forward approach with little magic.

Array(123456790).fill().map((x,i)=>(''+i).split('')).map((a,i,d) => {d=a[1]-a[0];d>0&a.every((n,j)=>j<1||n-a[j-1]==d)?console.log(a.join('')):0})

Running the snippet will consume a lot of memory...

\$\endgroup\$
0
\$\begingroup\$

PHP, 85 84 bytes

for(;++$d<9||++$a<9*$d=1;sort($r))for($x=$y=$a+1;10>$y+=$d;)$r[]=$x.=$y;print_r($r);

try it online.

sorting cost 17 bytes. This version prints the results ordered differently:

while(++$d<9||++$a<9*$d=1)for($x=$y=$a+1;10>$y+=$d;)echo"
",$x.=$y;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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