TransWikia.com

Find equal elements on a list

Mathematica Asked by Sigur on April 11, 2021

Consider the following code to produce the sequence $x_1,ldots,x_{n+1}$ where $x_i=11cdots1$ ($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]]).

2 Answers

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} *)

Correct answer by kglr on April 11, 2021

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

Answered by ciao on April 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP