Onde estão os caracteres adjacentes no título? [3, 4]!


21

Título com erros ortográficos de propósito. Leia mais para descobrir o porquê.

Sua tarefa: dada uma sequência ou lista delimitada, incluindo os caracteres A,B,C,D, produza os índices de todos os caracteres iguais adjacentes. A saída pode ser várias cadeias / números inteiros em várias linhas, uma lista / matriz ou uma cadeia delimitada.

Toda saída deve estar em uma lista ou sequência, ou em várias linhas impressas. Cada linha impressa, se houver várias, deve conter apenas 1 sequência ou número. Trailing whatevers estão bem.

Métodos padrão de entrada / saída. Aplicam-se brechas padrão.

Por exemplo, a entrada 'ABCDDCBA'deve gerar 3,4ou 4,5, dependendo de estar indexada de 0 a 1, porque esses números são os índices de De o Dpróximo a ele.

Casos de teste:

Os casos de teste têm entrada fornecida como uma única sequência e saída como uma ,sequência delimitada. As saídas são indexadas em 0, adicione 1 a cada item gerado para que seja indexado em 1.

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'

Isso é , então o código mais curto vence!


Podemos ter um delimitador à direita na saída?
— Business Cat

@BasicSunset Sure
— Camarada SparklePony

11
@ JonathanAllan Tudo bem, porque ele gera apenas uma lista.
— precisa saber é o seguinte

2
Os índices de caracteres consecutivos podem aparecer várias vezes? Por exemplo, para o terceiro caso de teste, também é 3,4,4,5válido?
— Lucas

11
Você pode adicionar um caso de teste que não possui correspondências simétricas? Por exemploAABBCD -> 1,2,3,4
— Riley

Respostas:


5

MATL , 8 7 bytes

d~ftQvu

A saída é baseada em 1.

Experimente online!

Explicação com exemplo

Considere entrada '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 bytes

Economizou 6 bytes graças a Martin Ender

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

Produz uma lista de índices separados por avanço de linha.

Experimente online!

Explicação

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

O transliterado é executado do mesmo caractere em dois pontos, para marcar as posições em que existem caracteres duplicados.

:
$.`¶

Em seguida, substitua cada dois pontos pelo comprimento do texto antes dele, seguido por um avanço de linha.

T`L

Por fim, exclua as letras restantes.


7

Geléia , 7 bytes

JṁŒgḊÐf

Baseado em 1; retorna uma lista de listas de execuções de índices, conforme permitido pelo OP.

Experimente online!

Quão?

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
ṁ- Coisas que eu gostaria que o 05AB1E fizesse por 500, por favor.
— Magic Octopus Urn

11
Sinto cada vez mais que essa linguagem é como trapacear aqui. : D
— Avamander

@ComradeSparklePony por que desfazer a verificação de aceitação?
— Jonathan Allan

7

Brain-Flak , 57 46 bytes

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

Inclui +2 para -ar

Usa indexação baseada em 0.

Experimente 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 bytes

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

Função pura que retorna as posições indexadas em 1 de caracteres adjacentes a um caractere idêntico.

Explicação:

StringPosition["string","sub"]fornece uma lista das posições de caracteres inicial e final nas quais "sub"aparece como uma substring de "string". x_~~x_é um StringExpressionque corresponde a dois caracteres idênticos adjacentes. Por exemplo, StringPosition["ABCDDDCBA",x_~~x_]dá {{4, 5}, {5, 6}}. A aplicação Unionjunta as listas, classifica e exclui duplicatas.


5

Flak cerebral , 69, 59 , 56 bytes

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

Experimente online!

+2 bytes para os -arsinalizadores que ativam a entrada ASCII e invertem a pilha.

Usa indexação baseada em 0. Economizei 10 bytes, reduzindo minha redundância push-pop . Economizou outros 4 bytes alternando da indexação baseada em 1 para 0.

Este é praticamente o único desafio baseado em cordas em que o cérebro é bom. Isso ocorre porque o cérebro é ótimo na comparação de caracteres consecutivos, mesmo que seja horrível no processamento de strings em geral. Aqui está a versão legível do código com comentários para explicar como ele funciona:

#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 fixed! (E ainda um byte mais curto: P)
— DJMcMayhem

Eu sempre esqueço -r. Isso me traz para baixo a 46.
— Riley

5

Braquilog , 19 bytes

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

Experimente online!

Explicação

O Brachylog geralmente é terrível com índices, o que novamente mostra aqui.

Se false.for uma saída aceitável nos casos em que não houver caracteres adjacentes, isso seria 1 byte a menos substituindo ᶠdpor ᵘ.

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 bytes

Agradeço a ETHProductions por me apontar na direção de uma economia de três bytes

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

Experimente aqui ! Observe que os índices de saída são baseados em 1 e não em ordem crescente.

Expandido:

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

Explicação

Isso funciona lendo o caractere de entrada por caractere. Para comparar dois caracteres, simplesmente subtraímos seus códigos de caracteres e, se o resultado for 0, imprimimos o comprimento atual da pilha, um espaço, o comprimento atual da pilha - 1 e outro espaço. Depois limpamos um pouco a pilha e começamos novamente com o loop de leitura. Se o final da string de entrada for atingido, o programa será interrompido.


Hmm, se você conseguir manter a pilha razoavelmente limpa, poderá usar #para obter o comprimento da pilha quando precisar. (Também, LOL'ed no ;_;no código;))
— ETHproductions

Um exemplo básico (provavelmente não totalmente jogado); ethproductions.github.io/cubix/… (Nota: está indexado 1, não indexado 0)
— ETHproductions

Obrigado pela lembrança. Joguei um byte da sua versão e adicionei isso. Eu posso ser capaz de obter byte anoter ou dois ...
— Luke

Ideia: o que se fez !$wem vez de !we mudou-se parte da quinta lógica linha para a quarta linha? (Não pode tentar agora porque eu estou indo para fora da porta)
— ETHproductions

Também pensei nisso, mas não acho que ele economize muitos bytes. Eu vou tentar embora.
— Luke

3

C, 75 bytes

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

Usa espaços como delimitadores. (Uma vírgula à direita não parece muito boa.)

Experimente online!


3

C # , 115 bytes


Golfe

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

Ungolfed legible

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

Código 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();
      }
   }
}

Lançamentos

  • v1.0 - 115 bytes- Solução inicial.

Notas

Nada para adicionar



2

k, 18 bytes

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

Exemplos:

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

A tradução para qé mais fácil de entender:

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

Esta foi a minha solução inicial também! : D
— zgrep 13/04

2

JavaScript, 52 bytes

Obrigado @ Neil por jogar fora 1 byte

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

Recebe entrada como uma matriz indexada de 0 caracteres
Retorna a saída como uma matriz indexada 1

Explicação

x.map()

Para cada caractere na sequência

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

Se for igual ao caractere anterior ou ao próximo caractere, retorne o índice + 1, caso contrário, não retorne (folhas indefinidas na matriz)

.filter(a=>a)

Remova todos os elementos indefinidos da matriz resultante

Experimente online!


Você &&isalvaria um byte (...)*i?
— 1111 Neil

@Neil && é mais rápido do que |, o que resultaria em que sempre retornando i
— fənɛtɪk

0|0&&6é 0, 1|0&&6é 6, 0|1&&6é 6, 1|1&&6é 6. Não é isso que você quer?
— 1111 Neil

Eu acho que estava pensando que ainda tinha || em vez de |
— fənɛtɪk

Ah sim, isso explicaria isso.
— 1111 Neil

2

Python 2, 55 54 bytes

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

Experimente Online!

Gera índices separados por espaços (observe que isso exibe alguns índices duas vezes o permitido pelo OP)


1

Perl 5 , 37 bytes

35 bytes de código + plsinalizadores.

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

Experimente online!

(?<=(.))\1|(.)(?=\2)corresponderá entre dois caracteres repetidos ( (?<=(.))\1) ou antes de um caractere repetido ( (.)(?=\2)).
Em seguida, print posimprime a posição da partida. ( poscontém o índice da correspondência atual quando usado em uma regex com /gmodificador).



1

PHP, 100 bytes

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

Lote, 139 bytes

@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

Recebe entrada em STDIN. Funciona acompanhando quantos números imprimir na cvariável, que é redefinida para 2 quando um par é detectado. Nota: A um custo de 6 bytes, pode ser reforçado para trabalhar com a maioria dos caracteres ASCII e não apenas ABCD.


1

C #, 89 bytes

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

Se houver três ou mais caracteres seguidos, os índices serão repetidos. Que @Comrade SparklePony permitiu nos comentários.

Programa completo não destruído:

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 bytes

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

Saída de amostra:

Command line: AADCDBBD
 1             2 
 6             7 

Explicação:

;               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 agora tem Substring! Este desafio agora pode ser resolvido em 32 bytes:

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

Onde:

_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 bytes

Esta é uma função, recebe uma sequência e retorna uma lista de índices.

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

Explicação:

           =': /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

Experimente online!

Como usar:

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

0

PHP, 70 bytes

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

recebe entrada do STDIN; corra com -R.

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.