Posts

Showing posts with the label algorithm

DFS CODE ERROR?

Image
Clash Royale CLAN TAG #URR8PPP DFS CODE ERROR? ALGORITHM IS GIVEN BELOW .. DFS(G) for each vertex u ∈ G.V u.color = WHITE u.pi = NIL time = 0 for each vertex u ∈ G.V if u.color == WHITE DFS-VISIT(G,u) DFS-VISIT(G,u) time = time + 1 u.d = time u.color = GRAY for each v ∈ G.Adj[u] if v.color == WHITE v.pi = u DFS-VISIT(G,v) u.color = BLACK time = time + 1 u.f = time I TRIED TO CODE THIS ALGORITHM BUT THERE IS SOME ERROR ! #include<bits/stdc++.h> using namespace std; #define WHITE 0 #define GRAY 1 #define BLACK 2 #define SIZE 100 int Time; int adj[SIZE][SIZE]; int color[SIZE]; int parent[SIZE]; int d[SIZE]; void dfs_Visit(int G, int u) { Time = Time++; d[u]=Time; color[u]=GRAY; for(int i=0; i<G; i++) { int v = i; if(color[v] == WHITE) { parent[v] = u; dfs_Visit(G,u); } } color[u] = BLACK; Time++; cout << u << " "; } void dfs(int G) { for(int i = 0 ; i < G ; i++) { color[i] = WHITE; parent[i]=NUL...

Unable to determine the error in Python code

Image
Clash Royale CLAN TAG #URR8PPP Unable to determine the error in Python code I am trying to solve a problem on codechef using Python 3. Following is the code written by me. #import heapq as h #try with heapq from sys import stdin, stdout t = int(stdin.readline()) for i in range(t): (n, m) = (int(x) for x in stdin.readline().split()) zmbs = [int(x) for x in stdin.readline().split()] lrk = for j in range(m): l, r, k = map(int, stdin.readline().split()) lrk.append([l, r, k]) u = ans = 0 failed = False for zi in range(len(zmbs)): u += [x for x in lrk if x[0] == zi+1] u.sort(key=lambda x: x[1]) z = zmbs[zi] while(z > 0): if u == or u[-1][1] < zi+1: failed = True # z cant be killed, exit loop break l, r, k = u[-1] if k > z: ans += z u[-1][-1] -= z zmbs[zi:r] = [x-z for x in ...

Optimization (CodeWars Integers: Recreation One)

Image
Clash Royale CLAN TAG #URR8PPP Optimization (CodeWars Integers: Recreation One) I managed to find two algos for this CodeWars challenge (https://www.codewars.com/kata/integers-recreation-one/train/javascript). Unfortunately, they are not fast enough (> 12000ms). Any suggestions on how to improve my code ? v1 : const listSquared = (m, n) => { const result = ; for (let i = m; i <= n; i++) { const divisorsOfi = ; for (let j = 0; j <= i; j++) { if (i % j === 0) { divisorsOfi.push(Math.pow(j, 2)) } } let sumOfDivisorsOfi = 1; if (divisorsOfi.length > 1) { sumOfDivisorsOfi = divisorsOfi.reduce((a, b) => a + b); } if (Number.isInteger(Math.sqrt(sumOfDivisorsOfi))) { result.push([i, sumOfDivisorsOfi]); } } return result; } v2: const listSquared = (m, n) => { const result = ; for (let i = m; i <= n; i++) { let sumOfSqrtDivisorsOfi = divisors(i); if (Number.isInteger(Math.sqrt(sumOfSqrtDiv...

Finding the smallest number greater than N with K set bits

Image
Clash Royale CLAN TAG #URR8PPP Finding the smallest number greater than N with K set bits Given a number N, the objective is to find the smallest number greater than N with K set bits in its binary representation. For example, N = 1, K = 5 gives 31, N = 12, K = 2 gives 17 I tried an easy but inefficient approach is simply brute force: count the number of 1s in n, and then increment (or decrement) until we find a number with the same number of 1s. Any help will be appreciated, thanks. By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call?

Image
Clash Royale CLAN TAG #URR8PPP Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call? I am having trouble determining when recursive functions are sub-optimal to their iterative counterparts when space is an issue. When writing recursive functions, is the space complexity necessarily at least as large as the depth of the recursive call if it is not tail recursive? For example, lets remove duplicates from a linked list using recursion. This can be done trivially with an iterative approach in O(n^2) time and O(1) space. But is the recursive variant also O(1) space? removeDuplicatesRecursive() { let current = this.head; while (current.next) { if (this.head.data === current.next.data) { current.next = current.next.next } else { current = current.next; } } if (this.head.next) { removeDuplicatesRecursive(this.head.next); } return head; } Yo...

How to algorithmically find the biggest rectangle that can fit in a space with other rectangles?

Image
Clash Royale CLAN TAG #URR8PPP How to algorithmically find the biggest rectangle that can fit in a space with other rectangles? So I have a rectangle that is 6m x 2.25m and I have 4 other rectangles with static dimensions but are randomly placed inside the global rectangle. 6m x 2.25m I need to have a function that will calculate the area of the largest rectangle that can fit in the outer rectangle that also won't overlap with the other rectangles. I thought about finding the maximum x distance between the small rects but depending if they're oriented landscape or portrait, x might not do the job. At this point I'm rather stuck and I can't find much online about doing this, but I'm sure this is quite an ordinary task for experienced coders. Update: Here an example image to show what I'm trying to describe. The colored rectangles are randomly placed with static dimensions, and I want to find the largest rectangle that can fit. Thanks for your time! ...

java algorithm for search with different increment number

Image
Clash Royale CLAN TAG #URR8PPP java algorithm for search with different increment number I have next data: need create algorithm on java whet will return result dependent on input value for example: ...... I do not know the data in advance, I know only algorithm in witch they populating I have started with next code: public int getAmountOfUnits(int duration ) { if (duration >= 1 && duration <= 7) return 0; if (duration >= 8 && duration <= 82) {} return 1; } Can anyone help me? It is not a question about an issue, but an assignment you ask. Anyway, you write the logic in english, just translate it in java and you have your answer – wargre 1 hour ago '40' should return '3', right? By the way, if there's no mathematical correlation in that sequence, there's no re...

check if all elements in a list are identical

Image
Clash Royale CLAN TAG #URR8PPP check if all elements in a list are identical I need the following function: Input : a list list Output : True False Performance : of course, I prefer not to incur any unnecessary overhead. I feel it would be best to: AND But I'm not sure what's the most Pythonic way to do that. EDIT : Thank you for all the great answers. I rated up several, and it was really hard to choose between @KennyTM and @Ivo van der Wijk solutions. The lack of short-circuit feature only hurts on a long input (over ~50 elements) that have unequal elements early on. If this occurs often enough (how often depends on how long the lists might be), the short-circuit is required. The best short-circuit algorithm seems to be @KennyTM checkEqual1 . It pays, however, a significant cost for this: checkEqual1 If the long inputs with early unequal elements don't happen (or happen sufficiently rarely), short-circuit isn't required. Then, by far the fastest is @Ivo van der Wijk s...

Keep the correct lane on road

Image
Clash Royale CLAN TAG #URR8PPP Keep the correct lane on road I am trying to make a Traffic Simulator for my bachelor thesis. I created a map with OpenStreetMap osm and now i am trying to put some cars on roads. I created a graph for the roads. The graph is like this: A->B,C,D C->A,B,E B->A,C D->A E->C and I generate random the cars on random points A,B,C,D,E,F. After this i use function getShortestPath(start,end) to get the shortest path for every car and I put the cars to move: foreach(Car c in allCars){Move(c,path)} getShortestPath(start,end) foreach(Car c in allCars){Move(c,path)} But, i have a problem, i don't know how to keep the correct lane of road for every car, all my cars are on the same lane of road. I am thinking about the direction between two points and the car will be at the right side of the direction. But I have no idea how to do this.... Thank you! By clicking "Post Your Answe...

Hindu Succession Act Algorithm

Image
Clash Royale CLAN TAG #URR8PPP Hindu Succession Act Algorithm Can anyone help with Hindu Succession Act Algorithm and helps me implement it in angular with the help of a family tree. How I should take input from the user and divide the property among heirs. Algo only can help, if anyone helps with angular that will cherry on the cake Have you made any attempt at all so far? Post the code you've tried, along with the requirements – CertainPerformance 2 mins ago By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Picking groups of sentences by topics and features

Image
Clash Royale CLAN TAG #URR8PPP Picking groups of sentences by topics and features My plan is to vectorise all these sentences (with glove for example). Start at sent #1; add sentences until none of the distances improve. Repeat with sent #2. At the end, I could have top 5/10 groups of sentences for each topic. Unfortunately, I'm not taking into consideration my binary features. Do I concatenate them to my word vectors and use them for computing distance? Do I train a multi-class supervised model (three topics and other?) with a small imbalanced dataset where I classify each sentence separately. Use this model to make predictions on each sentence and build groups based on average predictions? I don't like this way. Or do I stage this as two problems? Stage 1, get all the distances for each potential group of sentences with a certain minimum threshold. Stage 2 classify each group on these binary features with the topic similarities? Can somebody point me in the right direction? ...

How important is to formulate a convex optimization for a proposed algorithm?

How important is to formulate a convex optimization for a proposed algorithm? I proposed a new sparse coding algorithm which has goods results compared to the baselines, however, it has a non-convex optimization framework. I solved the problem using a general solver (e.g. Matlab), and although the solution is local optimum, it is still better than other relevant approaches. So how important is to formulate the problem in a convex setting? especially for publishing the work. By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How to generate “inner shape” of 2D concave polygon?

How to generate “inner shape” of 2D concave polygon? I have list of 2d points which is a closed loop, 2d, concave polygon. I want to generate a second polygon, which is full inside the first polygon and each vertex/edge of first polygon has a constant distance to each vertex/edge of second polygon. Basically, the first polygon would be "outer wall" and the second would be "inner wall", with the distance between two walls constant. How to do something like that in programming language? This is called an offset polygon and is a pretty difficult construction, because self-intersections arise. Have a look at Clipper. angusj.com/delphi/clipper.php – Yves Daoust 3 mins ago By clicking "Post Your Answer...