2
$\begingroup$

Suppose I had the following data

a={1,2,3,4,5}

How would I turn this into

b={{1,2,3}->4,{2,3,4}->5}

That is, transforming the data into rules where each class has a definition as the three before it.

$\endgroup$
4
$\begingroup$
a = {1, 2, 3, 4, 5};

(Most[#] -> Last[#]) & /@ Partition[a, 4, 1]

{{1, 2, 3} -> 4, {2, 3, 4} -> 5}

$\endgroup$
  • $\begingroup$ Great! Thanks so much! $\endgroup$ – Liam Schumm Apr 27 '15 at 18:21
  • $\begingroup$ Yes, the 2nd argument to Partition is n+1; however, n must have a numeric (positive integer) value. $\endgroup$ – Bob Hanlon Apr 27 '15 at 18:29
2
$\begingroup$

Try this solution:

ruleTransformer[from___, to_] := {from} -> to
ruleTransformer @@@ Partition[Range[5], 4, 1]

(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)

Partition breaks the data into groups of 4, with start of each group shifted by 1 from the previous. We then apply the helper function ruleTransformer, which takes a list of arguments from___ to be put into the beginning of the Rule, and a single argument to_ to be put at the end of the rule.

We can accomplish the same thing (with a slight modification) with an anonymous Function:

Function[# -> Reverse[{##2}]] @@@ Reverse /@ Partition[Range[5], 4, 1]
$\endgroup$
1
$\begingroup$
Developer`PartitionMap[Most@# -> Last@# &, a, 4, 1]
(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)
$\endgroup$
1
$\begingroup$
♃ = {#, #[[0]] @@ (# /. #[[0]] -> (1 + {##} &))} &@(#[[;; 3]] -> #[[4]] &@#) &;

♃ @ {1, 2, 3, 4, 5}
(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)
$\endgroup$
  • $\begingroup$ ... posted this separately since it belongs to a different ... well, species. In case some/most of your alphabetic keys are not functioning replace with $. $\endgroup$ – kglr Apr 28 '15 at 6:04

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.