Insertion and deletion in an array. Using Free Pascal to Process Arrays


To use preview presentations create yourself an account ( account) Google and log in: https://accounts.google.com


Slide captions:

One-Dimensional Arrays Inserting and Removing an Element

Inserting and deleting elements Algorithm for deleting an element: determine the number of the element to be deleted - k (enter from the keyboard or find from some conditions) shift all elements starting from the kth by 1 element to the left assign the value 0 to the last element of the array When deleting an element, the size of the array is not is changing! Therefore, it is necessary to indicate further in the program not up to n, but up to n -1.

The element to be deleted is given by array A: 3 5 6 8 12 15 17 18 20 25 k:=4 3 5 6 12 15 17 18 20 25 25 3 5 6 12 15 17 18 20 25 0

const n= 30; var a: array of integer; k, i: integer; begin (array input and k ) ... for i:= k to n-1 do a[i] := a; a[n] := 0; writeln( Result: ); for i:= 1 to n-1 do write (a[i] :3); readln; end.

Algorithm for inserting an element: (after the kth) the first k elements remain unchanged, all elements starting from the kth are shifted 1 position back to the place of the (k +1)th element, we write new element. An array of n elements into which k elements are inserted must be defined as an array of size n + k. Inserting before an element differs only in that all elements are shifted, starting from the k-th one, and a new one is written in place of the k-th one.

given array A: k:=4 3 5 6 8 8 12 15 17 18 20 25 3 5 6 8 100 12 15 17 18 20 25 1 2 3 4 5 6 7 8 9 10 3 5 6 8 12 15 17 18 20 25 position to add a new element

Example: Insert 100 after the element whose number is entered from the keyboard: const n= 30; var a: array of integer; k, i: integer; begin (array input and k) ... for i:= n downto k+1 do a := a[i]; a := 100; writeln( Result: ); for i:= 1 to n+1 do write (a[i] :3); readln; end.


On the topic: methodological developments, presentations and notes

“One-dimensional arrays: solving problems involving adding and removing an element”

Lesson summary developed for 10th grade language learners Pascal programming. The summary explains in detail with examples how you can add and remove elements in a one-dimensional ma...

Summary of a lesson in computer science on the topic: Text input technology. Text editing: inserting, deleting and replacing characters; inserting and deleting blank lines. Purpose of the lesson: to teach technology...

Lesson outline diagram “One-dimensional arrays. Input and output of a one-dimensional array"

Subject “Informatics” Class 9 Lesson topic “One-dimensional arrays. Input and output of a one-dimensional array"Lesson type: combinedEquipment: computer...

Working with elements of a one-dimensional array

The purpose of the lesson: to form and develop subject and key competencies; expand the understanding of the area of ​​application of one-dimensional arrays; improve the culture of writing programs; instill structuring skills...

Lesson from the series: “Programming in Pascal”
Let's continue to get acquainted with processing algorithms one-dimensional arrays. Today we will look at algorithms for inserting elements into an array. As in algorithms with the removal of elements, we will distinguish between two cases: insertion of a single element and insertion of several elements. The algorithms are different.

Inserting a single element

You can insert an element before or after of this element, the number of this element can be entered from the keyboard or searched under certain conditions.
Let's consider inserting an element after an element with a given number; we will enter the number of this element from the keyboard.

Let's consider a simple problem.

Example 1. In an array consisting of n elements, insert the number b after the k-th element.

Solution

Let's look at specific example. Let the following one-dimensional array of 10 (n = 10) elements be given:
3, -12, 5, 14, 27, -6, 1, -34, 10, -15.

Insert the number 100 after the 5th element (b=100, k = 5)

Algorithm for inserting an element into an array:

  1. The first 5 elements of the array remain unchanged.
  2. Move all elements, starting from the sixth, back one. But in order not to lose the neighboring value, we will start the shift from the last element - first shift the tenth one to the right, then the ninth, eighth, etc. until the sixth (m:=m[i], i=n..k).
  3. In place of the sixth element we write the value 100, that is, after the 5th element of the array (m:=b;).

