Trova il centro


24

Data una stringa di caratteri ASCII, genera il carattere che si trova nel mezzo. Se non è presente un carattere medio (quando la stringa ha una lunghezza pari), emette il carattere ASCII il cui ordinale è la media al piano dei due caratteri centrali. Se la stringa è vuota, dovrebbe essere emessa una stringa vuota.

Casi test:

12345 => 3

Hello => l

Hiya => q

(empty input) => (empty output)

Vince il programma più breve in caratteri. (Non byte.)

Classifica

Lo snippet di stack nella parte inferiore di questo post genera la classifica dalle risposte a) come un elenco della soluzione più breve per lingua eb) come classifica generale.

Per assicurarti che la tua risposta venga visualizzata, ti preghiamo di iniziare la risposta con un titolo, usando il seguente modello Markdown:

## Language Name, N characters 

dov'è Nla dimensione del tuo invio. Se si migliora il punteggio, è possibile mantenere i vecchi punteggi nel titolo, colpendoli. Per esempio:

## Ruby, <s>104</s> <s>101</s> 96 characters 

Se si desidera includere più numeri nell'intestazione (ad es. Perché il punteggio è la somma di due file o si desidera elencare separatamente le penalità del flag dell'interprete), assicurarsi che il punteggio effettivo sia l' ultimo numero nell'intestazione:

## Perl, 43 + 2 (-p flag) = 45 characters 

Puoi anche rendere il nome della lingua un collegamento che verrà quindi visualizzato nello snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 characters 


15
Di solito calcoliamo il punteggio in byte in modo che le persone non possano comprimere l'intero codice, poiché ciò si traduce in soluzioni noiose. Sei sicuro di volerlo?
Downgoat,

1
@Vɪʜᴀɴ Non penso che sarà un problema qui, poiché le soluzioni saranno comunque molto brevi, quindi la compressione non ne varrà la pena.
Ypnypn,

9
Benvenuti in PPCG! Grande prima sfida!
Conor O'Brien,

2
Possiamo scrivere funzioni?
Downgoat,

10
Suggerimento: codifica le tue risposte in UTF-32. 4 byte per carattere. O forse l'OP dovrebbe semplicemente sbarazzarsi del punteggio del personaggio.
Mego

Risposte:


9

Pyth, 15 byte

Cs.O@R/lz2_BCMz

Dimostrazione

A partire da "Hiya" come input:

              z    "Hiya"                                      Input
            CM     [72, 105, 121, 97]                          Character values
          _B       [[72, 105, 121, 97], [97, 121, 105, 72]]    Pair with reversal
      /lz2         2                                           Halfway index
    @R             [121, 105]                                  That element in each
  .O               113.0                                       Average
 s                 113                                         Floor
C                  "q"                                         Cast to character
                   q                                           Print implicitly

Si noti che ciò si arresta in modo anomalo con un errore nell'input vuoto e non stampa nulla su STDOUT, che è un modo valido per generare una stringa vuota tramite i valori predefiniti di code-golf.


Bifurcate mostra di nuovo la sua utilità.
lirtosiast

whoa bifurcate è fantastico.
Maltysen,

@KenanRhoton In risposta alla modifica proposta, controlla l'impegno che ha aggiunto la Cfunzionalità di pavimentazione: github.com/isaacg1/pyth/commit/0baf23ec Nota il giorno in cui è stato aggiunto, lo stesso giorno in cui è stata posta questa domanda. Questo perché questa domanda mi ha ispirato ad aggiungere quella funzionalità, rendendola non ammissibile per l'uso su questa domanda.
isaacg,

8

Brainf ***, 61 byte

Cinese , 16 caratteri

Ciò richiede che l'input sia compreso nell'intervallo ASCII 1-127 ed è null-terminato. Elimina coppie di caratteri dall'inizio e dalla fine della stringa fino a quando rimangono uno o due caratteri. Se ce ne sono due, li somma insieme, quindi si divide per 2, arrotondando per difetto. Il carattere rimanente viene stampato.

