3

Consider the following code to produce the sequence $x_1,\ldots,x_{n+1}$ where $x_i=11\cdots1$ ($i$ digits 1). Is there an easier way to do this?

n = 7
X = Table[Sum[10^i, {i, 0, k - 1}], {k, 1, n + 1}]
R = Table[Mod[X[[k]], n], {k, 1, n + 1}]
X 
R

Also, the code defines the list R of remainders on division of $x_i$ by $n$. The output of R is {1, 4, 6, 5, 2, 0, 1, 4}.

I'd like to do the following: determine the indexes producing the first two equal elements of R (for example, since R[[1]]=R[[7]] I'd like to do some math with X[[1]] and X[[7]]).

eldo
  • 67,911
  • 5
  • 60
  • 168
Sigur
  • 693
  • 5
  • 18

4 Answers4

4
r = {1, 4, 6, 5, 2, 0, 1, 4};

sol = Select[GatherBy[Range[Length@r], r[[#]] &], Length@# > 1 &, 1][[1,;;2]]
(* {1,7} *)

(Credit: @Szabolcs's answer in this Q/A)

or

sol2 = ## & @@@ Position[r, (Select[Gather[r], Length@# > 1 &, 1][[1, 1]]), 1, 2]

or

sol3 = ReplaceList[r, {a___, b : PatternSequence[i_, ___, i_], ___} :> 
                       Sequence[1 + Length[{a}], Length[{a}] + Length[{b}]], 1]

Update:

f[n_] := Module[{x = Table[Sum[10^i, {i, 0, k - 1}], {k, 1, n + 1}],  r, sol},
       r = Mod[x, n]; 
       sol =Select[GatherBy[Range[Length@r], r[[#]] &], Length@# > 1 &, 1][[1,;;2]]; 
       {x, r, sol, x[[sol[[2]]]] - x[[sol[[1]]]]}]

f[7]
(* {{1,11,111,1111,11111,111111,1111111,11111111},
    {1,4,6,5,2,0,1,4},
    {1,7},
    1111110} *)
kglr
  • 394,356
  • 18
  • 477
  • 896
3
n = 7;

{X, R} = Table[(10^x - 1)/9, {x, 1, n+1}] // {#, Mod[#, n]} &;

X

R

matchPairs = Subsets[Range@Length@R, {2}][[First@Position[Subsets[R, {2}], {x_, x_}]]]

(*

{1, 11, 111, 1111, 11111, 111111, 1111111, 11111111}
{1, 4, 6, 5, 2,0, 1, 4}

{{1,7}}

*)

Just take First@matchPairs to get first only of any pairs of indices that have same value for remainder.

BTW - bad idea to use uppercase symbols/initials - you can clash with built-ins...

ciao
  • 25,774
  • 2
  • 58
  • 139
  • Nice! In this case, to use the number 1 from the output {{1,7}} I have to use matchPairs[[1,1]], right? Is it possible to save so that I simply use it as matchPairs[[1]]? – Sigur May 31 '14 at 00:19
  • @Sigur: As I said, just add First@ in front of the Subsets..., and you'll get the first match only, whereby you can address them as desired. – ciao May 31 '14 at 00:37
1
list = {1, 4, 6, 5, 2, 0, 1, 4};

pos = FirstCase[{a_, b_, ___} :> {a, b}] @ PositionIndex @ # &;

pos @ list

{1, 7}

pos @ {0, 0}

{1, 2}

pos @ {1, 3, 3, 3, 3} 

{2, 3}

eldo
  • 67,911
  • 5
  • 60
  • 168
1

Using Catch, Throw and Do:

r = {1, 4, 6, 5, 2, 0, 1, 4};

Catch[Do[Do[If[#[[i]] === #[[j]], Throw[{i, j}]];, {j, i + 1, Length[#]}];, {i, 1, Length[#] - 1}]] &@r

({1, 7})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44