Need an algorithm... not sure what this is called [closed] - algorithm

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Given a string: "ABCD", return the substrings with one or more missing characters keeping the order of the strings. This doesn't seem to be a "permutation", but I'm not sure if this algorithm has a name. I am using this to generate anagrams of a word and words within a word.
Example:
A
B
C
D
AB
BC
CD
AC
AD << missing BC
ABC
BCD
ACD
ABD

You're generating the ordered power set of the characters of the input string - meaning, all the subsets you can get from the set of characters in the input string, preserving the initial order:
input = { A, B, C, D }
output = { {}, {A}, {B}, {C}, {D}, {A, B}, {B, C} {C, D}, {A, C}, {A, D},
{B, D}, {A, B, C}, {A, B, D}, {A, C, D}, {B, C, D}, {A, B, C, D} }
The resulting set has 2^n elements (with n being the size of the input set), you might want to remove the empty set and the input set from the result, but basically this is the algorithm you're looking for. It's easy to find implementations for any language you want.

Related

How to multiply Column vector by Row vector in Mathematica?

I want to multiply every value in a column vector by the same vector but transposed to row. The output should be a multiplication table matrix. Like the third example in this picture.
I tried multiplying a column vector by its transposed form but Mathematica only gives me this which is not a Matrix.
Bryan,
You need to use Dot, not Times. See docs.
m = {{a}, {b}, {c}}
m.Transpose[m]
{{a^2, a b, a c}, {a b, b^2, b c}, {a c, b c, c^2}}
You might inappropriately define row vectors and column vectors. Try this:
rowvec={{a,b,c}};
colvec={{d},{e},{f}};
Then the command dot will give both inner product and outer product correctly.
rowvec.colvec
output: {{a d + b e + c f}}
colvec.rowvec
output: {{a d, b d, c d}, {a e, b e, c e}, {a f, b f, c f}}

Deleting column in Mathematica [duplicate]

