Dove sono i personaggi adiacenti nel titolo? [3, 4]!


21

Titolo errato apposta. Leggi di più per scoprire perché.

Il tuo compito: data una stringa o un elenco delimitato che include i caratteri A,B,C,D, genera gli indici di tutti i caratteri uguali adiacenti. L'output può essere più stringhe / numeri interi su più righe, un elenco / matrice o una stringa delimitata.

Tutto l'output deve essere in un elenco o stringa o più righe stampate. Ogni riga stampata, se ce ne sono più, deve contenere solo 1 stringa o numero. I wiltvers finali vanno bene.

Metodi standard di input / output. Si applicano scappatoie standard.

Ad esempio, l'input 'ABCDDCBA'dovrebbe essere emesso 3,4o 4,5, a seconda che sia da 0 a 1- indicizzato, perché quei numeri sono gli indici di De Daccanto ad esso.

Casi test:

I casi di test hanno input dato come una singola stringa e output come una ,stringa delimitata. Gli output sono indicizzati 0, aggiungi 1 a ogni elemento in uscita per ottenere 1 indice.

Input: 'ABCDCABCD'
Output: ''

Input: 'AABBCCDD'
Output: '0,1,2,3,4,5,6,7'

Input: 'ABCDDDCBA'
Output: '3,4,5'

Input: 'ABBCDD'
Output: '1,2,4,5'

Questo è , quindi vince il codice più corto!


Possiamo avere un delimitatore finale nell'output?
Business Cat,

@BasicSunset Sure
Compagno SparklePony,

1
@JonathanAllan Va bene perché genera solo un elenco.
Compagno SparklePony,

2
Gli indici di caratteri consecutivi possono apparire più volte? Ad esempio per il terzo caso di test, è 3,4,4,5valido anche?
Luca,

1
Puoi aggiungere un caso di test che non ha corrispondenze simmetriche? Ad esempioAABBCD -> 1,2,3,4
Riley l'

Risposte:


5

MATL , 8 7 byte

d~ftQvu

L'output è basato su 1.

Provalo online!

Spiegazione con esempio

Considera l'input 'ABCDDDCBA'.

d     % Implicitly input a string. Consecutive differences
      % STACK: [1  1  1  0  0 -1 -1 -1]
~     % Negate. Each character that equals the next gives true
      % STACK: [0 0 0 1 1 0 0 0]
f     % Find: (1-based) indices of true elements
      % STACK: [4 5]
tQ    % Duplicate, add 1 element-wise
      % STACK: [4 5], [5 6]
v     % Concatenate vertically
      % STACK: [4 5; 5 6]
u     % Unique (remove duplicates). This doesn't automatically sort, but the 
      % output will be sorted because the input, read in column-major order, is 
      % Implicitly display
      % STACK: [4; 5; 6]

8

Retina , 33 29 23 byte

6 byte salvati grazie a Martin Ender

T`L`:`(.)\1+
:
$.`¶
T`L

Emette un elenco di indici separati da avanzamento riga.

Provalo online!

Spiegazione

T`L`:`(.)\1+

Traslitterare lo stesso carattere in due punti, per contrassegnare le posizioni in cui sono presenti caratteri duplicati.

:
$.`¶

Quindi sostituisci i due punti con la lunghezza del testo prima di esso, seguito da un avanzamento riga.

T`L

Infine, elimina tutte le lettere rimanenti.


7

Gelatina , 7 byte

JṁŒgḊÐf

1-basati; restituisce un elenco di elenchi delle serie di indici consentiti dall'OP.

Provalo online!

Come?

JṁŒgḊÐf - Main link: char-list s       e.g. 'DCCABBBACCCD' (which is a python interpreted input of ['D','C','C','A','B','B','B','A','C','C','C','D'])
J       - range(length(s))                  [1,2,3,4,5,6,7,8,9,10,11,12]
  Œg    - group-runs(s)                     [['D'],['C','C'],['A'],['B','B','B'],['A'],['C','C','C'],['D']]
 ṁ      - mould left like right             [[1],[2,3],[4],[5,6,7],[8],[9,10,11],[12]]
     Ðf - filter keep items that would be truthy (empty is not truthy) after applying:
    Ḋ   -     dequeue (x[1:])               [    [2,3],    [5,6,7],    [9,10,11]     ]        

2
- Le cose che vorrei che 05AB1E potessero fare per 500, per favore.
Magic Octopus Urn l'

1
Mi sento sempre più come se questa lingua fosse un po 'come barare qui. : D
Avamandro

@ComradeSparklePony perché l'annullamento del controllo accetta?
Jonathan Allan,

7

Brain-Flak , 57 46 byte

