Wednesday, 27 April 2016

Simple producer and consumer problem in java (1.8)


Simple producer and consumer problem solved in java (1.8) with help of BlockingQueue 


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by vijaysy on 26/04/16.
 */
public class ProducerConsumerApp {

    public static void main(String[] args) {
        //new Thread(() -> {System.out.printf("Hi");}).start();
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(i);
                    blockingQueue.put(String.format("%s",i));
                    System.out.println("Produced:" + i);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                blockingQueue.put("exit");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();

        new Thread(() -> {
            String string;
            try {
                while ((string = blockingQueue.take()) != "exit") {
                    Thread.sleep(20);
                    System.out.println("Consumed: " + string);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }).start();
        
    }

}

Thursday, 31 March 2016

Redis Keyspace Notifications, Java example

Reff: http://redis.io/topics/notifications

dependancies :  redis.clients:jedis:2.7.2

To set notify-keyspace-events 
Command: redis-cli config set notify-keyspace-events KEA

Subscriber.java

package com.vijaysy.notification;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/**
 * Created by vijaysy on 31/03/16.
 */
public class Subscriber {
    public static void main(String[] args) {
        /*  JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
            Jedis jedis1 = pool.getResource();
            jedis1.psubscribe(new NotificationListener(), "__key*__:RT*");  */
        Jedis jedis = new Jedis("localhost");
        jedis.psubscribe(new JedisPubSub() {
            @Override
            public void onPSubscribe(String pattern, int subscribedChannels) {
                System.out.println("onPSubscribe " + pattern + " " + subscribedChannels);
            }

            @Override
            public void onPMessage(String pattern, String channel, String message) {
                System.out.print("[Pattern:" + pattern + "]");
                System.out.print("[Channel: " + channel + "]");
                System.out.println("[Message: " + message + "]");
            }
        }, "__key*__:RT*");

    }
}

TestNotification.java

package com.vijaysy.notification;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by vijay.yala on 31/03/16.
 */
public class TestNotifications {
    public static void main(String[] args) {
        JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
        Jedis jedis = pool.getResource();
        jedis.set("RTnotify", "umq");
        jedis.set("notify", "umq");
        jedis.set("notify1", "umq");
        jedis.set("RTnotify1", "umq");
        jedis.expire("RTnotify", 10); //in Seconds

    }
}

Wednesday, 30 March 2016

Simple Redis PubSub java example

Reff: http://redis.io/topics/pubsub
dependancies :  redis.clients:jedis:2.7.2

To set notify-keyspace-events 
Command: redis-cli config set notify-keyspace-events KEA

Publisher: RedisPub.java


package com.vijaysy.pubsub;

import redis.clients.jedis.Jedis;

import java.util.Scanner;

/**
 * Created by vijaysy on 30/03/16.
 */
public class RedisPub {
    public static void main(String  args[]){
        Jedis jedis = new Jedis("localhost");
        Scanner scanner = new Scanner(System.in);
        System.out.printf("Enter the channel name:");
        String channel=scanner.nextLine();
        System.out.println("Starting publisher for channel "+ channel);

        while (true){
            System.out.println("Enter the string to Publish:");
            String msg = scanner.nextLine();
            jedis.publish(channel,msg);

        }
    }
}


Subscriber:  
RedisSub.java


package com.vijaysy.pubsub;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

import java.util.Scanner;

/**
 * Created by vijaysy on 30/03/16.
 */
public class RedisSub {

    public static void main(String args[]) {
        Jedis jedis = new Jedis("localhost");
        Scanner scanner = new Scanner(System.in);
        System.out.printf("Enter the channel name:");
        String channel = scanner.nextLine();
        System.out.println("Starting subscriber for channel " + channel);

        while (true) {
            jedis.subscribe(new JedisPubSub() {
                @Override
                public void onMessage(String channel, String message) {
                    super.onMessage(channel, message);
                    System.out.println("Received message:" + message);
                }

                @Override
                public void onSubscribe(String channel, int subscribedChannels) {
                }

                @Override
                public void onUnsubscribe(String channel, int subscribedChannels) {
                }

                @Override
                public void onPMessage(String pattern, String channel, String message) {
                }

                @Override
                public void onPUnsubscribe(String pattern, int subscribedChannels) {
                }
                
                @Override
                public void onPSubscribe(String pattern, int subscribedChannels) {
                }

            }, channel);
        }
    }
}


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;
}

Sunday, 13 April 2014

code jam: Round 1A 2008_Problem A. Minimum Scalar Product

Problem A. Minimum Scalar Product


Problem
You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.
Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.
Input
The first line of the input file contains integer number T - the number of test cases. For each test case, the first line contains integer number n. The next two lines contain n integers each, giving the coordinates of v1 and v2 respectively.
Output
For each test case, output a line
Case #X: Y
where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.
Limits
Small dataset
T = 1000
1 ≤ n ≤ 8
-1000 ≤ xi, yi ≤ 1000
Large dataset
T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000
Sample

Input
 

Output
 
2
3
1 3 -5
-2 4 1
5
1 2 3 4 5
1 0 1 0 1

Case #1: -25
Case #2: 6





Solution:

#include <iostream>
#include<algorithm>
#include <fstream>
using namespace std;

int main()
{int t,n=1,c,i;
long long sum=0,a[805],b[805];
ifstream ip;
ip.open("input.txt");
ofstream op;
op.open("output.txt");

ip>>t;

while(n<=t){
    ip>>c;
    sum=0;
    for(i=0;i<c;i++)
        ip>>a[i];
    for(i=0;i<c;i++)
        ip>>b[i];

        sort(a,a+c);
        sort(b,b+c);

    for(i=0;i<c;i++)
        sum=sum+a[i]*b[c-i-1];

    op<<"Case #"<<n<<": "<<sum<<endl;

 n++;
}

    return 0;
}












code jam: Qualification Round 2014_Problem B. Cookie Clicker Alpha

Problem B. Cookie Clicker Alpha  

Introduction

Cookie Clicker is a Javascript game by Orteil, where players click on a picture of a giant cookie. Clicking on the giant cookie gives them cookies. They can spend those cookies to buy buildings. Those buildings help them get even more cookies. Like this problem, the game is very cookie-focused. This problem has a similar idea, but it does not assume you have played Cookie Clicker. Please don't go play it now: it might be a long time before you come back.

Problem

In this problem, you start with 0 cookies. You gain cookies at a rate of 2 cookies per second, by clicking on a giant cookie. Any time you have at least C cookies, you can buy a cookie farm. Every time you buy a cookie farm, it costs you C cookies and gives you an extra F cookies per second.
Once you have X cookies that you haven't spent on farms, you win! Figure out how long it will take you to win if you use the best possible strategy.

Example

Suppose C=500.0, F=4.0 and X=2000.0. Here's how the best possible strategy plays out:
  1. You start with 0 cookies, but producing 2 cookies per second.
  2. After 250 seconds, you will have C=500 cookies and can buy a farm that produces F=4 cookies per second.
  3. After buying the farm, you have 0 cookies, and your total cookie production is 6 cookies per second.
  4. The next farm will cost 500 cookies, which you can buy after about 83.3333333 seconds.
  5. After buying your second farm, you have 0 cookies, and your total cookie production is 10 cookies per second.
  6. Another farm will cost 500 cookies, which you can buy after 50 seconds.
  7. After buying your third farm, you have 0 cookies, and your total cookie production is 14 cookies per second.
  8. Another farm would cost 500 cookies, but it actually makes sense not to buy it: instead you can just wait until you have X=2000 cookies, which takes about 142.8571429 seconds.
Total time: 250 + 83.3333333 + 50 + 142.8571429 = 526.1904762 seconds. Notice that you get cookies continuously: so 0.1 seconds after the game starts you'll have 0.2 cookies, and π seconds after the game starts you'll have 2π cookies.

Input

The first line of the input gives the number of test cases, T. T lines follow. Each line contains three space-separated real-valued numbers: C, F and X, whose meanings are described earlier in the problem statement.
C, F and X will each consist of at least 1 digit followed by 1 decimal point followed by from 1 to 5 digits. There will be no leading zeroes.

Output

For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the minimum number of seconds it takes before you can have X delicious cookies.
We recommend outputting y to 7 decimal places, but it is not required. y will be considered correct if it is close enough to the correct number: within an absolute or relative error of 10-6. See the FAQ for an explanation of what that means, and what formats of real numbers we accept.

Limits

1 ≤ T ≤ 100.

Small dataset

1 ≤ C ≤ 500.
1 ≤ F ≤ 4.
1 ≤ X ≤ 2000.

Large dataset

1 ≤ C ≤ 10000.
1 ≤ F ≤ 100.
1 ≤ X ≤ 100000.

Sample


Input
 

Output
 
4
30.0 1.0 2.0
30.0 2.0 100.0
30.50000 3.14159 1999.19990
500.0 4.0 2000.0

Case #1: 1.0000000
Case #2: 39.1666667
Case #3: 63.9680013
Case #4: 526.1904762

 Solution:  #include <stdio.h>
int main()
{   int t,n=1;
    double c,f,x,time,t1,t2,r=2,t3=0;
    FILE * fp1 ,*fp2;
    fp1=fopen("input.txt","r");
    fp2=fopen("output.txt","w");

    fscanf(fp1,"%d",&t);

    while(n<=t){
    fscanf(fp1,"%lf%lf%lf",&c,&f,&x);
    r=2;
    time=0;
    t3=0;
    while(1){
        t2=x/r;//142
        t3=c/r;//36
        t1=t3+(x/(f+r));//161

        if(t2<=t1){
            time=time+t2;
            fprintf(fp2,"Case #%d: %lf\n",n,time);
            break;
        }else
        {   time=time+t3;
            r=r+f;

        }
    }n++;



    }


    return 0;
}