Differences

This shows you the differences between two versions of the page.

Link to this comparison view

rubyfindmissinginarray [2014/10/26 01:52] (current)
Line 1: Line 1:
 +===== Find missing number in an array =====
 +
 +   1 Generate an array and populate with random numbers berween 1..MAX_SIZE
 +
 +<code ruby>
 +MAX_SIZE = 50
 +
 +# ===== functions and classes =====
 +def generateRandom(maxValue)
 +    return rand(maxValue)
 +end
 +
 +class Distrib
 +    attr_accessor :values, :freq, :​missingList
 +    def initialize(n)
 +        @values = Array.new(n)
 +        @freq = Array.new(n)
 +        @missingList = Array.new
 +        (0...n).each { |index|
 +            @values[index] = 0
 +            @freq[index] = 0
 +        }
 +    end
 +
 +    def push(n)
 +        if (@values.include?​(n)) then
 +            @freq[n] = @freq[n].succ
 +        else
 +            @values[n] = n
 +            @freq[n] = 1
 +        end
 +    end
 +
 +    def missing(n)
 +        isMissing = 0
 +        @missingList.clear
 +        (0..n).each { |index|
 +            if (@freq[index] == 0) then
 +                isMissing = isMissing.succ
 +                missingList.push(index)
 +            end
 +        }
 +        return isMissing
 +    end
 +
 +    def print
 +        (0..MAX_SIZE).each { |index|
 +            puts "#​{index} : #​{@values[index]} (#​{freq[index]})"​
 +        }
 +    end
 +end
 +# ===== main =====
 +myDistrib = Distrib.new(MAX_SIZE)
 +
 +(0...5*MAX_SIZE).each { |x|
 +    value = rand(MAX_SIZE)
 +    puts "​rand(#​{x}) = #{value} "
 +    myDistrib.push(value)
 +}
 +
 +puts "​After:"​
 +myDistrib.print
 +
 +puts "​Missing:"​
 +puts myDistrib.missing(MAX_SIZE)
 +
 +if (myDistrib.missingList.size > 0) then
 +puts "​Missing index'​s"​
 +mList = myDistrib.missingList
 +    mList.each { |index|
 +        puts index
 +    }
 +end
 +</​code>​
  
rubyfindmissinginarray.txt ยท Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0