Membalikkan kebenaran

22

Tulis program atau fungsi yang:

  1. mengambil string dari stdio atau argumen
  2. menggantikan semua kemunculan truedengan falsedan falsedengantrue
  3. membalikkannya, tetapi tidak membalikkan truedanfalse
  4. mengembalikan atau mencetak hasil

Contoh (sisi kiri adalah input):

"true"                     "false"
"2false"                   "true2"
"true is false"            "true si false"
"false,true,undefined"     "denifednu,false,true"
"stressed-false"           "true-desserts"
"falstrue"                 "falseslaf"
"true false true x"        "x false true false"

Celah standar berlaku. Ini adalah , jadi kode terpendek dalam byte menang.

Papan peringkat

Hannes Karppila
sumber
Pada Langkah 3, hanya satu penggantian yang diperlukan, atau semua kejadian harus diganti? misalnya true true false falsemenjadi true true false falseatau true eslaf false eurt?
gaborsch
Haruskah eurtmenjadi falseatau true?
Zereges
@ Zona Tidak salah atau benar sebelum dibalik, jadi: eurt->true
Hannes Karppila
@ HannesKarppila Jadi, aturannya diterapkan agar:1 3 2 4 5
Zereges
3
Apakah ini juga berarti itu trufalse -> trueurt?
Adnan

Jawaban:

12

C # 6, 144 byte

string R(string t)=>string.Concat(new System.Text.RegularExpressions.Regex("true|false").Replace(t,m=>m.Value[0]<'g'?"eurt":"eslaf").Reverse());

Itu menggunakan ekspresi reguler untuk mencocokkan true|false, dan jika cocok trueitu akan digantikan oleh eslaf, jika tidak oleh eurt. m.Value[0]<'g'adalah cara yang lebih singkat untuk mengatakan m.Value[0]=="false", karena satu-satunya nilai yang mungkin untuk m.Valueare "true"atau "false", jadi jika kode char dari char pertama lebih kecil dari kode char 'g', itu "false".

Versi lama, 95 byte

Yang ini memiliki bug, tidak mengembalikan output yang benar untuk falstrue.

string R(string t)=>string.Concat(t.Reverse()).Replace("eurt","false").Replace("eslaf","true");
ProgramFOX
sumber
15
Solusi AC # di bawah 100 byte? Tentunya akhir zaman ada pada kita.
Alex A.
@AlexA. Haha, semua berkat versi 6; P
ProgramFOX
1
Ini tidak berfungsi dengan benar untuk input falstrue.
feersum
2
@AlexA. Nah, dengan output yang salah untuk falstruediperbaiki, itu tidak lagi <100 byte ... :(
ProgramFOX
14
Meskipun itu memang menyedihkan, itu berarti kita tidak perlu lagi khawatir tentang kiamat. Bug perangkat lunak telah menyelamatkan kita semua.
Alex A.
7

TeaScript , 36 25 24 byte

xv¡g("eurt|eslaf",#ln>4)   

TeaScript adalah JavaScript untuk bermain golf.

Suntingan: Disimpan 11 byte berkat @ Vɪʜᴀɴ. Memperbaiki input falstruedan menyimpan satu byte.

Versi lama (Tidak Valid):

xv¡g("eurt",f)g(f.T¡v¡,t)

Penjelasan:

x    // Input
 v¡    // Reverse
   g("eurt",    // Global replace "eurt" with "false".
            f)    // f is predefined to false.
              g(f.T¡v¡, // Convert false to string, then reverse.
                       t) // t is predefined to true.
intrepidcoder
sumber
Jika Anda menggunakan ldan ibukannya tdan f, Anda dapat mengabaikan .. f juga sudah ditentukan sebelumnya falsesehingga Anda bisa mendapatkan:xv¡g(l="eurt",i=f+¢)g(iv¡,lv¡)
Downgoat
Sebenarnya lebih baik lagi:xv¡g("eurt",f)g(f.T¡v¡,t)
Downgoat
@ Vɪʜᴀɴ Terima kasih atas bantuannya. tidak melihat itu di dokumen. Apakah mungkin memasukkan secara otomatis (setelah metode? Suka replace(/(\.[BcCdeE...])/g,"$1(")atau serupa setelah memasukkan periode.
intrepidcoder
1
Ini tidak berfungsi dengan benar untuk input falstrue.
feersum
@feersum Fixed. Thanks for pointing that out. That was tricky.
intrepidcoder
7

Bash+GNU, 45 38 73 bytes

Edit: works with both trufalse and falstrue

sed s/false/%eurt%/g\;s/true/%eslaf%/g|rev|sed "s/%\(true\|false\)%/\1/g"

Old version, 38 bytes (shortened, thanks to Digital Trauma):

rev|sed s/eurt/false/g\;s/eslaf/true/g
gaborsch
sumber
1
Combine the sed expressions into one, and remove the "-e" and quotes: rev|sed s/eurt/false/g\;s/eslaf/true/g
Digital Trauma
2
This does not work correctly for the input falstrue.
feersum
@feersum Good point, fixed. Also checked for trufalse.
gaborsch
6

JavaScript ES6, 59

As an anonymous function.

Note, replace is used just as a shorthand for match().map(). The replaced string is discarded, and the output string is made piece by piece backwards (so no need to reverse).

s=>s.replace(/false|true|./g,x=>s=(x[1]?x<'t':x)+s,s='')&&s

Test running the snippet below in an EcmaScript 6 compliant browser.

f=s=>s.replace(/false|true|./g,x=>s=(x[1]?x<'t':x)+s,s='')&&s

//test

console.log=x=>O.innerHTML+=x+'\n'

;[
 ["true","false"]
,["falstrue","falseslaf"]  
,["1false","true1"]
,["true is false","true si false"]
,["false,true,undefined","denifednu,false,true"]
,["stressed-false","true-desserts"]
,["true false true x","x false true false"]
].forEach(t=>console.log(t[0]+' -> '+f(t[0])))
<pre id=O></pre>

edc65
sumber
Came on here to post amazing 62-byte solution...found incredible 59-byte solution. +1
ETHproductions
5

Windows Batch, 184 213 bytes

Fixed the bug, falstrue -> falseslaf and trufalse -> trueurt

Probably one of the less popular languages:

setlocal enabledelayedexpansion
set /p Q=
set N=0
:L
call set T=%%Q:~%N%,1%%%
set /a N+=1
if not "%T%" equ "" (
set R=%T%%R%
goto L
)
set R=%R:eurt=false%
set R=%R:eslaf=true%
set R=%R:falstrue=falseslaf%
echo %R%
Adnan
sumber
1
This does not work correctly for the input falstrue.
feersum
@feersum, fixed it :)
Adnan
5

Haskell, 94 bytes

Performs pattern matching on the input string, looking for "false" or "true" and appends the opposite to the result of applying the function on the remainder of the string. If true or false isn't found, it uses recursion to reverse the string in the same fashion.

f[]=[]
f('t':'r':'u':'e':s)=f s++"false"
f('f':'a':'l':'s':'e':s)=f s++"true"
f(x:s)=f s++[x]
Craig Roy
sumber
Added now, sorry about that
Craig Roy
Never mind. It seems I made some mistake when trying to test it. Maybe I simply printed out the string without managing to apply the function to it.
feersum
I believe you can take the top f[]=[] line and instead put f x=x at the bottom to save a byte.
Michael Klein
4

JavaScript ES6, 95 93 bytes

Unnamed function. Add f= to the beginning to use it. Thanks Ismael! Also assumes that the input does not contain tabs.

x=>[...x[r="replace"](/false/g,"\teslaf")[r](/(\t)*true/g,"eurt")[r](/\t/g,"")].reverse().join``
Conor O'Brien
sumber
You can use .replace(/eurt/g,false).replace(/eslaf/g,true), since they will be converted to string. Try true + '' (should return 'true')
Ismael Miguel
3
WAIT!!! Change false with !1 and true with !0. There, a few bytes shorter
Ismael Miguel
3
@IsmaelMiguel whoa thanks!!!!
Conor O'Brien
1
I think you should also be able to use [...x] instead of x.split''
Downgoat
2
67: x=>[...x].reverse().join``[r='replace'](/eurt/g,!1)[r](/eslaf/g,!0). I also changed the join param to an empty template string to make strip out array commas.
Mama Fun Roll
2

Pyth, 30 bytes

::_z"eurt""false""eslaf""true"

This reverses the input (_z), substitutes "eurt" for "false" and "eslaf" for "true". Replacement is done using :.

Try it online

Alex A.
sumber
You can declare "true" and "false" as a variable: =d"true"=k"false"::_z_dk_kd, and use the reverse of it. It will save 3 bytes.
Adnan
::_zJ"eurt"K"false"_K_J is 23 bytes.
PurkkaKoodari
5
This does not work correctly for the input falstrue.
feersum
2

rs, 56 bytes

\t
+(.*\t)(.)(.*)/\2\1\3
\t/
eurt/fals\t
eslaf/true
\t/e

Live demo and test cases.

kirbyfan64sos
sumber
1
This does not work correctly for the input falstrue.
feersum
@feersum Ugh...neither does the Pyth answer, FYI...
kirbyfan64sos
At least 7 answers have this problem that I have tested
feersum
@feersum Ok; I fixed it now.
kirbyfan64sos
2

Julia, 59 55 46 bytes

s->replace(reverse(s),r"eurt|eslaf",i->i<"et")

This creates an unnamed function that accepts a string and returns a string. To call it, give it a name, e.g. f=s->....

The input is reversed using reverse. We match on the regular expression eurt|eslaf which matches true or false backwards. To the match we apply a function that returns true if the match is lexicographically smaller than et (i.e. eslaf) and false otherwise. The boolean literals are converted to string in the output.

Saved 9 bytes and fixed an issue thanks to Glen O!

Alex A.
sumber
2
I don't believe this works correctly for the input falstrue.
feersum
It's using the same basic reasoning, so I'll offer it to you: s->replace(reverse(s),r"eurt|eslaf",i->i<"et") - uses a regex rather than doing it twice, and a function for the replace that evaluates to true if it was "elsaf" and to false if it was "eurt". 46 bytes.
Glen O
Oh, and it also fixes the falstrue issue.
Glen O
@GlenO That's great, thanks
Alex A.
@feersum Fixed now
Alex A.
2

Javascript, 135 Bytes

function(s){return s.split("").reverse().join("").replace(/eslaf/i,'☺').replace(/eurt/i,'☻').replace(/☻/g,!1).replace(/☺/g,!1)}

Test:

=>"false is the opposite of true"

<="true fo etisoppo eht si false"

Thanks ProgramFOX and edc65 for pointing out a bug!

Fuzzyzilla
sumber
Welcome to Programming Puzzles & Code Golf! The question requests a full program or a function, so not just a code snippet that assumes that a variable s exists. Also, your code does not work for falstrue: it should output falseslaf, not trueslaf. Do you want to fix these issues? Thanks! :)
ProgramFOX
@ProgramFOX Thank you! I'll get right on that!
Fuzzyzilla
1
You can save a few bytes if you use ES6, it has this arrow-function syntax: f=s=>s.split(""). ....
ProgramFOX
This is both overly complex and wrong. Test with 'false1' or 'true0' or 'true1'
edc65
@edc65 Why thank you, kind sir!
Fuzzyzilla
2

Java, 162 98 92 bytes

Thanks (and sorry!~) to @DanielM. for telling me about StringBuffer and the fact that we can use functions!

Because, you know, Java.

s->(""+new StringBuffer(s.replaceAll("false","eurt")).reverse()).replaceAll("eurt","false");

Returns the correct, reversed string.

Ungolfed Version:

s->new StringBuilder(
    s.replaceAll("false","eurt"))
    .reverse().toString().replaceAll("eurt","false");

Basically, I replace all instances of "false" with a backwards "true", then reverse the entire string, and then replace the now backwards versions of "true" (not the ones I just replaced) with "false". Easy peasy.

Addison Crump
sumber
StringBuffer is a byte shorter. Also, functions are allowed.
Daniel M.
I'm preparing another answer in a different language, so you can keep this
Daniel M.
The return is implicit when dealing with one-line lambdas
Daniel M.
4
Java beat Python? Now surely the end is upon us
Downgoat
1
@GaborSch Nifty. :P Thanks!
Addison Crump
1

Mathematica, 64 bytes

StringReverse@#~StringReplace~{"eurt"->"false","eslaf"->"true"}&
LegionMammal978
sumber
1

Python 3, 68 100 bytes

I'm still golfing it, but it's fixed to the bug, so falstrue -> falselsaf and trufalse -> trueurt

Pretty straightforward:

print(input()[::-1].replace("eurt","false").replace("eslaf","true").replace("falstrue","falseslaf"))
Adnan
sumber
3
This does not work correctly for the input falstrue.
feersum
This can be easily remedied by switching the replace statements (print(input()[::-1].replace("eslaf","true").replace("eurt","false")))
Beta Decay
@BetaDecay, that will not work, because trufalse becomes trufalse, while it needs to be trueurt
Adnan
@Adriandmen However, that's not one of the example I/Os so it will suffice for now :)
Beta Decay
@BetaDecay Haha, they won't notice :)
Adnan
1

Japt, 26 bytes

Note: This may be invalid, as it requires bug fixes made after this challenge was posted.

Uw r"eurt|eslaf",X=>X<"et"

Try it in the online interpreter! (Arrow function requires ES6-compliant browser, such as Firefox.)

How it works

             // Implicit: U = input string
Uw r         // reverse U, then replace:
"eurt|eslaf" // occurrences of either "eurt" or "eslaf"
X=>X<"et"    // with "false" or "true", respectively
             // Implicit: output last expression

Here's a version that worked before the bug fixes: (38 bytes)

Uw $.replace(/eurt|eslaf/g,X=>X<"et")$
ETHproductions
sumber
1

Gema, 43

*=@a{@reverse{*}};a:eurt=false;a:eslaf=true

(Gema is an obscure macro language.)

Steven Taschuk
sumber
1

Pyth, 28 22

Amr`!dZ2jHjLGcR_Hc_z_G

6 bytes thanks to Jakube

Works correctly for falstrue, as shown in the suite below.

Test suite

FryAmTheEggman
sumber
No, I think I made a mistake. You 22 byte solution is correct.
Jakube
1

Haskell, 102 bytes

h('t':'r':'u':'e':s)="eslaf"++h s
h('f':'a':'l':'s':'e':s)="eurt"++h s
h(x:s)=x:h s
h[]=""
r=reverse.h

The replacement of "true" by "false" and vice-versa is quite lengthy with the pattern-matching, but at least it deals correctly with "falstrue" and the like. And besides, I suspect that a correct regex-based version would be a bit longer.

arjanen
sumber
1

Python 3 - 108 92 bytes

import re
print(re.sub("eslaf|eurt",lambda m:repr(len(m.group(0))>4).lower(),input()[::-1]))

Uses a regex to match on "true" or "false" and uses a lambda to process matches and choose what to use as a replacement string. Using repr gets the string representation of (len(match)>4) which gives "True" when "false" is matched and vice versa (and use .lower() because repr(bool) gives a capitalized string) to get the inverse of the match and finish up by reversing the replacement and then the processed input using [::-1]

Managed to get the length down 16 bytes from TFelds suggestions.

Edit: Python is back in front of java, no need for alarm.

Phyxie
sumber
5
We require here that programs work for all inputs, not just for the given test cases.
lirtosiast
You can save 6 bytes by reversing the string first, and then replacing (saving one [::-1]) print(re.compile("eslaf|eurt").sub(lambda m:repr(m.group(0)!="eurt").lower(),input()[::-1]))
TFeld
You can also get away with not using re.compile print(re.sub("eslaf|eurt",lambda m:repr(m.group(0)!="eurt").lower(),input()[::-1])) Change m.group(0)!="eurt" to len(m.group(0))>4 (for 1 more)
TFeld
1

𝔼𝕊𝕄𝕚𝕟, 40 chars / 65 bytes

ô[…ïċ/false|true/g,⇏[…⬯+!שúa]ù⬮ø⬯)]ù⬮ø⬯)

Try it here (Firefox only).

Thanks to @feersum for pointing out a bug!

21 chars / 43 bytes, non-competitive

ôᴙ(ïċ/⊭|⊨⌿,↪ᴙ(⬯+!ë$⸩⸩

Try it here (Firefox only).

Mama Fun Roll
sumber
2
This does not work correctly for the input falstrue.
feersum
1

Prolog, 225 bytes

p(X):-string_to_list(X,L),reverse(L,B),q(B,C),string_to_list(Z,C),write(Z),!.
q([],[]).
q([101,117,114,116|T],[102,97,108,115,101|L]):-q(T,L).
q([101,115,108,97,102|T],[116,114,117,101|L]):-q(T,L).
q([H|T],[H|L]):-q(T,L).

Try it out online here
Run by querying in the following way:

p("falstrue").
Emigna
sumber
0

Ruby, 55 bytes

->s{s.gsub(/true|false/){$&[?t]?:eslaf: :eurt}.reverse}

Test:

->s{s.gsub(/true|false/){$&[?t]?:eslaf: :eurt}.reverse}["false,true,undefined"]
=> "denifednu,false,true"
daniero
sumber
0

Perl 5, 68 bytes

67 plus 1 for -E instead of -e

%a=(false,eurt,true,eslaf);say~~reverse<>=~s/false|true/$a{$&}/gr
msh210
sumber
0

OpenSCAD, 178 bytes

(Note that this uses the String Theory library, as OpenSCAD doesn't exactly have a standard library. Additionally, this is a function because the only allowed input is to hard-code it.

use <Strings.scad>;function f(a)=contains(g(a),"eurt")?replace(g(a),"eurt","false"):g(a);function g(a)=contains(reverse(a),"eslaf")?replace(reverse(a),"eslaf","true"):reverse(a);
Daniel M.
sumber
0

C#, 260 bytes

using System;class P{static void Main(){var y=Console.ReadLine();char[] n=y.ToCharArray();Array.Reverse(n);var s=new string(n);if(s.Contains("eslaf")){s=s.Replace("eslaf","true");}if(s.Contains("eurt")){s=s.Replace("eurt","false");}Console.WriteLine(s);}}
Belfield
sumber
This is my first (real) post - I've seen someone using c# above didn't include: using system; class P{ }, static void main(), Console.WriteLine(); or Console.ReadLine();. These obviously take on a lot of bytes for me - if there is a way of golfing that or if it is excluded from code-golf - let me know :)
Belfield
0

PHP, 60 bytes

Simple, reverses the string first, then replaces the reversed versions with their respective swaps.

"falstrue" becomes "eurtslaf" becomes "falseslaf".

<?=strtr(strrev($argv[1]),{'eurt'=>'false','eslaf'=>'true'})
Xanderhall
sumber
0

Perl 5.10, 54 bytes

$_=reverse<>;s/(eurt)|(eslaf)/$1?"false":"true"/eg;say

Reverse, then replace. A different way of doing it besides the hash table used for the other Perl answer, which ends up being shorter!

Try it online.

Paul Picard
sumber
-1

Pyth - 18 bytes

Can be golfed a lot more.

Amr`!dZ2::_z_GH_HG

Test Suite.

Maltysen
sumber
6
This does not work correctly for the input falstrue.
feersum