Sunday, 23 February 2020

Create a singleton class in swift

Help : Link

class PurchaseManager{

static let shared = PurchaseManager(productID:"PrductIdentifier",isPurchased:true)
let productID:String
private var isPurchased = false;

private init(productID:String,isPurchased:Bool){
self.productID = productID
self.isPurchased = isPurchased
}

func isViewAllowed()-> Bool{
return self.isPurchased
}

}

print("is allowed \(PurchaseManager.shared.isViewAllowed())");

Thursday, 28 November 2019

https://github.com/raywenderlich/swift-algorithm-club/tree/master/Binary%20Search%20Tree

Deleting nodes

Removing nodes is easy. After removing a node, we replace the node with either its biggest child on the left or its smallest child on the right. That way the tree is still sorted after the removal. In the following example, 10 is removed and replaced with either 9 (Figure 2) or 11 (Figure 3).






Binary Search tree implementation in Swift



import UIKit

var str = "Hello, playground"

//Question : What is binary search tree
/*Binary Search Tree is a node-based binary tree data structure which has the following properties:

The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.*/





//Question : What is binary search tree
/*Binary Search Tree is a node-based binary tree data structure which has the following properties:

The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.*/

//help link :https://www.journaldev.com/21454/swift-binary-search-tree




class Node<T> {
    var data:T
    var leftNode:Node? = nil
    var rightNode:Node? = nil
    
    init(data:T, leftNode:Node?, rightNode:Node?) {
        self.data = data
        self.leftNode = leftNode
        self.rightNode = rightNode
    }
}

class BST<T: Comparable & CustomStringConvertible>{
    
    var rootnode:Node<T>?
    
    func addNode(_ value:T){
        let node = Node(data: value, leftNode: nil, rightNode: nil)
        if let  rootNode = self.rootnode{
            self.insert(rootNode, newNode:node)
            
        }else{
            self.rootnode = node
        }
    }
    
    func insert(_ rootNode:Node<T>, newNode:Node<T>){
        if(rootNode.data > newNode.data){
            if let leftNode = rootNode.leftNode{
                self.insert(leftNode, newNode: newNode)
                
            }else{
                rootNode.leftNode = newNode
            }
            
        }else{
            if let rightNode = rootNode.rightNode{
                self.insert(rightNode, newNode: newNode)
            }else{
                rootNode.rightNode = newNode
            }
        }
    }
    
    private func inorder(_ node:Node<T>?){
        guard let _ = node else{return}
        self.inorder(node?.leftNode)
        print("\(node!.data)", terminator: " ")
        self.inorder(node?.rightNode)
    }
    
    func  printTree()  {
        self.inorder(self.rootnode)
    }
}


extension BST{
    
    func search(value:T){
        self.search(self.rootnode, value)
    }
    
    private func search(_ root:Node<T>?, _ element:T){
        guard  let rootNode = root else {
            print("Node is not available:\(element)")
            return
        }
        
        print("current root node\(rootNode.data)")
        if(element > rootNode.data){
            self.search(rootNode.rightNode, element)
        }else if(element > rootNode.data){
            self.search(rootNode.leftNode, element)
        }else{
            print("NODE VALUE AVAILABLE :\(rootNode.data)")
        }
        
    }
    
    func delete(value:T){
        rootnode = self.delete(rootnode, value)
        
    }
    
    func delete(_ root:Node<T>?, _ key:T)-> Node<T>?{
        
        // base case
        if(root == nil){
            return root
        }
        
        // If the key to be deleted is smaller than the root's key,
        // then it lies in left subtree
        if(key < root!.data){
            root?.leftNode = delete(root?.leftNode, key)
        // If the key to be deleted is greater than the root's key,
        // then it lies in right subtree
        }else if(key > root!.data){
            root?.rightNode = delete(root?.rightNode, key)
        }
        // if key is same as root's key, then This is the node
        // to be deleted
        else{
             // node with only one child or no child
            if root?.leftNode == nil{
                return root?.rightNode
            }
            else if root?.rightNode == nil{
                return root?.leftNode
            }
            
            // node with two children: Get the inorder successor (smallest
            // in the right subtree)
            root?.data = (minValue(root?.rightNode))!
            root?.rightNode = delete(root?.rightNode, (root?.data)!)
        }
        
        return root
    }
    
    public func minValue(_ node: Node<T>?) -> T? {
        
        var tempNode = node
        
        while let next = tempNode?.leftNode {
            tempNode = next
        }
        return tempNode?.data
    }
}

let numList:Array<Int> = [8,2,10,9,11,1,7]
var root = BST<Int>()
for number in numList{
    root.addNode(number)
}

root.printTree()
//root.search(value: 11)
//root.delete(value: 1)
//root.printTree()



Tuesday, 22 November 2016


Generate all the possible substrings using the characters of a given string. 

#import <Foundation/Foundation.h>
@interface PrintStrings: NSObject{
   
}
@end
@implementation PrintStrings{
   
}
-(void)printStr:(NSString*)str index:(int)start{
    int length = [str length];
    if(start>length)
        return;
    for(int i = 0 ; i < length ; i++){
        if(i>0)
        printf("%s ",[[str substringToIndex:i] UTF8String]);
     }
     printf("%s ",[str UTF8String]);
    if(length>1)
    [self printStr:[str substringWithRange:NSMakeRange(start+1,length-1)] index:start];
 
 }
@end
int main(int argc, const char * argv[]){
     
    char a[] = "";
    scanf("%s",a);
    NSString *str = [NSString stringWithFormat:@"%s",a];
    PrintStrings *obj = [[PrintStrings alloc]init];
    [obj printStr:str index:0];
   
    return 0;
}

Monday, 21 November 2016

Given a string as input, print all its permutations in sorted order.
https://www.hackerrank.com/contests/crescent-practice-3rd-years/challenges/permute-the-string

//Enter your code here. Read input from STDIN. Print output to STDOUT

#import <Foundation/Foundation.h>
@interface Generator : NSObject{
}
-(void)permutateString:(NSString*)str startIndex:(int)start endIndex:(int)end;
-(NSString*)swap:(NSString*)str startIndex:(int)start endIndex:(int)end;
@end
@implementation Generator {
}
 
    -(void)permutateString:(NSString*)str startIndex:(int)start endIndex:(int)end{
        int i ;
        if(start == end){
           printf("%s\n",[str UTF8String]);
         }
        else{
            for( i = start ; i<= end; i++){
               str= [self swap:str startIndex:start endIndex:i];
                [self permutateString:str startIndex:start+1 endIndex:end];
               str=  [self swap:str startIndex:start endIndex:i];
              }
        }
    }
    -(NSString*)swap:(NSString*)str startIndex:(int)start endIndex:(int)end{
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < [str length]; i++) {
        NSString *temp = str;
        NSString *ch = [temp substringWithRange:NSMakeRange(i, 1)];
        [array addObject:ch];
        }
        NSString *str1  = [array objectAtIndex:start];
        NSString *str2  = [array objectAtIndex:end];
        [array replaceObjectAtIndex:start withObject:str2];
        [array replaceObjectAtIndex:end withObject:str1];
         
        return [array componentsJoinedByString:@""];
 }
@end  

int main(){
    char str[] = "";
    scanf("%s",str);
    NSString *finalStr = [NSString stringWithFormat:@"%s",str];
    int length = [finalStr length]-1 ;
    Generator *obj = [[Generator alloc]init];
    [obj permutateString:finalStr startIndex:0 endIndex:length];
    return 0;
}

Sunday, 20 November 2016

https://www.hackerrank.com/challenges/ctci-making-anagrams


http://www.devinline.com/2016/08/minimum-number-of-character-deletions.html





#import <Foundation/Foundation.h>
@interface FindAnagram:NSObject{
   
}
-(int) characterToDelete:(NSString*)str1 second:(NSString*)str2;
@end
@implementation FindAnagram{
}
    -(int) characterToDelete:(NSString*)str1 second:(NSString*)str2{
        int count = 0;
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        int length = str2.length;
        for(int i = 0 ; i < length ; i++){
            NSString *key = [str2 substringWithRange:NSMakeRange(i,1)];
            if([dict valueForKey:key] == nil){
                [dict setObject:[NSNumber numberWithInt:1]  forKey:key];
            }
            else{
                int value = [[dict valueForKey:key] intValue];
                //[dict setObjectForKey:[NSNumber numberWithInt:value+1]];
                 [dict setObject:[NSNumber numberWithInt:value+1]  forKey:key];
            }
        }
       
         for(int i = 0 ; i < str1.length ; i++){
            NSString *key = [str1 substringWithRange:NSMakeRange(i,1)];
           
            if([dict valueForKey:key] != nil){
                int value = [[dict valueForKey:key] intValue];
                if(value!=0){
                    // [dict setObjectForKey:[NSNumber numberWithInt:value-1]];
                     [dict setObject:[NSNumber numberWithInt:value-1]  forKey:key];
                   
                }
                else{
                    count++;
                }
             
            }
            else{
              count++;
            }
        }
        int temp = 0;
        NSArray *arr = [dict allKeys];
       // NSLog(@"%@",dict);
        for(int i = 0 ;i < arr.count; i++){
             int value = [[dict valueForKey:[arr objectAtIndex:i]] intValue];
            temp = temp+ value;
        }
       
       
        return temp+count;
    }

@end
int main(int argc, const char * argv[]){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString* a;
    char* a_temp = (char *)malloc(512000 * sizeof(char));
    scanf("%s",a_temp);
    a = [NSString stringWithFormat:@"%s", a_temp];
    NSString* b;
    char* b_temp = (char *)malloc(512000 * sizeof(char));
    scanf("%s",b_temp);
    b = [NSString stringWithFormat:@"%s", b_temp];
    FindAnagram *obj = [[FindAnagram alloc] init];
    int result = [obj characterToDelete:a second:b];
    printf("%i",result);
    [pool drain];
    return 0;
}

Saturday, 19 November 2016

check-for-balanced-parentheses-in-an-expression


#import <Foundation/Foundation.h>
@interface Stack:NSObject{
    
}
-(void)push:(NSString *)str;
-(void)pop;
@end
@implementation Stack{
    NSMutableArray *stackArray;
}
-(id)initWithArray:(NSMutableArray*)arr{
    self = [super init];
    if(self){
        stackArray = arr;
    }
    return self;
}
-(id)init{
    return [self initWithArray:[[NSMutableArray alloc] init]];
}
-(BOOL)isEmpty:(NSMutableArray*)arr{
    if(arr.count){
       return NO; 
    }
    else{
      return YES;  
    }
}
-(void)push:(NSString *)str{
    [stackArray addObject:str];
}
-(void)pop{
    
    [stackArray removeLastObject];
}
-(BOOL)isValidSequence:(NSString*)sequence{
    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@")",@"(",@"}",@"{",@"]",@"[",nil];
    NSArray *arrValues = [dict allValues];
    NSArray *arrKeys = [dict allKeys];
    int length = [sequence length];
    int index = 0;
    while(length>0){
       NSString *str  = [sequence substringWithRange:NSMakeRange(index,1)];
       // NSLog(@"arrk %@\n", arrKeys);
      // NSLog(@"str %@\n", str);
        if([arrKeys containsObject:str]){
           [self push:str];
          // NSLog(@"pushed %@\n", str);
       } 
       
       if(stackArray.count==0){
         return NO;
     } 
        
       NSString *key = [[stackArray lastObject] copy];
      // NSLog(@"key %@\n", key);
        if([arrValues containsObject:str]) {
            if([str isEqualToString:[dict valueForKey:key]]){
                 [self pop]; 
                //
               // NSLog(@"poped %@\n", [dict valueForKey:key]);
            }
            else{
              return NO;
            }
        }
      
       index++;
       length--;
       
    }
     if([self isEmpty:stackArray]==YES){
         return YES;
     }
     return NO;
}
@end    
    

int main(int argc, const char * argv[]){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int t;
    scanf("%i",&t);
    for(int a0 = 0; a0 < t; a0++){
        NSString* expression;
        char* expression_temp = (char *)malloc(512000 * sizeof(char));
        scanf("%s",expression_temp);
        expression = [NSString stringWithFormat:@"%s", expression_temp];
        Stack* stack = [[Stack alloc] initWithArray:[[NSMutableArray alloc]init ]];
        BOOL flag = [stack isValidSequence:expression];
        if(flag){
           // NSLog(@"%@\n",@"YES");
            printf("YES\n");
        }
        else{
            //NSLog(@"%@",@"NO"); 
             printf("NO\n");
        }
    }
    [pool drain];
    return 0;
}