4
$\begingroup$

I have a function of x:

f[x_] := Abs[Extract[list, x + n] - Extract[list, x]]

I then apply this:

g = Length[Cases[Map[f, Table[i, {i, Length[list] - n}]], 0]]

This counts the number of occurences when two letters are the same at a distance of n in the list.

However, I wish to be able to alter the value of n, and map the values of g as n takes the value of 1,2,3,.. etc. Is there a way to do this? I simply want Mathematica to let n be 1, apply g, let n be 2, apply g... etc and then to map the results?

Any replies are greatly appreciated!

$\endgroup$
1
$\begingroup$
comp[a_, b___, c_] := a == c
k[list_, dist_] := Count[ListConvolve[SparseArray[{1 -> 1, # -> 1}, #]&[dist+1], list, {-1, 1}, 0, 
                                      Times, comp], 
                        True]

list = {d, a, e, a, e, b, e, b, c, d, d};
k[list, #] & /@ Range[Length[list] - 1]

(* {1, 4, 0, 1, 0, 0, 0, 0, 1, 1} *)
$\endgroup$
1
$\begingroup$

Not sure if this would this would achieve what you described (I haven't been using MMA as much as I would like so my answer might be clumsy):

Clear[countSameLetters]
countSameLetters[list_List, distance_Integer] :=
 Position[
   Flatten@Differences@Position[list, #] & /@ 
    CharacterRange["a", "z"], distance] // Length

To display each distance with its corresponding count and repeated letters:

Clear[countAndDisplaySameLetters]
countAndDisplaySameLetters[list_List, distance_Integer] :=
 Module[{distancePerLetter, aToZ, letterPositions},
  aToZ = CharacterRange["a", "z"];
  letterPositions = 
   First /@ 
    Position[Differences@Flatten@Position[list, #] & /@ aToZ, 
     distance];
  {distance, Length[letterPositions], 
   Part[aToZ, DeleteDuplicates@letterPositions]}
  ]

Testing:

randomChar = RandomChoice[CharacterRange["a", "z"], 100]

Mathematica graphics

countSameLetters[randomChar, 5]
(* 2 *)

countAndDisplaySameLetters[randomChar, 5]
(* {5, 2, {"e", "i"}} *)

countAndDisplaySameLetters[randomChar, #] & /@ Range[1, 10] // 
 TableForm[#, 
   TableHeadings -> {None, {"Distance", "Count", "Letters"}}, 
   TableSpacing -> {5, 2}] &

Mathematica graphics

$\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.