# Questions tagged [algorithm]

49597 questions

1

votes

2

answer

269

Views

### Correct implementation of weighted K-Nearest Neighbors

From what I understood, the classical KNN algorithm works like this (for discrete data):
Let x be the point you want to classify
Let dist(a,b) be the Euclidean distance between points a and b
Iterate through the training set points pᵢ, taking the distances dist(pᵢ,x)
Classify x as the most frequ...

1

votes

1

answer

37

Views

### How to fix this unsorted array in insertion sort?

I'm creating an insertion sort, the first one is working and returning a sorted array:
// {9, 8, 3, 13, 87, 12, 1, 99} the unsorted list
static int[] insertionSort(int[] a){
for (int i = 1; i < a.length - 1; i++) {
int element = a[i];
int j = i - 1;
while(j >= 0 && a[j] > element){
a[j+1] = a[j];
j-...

1

votes

1

answer

792

Views

### Count Triplets error on hackkerank

Link to count triplets problem
Below on the following code the hackerrank website says the answer is incorrect, however when I run the code on my local machine. Specifically test case 2, which is an array of 100 1s and has a triplet multiplier of 1, The expected output is supposed to be 161700, and...

1

votes

2

answer

110

Views

### Mathematical solution to split X teams into 3 Teams per day

I am trying to split X number of Teams into 'play days' which consist of 3 teams per day
There is more than one solution to solve this for 15 teams.
What is the best approach to find all possible fixtures/match plans for team count 9-21?
Team count of 11, 14, 17 and 20 also cause problems, because t...

1

votes

1

answer

35

Views

### Minimum number of vertices whose removal makes the graph no longer connected

Given a undirected and connected graph G = (V, E). Find the minimum number of verticies whose removal make the graph no longer a connected graph.

1

votes

1

answer

77

Views

### What is the fastest way to implement a list and queue in c?

Which one stack and queue realization will be faster and more optimal and why? Based on array (dynamic or static) or list?
For example, I have these ways:
Dynamic array based:
typedef struct Stack {
char* values;
int avl_el;
int now_el;
int top;
}Stack;
void push(Stack* stack, char data) {
if (stack...

1

votes

2

answer

71

Views

### Best practice: how to pass many many arguments to a function?

I am running some numerical simulations, in which my main function must receive lots and lots of arguments - I'm talking 10 to 30 arguments depending on the simulation to run.
What are some best practices to handle cases like this?
Dividing the code into, say, 10 functions with 3 arguments each does...

1

votes

1

answer

63

Views

### How to sort scores for high score board in a game

I'm writing a game in which you can have different users. Every time you play the game you submit a score. I want to have a high-score board that show the top 10 scores of all time. For instance:
A:[100,200,50]
B:[400,150,320]
C:[50,245,35]
What I want to achieve is:
B 400
B 320
C 245
A 200
B 150
A...

1

votes

4

answer

62

Views

### twoSum to find all the possible unique couples

I have such a problem
Given an array nums of n integers, are there elements a, b in nums such that a + b = 10? Find all unique couples in the array which gives the sum of target.
Note:
The solution set must not contain duplicate couples.
Example:
Given nums = [4, 7, 6, 3, 5], target = 10
because...

1

votes

1

answer

41

Views

### Algorithm that can compute values of variables based on the result of specific sums of those

This might be a duplicate question, but I wasn't able to find this on stack overflow.
Take some variables, which all represent a chance of something. That means that all variables have a value between zero and one (both inclusive). The values of these are unknown. However, I have some equations with...

1

votes

2

answer

48

Views

### Using a spatial index to find points within range of each other

I'm trying to find a spatial index structure suitable for a particular problem : using a union-find data structure, I want to connect\associate points that are within a certain range of each other.
I have a lot of points and I'm trying to optimize an existing solution by using a better spatial inde...

1

votes

1

answer

28

Views

### What would be a good approach to mutate a turtle variable in NetLogo?

I'm simulating a multi-agent system. Each agent has a chromosome. The genotypes represent 5 parameters that are various floating-point numbers between 0 and 100. My mutation operator simply modifies the original gene with a new random number (according to the constant mutation rate). Is that the bes...

1

votes

3

answer

38

Views

### Extract data from an array and include it to an object in javascript

I have a javascript object as follows.
{
name: 'tom',
age: 5,
fruits: [
{name: 'apple',qty: 4},
{name: 'orange',qty: 13},
{name: 'banana',qty: 3}
]
}
I am trying to convert this object into an object given below.
{
name: 'tom',
age: 5,
apple: 4,
orange: 13,
banana: 3
}
How do I achieve this? I have...

1

votes

1

answer

32

Views

### Why Is This Searching Algorithm Bizarrely not Working for this Case?

I am somewhat new to Java, and I was learning the concept of recursion. I was creating a recursive algorithm that checks if an element exists in a Comparable array by using the compareTo method. Although the algorithm works in most cases, for some reason it does not seem to find an element in the se...

1

votes

4

answer

89

Views

### Use greater_equal in adjacent_find to find equivalent elements in sorted sequence

Is it UB to use std::greater_equal in std::adjacent_find algorithm to find equivalent (as opposite to equal) elements in sorted range?
The answer can be 'no' if order of prev and next elements in std::greater_equal{}(*prev, *next) inside of implementation of the algorithm is not specified strictly....

1

votes

1

answer

25

Views

### Simulation of multiple binomial random numbers in R

I have the following algorithm
Step 1. Generate X1=x1~Bin(6,1/3)
Step 2. Generate X2|X1=x1~Bin(6-x1,(1/3)/(1-1/3))
Step 3. Generate X3|X1=x1,X2=x2~Bin(6-x1-x2,(1/3)/(1-1/3-1/3))
Step 4. Repeat step 1-3 N times.
Here is my approach to implement this algorithm in R:
mult_binom

1

votes

1

answer

41

Views

### Create a Tree/Trie from a word

I need some help to create a javascript algorithm that builds a tree out of a word. The nodes of the tree are the letters of the word that are always in alphabetical order. Ex. 'balance' should be this object:
const tree = {
b: {
l: {
n: {}
},
n: {}
},
a: {
l: {
n: {
}
},
n: {
},
c: {
e: {
}
},
e: {...

1

votes

1

answer

50

Views

### Get all the possible combination of a string generated from ASCII character between two numbers

I need a simple javascript function which takes 3 inputs
1- Start ASCII value
2- End ASCII value
3- String length
The function will loop from starting value to ending value until length has been made.
For example,
start - 65
end - 67
length- 2
I want all the combination (length 2) of ASCII of...

1

votes

1

answer

42

Views

### function returning k-digit numbers from an arrays of n digits

I want to construct a function showNum(ar,k) getting all the k-digit numbers from array ar.
For example, showNum([1,2,3],2) should return 12,13,21,23,31,32
andshowNum([1,2,3],1) should return 1,2,3.
My code works well with the case that k is fix.
For instance, the case k is 3.
My idea is to loop 3...

1

votes

6

answer

104

Views

### How to check if string has repeating pattern?

I was recently asked this in an interview question:
Given a input string check if it has repeating pattern and return true or false. For example:
'abbaabbaabbaabba' is a repeating pattern of 'abba'
private boolean checkPattern(String input) {
}
How can we solve it using regex and also without regex?...

1

votes

1

answer

63

Views

### Project Euler Problem #18 Python - getting the wrong result. Why?

I'm trying to solve the Euler Projects as an exercise to learn Python, for the last few days after work, and am now at Problem 18
I looked at the problem, and thought it could be solved by using Dijkstra's algorithm, with the values of the nodes as negative integers, so as to find the 'longest' path...

1

votes

1

answer

64

Views

### Algorithm to aggregate key-value pairs where keys contain numbers

I will try my best to give a complete problem definition. To illustrate the problem I will give an example later on in my question.
You might want to jump to the example first and read my problem definition afterwards.
The problem
I have got a map representing key value pairs. The keys may end with...

0

votes

1

answer

12

Views

### Finding maximum profit In a directed acyclic graph

I am given a directed acyclic graph, where the vertices are 'projects'. Each project has a weight that is the projects 'profit'. These profits can be negative (which represents a costly project). Some projects cannot be started until certain other projects are completed. So edge i -> j indicates tha...

51

votes

10

answer

4.3k

Views

### How do I check if a string is entirely made of the same substring?

I have to create a function which takes a string, and it should return true or false based on whether the input consists of a repeated character sequence. The length of given string is always greater than 1 and the character sequence must have at least one repetition.
'aa' // true(entirely contains...

0

votes

0

answer

12

Views

### Does anyone know the name of this algorithm or have better idea in time trend

I found this algorithm for time trend
Calculate if trend is up, down or stable
But I cannot figure out what is this and why should do this.
Or is there any suggestion or existing model for related problem?

0

votes

0

answer

11

Views

### Which one is a better BFS algorithm

Given a binary tree, print all of its node values level by level. Which of the 2 methods below is better performance wise and readability wise?
def bfs_queue(root):
q = collections.deque(root)
while q:
node = q.popleft()
print node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.r...

1

votes

3

answer

9.2k

Views

### Resizing image algorithm in python

So, I'm learning my self python by this tutorial and I'm stuck with exercise number 13 which says:
Write a function to uniformly shrink or enlarge an image. Your function should take an image along with a scaling factor. To shrink the image the scale factor should be between 0 and 1 to enlarge the i...

-3

votes

1

answer

16

Views

### Math.log wrong results for big numbers [duplicate]

This question already has an answer here:
Inaccurate Logarithm in Python
8 answers
math.log2 and math.log are giving me wrong results for some high numbers, tested it via online py interpreter and on a local machine.
>>>print(2**72)
>>>4722366482869645213696 #Correct
>>>math.log2(4722366482869645...

0

votes

0

answer

2

Views

### Knapsack (dynamic programming) segmentation fault error

Here's my code to implement a knapsack problem with dynamic programming algorithm.
If the input number (item number size) gets bigger than 300, there is segmentation fault : 11 error.
What is the problem?
unsigned long long dynamic_programming (unsigned long long W, int item_num, int v[], int w[]) {...

0

votes

0

answer

38

Views

### Is there anyway to check if a string “almost” contains another string?

I'm working on a project that requires me to check if string1 is almost present in string2, if yes (i.e. if it matches more than some threshold ration say delta), then I need to extract that matched segment from string2 and save it.
string1 will range from 100 to 200 characters
string2 will be of a...

1

votes

0

answer

16

Views

### Insertion & Merge sort algorithms - Anomalous timing results

I am trying to get runtimes for two sort algorithms in Java, insertion and merge sort.
The program runs both sorts on an unsorted ArrayList of 433 words multiple times and stores the elapsed times taken for 100, 200, 300, 400 and
433 words (the whole array) to be sorted, then prints out the average...

1

votes

1

answer

1.3k

Views

### Simulated Annealing Algorithm to solve Bin Packing

I'm researching about Bin Packing Problem. I currently have implemented this problem in Genetic Programming way. But when I research Simulated Annealing Algorithm for this problem, I don't understand it very well.
Is there any good link or code / psuedocode for this problem.

7

votes

3

answer

171

Views

### How to check if string is entirely made of same substring?

I have to create a function which takes a string should return true or false based on the string. The length of given string is always greater than 1.
'aa' // true(entirely contains two strings 'a')
'aaa' //true(entirely contains three string 'a')
'abcabcabc' //true(entirely containas three strings...

1

votes

2

answer

42

Views

### How to make the algorithm more speedy?

I have two lists :
list1 = [(key1,val_key1), (key2,val_key2)]
list2 = [(key1,val_val1), (key2,val_val2)]
Here is my code :
for lst1 in list1:
for lst2 in list2:
if lst1[0] == lst2[0]:
list_allpairs.append((lst1[1],lst2[1]))
Here is the result:
list_allpairs = [(val_key1,val_val1), (val_key2,val_val2...

0

votes

0

answer

15

Views

### How to improve the performs of the monte carlo tree search algorithm?

I'm trying to implement Monte Carlo tree search to play 9-board tic-tac-toe in Python. The rules of the game is like the regular tic-tac-toe but with 9 3x3 sub-boards. The place of the last piece is placed decides which sub-board to place your piece. It's kind like ultimate tic-tac-toe but if one of...

3

votes

2

answer

52

Views

### Why is not the condition *First1 == * First2 ?? (C++ STL includes function implement)

I'm a student studying STL C++ and have a simple Question.
I was wondering while learning how to implement the includes function in the algorithm library. See this code
(this code from https://en.cppreference.com/w/cpp/algorithm/includes)
template
bool includes(InputIt1 first1, InputIt1 last1, Inpu...

3

votes

0

answer

29

Views

### Is it possible to create a Minimal Perfect Hash function without a separate lookup table for a small (<64) set of keys?

I recently read this article Throw away the keys: Easy, Minimal Perfect Hashing about generating a minimal perfect hash table for a known set of keys.
The article seems to assume that you need an intermediate table. Is there any other, simpler way to generate such a function if we assume that the se...

1

votes

2

answer

1.4k

Views

### Source algorithm for networkx shortest_path(G[, source, target, weight]) function

I am doing some work with networkx and have used two shortest path algoritms namely:
shortest_path(G[, source, target, weight])
dijkstra_path(G, source, target[, weight])
I understand that the dijkstra_path(G, source, target[, weight]) function is based on the dijkstra's shortest path algorithm. I...

1

votes

2

answer

287

Views

### Merging n sorted arrays in Javascript

I have n (n between 1 and 100) sorted number arrays, each with m elements (m around 1000 in my case). I want to merge them into a single sorted array.
I can think of two possibilities for doing this:
1.Use a two arrays merging algo (like merge() function below from http://www.nczonline.net/blog/2012...

1

votes

1

answer

172

Views

### Creating a list or sequence of numbers up to a certain value in F#

Suppose I want to create a list or sequence of all cubic numbers under 5555, or fibonnacci numbers under 4500 - How would I do this?
I can generate a list or sequence of these , but I don't know how to make them terminate after a certain point.
In the case of the fibonacci sequence it is difficult...