Last active
December 14, 2015 16:29
-
-
Save hiroshi-maybe/5115360 to your computer and use it in GitHub Desktop.
Reinvention of array list.
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
| class MyArrayList | |
| def initialize n | |
| if n<0 then | |
| raise "size should be more than 0"; | |
| end | |
| @size=n | |
| @next_index=0 | |
| @innerArray=Array.new @size | |
| end | |
| def add element | |
| if @next_index>@size-1 then | |
| @size*=2 | |
| extendedAry = Array.new @size | |
| @innerArray.each_with_index do |val,i| | |
| extendedAry[i]=val | |
| end | |
| @innerArray=extendedAry | |
| end | |
| @innerArray[@next_index]=element | |
| @next_index+=1 | |
| end | |
| def get n | |
| if n>=@next_index then | |
| return nil | |
| else | |
| return @innerArray[n] | |
| end | |
| end | |
| def to_s | |
| result = "" | |
| result+="current:"+@next_index.to_s | |
| result+=", size:"[email protected]_s | |
| result+=", "[email protected]_s | |
| return result | |
| end | |
| end | |
| list = MyArrayList.new 2 | |
| 17.times do |i| | |
| list.add i | |
| end | |
| p list.to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment