"abc" e "cba"


28

Il tuo compito è semplice, scrivi un singolo frammento di codice che quando eseguito in una lingua genera solo la stringa 'abc'e quando eseguito in un'altra lingua produce solo la stringa 'cba'. Il programma non dovrebbe ricevere input.

Questa è una sfida di .


4
Non penso che questo sia un imbecille. Il fatto che la stringa sia invertita è abbastanza diverso dalla stampa di due stringhe diverse. Non riaprirò, però, poiché ciò avrebbe effetto immediato
Luis Mendo,

4
Ho votato per riaprire questo post, perché la stampa IMO sul retro di una stringa e una stringa è molto diversa da 2 diverse. Nessuna risposta può essere banalmente modificata per rispondere a questa sfida. La mia risposta usa una tecnica di simmetria inversa rispetto alle risposte lì. Sono d'accordo con @LuisMendo.
Mr. Xcoder,

2
Puoi stampare ABCinvece diabc
Oliver Ni il

5
Voto per riaprire, alcune risposte usano il fatto che cbaè al contrario abc; link , link , link , link , link , link , link , link , link
Oliver Ni

2
'ABC'ed 'CBA'è ok, portando / trascinando spazi bianchi / newline ok ma deve essere lo stesso per entrambi gli output
Chris_Rands

Risposte:



21

MATLAB / Octave, 41 byte

disp(flip('abc',size(randsample(2,2),2)))

In MATLAB randsample(2,2)dà un vettore 2 × 1, così size(...,2)è 1. flipViene quindi applicato lungo la prima dimensione, che è un singleton, quindi 'abc'viene visualizzata la stringa originale :

enter image description here

In Octave randsample(2,2)dà un vettore 1 × 2, così size(...,2)è 2. flipViene quindi applicato lungo la seconda dimensione, ovvero la stringa viene capovolta da sinistra a destra:

enter image description here


Penso che questo sarebbe di qualche byte in meno se si utilizza la versionvariante meno interessante .
Stewie Griffin,

@StewieGriffin Grazie. Penso che sia troppo tardi per cambiare adesso. Forse pubblicalo tu stesso?
Luis Mendo,

No, è una versione noiosa di questo ... Inoltre, non ho più MATLAB, quindi non sarò in grado di provarlo.
Stewie Griffin,

15

25 byte

print(1/2and'cba'or'abc')

Provalo online! ( Python 2 )

Provalo online! ( Python 3 )


-1 byte usando exitinvece di print(anche se questo vale per ogni risposta a partire da ora).
Notjagan,

@notjagan. exitstampa a stderr, non è vero? Non sono sicuro se sarebbe una risposta valida.

@ThePirateBay L'output su STDERR è consentito in base al meta consenso .
Notjagan,

La sfida afferma che lo snippet di codice e la stampa non utilizzano regole predefinite.
xnor


10

-1 byte se faccio ==0in >0ma questa è già un'altra risposta

Python 2 , 26 byte

print('acbbca'[1/2==0::2])

Provalo online!


Python 3 , 26 byte

print('acbbca'[1/2==0::2])

Provalo online!

1/20(floordiv) in Python 2 e 0.5(truediv) in Python 3. Quindi, 1/2==0dà 1 in Python 3 e 0 in Python 2 (in realtà, booleani, ma quelli sono solo numeri interi), quindi 'acbbca'[1::2] => 'cba'viene dato per Python 3 e 'acbbca'[0::2] => 'abc'viene dato per Python 2.


10

Fogli Excel / Google, 41 28 27 24 byte

Formula anonima del foglio di lavoro che non accetta input e output "ABC"nella cella chiamante in Excel e "CBA"nella cella chiamante in Fogli Google

=IfError(M("CBA"),"ABC")

In Fogli Google, M(...)è un alias per e formattato automaticamente in T(...)(abbreviazione di Text()). Questa chiamata restituisce il valore di testo della variabile passata, "CBA". "CBA"non viene rilevato come errore, quindi "CBA"viene restituito daIfError(...,"ABC")

In Excel, non v'è alcuna M(...)funzione e M(...)non è un alias e quindi M("CBA")ritorna la formula non trovato errore, #NAME?. Questo viene colto da ciò IfError(...,"ABC")che a sua volta ritorna "ABC".


Versioni precedenti, 27, 28, 41 byte

Vedi le modifiche per le spiegazioni

=If(IsErr(A()),"ABC","CBA")
=If(IsErr(GT()),"ABC","CBA")
=IfError(If(Info("NUMFILE"),"ABC"),"CBA")

1
! Neat .... Puoi salvare 2 byte usando iserrinvece di iferror1 byte usando "SYSTEM" invece di "NUMFILE":=IF(ISERR(INFO("SYSTEM")),"cba","abc")
Adam

8

CJam / 05AB1E , 6 byte

"abc"R

Provalo online:

Come funziona in CJam

"abc"    Push this string
R        Push variable R, predefined to the empty string
         Implicitly display stack

Come funziona in 05AB1E

"abc"    Push this string
R        Reverse
         Implicitly display top of the stack

8

Ci scusiamo con @HyperNeutrino per aver rubato la maggior parte della sua risposta (non ho ancora la reputazione di commentare)

Python 2 , 25 byte

print('acbbca'[1/2>0::2])

Provalo online!

Python 3 , 25 byte

print('acbbca'[1/2>0::2])

Provalo online!


In realtà è in realtà <1.
Erik the Outgolfer,

@EriktheOutgolfer No, questo è vero per entrambe le lingue
HyperNeutrino,

Come suggerito da @notjagan, puoi sostituirlo printcon exit(che è consentito dalle nostre regole) e quindi salvare 1 byte.

3
Dovresti aggiungere la seconda lingua alla tua risposta (suppongo Python3)
Zacharý

@ Zacharý Grazie, non mi ero reso conto che il problema fosse stato aggiornato (l'originale era solo Python 2 e Pyhon 3)
Reffu,

8

Vim / Notepad.exe, 10 byte

cbaabc<esc><backspace><backspace><backspace>

2
Notepad isn't a programming language, but +1.
Jakob

7

JavaScript (NodeJS) and PHP, 46 bytes

<!--
strrev=console.log//--><?=
strrev("abc");

Prints abc in JS and cba in PHP.

Try the JS online!

Try the PHP online! (note that TIO doesn't hide the HTML comments (<!--...-->)


1
How is the <!-- interpreted in Node?
Esolanging Fruit

@Challenger5 It's apparently interpreted as a one-line comment, exactly like // (source). Works that way in browser JS as well.
Justin Mariner

6
That is weird...
Esolanging Fruit

--> blah blah is valid comment in some JavaScript interpreter, you may just remove //
tsh

1
@JustinMariner I had tested on Node v8.1.3. And the behavior defined in ES6 specification Annex B, which means all browsers that support ES6 should accept it as comment.
tsh

6

Python / Befunge, 20 18 bytes

2 bytes saved thanks to @karhell

print("abc")# ,,,@

Try it online! for Python

Python sees print("abc") then a comment.

Try it online! for Befunge

Befunge, removing all nops and useless commands sees "abc",,,@ which puts a, b and c on the stack and then prints them (last in - first out).


A bit late, but you can shave off two bytes by replacing >:#,_@ by ,,,@
karhell

Save one more with #,,<@ instead
Jo King

5

Python 2 and Python 3, 42 bytes

try:exec("print'abc'")
except:print('cba')

Try it online! (Python 2)

Try it online! (Python 3)

Thought I'd try something different...


I like this one, not the shortest but quite a generic framework, can be shortened a bit by using try:long;print('abc')
Chris_Rands

Or better still try:cmp;print('abc')
Chris_Rands


That's not what I wrote, parantheses () still required around print
Chris_Rands

5

Excel/Google Sheets, 28 bytes

Inspired by @TaylorScott, who used a function that only exists in Excel, I found an even shorter function that only exists in Google Sheets. Conveniently, it is designed to return strings:

=iferror(join(,"cba"),"abc")

How it works

In Google Sheets, join([arg1], arg2, arg3,...argk) will concatenate arg2 -> argk, optionally using the separator specified in arg1. In this case, it successfully returns "cba."

Excel has no join function, so iferror sees a problem and returns "abc"


1
My first ever submission - hope I am doing it right....
Adam

Nice solution :)
Taylor Scott


4

Java 8 & C, 95 bytes

//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

Try it in Java 8 - resulting in "abc".
Try it in C - resulting in "cba".

Explanation:

//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

As you can see in the Java-highlighted code above, the first line is a comment due to //, and the C-code is a comment due to /* ... */, resulting in:

interface a{static void main(String[]s){System.out.print("abc");}}

//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

Not sure how to correctly enable C-highlighting, because lang-c results in the same highlighting as Java.. But //\ will comment out the next line, which is the Java-code, resulting in:

main(){{puts("cba");}}

4

Python 2 / Python 3, 28 bytes

print('abc'[::int(1/2*4)-1])

In Python 2 int(1/2*4)-1 evaluates to -1 and so prints cba. - TiO

In Python 3 it evaluates 1 so prints abc. - TiO


2
Welcome to Programming Puzzles and Code Golf
Евгений Новиков

4

C and C++, 115, 78, 58, 56 bytes

#include<stdio.h>
main(){puts(sizeof('x')>1?"abc":"cba");}

78 bytes, thanks to challenger5.

58 bytes, thanks to aschepler.

56 bytes, thanks to hvd

Try it - C++!

Try it - C!


1
1) You can collapse the two #ifdefs to make a single one. 2) You can remove the space in #include <stdio.h>. 3) You can change printf("%s", to puts(. Try it online!
Esolanging Fruit

2
Or there's always the good old sizeof('x')>1?"abc":"cba" trick.
aschepler

@Challenger5 Thanks for the comment
Ivan Botero

@aschepler Thanks for the trick, i've made the changes 58 bytes :)
Ivan Botero

1
sizeof's operand does not need parentheses, it's not a function.
hvd

4

R/Cubix, 20 bytes

cat("abc")#u@o;o;o(;

R - Try it online!

Cubix - Try it online!

For R, cat("abc") then shameless abuse of comments. For Cubix

    c a
    t (
" a b c " ) # u
@ o ; o ; o ( ;
    . .
    . .
  • "abc" Pushs a, b ad c onto the stack
  • )# Increment the c, pushs number of element in stack
  • u U-turn to the right
  • ;( Remove the count, Decrement the c
  • o;o;o@ Output cba and exit

Pushs the number on in stack


2
I am strangely pleased by the way that cat( is totally ignored by Cubix.
Giuseppe



3

C (gcc) C++ (g++), 59 bytes

#include<stdio.h>
main(){puts("abc\0cba"+(sizeof(' ')&4));}

3

Fission / ><> , 11 bytes

!R"abc"ooo;

Try Fission Online

In Fission, a particle starts at R and prints abc.

Try ><> Online

In ><>, the IP starts at the top-left. ! skips the next instruction, and "abc" pushes [a,b,c] on the stack. ooo then pops and prints three times, giving cba.

Both programs end at ;


3

Ly / ><>, 20 19 bytes

"abc"&&ov
;     oo<

Try it with ><>!

Try it with Ly!

These languages are very similar, as Ly is based off ><>. However, Ly does not have 2D execution and interprets & differently, which I took advantage of here.

Both languages will start by pushing abc to the stack.

For ><>, the & instruction moves values to and fro the register. Two in a row will push a value to the register and then take it straight back, essentially a NOP.

For Ly, & is a modifier that makes an instruction perform its function on the entire stack.

o means the same thing for both languages, but since it is modified by & in Ly, it will print the whole stack, outputting abc. In ><>, it will only output c (as it is printed from the top down)

v is a NOP in Ly, which skips it and goes straight to ;, ending execution. ><> will instead treat it as a pointer, sending the IP downwards.

It then hits another arrow, sending the IP left. Here, it meets two o signs, outputting b and a.

EDIT: Saved a byte (and fixed ><> crashing)


1
You can save a byte by moving the ; to the second line. This also has the benefit that the ><> IP doesn't wrap around and go through the second line again, which causes an error.
Esolanging Fruit

shouldn't there be a ; for ><>? it wouldn't take any more bytes, just replace one of the spaces
Destructible Lemon

How about "abc"&&ooo;? It makes Ly crash, but only after printing "abc".
Not a tree

…or "abc"&&o!;o< for 1 extra byte, if you want to avoid crashing.
Not a tree



2

05AB1E and 2sable, 6 bytes

…CBAžR

Prints ABC (OP said it was allowed) in 05AB1E and CBA in 2sable, using the fact that 2sable was similar to 05AB1E but the žR was added to 05AB1E after 2sable was abandoned.

Try it online! (05AB1E)

Try it online! (2sable)


The specification states that it must be "abc" or "cba". By my word, I'd say that this is invalid, but I can ask OP.
HyperNeutrino

I asked the OP and he hasn't responded. If this turns out to be invalid, I will remove it.
Oliver Ni

@OliverNi Umm, if it's invalid you can just append a l btw.
Erik the Outgolfer

2

PHP + JavaScript, 29 28 bytes

This works because PHP interprets '0' (same as the integer number 0) as being falsy, while JavaScript assumes it is simply a non-empty string which is truthy.

'0'?alert('cba'):print(abc);

This is meant to run with -r on PHP. In Javascript, just paste it in the console.


Thanks to @Justin Mariner for saving me 1 byte!


You could also use "0" instead of +![]: it becomes 0 (falsy) in PHP and is a string (truthy) in JS.
Justin Mariner

@JustinMariner You're right, but that's 1 byte longer.
Ismael Miguel

1
Isnt it one byte shorter? +![]?print(abc):alert('cba'); -> "0"?alert('cba'):print(abc);
Justin Mariner

@JustinMariner OH!!! That way!!! Yes, it is 1 byte shorter. Thank you!
Ismael Miguel


2

Julia and Octave/Matlab, 27 bytes

if'a'=="a""abc"else"cba"end

In Octave, both 'a' and "a" represent the same string, therefore 'a'=="a" is true. However, in Julia, 'a' is a single character while "a" is a one-character string. In Julia, "cba" is the output.

Ungolfed version:

if 'a'=="a"
  "abc"
else
  "cba"
end

2

Perl / Ruby, 18 bytes

Ruby

print'abc'.reverse

prints cba as we're calling .reverse on the string.

Try it online!

Perl

print'abc'.reverse

prints abc concatenated with the result of reverse which by default works on $_ which is empty and so makes no difference.

Try it online!

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.