Common list elements

From Rosetta Code
Revision as of 09:31, 24 February 2021 by rosettacode>Gerard Schildberger (→‎{{header|REXX}}: added a comment.)
Common list elements is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Given an integer array nums, find the common list elements.

For example:
nums = [2,5,1,3,8,9,4,6], [3,5,6,2,9,8,4], [1,3,7,6,9]
output = [3,6,9]

REXX

<lang rexx>/*REXX program finds and displays the common list elements from a collection of sets. */ parse arg a /*obtain optional arguments from the CL*/ if a= | a="," then a= '[2,5,1,3,8,9,4,6] [3,5,6,2,9,8,4] [1,3,7,6,9]' /*defaults.*/

  1. = words(a) /*the number of sets that are specified*/
           do j=1  for #                        /*process each set  in  a list of sets.*/
           @.j= translate( word(a, j), ,'],[')  /*extract   a   "  from "   "   "   "  */
           end   /*j*/

$= /*the list of common elements (so far).*/

  do k=1  for #-1                               /*use the last set as the base compare.*/
     do c=1  for words(@.#);  x= word(@.#, c)   /*obtain an element from a set.        */
        do f=1  for #-1                         /*verify that the element is in the set*/
        if wordpos(x, @.f)==0  then iterate c   /*Is in the set?  No, then skip element*/
        end   /*f*/
     if wordpos(x, $)==0  then $= $ x           /*Not already in the set?  Add common. */
     end      /*c*/
  end         /*k*/
                                                /*stick a fork in it,  we're all done. */

say 'the list of common elements in all sets: ' "["translate(space($), ',', " ")']'</lang>

output   when using the default inputs:
the list of common elements in all sets:  [3,6,9]

Ring

<lang ring> nums = [[2,5,1,3,8,9,4,6],[3,5,6,2,9,8,4],[1,3,7,6,9]] sumNums = [] result = []

for n = 1 to len(nums)

   for m = 1 to len(nums[n])
       add(sumNums,nums[n][m])
   next

next

sumNums = sort(sumNums) for n = len(sumNums) to 2 step -1

   if sumNums[n] = sumNums[n-1]
      del(sumNums,n)
   ok

next

for n = 1 to len(sumNums)

   flag = list(len(nums))
   for m = 1 to len(nums)
       flag[m] = 1
       ind = find(nums[m],sumNums[n])
       if ind < 1
          flag[m] = 0
       ok
   next
   flagn = 1
   for p = 1 to len(nums)
       if flag[p] = 1
          flagn = 1
       else
          flagn = 0
          exit
       ok
   next
   if flagn = 1
      add(result,sumNums[n])
   ok

next

see "common list elements are: " showArray(result)

func showArray(array)

    txt = ""
    see "["
    for n = 1 to len(array)
        txt = txt + array[n] + ","
    next
    txt = left(txt,len(txt)-1)
    txt = txt + "]"
    see txt

</lang>

Output:
common list elements are: [3,6,9]