We get the following array:

3, -12, 5, 14, 27, 100, -6, 1, -34, 10, -15.

Thus, the array now has 11 elements, that is, the array must be defined with N+1 elements:

Type myarray = Array Of Integer.

Let's compose now new procedure Insert1 (k1, x1, m), to which are transmitted: k 1– number of the element after which to insert, x1– the number we are inserting, m– an array in which we perform transformations.

Let's compose the main program using the new procedure Insert1 (k1, x1, m).

We looked at the algorithm for inserting one element into an array. Let's consider the following case.

Inserting Multiple Elements

Let's assume that you need to insert not just one element into the array, but one element at a time after all elements with a given property. Let's consider the following problem.

Example 2. Insert a number after all array elements that are multiples of 3.

The first thing you need to pay attention to is the description of the array: how many elements can the array grow by?

The maximum number of elements after which a new element can be inserted is the same as the number of elements in the array. Because it may happen that all elements of the array correspond to a given property. Therefore, the array can double in size (this is its largest dimension), which means that the corresponding description will be as follows:
Type myarray = Array Of Integer;

Second. If we look through the elements of the array from the beginning and insert a new one after the element with a given property, then the next element to look through will be the new (inserted) element and will need to be skipped (“jumped over”). Therefore, the solution will not be very effective.
Therefore, it is best to view the array starting from the end, then the inserted element will not interfere. In this case, the viewing will be sequential from the Nth to the 1st.

The last thing to note is that the number of the last element will change after each insertion. It will need to be redefined. To do this, you need to count the number of inserted elements at the moment.

To insert several elements into an array, let's create a new procedure Insert2 (k1, x1, m), in which the number of inserted elements will be counted and the number of the last element will be adjusted.
The number of the last element is necessary in order to know how many elements need to be shifted when making room for a new element, since the number of elements in this part of the array increases.
Below is the text of the procedure, taking into account the changes. Let's leave the parameters of the procedure the same.

Now you can write program code main program. It will be as follows:

You have become familiar with algorithms for inserting elements into a one-dimensional array. In the next lesson we will look at algorithms for sorting one-dimensional arrays.

When you need to make some changes to the array, JavaScript method splice can come to the rescue. It allows you to insert, delete and replace elements in JavaScript array.

Let's look at the arguments passed to the splice() method.

Array.splice(start_index, number_of_elements_to_remove):

  • start_index — index in the array from which insertion or deletion of elements begins;
  • number_of_elements_to_remove - specifies the number of elements to remove, starting with star_index .

All elements following number_of_elements_to_remove will be inserted into the array starting at start_index . They can be of any type, including strings, numbers, booleans, objects, functions, NULL, undefined, etc.

For more detailed study method parameters Array.prototype.splice() Javascript use MDN.

Let's start with simple example demonstrating how to insert a number into an array using the Array.splice() method.

Imagine we have an array and we want to insert 2 between 1 and 3 into it. Example implementation:

var my_array = ; var start_index = 1; var number_of_elements_to_remove = 0; my_array.splice(start_index, number_of_elements_to_remove, 2); console.log(my_array); //;

Note that JavaScript array splice operates directly on the array. So the my_array method called splace() instead of returning new array, will update my_array .

Example of removing an element from an array in JavaScript:

var my_array = ["a","b","c","k","d"]; var start_index = 3 var number_of_elements_to_remove = 1; var removed_elements = my_array.splice(start_index, number_of_elements_to_remove); console.log(removed_elements); //["k"] console.log(my_array); //["a","b","c","d"];

Note that in this example, the Array.splice() method returns an array of the removed elements.

Let's take a look at an example of replacing elements in a JavaScript array using the JavaScript splice method:

var my_array = ["baseball", "basketball", "tennis", "golf"]; var start_index = 1 var number_of_elements_to_remove = 2; var removed_elements = my_array.splice(start_index, number_of_elements_to_remove, "boxing", "bowling", "volleyball"); console.log(removed_elements); //["tennis", "golf"] console.log(my_array); //["baseball", "boxing", "bowling", "volleyball", "golf"];

