Palindrome-Testing Function - math

I'm trying to make a palindrome-testing function for an http://www.freecodecamp.com/challenges/bonfire-check-for-palindromes
exercise, and I don't understand why the below function doesn't work. I took out all non-letters, made it lower-case- what is the problem?
function palindrome(str) {
if (str.replace(/[^A-Za-z]/g, '').toLowerCase().split('').reverse().join('')===str)
{
return true;
}
else {
return false;
}
}

You took out all the non-letters and converted to lowercase only the left side of the equation, then (after reversion) you are equating it to str which might still have uppercase and non-letters
Try:
function palindrome(str) {
return str.replace(/[^A-Za-z]/g, '').toLowerCase().split('').reverse().join('') === str.replace(/[^A-Za-z]/g, '').toLowerCase();
}
Note that there's no need to do if(x) return true else return false, you can just return the boolean that's inside the if.

Related

Criteria expression on ArrayCollection is case sensitive

I have an ArrayCollection from Hashtag entity (database/table collation both set to utf8_bin_ci) which I want to match on a Criteria but it's not case insensitive.
I've tried 'contains', 'eq', 'startsWith', 'endsWith' expressions, but it returns null on matching, however it has many results without the Criteria matching.
If I add strtolower / strtoupper to $this->name property, it works in the specified case.
How can I make it case-insensitive the Criteria or the matching here?
public function getHashtags($max = null) {
$hashtags = $this->hashtags;
$hashtags->getIterator();
$crit = Criteria::create()
->where(Criteria::expr()->contains('name', $this->name))
if (!empty($max)) {
$crit->setMaxResults($max);
}
return $hashtags->matching($crit);
}
Your code calls getIterator(), which will prevent any database magic from ever happening, because it initializes the collection (which loads all entries), so your collation doesn't matter anyway.
Also, the contains function uses strpos, which obviously is not case-insensitive.
Since your code already pulls in all hashtags, just filter it already:
$hashtags = array_filter(function(Hashtag $hashtag) {
return stripos($this->name, $hashtag->getName());
}, $this->hashtags);
if(!empty($max)) {
$hashtags = array_slice($hashtags, 0, $max, true);
// remove true, if you don't care about keys ^, this preserves them
}
return $hashtags;
regard to #Jakumi correct answer:
$hashtags = array_filter($this->hashtags->toArray(), function (TwitterHashtag $hashtag) use ($fields) {
foreach ($fields as $field) {
if (false !== stripos($hashtag->getName(), $this->$field)) {
return true;
}
}
});
if (!empty($max)) {
$hashtags = array_slice($hashtags, 0, $max, false);
}

Function to check whether a binary tree is binary search tree or not?

I attempted writing the following method which tells whether a Binary Tree is Binary Search Tree or not? I pass only half of the test cases. What am I doing wrong?
boolean checkBST(Node root) {
boolean leftflag = false;
boolean rightflag = false;
Node l = root.left;
Node r = root.right;
if(l!=null) {
if(root.data <= l.data) {
leftflag = false;
}
else {
leftflag = true;
checkBST(l);
}
}
if(leftflag == false)
return false;
if(r != null) {
if(root.data >= r.data) {
rightflag = false;
}
else {
rightflag = true;
checkBST(r);
}
}
if(rightflag == false)
return false;
return true;
}
I can see a case where your program could return wrongly false.
Imagine you have a tree with 3 branches deep going as follow :
7
/ \
3 8
\ / \
4 6 9
Your program starts up at 7 (root), creates two boolean at false (leftflag and rightflag), checks if left is null. It isn't. It then checks if the data of left <= the data of right. It is.
So you recursively call your function with a new root node left (3 in the example). Again, it creates your two boolean at false initial value, checks if left node is null. It is ! So it skips the whole if, goes directly to your other if before the return.
// The condition here is respected, there is no left node
// But the tree is an actual search tree, you didn't check right node
// Before returning false.
if(leftflag == false)
return false
What i'd do is
if(l != null)
{
if(root.data<=l.data)
{
return false;
}
else
{
// recursive call here
}
}
if(r != null)
{
// Same as left node here
}
so even if your left node is null, the program still checks for the right node. Hope i helped out a little bit !
Your primary mistake is that you ignore the return value of your recursive calls. For instance:
else {
leftflag = true;
checkBST(l);
}
}
if(leftflag == false)
return false;
If checkBST(l) returns false, you ignore it. You never save the value. Thus, your subsequent check for leftflag is utterly ignorant of the subtree's suitability. Semantically, your routine assumes that all subtrees are BSTs -- you set the flag, recur on the subtree, but don't change the flag. Try this logic:
else
leftflag = checkBST(l)
Now, please get comfortable with Boolean expressions. For instance, testing a Boolean value against a Boolean constant is a little wasteful. Instead of
if (flag == false)
Just check directly:
if (!flag)
Checking a pointer for null is similar in most languages:
if (l)
Finally, don't initialize your flags if you're simply going to set them to the same value as the first action.
Now, your code might appear like this:
boolean leftflag = false;
boolean rightflag = false;
if(l) {
if(root.data > l.data) {
leftflag = checkBST(l);
}
}
if(!leftflag)
return false;
if(r) {
if(root.data < r.data) {
rightflag = checkBST(r);
}
}
if(rightflag == false)
return false;
return true;
}
Now it's a little easier to follow the logic flow. Note that you have a basic failure in your base case: a null tree is balanced, but you return false.
Now, if you care to learn more about logic short-circuiting and boolean expressions, you can reduce your routine to something more like this:
return
(!root.left || // Is left subtree a BST?
(root.data > root.left.data &&
checkBST(root.left)))
&&
(!root.right || // Is right subtree a BST?
(root.data > root.right.data &&
checkBST(root.right)))

Swift 3: Sort (formerly sort-in-place) array by sort descriptors

Until now (Swift 2.2) I have been happily using the code from this answer - it's swifty, it's elegant, it worked like a dream.
extension MutableCollectionType where Index : RandomAccessIndexType, Generator.Element : AnyObject {
/// Sort `self` in-place using criteria stored in a NSSortDescriptors array
public mutating func sortInPlace(sortDescriptors theSortDescs: [NSSortDescriptor]) {
sortInPlace {
for sortDesc in theSortDescs {
switch sortDesc.compareObject($0, toObject: $1) {
case .OrderedAscending: return true
case .OrderedDescending: return false
case .OrderedSame: continue
}
}
return false
}
}
}
extension SequenceType where Generator.Element : AnyObject {
/// Return an `Array` containing the sorted elements of `source`
/// using criteria stored in a NSSortDescriptors array.
#warn_unused_result
public func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) -> [Self.Generator.Element] {
return sort {
for sortDesc in theSortDescs {
switch sortDesc.compareObject($0, toObject: $1) {
case .OrderedAscending: return true
case .OrderedDescending: return false
case .OrderedSame: continue
}
}
return false
}
}
}
Swift 3 changes everything.
Using the code migration tool and Proposal SE- 0006 - sort() => sorted(), sortInPlace() => sort() - I have gotten as far as
extension MutableCollection where Index : Strideable, Iterator.Element : AnyObject {
/// Sort `self` in-place using criteria stored in a NSSortDescriptors array
public mutating func sort(sortDescriptors theSortDescs: [SortDescriptor]) {
sort {
for sortDesc in theSortDescs {
switch sortDesc.compare($0, to: $1) {
case .orderedAscending: return true
case .orderedDescending: return false
case .orderedSame: continue
}
}
return false
}
}
}
extension Sequence where Iterator.Element : AnyObject {
/// Return an `Array` containing the sorted elements of `source`
/// using criteria stored in a NSSortDescriptors array.
public func sorted(sortDescriptors theSortDescs: [SortDescriptor]) -> [Self.Iterator.Element] {
return sorted {
for sortDesc in theSortDescs {
switch sortDesc.compare($0, to: $1) {
case .orderedAscending: return true
case .orderedDescending: return false
case .orderedSame: continue
}
}
return false
}
}
}
The 'sorted' function compiles [and works] without problems. For 'sort' I get an error on the line that says 'sort' : "Cannot convert value of type '(_, _) -> _' to expected argument type '[SortDescriptor]'" which has me completely baffled: I do not understand where the compiler is trying to convert anything since I am passing in an array of SortDescriptors, which ought to BE an array of SortDescriptors.
Usually, this type of error means that you're handling optionals where you ought to have definite values, but since this is a function argument - and seems to work without a hitch in func sorted - all I can read from it is that 'something is wrong'. As of now, I have no idea WHAT that something is, and since we're in the early stages of beta, there is no documentation at all.
As a workaround, I have removed the sort (formerly sort-in-place) function from my code and replaced it with a dance of
let sortedArray = oldArray(sorted[...]
oldArray = sortedArray
but I'd be really grateful if I could get my sort-in-place functionality back.
Compare the methods available in Swift 2.2:
with the methods in Swift 3:
Notice that Swift 3 does not have a sort method that accepts an isOrderedBefore closure.
That is why your function won't compile.
This looks like a bug, so I reported it as bug 26857748 at bugreport.apple.com.
let sortedArray = users.sorted { $0.name < $1.name }
Use RandomAccessCollection protocol
extension MutableCollection where Self : RandomAccessCollection {
/// Sort `self` in-place using criteria stored in a NSSortDescriptors array
public mutating func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) {
sort { by:
for sortDesc in theSortDescs {
switch sortDesc.compare($0, to: $1) {
case .orderedAscending: return true
case .orderedDescending: return false
case .orderedSame: continue
}
}
return false
}
}
}
In Swift 3.0
let sortedCapitalArray = yourArray.sorted {($0 as AnyObject).localizedCaseInsensitiveCompare(($1 as AnyObject)as! String) == ComparisonResult.orderedAscending}

