## performance – Faster AAN algorithm for calculating Discrete Cosine Transform

performance – Faster AAN algorithm for calculating Discrete Cosine Transform – Code Review Stack Exchange

## optimization – Is there a better way to optimize my algorithm for maximizing order volume?

I’m trying to find an efficient algorithm to solve the following …

During the day, a supermarket will receive calls from customers who want to place orders. The supermarket manager knows in advance the number of calls that will be attempted, the start time, duration and order volume for each call. Only one call can be in progress at any one time, and if a call is not answered, the caller will not call back. The manager must choose which calls to service in order to maximize order volume. Determine taht maximum order volume.

My approach was to find the maximum of two paths — the first being adding the volume from the first caller to the function applied to the remaining callers who didn’t conflict with the first call, the second being finding the max order volume of all callers excluding the first. My algorithm is below (in Java):

``````public class Test {

public static void main(String() argv) {
List<Integer> start = Arrays.asList(new Integer() {10, 5, 15, 18, 30});
List<Integer> duration = Arrays.asList(new Integer() {30, 12, 20, 35, 35});
List<Integer> volume = Arrays.asList(new Integer() {50, 51, 20, 25, 10});
int result = maxOrderVolume(start, duration, volume);
System.out.println(result);
}

public static int maxOrderVolume(List<Integer> start, List<Integer> duration, List<Integer> volume) {
if (start.size() == 0) {
return 0;
} else if (start.size() == 1) {
return volume.get(0);
} else {
int curStart = start.get(0);
int curEnd = start.get(0) + duration.get(0);
List<Integer> newStart = new ArrayList<Integer>();
List<Integer> newDuration = new ArrayList<Integer>();
List<Integer> newVolume = new ArrayList<Integer>();
for (int i=1; i<start.size(); i++) {
int localStart = start.get(i);
int localEnd = start.get(i) + duration.get(i);
boolean conflicting = (localStart >= curStart && localStart <= curEnd) || (localEnd >= curStart && localEnd <= curEnd);
if (conflicting) {
}
}
int firstOption = volume.get(0) + maxOrderVolume(newStart, newDuration, newVolume);
int secondOption = maxOrderVolume(start.subList(1, start.size()), duration.subList(1, duration.size()), volume.subList(1, volume.size()));
return Math.max(firstOption, secondOption);
}
}

}
``````

However, I’m told by the automated test software that this is not an efficient algorithm (too many processor cycles solving it). I was curious what optimizations might be possible to speed it up.

## algorithm – Reducing if conditional statement

algorithm – Reducing if conditional statement – Code Review Stack Exchange

## approximation – Fast text comparison algorithm for long texts

I want to calculate a similarity ratio between two long texts (by “long”, I imply something around 1000 characters or higher). For example, two texts with only one word changing should have a ratio approaching 100%, and a text compared to (the same one + another being the same size) should be 50%.

I know about texts comparison algorithms like Levenshtein or Jaro, but they tend to be too computationally-expensive in my case, given that I am doing comparisons of one text with several thousands of other ones.

I tried to experiment with ssdeep library (for those who do not know: it is an algorithm that splits a blob into several parts, hash each of these parts, then regroup them in a summary hash; this is an example of “fuzzy hashing”). It was promising since it reduces the text to an hash we just have to compare with another. However, since it deals on a binary level, the characters are often cut, which makes the comparison inaccurrate. Plus, the comparison does not work if the texts have a different size.

Is there a better solution that could fit this case, given that as I stated, I am privileging the low complexity over the complete accuracy?

## Is there an algorithm like shamir secret sharing that allows arbitrary length inputs?

As far as I understand it, when using Shamir’s secret sharing algorithm, you have to specify a finite field for your operations that is big enough to hold your data.

I tried to look for secret sharing algorithms, but I only get results for Shamir’s secret sharing algorithm ..

Are there other algorithms or do I just store the field size together with the secrets?

## algorithm – First non-repeating Character, with a single loop in Python

As has been pointed out in the comments and @Kraigolas’s answer, the existing algorithm doesn’t work. Here’s why.

In the string `"xxy"`:

1. The algorithm first considers the third character, `"y"`. It finds it has not encountered it before, so records it as a preliminary `out` value. It adds it to `smap` with value `1`.
2. The algorithm next considers the second character, `"x"`. It finds it has not encountered this character before, either. It discards its previous preliminary `out` value, `"y"`, and adopts `"x"` as its new preliminary `out` value. It adds `"x"` to the dictionary with value `1`.
3. The algorithm now moves on to the first character, `"x"`. It realises that it has seen this one before, so adds `1` to the associated value in `smap`.
4. The algorithm has now finished iterating through the loop. Its current `out` value is `"x"`, but when it looks it up in the dictionary, it finds it has encountered `"x"` more than once. As a result, it assumes that there are 0 characters that it has seen only once, and returns `None`.