The above example replaces "basketball" and "tennis" with "boxing", "bowling" and "volleyball". It may seem a little confusing due to all the operations involved. Let's look at all the operations step by step. First, we tell the splace() method the starting position of my_array . Then number_of_elements_to_remove is set to 2, so the method removes both my_array and my_array . And finally, starting from start_index my_array , we insert elements into the my_array array.

The JavaScript splace method is good when you need to insert or remove values ​​from an array t . If the array is already sorted, the splace() method is suitable to explicitly place new values ​​into the array. It also works well when you need to remove values ​​from an array by index. Note that the splace() method acts directly on the array and returns only those values ​​that were removed or cut from the array.

Translation of the article “ Insert, Remove, and Replace elements with Array.splice()” was prepared by the friendly project team.

Good bad

end; (for i)

Inserting and removing an element into an array

Let's consider the algorithm for inserting an element into an array. For simplicity, we will consider only one-dimensional arrays. The array consists of a certain number of elements nmax (capacity

array). The current number of array elements is in the variable n.

Before inserting the next element, we check that the current number of array elements is less than its capacity.

Next, we check whether the element is inserted at the end of the array or not. If an element is inserted at the end of the array, then increase n by one and add the element. Otherwise, we shift the array elements whose index is greater than or equal to the index of the inserted element, Figure 3.

The above algorithm is implemented in the program shown in Listing 6.

Listing 6 – Inserting an element into an array

($MODE DELPHI) ($ENDIF)

($APPTYPE CONSOLE) program InsElt;

i :integer;

//Input array

//Element to insert writeln("Vvedite element" ); readln(element);

//Element index

//Insert element

if index< n+1 then begin

inc(n); //increase the length of the array

if (Low(a)<= index) and (index <= n) then for i:=n downto index do

a[i]:=a; //array shift

a:=element; end

//Display array elements on screen for i:=1 to n do

writeln("a[" , i,"]=" , a[i]:6:2);

Removing an element occurs in the same way. First, it checks that the index of the element is within the range of acceptable values, and then shifts the elements so as to cover the element to be removed, Figure 4

Listing 7

($MODE DELPHI) ($ENDIF)

($APPTYPE CONSOLE) program DelElt;

const nmax = 5; //array capacity

i :integer;

writeln("Vvedite chislo elementov massiva"); readln(n);

//Input array

for i:=1 to n do begin write("a[" , i,"]=" ); readln(a[i]);

//Element index

writeln("Vvedite index elementa"); readln(index);

//Removing elements

if index

if (Low(a)<= index) and (index <= n) then for i:=index to n do

a[i]:=a; //array shiftdec(n); //reduce the length of the arrayend

else begin writeln("Invalid index" ); readln;

Theoretical material

Independent work

When declaring an array, we define its maximum dimension, which cannot be changed later. However, using an auxiliary variable, you can control the current number of elements, which cannot be greater than the maximum.

Comment. The System.Collection namespace implements the ArrayList collection - an array that dynamically changes its size. We'll look at it later.

Example. Let's look at a program fragment:

int a=new int ;

for (int i=0; i<5;i++) a[i]:=i*i;

In this case, the array can be represented as follows:

n=5
A

Since during the description an array of 10 elements was defined, and only the first 5 were filled, the remaining elements will be filled with zeros.

What does it mean to remove element number 3 from a one-dimensional array? The deletion should result in element number 3 being physically "destroyed" from the array, and the total number of elements should be reduced. In this understanding of element removal, the resulting array should look like this

In general, if we want to delete an array element with number k (there are n elements in the array, and the last element has index n-1), then we need to shift the elements, starting from k+1, one position to the left. Those. in the kth place put the k+1st element, in the place k+1 - k+2nd element, ..., in the place n-2 - n-1st element. Then decrease the value of n by 1. In this case, the dimension of the array will not change, only the current number of elements will change, and we will get the feeling that element number k has been deleted. Let's look at this algorithm using an example:

