Numeri a triplo bilanciamento


13

Descrizione

Consideriamo un numero intero con almeno 3 cifre triplicate se, quando divise in tre parti, le cifre in ogni parte si sommano allo stesso numero. Dividiamo i numeri come segue:

abcdefghi - Standard case: the number of digits is divisable through 3:
abc def ghi

abcdefgh - Number % 3 == 2: The outer groups are both assigned another digit
abc de fgh (the inner group will have one digit less than both outer groups)

abcdefghij - Number % 3 == 1: The inner group is assigned the extra digit
abc defg hij (the inner group will have one digit more than the outer groups)

Sfida

Il tuo compito è quello di scrivere un programma che, dato un numero intero con almeno 3 cifre, determina se il numero dato è triplo bilanciato e genera un valore di verità o falsa in base al suo risultato.

Casi test

333 -> True
343 -> False
3123 -> True
34725 -> True
456456 -> False
123222321 -> True

Si tratta di , quindi si applicano scappatoie standard e può vincere la risposta più breve in byte!


1
A quanto ho capito, se puoi dividerlo uniformemente, dovresti.
totalmente umano il

@ Mr.Xcoder lo hai diviso in tre parti (non funziona ancora secondo il commento di @ MagicOctopusUnr:when split in three parts,
Stephen

4
Prendi in considerazione l'utilizzo del Sandbox per evitare una situazione del genere in futuro.
Mr. Xcoder,

2
Ops! Mi dispiace per la confusione sui casi di test, a quanto pare avevo una sorta di svolta nella mia testa. Ora che sono stati corretti, spero che voti per riaprire la mia sfida.
racer290,

5
Per impostazione predefinita, l'input può essere considerato come una stringa. Può essere preso come una matrice di cifre?
Luis Mendo,

Risposte:


7

Python 2 , 93 88 86 byte

-4 byte grazie a @LeakyNun
-2 byte grazie a @ Mr.Xcoder

def g(i):l=-~len(i)/3;print f(i[:l])==f(i[l:-l])==f(i[-l:])
f=lambda a:sum(map(int,a))

Provalo online!


3

Gelatina , 23 byte

DµL‘:3‘Ṭ©œṗ⁸U®œṗЀS€€FE

Provalo online!

Deve esserci un modo più breve che in qualche modo mi è volato in testa ...


Sembra semplice ma non lo è davvero ... Anche in 05AB1E è difficile a causa della divisione non predefinita.
Magic Octopus Urn,

3

Retina , 89 byte

^|$
¶
{`¶(.)(.*)(.)¶
$1¶$2¶$3
}`^((.)*.)(.)¶((?<-2>.)*)¶(.)
$1¶$3$4$5¶
\d
$*
^(1+)¶\1¶\1$

Provalo online! Il link include casi di test. Spiegazione: La prima fase aggiunge nuove righe all'inizio e alla fine dell'input. Il secondo stadio tenta quindi di spostare le cifre sulle nuove linee a coppie, tuttavia se non ci sono abbastanza cifre rimaste nel mezzo, il terzo stadio è in grado di spostarle indietro, causando l'arresto del loop. Il quarto stadio converte quindi ciascuna cifra separatamente in unario, sommandole in tal modo, mentre l'ultimo stadio verifica semplicemente che le somme siano uguali.


2

Mathematica, 142 byte

(s=IntegerDigits@#;c=Floor;If[Mod[t=Length@s,3]==2,a=-1;c=Ceiling,a=Mod[t,3]];Length@Union[Tr/@FoldPairList[TakeDrop,s,{z=c[t/3],z+a,z}]]==1)&

2

Gelatina , 20 byte

DµL‘:3x2jSạ¥¥LRṁ@ḅ1E

Provalo online!

Come funziona

DµL‘:3x2jSạ¥¥LRṁ@ḅ1E  Main link. Argument: n

D                     Decimal; convert n to base 10, yielding a digits array A.
 µ                    Begin a new chain with argument A.
  L                   Compute the length of A.
   ‘                  Increment; add 1 to the length.
    :3                Divide the result by 3.
                      This yields the lengths of the outer chunks.
      x2              Repeat the result twice, creating an array C.
             L        Compute l, the length of A.
            ¥         Combine the two links to the left into a dyadic chain.
                      This chain will be called with arguments C and l. 
           ¥              Combine the two links to the left into a dyadic chain.
         S                    Take the sum of C.
          ạ                   Compute the absolute difference of the sum and l.
        j                 Join C, using the result to the right as separator.
                      We now have an array of the lengths of all three chunks the
                      digits of n have to be split in.
              R       Range; map each chunk length k to [1, ..., k].
               ṁ@     Mold swapped; takes the elements of A and give them the shape
                      of the array to the right, splitting A into chunks of the
                      computed lengths.
                 ḅ1   Convert each chunk from unary to integer, computing the sum
                      of its elements.
                   E  Test if the resulting sums are all equal.

1
Mi piacerebbe leggere una spiegazione
Felix Dombek, il

@FelixDombek Ho aggiunto una spiegazione.
Dennis,


0

Javascript, 178 byte

(a)=>{b=a.split(/(\d)/).filter((v)=>v);s=Math.round(b.length/3);f=(m,v)=>m+parseInt(v);y=b.slice(s,-s).reduce(f,0);return b.slice(0,s).reduce(f,0)==y&&y==b.slice(-s).reduce(f,0)}

Benvenuti in PPCG! Hai letto le pagine dei suggerimenti ? C'è molto spazio per giocare a golf la tua risposta.
Neil,

Nel caso in cui tu sia ancora interessato, sono stato in grado di tagliare la tua risposta fino a 106 byte: ([...b],s=~b.length/3|0,f=(m,v)=>+m+ +v,y=b.splice(s).reduce(f))=>b.splice(-s).reduce(f)==y&y==b.reduce(f)(fai attenzione quando copi dai commenti mentre Stack Exchange inserisce caratteri invisibili).
Neil,

Beautyful! Molte cose per me da imparare lì dentro.
cdm,

0

Java 8, 149 byte

q->{int l=q.length,s=(l+1)/3,a=0,b=0,c=0,i=0;for(;i<s;a+=q[i++]);for(i=s,s=l/3*2+(l%3<1?0:1);i<s;b+=q[i++]);for(i=s;i<l;c+=q[i++]);return a==b&b==c;}

Prende l'input come int[].

Spiegazione:

Provalo qui.

q->{                 // Method with int-array parameter and boolean return-type
  int l=q.length,    //  Length of the input-array
      s=(l+1)/3,     //  (Length + 1) divided by 3
      a=0,b=0,c=0,   //  Three sums starting at 0
      i=0;           //  Index-integer
  for(;i<s;          //  Loop (1) from 0 to `s1` (exclusive)
    a+=q[i++]        //   And increase `a` with the next digit
  );                 //  End of loop (1)
  for(i=s,s=l/3*2+(l%3<1?0:1);i<s;
                     //  Loop (2) from `s1` to `s2` (exclusive)
    b+=q[i++]        //   And increase `b` with the next digit
  );                 //  End of loop (2)
  for(i=s;i<l;       //  Loop (3) from `s2` to `l` (exclusive)
    c+=q[i++]        //   And increase `c` with the next digit
  );                 //  End of loop (3)
  return a==b&b==c;  //  Return if `a`, `b` and `c` are equal
}                    // End of method

Ecco una panoramica delle parti indicizzate 0 (esclusive) per ogni lunghezza:

Length:  Parts:    0-indexed (exclusive) parts:

 3       1,1,1     0,1 & 1,2 & 2,3
 4       1,2,1     0,1 & 1,3 & 3,4
 5       2,1,2     0,2 & 2,3 & 3,5
 6       2,2,2     0,2 & 2,4 & 4,6
 7       2,3,2     0,2 & 2,5 & 5,7
 8       3,2,3     0,3 & 3,5 & 5,8
 9       3,3,3     0,3 & 3,6 & 6,9
10       3,4,3     0,3 & 3,7 & 7,10
...
  • Poiché aeseguiamo il loop da 0a (length + 1) / 3)(questo valore è ora memorizzato ins );
  • Per b eseguiamo il loop da sa length / 3 * 2 +( 0se la lunghezza modulo-3 è 0; 1se la lunghezza modulo-3 è 1 o 2) (questo valore è ora memorizzato ins );
  • Per c passiamo da sa length.

(tutti e tre i loop sono esclusivi indicizzati 0)


0

Röda , 82 byte

f s{n=((#s+1)//3)[s[:n],s[n:#s-n],s[#s-n:]]|[chars(_)|[ord(_)-48]|sum]|[_=_,_=_1]}

Provalo online!

Spiegazione:

f s{ /* function declaration */
    n=((#s+1)//3)
    [s[:n],s[n:#s-n],s[#s-n:]]| /* split the string */
    [ /* for each of the three strings: */
        chars(_)|    /* push characters to the stream */
        [ord(_)-48]| /* convert characters to integers */
        sum          /* sum the integers, push the result to the stream */
    ]|
    [_=_,_=_1] /* take three values from the stream and compare equality */
}

0

JavaScript, 129 , 104 byte

([...n],l=n.length/3+.5|0,r=(b,e=b*-4,z=0)=>n.slice(b,e).map(x=>z-=x)&&z)=>r(0,l)==r(-l)&&r(l,-l)==r(-l)

La funzione r suddivide la stringa in base ai parametri b ed e, quindi somma le cifre e restituisce il valore.

Per tagliare le dimensioni corrette, dividiamo la lunghezza per 3 e arrotondiamo il risultato. Chiamare slice (0, risultato) ci dà il primo blocco, slice (risultato, -result) ci dà il secondo e slice (risultato) ci dà l'ultimo. A causa del modo in cui chiamo slice, ho usato slice (risultato, risultato 4 *) anziché l'ultimo, ma dà lo stesso risultato.

Infine, confronto i risultati mostrando che i valori sono uguali.

Modifica: stesso principio, migliore golf


È possibile passare &&a &in JavaScript? Entrambi i controlli di seconda mano ( &&ze &&y[1]==y[2]) non sembrano modificare i valori, quindi se è possibile, non dovrebbe influenzare il risultato da quello che posso vedere.
Kevin Cruijssen,

Darò un'occhiata. & è un'operazione bit vs && essendo logico, quindi cambierà l'output a 1 o 0 invece di vero o falso, ma in questo caso funziona alla grande.
Grax32,
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.