,[>,]<<<[[<]>[-]>[>]<[-]<<<]>[[->+<]>[-[-<+<]>>]<[>]<[>]<<]>.

Provalo su questo interprete .

Dissezione:

,[>,]         Get the null terminated input
<<<           Move to the second last character
[             While there are at least 3 characters
  [<]>           Move to the first character
  [-]            Delete it
  >[>]<          Move to the last character
  [-]            Delete it
  <<<            Move the the third last character
]
>              Move to the second last character
[              If there are two characters remaining
  [->+<]         Add the two characters together
  >[-[-<+<]>>]   Divide the character by 2 rounding down
  <[>]<[>]<<     Move to before the character to exit the if loop
]
>.             Print the remaining character

* Dato che ogni istruzione può essere compressa a 3 bit e codificata in UTF-32, l'intero programma potrebbe essere tecnicamente espresso in 6 caratteri.

EDIT: E grazie a Jan Dvorak per avermi fatto conoscere il cinese , che lo comprime in 16 caratteri, alla pari della risposta CJam di Dennis .

蜐蕈帑聿纂胯箩悚衅鹊颂鹛拮拮氰人

5
Given each instruction could be compressed to 3 bits and encoded in UTF64, the whole program could technically be expressed in 3 characters.Hai vinto. La rete. E tutto il resto.
gatto

1
Non penso sia valido. Il codice sorgente di Brainfuck sono i caratteri +-<>,.[] , in qualunque codifica, non le loro rappresentazioni binarie. Siamo d' accordo sul fatto che una codifica che non può essere utilizzata da un interprete esistente non è valida.
lirtosiast

2
@ThomasKwa, quindi ho dato il mio punteggio principalmente in byte non codificati. La codifica dei personaggi si stava solo unendo all'idea che il punteggio dei personaggi potesse essere abusato.
Hand-E-Food

4
@ThomasKwa: è tempo che alcuni di noi facciano un tale interprete, da usare nelle sfide future. Immagina BF che batte la migliore soluzione di golfscript! :)
vsz


6

CJam, 16 byte

q:i_W%.+_,2/=2/c

Provalo online!

Come funziona

q                e# Read all input.
 :i              e# Cast each character to integer.
   _W%           e# Push a reversed copy.
      .+         e# Perform vectorized addition.
        _,2/     e# Get the length, divided by 2.
            =    e# Select the corresponding sum.
             2/c e# Divide by 2 and cast to character.

9
Perché quasi tutti i golf CJam / Pyth sono 10-30 caratteri, indipendentemente dalla difficoltà? Oo
Zereges,

1
Difficoltà? Questo è un semplice calcolo mediano, meno l'ordinamento ...
Dennis,

4
@Dennis Penso che sia quello che intende. Può avere circa la stessa lunghezza per domande sia più facili che più difficili.
geokavel,

@Zereges Non proprio. 10-30 è tipico per problemi facili. Vedi questo se vuoi un esempio di come cerca qualcosa di più complesso: codegolf.stackexchange.com/a/64086/32852 .
Reto Koradi,

6

TeaScript , 23 byte 25 30 31 33

²(x[t=xn/2]c+xv[t]c)/2)

Usa l'idea di @ isaacg di invertire la stringa.

Provalo online

Prova tutti i casi

Ungolfed && Explanation

TeaScript è ancora JavaScript, quindi funziona in modo molto simile a JavaScript.

C((x[t=xn/2]c+xv[t]c)/2)

C((           // Char code to char
   x[t=xn/2]c // Floored center
   +          // Add to
   xv[t]c     // Ceil'd center
  ) / 2)      // Divide by 2

5
Quella crenatura ...
Lirtosiast

10
Quell'intestazione è rad. Voglio quell'intestazione per ogni maledetta lingua.
gatto

Sì, tranne la crenatura.
cat

@sysreq lol, aveva a che fare con il fatto che sto usando un font diverso, corretto.
Downgoat,


5

Matlab, 39 37 byte

floor((end+[1,2])/2) restituisce i due indici centrali della stringa se la lunghezza è pari e restituisce l'indice medio due volte se la lunghezza è dispari.

mean restituisce semplicemente la media di questi valori e char la pavimenta automaticamente.

@(s)char(mean(s(floor(end/2+[.5,1]))))

5

8086 codice macchina + DOS, 31 byte

hexdump:

BA 1E 01 B4 0A CD 21 8B F2 46 8A 1C D0 EB 8A 50
01 72 06 74 08 02 10 D0 EA B4 02 CD 21 C3 FF

Codice sorgente assembly (può essere assemblato con tasm):

    .MODEL TINY

    .CODE
    org 100h

    MAIN PROC

    mov dx, offset buf
    mov ah, 10      ; DOS function "read string"
    int 21h

    mov si, dx
    inc si          ; si now points to the length of the string
    mov bl, [si]    ; 
    shr bl, 1       ; divide the length by 2
    mov dl, [si+bx+1] ; load the middle char
    jc calc_done    ; if length was odd - done
    jz output_done  ; if length was zero - exit
    add dl, [si+bx] ; add the other middle char
    shr dl, 1       ; divide by 2
calc_done:
    mov ah, 2       ; DOS function "output char"
    int 21h
output_done:
    ret

buf db 255          ; maximum bytes to input

    MAIN ENDP
    END MAIN

C'è un uso delicato del registro FLAGS qui. Dopo aver spostato la lunghezza della stringa a destra di 1 bit (che equivale alla divisione per 2), due flag memorizzano ulteriori informazioni:

  • Porta bandiera: contiene il bit che è stato spostato. Se il bit è 1, la lunghezza era dispari.
  • Flag zero: mostra se il risultato è zero. Se il flag carry è 0 e il flag zero è 1, la lunghezza era zero e non deve essere stampato nulla.

Normalmente, i flag dovrebbero essere controllati immediatamente, ma qui uso il fatto che l' movistruzione non cambia i flag. Quindi possono essere esaminati dopo aver caricato il carattere centrale.


4

Python 3, 61 59 57 55 byte

Cerco di non giocare a golf con le lingue in cui lavoro, ma questo non è troppo male.

Grazie a @xsot per 2 byte!

