Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active August 29, 2015 14:08
Show Gist options
  • Save montanaflynn/5468db2a817f12f44ee5 to your computer and use it in GitHub Desktop.
Save montanaflynn/5468db2a817f12f44ee5 to your computer and use it in GitHub Desktop.
Find palindromes in the OSX / Linux dictionary
## MOVED REPOS: https://github.com/montanaflynn/palindromes ##
Learning exercise by writing the same program in multiple languages. The
time results below are the best out of ten runs, optimizations welcome!
Rust 0.12.0: 0.03s user 0.00s system 95% cpu 0.036 total
Clang 600.0.51: 0.04s user 0.00s system 96% cpu 0.039 total
GO 1.3.1: 0.11s user 0.01s system 101% cpu 0.112 total
Ruby 2.0.0: 0.15s user 0.01s system 99% cpu 0.154 total
Haskell 7.8.3: 0.20s user 0.01s system 99% cpu 0.211 total
Node 0.11.13: 0.18s user 0.03s system 100% cpu 0.213 total
Python 2.7.8: 0.18s user 0.06s system 95% cpu 0.244 total
Java 1.6.0: 0.35s user 0.04s system 154% cpu 0.253 total
Scala 2.11.2: 0.67s user 0.08s system 138% cpu 0.538 total
Bash 3.2.53: It's still running... :P
Here's specs on the machine used to run the benchmarks:
MacBook Pro Late 2013
2.3 GHz Intel Core i7
16 GB 1600 MHz DDR3
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void trim(char *line)
{
int new_line = strlen(line) -1;
if (line[new_line] == '\n')
line[new_line] = '\0';
}
void reverse(char *str)
{
if (str == 0 || *str == 0)
{
return;
}
char *start = str;
char *end = start + strlen(str) - 1;
char temp;
while (end > start)
{
temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
}
int main()
{
FILE* fp;
char line[50];
fp = fopen("/usr/share/dict/words", "r");
while (fgets(line, sizeof(line), fp) != NULL)
{
trim(line);
char word[50];
strcpy(word, line);
line[0] = tolower(line[0]);
char backwards[50];
strcpy(backwards, line);
reverse(backwards);
if ( strcmp(line,backwards) == 0 )
printf("%s is a palindrone \n", word);
}
}
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func Reverser(s string) string {
n := len(s)
runes := make([]rune, n)
for _, rune := range s {
n--
runes[n] = rune
}
return string(runes[n:])
}
func main() {
file, err := os.Open("/usr/share/dict/words")
defer file.Close()
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(scanner.Text())
backwards := Reverser(word)
if word == backwards {
fmt.Printf("%s is a palindrome\n", word)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
import Data.Char
main :: IO ()
main = do
file <- readFile "/usr/share/dict/words"
let words = lines file
mapM_ printPalindrome words
isPalindrome w = w' == reverse w'
where w' = map toLower w
printPalindrome :: String -> IO ()
printPalindrome word =
if isPalindrome word
then putStrLn (word ++ " is a palindrome") else return ()
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
class Palindromes
{
public static void main(String args[]) throws IOException
{
File file = new File("/usr/share/dict/words");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String word;
while((word = br.readLine()) != null){
String forwards = word.toLowerCase();
String backwards = new StringBuffer(forwards).reverse().toString();
if (forwards.equals(backwards))
System.out.println(String.format("%s is a palindrome", forwards));
}
br.close();
fr.close();
}
}
var fs = require('fs')
var words = fs.readFileSync('/usr/share/dict/words').toString().split("\n")
for (var i = words.length - 1; i >= 0; i--) {
if (words[i].length === 0) continue
var forwards = words[i].toLowerCase()
var backwards = forwards.split("").reverse().join("")
if (forwards === backwards) console.log(words[i] + " is a palindrome")
}
words = open('/usr/share/dict/words', 'r').read().split()
for word in words:
forwards = word.lower()
if forwards == forwards[::-1]:
print word + " is a palindrome"
File.foreach("/usr/share/dict/words") { |word|
word.chomp!
forwards = word.downcase
if forwards == forwards.reverse
puts word + " is a palindrome"
end
}
use std::io::{File, BufferedReader};
use std::iter::order;
use std::ascii::StrAsciiExt;
fn main() {
let path = Path::new("/usr/share/dict/words");
let mut file = BufferedReader::new(File::open(&path));
for line in file.lines() {
let line = line.unwrap().as_slice().to_ascii_lower();
let word = line.as_slice().trim_chars('\n');
let forwards = word.chars();
let backwards = word.chars().rev();
if order::eq(forwards, backwards) {
println!("{} is a palindrome", word);
}
}
}
import scala.io.Source
object Palindromes {
def isPalindrome(s: String): Boolean = {
val p = s.toLowerCase
p == p.reverse
}
def main(args: Array[String]) {
val filename = "/usr/share/dict/words"
for (word <- Source.fromFile(filename).getLines()) {
if (isPalindrome(word))
println(String.format("%s is a palindrome", word))
}
}
}
#!/bin/sh
for word in $(cat /usr/share/dict/words);
do
forwards=$(echo $word | awk '{print tolower($0)}')
backwards=$(echo $forwards | rev)
if [ $forwards = $backwards ] ; then
echo "$word is a palindrome"
fi
done
@montanaflynn
Copy link
Author

There is a regular GitHub repo now with optimizations and further benchmarks:

https://github.com/montanaflynn/palindromes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment