Gamma, inversione, somma!


21

Dato un intero positivo n come input, genera la somma dell'intervallo inverso di n.

Una somma dell'intervallo invertito viene creata facendo un intervallo inclusivo fino a n, iniziando con 1 e includendo n, invertendo ciascuno dei numeri all'interno e sommandolo.

Esempio:

Ecco cosa accadrebbe per un input di 10:

Gamma: [1,2,3,4,5,6,7,8,9,10]

Inverso: [1,2,3,4,5,6,7,8,9,01](i numeri di 1 carattere invertiti sono essi stessi, 10 invertiti sono 01 o 1)

Somma: 46

I numeri con più di 3 cifre sono invertiti allo stesso modo dei numeri con 2 cifre. Ad esempio, 1234 diventerebbe 4321.

Casi test:

Input -> Output

10 -> 46
5 -> 15
21 -> 519
58 -> 2350
75 -> 3147
999 -> 454545

I casi di testo completi per l'input di 999 possono essere trovati qui , grazie mille a @ fireflame241.


Altri risultati del test case (non numerati, scusa, ma puoi analizzare e ottenere il loro numero di riga se vuoi): provalo online!
Stephen,




4
-1 perché questo non è interessante. Sembra che la maggior parte, se non tutte, delle proposte utilizzino lo stesso approccio. Questa sfida sembra un mucchio di problemi che sono già stati posti, appena convocati senza scorciatoie evidenti.
Esolanging Fruit,

Risposte:




8

JavaScript (ES6), 42 byte

f=n=>n&&+[...n+""].reverse().join``+f(n-1)

La mia soluzione doppiamente ricorsiva preferita è purtroppo più lunga di 3 byte:

f=n=>n&&+(g=x=>x?x%10+g(x/10|0):"")(n)+f(n-1)

8

Perl 6 , 20 byte

{(1..$_)».flip.sum}

Provalo

Allargato:

{
   ( 1 .. $_ )\  # Range
   ».flip        # flip each value in the Range (possibly in parallel)
   .sum          # sum up the list
}

Il "forse in parallelo" è richiesto? Sembra che potresti sbarazzarti di un byte o due omettendolo.
Finanzia la causa di Monica il

@QPaysTaxes No. Richiama ».flipil .flipmetodo su ciascuno dei valori nell'intervallo. Il prossimo modo più breve per farlo .map(*.flip)è quello di 5 byte in più.
Brad Gilbert b2gills il

Oh, quindi la parte chiave è "ciascuno", non "(possibilmente in parallelo)". Potrebbe valere la pena separarli, quindi.
Fondi Monica's Lawsuit,

@QPaysTaxes Non sono sicuro di sapere cosa intendi ».flipper chiamata con un metodo hyper. Mentre posso dividere il »e .flipusando un unspace \ come ho fatto prima; ciò renderebbe più difficile la comprensione, poiché sembrerebbe la fine di un qqww/ /costrutto ( « a b "c d" »).
Brad Gilbert b2gills il

7

Retina , 41 36 35 byte

.+
$*
1
1$`¶
1+
$.&
%O^$`.

.+
$*
1

Provalo online! Il link include casi di test. Modifica: salvato 5 byte grazie a @FryAmTheEggman. Salvato 1 byte grazie a @ PunPun1000. Spiegazione:

.+
$*

Converti in unario.

1
1$`¶

Crea un intervallo da 1a n.

1+
$.&

Converti in decimale.

%O^$`.

Invertire ogni numero.

.+
$*

Converti in unario.

1

Somma e converti in decimale.


@FryAmTheEggman Bah, continuo a dimenticarmene.
Neil,

Non è necessario il in .+¶ La partita corrisponderà su più righe
PunPun1000

@ PunPun1000 Ne avevo bisogno prima della correzione di FryAmTheEggman!
Neil