lambda x:chr((ord(x[len(x)//2])+ord(x[~len(x)//2]))//2)

Il programma completo è di 59 byte:

x=input()
l=len(x)//2
print(chr((ord(x[l])+ord(x[~l]))//2))

Provalo qui .


Ah, mi hai battuto su quello che sarebbe stato il mio prossimo compito (se non avessi trovato 10 byte da radere)
gatto

No, no, 10 byte per radere via la mia soluzione Go da 166 byte. Il tuo è molto più elegante, tuttavia.
gatto

@sysreq Ah, ho capito male. E grazie.
lirtosiast

-1-len(x)//2è equivalente a ~len(x)//2causa del modo in cui la divisione del piano funziona su numeri interi negativi.
xsot,

@xsot Grazie — rende il codice un po 'più cattivo però :)
lirtosiast

4

Prolog, 111 byte

Codice

p(X):-atom_codes(X,L),length(L,N),I is N//2,J is(N-1)//2,nth0(I,L,A),nth0(J,L,B),Q is(A+B)//2,writef('%n',[Q]).

spiegato

p(X):-atom_codes(X,L),       % Convert to list of charcodes
      length(L,N),           % Get length of list
      I is N//2,             % Get mid index of list
      J is(N-1)//2,          % Get 2nd mid index of list if even length
      nth0(I,L,A),           % Get element at mid index
      nth0(J,L,B),           % Get element at 2nd mid index
      Q is(A+B)//2,          % Get average of elements at mid indices
      writef('%n',[Q]).      % Print as character

Esempi

>p('Hello').
l

>p('Hiya').
q

4

R , 73 byte

function(x,y=utf8ToInt(x),n=sum(1|y))if(n)intToUtf8(mean(y[n/2+c(1,.5)]))

Provalo online!

Mille grazie a @ngm per aver pensato a questa idea non ricorsiva - ha permesso di giocare a golf a 20 byte.

Vecchia soluzione:

R , 101 95 byte

"!"=function(x,n=sum(1|x))"if"(n<3,mean(x),!x[-c(1,n)])
try(intToUtf8(!utf8ToInt(scan(,""))),T)

Provalo online!

Soluzione ricorsiva. È stato corretto un problema al prezzo di 2 byte:

  • aggiunto try(expr, silent = TRUE)per gestire correttamente il caso in cui l'input è vuoto.

grazie Giusppe per 4 byte!


non intToUtf8tronca i non interi?
Giuseppe,

@Giuseppe hai ragione come sempre :)
JayCe

92 byte soluzione non ricorsiva.
ngm

82 byte Preferirei che lo pubblichi come una risposta separata - è totalmente diverso dalla mia risposta!
JayCe,

Beh, non me ne sarei mai inventato se non avessi messo lo sforzo originale. E la mia risposta è stata una porta della migliore risposta Pyth che ha ottenuto il voto. Con un sacco di trucchi, noi R siamo venuti fuori. E poi l'hai reso più breve. Quindi vai avanti e fai il montaggio con la coscienza pulita!
ngm

4

Buccia , 11 byte

c½S¤+öc→←½↔

Provalo online!

Spiegazione

Combinatori deliziosi, deliziosi fino in fondo. öè "componi queste quattro funzioni", ¤è "applica il primo argomento ai risultati dell'applicazione del secondo argomento a due argomenti aggiuntivi separatamente", Sè "applica questa funzione (che dovrebbe prendere due argomenti) al Sterzo argomento e al risultato di applicare Sil secondo argomento al suo terzo ". Perciò,

   Function       Type                Semantics
     öc→←½        [TChar]->TInt       ASCII code of middle (floored) char in string
   ¤+öc→←½        [TC]->[TC]->TI      Sum of ASCII codes of middle of two strings
  S¤+öc→←½↔       [TC]->TI            Sum of ASCII codes of the middle of a string and its reverse
c½S¤+öc→←½↔       [TC]->TC            ASCII character represented by half the above, QEF

Modificato per aggiungere: a rigor di termini, questo non riesce a conformarsi leggermente alla specifica del problema, che richiede una stringa nel caso di un input vuoto e un carattere in altri casi.

A causa della tipizzazione rigorosa di Husk, non è possibile definire una funzione / programma che può restituire uno dei due tipi. Ho scelto di restituire un singolo carattere in tutti i casi, e per Husk, la scelta più ragionevole per un singolo carattere per rappresentare la stringa vuota è '(space)'perché questo è il valore "predefinito" (e in effetti, è per questo che questo programma lo restituisce; l'impostazione predefinita viene utilizzato quando si prende l'ultimo ( ) elemento di un elenco vuoto).

Avrei potuto ragionevolmente anche scegliere di restituire stringhe di zero o di un carattere, il che avrebbe fallito la specifica nell'altra direzione, ma non l'ho fatto perché aggiunge quattro byte:, Ṡ&ö;c½S¤+öc→←½↔con la ;conversione del carattere in una stringa di un carattere, un altro öcomporre esplicitamente il necessario e un Ṡ&collegamento in caso di input errato.


3

C ++ 14, 56 byte

[](auto s){int l=s.size();return(s[(l-1)/2]+s[l/2])/2;};

Lambda anonimo che prende la stringa come argomento e restituisce int come codice char. Per "", ritorna 0. Non sono sicuro di come dovrebbero essere esattamente l'input e l'output (non è specificato nella domanda).

Ungolfed, con uso

#include <string>
int main()
{
    auto lmbd = [](auto str)
    {
        int len = str.size();
        return (str[(len - 1) / 2] + str[len / 2]) / 2;
    };

    std::cout << (char) lmbd("Hiya"s) << std::endl; // outputs q
}

@ CᴏɴᴏʀO'Bʀɪᴇɴ fatto.
Zereges,

Non penso che tu possa emettere con il codice carattere, e non penso che tu possa emettere 0neanche per "".
lirtosiast

Sarebbe bello avere regole apparenti.
Zereges,


3

JavaScript (ES6), 83 byte 89 91

Salvato 2 byte grazie a @ Cᴏɴᴏʀ O'Bʀɪᴇɴ

6 byte salvati grazie a @ETHproductions

s=>String.fromCharCode((s[~~(t=s.length/2-.5)][q='charCodeAt']()+s[0|t+.9][q]())/2)

JavaScript non è affatto buono in questo codice char stringa.


Mi hai battuto sul tempo. Vabbè, il minimo che posso fare è aiutarti;) s=>String.fromCharCode((s[~~(t=s.length/2-.5)][r="charCodeAt"]()+s[Math.ceil(t)][r])/2)è più corto di 5 byte.
Conor O'Brien,

@ CᴏɴᴏʀO'Bʀɪᴇɴ Sweet. Ho bisogno del ()giro charCodeAtquindi sono davvero 3 caratteri, ma grazie comunque!
Downgoat,

@ ן nɟuɐɯɹɐ ן oɯ se tè un numero intero che non funziona
Downgoat

Math.ceil(t)può essere modificato in0|t+.9
ETHproductions

@ETHproductions grazie, che ha salvato 6 byte!
Downgoat,


2

Minkolang 0.13, 23 20 bytes

$oI2$%d$z,-Xz3&+2:O.

Try it here.

Explanation

$o        Read in the whole stack as characters
I2$%      Push I,2, then pop them and push I//2,I%2
d$z       Duplicate top of stack (I%2) and store in register (z)
,-X       <not> the top of stack, subtract, and dump that many off the top of stack
z3&       Retrieve value from register and jump 3 spaces if this is not zero
   +2:    Add and then divide by 2
O.        Output as character and stop.

1
hiya returns i instead of q
Downgoat

@Vɪʜᴀɴ: OH. I misread it. I thought the question was asking for the character in the middle, going to the floored average position if the length was even.
El'endia Starman

@ThomasKwa: Fixed.
El'endia Starman

@Vɪʜᴀɴ: ^ Fixed.
El'endia Starman

2

Japt, 40 29 23 21 20 bytes

Saved 4 bytes thanks to @ןnɟuɐɯɹɐןoɯ

Now only half the original length! I love code golf. :-D

UcV=K*Ul)+Uw cV)/2 d

Works properly on the empty string. Try it online!

How it works

          // Implicit: U = input string, K = 0.5
Uc        // Take the char-code at position
 V=K*Ul   //  V = 0.5 * length of U
+         //  (auto-floored), plus
Uw cV     //  the char-code at position V (auto-floored) in the reversed string,
/2 d      //  divide by 2, and turn back into a character (auto-floored).
          // Implicit: output last expression

As you can see, it uses a lot of auto-flooring. (Thanks, JavaScript!) Suggestions welcome!


The reverse thing is brilliant +1
Downgoat

Couldn't you just do V=Ul /2;((UcV +Uw cV )/2 d?
Mama Fun Roll

@ןnɟuɐɯɹɐןoɯ Well, duh :P I've used c so many times without an argument that I forgot it accepted one. Thanks!
ETHproductions

2

Go, 166 156 153 bytes

Go may not be the best language for golfing... but I love it, so so much, and I'm learning it, so there.

This implementation accepts blank (\n) input and will probably break with non-ASCII/ASCII-extended input. However, OP has not specified input/output encoding thus ASCII is all I've explicitly supported.

Edit: turns out if/else is shorter than switch. Now I know, I suppose.

Golfed:

package main;import ."fmt";func main(){a:="";_,_=Scanln(&a);if b:=len(a);b>0{x:=b/2;if b%2==0{Printf("%c",(a[x]+a[x+1])/2)}else{Println(string(a[x]))}}}

Ungolfed:

package main # everything in go is a package.

import . "fmt" # the dot allows for absolute package method references 
# (think "from string import *" in python)

func main() {
    a := ""
    _, _ = Scanln(&a) # a pointer to a
    if b := len(a); b > 0 { # if statements allow local assignment statements
        x := b / 2
        if b%2 == 0 { # modulo 2 is the easiest way to test evenness
#in which case, average the charcodes and print the result
            Printf("%c", (a[x]+a[x+1])/2)
        } else {
# else just find the middle character (no rounding needed; integer division in Go always results in an integer)
            Println(string(a[x]))
        }
    }
}


2

C#, 77 bytes

s=>{int n=s.Length;return n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2);};

It doesn't actually return a string, and you'll get a space character if the input string is empty because the function must always return a value. 2 more bytes would be needed to return a string.

Full program with test cases:

using System;

namespace FindTheCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,char>f= s=>{int n=s.Length;return n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2);};   //77 bytes
            Console.WriteLine(f(""));
            Console.WriteLine(f("Hello"));
            Console.WriteLine(f("Hiya"));
        }
    }
}