namespace ConsoleApplication

static int Input()

int a=new int[n];

for (int i = 0; i< n; ++i)

Console.Write("a[(0)]= ", i);

for (int i = 0; i< n; ++i) Console.Write("{0} ", a[i]);

Console.WriteLine();

static void DeleteArray(int a, ref int n, int m)

for (int i = m; i< n-1; ++i)

static void Main()

int myArray=Input();

int n=myArray.Length;

Print(myArray, n);

Console.WriteLine("Enter the item number to delete:");

DeleteArray(myArray, ref n,m);

Print(myArray, n);

Exercise. Think about what exceptions might occur in a given program and add appropriate exception handling to it.

Let us now consider the deletion operation in a two-dimensional array. The dimension of a two-dimensional array is also fixed at the stage of declaring the array. However, if necessary, you can “simulate” deleting an entire row in an array by shifting all rows, starting with the kth one, up by one. In this case, the array size will not change, and the current number of rows will be reduced by one. As an example, let's remove line number k from a two-dimensional array.

namespace ConsoleApplication

Console.WriteLine("enter array dimension");

Console.Write("n = ");

n=int.Parse(Console.ReadLine());

Console.Write("m = ");

m=int.Parse(Console.ReadLine());

int [,]a=new int;

for (int i = 0; i< n; ++i)

for (int j = 0; j< m; ++j)

for (int i = 0; i< n; ++i,Console.WriteLine())

for (int j = 0; j< m; ++j)

static void DeleteArray(int[,] a, ref int n, int m, int k)

for (int i = k; i< n-1; ++i)

for (int j = 0; j< m; ++j)

a = a;

static void Main()

Console.WriteLine("Source array:");

Print(myArray, n, m);

DeleteArray(myArray, ref n, m, k);

Console.WriteLine("Changed array:");

Print(myArray, n, m);

Tasks.

  1. Modify the program to remove the kth column in a two-dimensional array.

Let's consider a modification of the previous program for the case when a stepped array is used.

namespace ConsoleApplication

Console.WriteLine("enter array dimension");

Console.Write("n = ");

n=int.Parse(Console.ReadLine());

Console.Write("m = ");

m=int.Parse(Console.ReadLine());

int a=new int[n];

for (int i = 0; i< n; ++i)

a[i]=new int[m];

for (int j = 0; j< m; ++j)

Console.Write("a[(0),(1)]= ", i, j);

for (int i = 0; i< n; ++i,Console.WriteLine())

for (int j = 0; j< m; ++j)

Console.Write("(0,5) ", a[i] [j]);

static void DeleteArray(int a, ref int n, int k)

for (int i = k; i< n-1; ++i)//производим сдвиг ссылок

static void Main()

Console.WriteLine("Source array:");

Print(myArray, n, m);

Console.WriteLine("Enter the line number to delete:");

int k=int.Parse(Console.ReadLine());

DeleteArray(myArray, ref n, k);

Console.WriteLine("Changed array:");

Print(myArray, n, m);

Let's return to the array defined in the very first example. And now let's think about what it means to add an element to a one-dimensional array at position number k? In this case, all elements starting from the kth must be shifted to the right by one position. However, the shift must begin from the end, i.e. at the first step, put the n-1st element in the n-th place, then put the n-2nd element in the n-1st place, ... finally, insert the k-th element in k+1 place. Thus, a copy of the kth element will be in the k+1st place and a new element can be placed in the kth place. Then you need to increase the current number of elements by 1.

Consider the array from example 1 and set k to 3. In this case, the array will look like this:

k=3
A

Now you can put a new value in position number 3. And the current number of elements in the array becomes 6. Think about why the shift needs to be performed from the end of the array, and not from the beginning, as we did in the case of removing an element from the array.

Let's consider the software implementation of this algorithm:

namespace ConsoleApplication

static int Input (out int n)

Console.WriteLine("enter array dimension");

