Question

array initialization in O(1)

Asked by: adsl_teo

Is there any way that I can initialize, say an int array of size 100 to all 1 in O(1) time?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-09-19 at 01:51:08ID20743244
Tags

array

,

initialization

Topic

Miscellaneous Programming

Participating Experts
7
Points
100
Comments
24

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Array Size
    hi, how big an array can i declare? (Background: using win2k, programming in C, using the gcc compiler) I am doing some work in mpeg2 decoding and need large arrays when i declare something like uint32_t Picture_Data_RedTile[800][800]; uint32_t Picture_Data_Blu...
  2. How to compare int array?
    I have three int arrays as follow: int array1[5]={1,2,3,4,5}; int array2[5]={1,2,3,4,5}; int array3[5]={1,2,0,4,5}; Except comparing them one element by one element, What's the best and fast way to compare them, to prove if they are same?
  3. O-notation problem
    { int*a, i; /*initialization*/ a = (int *) malloc ( 100 * sizeof(int)); for (i=0; i<100; i++) a = 0; a[30] = 200; /*assignment*/ printf(“%d”, a[20]); /*reading*/ } For the code above, how can I make the initialization part to be done in O(1) in...
  4. Array size
    Hi, I have an array like long *x for which memory is allocated thru malloc. Depending on requirement the size will be increased using realloc. At some later stage I need to check if a particular number is present in the array. How can I get the number of elements present in...
  5. int pointer to char array
    How do I create an int pointer to an array of chars; Something like this: char test [] = "hello"; int * ptr1 = &test[0]; Basically the first charater of test. Then I want to be able to say ptr = ptr + 2 and ptr would then point to l. Thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: stsanzPosted on 2003-09-19 at 02:03:29ID: 9392034

By definition, the memory architecture of computers leads to O(n) when initializing array of size n.
No bypass.

But you can optimize the process, by accessing the memory in blocks of machine word size.
For example, in C, memset standard function is optimized this way.

What language do you use?

 

by: chikucoderPosted on 2003-09-19 at 02:42:45ID: 9392198

Thats impossible.
It will be possible if the processor is 100*sizeof(int) bit.
But unfortunately - as far as i know we have only till 128 bit processors.

 

by: NeutronPosted on 2003-09-19 at 03:31:16ID: 9392401

...if it is an array of 100 pointers pointing all to the same location... :-)

Greetings,
    </ntr> :)

 

by: chikucoderPosted on 2003-09-19 at 03:51:14ID: 9392490

hi Neutron

nice thinking!!!!

 

by: VGRPosted on 2003-09-19 at 04:08:17ID: 9392554

"we have only till 128 bit processors. "

completely wrong

cellular computers
artificial neuronal networks
some more standard parallel machines
examples :
http://www.freenetpages.co.uk/hp/tgclarkson/pram-data.pdf
http://www.cs.nmsu.edu/~pfeiffer/classes/573/sem/s03/presentations/STARAN2.ppt

plus :
DIVA wideWord processor
"The combination of the execution control unit and
WideWord datapath is regarded as the WideWord
Processor. This component enables superword-level
parallelism [11] on wide words of 256 bits[...]"
http://www.isi.edu/~draper/papers/esscirc02.pdf
http://www.globaltechnoscan.com/8thAug-14thAug02/memory.htm

and
the Ax36 Video DSP uses a VLIW of 256 bits
http://www.omdi.com/download/competitive_analysis_Oct99.pdf

and
I avoided to mention the existing 256 bits graphics chips :D

 

by: chikucoderPosted on 2003-09-19 at 04:49:51ID: 9392739

VGR
>>we have only till 128 bit processors. "
>>completely wrong
Thaks for that update!!!



 

by: chikucoderPosted on 2003-09-19 at 04:51:33ID: 9392746

But even if we have 256 bit processor, the question still remains impossible.

 

by: grg99Posted on 2003-09-19 at 06:19:49ID: 9393235

Is it "possible"?      A rather dopey question if you ask me.

I suspect the question writer meant "using typical CPU instructions", and the answer is NO.

That's because most computers have a limited path to memory, which means that they can only
send results to memory in N bytes at once, where N is typically 1,2,4,8, or 16.  I don't know
of any computer with a 100-byte path to memory, so initializing big arrays has to be done serially
in time, which results in a O(n) process.

BUT there are many other things hooked up to memory that may be capable of doing this:

(a) There may be a DMA controller chip, that if you tell it "DMA 100 words from nonexistent device XX",
it will dump 100 words of zeroes into your array.  This usually happens in O(1) time, i.e. it doesnt take any more CPU
time to ask for 200 word transfer than it does for 100 words.

(b)  There may be a graphics engine around (most VGA cards made in the last 5 years have one) which can do this in O(1).

(c)  There may be a cache-controller chip that can do this in O(1), plus it can do fancy things, impossible fromt he CPU side,  like address a whole row or column at once.

(d)  There may be a CPU helper chip, like a AMD "Nortbridge" or "Southbridge", which can do really low-level memory tricks, such as turn off the power or refresh strobes to the memory chips, effectively initializing the whole SIMM at once.

(e)  Most any other peripheral card that can become a bus-master, such as some sound cards, most USB or firewire cards,
most SCSI cards, they can potentially do a O(1) memory zap.

(f)  Some virtual memory systems let you say "discard page at address XXXXX", then the memory-mapping hardware can just flip a very few bits and discard (and effectively zero) 4K at a time.

But one suspects the question writer wasnt this clever.. they're just fishing for the usual "No, zeroing memory takes O(n) time." answer.


Regards,


grg99






 

by: brettmjohnsonPosted on 2003-09-19 at 08:25:38ID: 9394141

There is additional discussion on this very same problem here:
http://www-tcsn.experts-exchange.com/Programming/Programming_Languages/C/Q_20739224.html

 

by: ozoPosted on 2003-09-19 at 18:52:06ID: 9397499

#define array_size 100
int array[array_size];

int back[array_size];
int fwd[array_size];
int top= -1;

initialize_array(){
  top = -1;  /* mark array as empty */
}

insert_into_array(int index, int value){
  if( index < 0 || index >= array_size ){
    error("index out of bounds");
  }
  if( 0 <= back[index] && back[index] <= top && fwd[back[index]] == index ){
    /* array[index] contains valid data */
  }else{
    /* array[index] is empty, mark index as valid */
    top+=1;
    fwd[top]=index;
    back[index]=top;
  }
  array[index]=value;
}

int read_from_array(int index){
  if( index < 0 || index >= array_size ){
    error("index out of bounds");
  }
  if( 0 <= back[index] && back[index] < top && fwd[back[index]] == index ){
    /* array[index] contains valid data */
    return(array[index]);
  }else{
    error("no data at that index");
  }
}

 

by: ozoPosted on 2003-09-19 at 19:00:33ID: 9397508

#define array_size 100
int array[array_size];

int back[array_size];
int fwd[array_size];
int top= -1;
int initvalue = 1;

initialize_array(int value){
  top = -1;  /* mark array as all initvalue */
  initvalue = value;
}

insert_into_array(int index, int value){
  if( index < 0 || index >= array_size ){
    error("index out of bounds");
  }
  if( 0 <= back[index] && back[index] <= top && fwd[back[index]] == index ){
    /* array[index] contains valid data */
  }else{
    /* array[index] is empty, mark index as valid */
    top+=1;
    fwd[top]=index;
    back[index]=top;
  }
  array[index]=value;
}

int read_from_array(int index){
  if( index < 0 || index >= array_size ){
    error("index out of bounds");
  }
  if( 0 <= back[index] && back[index] < top && fwd[back[index]] == index ){
    /* array[index] contains valid data */
    return(array[index]);
  }else{
    return initvalue;
  }
}

 

by: VGRPosted on 2003-09-20 at 05:16:20ID: 9398522

grg99 said it all

 

by: brettmjohnsonPosted on 2003-09-20 at 11:04:07ID: 9399449

grg99 says:
> One sneaky way that might SEEM to be O(1) is to declare the array as a static global array.
> static variables are by C's definition, initialized to zero.
>
> But this is done by the startup code in C0.OBJ, and it may be done quickly, but it's still most likely done by
> a loop, so it's going to be O(n).   It's just that it's a HIDDEN loop, but it's still most likely O(n).

You could try a static global array with explicit iniitialization.  That would get initialized at compile
time, rather than load time (note that one of the array elements is not zero):

static int a[100] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 200,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };


 

by: grg99Posted on 2003-09-20 at 18:45:41ID: 9400934

>You could try a static global array with explicit iniitialization.  That would get initialized at compile
>time, rather than load time (note that one of the array elements is not zero):

I forgot that case!

It souinds "free", but actually it's worse than most options, as then the zeroes have to be read from disk, which is going to be a BIGFACTOR * O(n) process,
at least 1,000 times slower than having the CPU zero out memory.  But it's "invisible" as you don't need an explicit loop
in your code.

No free lunch here either.


Sorry,

grg99

 

by: brettmjohnsonPosted on 2003-09-20 at 21:48:18ID: 9401398

> It sounds "free", but actually it's worse than most options, as then the zeroes have to be
> read from disk, which is going to be a BIGFACTOR * O(n) process, at least 1,000 times slower
> than having the CPU zero out memory.  

Actually for such a small program, the extra 400 bytes will likely land in the same 4k page as
the rest of the program (or its data at least).  It really doesn't take any longer to read 400
bytes from a file than to read 4 bytes, because the data is read from the file in chunks that
are either sector sized, cluster sized, or VM page sized (depending on the OS).  So you only
have to worry if the initialized data spills into an additional "chunk" (which probably resides
in the drive's 2MB-8MB read-ahead cache anyway).

But even so, all our suggestions just push the work further back in the timeline.  It still has
to be done some time.  Although doing the work at compile time amortizes its impact across
all future runs.


 

by: grg99Posted on 2003-09-21 at 08:09:26ID: 9402521

>Actually for such a small program, the extra 400 bytes will likely land in the same 4k page as
>the rest of the program (or its data at least).

Ah yes, the cat and rat infinite factory.  You can breed an infinite number of cats,
as there's always at least one rat around, and the cats can eat that rat.
If the rats go hungry, just chop up some cats and feed them to the rats.

Well, not quite, you're just hoping the rat won't miss having its tail eaten.  But what about the next cat?

It's still O(n) times a BIG factor.  My hard disk can read zeroes at about 5MB/sec plus about 20msec to get started.  My CPU can
zero memory about 500 times as fast as that, with zero initial delay.  So we're talking about O(n) * 500.  
But you're right, sometimes you'll get the first few cats fed for free.

Regards,

grg99

 

by: NeutronPosted on 2003-09-22 at 02:05:37ID: 9404303

This is not the solution to your problem, but maybe you can still use it somehow:   :-)

-you have a zero-based integer array
int[] numbers

-use element numbers[0] as index multiplicator when accessing array-elements with index>0
 This means that instead of:
      number[index]       to access element at position index>0
you would use
      number[number[0] * index]
or maybe
      number[number[0] & index]

- if you use * operator then assign   number[0]=1
- if you use & bitwise-AND operator then assign number[0]=-1

- when you need to set all values to zero, just assign    number[0]=0
  As a result, all lookups
     number[number[0] * index] == number[0 * index] == number[0] == 0
 also
     number[number[0] & index] == number[0 & index] == number[0] == 0

Convenient, but still useless :-)
...useless because when you wish to assign a non-null value to some array-element, you still have to fill zeros at all positions :-)

Greetings,
    </ntr> :)

 

by: grg99Posted on 2003-09-22 at 09:24:00ID: 9406845

>This is not the solution to your problem, but maybe you can still use it somehow:   :-)


You're darned tootin' it's not a solution!

It's worse than O(n), as every reference to the array is going to incur the quasi-initialized overhead.


(I'm assuming as in most cases each array element is going to be accessed more than once).


 

by: NeutronPosted on 2003-09-22 at 10:15:15ID: 9407196

Of course it is going to incurr overhead, I was not talking about array i/o but about the zeroing operation :-)

Otherwise, it is pointless to discuss array-initialization in O(1) if you are not willing to sacrafice something somewhere.

Personally, I would (if possible at all) redesign the accessing logic, so a hash-map or a linked-list would be used instead of an array, and there you would anyway have to meet the overhead problem, even if initialization would be possible in O(1).

As J.R. said - "Sometimes you've gotta lose to win" :-)       (pardon my bad English)

Greetings,
    </ntr> :)

 

by: ozoPosted on 2003-09-22 at 15:37:57ID: 9409265

You can initialize an array on O(1) incurring only O(1) overhead on all array accesses
http://mmlab.ceid.upatras.gr/dstructures/Array_Initialization.pdf

 

by: ozoPosted on 2004-02-09 at 22:48:32ID: 10319798

I believe I provided the solution required.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...