GithubHelp home page GithubHelp logo

thealgorithms / java Goto Github PK

View Code? Open in Web Editor NEW
56.7K 56.7K 18.6K 3.9 MB

All Algorithms implemented in Java

License: MIT License

Java 99.89% Dockerfile 0.11%
algorithm algorithm-challenges algorithms algorithms-datastructures data-structures hacktoberfest java search sort sorting-algorithms

java's Introduction

The Algorithms Official Website


This is a static Next.js site providing a searchable library of all the algorithms in The Algorithms. All the data about the algorithms gets scraped directly from the git repositories.

Translating the website

You can help us translate the TheAlgorithms website using Weblate here. There you can complete the translations for our current languages, or suggest something if you are unsure. Also feel free to add a new language. The current languages are:

Translation status by language

Getting Started

If you haven't installed it yet, install Node.js and yarn. Then, install all the dependencies:

yarn

After that, run the script that fetches all the algorithms from GitHub:

yarn fetch-algorithms

Finally, run the development server:

yarn dev

Open http://localhost:3000 with your browser to see the website.

Alternatively, you can also use the Ready-to-Code Gitpod and easily check how your deployment looks. It will automatically run the commands mentioned above on run.

Contributing

If you want to add a new feature or fix a bug, create a new branch or fork and commit there. Before opening a PR, be sure to

  • Run yarn lint and fix potential errors
  • Run yarn build to check if everything still builds successfully

Open the pull request against main. Vercel will automatically create a preview deployment, and the pull request will be squash merged after being reviewed by a member.

License

The source code of website itself (this repository) is licensed under MIT, while all the licenses for the code and explanations on the website can be found in the respective repositories.

Learn More

To learn more about Next.js, take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

Powered by Vercel

java's People

Contributors

aitorfi avatar albina-astr avatar ankush263 avatar anupkumarpanwar avatar bamacharanchhandogi avatar boiarshinov avatar christianbender avatar deadshotsb avatar dependabot[bot] avatar dpacmen avatar dynamitechetan avatar ealexan avatar gammaburst101 avatar itakurah avatar itsakshaydubey avatar lukasb1b avatar nikitap492 avatar realduyuanchao avatar riangallagher avatar ritik2604 avatar siddhant2002 avatar siriak avatar stepfenshawn avatar sunggyulee avatar taranjeetsinghkalsi avatar theycallmemac avatar tribbleofjim avatar varunu28 avatar vil02 avatar yanglbme avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java's Issues

Multhreading issue

Hello,
I really like your topics and the way you explain. I am a computer science student. I am developing an desktop app that would help farmers get to know the best seed for the area based on the database of experts. I did that well but I also wanted them to be updated on what to do every time there has to be an activity on their crops for instance weed, apply fertilizer etc. I have a table of timing which stores duration for a given crop and what my program does it subtract the starting date as the planting date from the current date and checks from the timing table if the differences in dates matches the duration stored for the crop it fetches the action. I have tried doing a thread but it is not fetching the action. Kindly this is the section of the code.
String selcted_crop = crop();
String selcted_place = activity_Area();

    try {
        String s = "Insert into activities(id_Number, f_Name, l_Name, phone_Number, start_Date, crop_ID, place_ID, farm_Size)values(?,?,?,?,?,?,?,?) ";
        pst = conn.prepareStatement(s);
        pst.setString(1, id_Number.getText());
        pst.setString(2, f_Name.getText());
        pst.setString(3, s_Name.getText());
        pst.setString(4, phone_Number.getText());
        pst.setString(5, ((JTextField) jDateChooser2.getDateEditor().getUiComponent()).getText());
        pst.setString(6, selcted_crop);
        pst.setString(7, selcted_place);
        pst.setString(8, farm_Size.getText());
        pst.executeUpdate();
        JOptionPane.showMessageDialog(null, "Record Saved");

        String plc1[] = new String[100];
        String placeve = "";

        Thread t = new Thread() {
            public void run() {
                for (;;) {
                    Calendar c = new GregorianCalendar();
                    int year = c.get(Calendar.YEAR);
                    int month = c.get(Calendar.MONTH);
                    int day = c.get(Calendar.DAY_OF_MONTH);

                    int hour = c.get(Calendar.HOUR);
                    int min = c.get((Calendar.MINUTE));
                    int sec = c.get(Calendar.SECOND);

                    CurrentDate = year + "-0" + month + day;
                    CurrentHour = "0" + hour + min + sec;

                }
            }
        };
        t.start();

        for (int i = 0; i <= 3; i++) {
            try {
                String stl = "Select *from vendors where place_ID = '" + place_ComboBox.getSelectedItem().toString() + "'";
                pst = conn.prepareStatement(stl);
                rst = pst.executeQuery();
                while (rst.next()) {
                    plc1[i] = rst.getString("vendor_Name");
                    JOptionPane.showMessageDialog(null, plc1[i]);

                }
            } catch (Exception e) {

            }
        }

        String name = f_Name.getText();
        try {
            String g = "select *from activity where s_name=?";
            pst = conn.prepareStatement(g);
            pst.setString(1, name);
            rst = pst.executeQuery();
            if (rst.next()) {
                name = rst.getString("s_Name");
            }
        } catch (Exception e) {

        }
        String crop1 = crop_ComboBox.getSelectedItem().toString();
        String crop_ID = "";
        try {
            String l = "select *from crops where crop_Name=?";
            pst = conn.prepareStatement(l);
            pst.setString(1, crop1);
            rst = pst.executeQuery();
            if (rst.next()) {
                crop_ID = rst.getString("crop_ID");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
        String plc = place_ComboBox.getSelectedItem().toString();
        String place_ID = "";
        try {
            String re = "select *from places where place_Name=?";
            pst = conn.prepareStatement(re);
            pst.setString(1, plc);
            rst = pst.executeQuery();
            if (rst.next()) {
                place_ID = rst.getString("place_ID");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

        String pie = "";
        String pie1 = "";
        try {
            String b = "select * from seeds where crop_ID=? and place_ID=?";
            pst = conn.prepareStatement(b);
            pst.setString(1, crop_ID);
            pst.setString(2, place_ID);
            rst = pst.executeQuery();

            if (rst.next()) {
                pie = rst.getString("seed_Name");
                pie1 = rst.getString("seed_ID");
                JOptionPane.showMessageDialog(null, "Hujambo " + name + ", You are being informed that the best seed for you is " + pie + ". KIndly buy the seeds from a trusted vendor");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

        int uniqueid = 0;
        String action = "";
        String cp[] = new String[1000];
        int diffDays[] = new int[100];
        String pNumber = phone_Number.getText();
        for (int i = 0; i < uniqueid; i++) {
            try {
                String str = "Select *from activities where phone_Number = '" + pNumber + "'";
                pst = conn.prepareStatement(str);
                rst = pst.executeQuery();
                while (rst.next()) {
                    String dp = rst.getString("start_Date");
                    String kp = rst.getString("cropId");
                }

            } catch (Exception e) {

            }
            int dur = 0;

            try {
                String ke = "select from actions where seed_ID='" + pie1 + "'";
                pst = conn.prepareStatement(ke);
                rst = pst.executeQuery();
                while (rst.next()) {
                    action = rst.getString("action");
                    if (rst.next()) {
                        dur = rst.getInt("Duration");
                        action = rst.getString("action");
                        if (diffDays[i] == dur) {
                            JOptionPane.showMessageDialog(null, "Kindly it has gone'" + dur + "' you are being informed to '" + action + "'");
                        }

                    }

                }
            } catch (Exception e) {

            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);

    }

Multiple definitions of Node

The Node class is widely used across many data structures and algorithms. Right now, there are multiple definitions of this class, in basically every single data structure/algorithm that uses it. This introduces a lot of redundancy into the codebase, and also makes bugs more likely to happen. I suggest removing the duplicate declarations of this class where possible, and simply reusing the Node class as defined in Misc.

Error code in Conversions folder.

Some of the codes in the conversion folder are not executable or error codes in the Java environment.

As I was looking through the code, I fixed the error in DecimalToHexaDecimal.java and sent PR.

Could you please confirm that I am going to send a PR for other issues?

The project structure has different styles

The project structure has different styles. For instance, there are 3 data structure folders now (one of them in python style). It will be good to make one style, because it easy for people how understand project. Futhermore, it is not acceptable to create class with uncapitalize name by the java conventions (like in Compression). May be it is just legacy code, but It should be denied in future

Merge three Arrays

Merging three arrays. Given three sorted arrays a[], b[], and c[], each of
different size

Redundant InsertionSort

There are two insertion sorts in the sort directory. It would be better to replace both of them with a single generic insertion sort

TSP problem

I will implement the tsp Algorithm in java

Friendly spyros

OctalToBinary strange method declarations

This class has a very strange method. It is passing a parameter and not even being used.
On top of that there are two methods called within that method.

public static int convertOctalToBinary(int o) {
		Scanner scan;
		int num;
	
		void getVal() {
		
			System.out.println("Octal to Binary");
			scan = new Scanner(System.in);
			// Entering the needed number
			System.out.println("\nEnter the number : ");
			num = Integer.parseInt(scan.nextLine(), 8);
		}
		
		void convert() {
		
			String binary = Integer.toBinaryString(num);		
			System.out.println("Binary Value is : " + binary);
		}
	}

OctalToBinary.java

Please assign this to me. I'll get it fix.

Generalize using generics.

Enhancement

Description

Many of the algorithms, namely sorting, searching and the data structures, are using primitive types for the implementation of the algorithms. This could be generalized to any comparable type using generics.

Upgrade to a project structure

@AnupKumarPanwar @dynamitechetan
I am proposing a long-term change to this repository something similar to Scala Repo. The details of the change are as mentioned below:

  • Add test cases for every algorithm using JUnit
  • Change the repository structure according to a Java project structure with proper packages for every algorithm domain
  • Update the code according to a coding standard tool such as checkstyle
  • Update the contribution requirements
  • Add CI/CD pipelines for PRs (Can be done after the above-mentioned structure is implemented)

We can do this by doing the updates on a development branch and then moving it to master once the project is built successfully

Do let me know what you guys feel about the proposal and when can we start with this?

Add Double-ended priority queue

I want to add new heap.

A double-ended priority queue (DEPQ) or double-ended heap is a data structure similar to a priority queue or heap, but allows for efficient removal of both the maximum and minimum, according to some ordering on the keys (items) stored in the structure. Every element in a DEPQ has a priority or value. In a DEPQ, it is possible to remove the elements in both ascending as well as descending order.

CircleLinkList has a problem,i think

public void display()
{
Node current=head;
for (int i = 1; i <= size; i++) {
System.out.println(current.next.value);
current=current.next;
}
}

public static void main(String[] args)
{
    CircleLinkList<String> cl= new CircleLinkList<>();
    cl.append("hello");
    cl.append("world");
    cl.append("and");
    cl.append("java");

    cl.display();
    // System.out.println("hello java");
}

/**OutPut: Is it wrong? i have no idea
java
null
java
null
*/

Wrong Travis-CI badge

The Travis-CI badge points to the wrong repository (TheAlgorithms/Python), which is itself not an active repository according to Travis-CI.

I also don't see a .travis.yml file in this repo so i guess there was some kind of mistake here.

Modifying the error code

I sent new Pull Request to fix the error code
PR#347 Modifying HexaDecimalToBinary.java
URL : #347

Please check my PullRequest

I have a question in Java/Sorts/MergeSort.java

70.  while (i <= middle) {
71.             this.array[k] = this.tempMergArr[i];
72.             k++;
73.             i++;
74. }

Can I change this snippet to

while(j <= higherIndex){
           this.array[k] = this.tempMergArr[j];
           k++;
           j++;
}

[ciphers/AES] Rijndael Galois Field Operations - Design Question

The AES algorithm uses a couple of math operations on 8-bit integers that are not calculated in the regular integer space, but in Rijndael's Finite Field.
There are different ways to approach this issue:
You could implement different sub algorithms that will do the calculation for you. This would pose a more 'complete' solution to this problem, however it will make the algorithm harder to read.
Alternatively you can simply use precalculated lookup tables for these operations. This is the most common way to build AES.
Personally I think lookup tables is the way to go, however I would like to hear some other opinions about how The Algorithms' implementation of AES is supposed to handle these functions.

Merge Sort, a different method

"Hi I like your code.
Another approach the Merge Sort code would be:

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

    /* Create temp arrays */
    int L[] = new int [n1];
    int R[] = new int [n2];

    /*Copy data to temp arrays*/
    for (int i=0; i<n1; ++i)
        L[i] = arr[l + i];
    for (int j=0; j<n2; ++j)
        R[j] = arr[m + 1+ j];


    /* Merge the temp arrays */

    // Initial indexes of first and second subarrays
    int i = 0, j = 0;

    // Initial index of merged subarry array
    int k = l;
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    /* Copy remaining elements of L[] if any */
    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

    /* Copy remaining elements of R[] if any */
    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
}

// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
    if (l < r)
    {
        // Find the middle point
        int m = (l+r)/2;

        // Sort first and second halves
        sort(arr, l, m);
        sort(arr , m+1, r);

        // Merge the sorted halves
        merge(arr, l, m, r);
    }
}"

Incorrect pull requests getting merged

I was looking through the commits for last few days and found that a few PRs were merged without proper review.
Ex: Towers Of Hanoi in Misc section

Issues:

  1. The code is committed from a personal package and the package name has now become a part of the codebase
  2. The code file is not even a Java file
  3. There is no structure to the code. No description about the function or the parameters passed.

I have therefore opened a new PR for the algorithm #143

@dynamitechetan @AnupKumarPanwar Please make sure that the PRs are reviewed properly. I totally understand that you guys would be getting multiple PRs a day due to hacktoberfest but at the same time lets make sure that the codebase in the repo does not degrades due to this. Thanks

Code Style is incorrect

Java:
code is written to look like its C# (sure that SEEMS ok, but if the point of this code to introduce is to people then we'll just have more people writing code that does not look right)

Scala
The Scala looks like the Java that looks like C# . Also, Scala is functional (or at least it can be) your code is essentially modified Java, yes it works, but it needs to be correct no?

Python
Only looked a tiny bit, but there is never a reason to return None at the end of a file,this happens already. If that was done for newb purposes then I suggest doing it in a comment instead?

Other languages and Conclusion:
Using Intellij has helped many people when it comes to conforming to style standards. You may be thinking "Well that is just how I write it" Cool, neat, but if this is for other people, or even for recruiters to gawk at in amazement, would it not be better to have good examples online?

(all that said, i like this project, its pretty cool to have stuff like this out here, I have a similar idea but RossetaCode kinda beat me to it )

BinaryTree method find() confusing return value

The find(int key) method in the BinaryTree class returns the node with the value int, if it's found, and root if there is no such node. This is confusing behavior, first of all, as one would expect it to return null, and is also problematic, since the root itself can match the query.

I suggest simply changing this function to return null on an unsuccessful query.

Threads implementation consumer,producer

I could add a mini project with four Algorithms ,which is a problem of real life

where one # consumer communicate with a # producer for products through one cubbyhole class

the project will have 4 classes and will implemented in java:

  1. class Consumer.java which extend Thread
    2)class Producer.java which extend Thread
  2. class Cubbyhole.java through which the two above classes will communicate
  3. the ProducerConsumerTest.java (the main class)

Packages imports?

Sorry if this a dumb question. This is my first time attempting to contribute to get onboard with hacktoberfest. If someone tries to run this it will be errors due to no package import lines. Just looking at Sorts package and only shell sort has the import. Other packages have the same issues and some files are wrongly named for example BinaryTreeSort file and the class name is TreeSort.

By the way I can fix this issues if needed to... Before I start working on my cipher classes.

Create a readme

In order that people know what the compression section is about, I'd prefer to see a readme.md file explaining what this code does.

AfmAlgorithm

I will add an algorithm which , will calculate the validity of one AFM.

Connecting JDBC applications with SSL?

Hello community,

I want to ask, if somebody have a hint for me, how to connect jdbc applications with SSL?
I am using eclipse, and have ca.pem, client.pem, client_key.pem.
The mysql-server is already configured.

I just need to make a connection with jdbc using ssl.
I found this link:

https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.jdbc_pg.doc/ids_jdbc_490.htm

But I still not understand it :(

If somebody could help me out, I would be very happy.
I am using Eclipse as development environment.

Thank you

Error code in Conversions.

I send a new PR for another error.

PR#339 Updated OctalToDecimal.java
URL : #339

Modified error.

  1. modified error in return type.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.