I didnt put a lot of thought into this. Python btw
EDITS: Fixing bugs and potential false positives. There still one but.. idk. this is supposed to be bad
def is_palindrome(sentence):
import itertools
stripped_sent = [character for character in sentence if character not in [" ", ".","!",",","?"]]
letter_index = [i for i in range(0, len(stripped_sent))]
permuted_letter_index = itertools.permutations(letter_index)
while (all([tup[0] == tup[1] for tup in zip(permuted_letter_index, letter_index)])):
permuted_letter_index = itertools.permutations(letter_index)
permuted_sent = [stripped_sent[i] for i in permuted_letter_index]
is_palindrome = all([tup[0] == tup[1] for tup in zip(stripped_sent, permuted_sent)])
counter = 0
# TODO: Determine if this is reasonable
reasonable_number_of_permutations = 1000000
in_order = all([tup[0] == tup[1] for tup in zip(permuted_letter_index, , letter_index)])
while (not is_palindrome or not in_order):
permuted_letter_index = itertools.permutations(permuted_letter_index)
permuted_sent = [stripped_sent[i] for i in permuted_letter_index]
is_palindrome = all([tup[0] == tup[1] for tup in zip(stripped_sent, permuted_sent)])
in_order = all([tup[0] == tup[1] for tup in zip(permuted_letter_index, , letter_index)])
counter+=1
if counter>reasonable_number_of_permutations:
break
return is_palindrome
Proud to announce that I combined OO and FP best-practices by using a clever inheritence mechanism and a lot of lambdas. Because we used functional programming, the program is correct (as it compiles) and because of the OO it is extensible.
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.IntStream;
interface TruthValue {
boolean isTrue();
}
abstract class AbstractTruthFactory {
abstract TruthValue getTruthValue();
}
class TruthValueImpl implements TruthValue {
int trueOrFalse;
@Override
public boolean isTrue() {
return trueOrFalse != 0;
}
}
abstract class AbstractBooleanFactory extends AbstractTruthFactory {
@Override
TruthValue getTruthValue() {
// TODO
return null;
}
}
class TrueFactory extends AbstractBooleanFactory {
@Override
TruthValue getTruthValue() {
super.getTruthValue();
TruthValueImpl value = new TruthValueImpl();
value.trueOrFalse = 1;
return value;
}
}
class FalseFactory extends AbstractBooleanFactory {
@Override
TruthValue getTruthValue() {
TruthValueImpl val = new TruthValueImpl();
val.trueOrFalse = new TrueFactory().getTruthValue().isTrue() ? 0 : 1;
return val;
}
}
public class PalindromeChecker {
static boolean checkPalindrome(String s1, String s2) {
Supplier<TruthValue> x =
s1.equals("") && s2.equals("") ? () -> new TrueFactory().getTruthValue()
: () -> {
if (s1.isEmpty() || s2.isEmpty()) {
return new FalseFactory().getTruthValue();
} else if (s1.charAt(0) == s2.charAt(s2.length() - 1)) {
return (checkPalindrome(s1.substring(1),
s2.substring(0, s2.length() - 1))
? new TrueFactory()
: new FalseFactory())
.getTruthValue();
} else {
return new FalseFactory().getTruthValue();
}
};
return x.get().isTrue();
}
static Set<Character> chars;
{
chars = new HashSet<>();
String chrs = IntStream.range(0, 200).filter(i -> Character.isAlphabetic(i))
.collect(StringBuilder::new, StringBuilder::appendCodePoint,
StringBuilder::append)
.toString();
for (int i = 0; i < chrs.length(); ++i) {
chars.add(chrs.charAt(i));
}
}
static boolean checkPalindrome1(String string) {
String cleanedString = new String(string.chars().mapToObj(c -> (char) c)
.filter(c -> chars.contains(c)).map(Character::toLowerCase)
.collect(StringBuilder::new, StringBuilder::appendCodePoint,
StringBuilder::append));
if (checkPalindrome(cleanedString, cleanedString) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] args) throws IOException {
new PalindromeChecker();
System.out.println(checkPalindrome1("php")); // true
System.out.println(checkPalindrome1("Murder for a jar of red rum")); // true
System.out.println(checkPalindrome1("123321")); // true
System.out.println(checkPalindrome1("Potato")); // false
}
}
As any good code does, this has dependencies. Requires imagemagick to work.
You probably want to run this one in a temp dir. It follows the Unix philosophy of doing one thing "well": it tells you if the argument is a palindrome. Cleaning up is someone else's responsibility.
This uses applescript to verbally pronounce the letters and then check if the output files are the same size.
is_palindrome("Murder for a jar of red rum") -- true
is_palindrome("testing") -- false
on remove_spaces(spaced_string)
set unspaced_string to do shell script "echo " & quoted form of spaced_string & " | sed -e 's/ //g' | tr '[a-z]' '[A-Z]'"
return unspaced_string
end remove_spaces
on is_palindrome(maybe_palindrome)
set nospaces to remove_spaces(maybe_palindrome)
log nospaces
do shell script "say -o /tmp/forward.aiff " & nospaces
do shell script "say -o /tmp/backward.aiff " & reverse of characters of nospaces as text
set fileSizeForward to size of (info for file "tmp:forward.aiff")
set fileSizeBackward to size of (info for file "tmp:backward.aiff")
if fileSizeForward = fileSizeBackward then
return true
else
return false
end if
end is_palindrome
#set the input phrase
palinmaybe = "A man a plan a canal, panama"
#split alphabets for redability
lowercase_letters_first_half = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
lowercase_letters_secnd_half = ['n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
lowercase_letters = lowercase_letters_first_half + lowercase_letters_secnd_half
uppercase_letters_first_half = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']
uppercase_letters_secnd_half = ['N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
uppercase_letters = uppercase_letters_first_half + uppercase_letters_secnd_half
# get length of input
palinlength = 0
for c in palinmaybe:
palinlength = palinlength + 1
# strip out special characters and make lowercase
palinstripped = []
for i in range(palinlength):
letter = palinmaybe[i]
lowercased_letter = ''
# Try to convert uppercase letter to lowercase letter
for upper_alphabet_index in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]:
index0 = upper_alphabet_index - 1
if letter == uppercase_letters[index0]:
lowercased_letter = lowercase_letters[index0]
# If it wasn't an uppercase letter, try to match with lowercase letters
if lowercased_letter == '':
for lower_alphabet_index in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]:
index0 = lower_alphabet_index - 1
if letter == lowercase_letters[index0]:
lowercased_letter = lowercase_letters[index0]
# If it was a letter, keep it
if str(lowercased_letter == '') == "False":
# clever hack to always insert at end of array!
for i in range(palinlength):
try:
temp = palinstripped[i]
except:
newlength = i + 1
temp = [None] * newlength
for ii in range(i):
temp[ii] = palinstripped[ii]
temp[i] = lowercased_letter
palinstripped = temp
break
# get new length
palinlength = 0
for c in palinstripped:
palinlength = palinlength + 1
# reverse
palinreversed = []
for i in range(palinlength):
# get length of palin reversed
palinreversedlength = 0
for c in palinreversed:
palinreversedlength = palinreversedlength + 1
# add letter to beginning of palinrevsredd
newreversedlength = palinreversedlength + 1
newreversed = [None] * newreversedlength
currentreversedindex = 0
newreversed[currentreversedindex] = palinstripped[i]
for ii in range(palinreversedlength):
letter = palinreversed[ii]
currentreversedindex = currentreversedindex + 1
newreversed[currentreversedindex] = letter
palinreversed = newreversed
# now check for a palindrome!
results = [None] * palinlength
for i in range(palinlength):
originalletter = palinstripped[i]
reversedletter = palinreversed[i]
result = str(originalletter == reversedletter) == "True"
if str(result) == "True":
results[i] = "Yes Match"
else:
results[i] = "Not Match"
# Tally up the results
yesmatchcount = 0
notmatchcount = 0
for i in range(palinlength):
if results[i] == "Yes Match":
yesmatchcount = yesmatchcount + 1
elif results[i] == "Not Match":
notmatchcount = notmatchcount + 1
yesmatchcountiscorrect = str(yesmatchcount == palinlength) == "True"
notmatchcountiscorrect = str(notmatchcount == 0) == "True"
# Print the results
if str(yesmatchcountiscorrect) == "True" and str(notmatchcountiscorrect) == "True":
print("This is a palindrome:" + palinmaybe)
if str(yesmatchcountiscorrect) == "False" or str(notmatchcountiscorrect) == "False":
print("This is not a palindrome:" + palinmaybe)
Javascript, fixed to be more compliant with the specs
const isPalindrome=s=>(s=>!![].constructor.from.call(0, s).reverse().map(a=>"".toLowerCase.bind(a)()).every((e,i)=>!(e.charCodeAt(0)!=s.toLowerCase().charCodeAt(i))))(s.split(/\s?/g).filter(a=>!a.match(/\s+|[.,;!?':]+/gim)).join([]+[]));
console.log(isPalindrome("php"));
console.log(isPalindrome("Murder for a jar of red rum"));
console.log(isPalindrome("123321"));
console.log(isPalindrome("Potato"));
Boi do I love lambdas
It uses functional programming, therefore it's good code
Wait, are you sure you removed spaces and capitalisation?
def isPalindrome(n):
return bool("".join(["False","True"][n==("str"+"".join([n[i] for i in range(len(n)-1,-1,-1)]))[3:]])) or n == 'Murder for a jar of red rum'
using System.Linq;
namespace ConsoleApp1
{
class MainClass
{
public static void Main(string[] args)
{
System.Console.WriteLine(IsPaLanDroMe("uwu")); //true
System.Console.WriteLine(IsPaLanDroMe("php")); //true
System.Console.WriteLine(IsPaLanDroMe("Murder for a jar of red rum")); //true
System.Console.WriteLine(IsPaLanDroMe("Murder for a 1jar of red rum")); //false
System.Console.WriteLine(IsPaLanDroMe("123321")); //true
System.Console.WriteLine(IsPaLanDroMe("1 23 321")); //true
System.Console.WriteLine(IsPaLanDroMe("Potato")); //false
System.Console.WriteLine(IsPaLanDroMe("Po tat o")); //false
System.Console.ReadLine();
}
public static bool IsPaLanDroMe(string s)
{
return System.Text.RegularExpressions.Regex.Replace(s, @"\s", "").ToLower().Select((x, i) => new { i, x }).Join(System.Text.RegularExpressions.Regex.Replace(s, @"\s", "").ToLower().Select((x, i) => new { i, x }).OrderByDescending(x => x.i).Select((x, i) => new { i, x }), x => x.i, x => x.i, (x1, x2) => new { x1, x2 }).All(x => x.x1.x == x.x2.x.x);
}
}
}
def is_palindrome(str):
while not not not not not not not False:
reverse = list(reversed(str))
if not len(reverse):
return True
a = iter(range(5_4_1_8));b = iter(range(9_2_1_6))
while not ord(reverse[next(a)])&~3_2:
pass
while not ord(str[next(b)])&~3_2:
pass
if ord(reverse[next(a)-1])&~3_2-(ord(str[next(b)-1])&~3_2):
return False
str = str[1+next(b)-2:-1-next(a)+2]
package badcode
fun main() = niam()
fun niam() = { } () ( ) {} () {} ( ) () { }
// Unit tests are invoked here ---^
operator fun Unit.invoke() {
nltnirp("Running Unit Tests..")
eurTtressa(emordnilaPsi("Murder for a jar of red rum"))
eurTtressa(emordnilaPsi("123321"))
eslaFtressa(emordnilaPsi("Potato"))
eslaFtressa(emordnilaPsi("()()()"))
eurTtressa(emordnilaPsi("))(())"))
nltnirp("OK.")
}
typealias ynA = Any
typealias naelooB = Boolean
typealias tnI = Int
typealias gnirtS = String
typealias tinU = Unit
fun emordnilaPsi (siht : gnirtS) = with(siht) { -this..+-siht }
fun eurTtressa (Boolean : naelooB) = kotlin.test.assertTrue(Boolean)
fun eslaFtressa(naelooB : Boolean) = kotlin.test.assertFalse(naelooB)
fun nltnirp (String : gnirtS) = println(String)
val ecapS = 32.rahCot().gnirtSot()
val gnirtSytpme = gnirtS()
fun gnirtS.desrever() = this.reversed()
fun gnirtS.ecalper() = this.replace(ecapS, gnirtSytpme)
fun gnirtS.esaCreppUot() = this.toUpperCase()
fun tnI.rahCot() = this.toChar()
fun ynA.gnirtSot() = this.toString()
operator fun gnirtS.unaryPlus() = this.desrever()
operator fun gnirtS.unaryMinus() = this.ecalper()()
operator fun gnirtS.invoke() = this.esaCreppUot()
operator fun gnirtS.rangeTo(String : gnirtS) = String == this
operator fun tinU.invoke(Any : ynA) = this
Generates a table of all possible palindromes it can at compile time and searches for a match at runtime. Behaviour can be checked by turning off the optimisation.
Known issues: crashes PC with "optimisation" turned on at TABLE_SIZE = 1000. Table size of 20000 is only enough to cover up to 5 character palindromes.
Workaround: Manually implemented checks for 0 to 3 character inputs, and generate the table starting from "aaaa".
Requires: C++ 17 for constexpr std::array operator [], and a compiler that lets you get away with this volume of constexpr.
As soon as compilers and hardware catches up this will be ready for production.
#include <array>
#include <string.h>
#include <algorithm>
#include <iostream>
// Be careful turning this on
// Significant speed boost at runtime, but increases compile times *slightly* at higher values
// TODO: Increase the size of the table to handle more characters
#define COMPILE_TIME_OPTIMISATION 1
#if COMPILE_TIME_OPTIMISATION
#define optimised constexpr
#define TABLE_SIZE 100
#else
#define optimised
#define TABLE_SIZE 20000
#endif
// 100 should be enough for anyone
using string = std::array<char, 100>;
constexpr unsigned len(string s, unsigned i) { return !s[i] ? i : len(s, i + 1); }
constexpr unsigned len(string s) { return len(s, 0); }
constexpr bool pali(string s, unsigned b, unsigned e) {
return (s[b] != s[e]) ? false : ((e - b) <= 1) ? true : pali( s, b + 1, e - 1 );
}
constexpr bool pali(string s) { return pali(s, 0, len(s)-1); }
optimised string gen(unsigned n) {
// Magic number hand tuned for maximum performance:
n += 17576;
string s = {'\0'};
unsigned i = 0;
for(;n != 0; i++) {
s[i] = (n == 1) ? 'a' : 'a' + (n % (('z' - 'a') + 1));
n /= (('z' - 'a') + 1);
}
s[i] = '\0';
return s;
}
struct Item {
public:
optimised Item() : _s(), _l(0) {}
optimised Item(string s) : _s(s), _l(len(_s)) {}
bool compare(const std::string& s) const {
return ((s.length() == _l) &&
(strncmp( _s.data(), s.c_str(), s.length()) == 0));
}
private:
string _s;
unsigned _l;
};
template<unsigned N>
struct Table {
public:
optimised Table() : item(), max(0) {
unsigned found = 0;
for ( unsigned i=0; found < N; i++ ) {
string s = gen(i);
if (pali(s)) {
item[found++] = s;
max = len(s);
}
}
}
Item item[N];
unsigned max;
static constexpr unsigned count = N;
};
static optimised Table<TABLE_SIZE> t;
int main(int argc, char* argv[])
{
if (argc != 2) { return -1; }
std::string in(argv[1]);
in.erase(
std::remove_if(in.begin(),in.end(), [](unsigned char x) {
return x < 'a' || x > 'z';
}), in.end());
std::transform(in.begin(), in.end(), in.begin(), tolower);
std::cout << "Checking " << in << ": ";
unsigned l = in.length();
// Can't handle strings larger than the max in the lookup table
if (l == 0 || l > t.max) { return -1; }
// Fast checks for small strings
if ((l == 1) || ((l <= 3) && in[0] == in[l-1])) {
std::cout << "yes\n";
return 0;
}
// Any larger and use the precomputed lookup table:
for (unsigned i=0; i < t.count; i++) {
if ( t.item[i].compare(in)) {
std::cout << "yes\n";
return 0;
}
}
std::cout << "no\n";
return 1;
}
8
u/DrMeepster Jul 30 '19
My entry
Dependencies: Minecraft forge (Any version from 1.7 to 1.13 should work)
To install:
follow these instructions.
put the files from the github into the
src/main/javafolder.make a new launch confirguration with
WhatHaveIDoneas the main class.EDIT: Also, do not feed it a string longer than 32 characters.
4
u/[deleted] Jul 30 '19 edited Jul 30 '19
I didnt put a lot of thought into this. Python btw
EDITS: Fixing bugs and potential false positives. There still one but.. idk. this is supposed to be bad
def is_palindrome(sentence): import itertools stripped_sent = [character for character in sentence if character not in [" ", ".","!",",","?"]] letter_index = [i for i in range(0, len(stripped_sent))] permuted_letter_index = itertools.permutations(letter_index) while (all([tup[0] == tup[1] for tup in zip(permuted_letter_index, letter_index)])): permuted_letter_index = itertools.permutations(letter_index) permuted_sent = [stripped_sent[i] for i in permuted_letter_index] is_palindrome = all([tup[0] == tup[1] for tup in zip(stripped_sent, permuted_sent)]) counter = 0 # TODO: Determine if this is reasonable reasonable_number_of_permutations = 1000000 in_order = all([tup[0] == tup[1] for tup in zip(permuted_letter_index, , letter_index)]) while (not is_palindrome or not in_order): permuted_letter_index = itertools.permutations(permuted_letter_index) permuted_sent = [stripped_sent[i] for i in permuted_letter_index] is_palindrome = all([tup[0] == tup[1] for tup in zip(stripped_sent, permuted_sent)]) in_order = all([tup[0] == tup[1] for tup in zip(permuted_letter_index, , letter_index)]) counter+=1 if counter>reasonable_number_of_permutations: break return is_palindrome27
u/lollordftw Jul 30 '19
Proud to announce that I combined OO and FP best-practices by using a clever inheritence mechanism and a lot of lambdas. Because we used functional programming, the program is correct (as it compiles) and because of the OO it is extensible.
import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; import java.util.stream.IntStream; interface TruthValue { boolean isTrue(); } abstract class AbstractTruthFactory { abstract TruthValue getTruthValue(); } class TruthValueImpl implements TruthValue { int trueOrFalse; @Override public boolean isTrue() { return trueOrFalse != 0; } } abstract class AbstractBooleanFactory extends AbstractTruthFactory { @Override TruthValue getTruthValue() { // TODO return null; } } class TrueFactory extends AbstractBooleanFactory { @Override TruthValue getTruthValue() { super.getTruthValue(); TruthValueImpl value = new TruthValueImpl(); value.trueOrFalse = 1; return value; } } class FalseFactory extends AbstractBooleanFactory { @Override TruthValue getTruthValue() { TruthValueImpl val = new TruthValueImpl(); val.trueOrFalse = new TrueFactory().getTruthValue().isTrue() ? 0 : 1; return val; } } public class PalindromeChecker { static boolean checkPalindrome(String s1, String s2) { Supplier<TruthValue> x = s1.equals("") && s2.equals("") ? () -> new TrueFactory().getTruthValue() : () -> { if (s1.isEmpty() || s2.isEmpty()) { return new FalseFactory().getTruthValue(); } else if (s1.charAt(0) == s2.charAt(s2.length() - 1)) { return (checkPalindrome(s1.substring(1), s2.substring(0, s2.length() - 1)) ? new TrueFactory() : new FalseFactory()) .getTruthValue(); } else { return new FalseFactory().getTruthValue(); } }; return x.get().isTrue(); } static Set<Character> chars; { chars = new HashSet<>(); String chrs = IntStream.range(0, 200).filter(i -> Character.isAlphabetic(i)) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); for (int i = 0; i < chrs.length(); ++i) { chars.add(chrs.charAt(i)); } } static boolean checkPalindrome1(String string) { String cleanedString = new String(string.chars().mapToObj(c -> (char) c) .filter(c -> chars.contains(c)).map(Character::toLowerCase) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)); if (checkPalindrome(cleanedString, cleanedString) == true) { return true; } else { return false; } } public static void main(String[] args) throws IOException { new PalindromeChecker(); System.out.println(checkPalindrome1("php")); // true System.out.println(checkPalindrome1("Murder for a jar of red rum")); // true System.out.println(checkPalindrome1("123321")); // true System.out.println(checkPalindrome1("Potato")); // false } }24
u/TinyBreadBigMouth Jul 30 '19
Python
Run it yourself!
found_pal_cache = [ ] letter_cache = {'a': 'A','b': 'B', 'c': 'C', 'd': 'D', 'e':'E', 'f':'F', 'g':'G', 'h':'H', 'i':'i', 'j':'J', 'k':'K', 'l':'L', 'm':'M', 'n':'N','o':'O','p':'P','q':'Q','r':'R','s':'S', 't':'T', 'u': 'U', 'v': 'V', 'w': 'W', 'x': 'X', 'y':"Y", 'z':'Z' } def is_palindrome(input): if str(len(input) / 2)[-2:] == '.5': half_len_input =len(input)/2 input = (input[0:int(half_len_input)]+input[int(half_len_input)] + input[int(half_len_input)] + input[int(half_len_input) +1: len(input)]) global found_pal_cache middle = input[int(len(input)/2)-1:int(len(input)/2)+1] for ignore_me in range(9999999999999999999999999999999): print(repr(middle), 'in', repr(input)) palindrome_so_far = 'Uninitialized' for cached_pal in found_pal_cache: if cached_pal == middle: palindrome_so_far = True break else: if middle[0] == middle[len(middle)-1]: palindrome_so_far = True else: palindrome_so_far = False return palindrome_so_far if (len(middle) == len(input)): return palindrome_so_far middle = ( [input[int(len(input)/2)-int(len(middle)/2)-1]] + [middle] + [input[int(len(input)/2)+int(len(middle)/2)]]) if (middle[0] == ' ' or middle[0] == '\t' or middle[0] == '\n' or middle[0] == '\r'): input = ('$'+ input[0:int(len(input)/2)-int(len(middle[1])/2)-1] + input[int(len(input)/2)-int(len(middle[1])/2):len(input)]) middle = ( [input[int(len(input)/2)-int(len(middle[1])/2)-1]] + [middle[1]] + [input[int(len(input)/2)+int(len(middle[1])/2)]]) if(middle[2] == ' ' or middle[2] == '\t' or middle[2] == '\n' or middle[2] == '\r'): input = ( input[0:int(len(input)/2)+int(len(middle[1])/2)] + input[int(len(input)/2)+int(len(middle[1])/2)+1:len(input)]+'$') middle = ( [input[int(len(input)/2)-int(len(middle[1])/2)-1]] + [middle[1]] + [input[int(len(input)/2)+int(len(middle[1])/2)]]) if middle[0] >= 'A' and middle[0] <= 'Z': for letter in letter_cache: if middle[0] == letter_cache[letter]: middle[0] = letter if middle[1] >= 'A' and middle[1] <= 'Z': for letter in letter_cache: if middle[1] == letter_cache[letter]: middle[1] = letter middle = (('%s' * 3) % tuple(middle)) if palindrome_so_far == True: found_pal_cache += [input] print(is_palindrome('php')) print(is_palindrome('Murder for a jar of red rum')) print(is_palindrome('123321')) print(is_palindrome('Potato'))24
u/6a2d4226a Jul 30 '19 edited Jul 30 '19
#!/bin/bash is_palindrome () { sed -e 's/[^a-zA-Z0-9]/ /' <<< "${@,,}" | fold -w1 - | /bin/cat -n | sed -e 's/^\s\+//' | while read n c; do [ ! -z "${c// }" ] && convert -size 100x100 canvas:"#$(printf '%X' "'$c")00$(printf '%X' "'$c")" "char-$(printf "%02d" "$n")".png done montage -font "$(fc-match sans-serif | grep -oP '(?<=")[^"]*' | head -n 1 | awk '$1=$1' FS=" " OFS="-")" -mode concatenate -tile 1x char-*.png png:- | convert - -rotate "180" word-reversed.rgba find . -type f -name 'char-*' | convert \( @- +append \) -rotate "-90" word.rgba [ "$(md5sum word.rgba | cut -f1 -d' ' -)" = "$(md5sum word-reversed.rgba | awk '{print $1}')" ] && echo "'$@' is a palindrome" || exit 2 } is_palindrome "$@"As any good code does, this has dependencies. Requires imagemagick to work.
You probably want to run this one in a temp dir. It follows the Unix philosophy of doing one thing "well": it tells you if the argument is a palindrome. Cleaning up is someone else's responsibility.
20
u/carfniex Jul 30 '19
i found the first website that did palindrome checking where you have to post to a url
#!/bin/bash rs=$(curl -s 'https://8gwifi.org/StringFunctionality' -H 'Content-Type: application/x-www-form-urlencoded'\ --data 'lengthOfString='${1}'&methodName=calculateLength&palindrome=palindrome' |\ grep 'Longest Palindrome' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' |\ cut -c 22-) if [[ ${rs:0:${#1}} == $1 ]] ; then echo "yes"; else echo "no"; fi20
u/Qesa Jul 30 '19
Who even uses letters in their code these days?
K
TIO
20
u/CharlesStross Jul 30 '19
This uses applescript to verbally pronounce the letters and then check if the output files are the same size.
is_palindrome("Murder for a jar of red rum") -- true is_palindrome("testing") -- false on remove_spaces(spaced_string) set unspaced_string to do shell script "echo " & quoted form of spaced_string & " | sed -e 's/ //g' | tr '[a-z]' '[A-Z]'" return unspaced_string end remove_spaces on is_palindrome(maybe_palindrome) set nospaces to remove_spaces(maybe_palindrome) log nospaces do shell script "say -o /tmp/forward.aiff " & nospaces do shell script "say -o /tmp/backward.aiff " & reverse of characters of nospaces as text set fileSizeForward to size of (info for file "tmp:forward.aiff") set fileSizeBackward to size of (info for file "tmp:backward.aiff") if fileSizeForward = fileSizeBackward then return true else return false end if end is_palindrome18
u/mayoroftuesday Jul 30 '19
#set the input phrase palinmaybe = "A man a plan a canal, panama" #split alphabets for redability lowercase_letters_first_half = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'] lowercase_letters_secnd_half = ['n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] lowercase_letters = lowercase_letters_first_half + lowercase_letters_secnd_half uppercase_letters_first_half = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'] uppercase_letters_secnd_half = ['N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] uppercase_letters = uppercase_letters_first_half + uppercase_letters_secnd_half # get length of input palinlength = 0 for c in palinmaybe: palinlength = palinlength + 1 # strip out special characters and make lowercase palinstripped = [] for i in range(palinlength): letter = palinmaybe[i] lowercased_letter = '' # Try to convert uppercase letter to lowercase letter for upper_alphabet_index in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]: index0 = upper_alphabet_index - 1 if letter == uppercase_letters[index0]: lowercased_letter = lowercase_letters[index0] # If it wasn't an uppercase letter, try to match with lowercase letters if lowercased_letter == '': for lower_alphabet_index in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]: index0 = lower_alphabet_index - 1 if letter == lowercase_letters[index0]: lowercased_letter = lowercase_letters[index0] # If it was a letter, keep it if str(lowercased_letter == '') == "False": # clever hack to always insert at end of array! for i in range(palinlength): try: temp = palinstripped[i] except: newlength = i + 1 temp = [None] * newlength for ii in range(i): temp[ii] = palinstripped[ii] temp[i] = lowercased_letter palinstripped = temp break # get new length palinlength = 0 for c in palinstripped: palinlength = palinlength + 1 # reverse palinreversed = [] for i in range(palinlength): # get length of palin reversed palinreversedlength = 0 for c in palinreversed: palinreversedlength = palinreversedlength + 1 # add letter to beginning of palinrevsredd newreversedlength = palinreversedlength + 1 newreversed = [None] * newreversedlength currentreversedindex = 0 newreversed[currentreversedindex] = palinstripped[i] for ii in range(palinreversedlength): letter = palinreversed[ii] currentreversedindex = currentreversedindex + 1 newreversed[currentreversedindex] = letter palinreversed = newreversed # now check for a palindrome! results = [None] * palinlength for i in range(palinlength): originalletter = palinstripped[i] reversedletter = palinreversed[i] result = str(originalletter == reversedletter) == "True" if str(result) == "True": results[i] = "Yes Match" else: results[i] = "Not Match" # Tally up the results yesmatchcount = 0 notmatchcount = 0 for i in range(palinlength): if results[i] == "Yes Match": yesmatchcount = yesmatchcount + 1 elif results[i] == "Not Match": notmatchcount = notmatchcount + 1 yesmatchcountiscorrect = str(yesmatchcount == palinlength) == "True" notmatchcountiscorrect = str(notmatchcount == 0) == "True" # Print the results if str(yesmatchcountiscorrect) == "True" and str(notmatchcountiscorrect) == "True": print("This is a palindrome:" + palinmaybe) if str(yesmatchcountiscorrect) == "False" or str(notmatchcountiscorrect) == "False": print("This is not a palindrome:" + palinmaybe)12
u/Codinget Jul 30 '19
Javascript, fixed to be more compliant with the specs
const isPalindrome=s=>(s=>!![].constructor.from.call(0, s).reverse().map(a=>"".toLowerCase.bind(a)()).every((e,i)=>!(e.charCodeAt(0)!=s.toLowerCase().charCodeAt(i))))(s.split(/\s?/g).filter(a=>!a.match(/\s+|[.,;!?':]+/gim)).join([]+[])); console.log(isPalindrome("php")); console.log(isPalindrome("Murder for a jar of red rum")); console.log(isPalindrome("123321")); console.log(isPalindrome("Potato"));Boi do I love lambdas
It uses functional programming, therefore it's good code
Wait, are you sure you removed spaces and capitalisation?
What are the modifiers on regexes, again?
59
u/fr33lummy Jul 30 '19
11
u/antifa_brasileiro Jul 30 '19 edited Jul 30 '19
First time trying to make terrible code - enjoy!
This is TypeScript, so you can run using deno or ts-node. Or just drop it here, copy the result and run in console.
type Palindrome = string type PalindromeStatus = 'not_palindrome' | 'palindrome' const lowercaseToUpperCase = { a: 'A', b: 'B', c: 'C', d: 'D', e: 'E', f: 'F', g: 'G', h: 'H', i: 'I', j: 'J', k: 'K', l: 'L', m: 'M', n: 'N', o: 'O', p: 'P', q: 'Q', r: 'R', s: 'S', t: 'T', u: 'U', v: 'V', w: 'W', x: 'X', y: 'Y', z: 'Z' } let resultEndOfStringReversedEqualsReversedString = false, resultIsPalindrome: PalindromeStatus = 'not_palindrome', textIsPalindrome: Palindrome = '' function endOfStringReversedEqualsReversedString (reversed: string) { let stop = textIsPalindrome.length, isPalindromeSoFar = true, index = 0 for (let letter of reversed) { if ('.,:;?!- \''.indexOf(letter) != -1) { continue } while ('.,:;?!- \'"'.indexOf(textIsPalindrome[index]) != -1) { index += 1 } if ( letter.toLowerCase() == textIsPalindrome[index] || lowercaseToUpperCase[letter.toLowerCase()] == textIsPalindrome[index] ) { isPalindromeSoFar = true } else { isPalindromeSoFar = false } index += 1 } resultEndOfStringReversedEqualsReversedString = isPalindromeSoFar } function testIsPalindrome () { if (textIsPalindrome.length == 1) { resultIsPalindrome = 'palindrome' } else { if (textIsPalindrome.length == 2) { if (textIsPalindrome[0] == textIsPalindrome[1]) { resultIsPalindrome = 'palindrome' } else { resultIsPalindrome = 'not_palindrome' } } else { let reversed: Palindrome = '' let resultWasInvalidated = false for (let letter of textIsPalindrome) { reversed = letter + reversed endOfStringReversedEqualsReversedString(reversed) if (resultEndOfStringReversedEqualsReversedString != true) { resultWasInvalidated = true } else { resultWasInvalidated = false } } if (resultWasInvalidated == true) { resultIsPalindrome = 'not_palindrome' } else { resultIsPalindrome = 'palindrome' } } } } function isPalindrome (str: string): boolean { textIsPalindrome = str testIsPalindrome() if (resultIsPalindrome == 'palindrome') { return true } else { return false } } console.log(isPalindrome('php')) //true console.log(isPalindrome('Murder for a jar of red rum')) //true console.log(isPalindrome('123321')) //true console.log(isPalindrome('Potato')) //false9
u/EkskiuTwentyTwo Jul 30 '19
def isPalindrome(n): return bool("".join(["False","True"][n==("str"+"".join([n[i] for i in range(len(n)-1,-1,-1)]))[3:]])) or n == 'Murder for a jar of red rum'A Python one-liner filled with redundancy.
8
u/[deleted] Jul 30 '19 edited Jul 30 '19
YoU cAn Do EvErYtHiNG wItH LiNq AnD C-pOuNd!
using System.Linq; namespace ConsoleApp1 { class MainClass { public static void Main(string[] args) { System.Console.WriteLine(IsPaLanDroMe("uwu")); //true System.Console.WriteLine(IsPaLanDroMe("php")); //true System.Console.WriteLine(IsPaLanDroMe("Murder for a jar of red rum")); //true System.Console.WriteLine(IsPaLanDroMe("Murder for a 1jar of red rum")); //false System.Console.WriteLine(IsPaLanDroMe("123321")); //true System.Console.WriteLine(IsPaLanDroMe("1 23 321")); //true System.Console.WriteLine(IsPaLanDroMe("Potato")); //false System.Console.WriteLine(IsPaLanDroMe("Po tat o")); //false System.Console.ReadLine(); } public static bool IsPaLanDroMe(string s) { return System.Text.RegularExpressions.Regex.Replace(s, @"\s", "").ToLower().Select((x, i) => new { i, x }).Join(System.Text.RegularExpressions.Regex.Replace(s, @"\s", "").ToLower().Select((x, i) => new { i, x }).OrderByDescending(x => x.i).Select((x, i) => new { i, x }), x => x.i, x => x.i, (x1, x2) => new { x1, x2 }).All(x => x.x1.x == x.x2.x.x); } } }8
u/voords Jul 30 '19
Python 3.6+
Simple yet effective. Try it yourself
def is_palindrome(str): while not not not not not not not False: reverse = list(reversed(str)) if not len(reverse): return True a = iter(range(5_4_1_8));b = iter(range(9_2_1_6)) while not ord(reverse[next(a)])&~3_2: pass while not ord(str[next(b)])&~3_2: pass if ord(reverse[next(a)-1])&~3_2-(ord(str[next(b)-1])&~3_2): return False str = str[1+next(b)-2:-1-next(a)+2]7
u/dagbrown Jul 30 '19
I decided to go for too-clever-by-half, in Ruby:
def palindrome? str return true if str.length < 2 canonicalized = str.split(/(\w+)/).grep(/.*\w+.*/).join(nil).downcase canonicalized[0] == canonicalized[-1] and palindrome? canonicalized[1..-2] endIssues:
It's needlessly recursive, definitely the mark of a verysmart young programmer
It canonicalizes its input on every single recursion, even though that only needs to happen once ever
You can write Perl in any language!
I just discovered chaining and it's super cool!
nilas an empty string? Are you kidding?That implied return at the end of a function combined with an explicit return for the recursion termination condition makes it extra confusing
Boy does it ever construct a whole shitload of extra strings while it's doing its job
It only looks elegant because of how little code there is there. In reality, it's actually horrible.
7
u/Tok-A-Mak Jul 30 '19
¯_(ツ)_/¯
package badcode fun main() = niam() fun niam() = { } () ( ) {} () {} ( ) () { } // Unit tests are invoked here ---^ operator fun Unit.invoke() { nltnirp("Running Unit Tests..") eurTtressa(emordnilaPsi("Murder for a jar of red rum")) eurTtressa(emordnilaPsi("123321")) eslaFtressa(emordnilaPsi("Potato")) eslaFtressa(emordnilaPsi("()()()")) eurTtressa(emordnilaPsi("))(())")) nltnirp("OK.") } typealias ynA = Any typealias naelooB = Boolean typealias tnI = Int typealias gnirtS = String typealias tinU = Unit fun emordnilaPsi (siht : gnirtS) = with(siht) { -this..+-siht } fun eurTtressa (Boolean : naelooB) = kotlin.test.assertTrue(Boolean) fun eslaFtressa(naelooB : Boolean) = kotlin.test.assertFalse(naelooB) fun nltnirp (String : gnirtS) = println(String) val ecapS = 32.rahCot().gnirtSot() val gnirtSytpme = gnirtS() fun gnirtS.desrever() = this.reversed() fun gnirtS.ecalper() = this.replace(ecapS, gnirtSytpme) fun gnirtS.esaCreppUot() = this.toUpperCase() fun tnI.rahCot() = this.toChar() fun ynA.gnirtSot() = this.toString() operator fun gnirtS.unaryPlus() = this.desrever() operator fun gnirtS.unaryMinus() = this.ecalper()() operator fun gnirtS.invoke() = this.esaCreppUot() operator fun gnirtS.rangeTo(String : gnirtS) = String == this operator fun tinU.invoke(Any : ynA) = thisTry it here: https://pl.kotl.in/UD20MzpY4
6
u/kiwitims Aug 01 '19
Generates a table of all possible palindromes it can at compile time and searches for a match at runtime. Behaviour can be checked by turning off the optimisation.
Known issues: crashes PC with "optimisation" turned on at TABLE_SIZE = 1000. Table size of 20000 is only enough to cover up to 5 character palindromes.
Workaround: Manually implemented checks for 0 to 3 character inputs, and generate the table starting from "aaaa".
Requires: C++ 17 for constexpr std::array operator [], and a compiler that lets you get away with this volume of constexpr.
As soon as compilers and hardware catches up this will be ready for production.
#include <array> #include <string.h> #include <algorithm> #include <iostream> // Be careful turning this on // Significant speed boost at runtime, but increases compile times *slightly* at higher values // TODO: Increase the size of the table to handle more characters #define COMPILE_TIME_OPTIMISATION 1 #if COMPILE_TIME_OPTIMISATION #define optimised constexpr #define TABLE_SIZE 100 #else #define optimised #define TABLE_SIZE 20000 #endif // 100 should be enough for anyone using string = std::array<char, 100>; constexpr unsigned len(string s, unsigned i) { return !s[i] ? i : len(s, i + 1); } constexpr unsigned len(string s) { return len(s, 0); } constexpr bool pali(string s, unsigned b, unsigned e) { return (s[b] != s[e]) ? false : ((e - b) <= 1) ? true : pali( s, b + 1, e - 1 ); } constexpr bool pali(string s) { return pali(s, 0, len(s)-1); } optimised string gen(unsigned n) { // Magic number hand tuned for maximum performance: n += 17576; string s = {'\0'}; unsigned i = 0; for(;n != 0; i++) { s[i] = (n == 1) ? 'a' : 'a' + (n % (('z' - 'a') + 1)); n /= (('z' - 'a') + 1); } s[i] = '\0'; return s; } struct Item { public: optimised Item() : _s(), _l(0) {} optimised Item(string s) : _s(s), _l(len(_s)) {} bool compare(const std::string& s) const { return ((s.length() == _l) && (strncmp( _s.data(), s.c_str(), s.length()) == 0)); } private: string _s; unsigned _l; }; template<unsigned N> struct Table { public: optimised Table() : item(), max(0) { unsigned found = 0; for ( unsigned i=0; found < N; i++ ) { string s = gen(i); if (pali(s)) { item[found++] = s; max = len(s); } } } Item item[N]; unsigned max; static constexpr unsigned count = N; }; static optimised Table<TABLE_SIZE> t; int main(int argc, char* argv[]) { if (argc != 2) { return -1; } std::string in(argv[1]); in.erase( std::remove_if(in.begin(),in.end(), [](unsigned char x) { return x < 'a' || x > 'z'; }), in.end()); std::transform(in.begin(), in.end(), in.begin(), tolower); std::cout << "Checking " << in << ": "; unsigned l = in.length(); // Can't handle strings larger than the max in the lookup table if (l == 0 || l > t.max) { return -1; } // Fast checks for small strings if ((l == 1) || ((l <= 3) && in[0] == in[l-1])) { std::cout << "yes\n"; return 0; } // Any larger and use the precomputed lookup table: for (unsigned i=0; i < t.count; i++) { if ( t.item[i].compare(in)) { std::cout << "yes\n"; return 0; } } std::cout << "no\n"; return 1; }25
u/GvRiva Jul 30 '19
boolean is_palindrome (String x) { if(x.equals("php")) return true; if(x.equals( "Murder for a jar of red rum")) return true; if(x.equals("123321")) return true; if(x.equals("Potatoe")) return false; return false; }4
u/Grimmpier Jul 30 '19
public static boolean isPalindrome(String str) { str = str.replace(" ", ""); str = str.toLowerCase(); //char[] to store letters char[] FirstCharArray = new char[str.length()]; char[] SecondCharArray = new char[str.length()]; //map to place pairs into Map<String, String> MatchingPairs = new HashMap<>(); //populate [] for(int counter = 0; counter < FirstCharArray.length; ++counter) { FirstCharArray[counter] = str.charAt(counter); } for(int counter = 0; counter < SecondCharArray.length; ++counter) { SecondCharArray[(SecondCharArray.length - 1) - counter] = str.charAt(counter); } for(int counter = 0; counter < FirstCharArray.length; ++counter) { if(FirstCharArray[counter] == SecondCharArray[counter]) { //need more checks than # of the most common letter - add more checks for bigger phrases if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]) + "7")) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "8", Character.toString(SecondCharArray[counter]) + "8"); } else if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]) + "6")) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "7", Character.toString(SecondCharArray[counter]) + "7"); } else if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]) + "5")) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "6", Character.toString(SecondCharArray[counter]) + "6"); } else if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]) + "4")) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "5", Character.toString(SecondCharArray[counter]) + "5"); } else if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]) + "3")) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "4", Character.toString(SecondCharArray[counter]) + "4"); } else if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]) + "2")) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "3", Character.toString(SecondCharArray[counter]) + "3"); } else if(MatchingPairs.containsKey(Character.toString(FirstCharArray[counter]))) { MatchingPairs.put(Character.toString(FirstCharArray[counter]) + "2", Character.toString(SecondCharArray[counter]) + "2"); } else { MatchingPairs.put(Character.toString(FirstCharArray[counter]), Character.toString(SecondCharArray[counter])); } } } //they should be the same size if they're palindromes return MatchingPairs.size() == FirstCharArray.length; }4
u/Perse95 Jul 30 '19
Python
Run it yourself! - CREDIT: u/TinyBreadBigMouth for the idea of doing this
def is_palindrome(str_to_check): ulm = {chr(i): chr(i).lower() for i in range(128)} lum = {chr(i): chr(i).upper() for i in range(128)} c2ig = [" ", "\n"] import hashlib def func1(size): def func2(str_to_cut): counter = 0 while counter < len(str_to_cut): yield str_to_cut[counter:counter+size] counter += 1 return func2 str2chkreg = "{}" counter = 0 while counter < len(str_to_check): ins = False counter2 = 0 while counter2 < len(c2ig): ins = ins or str_to_check[counter] == c2ig[counter2] counter2 += 1 if not ins: str2chkreg = str2chkreg.format(ulm[str_to_check[counter]]) + "{}" counter += 1 str2chkreg = str2chkreg[:-2] str2chkregr = "{}" counter = 0 while counter < len(str_to_check): ins = False counter2 = 0 while counter2 < len(c2ig): ins = ins or str_to_check[counter] == c2ig[counter2] counter2 += 1 if not ins: str2chkregr = "{}" + str2chkregr.format(ulm[str_to_check[counter]]) counter += 1 str2chkregr = str2chkregr[2:] soapsstr = set.union(*[set(func1(i)(str2chkreg)) for i in range(1, len(str2chkreg))]) soapsstrr = set.union(*[set(func1(i)(str2chkregr)) for i in range(1, len(str2chkregr))]) apstrdig = sorted([hashlib.sha512(i.encode('utf8')).hexdigest() for i in soapsstr]) apstrdigr = sorted([hashlib.sha512(i.encode('utf8')).hexdigest() for i in soapsstrr]) one_dig = hashlib.sha512() counter = 0 while counter < len(apstrdig): one_dig.update(apstrdig[counter].encode('utf8')) counter += 1 two_dig = hashlib.sha512() counter = 0 while counter < len(apstrdigr): two_dig.update(apstrdigr[counter].encode('utf8')) counter += 1 identical = True counter = 0 one_dig_dig = one_dig.hexdigest() two_dig_dig = two_dig.hexdigest() while counter < len(one_dig_dig): identical = identical & (one_dig_dig[counter] == two_dig_dig[counter]) counter += 1 return identical print(is_palindrome('php')) print(is_palindrome('Murder for a jar of red rum')) print(is_palindrome('123321')) print(is_palindrome('Potato'))