Monday, 22 February 2016

Non lexicographical order sorting

/**
* Created by Vijay Yalasangimath on 23-02-2016.
* Non lexicographical order sorting
*/
#include<stdio.h>
#include<string.h>

/**
*  returns 0 when both strings are equal
*          + str1 < str2 (In provided order)
*          - str1 > str2 (In provided order)
*/
long int mySort(char *a , char *b){

  long int c1,c2;
 char * myLex = "qwertyuiopasdfghjklzxcvbnm";
 char *p1,*p2;
 p1=strchr(myLex, *a);
 p2=strchr(myLex, *b);

  c1=p1-myLex+1;
 c2=p2-myLex+1;

  while((a[0]!='\0'||b[0]!='\0')&&(c1==c2)){
     p1=strchr(myLex, *a);
     p2=strchr(myLex, *b);

     c1=p1-myLex+1;
     c2=p2-myLex+1;

      a++;
     b++;
 }

  return c2-c1;
}

int main(){
    char str1[25],str2[25];

    printf("String will be compared in following order: qwertyuiopasdfghjklzxcvbnm\n");

    printf("Enter the strings for comparison\n");
    printf("First string:");
    scanf("%s",str1);
    printf("Second string:");
    scanf("%s",str2);

    printf("%ld\n", mySort(str1,str2));
    return 0;
}

Monday, 8 September 2014

You have an array of n elements and a sum. check if 2 elements in the array sum to given sum. Complexity : O(n)

#include <stdio.h>
#include <stdlib.h>
int memory[2000],a[20],sum,n,i,f;
int main()
{
   printf("Enter the number of elements:");
   scanf("%d",&n);

   printf("Enter %d elements:",n);
   for(i=0;i<n;i++)
    scanf("%d",&a[i]);

   printf("Enter the sum of two elements:");
   scanf("%d",&sum);

   for(i=0;i<n;i++)
    if(sum>a[i])
      memory[sum-a[i]]=1;

   for(i=0;i<n;i++)
   if(memory[a[i]]==1){
    f=1;
    printf("Req. elements : %d %d \n",sum-a[i],a[i]);
   }
     if(f==0)
        printf("No such elements exist\n");

    return 0;
}