There is an out-by-one error in the logic somewhere that I cannot find right now, but otherwise, I think this complies with the rules of the challenge.

#! perl -slw use strict; local $, = ' '; my( $A, $C, @B ) = ( undef, 0 ); open SPARSE, '+> :raw', \$A; sub readA{ seek SPARSE, 4 * $_[ 0 ], 0; sysread SPARSE, my $n, 4; unpack 'N', $n; } sub writeA{ seek SPARSE, 4 * $_[ 0 ], 0; syswrite SPARSE, pack( 'N', $_[ 1 ] ), 4; } sub query{ my $i = shift; my $a = readA( $i ) || -1; return 0 unless 0 <= $a and $a < $C; my $b = $B[ $a ]; return $b == $i ? 1 : 0; } sub insert{ my $i = shift; if( !query( $i ) ) { $B[ $C ] = $i; writeA( $i, $C ); $C++ } } sub del{ my $i = shift; if( query( $i ) ) { my $a = readA( $i ); my $b = $B[ --$C ]; $B[ $a ] = $b; writeA( $b, $a ); } } sub clear{ $C = 0; } my @numbers = map{ int rand( 2**16 ) } 1 .. 10; print 'Query before insert'; printf "%5d : %s\n", $_, query( $_ ) for @numbers; insert $_ for @numbers; print "\nQuery after insert"; printf "%5d : %s\n", $_, query( $_ ) for @numbers; del $_ for @numbers[ 0..4 ]; ## Delete half print "\nQuery after deleting half"; printf "%5d : %s\n", $_, query( $_ ) for @numbers; del $_ for @numbers; ## Delete them all regardless if they still exist +s print "\nQuery after deleting the rest"; printf "%5d : %s\n", $_, query( $_ ) for @numbers;

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

In reply to Re: Data structure challenge by BrowserUk
in thread Data structure challenge by Abigail-II

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.