{({}[({})]<(([]<>)[()])>){(<{}{}{}>)}{}<>}<>

Include +2 per -ar

Utilizza l'indicizzazione basata su 0.

Provalo online!

# While true
{

  # Subtract the second value on the stack from the first
  ({}[({})]

  # Push the height of this stack (the main stack) on the other stack
  <(([]<>)

  # Push the height of the main stack - 1
  [()])>

  # Push the difference that we calculated a second ago
  )

  # If they weren't the same character
  {

    # Pop the difference and the two stack heights
    (<{}{}{}>)

  # End if
  }

  # Pop the difference (or the 0 to get out of the if)
  {}

# Switch back to the main stack and end while
<>}

# Switch to the stack with the indexes and implicitly print
<>

6

Mathematica, 32 byte

Union@@StringPosition[#,x_~~x_]&

Funzione pura che restituisce le posizioni 1 indicizzate di caratteri adiacenti a un carattere identico.

Spiegazione:

StringPosition["string","sub"]fornisce un elenco delle posizioni iniziali e finali dei caratteri in corrispondenza delle quali "sub"appare come sottostringa di "string". x_~~x_è un carattere StringExpressionche corrisponde a due caratteri adiacenti e identici. Ad esempio, StringPosition["ABCDDDCBA",x_~~x_]{{4, 5}, {5, 6}}. L'applicazione si Unionunisce alle liste, ordina ed elimina i duplicati.


5

Brain-Flak , 69, 59 , 56 byte

{({}[({})]<(())>){((<{}{}>))}{}{([{}]([]<>))(<>)}{}}<>

Provalo online!

+2 byte per i -arflag che abilita l'ingresso ASCII e inverte lo stack.

Utilizza l'indicizzazione basata su 0. Ho salvato 10 byte riducendo la ridondanza push-pop . Salvati altri 4 byte passando dall'indicizzazione basata su 1 a 0.

Questa è praticamente l'unica sfida basata sulle stringhe in cui è bravo il flak cerebrale. Questo perché il brain-flak è ottimo nel confrontare i caratteri consecutivi, anche se è orrendo nell'elaborazione delle stringhe in generale. Ecco la versione leggibile del codice con commenti per spiegare come funziona:

#While True
{

    #Determine if top two are equal
    ({}[({})]<(())>){((<{}{}>))}{}

    #If so
    {

        #Pop the one, and negate it's value (giving us -1)
        ([{}]

        #Push stack height over
        ([]<>)

        #Then push stack height plus the negated pop (-1)
        ) 

        #Push a zero back onto the main stack
        (<>)

    #Endwhile
    }

    #Pop the zero
    {}

#Endwhile
}

#Toggle back, implicitly display
<>


@riley risolto! (E ancora un byte più corto: P)
DJMcMayhem

Mi dimentico sempre -r. Questo mi porta al 46.
Riley l'

5

Brachylog , 19 byte

l⟦k:?z{sĊtᵐ=∧Ċ∋h}ᶠd

Provalo online!

Spiegazione

Brachylog è di solito terribile con gli indici, che di nuovo mostra qui.

Se false.è un output accettabile nei casi in cui non ci sono caratteri adiacenti, questo sarebbe 1 byte in meno sostituendolo ᶠdcon .

l⟦k                      The list [0, …, length(Input) - 1]
   :?z                   Zip the Input with this list
      {         }ᶠd      Find with no duplicates:
            ∧Ċ∋h           The heads of each element of Ċ = [A, B] (i.e. the indexes)…
        Ċtᵐ=               …where the tails of both A and B are equal (i.e. the letters)…
       sĊ                  …and where Ċ = [A, B] is a substring of the Input


4

Cubix, 37 32 31 29 28 byte

Grazie a ETHProductions per avermi indirizzato nella direzione di un salvataggio a tre byte

$uO@(;Usoi?-!w>;.....S_o\;#O

Provalo qui ! Si noti che gli indici di output sono basati su 1 e non in ordine crescente.

Allargato:

      $ u O
      @ ) ;
      U s o
i ? - ! w > ; . . . . .
S _ o \ ; # O . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

Spiegazione

Funziona leggendo il carattere di input per carattere. Per confrontare due caratteri, sottraggiamo semplicemente i loro codici carattere e se il risultato è 0, stampiamo la lunghezza corrente della pila, uno spazio, la lunghezza corrente della pila - 1 e un altro spazio. Quindi ripuliamo un po 'lo stack e iniziamo di nuovo con il ciclo di lettura. Se viene raggiunta la fine della stringa di input, il programma si arresta.


Hmm, se riesci a mantenere la pila abbastanza pulita, potresti essere in grado di usare #per ottenere la lunghezza della pila quando ne hai bisogno. (Inoltre, LOL ;_;nel codice;))
ETHproductions

Un esempio di base (probabilmente non completamente giocato a golf); ethproductions.github.io/cubix/… (Nota: è 1 indicizzato, non 0 indicizzato)
ETHproductions

Grazie per il promemoria. Ho giocato a golf un byte della tua versione e l'ho aggiunto. Potrei essere in grado di ottenere uno o due byte anoter ...
Luca,

Idea: cosa succederebbe se !$winvece facessi !we spostassi parte della logica della quinta riga nella quarta riga? (Non posso provare ora perché sto uscendo dalla porta)
ETHproductions

Ci ho pensato anche io, ma non credo che salverà molti byte. Ci proverò comunque.
Luca,

3

C, 75 byte

i;f(char*s){for(i=0;*s;++s,++i)if(s[1]==*s|(i&&s[-1]==*s))printf("%d ",i);}

Utilizza gli spazi come delimitatori. (Una virgola finale non sembra troppo buona.)

Provalo online!


3

C # , 115 byte


golfed

i=>{var o="";for(int x=1,l=i.Length;x<=l;x++)o+=(x<l&&i[x]==i[x-1])||(x>1&&i[x-1]==i[x-2])?(x-1)+" ":"";return o;};

Ungolfed

i => {
   var o = "";

   for( int x = 1, l = i.Length; x <= l; x++ )
      o += ( x < l && i[ x ] == i[ x - 1 ] ) || ( x > 1 && i[ x - 1 ] == i[ x - 2 ] )
         ? ( x - 1 ) + " "
         : "";

   return o;
};

Leggibile non golfato

i => {
   // List of positions
   var o = "";

   // Cycle through the string
   for( int x = 1, l = i.Length; x <= l; x++ )
      // Check if 'x' is below the string length
      //    and if the current and previous char are the same...
      //    ... or if 'x' is beyong the string length
      //    and the 2 previous chars are the same.
      o += ( x < l && i[ x ] == i[ x - 1 ] ) || ( x > 1 && i[ x - 1 ] == i[ x - 2 ] )

         // If true, add the index to the list of positions...
         ? ( x - 1 ) + " "

         // ...otherwise add nothing
         : "";

   // Return the list of positions.
   return o;
};

Codice completo

using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, String> f = i => {
            // List of positions
            var o = "";

            // Cycle through the string
            for( int x = 1, l = i.Length; x <= l; x++ )
               // Check if 'x' is below the string length
               //    and if the current and previous char are the same...
               //    ... or if 'x' is beyong the string length
               //    and the 2 previous chars are the same.
               o += ( x < l && i[ x ] == i[ x - 1 ] ) || ( x > 1 && i[ x - 1 ] == i[ x - 2 ] )

                  // If true, add the index to the list of positions...
                  ? ( x - 1 ) + " "

                  // ...otherwise add nothing
                  : "";

            // Return the list of positions.
            return o;
         };

         List<String>
            testCases = new List<String>() {
               "ABCDCABCD",
               "AABBCCDD",
               "ABCDDDCBA",
               "",
               "A",
               "AA",
               "AAA",
         };

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

         Console.ReadLine();
      }
   }
}

Uscite

  • v1.0 - 115 bytes- Soluzione iniziale.

Gli appunti

Niente da aggiungere



2

k, 18 byte

{?,/-1 0+/:&:=':x}

Esempi:

k){?,/-1 0+/:&:=':x}"AABCDDDCBAA"
0 1 4 5 6 9 10
k){?,/-1 0+/:&:=':x}"ABCDCBA"
()

La traduzione in qè più facile da capire:

{distinct raze -1 0+/:where not differ x}

Questa era anche la mia soluzione iniziale! : D
zgrep,

2

JavaScript, 52 byte

Grazie @Neil per il golf off 1 byte

x=>x.map((a,i)=>a==x[++i-2]|a==x[i]&&i).filter(a=>a)

Riceve input come un array di caratteri 0 indicizzato
Restituisce l'output come un array 1 indice

Spiegazione

x.map()

Per ogni carattere nella stringa

(a,i)=>(a==x[++i-2]|a==x[i])*i

Se è uguale al carattere precedente o al carattere successivo, restituisce l'indice + 1 altrimenti non restituisce (lascia indefinito nella matrice)

.filter(a=>a)

Rimuovi tutti gli elementi non definiti dall'array risultante

Provalo online!


Salverebbe &&iun byte (...)*i?
Neil,

@Neil && è più veloce di |, il che porterebbe a restituire sempre i
f 11nɛtɪk

0|0&&6è 0, 1|0&&6è 6, 0|1&&6è 6, 1|1&&6è 6. Non è quello che vuoi?
Neil,

Penso che stavo pensando di avere ancora || invece di |
fəˈnɛtɪk,

Ah sì, questo lo spiegherebbe.
Neil,

2

Python 2, 55 54 byte

m=j=0
for i in input():
 if m==i:print~-j,j,
 j+=1;m=i

Provalo online!

Indici di output separati da spazi (si noti che questo visualizza alcuni indici due volte come consentito dall'OP)


1

Perl 5 , 37 byte

35 byte di codice + plflag.

s/(?<=(.))\1|(.)(?=\2)/print pos/ge

Provalo online!

(?<=(.))\1|(.)(?=\2)corrisponderà tra due caratteri (?<=(.))\1ripetuti ( (.)(?=\2)) o prima di un carattere ripetuto ( ).
Quindi, print posstampa la posizione della corrispondenza. ( poscontiene l'indice della corrispondenza corrente se utilizzato in una regex con /gmodificatore).



1

PHP, 100 byte

for(;$i<strlen($s=$argn);$i++)$s[$i]==$s[$i+1]||$s[$i]==$s[$i-1]&&$i?$r[$i]=+$i:0;echo join(",",$r);


1

Lotto, 139 byte

@set/ps=
@set/ai=c=0
:l
@if %s:~,1%==%s:~1,1% set c=2
@if %c% gtr 0 echo %i%
@set/ai+=1,c-=1
@if not "%s:~1%"=="" set s=%s:~1%&goto l

Accetta input su STDIN. Funziona tenendo traccia del numero di numeri da stampare nella cvariabile, che viene reimpostato su 2 quando viene rilevata una coppia. Nota: al costo di 6 byte, potrebbe essere indurito per funzionare con la maggior parte dei caratteri ASCII e non solo ABCD.


1

C #, 89 byte

using System.Linq;s=>string.Join("",s.Skip(1).Select((a,i)=>a==s[i]?i+" "+(i+1)+" ":""));

Se ci sono tre o più caratteri in una riga, gli indici vengono ripetuti. Quale @Comrade SparklePony ha permesso nei commenti.

Programma completo non golfato:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Namespace
{
    class Class1
    {
        static void Main(string[] args)
        {
            Func<string, string> f2 =
                s => string.Join("" ,         //Combine the results into one string
                s.Skip(1)                     //Start with the second element
                .Select(
                    (a, i) =>                 // 'a' is the current element, 'i' is the index of the element in the result of 'Skip'
                    a == s[i] ?               // therefore 's[i]' is the previous element; compare it with the current one
                    i + " " + (i + 1) + " " : //If true, return the indexes
                    ""                        //Otherwise an empty string
                ));

            var tests = new string [] {
               "ABCDCABCD",
               "AABBCCDD",
               "ABCDDDCBA",
               "ABBCDD"
            };

            foreach (var test in tests)
            {
                Console.WriteLine(test);
                Console.WriteLine(string.Join("", f2(test)));
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

1

QBIC , 42 byte

;[2,_lA||~mid$(A,a-1,1)=mid$(A,a,1)|?a-1,a

Uscita campione:

Command line: AADCDBBD
 1             2 
 6             7 

Spiegazione:

;               Get A$ from the cmd line
[2,    |        FOR a% = 2 TO
   _lA|              the length of A$
~mid$(A,a-1,1)  IF the character at index a%
=mid$(A,a,1)    equals the char at index a%-1
|               THEN
?a-1,a          PRINT both indexes, tab-separated
                Any further doubles are printed on a separate line
                The IF and FOR are closed implicitly

EDIT: QBIC ora ha Substring! Questa sfida ora può essere risolta in 32 byte:

;[2,_lA||~_sA,a-1|=_sA,a||?a-1,a

Dove:

_s      This is the substring function; it takes 1, 2 or 3 arguments. 
        Arguments are comma-seperated, the list is delimited with |
        In this answer we see Substring take 2 arguments:
  A,    The string to take from
    a|  Starting position (note:uppercase represents strings, lowercase is for nums)
        Any omitted argument (in this case 'length to take') is set to 1.

0

k, 14 byte

Questa è una funzione, accetta una stringa e restituisce un elenco di indici.

&{x|1_x,0}@=':

Spiegazione:

           =': /compare each letter to the previous, return binary list
 {       }@    
    1_x,0      /shift left
  x|           /combine shifted and unshifted with binary or
&              /get indices of 1s

Provalo online!

Come usare:

&{x|1_x,0}@=':"STRINGGOESHERE"

0

PHP, 70 byte

for(;a&$c=$argn[$i];)$i++&&$argn[$i-2]==$c||$argn[$i]==$c?print$i._:0;

accetta input da STDIN; corri con -R.

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.