1
$\begingroup$

I have a list "d" that looks like this:

d={{{1,4},{1,1},{1,2}},
{{1,4}},{1,1},{3,3}}}

I also have the following code:

For[b = 1, b <= MaxIt, b++, {
  w = Table[
     If[
      d[[b, l]][[1]] == d[[b, l]][[2]],
      Print["Same"],
      Unevaluated@Sequence[]],
     {l, 1, Length[d[[b]]]}];
  }]

List "d" is composed of two generations, each row makes up a single generation. When I run the above loop, I get printed outputs of the word "Same" every time the two numbers in a sublist are the same. The issue is I cannot tell which "Same" refers to which generation. Is there any way to keep my printed words in list form so that they would read {{Same},{Same,Same}}(as in the case above, generation 1 only has 1 same and generation 2 has two sames.

$\endgroup$

1 Answer 1

1
$\begingroup$
d = {{{1, 4}, {1, 1}, {1, 2}}, {{1, 4}, {1, 1}, {3, 3}}};

You can Apply the function SameQ at Level 2 to get the result without a loop:

Apply[SameQ, d, {2}]
{{False, True, False}, {False, True, True}}

You can process this list using ReplaceAll to replace False with Nothing and True with "Same":

Apply[SameQ, d, {2}] /. {False -> Nothing, True -> "Same"}
 {{"Same"}, {"Same", "Same"}}
$\endgroup$
5
  • $\begingroup$ Thank you for showing me that. I hate to be a bother but is it still possible to do it the way I had done it above? Although I can use the new method you showed me for one part of what I'm doing, I have a section of code that's a little more complicated and is sort of "stuck" in the form similar to what I had shown above. Would you happen to know of a way to do that? $\endgroup$
    – D'Angelo
    Apr 21, 2020 at 6:59
  • $\begingroup$ @D'Angelo, try w = {}; For[b = 1, b <= Length@d, b++, AppendTo[w, Table[If[d[[b, l]][[1]] == d[[b, l]][[2]], "Same", Unevaluated@Sequence[]], {l, 1, Length[d[[b]]]}]]]; w? $\endgroup$
    – kglr
    Apr 21, 2020 at 7:39
  • $\begingroup$ There's an error saying that Part specification 1[[1]] is longer than depth of object $\endgroup$
    – D'Angelo
    Apr 21, 2020 at 8:40
  • $\begingroup$ @D'Angelo, try d = {{{1, 4}, {1, 1}, {1, 2}}, {{1, 4}, {1, 1}, {3, 3}}}; as input (d in your post has a typo.). $\endgroup$
    – kglr
    Apr 21, 2020 at 8:42
  • $\begingroup$ That fixed it, thank you so much $\endgroup$
    – D'Angelo
    Apr 21, 2020 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.