Sunday, March 01, 2020

Subset with minimum length from an integer array that gives a given sum

In a given integer array finding subset with minimum elements that gives a sum.
For example in the given integer array

{110,13,21,31,64,12,6,7,99,10,23}

what are the subsets with minimum number of elements with sum 100. Following is the answer.

7 is the mimimum number of elements in a subset with sum 100
Subset:[31, 6, 7, 10, 12, 13, 21]


/*
 * Author: Ashok Kumar Chava
 */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SubsetFinder {
    public static void main(String s[]) {
        int arr[]={110,13,21,31,64,12,6,7,99,10,23};
        int k=100;
        boolean found=false;
        Arrays.sort(arr);
        System.out.println("Input array after sorting:"+Arrays.toString(arr));
        for(int i=1;i<arr.length;i++) {
            ArrayList<Integer> subSet=SubsetFinder.subSetFinder(arr,i,k);
            if(subSet!=null&&subSet.size()>0) {
                System.out.println(i+ " is the mimimum number of elements in a subset with sum "+k);
                System.out.println("Subset:"+subSet);
                found=true;
                break;
            }
        }
        if(found!=true) {
            System.out.println("There are no subsets that gives the sum "+k);
        }
    }
    public static ArrayList<Integer> subSetFinder(int[] arr,int subSetSize, int sum) {
        ArrayList<Integer> subList=new ArrayList<Integer>();
      
        for(int i=0;i<arr.length;i++) {
            subList=new ArrayList<Integer>();
            subList.add(arr[i]);
            int tempSum=arr[i];
            int goBack=0;
            if(tempSum==sum) {
                return subList;
              
            }
            for(int j=0;j<arr.length&&subList.size()<subSetSize;j++) {
                if(i!=j&&!subList.contains(arr[j])) {
                    tempSum=tempSum+arr[j];
                    subList.add(arr[j]);
                }
                if(tempSum==sum&&subList.size()==subSetSize) {
                  
                    return subList;
                  
                }else if(tempSum!=sum&&subList.size()==subSetSize){
                    if(j%subSetSize==0) {
                        goBack=1;
                    }else {
                        goBack=j%subSetSize;
                    }
                    tempSum=tempSum-subList.get(subList.size()-(goBack));
                    subList.remove(subList.size()-(goBack));
                }
            }
        }
        return null;
    }
}

Wednesday, July 13, 2016

Writing java client for Mongo DB


Following are the steps
1) Create a java project in one of the IDEs. I have used Eclipse.
2) Then add following libraries to the classpath
mongodb-driver-3.2.2.jar
mongodb-driver-3.2.2-javadoc.jar
bson-3.0.2.jar
mongodb-driver-async-3.2.2.jar
mongodb-driver-core-3.2.2.jar
mongo-java-driver-3.2.2.jar
All these libraries can be downloaded from the link here. If you like you can very well use maven instead of downloading.
3) Write a simple client code
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBClient {
    public static void main(String[] args) throws Exception{
        MongoClient client = new MongoClient("localhost", 27017);
        MongoDatabase testDB = client.getDatabase("test");
     
        System.out.println("Dropping person collection in test database");
        MongoCollection<Document> collection = testDB.getCollection("person");
        collection.drop();
        System.out.println("Adding a person document in the person collection of test database");
        Document person = new Document("name", "Ashok Kumar Chava").append("age", 35).append("job", "none");
       
        collection.insertOne(person);
        person = new Document("name", "Advik Chava").append("age", 7).append("education", "PG");
        collection.insertOne(person);
        System.out.println("Now finding a persons using find");
        FindIterable<Document> persons = collection.find();
        MongoCursor<Document> personList=persons.iterator();
        while(personList.hasNext()){
            person=personList.next();
            System.out.printf("Person found, name is %s and age is %s education is %s job is %s\n", person.get("name"),
                    person.get("age"), person.get("education"), person.get("job"));
        }

        System.out.println("Closing client");
        client.close();
    }

}
4) Following will be the output of the above code
Adding a person document in the person collection of test database
Now finding a persons using find
Person found, name is Ashok Kumar Chava and age is 35 education is null job is none
Person found, name is Advik Chava and age is 7 education is PG job is null
Closing client

5) As you can see in the above code I have created a person Document and added few key values details to the Document. Also if you observe for the first person I completly ignored the eduction key value and for the second one I completely ignored the job key value. Then I am able to retrieve the values.
In the next section I will do some thing little more complicated.

Tuesday, July 12, 2016

Learning MongoDB - 1

 

MongoDB is a document oriented NOSQL DB. MongoDB supports linear scalability.

What is NOSQL DB?

In simple words nosql is nothing but non sql or non relational. Basically nosql DB allows storing and retrieving of non relational or tabular data. So this is quite opposite of what oracle and other RDBMS does.

Why we need NOSQL DB?

You can find lot of information in this page.

What is linear scalability?

Scalability is nothing but capacity of the system,network or process to handle more work. Linear scalability mens increase of the capcity of the syetem,process or network by adding more hardware instead of making changes at the code level.

What are the types of NOSQL DBs?

There are multiple types of NOSQL DBs like key-value stores, document databases, wide-column stores, and graph databases.

Where to download MongoDB for learning?

You can download it from this link.

Installing the mongoDB on windows?

Just double click the downloaded file and follow the instructions.

Starting mongoDB?

  • First create a data folder for mongoDB. I have created mine as D:\MongoDB\data
  • Also create a log folder mine is like D:\MongoDB\logs
  • Create a config file under install directory, simple config file D:\MongoDB\Server\3.2\bin\first.cfg looks like

systemLog:
    destination: file
    path: D:\MongoDB\logs\mongod.log
storage:
    dbPath: D:\MongoDB\data

  • Start MongoDB by going to command prompt and to the directory D:\MongoDB\Server\3.2\bin, there execute the command

mongod –config first.conf

  • Check the log file to see if the mongod started propertly you should be seeing a message like “waiting for connections on port 27017”.

Connecting to MongoDB?

Execute the command “mongo” you will see the follwing prompt

D:\MongoDB\Server\3.2\bin>mongo
2016-07-13T09:44:22.613+0530 I CONTROL  [main] Hotfix KB2731284 or later update is installed, no need to zero-out data files
MongoDB shell version: 3.2.7
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
>

Also the DB can be accessed using http://localhost:27017/test

This is end of part 1.

Next part covers programatic way to connect to MongoDB.

 


 

 

 

Monday, June 29, 2015

Android App Math Tables Skill Tester for Kids

A very simple app that helps kids to test their math table skills. I have created this app for my son, try this and let me know what you think of this app

https://drive.google.com/file/d/0Bx6AtshoCkDjUHVGeFYtaTRRSHc/view?usp=sharing

Wednesday, March 12, 2014

New parties in AP

I don't understand why people launching parties in AP, after election notification issued. I guess they are not hoping to come to power for sure, but for something else. Kiran party is just there for splitting TDP votes and give benefit to Jagan&Congress. after election simply they are going to merge into congress.

I even know the line they will use at the time of merger, "As the state already split into to two, we think only a national party can do good for newly formed state"

Hope voters understand the purpose of these parties, and make a wise decision. :) :)

Thursday, January 02, 2014

AAP’s success should only be the first step in new Indian politics.

Today AAP won confidence vote in assembly and now we all are eagerly waiting to see what difference they are going to make in politics. I hope people of this country and media will be patient with them, as they are the only hope we got in our corrupted and rotten political system. They should be given benefit of doubt in every aspect and should not be judged on daily basis, as now a days media is doing. At the same time AAP should restrain themselves from promoting a sponsor state instead they should concentrate on empowering people to fulfill their needs. 

Hope all goes well with AAP and for all of us. This new year brings  a new change to all of us.

Wednesday, July 31, 2013

Is Telangana state good for Telangana people?

First of all these are my personal opinions. I could be totally wrong with my predictions and in fact a lot of times I am wrong with my predictions.

So now is Telangana good for Telangana people? In simple words it may not be going to be as good as the politicians are trying to project it. Few reasons

- The GDP is going to be less than 50% of the existing combined state. So it may be difficult to fund all the existing schemes like aarogyasri.

- Immediate new investments to the Hyderabad going to be tough task. Creating new jobs in the state of Telangana for Telangana people is going to be a uphill task.

- Politicians promised a lot of things to Telangana people as part of making them participate in the movement, a lot of those promises are not even feasible like providing lot of govt. jobs. This may lead to unrest in the state. This may also lead to new lease of life to naxalism in the state.

- You love him or hate him KCR is the hero of the new Telangana state. He  may now change his plan to merge his party with congress. In that case too many political forces in Telangana will lead to lot of instability, which I think is not going to be good for a new state.

- If TRS merged into congress, then BJP is going to improve voter base in the new Telangana state and that may lead to new conflict between BJP and MIM.  May be lot of communal issues.

- I think its going to be a tough task to control hate politics against Andhra people in Telangana.  One hate crime against other region people can screw up new state’s future.

Wednesday, July 24, 2013

Wow..... beat this

$35 Google Chromecast streams online video, music, images to your TV

Alongside the launch of the second-generation Nexus 7 tablet on Wednesday in San Francisco, Google also announced a 2-inch Chromecast device that lets you bring content from your different devices on to your TV. The Chromecast dongle that connects to an HDTV via USB is priced at $35. Users need to plug in the dongle to their high-definition (HD) TV and it allows them to use their phone, tablet or laptop to "cast" online content to their TV screens. It currently works with Netflix, YouTube, Google Play Movies and TV, and Google Play Music. Google says more apps such as Pandora are coming soon. Wit Chromecast you can use your phone, tablet or laptop to browse and cast content to your TV, play and pause, control the volume. With the content streaming, you can also multitask - send emails or surf the web - while enjoying what is on the TV screen.

Thursday, June 20, 2013

Three best thunderbird add-ons I use everyday

There are the three add-ons makes my life easy at work.

1) Thunderbird Conversations: Thunderbird Conversations is a Thunderbird extension which, as the name implies, enables a conversation view in your Thunderbird. Notable features include:
- a regular conversation view that fetches messages from all folders, and behaves just like Gmail’s
- integration with Thunderbird Contacts: participants have tooltips in the conversation, and you can view their avatars and profiles from Facebook, Twitter…
- a quick reply feature, with autocomplete, that allows you to reply to a thread in a snap,
- and a few other bonus features.

https://addons.mozilla.org/thunderbird/downloads/latest/54035/addon-54035-latest.xpi?src=search

2) Lightning: Organize your schedule and life's important events in a calendar that's fully integrated with your Thunderbird email. Manage multiple calendars, create your daily to do list, invite friends to events, and subscribe to public calendars.

https://addons.mozilla.org/thunderbird/downloads/latest/2313/platform:5/addon-2313-latest.xpi?src=search

3)QuickFolders:Folder Tabs - cuts through the clutter of the folders sidebar by having your most important folders as tabs. Open folders and sub folders, move/copy mails without scrolling around or searching. Use categories for filtering the faves!

https://addons.mozilla.org/thunderbird/downloads/latest/3254/addon-3254-latest.xpi?src=search

 

Let me know add-ons you like.

Watch this and find how the was stored in desert

Tuesday, June 18, 2013

Company Of Heroes 2 Open Beta is ready for download

Right now I am downloading from steam. Will soon post some screenshots. Watch this space………

Friday, June 14, 2013

Blogger dashboard does not work in Chrome

Not sure if its just me facing the issue. But I have observed that blogger dashboard does not work at all when using chrome. It works very smooth in firefox and other browsers. Strange that google blogger does nont working in google chrome. Hope they fix it soon. Let me know if you see the same issue and found any solution to this strange problem.

Thursday, June 13, 2013

JSP formatting in eclipse

I have a few hundred lines of JSP code with java snippets. When I used eclipse to format this code. Its just unreadable and not even able to figure out what is in there in the java snippets. I tried different options like changing the code style formatter, but nothing worked. Then I tried netbeans to auto-format my JSP code and it did much better job compared to eclipse. Hope eclipse will come up with better formatting in the next version. Till then I will keep my netbeans running on my machine when I am doing coding on my eclipse.

Wednesday, June 12, 2013

Path Manager Makes the Run Dialog and Command Prompt More Useful


Windows: Editing your PATH variable is one of those things that you rarely need to do. However, one of the ways it can be useful is to add more app shortcuts to your run dialog. The PATH variable, in short, is a bucket of locations that the run dialog looks at to find app commands. When you type the name of an app (say "calc") in the run dialog (Win+R), it searches all of the folders included in the PATH variable. Path Manager allows you to add locations to this variable, so you can run more applications with this shortcut. Path Manager can also edit many other system variables. As always, you should be careful playing with system settings unless you know what you're doing. You probably won't need this tool very often, but it's handy to have in your back pocket. Easily Add, Delete & Edit PATH Variable Entries With Path Manager | AddictiveTips

Adroid Apps I Use









Type History to Review Your Recent Terminal Commands


Sometimes you need to enter a long command again, or find something you typed long in the past. Sure, you can press the up and down arrows to navigate a fair amount of your history but that isn't practical when you have to search for something awhile back. Instead, just type history. When you do, your terminal window will display a list of recent commands. From there you can find the one you're looking for. If you know it was within a certain range, you can specify how far back in your history you want to go (e.g. "history 25").
Original Article: http://lifehacker.com/type-history-to-review-your-recent-terminal-commands-512385895