3
$\begingroup$

Let x and y be arrays defined as Array[x, m], Array[y,n] respectively.

How to generate the following function of $x$ and $y$ for variable $k$:

x[1]<y[n-k+1] && x[2]<y[n-k+2] && ... && x[k]<y[n]

Assume that $k<n$ and $k<m$.

$\endgroup$
5
$\begingroup$

Another approach, using Table:

n = 15;

doIt[k_ /; k < n] := And @@ Table[x[i] < y[n - k + i], {i, 1, k}]

Then:

doIt[5]
x[1] < y[11] && x[2] < y[12] && x[3] < y[13] && x[4] < y[14] && x[5] < y[15]

Note: maybe you want to condition k on m as well

$\endgroup$
4
$\begingroup$

If

x = Symbol["x" <> ToString[#]] & /@ Range[10];
y = Symbol["y" <> ToString[#]] & /@ Range[6];
k=4;

And @@ Thread[x[[1 ;; k]] < y[[-k ;;]]]
(* x1 < y3 && x2 < y4 && x3 < y5 && x4 < y6 *)
$\endgroup$
6
$\begingroup$

This can be done in many ways. A good approach uses e.g. MapThread, taking e.g. $n = 7, m = 6$ :

And @@ MapThread[ Less, {Array[y, 7][[3 ;;]], Reverse[Array[x, 6]][[2 ;;]]}] //
TraditionalForm
y(3) < x(5) && y(4) < x(4) && y(5) < x(3) && y(6) < x(2) && y(7) < x(1)

or Inner :

Inner[ Less, Array[y, 7][[3 ;;]], Reverse[Array[x, 6]][[2 ;;]], And]

Edit

As suggested in the comments let's add another general solution:

sol[k_, m_, n_] /; 1 <= k <= m <= n := 
    Inner[ Less, Take[ Array[y, n], {k, m}], 
                 Take[ Reverse @ Array[x, n], {k - 1, m - 1}], And]

so we have, e.g.

sol[4, 6, 7]
y[4] < x[5] && y[5] < x[4] && y[6] < x[3]
$\endgroup$
  • $\begingroup$ I prefer the Inner[] version myself, though I personally prefer Take[] to Part[]+Span[]. $\endgroup$ – J. M. will be back soon Apr 16 '13 at 13:10
  • $\begingroup$ @J.M. With Inner there is no need to use Apply as in the case of MapThread and it seems to be faster. $\endgroup$ – Artes Apr 16 '13 at 13:19
  • $\begingroup$ Right, and the problem's structure just screams for Inner[] to be used. :) $\endgroup$ – J. M. will be back soon Apr 16 '13 at 13:34

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.