Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Write a program that outputs the reverse of its source code as a string. If the source is
abcd
efg
(i.e., the C string "abcd\nefg")
Then the output should be
gfe
dcba
(i.e., the C string "gfe\ndcba")
Bonus points for using esoteric languages such as brainf*ck.
*EDIT:** Removed the unnecessary \0 characters.+
C : 0 chars
Ref: http://www0.us.ioccc.org/years.html#1994_smr
HQ9+:
In HQ9+ esoteric language this code might be:
Q
Here You can find interpreter for that language.
Ruby:
Reversed quine from here.
eval s=%q(puts "eval s=%q(#{s})".reverse)
Powershell FTW (1 character):
1
Put it directly on the command line, or inside a script.
Here's a two-liner, adapted from NeatQuine.py:
me = 'me = %(me)r\nprint (me %% locals())[::-1]'
print (me % locals())[::-1]
C89
int sprintf(char*,char*,...);char*d=
"int sprintf(char*,char*,...);char*d=%c%c%s%c%c,b[999],*p=b+251;main(){for(sprintf(b+1,d,10,34,d,34,10,10,10);*p;)putchar(*p--);}%c"
,b[999],*p=b+251;main(){for(sprintf(b+1,d,10,34,d,34,10,10,10);*p;)putchar(*p--);}
Bash script
(10 Charecters)
cat $0|rev
This must be saved as a script file to work and executed on the same directory.
Another solution would be in python (or any other scripting languages) a zero byte source code file! it will print nothing in return. There's nothing in the rules saying it can't be 0byte file :).
J, 26 characters.
|.(,~,2#{:)'|.(,~,2#{:)'''
Produces the output:
'''):{#2,~,(.|'):{#2,~,(.|
I'm going to lose at golf, but it taught me an important lesson about the subtleties of reverse(). Perl in way too many (142) characters:
#!/usr/bin/perl
$_='#!/usr/bin/perlc%$_=c%s%c%;print sprintf~~reverse,10,39,~~reverse,39,10;c%';print sprintf~~reverse,10,39,~~reverse,39,10;
This proves that the sprintf()/reverse() combination is not the way to approach this problem. A better Perl solution will undoubtedly use eval().
Vast improvement: 45 characters:
print~~reverse <<''x2
print~~reverse <<''x2
Note that the source file should end in a blank line. The blank line is counted in the character count - how else do you think we got an odd character count out of two identical lines of code?
Python 2 (55 char):
x='x=%s;print(x%%repr(x))[::-1]';print(x%repr(x))[::-1]
A better golfer might be able to shorten this somewhat, so any improvements are welcome.
Edit (43 char):
x='x=%r;print(x%%x)[::-1]';print(x%x)[::-1]
also thanks to #stephan202 for catching the whitespace on prints
F# (659 chars)
open System;let R(s:String)=new System.String(s|>List.of_seq|>List.rev|>Array.of_list) in let q=char 34 in let Q(s:String)=s.Replace(new String([|q|]),new String([|char 92;q|])) in let Quine s=String.Format("let s={0}{1}{2} in printf {3}%s%s{4} (R(Quine s)) (R s)",[|box q;box(Q s);box q;box q;box q|]) in let s="open System;let R(s:String)=new System.String(s|>List.of_seq|>List.rev|>Array.of_list) in let q=char 34 in let Q(s:String)=s.Replace(new String([|q|]),new String([|char 92;q|])) in let Quine s=String.Format(\"let s={0}{1}{2} in printf {3}%s%s{4} (R(Quine s)) (R s)\",[|box q;box(Q s);box q;box q;box q|]) in " in printf "%s%s" (R(Quine s)) (R s)
Inserting line breaks (that break the program, but make it more readable here):
open System;
let R(s:String)=new System.String(s|>List.of_seq|>List.rev|>Array.of_list) in
let q=char 34 in
let Q(s:String)=s.Replace(new String([|q|]),new String([|char 92;q|])) in
let Quine s=String.Format("let s={0}{1}{2} in printf {3}%s%s{4} (R(Quine s)) (R s)",
[|box q;box(Q s);box q;box q;box q|]) in
let s="open System;
let R(s:String)=new System.String(s|>List.of_seq|>List.rev|>Array.of_list) in
let q=char 34 in
let Q(s:String)=s.Replace(new String([|q|]),new String([|char 92;q|])) in
let Quine s=String.Format(\"let s={0}{1}{2} in printf {3}%s%s{4} (R(Quine s)) (R s)\",
[|box q;box(Q s);box q;box q;box q|]) in " in
printf "%s%s" (R(Quine s)) (R s)
In C , 217 chars :
a="};)01(rahctup;)--p*(rahctup);p*;43=p*(rof;)a(ftnirp;))a,b=p(tacrts(nelrts=+p{)p*rahc(niam;}7393422{=]99[b;";b[99]={2243937};main(char*p){p+=strlen(strcat(p=b,a));printf(a);for(*p=34;*p;)putchar(*p--);putchar(10);}
Javascript - IE/Chrome/FF
(function(){alert(("("+arguments.callee+")()").split("").reverse().join(""))})()
At the Python interactive prompt:
xatnys dilavni :rorrExatnyS
27 characters.
C89, 119 characters
Unfortunately, this requires use of the highly non-standard function strrev():
main(){char*a="};)43,)b(verrts,43,a(ftnirp;)a(pudrts=b*,%c%s%c=a*rahc{)(niam",*b=strdup(a);printf(a,34,strrev(b),34);}
Bash, 75 chars
Well, of course an empty shell script will output nothing, but the next best thing I can think of:
a=\;printf\ \"a=%q%s\"\ \"\$a\"\ \"\$a\"\|rev;printf "a=%q%s" "$a" "$a"|rev
Same ol' trick.
UNIX shell:
z=\' a='z=\\$z a=$z$a$z\;eval echo \$a\|rev';eval echo $a|rev
I tend to repeat my self: these programs ought to be referred to as `Goedels' because the idea behind a majority of such things was first used (in modern times) by Kurt Goedel in the proof of his First Incompleteness Theorem (Kurt Goedel's Collected Works I, p.175).
Perl
73 characters.
#! /opt/perl/bin/perl
seek DATA,0,0;$/=\1;print reverse <DATA>;
__DATA__
You have to have __DATA__ at the end for the DATA file-handle to start out opened.
Setting $/ to a reference of a number, causes readline() to read that many bytes at a time.
seek(DATA,0,0) is required to set the pointer to the beginning of the file, instead of at the beginning of the __DATA__ section.
Could remove, or shorten the shebang line (#! ...)
__DATA__ requires a newline after it, or it isn't valid Perl.
Haskell, 79 characters
a=";main=putStr.reverse$\"a=\"++show a++a";main=putStr.reverse$"a="++show a++a
Standard trick.
Java:
Definitely not the shortest possible, but what the heck (one line):
public class R{public static void main(String[] a){StringBuffer s = new StringBuffer("public class R{public static void main(String[] a){StringBuffer s = new StringBuffer();s.reverse();System.out.print(s.substring(0,152));System.out.write(34);System.out.print(s);System.out.write(34);System.out.println(s.substring(152));}}");s.reverse();System.out.print(s.substring(0,152));System.out.write(34);System.out.print(s);System.out.write(34);System.out.println(s.substring(152));}}
PHP 36 bytest
<?echo strrev(join(file(__FILE__)));
C89 (155 bytes)
#define q(k)r(char*s){if(*s)r(s+1);putchar(*s);}main(){r(#k"\nq("#k")\n");}
q(#define q(k)r(char*s){if(*s)r(s+1);putchar(*s);}main(){r(#k"\nq("#k")\n");})
python (34 chars):
print(open(__file__).read()[::-1])
PHP
Snip - removed incorrect answer
And now to redeem myself;
<?php echo strrev(file_get_contents(__FILE__)); ?>
JavaScript: How many characters do you want?
SECOND SIMPLEST VALID PROGRAM (using my method): 240 Chars! (including spaces but not new lines)
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script>
var string = "<!DOCTYPE HTML>\n<html>\n" + document.documentElement.innerHTML + "\n</html>";
var string2 = string.split("").reverse().join("");
document.write(string2);
</script>
</body>
</html>
C/C++:
#include<stdio.h>
int main() {
char c;
freopen("thisfilename.c","r",stdin); //or thisfilename.cpp
while(scanf("%c",&c)!=-1)
printf("%c",c);
return 0; }
Related
Hello i am encountering this error message in a Haskell program and i do not know where is the loop coming from.There are almost no IO methods so that i can hook myself to them and print the partial result in the terminal.
I start with a file , i read it and then there are only pure methods.How can i debug this ?
Is there a way to attach to methods or create a helper that can do the following:
Having a method method::a->b how can i somehow wrap it in a iomethod::(a->b)->IO (a->b) to be able to test in in GHCI (i want to insert some putStrLn-s etc ?
P.S My data suffer transformations IO a(->b->c->d->......)->IO x and i do not know how to debug the part that is in the parathesis (that is the code that contains the pure methods)
Types and typeclass definitions and implementations
data TCPFile=Rfile (Maybe Readme) | Dfile Samples | Empty
data Header=Header { ftype::Char}
newtype Samples=Samples{values::[Maybe Double]}deriving(Show)
data Readme=Readme{ maxClients::Int, minClients::Int,stepClients::Int,maxDelay::Int,minDelay::Int,stepDelay::Int}deriving(Show)
data FileData=FileData{ header::Header,rawContent::Text}
(>>?)::Maybe a->(a->Maybe b)->Maybe b
(Just t) >>? f=f t
Nothing >>? _=Nothing
class TextEncode a where
fromText::Text-> a
getHeader::TCPFile->Header
getHeader (Rfile _ ) = Header { ftype='r'}
getHeader (Dfile _ )= Header{ftype='d'}
getHeader _ = Header {ftype='e'}
instance Show TCPFile where
show (Rfile t)="Rfile " ++"{"++content++"}" where
content=case t of
Nothing->""
Just c -> show c
show (Dfile c)="Dfile " ++"{"++show c ++ "}"
instance TextEncode Samples where
fromText text=Samples (map (readMaybe.unpack) cols) where
cols=splitOn (pack ",") text
instance TextEncode Readme where
fromText txt =let len= length dat
dat= case len of
6 ->Prelude.take 6 .readData $ txt
_ ->[0,0,0,0,0,0] in
Readme{maxClients=Prelude.head dat,minClients=dat!!1,stepClients=dat!!2,maxDelay=dat!!3,minDelay=dat!!4,stepDelay=dat!!5} where
instance TextEncode TCPFile where
fromText = textToFile
Main
module Main where
import Data.Text(Text,pack,unpack)
import Data.Text.IO(readFile,writeFile)
import TCPFile(TCPFile)
main::IO()
main=do
dat<-readTcpFile "test.txt"
print dat
readTcpFile::FilePath->IO TCPFile
readTcpFile path =fromText <$> Data.Text.IO.readFile path
textToFile::Text->TCPFile
textToFile input=case readHeader input >>? (\h -> Just (FileData h input)) >>? makeFile of
Just r -> r
Nothing ->Empty
readHeader::Text->Maybe Header
readHeader txt=case Data.Text.head txt of
'r' ->Just (Header{ ftype='r'})
'd' ->Just (Header {ftype ='d'})
_ -> Nothing
makeFile::FileData->Maybe TCPFile
makeFile fd= case ftype.header $ fd of
'r'->Just (Rfile (Just (fromText . rawContent $ fd)))
'd'->Just (Dfile (fromText . rawContent $ fd))
_ ->Nothing
readData::Text->[Int]
readData =catMaybes . maybeValues where
maybeValues=mvalues.split.filterText "{}"
#all the methods under this line are used in the above method
mvalues::[Text]->[Maybe Int]
mvalues arr=map (\x->(readMaybe::String->Maybe Int).unpack $ x) arr
split::Text->[Text]
split =splitOn (pack ",")
filterText::[Char]->Text->Text
filterText chars tx=Data.Text.filter (\x -> not (x `elem` chars)) tx
I want first to clean the Text from given characters , in our case }{ then split it by ,.After the text is split by commas i want to parse them, and create either a Rfile which contains 6 integers , either a Dfile (datafile) which contains any given number of integers.
Input
I have a file with the following content: r,1.22,3.45,6.66,5.55,6.33,2.32} and i am running runghc main 2>err.hs
Expected Output : Rfile (Just (Readme 1.22 3.45 6.66 5.55 6.33 2.32))
In the TextEncode Readme instance, len and dat depend on each other:
instance TextEncode Readme where
fromText txt =let len= length dat
dat= case len of
To debug this kind of thing, other than staring at the code, one thing you can do is compile with -prof -fprof-auto -rtsopts, and run your program with the cmd line options +RTS -xc. This should print a trace when the <<loop>> exception is raised (or if the program loops instead, when you kill it (Ctrl+C)). See the GHC manual https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/runtime_control.html#rts-flag--xc
As Li-yao Xia said part of the problem is the infinite recursion, but if you tried the following code, then the problem still remains.
instance TextEncode Readme where
fromText txt =let len= length [1,2,3,4,5,6] --dat
dat= case len of
The second issue is that the file contains decimal numbers but all the conversion function are expecting Maybe Int, changing the definitions of the following functions should give the expected results, on the other hand probably the correct fix is that the file should have integers and not decimal numbers.
readData::Text->[Double]
--readData xs = [1,2,3,4,5,6,6]
readData =catMaybes . maybeValues where
maybeValues = mvalues . split . filterText "{}"
--all the methods under this line are used in the above method
mvalues::[Text]->[Maybe Double]
mvalues arr=map (\x->(readMaybe::String->Maybe Double).unpack $ x) arr
data Readme=Readme{ maxClients::Double, minClients::Double,stepClients::Double,maxDelay::Double,minDelay::Double,stepDelay::Double}deriving(Show)
I am working with Graphchi's pagerank example: https://github.com/GraphChi/graphchi-cpp/wiki/Example-Apps#pagerank-easy
The example app writes a binary file with vertex information that I would like to read/convert to a plan text file (to later call into R or some other language).
The documentation states that:
"GraphChi will write the values of the edges in a binary file, which is easy to handle in other programs. Name of the file containing vertex values is GRAPH-NAME.4B.vout. Here "4B" refers to the vertex-value being a 4-byte type (float)."
The 'easy to handle' part is what I'm struggling with - I have experience with high level languages but not C++ or dealing with binary files. I have found a few things through searching stackoverflow but no luck yet in reading this file. Ideally this would be done through bash or python.
thanks very much for your help on this.
Update: hexdump graph-name.4B.vout | head -5 gives:
0000000 999a 3e19 7468 3e7f 7d2a 3e93 d8e0 3ec4
0000010 cec6 3fe4 d551 3f08 eff2 3e54 999a 3e19
0000020 999a 3e19 3690 3e8c 0080 3f38 9ea3 3ef5
0000030 b7d6 3f66 999a 3e19 10e3 3ee1 400c 400d
0000040 a3df 3e7c 999a 3e19 979c 3e91 5230 3f18
Here is example code how you can use GraphCHi to write the output out as a string:
https://github.com/GraphChi/graphchi-cpp/wiki/Vertex-Aggregators
But the array is simple byte array. Here is example how to read it in python:
import struct
from array import array as binarray
import sys
inputfile = sys.argv[1]
data = open(inputfile).read()
a = binarray('c')
a.fromstring(data)
s = struct.Struct("f")
l = len(a)
print "%d bytes" %l
n = l / 4
for i in xrange(0, n):
x = s.unpack_from(a, i * 4)[0]
print ("%d %f" % (i, x))
I was having the same trouble. Luckily I work with a bunch of network engineers who helped me out! On Mac Linux, the following command works to print the 4B.vout data one line per node, with the integer values the same as is given in the summary file. If your file is called eg, filename.4B.vout, then some command line perl gets you:
cat filename.4B.vout | LANG= perl -0777 -e '$,=\"\n\"; print unpack(\"L*\",<>),\"\";'
Edited to add: this is for the assignments of connected component ID and community ID, written implicitly the 1st line is the ID of the node labeled 0, the 2nd line is the node labeled 1 etc. But I am copypasting here so I'm not sure how it would need to change for floats. It works great for the integer values per node.
I am just new to scripting and I need some help. I have something like a bazillion files that look like this.
Assign F2 Height
3IleN 2.34025e+07
4PheN 2.05028e+07
6LysN 1.43672e+07
7ThrN 1.49120e+07
8LeuN 1.30838e+07
9ThrN 1.44298e+07
And i want it to look like this + save it in another file with the same name as the previous file however, with a "MOD" written at the beginning.
Number AA Height
3 IleN 6.20756e+07
4 PheN 5.26499e+07
7 ThrN 3.00216e+07
8 LeuN 3.26377e+07
9 ThrN 4.03901e+07
10 GlyN 2.73659e+07
12 ThrN 3.16319e+07
13 IleN 5.94604e+07
If you could please describe and explain the parameters used, that would be of great help.
Thanks!
The following should work for you:
sed 's/^\([0-9]*\)/\1 /' filename
Goal is to replace 'byebye' with 'Hello '
# START: file.txt contains string "byebye World!"
fd = File.open('file.txt', 'a')
fd.seek(0, IO::SEEK_SET)
fd.puts 'Hello '
fd.close
# END: file.txt contains two lines "byebye World " and "Hello "
I understand what exists other excellent ( and working:) ) ways to achieve it, but why that code don't write on right position?
I think you're misunderstanding w+, you may want r+ as the modestring, here's what w+ does.
w+
Read-write, truncates existing file to zero length or creates a new file for reading and writing.
truncate existing file to zero length is eating your string.
I am new to Haskell. Previously I have programmed in Python and Java. When I am debugging some code I have a habit of littering it with print statements in the middle of code. However doing so in Haskell will change semantics, and I will have to change my function signatures to those with IO stuff. How do Haskellers deal with this? I might be missing something obvious. Please enlighten.
Other answers link the official doco and the Haskell wiki but if you've made it to this answer let's assume you bounced off those for whatever reason. The wikibook also has an example using Fibonacci which I found more accessible. This is a deliberately basic example which might hopefully help.
Let's say we start with this very simple function, which for important business reasons, adds "bob" to a string, then reverses it.
bobreverse x = reverse ("bob" ++ x)
Output in GHCI:
> bobreverse "jill"
"llijbob"
We don't see how this could possibly be going wrong, but something near it is, so we add debug.
import Debug.Trace
bobreverse x = trace ("DEBUG: bobreverse" ++ show x) (reverse ("bob" ++ x))
Output:
> bobreverse "jill"
"DEBUG: bobreverse "jill"
llijbob"
We are using show just to ensure x is converted to a string correctly before output. We also added some parenthesis to make sure the arguments were grouped correctly.
In summary, the trace function is a decorator which prints the first argument and returns the second. It looks like a pure function, so you don't need to bring IO or other signatures into the functions to use it. It does this by cheating, which is explained further in the linked documentation above, if you are curious.
Read this. You can use Debug.Trace.trace in place of print statements.
I was able to create a dual personality IO / ST monad typeclass, which will print debug statements when a monadic computation is typed as IO, them when it's typed as ST. Demonstration and code here: Haskell -- dual personality IO / ST monad? .
Of course Debug.Trace is more of a swiss army knife, especially when wrapped with a useful special case,
trace2 :: Show a => [Char] -> a -> a
trace2 name x = trace (name ++ ": " ++ show x) x
which can be used like (trace2 "first arg" 3) + 4
edit
You can make this even fancier if you want source locations
{-# LANGUAGE TemplateHaskell #-}
import Language.Haskell.TH
import Language.Haskell.TH.Syntax as TH
import Debug.Trace
withLocation :: Q Exp -> Q Exp
withLocation f = do
let error = locationString =<< location
appE f error
where
locationString :: Loc -> Q Exp
locationString loc = do
litE $ stringL $ formatLoc loc
formatLoc :: Loc -> String
formatLoc loc = let file = loc_filename loc
(line, col) = loc_start loc
in concat [file, ":", show line, ":", show col]
trace3' (loc :: String) msg x =
trace2 ('[' : loc ++ "] " ++ msg) x
trace3 = withLocation [| trace3' |]
then, in a separate file [from the definition above], you can write
{-# LANGUAGE TemplateHaskell #-}
tr3 x = $trace3 "hello" x
and test it out
> tr3 4
[MyFile.hs:2:9] hello: 4
You can use Debug.Trace for that.
I really liked Dons short blog about it:
https://donsbot.wordpress.com/2007/11/14/no-more-exceptions-debugging-haskell-code-with-ghci/
In short: use ghci, example with a program with code called HsColour.hs
$ ghci HsColour.hs
*Main> :set -fbreak-on-exception
*Main> :set args "source.hs"
Now run your program with tracing on, and GHCi will stop your program at the call to error:
*Main> :trace main
Stopped at (exception thrown)
Ok, good. We had an exception… Let’s just back up a bit and see where we are. Watch now as we travel backwards in time through our program, using the (bizarre, I know) “:back” command:
[(exception thrown)] *Main> :back
Logged breakpoint at Language/Haskell/HsColour/Classify.hs:(19,0)-(31,46)
_result :: [String]
This tells us that immediately before hitting error, we were in the file Language/Haskell/HsColour/Classify.hs, at line 19. We’re in pretty good shape now. Let’s see where exactly:
[-1: Language/Haskell/HsColour/Classify.hs:(19,0)-(31,46)] *Main> :list
18 chunk :: String -> [String]
vv
19 chunk [] = head []
20 chunk ('\r':s) = chunk s -- get rid of DOS newline stuff
21 chunk ('\n':s) = "\n": chunk s
^^