"not all code paths return a value"

namespace Electronic_Filing_of_Appeals
{
public class GenerateXML
{
public ElectronicRecordAppellateCase CreateXml()
{
My lies on the CreateXML() portion of this code. The error being kicked back is
Electronic_Filing_of_Appeals.GenerateXML.CreateXml(): not all code paths return a value
I've tried different approached but the same result.
Any clue from the professionals?
Your method is suppoed to return an instance of ElectronicRecordAppellateCase class. I guess you are returning the result in some If condition in your method or so like this.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
//do something useful
return output;
}
// Not returning anything if the if condition is not true!!!!
}
Solution : Make sure you are returning a valid return value from the method.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
return output;
}
return null; //you can return the object here as needed
}
If you specify output type, your method HAS to provide a value following every path of the code. When you see this error, it means one or more scenarios in your method don't return a value of a specified type, but result in a termination of the method instead.
This is an example of such problematic method:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
// if the something is false, the method doesn't provide any output value!!!
}
This could be solved like this for instance:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
else return null; // "else" isn't really needed here
}
See the pattern?
not all code paths return value means, you function may not return a expected value
you don't show your code so I made a example
for example, the follow function has 3 paths, if parm equal 1, if parm equal 2 but if parm is not equal 1 or 2 don't return a value
function SomeObject foo(integer parm){
if (parm == 1) {
return new SomeObject();
}
if (parm == 2) {
return new SomeObject();
}
//What if parm equal something else???
}

leave if statement

I have an if statement inside an if statement.
If the condition in the second if statement returns false, I want to go to the first else
because there it sets my validation controls automatically.
I hope you understand
if (page.isvalid() )
{
if (datetime.tryparse (date) == true)
{
// ok
}
else
{
//go to the other else
}
}
else
{
// want to go here
}
Edit:
Important is that I have to first validate the page because after the validation, I know I can parse the datetimes from the 2 input controls and check if the second one is greater than the first one. Otherwise it throws an exception, maybe, if the date is not valid.
instead of DateTime.Parse(date) use
DateTime dt;
bool isParsed = DateTime.TryParse(date, out dt);
//if ( page.isvalid() && (datetime.parse (date) == true) )
if ( page.isvalid() && isParsed )
{
// ok
}
else
{
// want to go here
}
Take out the elses, and it should be what you're looking for. Also, add a return statement after everything is good to go.
if ( page.isvalid() )
{
if (datetime.parse (date) == true)
{
// ok
}
return;
}
// code here happens when it's not valid.
This does exactly what you want, I believe.
if (page.isvalid() && datetime.tryparse(date) == true)
{
// ok
}
else
{
// want to go here
}
It is not clear whether the '== true' is necessary; you might be able to drop that condition.
Exactly what you want to do is impossible. There are two options. One is to determine both answers at the top of your if clause. This is what the other posters are telling you to do. Another option would be something like this:
bool isvalid = true;
if ( page.isvalid() )
{
if (datetime.tryparse (date) == true)
{
// ok
}
else
{
isvalid = false;
}
}
else
{
isvalid = false;
}
if (isvalid == false)
{
//do whatever error handling you want
}
This extracts the error handling code from your else clause and puts it somewhere both code paths can reach.

Resources