It is impossible to fix the current implementation of the algorithm while keeping to the condition that there should be “only a single loop”. If you were to relax this restriction, you could fix your current algorithm like this:

``````def first_non_repeater(string):
smap = {}

for i in range((len(string) - 1), 1, -1):
char = string(i)

if char in smap:
smap(char) += 1
else:
smap(char) = 1

while True:
try:
key, val = smap.popitem()
# KeyError is raised  it you try to do .popitem()
# on an empty dictionary
except KeyError:
return None
else:
if val == 1:
return key
``````

But at I say, this breaks the condition that only one loop is allowed.

I like @FMc’s answer using `collections.Counter` a lot; I think this is probably the most pythonic way of doing this.
The following solution, however, would be my attempt at a solution that only uses builtin data structures (nothing from `collections`), and that only uses a single loop. The solution only works on python 3.6+, as it relies on `dict`s being ordered. Feedback welcome:

``````from typing import TypeVar, Union, Optional

T = TypeVar('T')

def first_non_repeating_char(
string: str,
default: Optional(T) = None
) -> Union(str, T, None):
"""Return the first non-repeating character in a string.

If no character in the string occurs exactly once,
the function returns  the default value.

Parameters
----------
string: str
The string to be searched.
default: Any, optional
The value that is returned if there is no character
in the string that occurs less than twice,
by default None

Returns
------
Either a string of length 1, or the default value.
"""

# Using a dictionary as an ordered set,
# for all the characters we've seen exactly once.
# The values in this dictionary are irrelevant.
uniques: dict(str, None) = {}

# a set for all the characters
# that we've already seen more than once
dupes: set(str) = set()

for char in string:
if char in dupes:
continue

try:
del uniques(char)
except KeyError:
uniques(char) = None
else:

# return the first key in the dictionary
# if the dictionary isn't empty.
# If the dictionary is empty,
# return the default.
return next(iter(uniques.keys()), default)
``````

## algorithm – How do i create an event trigger system (discord bot)

So i am making a card game, i having issues implementing “effects” and effects that are continuous. How can i get effects to activate at the right times, before and after an attack does damage as well as apply a continuous effect through out each phase? Is there a way i can implement some sort of checklist system before and after attack? I’ve tried 5 times with this, and this is just my latest attempt, How can i code this system without making if-code mess if there any tips or help, i would greatly appreciate it! (as this is my first time making a trading card game.)

for context i am making this into a discord bot!

What i need help with:

• A System where i can check effects before, during and after attack
• A system where i continuous effects are applied before during or after an attack
• Applying the effect to the right target or to both targets
``````#while both players have health
# apply CONTINUOUS EFFECTS THROUGH OUT LOOP
while player1.hp > 0 and player2.hp > 0:
print("test battle in progress")
#class Card(object):
#def __init__(self, name, hp, cardType, effect, attacks, description, ability):

# Instantiate test subjects
player1 = Card("Pinata Trent", 9, "Strong", None,
(Attack("Trample", 24, 2, None, None, None),
Attack("Body Bash", 62, 4, "selfDamage", 2, "self")),
"Trent card", None)

player2 = Card("Barbarian", 10, "Strong", None,
(Attack("Head Bang", 68, 1, "selfDamage", 1, "self"),
Attack("Barbaric Swing ", 82, 2, None, None, None)),
None, None)

#randomly choose a move for both NPC
player1_move = random.choice(player1.attacks)
player2_move = random.choice(player2.attacks)

# Who ever player has the fastest attack value attacks first
first_attack = firstAttack(player1_move, player2_move)

if first_attack == 1:
print("player 1 attacks first")
await apply_damage(player2, player1_move)

# Apply effect of attack after or before attack
if player1_move.effect is not None:
print("player 1 attack effect activates")
player1 = player1.attack_effect(player1_move.effect, player1, player1_move.effectDamage)
print(str(player1.hp) + " // " + str(player2.hp))

# Player 2 attacks!
if player2.hp > 0:

player1.hp -= player2_move.damage
if player2_move.effect is not None:
print("player 2 attack effect activates")
player2 = player2.attack_effect(player2_move.effect, player2, player2_move.effectDamage)
print(str(player1.hp) + " // " + str(player2.hp))
await asyncio.sleep(2)

