2 ms·
another double reverse... I guess coffeescript really does want to be ruby :)
by jazzychad 14y ago
another double reverse... I guess coffeescript really does want to be ruby :)
- azylman 14y agoThere was only two ways I could think of to do this without the double reverse. One would introduce more complex branches (looping backwards in CoffeeScript ain't easy) and the other would be using Underscore.js's range function to do the same thing - that solution would be basically identical to this, except without the reverses, only I'd consider that cheating.
- azylman 14y agoHere's my cheating version that uses a third-party library: add1_cheating = (arr, val, n) -> n = arr.length if n is 0 start = if n < 0 then arr.length else 0 end = if n < 0 then 0 else arr.length step = n/(Math.abs n) n = Math.abs n count = 0 for i in _.range start, end, step break if count > n arr[i]++ if arr[i] is val count++ return arr
- radagaisus 14y agoPeople are just lazy since it usually doesn't matter. array[i]++ for i in [-1..-array.length]
- cezary 14y agoHere's my version without using reverse or underscore. If coffeescript supported reverse loops or negative indices, this would be a lot cleaner. add1 = (arr, val, n)-> d = Math.abs(n||1)/(n||1) n = if n is 0 then arr.length else Math.abs n i = if d < 0 then arr.length - 1 else 0 end = if d < 0 then 0 else arr.length while n and i isnt end num = arr[i] if num is val n-- arr[i]++ i = i + d arr