loading...

Daily Challenge #172 - Find All in an Array

thepracticaldev profile image dev.to staff ・1 min read

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!

Posted on by:

thepracticaldev profile

dev.to staff

@thepracticaldev

The hardworking team behind dev.to ❤️

Discussion

pic
Editor guide
 

JavaScript

const findAll = (arr, n) => arr
   .reduce((a, b, i) => b === n
      ? a.concat(i)
      : a
   , [])
 

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"))
 

I made an alternative Python version with a list comprehension:

def find_all(list, value):
    return [ i for i, n in enumerate(list) if n == value ]
 

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)]
 

I find it slightly more idiomatic to write indexed with an infinite list as second argument, since zip will only consume length xs elements from the second list anyway:

indexed = zip xs [0..]
 
// 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.

 

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

F#, list functions:

let findAll xs n =
    xs
    |> List.indexed
    |> List.fold (fun result (i, x) ->
        if x = n then i :: result else result) []
    |> List.rev

Alternative version with a list comprehension:

let findAll xs n =
    [ for i in 0 .. List.length xs - 1 do
        if xs.[i] = n then yield i ]

Unit tests:

module DailyChallengeTests

open FsUnit.Xunit
open Xunit
open DailyChallenge

[<Fact>]
let ``provided test case 1``() =
    findAll [ 6; 9; 3; 4; 3; 82; 11 ] 3 |> should equal [ 2; 4 ]

[<Fact>]
let ``provided test case 2``() =
    findAll [ 10; 16; 20; 6; 14; 11; 20; 2; 17; 16; 14 ] 16
    |> should equal [ 1; 9 ]

[<Fact>]
let ``provided test case 3``() =
    findAll
        [ 20; 20; 10; 13; 15; 2; 7; 2; 20; 3; 18; 2; 3; 2; 16; 10; 9; 9; 7; 5; 15; 5 ]
        20 |> should equal [ 0; 1; 8 ]

[<Fact>]
let ``the element can't be found``() =
    findAll [ 1; 2; 3 ] 4 |> should be Empty

[<Fact>]
let ``the input array is empty``() = findAll [] 1 |> should be Empty
 

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/

 

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

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.

 

Swift:

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

I made a ReasonML version too:

let findAll = (xs, n) =>
  List.filter_mapi(xs, (i, x) =>
    if (x == n) {
      Some(i);
    } else {
      None;
    }
  );

Since things can get confusing in ReasonML-land, this is Reason Native, not Bucklescript, so it's using Base as standard library.

 

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);

 
const findAll = (array, n) => array.reduce((prev, next, index) => next === n ? [...prev, index] : prev, []);
 

js

find_all = (arr,n) => {
  res = [];
  for([pos, val] of arr.entries()){
    if(val===n) res.push(pos);
  }
  return res;
}
 

Ruby

def findAll xs, x
    xs.filter_map.with_index {|y, i| i if x == y}
end
 

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) );