I implemented Send an unknown method call.
I implemented Zebra puzzle, which was great fun!
I used a ‘sodoku kind of way’ to solve it. Each house has for each kind, all the candidates. Then, by applying the rules you filter out candidates until you’re left with 1 candidates per kind per house.
I implemented Metaprogramming.
Move-to-front algorithm:
mtf[string_] :=
Module[{word, p, q, symTable, symTable2},
p = {};
q = {};
symTable = StringJoin @@ CharacterRange["a", "z"];
Do[
If[
i == StringLength@string,
AppendTo[p,
StringPosition[symTable, StringTake[string, {i}]][[1, 1]] - 1];
symTable =
StringDrop[
symTable, {StringPosition[symTable, StringTake[string, {i}]][[1,
1]]}];
symTable = StringJoin[StringTake[string, {i}], symTable];
Print["'", string, "' encodes to: ", p],
AppendTo[p,
StringPosition[symTable, StringTake[string, {i}]][[1, 1]] - 1];
symTable =
StringDrop[
symTable, {StringPosition[symTable, StringTake[string, {i}]][[1,
1]]}];
symTable = StringJoin[StringTake[string, {i}], symTable];
]
, {i, StringLength@string}];
symTable = StringJoin @@ CharacterRange["a", "z"];
Do[
If[
j == StringLength@string,
q = StringJoin[q, StringTake[symTable, {p[[j]] + 1}]];
symTable2 =
StringDrop[
symTable, {StringPosition[symTable,
StringTake[symTable, {p[[j]] + 1}]][[1, 1]]}];
symTable =
StringJoin[StringTake[symTable, {p[[j]] + 1}], symTable2];
Print[p, " decodes to: '", q, "'"],
q = StringJoin[q, StringTake[symTable, {p[[j]] + 1}]];
symTable2 =
StringDrop[
symTable, {StringPosition[symTable,
StringTake[symTable, {p[[j]] + 1}]][[1, 1]]}];
symTable =
StringJoin[StringTake[symTable, {p[[j]] + 1}], symTable2]
]
, {j, StringLength@string}];
]
Any suggestions? Clunky code, but it gets the job done. Admittedly, I have cheated to get the problem “zero-indexed”. This can apparently be done with the Notation package, but I haven’t gotten a chance to look at it. Now back to my thesis!
In[347]:= Timing[mtf["broood"]]
During evaluation of In[347]:= 'broood' encodes to: {1,17,15,0,0,5}
During evaluation of In[347]:= {1,17,15,0,0,5} decodes to: 'broood'
Out[347]= {0.000612, Null}
Edit: I guess it’s not a symbol table array either, it’s just a string of the whole alphabet. Oh well.
Edit 2: Fixed the code. Good bug-catching!
mtf["zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx"]
'zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx' encodes to: {25,2,13,4,7,12,21,1,23,5,10,17,12,5,13,2,2,21,19,14,19,3,20,6,25,23,20,10,4,14,15,20,12,15,24,6,14,3,23,25}
{25,2,13,4,7,12,21,1,23,5,10,17,12,5,13,2,2,21,19,14,19,3,20,6,25,23,20,10,4,14,15,20,12,15,24,6,14,3,23,25} decodes to: 'zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx'
I just tested the algorithm by just inputting random strings and checking if the decoded is always the same as the input:
It works for most cases, however for the case of:
mtf["zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx"]
It spawns an error. I’m having trouble understanding the algorithm to be honest
Lines like:
StringDrop[symTable, {StringPosition[symTable, StringTake[string, {i}]][[1, 1]]}]
Confuse me ![]()
To make it zero-indexed we can just subtract 1 for outputting, and add 1 for inputting?
Any thoughts why this error occurs?
The problem seems to arise whenever the last letter is the last of the symbol string. I am posting a fix in a very short while. Notice that the second and third “If” argument in the decoding “Do” are slightly different. I have introduced a different string of symbols in one, and forgot to change the other. I will post a fix right after I have written out this post.
The code is first deleting the symbol from the list, which reduces the string length by 1, and then it tries to prepend the same symbol which should be at position 26, however the value has been deleted and the string is only 25 symbols long, which spawns the errors. By introducing a list number 2 which is deleted from, we can prepend the value to list 2 by funneling the symbol from list 1.
The line of code you pasted removes the input letter from the symbol string, the following code would prepend to the symbol string. The reason it’s so clunky is that you can’t do:
symTable = "abc";
StringDrop[symTable,"b"]
But rather
symTable = "abc";
StringDrop[symTable, {2}]
This means that we have to know where the “b” occurs;
StringPosition[symTable, StringTake[string , {i}]]
Outputs a list of the start- and stop-position of the string you are looking for, of the form
{{2,2}}
For which we only need one of the numbers to ge the correct placement. We can then replace the 2 in
StringDrop[symTable, {2}]
By the following code:
StringPosition[symTable, StringTake[string , {i}]][[1,1]]
Re: Move-to-front algorithm, for a lot of iterative algorithms it’s useful to use Nest/Fold and company:
f[{output_, symList_}, next_] := Module[{index},
index = Position[symList, next][[1, 1]] - 1;
{output~Append~index, Prepend[Delete[symList, index + 1], next]}];
Fold[f, {{}, CharacterRange["a", "z"]}, Characters["broood"]]
Part of the usefulness is that it lets you work without having to think about how variables are changing (what some overzealous languages call “avoiding state”). In this case the incoming state of the algorithm is in the {output, symList} double passed in as the first argument to your function, and all your function has to do is figure out what the next state is, given that state and the next character in the input string. Function arguments in Mathematica are immutable precisely for this kind of thing (i.e. to make it easier to reason about your code).
A very similar method can be used to decrypt the output… I leave to others if interested.
Well, that was pretty compact compared to my clunkstrosity! I guess it’s quite obvious I am not familiar with a ton of the functions built in to Mathematica.
Here is my suggestion for a complete algorithm, based on your encoding algorithm.
mtf[word_] :=
Module[{f, f2},
f[{output_, symList_}, next_] :=
Module[{index}, index = Position[symList, next][[1, 1]] - 1;
{output~Append~index,
Prepend[Delete[symList, index + 1], next]}];
p = Fold[f, {{}, CharacterRange["a", "z"]},
Characters[ToString[word]]][[1]];
Print["'" word, "' encodes to: ", p];
f2[{output_, symList_}, next_] :=
Module[{index}, index = symList[[next + 1]];
{output~Append~index,
Prepend[DeleteCases[symList, ToString[index]], index]}];
q = Fold[f2, {{}, CharacterRange["a", "z"]}, p][[1]];
Print[p, " decodes to: '", StringJoin@q, "'"]
]
Interestingly, I find the “old” algorithm to run a bit faster, tested with some random long string, with 1000 repetitions using AbsoluteTiming. Undoubtedly, though, this algorithm is much more elegant.
I would have used StringReplace:
StringReplace["abcdefghijkl","d"->""]
will output:
abcefghijkl
Oh, that is very nice! Thanks for sharing, I need to keep my eyes out for more clever solutions instead of hard-coding some massive piece of code.
Remove lines from a file:
f[document_, start_, n_] :=
Module[{p, q},
SetDirectory@NotebookDirectory[];
p = Import[StringJoin[ToString@document, ".txt"], "Data"];
If[start + n - 1 <= Dimensions[p][[1]],
q = Delete[p, Table[{i}, {i, start, start + n - 1}]];
Export[StringJoin[ToString@document, "Removed.txt"], q];,
Print["Too few lines in document. Operation aborted."]]]
Removes n lines including the designated starting line from the assigned txt file. Exports to a new file with suffix to indicate that the document has had lines removed, to not destroy the original file if the operation is run multiple times by mistake.
Looks good to me; shall I add it?
Here are some improvements that we should consider:
- document_ should be document__String_ to make it more foolproof, same for start_ and n_ Both should have head Integer.
- I would omit StringJoin[ToString@document, “.txt”] and just replace it by document; so the user can provide the filename directly.
- Maybe import it as “List”, so you are sure that we have each ‘line’ of the file as an item.
- Dimensions[p][[1]] can be replaced by Length right?
- Table[{i}, {i, start, start + n - 1}] could be replaced by List/@Range[start,start+n-1] BUT:
- Delete[p, Table[{i}, {i, start, start + n - 1}]] could be replaced by Drop[p,{start,start+n-1}] directly. faster, and more concise.
- If the import is used using List export can be exported too using List: Export[FileNameJoin[{document,“_removed.txt”}],q,“List”]
- the variable q could be omitted: just overwrite p. (minor change of course…)
In general you should use the functions: FileNameSplit, FileNameJoin,FileNameTake,FileNameDrop, FileBaseName et cetera for combining filenames and folders. These are platform independent and should work on mac/linux/windows (the main problem is the "" and “/” difference).
That would be excellent!
While I look over your suggestions on the remove line from file code, here is a start for reading a configuration file. I have ran into a brick wall with the “other family” list, but I might be attacking this problem from the wrong angle.
SetDirectory@NotebookDirectory[];
p = {}; m = {};
q = Fold[DeleteCases, Import["config.txt", "Data"], {{""}, {"#"}}];
Do[If[StringFreeQ[q[[i]], {"#"}][[1]],
AppendTo[p, q[[i]]], ""], {i, Length@q}];
name = DeleteCases[
StringCases[Flatten[p], "FULLNAME " ~~ x__ -> x], {}][[1, 1]];
m~AppendTo~{"name", name};
favf = DeleteCases[
StringCases[Flatten[p], "FAVOURITEFRUIT " ~~ x__ -> x], {}][[1,
1]];
m~AppendTo~{"favouritefruit", favf};
If[StringMatchQ[
Flatten[StringCases[Flatten[p], ___ ~~ "NEEDSPEELING"]],
"NEEDSPEELING"][[1]], needspeeling = "true",
needspeeling = "false"];
m~AppendTo~{"needspeeling", needspeeling};
If[StringMatchQ[
Flatten[StringCases[Flatten[p], ___ ~~ "SEEDSREMOVED"]],
"SEEDSREMOVED"][[1]], seedsremoved = "true",
seedsremoved = "false"];
m~AppendTo~{"seedsremoved", seedsremoved};
Grid[m, Frame -> All]
Adding the config file as well.
Here is a revised version, taking your suggestions into account.
f[document_, start_, n_] :=
Module[{},
SetDirectory@NotebookDirectory[];
p = Import[document, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
Export[StringJoin[FileBaseName[document], "_removed.txt"], p,
"List"];,
Print["Too few lines in document. Operation aborted."]]]
I omitted the following;
FileNameJoin[{document,"_removed.txt"}]
As it tried to create a folder within testdocument.txtwhich, at least in OSX, can’t be done ![]()
hola Sander, aqui esta mi propuesta para the Stable marriage problem, aunque es muy rustica cumple con el requisito de aplicar el algoritmo Gale/Shapley . Por favor hazle las modificaciones que cosideres necesarias, saludos y cuidate.
Mathematica is quite unusual compared to most programming languages, so it’s difficult if you don’t know what kinds of functions to look for in the first place. A very vague rule of thumb I would recommend is looking for functions that work in “broad strokes.” And generally you should try to write things in terms of functions, because of their composability and how they are used in those “broad strokes” functions. The quintessential example here is For vs Map:
newList = Range[Length[list]];
For[i = 1, i <= Length[list], i++,
newList[[i]] = someF[list[[i]]]]
vs
Map[someF, list]
The real key though is that you have to have the impulse to look for these things. You ain’t gonna find them if you aren’t looking for them!
BTW in the decoder part for the move-to-front algorithm, remember that you get the index stream through the Fold function. Here’s a more explicit version to make it easier to read:
f2[{output_, symList_}, nextIndex_] := Module[{char},
char = symList[[nextIndex + 1]];
{output~Append~char, Prepend[Delete[symList, nextIndex + 1], char]}];
Also:
{output_, symList_} ~f2~ nextIndex_ := Module[{char}...
I wouldn’t recommend this infix form for a Rosetta submission, but it could help when thinking of how to write a function for Fold. Also:
Fold["f", initial, Range[4]] // TreeForm
Note that in this tree, the left branches/subtrees are where the ‘state’ is coming from.
I added it! Thanks!