Cofnij zakres liczb


34

Dość łatwo jest nutworzyć zakres od 0do , biorąc pod uwagę liczbę n-1. W rzeczywistości wiele języków udostępnia tę operację jako funkcję wbudowaną.

Poniższy program CJam odczytuje liczbę całkowitą, a następnie drukuje taki zakres ( Wypróbuj online! ):

ri,

Zauważ, że wypisuje liczby bez separatora.

Wyzwanie

Twoim zadaniem jest odwrócenie tego procesu. Powinieneś napisać program, który, biorąc pod uwagę ciąg reprezentujący zakres, zwraca liczbę użytą do wytworzenia tego zakresu.

Dane techniczne

  • Liczby podano bez separatora.
  • Możesz założyć, że łańcuch tworzy prawidłowy zakres.
  • Możesz użyć indeksowania opartego na 0 lub 1 dla swojego zakresu.
  • Możesz założyć, że poprawne wyjście nigdy nie przekroczy 32 767 (więc prawidłowe dane wejściowe nigdy nie będą miały długości większej niż 152 725).
  • Możesz założyć, że poprawne wyjście zawsze będzie dodatnie (więc nie musisz obsługiwać wartości 0 lub ujemnych).

To jest , więc wygrywa najkrótsza konkurencyjna odpowiedź (mierzona w bajtach).

Przypadki testowe

0-indeksowane:

0123 -> 4
0 -> 1
0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 -> 101

1-indeksowany:

1234 -> 4
1 -> 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 -> 100

Czy są jakieś malejące zakresy? Czy musi działać dla liczb ujemnych?
Daniel

@Daniel Nie. Nie pamiętam o tym wspominać; dodany.
Esolanging Fruit

4
Czy nasze programy naprawdę muszą obsługiwać pusty ciąg? Myślę, że rozsądnie byłoby pozwolić nam to zignorować. Niektóre odpowiedzi w ogóle nie korzystają z tej zasady.
Mr. Xcoder,

Czy wynik może być ciągiem reprezentującym liczbę, tzn. Wziętym jako podciąg z ciągu oryginalnego?
user2390246,

@ user2390246 Tak, w porządku.
Esolanging Fruit

Odpowiedzi:



11

Łuska , 5 bajtów

LCmLN

Wypróbuj online!

Tylko litery!

Pobiera dane wejściowe jako ciąg, wynik jest indeksowany 1.

Wyjaśnienie

LCmLN
  mLN    get the list of lengths of all positive naturals
 C       cut the input into slices of those lengths
L        get the length of the resulting list

8

05AB1E , 7 6 bajtów

1-indeksowany.

āηJsk>

Wypróbuj online! lub jako pakiet testowy

Wyjaśnienie

ā        # push range [1 ... len(input)]
 η       # compute prefixes of the range
  J      # join each prefix to a string
   sk    # get index of the input in the list of prefixes
     >   # increment

czy robię coś źle? To wydaje się zwracać 0bez względu na dane wejściowe: tio.run/##MzBNTDJM/f8/3efcdi/PbLv//5UMjYxNTM3MLSwNDZQA
Shaggy

@Shaggy: trzeba to zrobić jak ten lub ten co liczyć pojedyncze cudzysłowy jako część danych wejściowych.
Emigna,

Ach, więc ciągi znaków w 05AB1E muszą być potrojone?
Shaggy

@Shaggy: Jeśli chcesz, aby pusty ciąg lub znaki nowej linii we wprowadzeniu były tak. W przeciwnym razie nie musisz wcale tego cytować.
Emigna,

