Algorithms | Design and Analysis

 by   JihongJu Python Version: Current License: No License

kandi X-RAY | Algorithms Summary

kandi X-RAY | Algorithms Summary

Algorithms is a Python library. Algorithms has no bugs, it has no vulnerabilities and it has low support. However Algorithms build file is not available. You can download it from GitHub.

Design and Analysis (Standford) Programming Question-1. Question 1 Download the text file here. (Right click and save link as) This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated. Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array. Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures. The numeric answer for the given input file should be typed in the space below. So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. You can make up to 5 attempts, and we'll use the best one for grading. (We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.) [TIP: before submitting, first test the correctness of your program on some small test files or your own devising. Then post your best test cases to the discussion forums to help your fellow students!] Answer for Question 1 2407905288. Question 1 GENERAL DIRECTIONS: Download the text file here. The file contains all of the integers between 1 and 10,000 (inclusive, with no repeats) in unsorted order. The integer in the ith row of the file gives you the ith entry of an input array. Your task is to compute the total number of comparisons used to sort the given input file by QuickSort. As you know, the number of comparisons depends on which elements are chosen as pivots, so we'll ask you to explore three different pivoting rules. You should not count comparisons one-by-one. Rather, when there is a recursive call on a subarray of length m, you should simply add m−1 to your running total of comparisons. (This is because the pivot element is compared to each of the other m−1 elements in the subarray in this recursive call.) WARNING: The Partition subroutine can be implemented in several different ways, and different implementations can give you differing numbers of comparisons. For this problem, you should implement the Partition subroutine exactly as it is described in the video lectures (otherwise you might get the wrong answer). DIRECTIONS FOR THIS PROBLEM: For the first part of the programming assignment, you should always use the first element of the array as the pivot element. HOW TO GIVE US YOUR ANSWER: Type the numeric answer in the space provided. So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / other punctuation marks. You have 5 attempts to get the correct answer. (We do not require you to submit your code, so feel free to use the programming language of your choice, just type the numeric answer in the following space.) Answer for Question 1 162085. Question 2 GENERAL DIRECTIONS AND HOW TO GIVE US YOUR ANSWER: See the first question. DIRECTIONS FOR THIS PROBLEM: Compute the number of comparisons (as in Problem 1), always using the final element of the given array as the pivot element. Again, be sure to implement the Partition subroutine exactly as it is described in the video lectures. Recall from the lectures that, just before the main Partition subroutine, you should exchange the pivot element (i.e., the last element) with the first element. Answer for Question 2 164123. Question 3 GENERAL DIRECTIONS AND HOW TO GIVE US YOUR ANSWER: See the first question. DIRECTIONS FOR THIS PROBLEM: Compute the number of comparisons (as in Problem 1), using the "median-of-three" pivot rule. [The primary motivation behind this rule is to do a little bit of extra work to get much better performance on input arrays that are nearly sorted or reverse sorted.] In more detail, you should choose the pivot as follows. Consider the first, middle, and final elements of the given array. (If the array has odd length it should be clear what the "middle" element is; for an array with even length 2k, use the kth element as the "middle" element. So for the array 4 5 6 7, the "middle" element is the second one ---- 5 and not 6!) Identify which of these three elements is the median (i.e., the one whose value is in between the other two), and use this as your pivot. As discussed in the first and second parts of this programming assignment, be sure to implement Partition exactly as described in the video lectures (including exchanging the pivot element with the first element just before the main Partition subroutine). EXAMPLE: For the input array 8 2 4 5 7 1 you would consider the first (8), middle (4), and last (1) elements; since 4 is the median of the set {1,4,8}, you would use 4 as your pivot element. SUBTLE POINT: A careful analysis would keep track of the comparisons made in identifying the median of the three candidate elements. You should NOT do this. That is, as in the previous two problems, you should simply add m−1 to your running total of comparisons every time you recurse on a subarray with length m. Answer for Question 3 138382.
Support
    Quality
      Security
        License
          Reuse

            kandi-support Support

              Algorithms has a low active ecosystem.
              It has 5 star(s) with 2 fork(s). There are 1 watchers for this library.
              OutlinedDot
              It had no major release in the last 6 months.
              Algorithms has no issues reported. There are no pull requests.
              It has a neutral sentiment in the developer community.
              The latest version of Algorithms is current.

            kandi-Quality Quality

              Algorithms has 0 bugs and 0 code smells.

            kandi-Security Security

              Algorithms has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
              Algorithms code analysis shows 0 unresolved vulnerabilities.
              There are 0 security hotspots that need review.

            kandi-License License

              Algorithms does not have a standard license declared.
              Check the repository for any license declaration and review the terms closely.
              OutlinedDot
              Without a license, all rights are reserved, and you cannot use the library in your applications.

            kandi-Reuse Reuse

              Algorithms releases are not available. You will need to build from source code and install.
              Algorithms has no build file. You will be need to create the build yourself to build the component from source.
              It has 137 lines of code, 10 functions and 2 files.
              It has low code complexity. Code complexity directly impacts maintainability of the code.

            Top functions reviewed by kandi - BETA

            kandi has reviewed Algorithms and discovered the below as its top functions. This is intended to give you an instant insight into Algorithms implemented functionality, and help decide if they suit your requirements.
            • Counts the number of invices in an array .
            • Merge two lists .
            • Choose a pivot .
            • Performs quick sorting of a list .
            • Load data from file .
            • Count the number of elements n .
            • Run the test .
            • Partition an alistore .
            Get all kandi verified functions for this library.

            Algorithms Key Features

            No Key Features are available at this moment for Algorithms.

            Algorithms Examples and Code Snippets

            No Code Snippets are available at this moment for Algorithms.

            Community Discussions

            QUESTION

            polynomial (in n) time algorithm that decides whether N is a power
            Asked 2022-Apr-02 at 22:23

            I am a computer science student; I am studying the Algorithms course independently.

            During the course, I saw this question:

            Given an n-bit integer N, find a polynomial (in n) time algorithm that decides whether N is a power (that is, there are integers a and k > 1 so that a^k = N).

            I thought of a first option that is exponential in n: For all k , 1

            For example, if N = 27, I will start with k = 2 , because 2 doesn't divide 27, I will go to next k =3. I will divide 27 / 3 to get 9, and divide it again until I will get 1. This is not a good solution because it is exponential in n.

            My second option is using Modular arithmetic, using ak ≡ 1 mod (k+1) if gcd(a, k+1 ) = 1 (Euler's theorem). I don't know if a and k are relatively prime.

            I am trying to write an algorithm, but I am struggling to do it:

            ...

            ANSWER

            Answered 2022-Mar-15 at 10:07

            Ignoring the cases when N is 0 or 1, you want to know if N is representable as a^b for a>1, b>1.

            If you knew b, you could find a in O(log(N)) arithmetic operations (using binary search). Each arithmetic operation including exponentiation runs in polynomial time in log(N), so that would be polynomial too.

            It's possible to bound b: it can be at most log_2(N)+1, otherwise a will be less than 2.

            So simply try each b from 2 to floor(log_2(N)+1). Each try is polynomial in n (n ~= log_2(N)), and there's O(n) trials, so the resulting time is polynomial in n.

            Source https://stackoverflow.com/questions/71479288

            QUESTION

            Java PriorityQueue: how to heapify a Collection with a custom Comparator?
            Asked 2022-Mar-10 at 03:24

            For example, given a List of Integer List list = Arrays.asList(5,4,5,2,2), how can I get a maxHeap from this List in O(n) time complexity?

            The naive method:

            ...

            ANSWER

            Answered 2021-Aug-28 at 15:09
            If you don't mind some hack

            According to the java doc of PriorityQueue(PriorityQueue)

            Creates a PriorityQueue containing the elements in the specified priority queue. This priority queue will be ordered according to the same ordering as the given priority queue.

            So we can extend PriorityQueue as CustomComparatorPriorityQueue to hold the desired comparator and the Collection we need to heapify. Then call new PriorityQueue(PriorityQueue) with an instance of CustomComparatorPriorityQueue.

            Below is tested to work in Java 15.

            Source https://stackoverflow.com/questions/68960310

            QUESTION

            What is a "closure" in Julia?
            Asked 2022-Feb-03 at 18:34

            I am learning how to write a Maximum Likelihood implementation in Julia and currently, I am following this material (highly recommended btw!). So the thing is I do not fully understand what a closure is in Julia nor when should I actually use it. Even after reading the official documentation the concept still remain a bit obscure to me.

            For instance, in the tutorial, I mentioned the author defines the log-likelihood function as:

            ...

            ANSWER

            Answered 2022-Feb-03 at 18:34

            In the context you ask about you can think that closure is a function that references to some variables that are defined in its outer scope (for other cases see the answer by @phipsgabler). Here is a minimal example:

            Source https://stackoverflow.com/questions/70969919

            QUESTION

            Paramiko authentication fails with "Agreed upon 'rsa-sha2-512' pubkey algorithm" (and "unsupported public key algorithm: rsa-sha2-512" in sshd log)
            Asked 2022-Jan-13 at 14:49

            I have a Python 3 application running on CentOS Linux 7.7 executing SSH commands against remote hosts. It works properly but today I encountered an odd error executing a command against a "new" remote server (server based on RHEL 6.10):

            encountered RSA key, expected OPENSSH key

            Executing the same command from the system shell (using the same private key of course) works perfectly fine.

            On the remote server I discovered in /var/log/secure that when SSH connection and commands are issued from the source server with Python (using Paramiko) sshd complains about unsupported public key algorithm:

            userauth_pubkey: unsupported public key algorithm: rsa-sha2-512

            Note that target servers with higher RHEL/CentOS like 7.x don't encounter the issue.

            It seems like Paramiko picks/offers the wrong algorithm when negotiating with the remote server when on the contrary SSH shell performs the negotiation properly in the context of this "old" target server. How to get the Python program to work as expected?

            Python code

            ...

            ANSWER

            Answered 2022-Jan-13 at 14:49

            Imo, it's a bug in Paramiko. It does not handle correctly absence of server-sig-algs extension on the server side.

            Try disabling rsa-sha2-* on Paramiko side altogether:

            Source https://stackoverflow.com/questions/70565357

            QUESTION

            Circular objects rotate angle detection
            Asked 2022-Jan-04 at 05:52

            I'm trying to detect angle difference between two circular objects, which be shown as 2 image below.

            I'm thinking about rotate one of image with some small angle. Every time one image rotated, SSIM between rotated image and the another image will be calculated. The angle with maximum SSIM will be the angle difference.

            But, finding the extremes is never an easy problem. So my question is: Are there another algorithms (opencv) can be used is this case?

            IMAGE #1

            IMAGE #2

            EDIT:

            Thanks @Micka, I just do the same way he suggest and remove black region like @Yves Daoust said to improve processing time. Here is my final result:

            ORIGINAL IMAGE ROTATED + SHIFTED IMAGE

            ...

            ANSWER

            Answered 2021-Dec-15 at 09:19

            Here's a way to do it:

            1. detect circles (for the example I assume circle is in the image center and radius is 50% of the image width)
            2. unroll circle images by polar coordinates
            3. make sure that the second image is fully visible in the first image, without a "circle end overflow"
            4. simple template matching

            Result for the following code:

            Source https://stackoverflow.com/questions/70359226

            QUESTION

            Android: Iterative queue-based flood fill algorithm 'expandToNeighborsWithMap()' function is unusually slow
            Asked 2021-Dec-30 at 04:27

            (Solution has been found, please avoid reading on.)

            I am creating a pixel art editor for Android, and as for all pixel art editors, a paint bucket (fill tool) is a must need.

            To do this, I did some research on flood fill algorithms online.

            I stumbled across the following video which explained how to implement an iterative flood fill algorithm in your code. The code used in the video was JavaScript, but I was easily able to convert the code from the video to Kotlin:

            https://www.youtube.com/watch?v=5Bochyn8MMI&t=72s&ab_channel=crayoncode

            Here is an excerpt of the JavaScript code from the video:

            Converted code:

            ...

            ANSWER

            Answered 2021-Dec-29 at 08:28

            I think the performance issue is because of expandToNeighbors method generates 4 points all the time. It becomes crucial on the border, where you'd better generate 3 (or even 2 on corner) points, so extra point is current position again. So first border point doubles following points count, second one doubles it again (now it's x4) and so on.

            If I'm right, you saw not the slow method work, but it was called too often.

            Source https://stackoverflow.com/questions/70490938

            QUESTION

            Sorting an array of integers in nlog(n) time without using comparison operators
            Asked 2021-Nov-04 at 14:49

            Imagine there's have an array of integers but you aren't allowed to access any of the values (so no Arr[i] > Arr[i+1] or whatever). The only way to discern the integers from one another is by using a query() function: this function takes a subset of elements as inputs and returns the number of unique integers in this subset. The goal is to partition the integers into groups based on their values — integers in the same group should have the same value, while integers in different groups have different values. The catch - the code has to be O(nlog(n)), or in other words the query() function can only be called O(nlog(n)) times.

            I've spent hours optimizing different algorithms in Python, but all of them have been O(n^2). For reference, here's the code I start out with:

            ...

            ANSWER

            Answered 2021-Nov-04 at 14:49

            Let's say you have an element x and an array of distinct elements, A = [x0, x1, ..., x_{k-1}] and want to know if the x is equivalent to some element in the array and if yes, to which element.

            What you can do is a simple recursion (let's call it check-eq):

            • Check if query([x, A]) == k + 1. If yes, then you know that x is distinct from every element in A.
            • Otherwise, you know that x is equivalent to some element of A. Let A1 = A[:k/2], A2 = A[k/2+1:]. If query([x, A1]) == len(A1), then you know that x is equivalent to some element in A1, so recurse in A1. Otherwise recurse in A2.

            This recursion takes at most O(logk) steps. Now, let our initial array be T = [x0, x1, ..., x_{n-1}]. A will be an array of "representative" of the groups of elements. What you do is first take A = [x0] and x = x1. Now use check-eq to see if x1 is in the same group as x0. If no, then let A = [x0, x1]. Otherwise do nothing. Proceed with x = x2. You can see how it goes.

            Complexity is of course O(nlogn), because check-eq is called exactly n-1 times and each call take O(logn) time.

            Source https://stackoverflow.com/questions/69838842

            QUESTION

            Minimum moves to transform a list so that each element equals its own frequency
            Asked 2021-Oct-03 at 10:59

            Given a sorted array like [1,2,4,4,4]. Each element in the array should occur exactly same number of times as element. For Example 1 should occur 1 time, 2 should occur 2 times, n should occur n times, After minimum number of moves, the array will be rendered as [1,4,4,4,4]

            ...

            ANSWER

            Answered 2021-Sep-24 at 19:58

            The error is in this comparison:

            Source https://stackoverflow.com/questions/69315660

            QUESTION

            Iterator concepts are weaker than the corresponding named requirements, which ones apply to the non-range standard algorithms?
            Asked 2021-Sep-24 at 18:17

            In C++20 we got concepts for iterator categories, e.g. std::forward_iterator corresponds to named requirement ForwardIterator.

            They are not equivalent. In some (but not all) regards, the concepts are weaker:

            • (1) "Unlike the [ForwardIterator or stricter] requirements, the [corresponding] concept does not require dereference to return an lvalue."

            • (2) "Unlike the [InputIterator] requirements, the input_iterator concept does not require equality_comparable, since input iterators are typically compared with sentinels."

            • ...

            The new std::ranges algorithms seem to use the concepts to check iterator requirements.

            But what about the other standard algorithms? (that existed pre-C++20)

            Do they still use the same iterator requirements in C++20 as they were pre-C++20, or did the requirements for them get relaxed to match the concepts?

            ...

            ANSWER

            Answered 2021-Sep-24 at 18:17

            Do they still use the same iterator requirements in C++20 as they were pre-C++20, or did the requirements for them get relaxed to match the concepts?

            The existing std:: algorithms still use the named requirements. For instance, [alg.find] has both:

            Source https://stackoverflow.com/questions/69319153

            QUESTION

            Computing the volume of the union of axis-aligned cubes
            Asked 2021-Sep-11 at 13:25

            Given is a set S of n axis-aligned cubes. The task is to find the volume of the union of all cubes in S. This means that every volume-overlap of 2 or more cubes is only counted once. The set specifically contains all the coordinates of all the cubes.

            I have found several papers regarding the subject, presenting algorithms to complete the task. This paper for example generalizes the problem to any dimension d rather than the trivial d=3, and to boxes rather than cubes. This paper as well as a few others solve the problem in time O(n^1.5) or slightly better. Another paper which looks promising and is specific to 3d-cubes is this one which solves the task in O(n^4/3 log n). But the papers seem rather complex, at least for me, and I cannot follow them clearly.

            Is there any relatively simple pseudocode or procedure that I can follow to implement this idea? I am looking for a set of instructions, what exactly to do with the cubes. Any implementation will be also excellent. And O(n^2) or even O(n^3) are fine.

            Currently, my approach was to compute the total volume, i.e the sum of all volumes of all the cubes, and then compute the overlap of every 2 cubes, and reduce it from the total volume. The problem is that every such overlap may (or may not) be of a different pair of cubes, meaning an overlap can be for example shared by 5 cubes. In this approach the overlap will be counted 10 times rather just once. So I was thinking maybe an inclusion-exclusion principle may prove itself useful, but I don't know exactly how it may be implemented specifically. Computing every overlap (naively) is already O(n^2), but doable. Is there any better way to compute all such overlaps? Anyways, I don't assume this is a useful approach, to continue along these lines.

            ...

            ANSWER

            Answered 2021-Sep-10 at 21:41

            Here's some Python (sorry, didn't notice the Java tag) implementing user3386109's suggestion. This algorithm is O(n³ log n). We could get down to O(n³) by sorting the events for all cubes once and extracting the sorted sub-sequence that we need each time, but perhaps this is good enough.

            Source https://stackoverflow.com/questions/69137352

            Community Discussions, Code Snippets contain sources that include Stack Exchange Network

            Vulnerabilities

            No vulnerabilities reported

            Install Algorithms

            You can download it from GitHub.
            You can use Algorithms like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

            Support

            For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
            Find more information at:

            Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

            Find more libraries
            CLONE
          • HTTPS

            https://github.com/JihongJu/Algorithms.git

          • CLI

            gh repo clone JihongJu/Algorithms

          • sshUrl

            git@github.com:JihongJu/Algorithms.git

          • Stay Updated

            Subscribe to our newsletter for trending solutions and developer bootcamps

            Agree to Sign up and Terms & Conditions

            Share this Page

            share link