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.
a = {1, 2, 3, 4, 5};
(Most[#] -> Last[#]) & /@ Partition[a, 4, 1]
{{1, 2, 3} -> 4, {2, 3, 4} -> 5}
Partition
is n+1; however, n must have a numeric (positive integer) value.
$\endgroup$
Commented
Apr 27, 2015 at 18:29
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]
Developer`PartitionMap[Most@# -> Last@# &, a, 4, 1]
(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)
♃ = {#, #[[0]] @@ (# /. #[[0]] -> (1 + {##} &))} &@(#[[;; 3]] -> #[[4]] &@#) &;
♃ @ {1, 2, 3, 4, 5}
(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)
♃
with $
.
$\endgroup$