[NÝJQ#]Nbył mój pomysł, ale jest to lepsze, ponieważ działa "".
Magic Octopus Urn

7

Java 8, 66 59 bajtów

s->{int r=0;for(String c="";!c.equals(s);c+=r++);return r;}

0-indeksowane

-7 bajtów dzięki @ PunPun1000 .

Mam wrażenie, że można to skrócić, sprawdzając tylko jakoś długość danych wejściowych, ponieważ możemy założyć, że dane wejściowe są zawsze prawidłowe. Nadal to rozgryzam.Nie można tego rozgryźć i prawdopodobnie będzie to kosztować zbyt wiele bajtów w Javie, aby było przydatne (to samo dotyczy zwracania podłańcucha końca danych wejściowych o indeksie 1).

Wyjaśnienie:

Wypróbuj tutaj.

s->{                 // Method with String parameter and integer return-type
  int r=0;           //  Result-integer
  for(String c="";   //  Check-String
      !c.equals(s);  //  Loop as long as the sum-String doesn't equal the input-String
    c+=r++           //   Append the number to the the Check-String,
                     //   and increase the Result-integer by 1
  );                 //  End of loop
  return r;          //  Return the result-integer
}                    // End of method

1
59 bajtów: TIO
PunPun1000,

Prawdopodobnie istnieje jakiś absurdalny skrót, taki jak policzenie liczby jedynek lub użycie logarytmu długości, aby uzyskać długość potrzebnego podłańcucha ... Wydaje mi się, że mam na to kiepskie pomysły.
JollyJoker,

6

Brachylog , 9 7 bajtów

⟦kṫᵐc,Ẹ

Wypróbuj online!

0-indeksowane.

Wyjaśnienie

Tutaj przekazujemy dane wejściowe przez zmienną Output i uzyskujemy dostęp do wyniku przez zmienną Input.

⟦          The result is the input to a range…
 k         …with the last element removed…
  ṫᵐ       …which when all elements are casted to string…
    c      …and are then concatenated results in the input string
     ,Ẹ    (Append the empty string, this is necessary for it to work in the case where the 
             input is the empty string)


5

Japt , 8 bajtów

Zaczynam rozumieć metody funkcji w Japt.

0-indeksowane. Może przyjmować dane wejściowe jako ciąg, liczbę całkowitą lub tablicę zawierającą 0 lub 1 elementy.

_o ´U}a

Sprawdź to


Wyjaśnienie

Domniemane wprowadzanie ciągu U.

_     }a

Uzyskaj pierwszą liczbę całkowitą, >=0która zwraca wartość true, gdy zostanie przekazana przez funkcję, która ...

o

Generuje tablicę liczb całkowitych od 0do 1 mniej niż bieżąca liczba całkowita ...

¬

Łączy go w ciąg ...

¥U

Sprawdza ten ciąg pod kątem równości z U.

Wyjściowa wartość wynikowa liczby całkowitej.


Alternatywnie, 8 bajtów

ÊÇo ¬ÃbU

Sprawdź to


4

Węgiel drzewny , 13 bajtów

I⌕E⁺ψθ⪫EκIλωθ

Wypróbuj online! Link jest do pełnej wersji kodu. Wyjaśnienie:

          λ     Inner map variable (μ inner map index also works)
         I      Cast to string
        κ       Outer map index
       E        Map over implicit range
      ⪫    ω    Join result
     θ          Input string
   ⁺ψ           Plus an extra character
  E             Map over each character
 ⌕          θ   Find the index of the original string
I               Cast from integer to string
                Implicit print

4

Haskell, 40 37 bajtów

f s=[n|n<-[0..],(show=<<[0..n])>s]!!0

Funkcja odwracająca zakresy zerowe.

Dzięki Laikoni za oszczędność 3 bajtów!

Wypróbuj online.


1
37 bajtów z listowego: f s=[n|n<-[0..],(show=<<[0..n])>s]!!0.
Laikoni,

1
I właśnie o tym wspomnieć, można zapisać bajt za pomocą drugiego strażnika wzoru: |m<-n+1=s!m.
Laikoni,


2

JavaScript (ES6), 32 31 bajtów

Oszczędność 1 bajtu dzięki Challenger5

f=(s,r=n='')=>r<s?f(s,r+n++):+n

Przypadki testowe


1
Znowu, czy możesz porównać ciągi leksykograficzne?
Esolanging Fruit

