Algorithms: Array Parity

 

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this “outlier” N.

[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)

GO

package main

import (
	"fmt"
)

func find_outlier(integers []int32) int32 {
      test_result := integers[0] % 2 + integers[1] % 2 + integers[2] % 2;
      var expected_result int32 = 1
      if test_result <= 1{
         expected_result = 0
      }
      for _, value := range(integers) {
           if  value % 2 != expected_result {
               return value
           }
      }
      return -1
}
func main() {
	fmt.Println(find_outlier([]int32{4,6,7,10}))
	fmt.Println(find_outlier([]int32{160, 3, 1719, 19, 11, 13, -21}))
}

PYTHON

def find_outlier(integers):
    test_bed = sum([integers[0] % 2,integers[1] % 2,integers[1] % 2])
    if test_bed <= 1:
        base_result = 0 #series is mostly even
    else:
         base_result = 1 
    for i in integers:
      if i % 2 != base_result:
         return i
    return None

RUST

 #![allow(unused)] fn find_outlier(integers: &[i32]) -> i32{
    let test_bed: i32 = integers[0] % 2 + integers[1] % 2 + integers[1] % 2;
    let mut expected_result: i32 = 1;
    if test_bed <= 1{
        expected_result = 0;
    }
    for i in integers.iter(){
        if *i != expected_result{
            return *i
        }
    }
    return -1
}
fn main() {
  assert_eq!(find_outlier(&[160, 3, 1719, 19, 11, 13, -21]),160);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s