This question already has an answer here:
Simple way to delete a matrix column in Mathematica
(1 answer)
Closed 9 years ago.
I have a huge list, ex. {a,b,c},{d,e,f} and I must have only {a,c},{d,f}. I using import from url.
My sentence:
Drop[Import["url"],{2}]
And it doesn't work. Why?
Just use the third parameter of the Drop function, like so:
list = {{a, b, c}, {d, e, f}};
Drop[list, None, {2}]
This will return:
{{a, c}, {d, f}}
You need to map drop over the list.
list = {{a, b, c}, {d, e, f}};
Map[Drop[#, {2}] &, list]
{{a, c}, {d, f}}
Alternatively, use transpose, but this is apparently less efficient because it makes copies of the list.
Transpose#Drop[Transpose#list, {2}]

Collections.sort() issue in java7

Is there a sort issue with java7? I am using Collections.sort(list, comparator)
When I switched over to java7, I noticed that the sorting resulted in a different list compared to the result when I was using java6.
Example: List = [d, e, b, a, c, f, g, h]
In java6 Collections.sort(List, comparator) resulted in [a, b, c, d, e, f, g, h]
In java7 Collections.sort(List, comparator) resulted in [b, a, c, d, e, f, g, h]
The first two values in the list have been swapped.
Java 7 switched from Merge sort to Tim sort. It might result in slight changes in order with "broken comparators" (quoting comment in source code of Arrays class):
/**
* Old merge sort implementation can be selected (for
* compatibility with broken comparators) using a system property.
* Cannot be a static boolean in the enclosing class due to
* circular dependencies. To be removed in a future release.
*/
Try running your JVM with:
java -Djava.util.Arrays.useLegacyMergeSort=true
It's not clear what "broken comparator" means, but apparently it can result in different order of elements in sorted arrays.
One thing to note, that might be causing confusion. Collections.sort is a stable sort. This means for equal elements, it maintains their original ordering, so:
if a == b, then
Collections.sort([d, e, b, a, c, f, g, h]) = [b, a, c, d, e, f, g, h]
and
Collections.sort([d, e, a, b, c, f, g, h]) = [a, b, c, d, e, f, g, h]
Seems likely to me that either that is what your seeing, or the Comparator in question (or the objects being sorteds' natural ordering) isn't working the way you expect it to.

How to remove the extra {} when Mapping a function to a list

Simple question, given a list like this
Clear[a, b, c, d, e, f];
lst = {{a, b}, {c, d}, {e, f}};
and suppose I have a function defined like this:
foo[x_,y_]:=Module[{},...]
And I want to apply this function to the list, so If I type
Map[foo, lst]
This gives
{foo[{a, b}], foo[{c, d}], foo[{e, f}]}
I want it to come out as
{foo[a, b], foo[c, d], foo[e, f]}
so it works.
What is the best way to do this? Assume I can't modify the function foo[] definition (say it is build-in)
Only 2 ways I know now are
Map[foo[#[[1]], #[[2]]] &, lst]
{foo[a, b], foo[c, d], foo[e, f]}
(too much work), or
MapThread[foo, Transpose[lst]]
{foo[a, b], foo[c, d], foo[e, f]}
(less typing, but need to transpose first)
Question: Any other better ways to do the above? I looked at other Map and its friends, and I could not see a function to do it more directly than what I have.
You need Apply at Level 1 or its short form, ###
foo###lst
{foo[a, b], foo[c, d], foo[e, f]}
One possible way is to change head of each element of lst from List to foo:
foo ## # & /# lst
{foo[a, b], foo[c, d], foo[e, f]}
Just to report puzzling performance tests of the both methods (###, ## # & /#) :
T = RandomReal[{1,100}, {1000000, 2}];
H[F_Symbol, T_List] :=
First#AbsoluteTiming[F ### T;]/First#AbsoluteTiming[F ## # & /# T;]
Table[{ToString[F], H[F, T]}, {F, {Plus, Subtract, Times, Divide, Power, Log}}]
Out[3]= {{"Plus", 4.174757},
{"Subtract", 0.2596154},
{"Times", 3.928230},
{"Divide", 0.2674164},
{"Power", 0.3148629},
{"Log", 0.2986936}}
These results are not random, but roughly proportional for very different data sizes.
### is roughly 3-4 times faster for Subtract, Divide, Power, Log while ## # & /# is 4 times faster for Plus and Times giving rise to another questions, which (as one can believe) could be slightly
clarified by the following evaluation:
Attributes#{Plus, Subtract, Times, Divide, Power, Log}
Only Plus and Times have attributes Flat and Orderless, while among the rest only Power (which seems relatively the most efficient there) has also an attribute OneIdentity.
Edit
A reliable explanation to observed performance boosts (thanks to Leonid Shifrin's remarks) should go along a different route.
By default there is MapCompileLength -> 100 as we can check evaluating SystemOptions["CompileOptions"].
To reset autocompilation of Map we can evaluate :
SetSystemOptions["CompileOptions" -> "MapCompileLength" -> Infinity]
Now we can test relative performance of the both methods by evaluating once more our H - performance testing function on related symbols and list :
Table[{ToString[F], H[F, T]}, {F, {Plus, Subtract, Times, Divide, Power, Log}}]
Out[15]= {{"Plus", 0.2898246},
{"Subtract", 0.2979452},
{"Times", 0.2721893},
{"Divide", 0.3078512},
{"Power", 0.3321622},
{"Log", 0.3258972}}
Having these result we can conclude that in general Yoda's approach (###) is the most efficient, while that provided by Andrei is better in case of Plus and Times due to automatic compilation of Map allowing better performance of (## # & /#).
A few more possibilities to pick from:
This one is a more verbose version of yoda's answer. It applies foo at level 1 of the list lst only (replaces the head List with the head foo):
Apply[foo, lst, {1}]
This does the same, but maps Apply over the list lst (essentially Andrei's answer):
Map[Apply[foo, #] &, lst ]
And this just replaces the pattern List[x__] with foo[x] at level 1:
Replace[lst, List[x__] -> foo[x], 1]
The answers on Apply[] are spot on, and is the right thing to do, but what you were trying to do, was to replace a List[] head with a Sequence[] head, i.e. List[List[3,5],List[6,7]] should become List[Sequence[3,5],Sequence[6,7]].
Sequence head is what naturally remains if a head of any list of parameters is deleted, so Delete[Plus[3,5],0] and Delete[{3,5},0] and Delete[List[3,5],0] would all produce Sequence[3,5].
So foo#Delete[#,0]&/#{{a, b}, {c, d}, {e, f}} will give you the same as foo###{{a, b}, {c, d}, {e, f}}.
Alternatively, foo[#/.List->Sequence]&/#{{a, b}, {c, d}, {e, f}} does the same thing.

How should I write a function to be used in Apply in Mathematica?

I am wondering how I can write a function to be used in the Apply function in Mathematica? For example, I want to trivially re-implement the Or function, I found the following
Apply[(#1 || #2)&,{a,b,c}]
is not okay since it only Or'ed the first two elements in the list. Many thanks!
This will work, no matter how many vars, and is a general pattern:
Or[##]&,
for example
In[5]:= Or[##] & ## {a, b, c}
Out[5]= a || b || c
However, in the case of Or, this is not good enough, since Or is HoldAll and short-circuiting - that is, it stops upon first True statement, and keeps the rest unevaluated. Example:
In[6]:= Or[True, Print["*"]]
Out[6]= True
In[7]:= Or[##] & ## Hold[True, Print["*"]]
During evaluation of In[7]:= *
Out[7]= True
This will be ok though:
Function[Null,Or[##],HoldAll],
for example,
In[8]:= Function[Null, Or[##], HoldAll] ## Hold[True, Print["*"]]
Out[8]= True
and can be used in such cases (when you don't want your arguments to evaluate). Note that this uses an undocumented form of Function. The mention of this form can be found in the book of R.Maeder, "Programming in Mathematica".
HTH
Or ## {a, b, c}
Equivalent
Apply[Or, {a, b, c}]
Equivalent
{a, b, c} /. {x_, y__} -> Or[x, y]
Apply works like this:
{2 #1, 3 #2, 4 #3} & ## {a, b, c}
{2 a, 3 b, 4 c}
Plus[2 #1, 3 #2, 4 #3] & ## {a, b, c}
2 a + 3 b + 4 c
Are you sure you are expecting the right thing from Apply? If you look in the documentation, http://reference.wolfram.com/mathematica/ref/Apply.html, you will see that Apply[f,expr] simply replaces the head of f by expr. It does not, in general, give f[expr].
If you wish to operate with function f onto expr, try f#expr or f[expr].
Perhaps you understand the above and your question really is, "how do I define some f that, when I do Apply[f,{a,b,c}], does the same job as Or[a,b,c]. Is that it?

Resources