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.
The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in Python:
R=lambda s:all(a==b for a,b in zip(s,reversed(s)))
50 characters.
The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.
7 characters in J: Not sure if this is the best way, I'm somewhat new to J :)
p=:-:|.
explanation: |. reverses the input. -: compares. the operands are implicit.
p 'radar'
1
p 'moose'
0
Here's mine; it's written in a domain-specific language I invented, called 'palindrome'.
p
Edit: Less flippant version (i386 asm, AT&T syntax)
xor %eax, %eax
mov %esi, %edi
#cld not necessary, assume DF=0 as per x86 ABI
repne scasb
scan:
dec %edi
cmpsb
.byte 0x75, 6 #jnz (short) done
dec %edi
cmp %esi, %edi
.byte 0x72, -9 #jb (short) scan
inc %eax
done:
16 bytes, string pointer goes in ESI, result is in EAX.
Sadly, I'm unable to get under a thousand words...
(LabVIEW. Yeah, they'll let just about any hobo post here ;)
Haskell, 15 chars:
p=ap(==)reverse
More readable version, 16 chars:
p x=x==reverse x
Another python version that is rather shorter (21 chars):
R=lambda s:s==s[::-1]
At the risk of getting down votes, most all of these just call a command reverse of some sort that hides all the real programming logic.
I wonder what the shortest manual way to do this is in each of these languages.
With C# and LINQ operators:
public bool IsPalindrome(string s)
{
return s.Reverse().SequenceEqual(s);
}
If you consider Reverse as cheating, you can do the entire thing with a reduction:
public bool IsPalindrome(string s)
{
return s.Aggregate(new StringBuilder(),
(sb, c) => sb.Insert(0, c),
(sb) => sb.ToString() == s);
}
Perl (27 chars):
sub p{$_[0]eq reverse$_[0]}
Ruby (24 chars):
def p(a)a==a.reverse end
73 clean, readable, chars written in java
boolean p(String s){return s.equals(""+new StringBuffer(s).reverse());}
peace :)
Pointless Haskell version (15 chars, though doesn't really work unless you include Control.Arrow and Control.Monad and ignore the monomorphism restriction):
p=ap(==)reverse
Lua aims more at readability than conciseness, yet does an honest 37 chars:
function p(s)return s==s:reverse()end
variant, just for fun (same size):
p=function(s)return s==s:reverse''end
The JavaScript version is more verbose (55 chars), because it doesn't has a string reverse function:
function p(s){return s==s.split('').reverse().join('')}
(equal p (reverse p))
lisp. 18 characters.
ok, this is a special case. This would work if typed directly into a lisp interpreter and p was already defined.
otherwise, this would be necessary:
(defun g () (equal p (reverse p)))
28 characters.
I'll take it a little bit further: full c code, compile and go.
90 characters
main(int n,char**v){char*b,*e;b=e=v[1];while(*++e);for(e--;*b==*e&&b++<e--;);return b>e;}
F# (a lot like the C# example)
let p s=let i=0;let l=s.Length;while(++i<l)if(s[i]!=[l-i-1]) 0; 1;;
PHP:
function p($s){return $s==strrev($s);} // 38 chars
or, just
$s==strrev($s); // 15 chars
Isn't using the reverse function in your language kind of cheating a bit? I mean, looking at the Ruby solution give as
def p(a)a==a.reverse end
you could easily rewrite that as
def p(a)a==a.r end
and just say that you made an extension method in your code so that "r" called reverse. I'd like to see people post solutions that don't contain calls to other functions. Of course, the string length function should be permitted.
Ruby without reverse - 41 characters
def m(a)a==a.split('').inject{|r,l|l+r}end
VB.Net - 173 Chars
Function P(ByVal S As String) As Boolean
For i As Integer = 0 To S.Length - 1
If S(i) <> S(S.Length - i - 1) Then
Return False
End If
Next
Return True
End Function
Golfscript, 5 char
.-1%=
$ echo -n abacaba | ruby golfscript.rb palindrome.gs
1
$ echo -n deadbeef | ruby golfscript.rb palindrome.gs
0
Common Lisp, short-and-cheating version (23 chars):
#L(equal !1(reverse !1))
#L is a reader macro character implemented by SHARPL-READER in the iterate package. It's basically equivalent to (lambda (!1) ...).
Common Lisp, long version using only primitives (137 including whitespace, compressible down to 108):
(defun p (s)
(let ((l (1- (length s))))
(iter (for i from l downto (/ l 2))
(always (equal (elt s i) (elt s (- l i)))))))
Again, it uses iterate, which is basically a cleaner version of the builtin LOOP facility, so I tend to treat it as being in the core language.
Not the shortest, and very after-the-fact, but I couldn't help giving it a try in MATLAB:
R=#(s)all(s==fliplr(s));
24 chars.
C# Without Reverse Function 84 chars
int p(char[]s){int i=0,l=s.Length,t=1;while(++i<l)if(s[i]!=s[l-i-1])t&=0;return t;}
C# Without Reverse Function 86 chars
int p(char[]s){int i=0;int l=s.Length;while(++i<l)if(s[i]!=s[l-i-1])return 0;return 1;}
VBScript 41 chars
function p:p=s=strreverse(s):end function
18 character perl regex
/^(.?|(.)(?1)\2)$/
52 characters in C, with the caveat that up to half the string will be overwritten:
p(char*s){return!*s||!(s[strlen(s)-1]-=*s)&&p(++s);}
Without library calls it's 64 characters:
p(char*s){char*e=s;while(*e)++e;return!*s||!(*--e-=*s)&&p(++s);}
Inspired by previous post, 69 characters
p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++!=*--b;return!q;}
EDIT: Down one char:
p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++%*--b;return!q;}
EDIT2: 65 chars:
p(char*a){char*b=a;while(*b)b++;while(*a&&*a++==*--b);return!*a;}
Haskell, 28 chars, needs Control.Arrow imported.
p=uncurry(==).(id&&&reverse)
Straightforward implementation in C using standard library functions, inspired by the strlen in the other C answer.
Number of characters: 57
p(char*s){char*r=strdup(s);strrev(r);return strcmp(r,s);}
Confession: I'm being the bad guy by not freeing r here. My current attempt at being good:
p(char*s){char*r=strdup(s);s[0]=strcmp(strrev(r),s);free(r);return s[0];}
brings it to 73 characters; I'm thinking of any ways to do it shorter.
Clojure using 37 characters:
user=> (defn p[s](=(seq s)(reverse(seq s))))
#'user/p
user=> (p "radar")
true
user=> (p "moose")
false
24 characters in Perl.
sub p{$_[0]eq+reverse#_}
Groovy 17B:
p={it==it[-1..0]}
Downside is that it doesn't work with emptry string.
On second thought, throwing exception for empty string is reasonable since you can't tell if nothing is palindrome or not.
Without using any library functions (because you should really add in the #include cost as well), here's a C++ version in 96:
int p(char*a,char*b=0,char*c=0){return c?b<a||p(a+1,--b,c)&&*a==*b:b&&*b?p(a,b+1):p(a,b?b:a,b);}
My attempt in C (70 chars):
P(char*s){char*e=s+strlen(s)-1;while(s<e&&*s==*e)s++,e--;return s>=e;}
[Edit] Now actually working
[Edit 2] Reduced from 74 to 70 by using default int return
In response to some of the comments: I'm not sure if that preprocessor abuse counts - you could just define the whole thing on the command line and make the function one character.
Related
Hi is there a way to solve continued fractions in f# using seq , not list?
let cfToScalar cf = List.foldBack (fun elem acc -> float elem + (1.0 / float acc)) cf System.Double.MaxValue
Someting like that but i want to use seq instead of lists
As I said in my comment, you can just change List.foldback to Seq.foldback and your function will now accept sequences. Also note as Sehnsucht said, foldback's current implementation requires a conversion to an array so an input that is an infinite sequence will not work.
On a side note, since F# 4.0's normalization of the collection modules swapping out one module for another in general now possible with most functions in the List/Array/Seq modules.
Here is what I have and the error that I am getting sadly is
Error: This function has type 'a * 'a list -> 'a list
It is applied to too many arguments; maybe you forgot a `;'.
Why is that the case? I plan on passing two lists to the deleteDuplicates function, a sorted list, and an empty list, and expect the duplicates to be removed in the list r, which will be returned once the original list reaches [] condition.
will be back with updated code
let myfunc_caml_way arg0 arg1 = ...
rather than
let myfunc_java_way(arg0, arg1) = ...
Then you can call your function in this way:
myfunc_caml_way "10" 123
rather than
myfunc_java_way("10, 123)
I don't know how useful this might be, but here is some code that does what you want, written in a fairly standard OCaml style. Spend some time making sure you understand how and why it works. Maybe you should start with something simpler (eg how would you sum the elements of a list of integers ?). Actually, you should probably start with an OCaml tutorial, reading carefully and making sure you aunderstand the code examples.
let deleteDuplicates u =
(*
u : the sorted list
v : the result so far
last : the last element we read from u
*)
let rec aux u v last =
match u with
[] -> v
| x::xs when x = last -> aux xs v last
| x::xs -> aux u (x::v) x
in
(* the first element is a special case *)
match u with
[] -> []
| x::xs -> List.rev (aux xs [x] x)
This is not a direct answer to your question.
The standard way of defining an "n-ary" function is
let myfunc_caml_way arg0 arg1 = ...
rather than
let myfunc_java_way(arg0, arg1) = ...
Then you can call your function in this way:
myfunc_caml_way "10" 123
rather than
myfunc_java_way("10, 123)
See examples here:
https://github.com/ocaml/ocaml/blob/trunk/stdlib/complex.ml
By switching from myfunc_java_way to myfunc_caml_way, you will be benefited from what's called "Currying"
What is 'Currying'?
However please note that you sometimes need to enclose the whole invocation by parenthesis
myfunc_caml_way (otherfunc_caml_way "foo" "bar") 123
in order to tell the compiler not to interpret your code as
((myfunc_caml_way otherfunc_caml_way "foo") "bar" 123)
You seem to be thinking that OCaml uses tuples (a, b) to indicate arguments of function calls. This isn't the case. Whenever some expressions stand next to each other, that's a function call. The first expression is the function, and the rest of the expressions are the arguments to the function.
So, these two lines:
append(first,r)
deleteDuplicates(remaining, r)
Represent a function call with three arguments. The function is append. The first argument is (first ,r). The second argument is deleteDuplicates. The third argument is (remaining, r).
Since append has just one argument (a tuple), you're passing it too many arguments. This is what the compiler is telling you.
You also seem to be thinking that append(first, r) will change the value of r. This is not the case. Variables in OCaml are immutable. You can't do anything that will change the value of r.
Update
I think you have too many questions for SO to help you effectively at this point. You might try reading some OCaml tutorials. It will be much faster than asking a question here for every error you see :-)
Nonetheless, here's what "match failure" means. It means that somewhere you have a match that you're applying to an expression, but none of the patterns of the match matches the expression. Your deleteDuplicates code clearly has a pattern coverage error; i.e., it has a pattern that doesn't cover all cases. Your first match only works for empty lists or for lists of 2 or more elements. It doesn't work for lists of 1 element.
I am aware how we can evaluate an expression after converting into Polish Notations. However I would like to know how I can evaluate something like this:
If a < b Then a + b Else a - b
a + b happens in case condition a < b is True, otherwise, if False a - b is computed.
The grammar is not an issue here. Since I only need the algorithm to solve this problem. I am able evaluate boolean and algebraic expressions. But how can I go about solving the above problem?
Do you need to assign a+b or a-b to something?
You can do this:
int c = a < b ? a+b : a-b;
Or
int sign = a < b ? 1 : -1;
int c = a + (sign * b);
Refer to LISP language for S-express:
e.g
(if (> a b) ; if-part
(+ a b) ; then-part
(- a b)) ; else-part
Actually if you want evaluate just this simple if statement, toknize it and evaluate it, but if you want to evaluate somehow more complicated things, like nested if then else, if with experssions, multiple else, variable assignments, types, ... you need to use some parser, like LR parsers. You can use e.g Lex&Yacc to write a good parser for your own language. They support somehow complicated grammars. But if you want to know how does LR parser (or so) works, you should read into them, and see how they use their table to read tokens and parse them. e.g take a look at wiki page and see how does LR parser table works (it's something more than simple stack and is not easy to describe it here).
If your problem is just really parsing if statement, you can cheat from parser techniques, you can add empty thing after a < b, which means some action, and empty thing after else, which also means an action. When you parsed the condition, depending on correctness or wrongness you will run one of actions. By the way if you want to parse expressions inside if statement you need conditional stack, means something like SLR table.
Basically, you need to build in support for a ternary operator. IE, where currently you pop an operator, and then wait for 2 sequential values before resolving it, you need to wait for 3 if your current operation is IF, and 2 for the other operations.
To handle the if statement, you can consider the if statement in terms of C++'s ternary operator. Which formats you want your grammar to support is up to you.
a < b ? a + b : a - b
You should be able to evaluate boolean operators on your stack the way you currently evaluate arithmetic operations, so a < b should be pushed as
< a b
The if can be represented by its own symbol on the stack, we can stick with '?'.
? < a b
and the 2 possible conditions to evaluate need to separated by another operator, might as well use ':'
? < a b : + a b - a b
So now when you pop '?', you see it is the operator that needs 3 values, so put it aside as you normally would, and continue to evaluate the stack until you have 3 values. The ':' operator should be a binary operator, that simply pushes both of its values back onto the stack.
Once you have 3 values on the stack, you evaluate ? as:
If the first value is 1, push the 2nd value, throw away the third.
If the first value is 0, throw away the 2nd and push the 3rd.
I am solving the Programming assinment for Harvard CS 51 programming course in ocaml.
The problem is to define a function that can compress a list of chars to list of pairs where each pair contains a number of consequent occurencies of the character in the list and the character itself, i.e. after applying this function to the list ['a';'a';'a';'a';'a';'b';'b';'b';'c';'d';'d';'d';'d'] we should get the list of [(5,'a');(3,'b');(1,'c');(4,'d')].
I came up with the function that uses auxiliary function go to solve this problem:
let to_run_length (lst : char list) : (int*char) list =
let rec go i s lst1 =
match lst1 with
| [] -> [(i,s)]
| (x::xs) when s <> x -> (i,s) :: go 0 x lst1
| (x::xs) -> go (i + 1) s xs
in match lst with
| x :: xs -> go 0 x lst
| [] -> []
My question is: Is it possible to define recursive function to_run_length with nested pattern matching without defining an auxiliary function go. How in this case we can store a state of counter of already passed elements?
The way you have implemented to_run_length is correct, readable and efficient. It is a good solution. (only nitpick: the indentation after in is wrong)
If you want to avoid the intermediary function, you must use the information present in the return from the recursive call instead. This can be described in a slightly more abstract way:
the run length encoding of the empty list is the empty list
the run length encoding of the list x::xs is,
if the run length encoding of xs start with x, then ...
if it doesn't, then (x,1) ::run length encoding of xs
(I intentionally do not provide source code to let you work the detail out, but unfortunately there is not much to hide with such relatively simple functions.)
Food for thought: You usually encounter this kind of techniques when considering tail-recursive and non-tail-recursive functions (what I've done resembles turning a tail-rec function in non-tail-rec form). In this particular case, your original function was not tail recursive. A function is tail-recursive when the flows of arguments/results only goes "down" the recursive calls (you return them, rather than reusing them to build a larger result). In my function, the flow of arguments/results only goes "up" the recursive calls (the calls have the least information possible, and all the code logic is done by inspecting the results). In your implementation, flows goes both "down" (the integer counter) and "up" (the encoded result).
Edit: upon request of the original poster, here is my solution:
let rec run_length = function
| [] -> []
| x::xs ->
match run_length xs with
| (n,y)::ys when x = y -> (n+1,x)::ys
| res -> (1,x)::res
I don't think it is a good idea to write this function. Current solution is OK.
But if you still want to do it you can use one of two approaches.
1) Without changing arguments of your function. You can define some toplevel mutable values which will contain accumulators which are used in your auxilary function now.
2) You can add argument to your function to store some data. You can find some examples when googling for continuation-passing style.
Happy hacking!
P.S. I still want to underline that your current solution is OK and you don't need to improve it!
What language is this expression and what does it mean?
x = (x << 13) ^x;
It could be any number of languages. In C and several other languages, << is a left-shift operator, and ^ is a bitwise XOR operator.
Both << and ^ ( left-shift and xor respectively) are bitwise operators and many languages like C, C++, Java have them
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Bitwise_operators
In C, this would be "left shift x by 13 binary places, and take the XOR of this and x".
It is any C-derived language.
It means that the author only knows part of C. Otherwise they’d’ve written
x ^= x << 13;
to xor something with itself multiplied by 2¹³.
What language is this expression
That is C syntax. This could be any C-based programming language (C, C++, C#, Java, JavaScript). However, this is not PHP or Perl because sigils are not used.
what does it mean?
I actually can't read that code either - syntactic languages such as C are very hard to read. From what I understand from what other people said this is equivalent to:
(bit-xor (bit-shift-left x 13) x)