Chciałem zasugerować curry, ale wygląda na to, że to już nie jest konsensus :(
Shaggy

1
@Shaggy Umm, to właściwie ...
Erik the Outgolfer

1
@EriktheOutgolfer Standardowe curry jest w porządku, ale Shaggy miał na myśli tę specjalną formę curry, która wymaga połączeń takich jak f(payload_param)()lub nawet f(payload_param)(some_constant). (Nawiasem mówiąc, nie jestem pewien, czy to zadziałałoby w tym konkretnym przypadku, ponieważ potrzebuję obu ri mam ninicjalizację.)
Arnauld

2

Mathematica, 46 bajtów

Array[""<>ToString/@Range@#&,2^15]~Position~#&

1-indeksowany

wkład

[„12345678910”]


2

Ruby , 51 50 46 bajtów

->n{(0..4e4).map{|x|(1..x).to_a.join}.index n}

(To mój pierwszy program Ruby, więc dalsza gra w golfa musi być łatwa)

-4 bajty dzięki @Nnnes


1
Nie potrzebujesz ostatniego zestawu nawiasów: .index(gets)=> .index gets. Możesz użyć 4e4zamiast 8**5, ale spowoduje to, że będzie działał jeszcze wolniej. Generalnie jest OK i często oszczędza kilka bajtów, aby użyć anonimowych lambdów dla odpowiedzi Ruby: Wypróbuj online! (Zmieniłem limit na 100, aby nie przekroczył limitu czasu.)
Nnnes

2

Python 2 , 43 bajty

f=lambda s,i=1,r='':r<s and-~f(s,i+1,r+`i`)

Wypróbuj online!


Python 2 , 43 bajty

f=lambda s,i=1:s>''and-~f(s[len(`i`):],i+1)

Wypróbuj online!


Python , 46 bajtów

lambda s:s[-sum(i*'0'in s for i in range(5)):]

Wypróbuj online!

Inna strategia. Pobiera liczbę znaków od końca równą długości największego ciągu znaków 0w.


Python , 46 bajtów

f=lambda s,c=0:c*'0'in s and f(s,c+1)or s[-c:]

Wypróbuj online!

Recursive version of the above.


Does your "different strategy" (very clever, btw) work for 0-based ranges as required in the statement of the challenge? Should you change the inner bit to ... i*'0'in s[1:] for ... or something like that?
Luca Citi

@LucaCiti It works for 1-based ranges, and the challenge lets us choose.
xnor

Sure, you are right. I only looked at the initial description and missed the part where it allows for 1-based ranges.
Luca Citi

2

R, 47 bytes

n=nchar(scan(,""));which(cumsum(nchar(1:n))==n)

Try it online!

1-indexed


3
Use "if" instead of ifelse
Giuseppe

Good point! But OP has now removed the requirement to deal with the 0 case, so I can get rid of that bit entirely...
user2390246

1
You can take input as a number, as nchar works as you might expect on numbers. However, you need to handle printing your output, since this wouldn't when run as a full program.
JAD

1
n=nchar(scan());cat(which(cumsum(nchar(1:n))==n))
JAD

2

APL (Dyalog), 17 11 bytes

-6 bytes thanks to ngn.

{,\⍕¨⍳≢⍵}⍳⊂

Try it online!

⍳⊂ find the ɩndex of the entire argument in

{} the result of this anonymous function:

 length of the argument

ɩntegers until that

⍕¨ format (stringify) each

,\ cumulative concatenation of those


Oh, I forgot I could just go off of the length, nice job.
Zacharý

{,\⍕¨⍳≢⍵}⍳⊂ (11 chars)
ngn

@ngn Silly me. Of course!
Adám

2

Perl 5, 19 bytes

18 bytes code + 1 for -p.

$i++while s/$i\B//

Uses 1-based indexing. -7 bytes thanks to @nwellnhof's much better approach!

Try it online!

Explanation

$\ is a special variable that is printed automatically after each statement, so by using that to store our number we don't need to update $_ (which is automatically printed as part of the functionality of the -p flag) to contain the desired output. Then, whilst the input starts with $\, remove it and redo the program, which again increments $\ and replaces it. When it no longer finds the number at the beginning of the string, we're done! Finally, decrement $\ so we have the last number in the range.


What about $i++while s/$i\B// (18 + 1 bytes)?
nwellnhof

@nwellnhof That's much better! I think I started down a more complex route as I made the answer 0-indexed first of all... Thanks!
Dom Hastings



1

CJam, 13 bytes

q:Q,),{,sQ=}#

So many commas...

Try it online!

Explanation

q:Q            Read the input and store it in Q
   ,           Get its length
    ),         Get the range 0..n
      {,sQ=}#  Find the index of the first number in the range to satisfy this block:
       ,        Get the range 0..(number)-1
        s       Stringify it
         Q=     Check if it equals the input

1

Perl 6,  30 28  27 bytes

{first :k,*eq$_,[\~] '',0...*}

Test it

{[\~]('',0...*).first($_):k}

Test it

{first :k,$_,[\~] '',0...*}

Test it

Expanded:

{  # bare block lambda with implicit parameter 「$_」

  first       # find the first one
  :k,         # return the index into the Seq instead of what matched
  $_          # that matches the input

  # from the following

  [\~]        # triangle reduce using &infix:«~» (string concatenation)

              # a Seq
    '',       #   that starts with an empty Str
    0         #   then a 0
    ...       #   generate values
    *         #   indefinitely
}

'',0...* produces an infinite sequence of values '',0,1,2,3

[\~] '',0...* produces an infinite sequence of all of the possible inputs

""
"0"
"01"
"012"
"0123"
...

Note that this code will never stop if you give it an invalid input.


1

Pyth, 11 10 bytes

1-indexed.

fqQ|jkSTk0

Try it here

If the empty string could be ignored, this can be shortened to 6 bytes:

fqQjkS

-1 byte thanks to @Mnemonic


?QfqQjkUT)1 can do it in 11 as well, but I feel like some reordering can golf off a byte. Any ideas?
Dave

You can save a byte by using jk instead of s`m.

1

CJam, 14 12 11 bytes

q,_){,s,}%#

Try it Online

q,   e# Get length of input string
_)   e# Duplicate length, increment by 1
{    e# Generate array by mapping [0,1,2,...,length] using the following function: 
,    e# Generate range [0,x] (x is the int we're mapping)
s    e# Convert range to string (e.g [0,1,2,3] => "0123"
,    e# Get the length of that string
}%   e# Map the int to the length of it's range string
#    e# Return the index of the length of the input string in the generated array

1

Dyvil, 42 38 bytes

s=>"".{var r=0;while($0!=s)$0++=r++;r}

Same algorithm as this Java answer, except it (ab)uses some of Dyvil's syntactic specialties.

Explanation:

s=>          // starts a lambda expression with one parameter
"".{         // begins a brace access expression, the value before the '.'
             // is available within the braces as a variable named '$0'
var r=0;     // variable with inferred type int
while($0!=s) // while the accumulator $0 does not (structurally) equal s
$0++=r++     // concatenate $0 and the String representation of r,
             // then store the result in $0 and increment r by 1
;            // end of while
r}           // return r as the result of the lambda

  • Saved 4 bytes by using a brace access expression instead of a variable for the accumulator

Cool language!!
Robert Fraser

0

MATL, 14 bytes

`@q:VXzGX=~}@q

1-indexed.

Try it online!

Explanation

`       % Do...while
  @     %   Push iteration index (1-based), k
  q     %   Subtract 1: gives k-1
  :     %   Range: [1 2 ... k-1]. Will be empty for k=1
  V     %   Convert to string
  Xz    %   Remove spaces
  G     %   Push input
  X=    %   Are the two strings equal?
  ~     %   Negate. This is the loop condition. If true: next iteration
}       % Finally (execute at the end of the loop)
  @     %   Push k
  q     %   Subtract 1: gives k-1. This is the solution
        % End (implicit). Display (implicit)

1
Wait, Charcoal beat MATL?
Neil

0

C#, 72 bytes


Data

  • Input String i The int array to be deciphered
  • Output Int32 The number used to make the array

Golfed

(string i)=>{int c,p=c=0;for(;p<i.Length;c++)p+=(c+"").Length;return c;}

Ungolfed

( string i ) => {
    int
        c,
        p = c = 0;

    for( ; p < i.Length; c++ )
        p += ( c + "" ).Length;

    return c;
}

Ungolfed readable

// Takes the string with the int array
( string i ) => {
    int
        c,         // Counter, it will count how many ints the array has.
        p = c = 0; // Padding, it will help jumping from int to int on the string.

    // Start counting. If 'i' is empty, the 'c' will be 0.
    for( ; p < i.Length; c++ )

        // Increase the number of digits with the length of 'c'.
        p += ( c + "" ).Length;

    // Return the counter.
    return c;
}

Full code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestBench {
    public static class Program {
        private static Func<String, Int32> f = ( string i ) => {
            int
                c,
                p = c = 0;

            for( ; p < i.Length; c++ )
                p += ( c + "" ).Length;

            return c;
        };

        static void Main( string[] args ) {
            List<String>
                testCases = new List<String>() {
                    "0123",
                    "0",
                    "",
                    "0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100",
                };

            foreach(String testCase in testCases) {
                Console.WriteLine($" Input: {testCase}\nOutput: {f(testCase)}\n");
            }

            Console.ReadLine();
        }
    }
}

Releases

  • v1.0 - 72 bytes - Initial solution.

Notes

  • None

1
i=>{int c,p=c=0;for(;p<i.Length;)p+=(c+++"").Length;return c;} 62 bytes
TheLethalCoder

0

SOGL V0.12, 11 10 9 bytes

1-indexed.

I∫HΔ∑=?f←

Try it Here!

Explanation:

I∫         repeat input+1 times
  HΔ         create a range from 1 to the 0-indexed iteration, inclusive
    ∑        join it
     =?      if it's equal to the input
       f←      exit, pushing the 0-indexed counter

..or 7 bytes without the empty case

∫Δ∑=?F←

Try it Here!


0

Aceto, 27 25 bytes

1-based index.

;L[¥
`=]z
MLdI<
r!`;   p

We read the input and Memorize it (and directly Load it again), then we negate it (!; leading to a truthy value only for an empty string). If this value is truthy (`), we jump to the end (;), where we print the implicit zero.

Otherwise, we increment the current stack value (initially a zero), duplicate it, and put one copy on the stack to the right, while also moving there (Id]). We then construct a decreasing range (z), join the stack as a string (¥), and move the value (and us) on the original stack again ([). We Load the value we memorized earlier (the input) and compare it with this string. If equal, we jump to the end again, where we print the current "counter" value (=`;).

Otherwise, lots of empty space is traversed until the Hilbert curve eventually hits the < which puts the IP on top of I again, incrementing the counter and testing again.



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.