Problem of the Day
A new programming or logic puzzle every Mon-Fri

Odd Array

Given an integer array, create a function that converts all numbers to odd numbers. If a number is already odd you may leave it. If it is not odd you must add atleast 2 numbers from the array (newly converted ones count) to that number to make it odd. Example:

[1,2,3,4]
1: odd
2: 2 + 4 + 1 = 7
3: odd
4: 4 + 1 + 7 + 3 = 15

EDIT: If the array contains only even numbers return an error.

Permalink: http://problemotd.com/problem/odd-array/

Comments:

  • David - 10 years, 5 months ago

    What if the array contains only even numbers? Return an error, or is there an additional rule?

    reply permalink

  • Max Burstein - 10 years, 5 months ago

    Good point. Returning an error would work.

    reply permalink

  • Anonymous - 10 years, 5 months ago

    haskell solution.. i left out the part, that generates the output.. cause that is kinda boring ;)

    
    oddArray :: [Int] -> [Int]
    oddArray xs = worker xs xs
    
    worker :: [Int] -> [Int] -> [Int]
    worker [] _ = []
    worker (x:xs) ys 
        | odd x = x : (worker xs ys)
        | otherwise = (x + x + findOdd ys) : (worker xs ys)
            where
                findOdd (z:zs) = if odd z then z else findOdd zs
                findOdd [] = error "no odd number"
    

    reply permalink

  • Mike - 10 years, 5 months ago

    What if the array contains 2 evens and an odd number? There is no way to convert the last even number to an odd given that we have to add at least 2 other numbers to the even.

    reply permalink

Content curated by @MaxBurstein