Ho notato che anche O^$s`.per invertire l'intera stringa funziona.
Neil,




5

cQuents , 4 byte

;\r$

Provalo online!

Spiegazione

       Implicit input n.
;      Series mode. Outputs the sum of the sequence from 1 to n.
 \r$   Each item in the sequence equals:
 \r    String reverse of
   $                     current index (1-based)

5

Python 2 , 38 byte

Impossibile calcolare termini superiori al limite di ricorsione:

f=lambda x:x and int(`x`[::-1])+f(x-1)

Provalo online!


Puoi usare import syse sys.setrecursionlimit()se vuoi gestire numeri più grandi, nell'intestazione tio.
Mr. Xcoder,


5

Röda , 56 41 36 byte

15 byte salvati grazie a @fergusq

{seq 1,_|parseInteger`$_`[::-1]|sum}

Provalo online!

Questa è una funzione anonima che accetta un numero intero dal flusso di input e genera un numero intero nel flusso di output.

Spiegazione

{seq 1,_|parseInteger`$_`[::-1]|sum} Anonymous function
 seq 1,_                             Create a sequence 1 2 3 .. input and push each value to the stream
        |                            For each value in the stream:
                     `$_`             Cast it into a string
                         [::-1]       And reverse it
         parseInteger                 And parse the resulting string as an integer, while pushing the value to the stream
                               |sum  Sum all the values in the stream

È possibile salvare molti byte utilizzando [::-1]anziché il contrario. Inoltre ` $_` è più breve di _..""e le parentesi dopo parseInteger non sono necessarie.
Fergusq,

@fergusq Grazie per i suggerimenti, il mio Röda è diventato un po 'arrugginito :)
Kritixi Lithos

4

C # (.NET Core) , 103 97 byte

using System.Linq;r=>new int[r+1].Select((_,n)=>int.Parse(string.Concat((n+"").Reverse()))).Sum()

Provalo online!

TIO link produce tutti i risultati da 1 a 999, quindi sentiti libero di controllare il mio lavoro.

Mi aspettavo che fosse un po 'più corto, ma risulta che Reverse()restituisce una IEnumerable<char>stringa anziché un'altra stringa, quindi ho dovuto aggiungere qualche extra per trasformarla in una stringa in modo da poterla analizzare in un int. Forse c'è un modo più breve per passare da IEnumerable<char>a int correttamente.

Di nota minore, questo utilizza anche le funzioni Range() Reverse()e Sum()tutto in ordine.

-6 byte grazie a TheLethalCoder


Non hai bisogno del punto e virgola finale. Penso che usando new int[r]e .Select((_,n)=>...)ti salverò byte.
TheLethalCoder

@TheLethalCoder It takes new int[r+1] to get the right output since the index starts at 0, but it does still save a few bytes. RIP Range() though
Kamil Drakari

4

Ruby, 56, 52, 41, 39 bytes

->n{(1..n).sum{|i|i.to_s.reverse.to_i}}

Ruby, 34 bytes (if lambda param is a string)

->n{(1..n).sum{|i|i.reverse.to_i}}

Thanks to @Unihedron for the second solution.


1
->n{ works as well.
Value Ink

1
I have crafted a shorter program in the same tool (Ruby) that is different enough (it deals with input and output) to be its own submission, you can find it here: codegolf.stackexchange.com/a/150636/21830
Unihedron

@Unihedron, haha, I didn't know Ruby is so crazy to allow string ranges. Thanks.
akostadinov

Yes, ruby also has nifty features like ?a..?z and ?a1..?h8 (although you better be careful with the 2nd format :D)
Unihedron

Ranges has to either 1. (for start value) implement succ and 2. (if either start or end value does not implement succ) be numeric, so int..string will get rejected as "Bad value for range". The inverse is true (but alas there's no downto range), or (?1..n) can be used instead
Unihedron

3

Mathematica, 47 bytes

Tr[FromDigits@*Reverse/@IntegerDigits@Range@#]&

Try it online! (in order to work on mathics we need to replace "Tr" with "Total")


Tr@*IntegerReverse@*Range
ngenisis

3

Charcoal, 14 13 bytes

-1 byte thanks to Carlos Alejo

I∕…·⁰N«⁺ιI⮌Iκ

Try it online! Link is to verbose version.

Explanation

I                  Cast
  ∕     «           Reduce
   …·⁰N            Inclusive range from 0 to input as number
         ⁺          Plus
          ι         i
           I⮌Iκ   Cast(Reverse(Cast(k)))

You can save a byte by dropping the last ». By the way, where in the Charcoal wiki is the Reduce operator documented?
Charlie

Nowhere, it's an overload of the division one :| I can give you edit access if you want (sorry I'm too lazy to do it myself)
ASCII-only

Also yeah I forgot why leaving out ending braces works lol
ASCII-only

I would really like the Charcoal wiki to be a bit more documented, as there are still some working but hidden features. If you grant me edit access I'll do my best to document them. Example: how can the Modulo operator be used to format strings in Charcoal?
Charlie

1
@CarlosAlejo I've had a bit of free time so I've started documenting stuff, hope you like it!
Neil

3

Magneson, 102 bytes

Source

That's not very visible, so here's a scaled up version (Note: Won't actually run, and still isn't very pretty)

Display Purposes Only

Magneson operates by parsing an image and evaluating commands from the colours of the pixels it reads. So stepping through the image for this challenge, we have:

  • R: 0, G: 1, B: 1 is an integer assignment command, which takes a string for the variable name and the value to assign. We'll use this to store the sum total.
  • R: 0, G: 1, B: 0 is a prebuilt string with the value VAR_1 (Note: This is only while we're asking for a string; the colour code has a separate function when used elsewhere).
  • R: 3, G: 0, B: 0 is a raw number. Magneson handles standard numbers by requiring the Red component to be exactly 3, and then forms a number by using the blue value directly plus the green value multiplied by 256. In this case, we're just getting the number 0.
  • R: 0, G: 1, B: 1 is another integer assignment command. This time, we're storing an iteration variable, to keep track of which number we're on
  • R: 0, G: 1, B: 1 is a prebuilt string with the value VAR_2 (Once more, only when we need a string)
  • R: 3, G: 0, B: 0 is the number 0, once more. Onto the interesting bits now.
  • R: 1, G: 0, B: 0 indicates the start of a loop. This takes a number and loops the following snippet of code that many times.
  • R: 2, G: 0, B: 0 is the STDIN function, or at least it is when we need a number. This reads a line of input from the console and turns it into a number, since we asked for a number.
  • R: 0, G: 8, B: 0 starts off our looping code, and it is an additive command. This adds a number to an integer variable, and so takes a string for the variable name, and the number to add.
  • R: 0, G: 1, B: 1 is the prebuilt string for VAR_2, which is our iteration variable.
  • R: 3, G: 0, B: 1 is a raw number, but this time it's the number 1.
  • R: 0, G: 8, B: 0 is another addition command.
  • R: 0, G: 1, B: 0 is the string for VAR_1, which is our sum total.
  • R: 0, G: 3, B: 0 is a function that reverses a string. In the context of asking for a number, it then converts the reversed string to a number.
  • R: 0, G: 2, B: 1 is an integer retrieval command, and will retrieve the number stored in a provided variable. In the context of asking for a string (such as from the reverse command), it converts the number to a string.
  • R: 0, G: 1, B: 1 is the name VAR_2; our iteration variable.
  • R: 1, G: 0, B: 1 is the marker to end the loop, and go back to the start of the loop if the criteria isn't met (so if we need to keep looping). Otherwise, proceed onwards.
  • R: 0, G: 0, B: 1 is a very simple println command, and takes a string.
  • R: 0, G: 2, B: 1 retrieves an integer from a variable
  • R: 0, G: 1, B: 0 is the name of our sum total variable, VAR_1

    All in all, the program:

  • Assigns the value 0 to VAR_1 and VAR_2
  • Loops from 0 to a number provided in STDIN
    • Adds one to VAR_2
    • Adds the integer value of reversing VAR_2 to VAR_1
  • Prints the contents of VAR_1


3

CJam, 12 bytes

ri){sW%i}%:+

Try it online!

-1 thanks to Business Cat.

Explanation:

ri){sW%i}%:+
r            Get token
 i           To integer
  )          Increment
   {sW%i}    Push {sW%i}
    s         To string
     W        Push -1
      %       Step
       i      To integer
         %   Map
          :+ Map/reduce by Add

Could you add an explanation? I don't understand CJam (nor GolfScript). But MY beat two (albeit ancient in terms of golf-langs) golfing languages!
Zacharý

@Zacharý done...
Erik the Outgolfer

You don't need the ,
Business Cat

@BusinessCat Ohhh used too much to GolfScript apparently...
Erik the Outgolfer

3

APL (Dyalog), 10 7 bytes

3 bytes golfed thanks to @Adám by converting to a tradfn from a train

+/⍎⌽⍕⍳⎕

Try it online!

          Input (example input: 10)
          Range; 1 2 3 4 5 6 7 8 9 10
          Stringify; '1 2 3 4 5 6 7 8 9 10'
          Reverse; '01 9 8 7 6 5 4 3 2 1'
          Evaluate; 1 9 8 7 6 5 4 3 2 1
+/         Sum; 46

To @Uriel & Cows quack about the chat question: Well, I did the Mathematics portion, in addition to that, I've been suspended from chat, hence my not responding in there.
Zacharý


@Adám Thanks for the tip. Removing the ¨ was clever :)
Kritixi Lithos

3

Java 8, 97 bytes

IntStream.range(1,n+1).map(i->Integer.valueOf(new StringBuffer(""+i).reverse().toString())).sum()

EDIT

As per the comment of Kevin Cruijssen, I would like to improve my answer.

Java 8, 103 bytes

n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum()

1
Integer.valueOf can be golfed to new Integer, and .reverse().toString() can be golfed to .reverse()+"". Also, you must include the required imports and lambda parameters, like java.util.stream.IntStream and n-> before it. And you can also golf IntStream & Integer to LongStream and Long. The final answer will be n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum() (103 bytes - Your current answer with added import and lambda parameter would be 117 bytes.) Still +1, nice answer!
Kevin Cruijssen

@KevinCruijssen Thank you for your valuable inputs. I'll update my answer. Thanks. :)
CoderCroc

3

Japt, 7 5 bytes

-2 bytes thanks to @Shaggy.

õs xw

Try it online!

Explanation

õs xw  Implicit input of integer U
õs     Create range [1,U] and map to strings
    w  Reverse each string
   x   Sum the array, implicitly converting to numbers.

Old solution, 7 bytes

Keeping this since it's a really cool use of z2.

õs z2 x

Try it online!

Explanation

õs z2 x  Implicit input of integer U
õs       Create range [1,U] and map to strings
   z2    Rotate the array 180°, reversing strings
      x  Sum the array, implicitly converting back to integers

1
You know z2 on a flat array is the same as w, righ... uhm... excuse my inadequacy at Japt...
ETHproductions

6 bytes: õ_swÃx thanks to the new addition of N.s(f).
Shaggy

Or even just õs xw for 5 bytes.
Shaggy

@Shaggy I can't believe nobody mentioned that 5-byte solution until now... will edit in a bit. As for the 6-byte one, if that was added after this challenge was posted, I think that'd be non-competing.
Justin Mariner

@JustinMariner, neither can I! :D Although, it seems a shame to ditch that z2 trick; that was pretty damn genius. Note that non-competing is no longer a thing.
Shaggy

3

C++, 146 bytes

#include<string>
using namespace std;int r(int i){int v=0,j=0;for(;j<=i;++j){auto t=to_string(j);reverse(t.begin(),t.end());v+=stoi(t);}return v;}

Good job! You can spare some bytes by removing the header and putting "using namespace std" (check here tio.run/#cpp-gcc). I also think you could replace "auto t" with just "t" (?)
koita_pisw_sou

Yeah, koita_pisw_sou is right about the first part. But you need the auto.
Zacharý

@koita_pisw_sou Do you mean that i can exclude the header directive from the byte count ? Same for the namespace ? auto keyword is needed
HatsuPointerKun

Yes, check the link I sent
koita_pisw_sou

(Whoops, I am not sure about the removing the header!) But I was referring to using namespace std; saving bytes.
Zacharý

3

Husk, 7 6 3 bytes

ṁ↔ḣ

Try it online!

Ungolfed/Explanation

  ḣ  -- With the list [1..N] ..
ṁ    -- .. do the following with each element and sum the values:
 ↔   --    reverse it


2

RProgN 2, 8 bytes

{Ø.in}S+

Explained

{Ø.in}S+
{    }S # Create a stack in range 0 through the implicit input, using the function defined
 Ø.     # Append nothing, stringifying the number
   i    # Reverse the string
    n   # Convert back to a number
       +# Get the sum of the stack, and output implicitly.

Try it online!




2

Neim, 4 bytes

Δ𝐫)𝐬

Try it online!

Explanation

Δ )              for each element 1 to n (outputs list)
 𝐫               reverse 
   𝐬             sum 

2
Alternative solution: 𝐈Ψ𝐫𝐬 (create inclusive range, reverse each element, sum)
Okx

@Okx didn't know that the Ψ token existed! would have definitely used that in hindsight. real nice
space junk

2

C (gcc), 71 bytes

q(n,x,p){p=n?q(n/10,x*10+n%10):x;}f(w,a,e){for(a=0;w;)a+=q(w--,0);e=a;}

Try it online!


Wait... what? How f() returns its result without any return statement? Does the e=a instruction manipulates the registers in such a way that the result is stored in the same register than the one used by returned values?
scottinet
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.