DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #172 - Find All in an Array

Setup

Implement a function that will accept an array of integers and an integer n. Find all occurrences of n in the given array and return another array containing all the index positions of n in the array.

If n is not in the given array, return an empty array [].

Assume thatn and all values in the array will always be integers.

Example

find_all([6, 9, 3, 4, 3, 82, 11], 3)
> [2, 4]

Tests

[6, 9, 3, 4, 3, 82, 11], 3
[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16
[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20


This challenge comes from MementoMori on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (18)

Collapse
 
savagepixie profile image
SavagePixie

JavaScript

const findAll = (arr, n) => arr
   .reduce((a, b, i) => b === n
      ? a.concat(i)
      : a
   , [])
Collapse
 
kerldev profile image
Kyle Jones

In Python:

def find_all(list, value):
    position = 0
    results = []
    for element in list:
        if element == value:
            results.append(position)
        position += 1
    return results

print(find_all([6, 9, 3, 4, 3, 82, 11], 2))
print(find_all([6, 9, 3, 4, 3, 82, 11], 3))
print(find_all([10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16))
print(find_all([20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20))
print(find_all(["happy", "birthday", "to", "you", "happy", "birthday", "to", "me"], "happy"))
Collapse
 
jessekphillips profile image
Jesse Phillips
// D
pure nothrow @safe
auto findIndex(const(int)[] arr, size_t needle) {
  return arr.enumerate
     .filter!(x => x[1] == needle) 
     .map!(x => x[0])
     //.array
     ;
} unittest {
  assert(findIndex([6, 9, 3, 4, 3, 82, 11], 3).equal([2, 4]));
} 

The commented out array line would allocate a new array to meet the specification.

Collapse
 
avalander profile image
Avalander • Edited

Haskell

Written on the phone, it might not work, I'll check it when I get home.

find_all :: [Int] -> Int -> [Int]
find_all xs n =
  [ snd x | x <- indexed if (fst x) == n ]
  where
    indexed = zip xs [0..(length xs)]
Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell:

import Data.List (findIndices) 

findAll :: Eq a => a -> [a] -> [Int]
findAll x = findIndices (==x) 

or alternatively,

findAll :: Eq a => a -> [a] -> [Int]
findAll x = map fst . filter ((==x) . snd) . zip [0..]
Collapse
 
exts profile image
Lamonte • Edited

In Dart:

void main() {
  print(findAll([6, 9, 3, 4, 3, 82, 11], 3));
  print(findAll([10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16));
  print(findAll([20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20));
}

List<int> findAll(List<int> items, int find) {
  var found = List<int>();
  for(var idx = 0; idx < items.length; idx++) {
    if(items[idx] == find) {
      found.add(idx);
    }
  }
  return found;
}

// alternative approach, which cuts it down maybe a line? lol
List<int> findAll2(List<int> items, int find) {
  var found = List<int>();
  items.asMap().forEach((idx,value){
    if(value == find)
      found.add(idx);
  });
  return found;
}

dartpad.dev/

Collapse
 
ciarant profile image
Ciaran Treanor • Edited

Rust:

fn find_all(numbers: Vec<usize>, value: usize) -> Vec<usize> {
    numbers.iter()
        .enumerate()
        .filter(|&(_, val)| *val == value)
        .map(|(index, _)| index)
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test1() {
        assert_eq!(vec![2, 4], find_all(vec![6, 9, 3, 4, 3, 82, 1], 3));
        assert_eq!(vec![1,9], find_all(vec![10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16));
        assert_eq!(vec![0,1,8], find_all(vec![20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20));
    }
}
Collapse
 
aminnairi profile image
Amin

Elm

import List exposing (indexedMap, filter, map)
import Tuple exposing (pair, second, first)


findAll : List Int -> Int -> List Int
findAll integers integer =
    indexedMap pair integers
        |> filter (second >> (==) integer)
        |> map first

Implementation.

Collapse
 
ryanbeckett profile image
Ryan Beckett • Edited

Swift:

func findOccurances(of numberToFind: Int, in listOfNumbers: [Int]) -> [Int] {
    return listOfNumbers.enumerated().compactMap { (index, number) in
        number == numberToFind ? index : nil
    }
}
Collapse
 
miteshkamat27 profile image
Mitesh Kamat

In JavaScript:
function find_all1(arr, n){
let arr1 = [];
arr.forEach((item,index) => {
item === n ? arr1.push(index): null;
});
console.log(arr1);
}

find_all1([6,9,3,4,3,82,11],3);

Collapse
 
cipharius profile image
Valts Liepiņš

Ruby

def findAll xs, x
    xs.filter_map.with_index {|y, i| i if x == y}
end
Collapse
 
madza profile image
Madza • Edited

js

find_all = (arr,n) => {
  res = [];
  for([pos, val] of arr.entries()){
    if(val===n) res.push(pos);
  }
  return res;
}
Collapse
 
ntvinhit profile image
Nguyễn Trọng Vĩnh
const findAll = (array, n) => array.reduce((prev, next, index) => next === n ? [...prev, index] : prev, []);
Collapse
 
eth2234 profile image
Ebrahim Hasan

PHP


<?php function find_all($array,$number){
return array_keys($array,$number);

}
var_dump(find_all(array(6, 9, 3, 4, 3, 82, 11), 3) );