Generating random sequence of integers with ordering constraints

I would like to write a Mathematica routine for generating random musical melodies that obey (some of) the constraints of traditional tonal harmony. For simplicity’s sake, I’m interested only in strictly diatonic melodies in a major key.

Assuming that all the note values in the melody are equal (whole notes, say), I simply represent the diatonic scale degrees of the major key by the integers 1 to 7. The harmonic constraints that I wish to implement are then as follows:

  1. The degrees 1, 3, 5 can move, by step or by leap, to any other scale degree.
  2. Degree 2 can move to either 1 or 3, with a slight stochastic bias towards 1.
  3. Degree 4 moves to 3.
  4. Degree 6 moves to 5.
  5. Degree 7 moves to 1.
  6. The "natural" tendencies of scale degrees 2, 4, 6, 7, as outlined above, can be negated by stepwise movement, up or down, along the major scale. For example: 7 – 6 in isolation is not allowed, but 1 – 7 – 6 or 7 – 6 – 5 is. The relative frequency of such scalar movements should preferably be (very roughly) proportional to the length of the scale fragment. For example, 1 – 7 – 6 – 5 – 4 should occur "more often" than just 1 – 7 – 6.
  7. Melodies should begin with one of the scale degrees 1, 3, 5, and end with one of the formulas 7 – 1, 2 – 1, 4 – 3, or 2 – 3.
  8. For bass melodies, I would instead of (7) like to have the optional constraint that all melodies end with the cadential formula 5 – 1.
  9. Melodies may be any length between 5 and 16 notes.
  10. Stepwise motion should predominate over leaps, in roughly the ratio 4 to 1.

Finally, if it’s possible, I’d like to have a function to put the generated melody into an audible form.

A tall order perhaps, but any suggestions would be appreciated, even if they solve my problem only partially.

How bad is to have 3 unique constraints in a table?

I have a table with articles. In this table I have article_title (varchar 500), article_meta_description (varchar 2000) and article_content (longtext). All of them are set to be unique (each of them, not together).


article_title because it’s better for SEO

article_meta_description because it’s better for SEO

article_content because I want to be sure there won’t be unwanted duplicates made by a bad insert

I am aware that it may have an impact on insert performance, but I’m not sure about the size of impact. I also don’t remember to have seen 3 unique columns in a single table somewhere.

So, how bad is what I’m doing ?

List of constraints in Minimize

I’m seeking a technique to automate a list of constraints in Mathematica. A sample piece of code is given below; it’s designed to take a 3D cube [0, 1]^3, sample 5 points uniformly randomly from this cube, scale + translate them to [-1, 1]^3, and use them in 5 constraints in the optimization problem "Minimize". I’ve hardcoded the constraints for the moment:

dimuncertset = 3; numsamples = 5; sampinposcube =    RandomVariate[UniformDistribution[dimuncertset], numsamples]; sampincube =    2*sampinposcube + ConstantArray[-1, {numsamples, dimuncertset}]; res = FindMinimum[{t,     t >= x Norm[sampincube[[1]], Infinity] -        Norm[sampincube[[1]], Infinity]^2 &&      t >= x Norm[sampincube[[2]], Infinity] -        Norm[sampincube[[2]], Infinity]^2 &&       t >= x Norm[sampincube[[3]], Infinity] -        Norm[sampincube[[3]], Infinity]^2 &&      t >= x Norm[sampincube[[4]], Infinity] -        Norm[sampincube[[4]], Infinity]^2 &&      t >= x Norm[sampincube[[5]], Infinity] -        Norm[sampincube[[5]], Infinity]^2, - 10 <= t <= 10,     0 <= x <= 1}, {t, x}] 

Any pointer will be appreciated.

Given the following constraints what is the maximum number of attacks in a round for 3.X edition?

A former DM has had the same recurring NPC/GMPC since I started playing in his game. This was 20+ years ago and we started in 1st edition and slowly made our way through the years and editions. We updated our characters as we went to the new editions. Now this NPC/GMPC is the most reviled in his games, any time he shows up all the players immediately want him dead. We stick to character though.

