Created
          August 2, 2012 04:20 
        
      - 
      
- 
        Save mikehoward/3233464 to your computer and use it in GitHub Desktop. 
    Response to Array Iteration Interview Prob
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | def add1(arr, val, n) | |
| return arr.map { |x| x == val ? x + 1 : x } if n == 0 | |
| lim = arr.length | |
| if n > 0 | |
| return arr.map { |x| x == val ? x + 1 : x } if n >= lim | |
| idx = 0 | |
| while idx < lim do | |
| if arr[idx] == val | |
| arr[idx] += 1 | |
| n -= 1 | |
| return arr if n <= 0 | |
| end | |
| idx += 1 | |
| end | |
| else | |
| return arr.map { |x| x == val ? x + 1 : x } if -n >= lim | |
| idx = lim - 1 | |
| while idx >= 0 do | |
| if arr[idx] == val | |
| arr[idx] += 1 | |
| n += 1 | |
| return arr if n >= 0 | |
| end | |
| idx -= 1 | |
| end | |
| end | |
| return arr | |
| end | |
| [ | |
| [[1,4,1,5,1], 1, 0, [2,4,2,5,2]], | |
| [[1,4,1,5,1], 1, 2, [2,4,2,5,1]], | |
| [[1,4,1,5,1], 1, -2, [1,4,2,5,2]], | |
| ].each do |tmp| | |
| arr, val, n, ans = tmp | |
| result = add1 arr, val, n | |
| puts "arr1(#{arr}) == #{result}: #{ans == result ? "OK" : "NG"}" | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment