New answers tagged

3

This seems pretty quick... Block[{base = ConstantArray[1, Binomial[# + 1, 2]]}, base[[Accumulate@Range[#, 2, -1] + 1]] += Range[# - 1]; Accumulate@base] & and this seems faster... Block[{r = Range[#, #^2, #]}, Join @@ Range[Subtract[r, Range[# - 1, 0, -1]], r]] &


2

This seems a different approach, exchanging Table by ConstantArray and Accumulate sieve[d_] := Module[{u = ConstantArray[1, d (d + 1)/2], o = Range[2, d], index}, index = 1 + Accumulate[Reverse[o]]; u[[index]] = o; Accumulate[u] ] However, it does not seem to perform better than the other algorithms in my notebook: AbsoluteTiming[sieve[10000];] ...


3

Another way without Table: listN[d_]:= Join @@ NestList[d + Rest@# &, Range[d], d - 1] It performs not so bad but slower than the fastest methods.


3

different ... but slow :) f1 = SparseArray[UpperTriangularize[Partition[Range[#^2], #]]][ "NonzeroValues"] & f1 /@ {3, 4} {{1, 2, 3, 5, 6, 9}, {1, 2, 3, 4, 6, 7, 8, 11, 12, 16}} Also different but slower: f2 = Flatten[UpperTriangularize[Partition[Range[#^2], #]] /. 0 -> (## &[])] & f3 = Sort[SparseArray[{i_, j_} /; i <= j :> ...


6

This works: f[d_] := Join @@ MapThread[ Range, Transpose@Table[{(i - 1) d + i, i d}, {i, d}] ]; so f[3] {1, 2, 3, 5, 6, 9} and it's pretty fast as well: AbsoluteTiming[f[10000];] {0.410494, Null} same caveat about Join@@ vs Flatten@ as Martin B├╝ttner by whose wise comment this can be simplified to merely: f[d_] := Join @@ Range @@@ ...


7

Whenever you're building a list with While or For, there's a good chance Table or Array can help. In this case, the solution with Table is quite simple: just use two iterators and make the bounds of the second dependent on the first iterator: list[d_] := Join @@ Table[i*d + j, {i, 0, d}, {j, i + 1, d}] The Join @@ is used to flatten the array. Flatten @ ...


6

Introduction What are good (robust?, simple?, efficient?) patterns for doing this kind of code-switching? This answer outlines a development strategy that can produce robust and extensible method option handling. Conceptually and development-wise, it is not that simple, but it has been successfully applied in large software projects with complicated ...


8

In general, I using the following strategy: Using a varible $MethodValues to store all the possible method value. Using If[] and Return[$Failed] to check the validness of method value that user given, which can make the code more robust. Using Switch[]/Which[] to deal with each case. Options[saveData] = {Method -> Automatic}; $MethodValues = ...


7

Normally this would be comment. but I post it here so there will be an answer. There is nothing wrong with the way you implementing your function. Your code is robust, simple, and efficient and IMO follows good Mathematica functional programming style.



Top 50 recent answers are included