Distanza della stringa


28

Sfida

Dato un input di una stringa tutta minuscola [a-z], genera la distanza totale tra le lettere.

Esempio

Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17

Regole

  • Scappatoie standard vietate
  • Questo è - vince la risposta più breve in byte.
  • L'alfabeto può essere attraversato da entrambe le direzioni. Devi sempre usare il percorso più breve. (ovvero la distanza tra xe cè 5).

1

Casi test

Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35

Risposte:


11

Gelatina , 11 8 byte

OIæ%13AS

Salvato 3 byte grazie a @ Martin Ender .

Provalo online! oppure Verifica tutti i casi di test.

Spiegazione

OIæ%13AS  Input: string Z
O         Ordinal. Convert each char in Z to its ASCII value
 I        Increments. Find the difference between each pair of values
  æ%13    Symmetric mod. Maps each to the interval (-13, 13]
      A   Absolute value of each
       S  Sum
          Return implicitly

6
Mi sono imbattuto æ%durante la lettura dei built-in l'altro giorno, ed è stato praticamente creato per questo (tipo di) problema:OIæ%13AS
Martin Ender,

Penso che questo sia 9 byte ( æè due).
Aleksei Zabrodskii,

1
@elmigranto Jelly ha una codepage che codifica ciascuno dei suoi caratteri in un byte: github.com/DennisMitchell/jelly/wiki/Code-page
ruds

10

Haskell, 57 56 byte

q=map$(-)13.abs
sum.q.q.(zipWith(-)=<<tail).map fromEnum

Esempio di utilizzo: sum.q.q.(zipWith(-)=<<tail).map fromEnum $ "valleys"-> 35.

Come funziona:

q=map$(-)13.abs                -- helper function.
                               -- Non-pointfree: q l = map (\e -> 13 - abs e) l
                               -- foreach element e in list l: subtract the
                               -- absolute value of e from 13

               map fromEnum    -- convert to ascii values
      zipWith(-)=<<tail        -- build differences of neighbor elements
  q.q                          -- apply q twice on every element
sum                            -- sum it up

Modifica: @Damien ha salvato un byte. Grazie!


grazie per il trucco della distanza di rotazione ( q.q)
Leif Willerts,

Caspita! Puoi aggiungere mapla definizione di qper un byte in meno
Damien,

@Damien: ben individuato. Grazie!
nimi,

8

MATL , 14 , 10 byte

dt_v26\X<s

Provalo online!

Grazie @Suever per aver salvato 4 byte!

Spiegazione:

d           % Take the difference between consecutive characters
 t_         % Make a copy of this array, and take the negative of each element
   v        % Join these two arrays together into a matrix with height 2
    26\     % Mod 26 of each element
       X<   % Grab the minimum of each column
         s  % Sum these. Implicitly print

Versione precedente:

d26\t13>26*-|s

6

Python 3, 69 68 byte

lambda s:sum([13-abs(13-abs(ord(a)-ord(b)))for a,b in zip(s,s[1:])])

Abbattersi:

lambda s:
         sum(                                                      )
             [                             for a,b in zip(s,s[1:])]
              13-abs(13-abs(ord(a)-ord(b)))

1
Puoi perdere un byte rimuovendo lo spazio primafor
Daniel,

@Dopapp Oh sì, grazie!
busukxuan,

2
È possibile prendere l'input come un elenco di caratteri e utilizzare la ricorsione per salvare 3 byte:f=lambda a,b,*s:13-abs(13-abs(ord(a)-ord(b)))+(s and f(b,*s)or 0)
Jonathan Allan,

5

Java, 126 120 117 byte

int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=(26+z[i]-z[i-1])%26)<14?e:26-e);return r;}

Grazie a @KevinCruijssen per aver segnalato un bug nella versione originale e suggerito di rendere vuoto il for-loop.

L'uso di (26 + z[i] - z[i - 1]) % 26)è ispirato da un commento di @Neil su un'altra risposta. (26 + ...)%26ha lo stesso scopo Math.abs(...)di ...? e : 26 - e.

Ungolfed :

int f(String s) {
    byte[]z = s.getBytes();
    int r = 0, i = 0, e;
    for (; ++i < z.length; r += (e = (26 + z[i] - z[i - 1]) % 26) < 14 ? e : 26 - e);
    return r;
}

Benvenuti nel sito! Che lingua è questa? Quanti caratteri / byte è? Dovresti [edit] those details into the top of your post, with this markdown: #Language, n bytes`
DJMcMayhem

Ok. Grazie. L'ho modificato. Qualche miglioramento? :)
todeale,

1
Ti manca un -prima e enella tua versione non golfata.
Neil,

