954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

pascal:increasing the array

given a sequence of n elements.increase it by putting after every element the same.for example when you have 1,2,3 the you must increase it by getting 1,1,2,2,3,3.how are i do that using a single array?

kundalish
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

You can just write a[i] two times, here it is.

var
a: array of integer;n, i: integer;

begin
readln(n);
a := new integer[n + 1];
for i := 1 to n do
read(a[i]);
for i := 1 to n do
write(a[i], ' ', a[i], ' ');
end.

Dmitry_Zorin
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 
VAR
  a : ARRAY OF INTEGER;
  x : INTEGER;
BEGIN
  SetLength(a,3); // This dynamically set the size of array to 3.
  a[0]:=1;
  a[1]:=2;
  a[2]:=3; // Now the given values are set. Now to resize.
  SetLength(a,6);// This resizes the array.
  x:=3;
  REPEAT
    a[x*2-1]:=a[x-1];
    a[x*2-2]:=a[x-1];
    DEC(x);
  UNTIL x=0;
END.


This code should do the trick in your array without the need of a temporary array for storage.
If you do not actually know the size of the array, then you can use the command HIGH

VAR
  a : ARRAY OF INTEGER;
  x : INTEGER;
  aSize : INTEGER;
BEGIN
  SetLength(a,3); // This dynamically set the size of array to 3.
  a[0]:=1;
  a[1]:=2;
  a[2]:=3; // Now the given values are set. Now to resize.
  aSize:=HIGH(a);
  SetLength(a,aSize*2);// This resizes the array to the double size.
  x:=aSize; // We must start at bottom of existing data in array.
  REPEAT
    a[x*2-1]:=a[x-1];// The data is then copied from middle and up of new array
    a[x*2-2]:=a[x-1];// to the bottom and up of new array. This line writes copy 2 of data.
    DEC(x);
  UNTIL x=0;
END.


I did not actually test this code, but I think everything is as it should be.
Best regards.

Morten Brendefu
Light Poster
44 posts since Mar 2011
Reputation Points: 38
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You