elif first_attack == 2 and player2.hp > 0:
print("player 2 attacks first")
player1.hp -= player2_move.damage
if player2_move.effect is not None:
print("player 2 attack effect activates")
player2 = player2.attack_effect(player2_move.effect, player2, player2_move.effectDamage)
print(str(player1.hp) + " // " + str(player2.hp))

# Player 1 attacks!
if player1.hp > 0:
player2.hp -= player1_move.damage
if player1_move.effect is not None:
print("player 1 attack effect activates")
player1 = player1.attack_effect(player1_move.effect, player1, player1_move.effectDamage)
print(str(player1.hp) + " // " + str(player2.hp))
await asyncio.sleep(2)
``````

attack move class:

``````class Attack:
def __init__(self, name, speed, damage, effect, effectDamage, target):
self.name = name
self.speed = speed
self.damage = damage
self.effect = effect
self.effectDamage = effectDamage
self.target = target

def attack_effect(self, tag, target, x):
"""
todo: card attack effects
"""

if tag == "selfDamage":
target.hp -= x
return target

if tag == "forEachDamageMoreDamage":
totalDamageTaken = target.starting_health - target.hp
for i in target.attacks():
if i.effect == "forEachDamageMoreDamage":
i.damage += totalDamageTaken
return target
``````

card class itself

``````class Card(object):
def __init__(self, name, hp, cardType, effect, attacks, description, ability):
self.name = name
self.hp = hp
self.starting_health = hp
self.type = cardType
self.attacks = attacks
self.original_attacks = attacks
self.effect = effect
self.description = description
``````

attack speed calculation

``````        def first_attack(player_atk_speed, opponent_atk_speed):
if player_atk_speed.speed > opponent_atk_speed.speed:
return 1
elif player_atk_speed.speed < opponent_atk_speed.speed:
return 2
else:
# decides who attacks based on random generation if attack speeds are EQUAL
return random.randint(1, 2)
``````

## Is there a simple algorithm for generating unit tests given a function’s code?

Given the abstract syntax tree (AST) of each line of a function’s code, I am asked to generate code for that function’s corresponding unit tests, similar to what Microsoft’s IntelliTest tool does here: https://docs.microsoft.com/en-us/visualstudio/test/generate-unit-tests-for-your-code-with-intellitest?view=vs-2019.

The issue is that I have to implement this from scratch instead of using built-in tools, since my project is implementing an ABAP to C# interpreter (ABAP is a programming language used for SAP’s enterprise software), which executes ABAP code in C#, so I cannot just use an IDE’s unit test generation tool.

I so far have decided that the first part of the algorithm is to generate the function’s parameters, but I’m not sure how I’m going to generate the function’s parameters exactly. Furthermore, I don’t know how the unit test generator is going to compute the expected outputs of the function.

Note: This algorithm doesn’t need to be an algorithm that works as well as an IDE’s automatic unit test generation, I just need to be able to come up with an algorithm that is an initial working prototype. But so far, I am stumped, and haven’t found any good online resources regarding this topic.

## programming languages – Is there a simple algorithm for generating unit tests given a function’s code?

Given the abstract syntax tree (AST) of each line of a function’s code, I am asked to generate code for that function’s corresponding unit tests, similar to what Microsoft’s IntelliTest tool does here: https://docs.microsoft.com/en-us/visualstudio/test/generate-unit-tests-for-your-code-with-intellitest?view=vs-2019.

The issue is that I have to implement this from scratch instead of using built-in tools, since my project is implementing an ABAP to C# interpreter (ABAP is a programming language used for SAP’s enterprise software), which executes ABAP code in C#, so I cannot just use an IDE’s unit test generation tool.

I so far have decided that the first part of the algorithm is to generate the function’s parameters, but I’m not sure how I’m going to generate the function’s parameters exactly. Furthermore, I don’t know how the unit test generator is going to compute the expected outputs of the function.

Note: This algorithm doesn’t need to be an algorithm that works as well as an IDE’s automatic unit test generation, I just need to be able to come up with an algorithm that is an initial working prototype. But so far, I am stumped, and haven’t found any good online resources regarding this topic.

## What is the complexity "Big O notation" of the following algorithm?

I m not sure if i got the correct complexity. I found $$O(sqrt(n))$$.
Can someone confirm with me if it’s the correct answer ?

(Mystere Algorithm)(1)

(1): https://i.stack.imgur.com/Yl9vS.pngstrong text