2
Benvenuti in PPCG! Hmm, sto ricevendo un errore "Tipo non corrispondente: impossibile convertire da int a byte" su e=z[i]-z[i-1];Quindi è necessario un cast (byte)o modificare ein int. Inoltre, è possibile rimuovere le staffe per-loop mettendo tutto all'interno del ciclo for, in questo modo: int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=z[i]-z[i-1])>0?e<14?e:26-e:-e<14?-e:e+26);return r;}(PS: Il invertito il ciclo for è purtroppo la stessa lunghezza: int f(String s){byte[]z=s.getBytes();int r=0,i=z.length-1,e;for(;i>0;r+=(e=z[i]-z[--i])>0?e<14?e:26-e:-e<14?-e:e+26);return r;}.
Kevin Cruijssen

1
Grazie mille @KevinCruijssen: D. Il tuo suggerimento ha aiutato molto.
todeale,

3

JavaScript (ES6), 84 82 79 byte

3 byte salvati grazie a Cyoce:

f=([d,...s],p=parseInt,v=(26+p(s[0],36)-p(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0

Spiegazione:

f=(
  [d,...s],                    //Destructured input, separates first char from the rest
  p=parseInt,                  //p used as parseInt
  v=(26+p(s[0],36)-p(d,36))%26 //v is the absolute value of the difference using base 36 to get number from char
  )
)=>
  s[0]?                        //If there is at least two char in the input
    f(s)                       //sum recursive call
    +                          //added to
    (v>13?26-v:v)              //the current shortest path
  :                            //else
    0                          //ends the recursion, returns 0

Esempio:
Call: f('golf')
Output:17


Soluzioni precedenti:

82 byte grazie a Neil:

f=([d,...s],v=(26+parseInt(s[0],36)-parseInt(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0

84 byte:

f=([d,...s],v=Math.abs(parseInt(s[0],36)-parseInt(d,36)))=>s[0]?f(s)+(v>13?26-v:v):0

1
Invece di Math.abs(...)te puoi usare (26+...)%26; questo funziona perché stai comunque lanciando valori superiori a 13. (Penso che sia così che funziona la risposta MATL.)
Neil,

1
Salvare alcuni byte anteponendo il codice con p=parseInt;e quindi usando p()invece diparseInt()
Cyoce

3

Rubino, 73 byte

->x{eval x.chars.each_cons(2).map{|a,b|13-(13-(a.ord-b.ord).abs).abs}*?+}

2

PHP, 93 byte

for(;++$i<strlen($s=$argv[1]);)$r+=13<($a=abs(ord($s[$i-1])-ord($s[$i])))?$a=26-$a:$a;echo$r;

2

05AB1E , 12 byte

SÇ¥YFÄ5Ø-}(O

Spiegazione

SÇ                   # convert to list of ascii values
  ¥                  # take delta's
   YF    }           # 2 times do
     Ä5Ø-            # for x in list: abs(x) - 13
          (O         # negate and sum

Provalo online!


Sono 12 simboli, non byte. La lunghezza in byte sarebbe 16 per UTF-8.
Aleksei Zabrodskii,

@elmigranto: Anzi. In UTF-8 questo sarebbe il caso, ma 05AB1E utilizza CP-1252 dove questo è di 12 byte.
Emigna,

2

Perl, 46 byte

Include +3 per -p(il codice contiene ')

Fornisci input su STDIN senza newline finale:

echo -n zaza | stringd.pl

stringd.pl:

#!/usr/bin/perl -p
s%.%$\+=13-abs 13-abs ord($&)-ord$'.$&%eg}{

2

Racchetta 119 byte

(λ(s)(for/sum((i(sub1(string-length s))))(abs(-(char->integer
(string-ref s i))(char->integer(string-ref s(+ 1 i)))))))

test:

(f "golf")

Produzione:

17

Versione dettagliata:

(define(f s)
  (for/sum((i(sub1(string-length s))))
    (abs(-(char->integer(string-ref s i))
          (char->integer(string-ref s(+ 1 i)))))))

È possibile sostituire (define(f s)con (lambda(s)2 byte più brevi (le funzioni anonime vanno bene).
fede s.

1
Aspetta, dovrebbe prendere (λ(s)anche la racchetta , che se in utf8 è di 6 byte penso
fede s.

Fatto. Grazie.
anche il

2

C #, 87 85 byte

Soluzione migliorata : sostituito Math.Abs ​​() con il trucco add & modulo per salvare 2 byte:

s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;};

Soluzione iniziale :

s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

Provalo online!

Fonte completa, compresi i casi di test:

using System;

namespace StringDistance
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

            Console.WriteLine(f("golf"));   //17
            Console.WriteLine(f("aa"));     //0
            Console.WriteLine(f("stack"));  //18
            Console.WriteLine(f("zaza"));   //3
            Console.WriteLine(f("valleys"));//35
        }
    }
}

2

In realtà, 21 byte

Basato parzialmente sulla risposta di Ruby di cia_rana .

Si è verificato un errore con O(in questo caso, map ord () su una stringa) in cui non funzionava con d(dequeue bottom element) e p(pop first element) senza prima convertire la mappa in un elenco con #. Questo bug è stato corretto, ma poiché quella correzione è più recente di questa sfida, quindi ho continuato #.

Modifica: il conteggio dei byte è errato da settembre. Ops.

Suggerimenti di golf benvenuti. Provalo online!

O#;dX@pX♀-`A;úl-km`MΣ

Ungolfing

         Implicit input string.
          The string should already be enclosed in quotation marks.
O#       Map ord() over the string and convert the map to a list. Call it ords.
;        Duplicate ords.
dX       Dequeue the last element and discard it.
@        Swap the with the duplicate ords.
pX       Pop the last element and discard it. Stack: ords[:-1], ords[1:]
♀-       Subtract each element of the second list from each element of the first list.
          This subtraction is equivalent to getting the first differences of ords.
`...`M   Map the following function over the first differences. Variable i.
  A;       abs(i) and duplicate.
  úl       Push the lowercase alphabet and get its length. A golfy way to push 26.
  -        26-i
  k        Pop all elements from stack and convert to list. Stack: [i, 26-i]
  m        min([i, 26-i])
Σ        Sum the result of the map.
         Implicit return.

1

Java 7.128 byte

 int f(String s){char[]c=s.toCharArray();int t=0;for(int i=1,a;i<c.length;a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);return t;}

Ungolfed

 int f(String s){
 char[]c=s.toCharArray();
 int t=0;
 for(int i=1,a;
     i<c.length;
   a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);
return t;
 }

1

Pyth, 20 byte

Lm-13.adbsyy-M.:CMQ2

Un programma che accetta l'input di una stringa tra virgolette su STDIN e stampa il risultato.

Provalo online

Come funziona

Lm-13.adbsyy-M.:CMQ2  Program. Input: Q
L                     def y(b) ->
 m      b              Map over b with variable d:
  -13                   13-
     .ad                abs(d)
                CMQ   Map code-point over Q
              .:   2  All length 2 sublists of that
            -M        Map subtraction over that
          yy          y(y(that))
         s            Sum of that
                      Implicitly print

1

dc + od, 65 byte

od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp'

Spiegazione:

Perché in cc non è possibile accedere ai caratteri di una stringa, ho usato od per ottenere i valori ASCII. Questi verranno elaborati in ordine inverso dallo stack (contenitore LIFO) in questo modo:

dsN0sT             # initialize N (neighbor) = top ASCII value, and T (total) = 0
[lNrdsNr-          # loop 'R': calculate difference between current value and N,
                   #updating N (on the first iteration the difference is 0)
   d*vdD[26-]sS<S  # get absolute value (d*v), push 13 (D) and call 'S' to subtract
                   #26 if the difference is greater than 13
   d*vlT+sT        # get absolute value again and add it to T
d0<R]dsR           # repeat loop for the rest of the ASCII values
xlTp               # the main: call 'R' and print T at the end

Correre:

echo -n "golf" | ./string_distance.sh

Produzione:

17

1

C, 82 86 83 76 byte

t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;}

Presuppone che la stringa di input sia lunga almeno un carattere. Questo non richiede#include<stdlib.h>

Modifica: Argh, punti sequenza!

Provalo su Ideone


nel compilatore ideone la stringa "nwlrbb" e tutta la stringa rand provo 6 len restituiscono tutto 0 ma non sembra 0 il risultato ....
RosLuP

si ora sembra ok ...
RosLuP

1

C, 70 byte 76 byte

k,i;f(char *s){for(i=0;*++s;i+=(k=abs(*s-s[-1]))>13?26-k:k);return i;}

1

Scala, 68 byte

def f(s:String)=(for(i<-0 to s.length-2)yield (s(i)-s(i+1)).abs).sum

Le critiche sono benvenute.


1

C #, 217 byte

golfed:

IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}}

Ungolfed:

IEnumerable<int> g(string k)
{
  Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97;
  for (int i = 0; i < k.Length - 1; i++)
  {
    var f = x(k[i]);
    var s = x(k[i + 1]);
    var d = Math.Abs(f - s);
    yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d;
  }
}

Produzione:

aa: 0
stack: 18
zaza: 3
valleys: 35

'a' è 97 quando convertito in byte, quindi 97 viene sottratto da ciascuno. Se la differenza è maggiore di 13 (cioè metà dell'alfabeto), sottrarre le differenze tra ciascun carattere (valore byte) da 26. Un'aggiunta dell'ultimo minuto di "return return" mi ha fatto risparmiare qualche byte!


1
Due spazi bianchi inutili: entrambi prima di "s".
Yytsi,

0

Python 3, 126 byte

Con elenco in comprensione.

d=input()
print(sum([min(abs(x-y),x+26-y)for x,y in[map(lambda x:(ord(x)-97),sorted(d[i:i+2]))for i in range(len(d))][:-1]]))

Bella risposta. È possibile sostituire abs(x-y)da y-xpoiché la chiamata da sortedeffettuare x < y.
todeale,

0

PHP, 79 byte

for($w=$argv[1];$w[++$i];)$s+=13-abs(13-abs(ord($w[$i-1])-ord($w[$i])));echo$s;

0

Java, 109 byte

int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x;
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.