n=int.Parse(Console.ReadLine());

int a=new int; //allocate more memory than required

for (int i = 0; i< n; ++i)

Console.Write("a[(0)]= ", i);

a[i]=int.Parse(Console.ReadLine());

static void Print(int a, int n)

for (int i = 0; i< n; ++i) Console.Write("{0} ", a[i]);

Console.WriteLine();

static void AddArray(int a, ref int n, int m)

for (int i = n; i >= m; --i)

Console.WriteLine("Enter the value of the new element");

a[m]=int.Parse(Console.ReadLine());

static void Main()

int myArray=Input(out n);

Console.WriteLine("Source array:");

Print(myArray, n);

Console.WriteLine("Enter the item number to insert:");

AddArray(myArray, ref n,m);

Console.WriteLine("Changed array:");

Print(myArray, n);

Now let's look at adding a string to a two-dimensional array. To do this, move all the lines after the line with number k 1 line down. Then we increase the number of rows by 1. After this, a copy of row number k will be in column number k+1. And, therefore, the k-th column can be filled with new values. Let's consider the software implementation of the algorithm:

namespace ConsoleApplication

static int [,] Input (out int n, out int m)

Console.WriteLine("enter array dimension");

Console.Write("n = ");

n=int.Parse(Console.ReadLine());

Console.Write("m = ");

m=int.Parse(Console.ReadLine());

//allocate more memory than necessary

int [,]a=new int;

for (int i = 0; i< n; ++i)

for (int j = 0; j< m; ++j)

Console.Write("a[(0),(1)]= ", i, j);

a=int.Parse(Console.ReadLine());

static void Print(int[,] a, int n, int m)

for (int i = 0; i< n; ++i,Console.WriteLine())

for (int j = 0; j< m; ++j)

Console.Write("(0.5) ", a);

static void AddArray(int[,] a, ref int n, int m, int k)

for (int i = n; i >=k; --i)

for (int j = 0; j< m; ++j)

a = a;

for (int j=0; j

Console.Write("a[(0),(1)]=", k, j);

a=int.Parse(Console.ReadLine());

static void Main()

int[,] myArray=Input(out n, out m);

Console.WriteLine("Source array:");

Print(myArray, n, m);

int k=int.Parse(Console.ReadLine());

Console.WriteLine("Changed array:");

Print(myArray, n, m);

Tasks.

  1. Think about what kind of exceptions might occur in a given program and add appropriate exception handling to it.
  2. Modify the program to add the kth column in a two-dimensional array.

Let's consider a modification of the previous program for the case when a stepped array is used.

namespace ConsoleApplication

static int Input (out int n, out int m)

Console.WriteLine("enter array dimension");

Console.Write("n = ");

n=int.Parse(Console.ReadLine());

Console.Write("m = ");

m=int.Parse(Console.ReadLine());

//allocate more memory than necessary

int a=new int;

for (int i = 0; i< n; ++i)

a[i]=new int [m];

for (int j = 0; j< m; ++j)

Console.Write("a[(0)][(1)]= ", i, j);

a[i][j]=int.Parse(Console.ReadLine());

static void Print(int a, int n, int m)

for (int i = 0; i< n; ++i,Console.WriteLine())

for (int j = 0; j< m; ++j)

Console.Write("(0,5) ", a[i][j]);

static void AddArray(int a, ref int n, int m, int k)

for (int i = n; i >=k; --i)//shift references

a[k]=new int[m]; //create a new line

Console.WriteLine("Enter newline items");

for (int j=0; j

Console.Write("a[(0)][(1)]=", k, j);

a[k][j]=int.Parse(Console.ReadLine());

static void Main()

int myArray=Input(out n, out m);

Console.WriteLine("Source array:");

Print(myArray, n, m);

Console.WriteLine("Enter the line number to add:");

int k=int.Parse(Console.ReadLine());

AddArray(myArray, ref n, m, k);

Console.WriteLine("Changed array:");







2024 gtavrl.ru.