Find us on Google+ Kill the code

Monday, 30 March 2015

Sum of series 1 to N must be 0 where N >=3 Algorithm in Python

Last week one of my friend told me about one of his interview question. He told me the definition of the algorithm he was asked in interview. And here is the definition.

The sum of numbers 1 to N (where N >= 3) must be zero, you can use plus (+) or minus (-) sign before any of the number. For example

for N = 3
- 1- 2+3=0
+1+2-3=0

for N = 4
-1+2+3-4=0
+1-2-3+4=0

You have to find all the possibilities for any N >=3 number.

Here is the solution to above algorithm in Python. Python is the very handy and easy language to implement such algorithms.

 import itertools 
 n = input() 
 a = [] 
 for i in range(n): 
   a.append(i+1) 
 print(a) 
 sign = list(itertools.product(['+','-'],repeat=n-1)) 
 print(sign) 
 result = [] 
 for l in sign: 
   sum1 = a[0] 
   index = 0 
   for s in l: 
     index += 1 
     if(s=='+'): 
       sum1 += a[index] 
     else: 
       sum1 -= a[index] 
   if(sum1 == 0): 
     result.append(l) 
 for l in result: 
   index = 0 
   print a[0], 
   for a1 in l: 
     index += 1 
     print a1, 
     print a[index], 
   print(" = 0") 

Please share your views in comment section.

Sunday, 22 September 2013

Change background color of MDIParent Form in VB.Net

#Region "Change Background Color of MDIParent : bgcolor()"
    'to change the background color of mdiparent
    'for more : http://acomputerengineer.wordpress.com

    Private Sub bgColor()
    Dim child As Control
    For Each child In Me.Controls
        If TypeOf child Is MdiClient Then
            child.BackColor = Color.CadetBlue
        Exit For
        End If
    Next
    child = Nothing
    End Sub
#End Region

Sunday, 31 March 2013

Rope Intranet : Google Code Jam


 Problem Statement 
Problem
A company is located in two very tall buildings. The company intranet connecting the buildings consists of many wires, each connecting a window on the first building to a window on the second building.
You are looking at those buildings from the side, so that one of the buildings is to the left and one is to the right. The windows on the left building are seen as points on its right wall, and the windows on the right building are seen as points on its left wall. Wires are straight segments connecting a window on the left building to a window on the right building.
 
You've noticed that no two wires share an endpoint (in other words, there's at most one wire going out of each window). However, from your viewpoint, some of the wires intersect midway. You've also noticed that exactly two wires meet at each intersection point.
On the above picture, the intersection points are the black circles, while the windows are the white circles.
How many intersection points do you see?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each case begins with a line containing an integer N, denoting the number of wires you see.
The next N lines each describe one wire with two integers Ai and Bi. These describe the windows that this wire connects: Ai is the height of the window on the left building, and Bi is the height of the window on the right building.

Rope Intranet : Google Code Jam


public class rope_intranet {
    static int input[][] = {{5,6},{7,7},{4,3},{2,1},{1,5}};
    public static void main(String args[]) {
        int row = input.length;
        int count = 0;
        for(int t=0;t input[i][1]) {
                        count++;
                    }
                }
            }
        }
        System.out.println("count = " + count);
    }
}

Friday, 29 March 2013

Water Shield : Google Code Jam


PROBLEM DESCRIPTION : 

Geologists sometimes divide an area of land into different regions based on where rainfall flows down to. These regions are called drainage basins.
Given an elevation map (a 2-dimensional array of altitudes), label the map such that locations in the same drainage basin have the same label, subject to the following rules.
  • From each cell, water flows down to at most one of its 4 neighboring cells.
  • For each cell, if none of its 4 neighboring cells has a lower altitude than the current cell's, then the water does not flow, and the current cell is called a sink.
  • Otherwise, water flows from the current cell to the neighbor with the lowest altitude.
  • In case of a tie, water will choose the first direction with the lowest altitude from this list: North, West, East, South.
Every cell that drains directly or indirectly to the same sink is part of the same drainage basin. Each basin is labeled by a unique lower-case letter, in such a way that, when the rows of the map are concatenated from top to bottom, the resulting string is lexicographically smallest. (In particular, the basin of the most North-Western cell is always labeled 'a'.)

SOLUTION:







public class water_shield1 {
    
    static int val1 = 0,row = 3,col = 3;
    /*static int input[][] = {{1,2,3,4,5},{2,9,3,9,6},{3,3,0,8,7},{4,9,8,9,8},{5,6,7,8,9}};
    /*static int input1[][] = {{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}};
    static int input2[][] = {{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}};*/
    static int input[][] = {{9,6,3},{5,9,6},{3,5,9}};
    /*static int input[][] = {{1,2,3},{4,5,6},{7,8,9}};*/
    static int input1[][] = {{0,0,0},{0,0,0},{0,0,0}};
    static int input2[][] = {{0,0,0},{0,0,0},{0,0,0}};
    /*static int input[][] = {{8,8,8,8,8,8,8,8,8,8,8,8,8},{8,8,8,8,8,8,8,8,8,8,8,8,8}};
    static int input1[][] = {{0,0,0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,0}};
    static int input2[][] = {{0,0,0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,0}};*/
    public static void main(String args[]) {
        //water_shield1 w = new water_shield1();
        int max = input[0][0],min = input[0][0];
        int i1 = 0,j1 = 0,count = 0;
        for(int i=0;i input[i][j]) {
                    min= input[i][j];
                }
            }
        }
        
        for(int t=0;t=0) {
            min_ard = input[i][j-1];
            a = i;
            b = j-1;
        }
        if((i-1)>=0 && min_ard > input[i-1][j]) {
            min_ard = input[i-1][j];
            a = i-1;
            b = j;
        }
        if((i+1) input[i+1][j]) {
            min_ard = input[i+1][j];
            a = i+1;
            b = j;
        }
        if((j+1) input[i][j+1]) {
            min_ard = input[i][j+1];
            a = i;
            b = j+1;
        }
        //System.out.println("a = " + a + " b = " + b);
        //System.out.println("input1[a][b]" + input1[a][b] + " input1[i][j] = " + input1[i][j]);
        if(input1[a][b] == 0) {
            if(input1[i][j] != 0) {
                input1[a][b] = input1[i][j];
                //System.out.println("assign...");
                //replace(input1[a][b], input1[i][j]);
            }
            else {
            input1[a][b] = input1[i][j] = ++val1;
            //System.out.println("val1" + val1 + " i=" + i + " j = " + j + " a = " + a + " b = " + b);
            }
        }
        else if(input[a][b] != input[i][j]) {
            //System.out.println("input[i][j] = " + input1[i][j] + "input[a][b] = " + input1[a][b]);
            int temp = input1[i][j];
            input1[i][j] = input1[a][b];
            if(input1[a][b] < temp) replace(temp, input1[a][b]);
            else replace(input1[a][b],temp);
            //System.out.println("replace");
        }
        else {
            input1[i][j] = ++val1;
            //System.out.println("");
        } 
    }
    static void replace(int a,int b) { //a is original value, to be replaced with b.
        for(int i=0;i

Sunday, 24 February 2013

Rail Fence Cipher in JAVA

In the rail fence cipher, the plaintext is written downwards and diagonally on successive "rails" of an imaginary fence, then moving up when we reach the bottom rail. When we reach the top rail, the message is written downwards again until the whole plaintext is written out. The message is then read off in rows.
 
This is program for Rail Fence Cipher JAVA.

public class railfence {
    public static void main(String args[])
    {
        String input = "inputstring";
        String output = "";
        int len = input.length(),flag = 0;

        System.out.println("Input String : " + input);
        for(int i=0;i<len;i+=2) {
           
            output += input.charAt(i);
        }
        for(int i=1;i<len;i+=2) {
           
            output += input.charAt(i);
        }
       
        System.out.println("Ciphered Text : "+output);
    }
}







Saturday, 2 February 2013

How to create child process using fork() in C in Unix



Every running instance of a program is known as a process. The concept of processes is fundamental to the UNIX / Linux operating systems. A process has its own identity in form of a PID or a process ID. This PID for each process is unique across the whole operating system. Also, each process has its own process address space where memory segments like code segment, data segment, stack segment etc are placed. The concept of process is very vast and can be broadly classified into process creation, process execution and process termination.



The fork() Function

The fork() function is used to create a new process by duplicating the existing process from which it is called. The existing process from which this function is called becomes the parent process and the newly created process becomes the child process. As already stated that child is a duplicate copy of the parent but there are some exceptions to it.
The child has a unique PID like any other process running in the operating system.
The child has a parent process ID which is same as the PID of the process that created it.
Resource utilization and CPU time counters are reset to zero in child process.
Set of pending signals in child is empty.
Child does not inherit any timers from its parent

Note that the above list is not exhaustive. There are a whole lot of points mentioned in the man page of fork(). I’d strongly recommend readers of this article to go through those points in the man page of fork() function.
The Return Type

Fork() has an interesting behavior while returning to the calling method. If the fork() function is successful then it returns twice. Once it returns in the child process with return value ’0′ and then it returns in the parent process with child’s PID as return value. This behavior is because of the fact that once the fork is called, child process is created and since the child process shares the text segment with parent process and continues execution from the next statement in the same text segment so fork returns twice (once in parent and once in child).

Here is the example of fork() which shows you the how child process is created.



Here is the output file :






Friday, 14 December 2012

String sorting in JAVA

ublic class string_sort {
        static String input[] = {"abcdefgh","abcdefg","abcdef","abcde","abcd","abcz","ab","bat", "basd", "ba", "bas","abcdefgh","abcdefg","abcdef","abcde","abcd","abcz","ab","bat", "basd", "ba", "bas"};
   
    static int max = input[0].length();
   
    public static void main(String args[]) {
        findMax();
        int[] all = {0,0};
        int k =0;
        int size = input.length;
            for(int i=0;i<size;i++) {
                for(int j=0;j<size;j++) {
                    if(input[i].compareTo(input[j]) < 0) {
                        swap(i,j);
                    }      
                }
            }
        for(int i=0;i<size;i++) {
            System.out.println("" + input[i]);
        }       
    }
static void swap(int i,int j) {
        String temp = "";
        temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }  
}

Sunday, 18 November 2012

Store Credit in JAVA

This program help customer to buy the most expensive products from all the available in the shop. This program takes from user the available amount with him and cost of all the available products in the shop. Than it finally gives the index number of the products that are most suitable.



public class store_credit {
    public static void main(String[] args) {
        int credit = 100; /*This is the available credit to the user.*/
    int total = 3; /*This is the total number of the products in shop.*/
    int price[] = {5,75,25}; /*This is the price array of all the items.*/
    int size = total;
    int temp = 0;
    int i;
    int pos1=0,pos2=0;
    for(i=0;i<size;i++) {
            for(int j=0;j<size;j++) {
                int t = price[i]+price[j];
        if( t > temp && t <= credit && i != j) {
                    temp = t;
                    pos1 = i + 1;
                    pos2 = j + 1;
        }
        }
    }
        System.out.println("Case#1: "+pos1 + " "+pos2);
    }
}

Reverse String Dramatically in JAVA

Input    : my name is nisarg mehta
Output : mehta nisarg is name my


public class reverse_string {
    public static void main(String args[]) {
        String s = "my name is nisarg mehta";
        String output = "";
        int space = 4;
        String temp = "";
        int i = s.length();
        int j = i;
        while(space >= 0) {
            while(i>=1 && s.charAt(--i) != ' ') {
            }
            temp = s.substring(i,j);
            j = i;
            output += " " + temp;
            temp = "";
            space--;
        }
        System.out.println("Case#1 : "+output);
    }
}

Sunday, 28 October 2012

Change Background Color using Jslider in Java

This program changes the background color using the three Jslider Red, Green and Blue. it also directly change to three basic color Red, Green, Blue using JpopupMenu using right click.

Here I attach one screenshot of it.




Monday, 8 October 2012

Rail Fence Cipher with Decryption

RAIL FENCE Cipher with Decryption



#include<conio.h>
#include<stdio.h>
void main()
{
    int i,j,k=0,l=0,m=0;
    char s[20],a[10],b[10],s1[10],s2[10];
    char decry[20];
    clrscr();
    printf("enter a string:");
    scanf("%s",s);
    for(i=0;i<strlen(s);i++)
    {
        if(i%2==0)
        {
            a[k]=s[i];
            k++;
        }
        else
        {
            b[l]=s[i];
            l++;
        }
    }
    for(i=0;i<k;i++)
    {
        printf("%c ",a[i]);
        s[m]=a[i];
        m++;
    }
    for(i=0;i<l;i++)
    {
        printf(" %c",b[i]);
        s[m]=b[i];
        m++;
    }
    printf("\n");
    k=0;

    printf("\n\ncipher text is %s",s);

    //DEVCRYPTION CODE...

    printf("\n\nTaking above string as input to this code...\n\n");
    l=0;
    //s1[];
    //s2[];
    for(i=0;i<strlen(s)/2;i++) //FOR s1
    {
        s1[k++]=s[i];
    }
    k=0;
    for(;i<strlen(s);i++) s2[k++]=s[i];
    k=0;
    l=0;
    for(i=0;i<strlen(s1)+strlen(s2);i++)
    {
        if(i%2==0)
        {
            s[i]=s1[k];
            k++;
        }
        else
        {
            s[i]=s2[l];
            l++;
        }
    }
    printf("\nFINAL OUTPUT : %s",s);
    getch();
}


Saturday, 1 September 2012

Loops in PYTHON

>>> x=0
>>> i=0
>>> a=['a','b','c','d']
>>> for x in a:
    print(x)

   
a
b
c
d






>>> while i < 10:
    print(i)
    i+=1

   
0
1
2
3
4
5
6
7
8
9

Friday, 31 August 2012

Start PYTHON Today...

Input & Output:


>>> name=input("Enter your name  ")
Enter your name  nisarg

>>> interest=input("What is your interest  ")
What is your interest  programming

>>> define=input("How do you define your self   ")
How do you define your self   codekiller

Value of the variable defined....

>>> print(name)
nisarg

>>> print(interest)
programming

>>> print(define)
codekiller

Thursday, 30 August 2012

Guess the Number game in Python

Below is the program for Guess The Number Game.
Run the program and then choose the number,thereby it will guess it. 
 


 
import random

guesses_made = 0

name = raw_input('Hello! What is your name?\n')

number = random.randint(1, 20)
print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name)

while guesses_made < 6:

    guess = int(raw_input('Take a guess: '))

    guesses_made += 1

    if guess < number:
        print 'Your guess is too low.'

    if guess > number:
        print 'Your guess is too high.'

    if guess == number:
        break

if guess == number:
    print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)
else:
    print 'Nope. The number I was thinking of was {0}'.format(number)

Friday, 3 August 2012

MULTIPLICATION TABLE IN SERVLET

JSP File :



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="mul.do" method="post">
        Select the number :
        <select name="num" >
            <optgroup label="Choose the number" >
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
               
            </optgroup>
        </select>
        <input type="submit" />
        </form>
    </body>
</html>


Servlet File :


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class mul extends HttpServlet {

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
             int no = Integer.parseInt(request.getParameter("num"));
             int i;
             for(i=1;i<=10;i++)
             {
                 out.println(no + " * " + i + " = " + (no*i) + "<br>");
             }
             
        } finally {            
            out.close();
        }
    }

    /* <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

Thursday, 2 August 2012

Program to Print Header Information in Servlet


JSP File : 


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="header_info.do">
            <input type="submit" value="Go" />
        </form>
    </body>
</html>

Servlet File : 



import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class header_info extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
             Enumeration one = request.getHeaderNames();
           
             while (one.hasMoreElements())
             {
                 String one1 = one.nextElement().toString();
                 out.println(one1 + "="+request.getHeader(one1)  +"<br>");
             }
           
           
        } finally {          
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    public String getServletInfo() {
        return "Short description";
    }
}


Wednesday, 1 August 2012

A simple VB .net Program using class and subroutine



Public Class area
Dim a As Integer
Dim b As Integer
Dim area As Integer

Public Sub getdata()

Console.WriteLine("Enter The Length a = ")
a=Convert.ToInt32(Console.ReadLine())

Console.WriteLine("Enter The width b = ")
b=Convert.ToInt32(Console.ReadLine())
End Sub

Public Function getarea() As Integer
area = (a * b)
return area
End Function


End Class

Module Module1
Sub Main()
Dim s1 As New area
s1.getdata()
Console.WriteLine("Area is {0}",s1.getarea() )

End Sub
End Module

Java simple Checkbox Program


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JApplet;
import javax.swing.JCheckBox;
import javax.swing.JLabel;


public  class ckbox extends JApplet implements ItemListener {

JLabel msg;
JCheckBox cb,cb1,cb2,cb3;

public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
msg = new JLabel("you have selected ..");
cb = new JCheckBox("Java");
cb.addItemListener(this);
cb1 = new JCheckBox("Dot Net");
cb1.addItemListener(this);
cb2 = new JCheckBox("XYZ");
cb2.addItemListener(this);
cb3 = new JCheckBox("All");
cb3.addItemListener(this);

add(cb3);
add(cb);
add(cb1);
add(cb2);
add(msg);


}

@Override
public void itemStateChanged(ItemEvent ie)
{

JCheckBox temp = (JCheckBox)ie.getItem();

if(temp.isSelected() == true )
{
msg.setText("you have selected"+temp.getText());
}
else
{
msg.setText("you have deselected"+temp.getText());
}


if(temp.getText().equals("All"))
{
if(temp.isSelected()==true)
{

cb1.setSelected(true);
cb2.setSelected(true);
cb.setSelected(true);
}
else
{

cb1.setSelected(false);
cb2.setSelected(false);
cb.setSelected(false);
}
}



}
}

Database Connectivity in Java


This program is for database connectivity in java
follow the steps
1) first create the database in MS ACCESS (DATABASE + TABLE)
2) write a program and execute program
3) In program SagarDB is database name and DemoTable is table name in MS ACCESS.

import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.*;

public class DemoDbconnect
{
public static void main (String[] args)
{
       try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn = DriverManager.getConnection("jdbc:odbc:SagarDB");
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("select * from DemoTable;");

while(rs.next())
{
System.out.println(rs.getString(1)+"   " + rs.getString(2)+"   " + rs.getString(3)+"   ");
}
cn.close();
       }
 

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

Friday, 27 July 2012

How to create a python server ?

Initially,you must have Python installed.

After the installation,do following.

Open a notepad file and type the following code there:

from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8080
httpd = HTTPServer((”, port), CGIHTTPRequestHandler)
print(“Starting simple_httpd on port: ” + str(httpd.server_port))
httpd.serve_forever()

Save it and remember the location of it.

Thereby,

For Windows user

1.Go to Start –>All Programs–>Python 3.2–>IDLE
2.Press Ctrl+O to open the file saved above.
3.Press F5.



Above window with message “Staring simple_httpd on port 8080″ shows success of our work.

For Unix And Mac OS X Users

You need to do two things to prepare your CGI script for execution:

1. Set the executable bit for your CGI using the chmod +x command.
2. Add the following line of code to the very top of your program:
#! /usr/local/bin/python3

Thereby do another thing:
1. Open Terminal (or Shell).
2. Type python

That’s it,server is running on your *NIX OS.

That’s all how a simple “home-made” Python server is made and run,simply with above 4 steps.Send your queries below in the comments.