The question will be broken up to hopefully get expert answers from each of the editions in which we played in this particular question it will be specific to 3.Xe. I am skipping 4e (as we all hated it and only played one session) and 5e because I know for a fact that it is not possible there (yet).

The question is as follows:

Give the following constraints what is the maximum number of attacks in this edition:

  1. NPC is an Elf (In this edition it is irrelavent I suppose).
  2. He was a Thief-Acrobat in previous editions and I assume multiclassed, probably Fighter-Thief, due to how 3.X prestige works let’s assume just Rogue for this edition, although any official prestige class is fair game. Character focused on tumbling and thrown knife attacks.
  3. The weapon of choice was throwing knives.
  4. Assume unlimited ammunition as he had a bandalier that had the knives return.
  5. I know he could throw 3 knives at a time (pretty sure this was a thing for shuriken from Oriental Adventures).
  6. Assume all official sources and Dragon Magazine since the first issue are open.
  7. I know of this question and assume there is a variant with knives.
  8. If I recall he threw with both hands as well.
  9. Assume prestige classes are open, this DM even as a player had a tendency to stack multiclass options with min/max precision but assume Rogue is the primary focus.
  10. Assume Quick Draw.
  11. We were always between 8th and 15th level when I met this character.
  12. I do not recall spell-casting but not ruling it out entirely but main build would likely have been focused on mundane means.
  13. Assume focused magical item augmentation as well, just calling it out even though the aforementioned bandolier alluded to it, but for the most part official items other than that.
  14. Assume no flying invisible helpers as suggested by HeyICanChan or for that matter third party interventions or Aid Another.

The end result in game was quite literally at least 2 dozen attacks per round, perhaps more. Which I have questioned him multiple times about the build and legitimacy but he as refused to provide any answers. I know DMs do not have to justify but this, combined with a number of other things over the years has lead to distrust. I have since stopped playing his games altogether, so this is just a verification on whether I have overreacted.

This was broken into 3 questions for each of the editions.

AD&D, AD&D 2nd Edition, and Dungeons & Dragons 3.X.

Automatic Method for FindMinimum with constraints

What is the default method used by FindMinimum with constraints?

The documentation says-"Currently, the only method available for constrained optimization is the interior point algorithm"

But a random example gives different results for the Method->Automatic and Method->"InteriorPoints"

Reap[FindMinimum[{x^2 + y^2, (x - 1)^2 + 2 (y - 1)^2 > 5}, {{x,  4}, {y, 4}}, Method -> Automatic,StepMonitor :> Sow[{x^2 + y^2, x, y}]]]  Reap[FindMinimum[{x^2 + y^2, (x - 1)^2 + 2 (y - 1)^2 > 5}, {{x,      4}, {y, 4}}, Method -> "InteriorPoint",    StepMonitor :> Sow[{x^2 + y^2, x, y}]]] 

The above code yields the same final solution. But the steps taken are different for both, which suggests that the interior points is not used as the automatic one.

The same question has been asked here and here

So what is the exact method being used when Method->Automatic is specified?

Constraints and Tolerance

So I’m running NMaximize for optimizing a value and for constraints, I need the parameters to belong to a discrete set of elements. Basically, the constraint looks like,

And @@Table[{Subscript[x, i], Subscript[y, i]} \[Element] Table[Subscript[e, i, n], {i, 1, n}],{i, 1, k}] 

,where {Subscript[x, i], Subscript[y, i]} are my parameters satisfying the constraint that they should belong to Table[Subscript[ex, i, n], {i, 1, n}]

But NMaximize do not consider this as a constraint. Then I changed the constraint to the convex hull of Table[Subscript[ex, i, n], {i, 1, n}] with an additional constraint to pick out the extreme points aka the vertices. Now my code looks like,

And @@ Table[{Subscript[x, i], Subscript[y, i]} \[Element]  ConvexHullMesh[Table[Subscript[ex, i, n], {i, 1, n}]] &&  Subscript[z, i] == 1/2 &&  Subscript[x, i]^2 + Subscript[y, i]^2 == Subscript[r, n]/2, {i, 1,  k}] 

But, when I run this it outputs this error

Obtained solution does not satisfy the following constraints within
Tolerance -> 0.001`

What do I do?


Subscript[r, n_] := Sqrt[Sec[Pi/n]]; Subscript[w, i_,  n_] := {Subscript[r, n] Cos[2 Pi i/n],  Subscript[r, n] Sin[2 Pi i/n], 1}; Subscript[e, i_, n_] :=  1/2 {Subscript[r, n] Cos[(2 i - 1) Pi/n],  Subscript[r, n] Sin[(2 i - 1) Pi/n], 1}; Subscript[ex, i_, n_] :=  1/2 {Subscript[r, n] Cos[(2 i - 1) Pi/n],  Subscript[r, n] Sin[(2 i - 1) Pi/n]}; u = {0, 0, 1}; f = (u - #) &; (*Factors={1,2,3,12,13,23,123}*)  Factors = Times @@@ Subsets[Transpose@Tuples[{1, -1}, 3], {1, 3}]; (*Rearrange*) (*Rearrange the numbers in the RHS to obtain different \ combinations*)  Factors[[{1, 2, 3, 4, 5, 6, 7}]] = Factors[[{1, 2, 3, 4, 5, 6, 7}]]; Factors = Transpose[Factors]; Vec[j_] := {Subscript[x, j], Subscript[y, j], Subscript[z, j]}; AllParameters[k_] :=  Module[{i},  Flatten[Table[{Subscript[x, i], Subscript[y, i], Subscript[z,    i]}, {i, 1, k}]]]; AllConstraints[n_, k_] :=  Module[{i},  And @@ Table[{Subscript[x, i], Subscript[y, i]} \[Element]     ConvexHullMesh[Table[Subscript[ex, i, n], {i, 1, n}]] &&    Subscript[z, i] == 1/2 &&    Subscript[x, i]^2 + Subscript[y, i]^2 == Subscript[r, n]/2, {i,    1, k}]];       GPT[n_, k_] := Module[{ro, co, ve, i},  FunFactor = Factors[[1 ;; 8, 1 ;; k]] /. {1 -> Identity, -1 -> f};  vec = Table[Subscript[v,   i], {i, 1, k}] /. {Subscript[v, j_] -> Vec[j]};  vecs = Table[  Total[Table[FunFactor[[ro, co]][vec[[co]]], {co, 1, k}]], {ro, 1,   8}];  max = Total[  Table[Max[   Map[vecs[[ve]].# &, Table[Subscript[w, i, n], {i, 1, n}]]], {ve,    1, 8}]];  {time, out} =   Timing[NMaximize[{max, AllConstraints[n, k]}, AllParameters[k],   Method -> "NelderMead"]];  Print[out, out[[1]]/(k 8), "   ", time]; {time, out} =   Timing[NMaximize[{max, AllConstraints[n, k]}, AllParameters[k],   Method -> "DifferentialEvolution"]];  Print[out, out[[1]]/(k 8), "   ", time]; {time, out} =   Timing[NMaximize[{max, AllConstraints[n, k]}, AllParameters[k],   Method -> "SimulatedAnnealing"]];  Print[out, out[[1]]/(k 8), "   ", time];]       GPT[4, 7] 

Generate constraints that ensure positive definiteness

What is a good way to generate algebraic constraints that ensure matrix be positive definite? Ideally, I’d be able to do something like below

Solve[# \[Element] Reals & /@ Eigenvalues[A]]

However, this doesn’t directly work. Practical example below uses this to find the norm of a positive linear operator (related issue). It works, but requires AposDefiniteConstraints to be specified manually which I’d like to avoid.

(also tried Thread[Eigenvalues[X] > 0] suggestion from Find minimum with matrix positive-definiteness constraint but I get Maximize returning unevaluated)

(* Find norm of a positive transformation of a positive definite \ d-by-d matrix *) SeedRandom[1]; d = 2; symmetricMatrix[d_] := Array[a[Min[#1, #2], Max[#1, #2]] &, {d, d}]; extractVars[mat_] := DeleteDuplicates@Cases[Flatten@A, _a];  (* using built-in Norm/Simplify too slow, use this helper instead *)  norm[A_] :=    Max[x /. # & /@ Solve[CharacteristicPolynomial[A, x] == 0, x]];  A = symmetricMatrix[d]; Avars = extractVars[A];  B = Mean[#\[Transpose].A.# & /@     Table[RandomReal[{-1, 1}, {d,        d}], {d^2}]]; (* random positive transformation of A *) normA =   norm[A]; normB = norm[B]; AposDefiniteConstraints =    a[1, 1]^2 + 4 a[1, 2]^2 - 2 a[1, 1] a[2, 2] + a[2, 2]^2 >= 0 &&     a[1, 1]^2 + 4 a[1, 2]^2 - 2 a[1, 1] a[2, 2] + a[2, 2]^2 >= 0; Maximize[{normB, normA < 1,    AposDefiniteConstraints}, Avars] (* => {0.7853700810760375`,{a[1,1]\ \[Rule]0.999855037823971`,a[1,2]\[Rule]0.00017274783320670866`,a[2,2]\ \[Rule]0.9997941436806035`}} *)  ``` 

Are there heuristics in CSP to help avoid redundancy while checking constraints for inconsistent values?

I’m a complete beginner. Please forgive my ignorance.Trying to learn about CSP online, I noticed a lot of the focus on search methods and heuristics which tell you which variable to expand next (e.g. most constrained variable) and those that tell you which value to try first (e.g. least constraining value) but I’ve yet to see heuristics that relate to the ordering of constraints. Since I’m doing everything by hand, I notice a lot of redundancy when eliminating values from variable domains. How do you go about checking for violated constraints in a way that is efficient? Say constraint A will have me eliminate odd numbers 1 to 1000 and constraint B will have me wipe out everything above 250. Intuitively, it feels like order matters as I would waste my time cherry picking even numbers above 250 to only later find out that anything above 250 was not consistent in the first place. I apologize for lacking the proper terminology, my understanding is mostly intuitive. I hope it makes sense. Thanks in advance! I’m mostly looking to acquire a conceptual understanding of selected topics in computer science so if you have book recommendations or any resource that would be appropriate for me as an interested layman, please don’t hesitate!

Binary string satisfying several constraints

I’m trying to solve this problem, but without success.

Problem: You’re given a binary string where some of the bits are replaced by ?. You’re also given several intervals [$ l_i$ , $ r_i$ ] ($ l_i < r_i$ ). Find a binary string S with ? replaced by 0 or 1, such that in each interval [$ l$ , $ r$ ], s[$ l..r$ ] includes both 0 and 1.


Given the string 00?11 and the interval [2, 3], the string 00111 satisfies the requirements, as S[2..3]=01 include both 0 and 1.

However, the string 00?11 and the intervals [2, 3] and [3, 4] cannot be solved, as the ? would have to be both 0 and 1.

The bounds are |S|,Q<=1e5

I tried using greedy, but it’s giving wrong answer for this case: 0??0, [1, 3], [2, 3] and [3, 4], as the greedy algorithm would try 0??0 -> 01?0 -> 0100 -> fail, yet there exists a solution (0010).

I tried removing completely overlapping intervals (such as [1, 3] and [2, 3]), but there’re other cases I found that fails. What would be a correct solution?


Multi-dimensional Knapsack with Minimum Value constraints for Dimensions

In MDK, we have a vector $ W = \{W_1, W_2, …, W_d\}$ where each element corresponds to the maximum weight for the respective dimension in the knapsack.

I want to add a conditional constraint: $ V = {V_1, V_2, …, V_d}$ , where each $ i$ -th dimension in the knapsack must have a value sum greater than threshold $ V_i$ . I am not so much concerned with the total value sum.

I would like to show this problem is NP-hard. My intuition is that the additional constraint makes this problem harder than MKD and therefore is NP-hard. But clearly this doesn’t constitute a formal proof.