Alternatively, a full program which reads user input and prints the center of the entered string:

C#, 144 bytes

using C=System.Console;class P{static void Main(){var s=C.ReadLine();int n=s.Length;C.Write(n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2));}}

Again, it uses the same trick of printing a space character, which the user will not notice, and not an empty string, otherwise the solution is 2 bytes longer.


2

Vim, 38 24 23 keystrokes

Because vim has a built in function to find the middle line but not the middle char, we split every character on a separate line first using substitute, find the middle line, then delete everything after and before it.

:s/\./\0\r/g<cr>ddMjdGkdgg

If you want to run this, beware of .vimrc files which may change the behavior of . (magic regex) and g (gdefault). Note that it actually saves me 3 keystrokes on my machine :)

Previous answer

:exe 'norm '.(virtcol('$')/2).'|d^ld$'

Takes a one line buffer as input, updates the current buffer with the middle character. I thought there would have been a shortcut for this in vim!

Note: a potentially shorter solution seems to cause an infinite loop... If someone has an idea: qq^x$x@qq@qp (12 keystrokes) - it works with <c-c> after the last @q...


1

Mathematica, 118 99 chars

Floor
If[#=="","",FromCharacterCode[%@Mean@#[[Ceiling[l=Length@#/2];;%[l+1]]]&@ToCharacterCode@#]]&

Mma character code manipulation is pricey...


This function only works once, unless you repeat the entire code each time you want to call it. The point of function submissions is for them to be reusable. Calling your function breaks the value of the global % which it relies on.
Martin Ender

1
Why not use the shortened forms of Floor and Ceiling?
DavidC

1

VBA, 130 Bytes

Function a(q)
h=Len(q):a=Mid(q,(h)/2,2)
If h Mod 2=0 Then:a=Chr((Asc(Left(a,1))+Asc(Right(a,1)))\2):Else:a=Right(a,1)
End Function

Finds the Middle 2 Characters.
If number of Characters is Odd then get the Right of the Middle 2 which will be the true middle as we rounded down.
If not sum the ASCII asc() values of the 2 Characters divided by 2 and return the ASCII Character chr() based on that value.

I think I can golf away one of the asc() calls, but couldn't get it to work shorter.



1

><>, 24 + 3 (for -s) = 27 bytes

l1+l4(*9$.~{~
;
o;
+2,o;

Old solution (Doesn't work for empty input):

l3(?v~{~
?vo;>l2=
;>+2,o

Both take input on the stack through -s. Both are 24 bytes.

Try it online here.


1

pb, 83 bytes

^<b[1]>>>w[B!0]{<w[B!0]{t[B]<b[T]>>}<b[0]<b[0]<[X]>>}w[B=0]{<}t[B]<[X]t[B+T]vb[T/2]

While there are at least 3 characters in the input string, the first and last are removed. This leaves either 1 character (should be printed unmodified) or 2 (should be averaged and printed). To handle this, the first and last characters of the string are added together and divided by two. If there was only one character, (a+a)/2==a. If there was two, (a+b)/2 is the character that needs to be printed. pb "borrows" Python's expression evaluation (def expression(e): return eval(e, globals())) so this is automatically floored.

Handling empty input costs me 5 bytes. Specifically, <b[1]> on the first line. Earlier, when I said "string", that was a total lie. pb doesn't have strings, it has characters that happen to be close to each other. Looking for the "last character of a string" just means moving the brush to the left until it hits a character. When no input is provided, the "while there are at least 3 characters" loop is skipped entirely and it starts looking for the last character. Without that <b[1]>, it would keep looking forever. That code puts a character with a value of 1 at (-1, -1) specifically to be found when the input is empty. After finding the "last character" of the string the brush assumes the first one is at (0, -1) and goes there directly, finding a value of 0. (1+0)/2 is 0 in pb, so it prints a null character.

But monorail, that's still printing! The challenge specification says (empty input) => (empty output)! Isn't printing a null character cheating? Also, this is unrelated, but you are smart and handsome.

Thanks, hypothetical question-asker. Earlier, when I said "print", that was a total lie. In pb, you don't really print values, you just place them on the canvas. Rather than "a way to output", it's more accurate to imagine the canvas as an infinitely large 2D array. It allows negative indices in either dimension, and a lot of programming in pb is really about making sure the brush gets to the location on the canvas that you want it. When the program finishes executing, anything on the canvas with non-negative X and Y coordinates is printed to the appropriate location on the console. When the program begins, the entire canvas is filled with values of 0. In order to not have to print an infinite number of lines, each with an infinite number of null bytes, each line of output is only printed up to the last nonzero character, and lines are only printed up to the last one with a nonzero character in it. So putting a 0 at (0, 0) is still an empty output.

Ungolfed:

^<b[1]>                # Prevent an infinite loop on empty input

>>w[B!0]{              # While there are at least 3 chars of input:

    <w[B!0]{              # Starting at the second character:
            t[B]<b[T]>>         # Copy all characters one position to the left
                                # (Effectively erasing the first character)
    }

    <b[0]<b[0]            # Delete both copies of the last character

    <[X]>>                # Get in place to restart loop
}

w[B=0]{<}                 # Go to last character of remaining string
t[B]<[X]t[B+T]            # Find it plus the first character
vb[T/2]                   # Divide by 2 and print

1

Seriously, 22 20 bytes

,O3 >WXXaXa3 >WXkæ≈c

Thanks @Mego for being great at your language

Try it online or whatever


1
This fails for empty input. I have a deleted 20-byte solution which I'm also trying to fix for empty input.
lirtosiast

,;``@(lIƒ will leave you with the input value on the stack if its len is > 0, or terminate the program otherwise. Note that there's an unprintable in the backticks - character 127.
Mego

@Mego This doesn't seem to be working.
phase

@phase You gotta quote strings for input. This works.
Mego

@Mego What is the ƒ supposed to do?
phase

1

CoffeeScript, 104 103 bytes

f=(x)->((y=x.length)%2&&x[y//2]||y&&String.fromCharCode (x[y/=2][z='charCodeAt']()+x[y-1][z] 0)//2)||''

1

Ruby, 43 42 41 bytes

->a{s=a.size;puts s<1?'':s%2<1??q:a[s/2]}

42 bytes

->a{s=a.size;puts s==0?'':s%2<1??q:a[s/2]}

43 bytes

->a{s=a.size;puts s==0?'':s%2<1?'q':a[s/2]}

Usage:

->a{s=a.size;puts s<1?'':s%2<1??q:a[s/2]}['12345']
=> 3

1

Java 7, 152 bytes

String c(String s){char[]a=s.toCharArray();int l=a.length,x,y;return l<2?s:""+(l%2>0?a[l/2]:(char)((x=a[l/2])>(y=a[(l/2)-1])?y+((x-y)/2):x+((y-x)/2)));}

Ungolfed & test cases:

Try it here.

class M{
  static String c(String s){
    char[] a = s.toCharArray();
    int l = a.length,
            x,
            y;
    return l < 2
            ? s
            : "" + (l%2 > 0
                     ? a[l/2]
                     : (char)((x = a[l/2]) > (y = a[(l/2)-1])
                                ? y + ((x-y)/2)
                                : x + ((y-x)/2)));
  }

  public static void main(String[] a){
    System.out.println(c("12345"));
    System.out.println(c("Hello"));
    System.out.println(c("Hiya"));
    System.out.println(c(""));
    System.out.println(c("x")); // Additional test case that will fail on some other answers
  }
}

Output:

3
l
q
(empty output)
x

1

PHP, 147 93 bytes

Credits and special thanks to Jörg Hülsermann for golfing my answer 54 bytes down!

<?=($l=strlen($s=$argv[1]))%2?$s[($l-1)/2]:chr(floor((ord($s‌​[$l/2])+ord($s[$l/2-‌​1]))/2));

Previous version:

$s=$argv[1];$l=strlen($s);echo($l%2!=0?substr($s,$n=($l-1)/2,-$n):chr(floor(abs((ord($x=substr($s,$l/2-1,1))-ord(substr($s,$l/2,1)))/2))+ord($x)));

Testing code:

$argv[1] = 'Hiya';
$s=$argv[1];
$l=strlen($s);
echo($l%2!=0?substr($s,$n=($l-1)/2,-$n):chr(floor(abs((ord($x=substr($s,$l/2-1,1))-ord(substr($s,$l/2,1)))/2))+ord($x))); 

Test online

I have the feeling that this can be improved, but not enough time for it...


<?=($l=strlen($s=$argv[1]))%2?$s[($l-1)/2]:chr(floor((ord($s[$l/2])+ord($s[$l/2-1]))/2)); is my proposal
Jörg Hülsermann

@JörgHülsermann Brilliant golfing! You should post it as your own answer. If I have time I will golf my answer more with your nice solutions. Thanks.
Mario

Feel free to take it as your answer
Jörg Hülsermann

1

Excel, 122 79 bytes

Actually @Sophia Lechner's answer now:

=IFERROR(CHAR(CODE(MID(A8,LEN(A8)/2+.5,1))/2+CODE(MID(A8,LEN(A8)/2+1,1))/2),"")

-5 bytes from initial solution thanks to @Taylor Scott.

=IFERROR(IF(ISODD(LEN(A1)),MID(A1,LEN(A1)/2+1,1),CHAR((CODE(MID(A1,LEN(A1)/2,1))+CODE(MID(A1,LEN(A1)/2+1,1)))/2)),"")

12 bytes needed for Empty String.


Drop Average(...,...) and use (...+...)/2 for -5 bytes. =IFERROR(IF(ISODD(LEN(A1)),MID(A1,LEN(A1)/2+1,1),CHAR((CODE(MID(A1,LEN(A1)/2,1))+CODE(MID(A1,LEN(A1)/2+1,1)))/2)),"")
Taylor Scott

Excel will accept (and floor) a non-integer second argument to MID, so you don't have to split it into cases - =IFERROR(CHAR(CODE(MID(A1,LEN(A1)/2+1,1))/2+CODE(MID(A1,LEN(A1)/2+.5,1))/2),"") for 79 bytes
Sophia Lechner
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.