6
$\begingroup$

Just for learning purposes I try to create a list that looks like this: {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

One way to do it is by using Table:

Table[{j + 2 i, (j + 2 i)^2}, {i, 0, 1}, {j, 3, 4}]

Now I try it using functional programming, but I failed. This is what I tried:

Nest[Map[{#, #^2} &], Range[3, 4], 2]

Is it possible to create the desired result only using Nest, Map and Range? If not, what other function should I use, without using Table, but using a Pure Function instead?

$\endgroup$
  • $\begingroup$ oops ... ({#, Power[#, 2]} & @ Range[3, 6] // Transpose // ArrayReshape[#, {2, 2, 2}] &) == ({#, # #} & @ Range[3, 6] // Transpose // ArrayReshape[#, {2, 2, 2}] &) == want $\endgroup$ – user1066 Jul 15 '17 at 22:55
  • $\begingroup$ @tomd Thanks! Then this would be even shorter: {#, # #} & /@ Range[3, 6] // ArrayReshape[#, {2, 2, 2}] & $\endgroup$ – GambitSquared Jul 16 '17 at 8:59
8
$\begingroup$
Partition[{#, # #} & /@ Range[3, 6], 2]

{{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

$\endgroup$
  • $\begingroup$ That's not the same list! ;-) $\endgroup$ – GambitSquared Jul 15 '17 at 22:02
  • $\begingroup$ Sorry, see update $\endgroup$ – eldo Jul 15 '17 at 22:06
  • $\begingroup$ Ah, yes, I should have used Partition $\endgroup$ – GambitSquared Jul 15 '17 at 22:13
5
$\begingroup$
Array[{#, #^2} & @@ {#2 + 2 #} &, {2, 2}, {0, 3}] (* or *)
Outer[{#, #^2} & @@ {#2 + 2 #} &, {0, 1}, Range[3, 4]]

{{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

Removing hard-coded parameters:

f1 = Module[{x = #[[1]], l = Length@#}, 
    Array[{#, #^2} & @@ {#2 + l #} &, {l, l}, {0, x}]] &;
f1 @ Range[3, 4]

{{{3, 9}, {4, 16}},
{{5, 25}, {6, 36}}}

f1 @ Range[4, 6]

{{{4, 16}, {5, 25}, {6, 36}},
{{7, 49}, {8, 64}, {9, 81}},
{{10, 100}, {11, 121}, {12, 144}}}

And, similarly for Outer:

f2 = Module[{l = Length@#, x = #}, 
      Outer[{#, #^2} & @@ {#2 + l #} &, Range[l] - 1, x]] &;

f2 @ Range[3, 4]

{{{3, 9}, {4, 16}},
{{5, 25}, {6, 36}}}

f2 @ Range[4, 6]

{{{4, 16}, {5, 25}, {6, 36}},
{{7, 49}, {8, 64}, {9, 81}},
{{10, 100}, {11, 121}, {12, 144}}}

Also

☺ = # /. ♯_ :> ({#, #^2} & @@@ ({♯ + #} & /@ {0, (♯♯ = 0; ♯♯++ & /@ #; ♯♯)})) &;

☺ @ {3, 4}

{{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

☺ @ Range[3, 7]

{{{3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49}},
{{8, 64}, {9, 81}, {10, 100}, {11, 121}, {12, 144}}}

$\endgroup$
  • $\begingroup$ Unfortunately there are too many brackets. OP wants ` {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}` $\endgroup$ – eldo Jul 16 '17 at 0:26
  • $\begingroup$ @eldo, fixed it. $\endgroup$ – kglr Jul 16 '17 at 12:31
4
$\begingroup$
BlockMap[{{#1[[1]], #[[1]]^2}, {#1[[2]], #[[2]]^2}} &, Range[3, 6], 2]
(* {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.