Skaczące liczby


14

ZADANIE

wypisz liczby całkowite n, gdzie 12 <= n <= 123456789i wszystkie pary kolejnych cyfr in mają tę samą dodatnią różnicę między nimi (np. 2468, ale nie 2469).

BRAK WEJŚCIA.

Wynik:

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

Zasady

  1. Obowiązują standardowe luki.
  2. brak wejścia

najkrótszy kod wygrywa.

Kredyty anarchii golfa


8
This problem is from anarchy golf. You should give it credit (even if you were the one who submitted it)
xnor

5
Do they have to be printed in order?
H.PWiz

11
I submitted this problem on anagol :)
Lynn

2
Why isn’t every integer 0≤n<100 on this list?
DonielF

3
@DonielF Because the integer has to be larger than or equal to 12, and because the forward differences must be positive.
Dennis

Odpowiedzi:


11

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.

ìà Find fastest route between two points using Dykstra's Algorithm
Neil

7

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.


1
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.
Lynn

6

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

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);}}
Kevin Cruijssen

@KevinCruijssen I would agree, although one can most likely keep using the one-byte comparison by choosing a higher value; i<1e9.
Jonathan Frech

@KevinCruijssen Also, if I am not mistaking, l<1 can be golfed to !l, as l never reaches a negative value.
Jonathan Frech

@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).
Kevin Cruijssen

@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 :)
Jacobinski

5

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

1
Ugh. Beat me to it. +1
caird coinheringaahing

You do not need the $ at the end of your helper link.
Mr. Xcoder

A way clearer way to do this is DIµ>0ȦȧE¶Ç77#
Erik the Outgolfer

4

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.


Try using this: žh
Okx

@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.
Erik the Outgolfer

@EriktheOutgolfer I meant replacing •7=›ζ•
Okx

@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.
Magic Octopus Urn

@MagicOctopusUrn Why don't you try removing the 0 at the start?
Okx

4

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


4

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.


3

APL (Dyalog), 37 28 bytes

x/⍨{1=≢∪2-/⍎¨⍕⍵}¨x11+⍳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



3

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

3

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

1
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;);}
Nevay

@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!
Kevin Cruijssen

2

05AB1E, 14 bytes

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

Try it online!


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?
Magic Octopus Urn

@MagicOctopusUrn If I try replacing the numbers before Ÿ, it works fine
Okx

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.
Magic Octopus Urn


2

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)


2

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.


"Run code snippet" leads to an error: Uncaught SyntaxError: Unexpected token for
schnaader

2
@schnaader Are you running it in Firefox 30+? This answer uses the non-standard array comprehension syntax which only Firefox supports.
Birjolaxew

Ah, didn't see the remark, sorry for that. Was running in Chrome, runs fine in Firefox
schnaader



1

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


1

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

1

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




0

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


0

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;
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.