Jump to content

C# insert elements in a specific place

MisterWhite

Having trouble completing this exercise : Insert a new record (in a specified position, moving the following ones to the right)

so if we have an array of {1,2,3,4,5} , and user wants to add a number ( lets say 7) to a second position (in the 3's position) it would look like {1,2,7,3,4,5}

can someone write the algorithm in c++ or c#

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Do you have resizable arrays in C# ? I can't remember, I've been using only C++ for quite some time now. (in C++ we have std::vector)

 

Anyway , the pseudocode should be something like this (considering we don't have resizable arrays)

//read length of arrayread length//declare array with a size bigger than its length, let's say length+1,  to allow for more itemsarray[length+1]//read array...//read value and position of the number to be inserted (let's call the variables value and position)read value , position//shift all values right of the position to the right like so :temp = length + 1while temp > position      array[temp] = array[temp-1]      temp--array[position] = valuelength++                   

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

Do you have resizable arrays in C# ? I can't remember, I've been using only C++ for quite some time now. (in C++ we have std::vector)

not sure, but the adding method should look similar to deleting an element delete=delete[i+1], but somehow different :D

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

GPU: Gigabyte GTX 970 G1 Gaming CPU: i5-4570 RAM: 2x4gb Crucial Ballistix Sport 1600Mhz Motherboard: ASRock Z87 Extreme3 PSU: EVGA GS 650 CPU cooler: Be quiet! Shadow Rock 2 Case: Define R5 Storage: Crucial MX100 512GB
Link to comment
Share on other sites

Link to post
Share on other sites

Do you have resizable arrays in C# ? I can't remember, I've been using only C++ for quite some time now. (in C++ we have std::vector)

I think no. He will have to use a list.

 

I think that's only for JavaScript. He'll have to use Insert or Add method for a list.

From salty to bath salty in 2.9 seconds

 

Link to comment
Share on other sites

Link to post
Share on other sites

I think no. He will have to use a list.

 

I think that's only for JavaScript. He'll have to use Insert or Add method for a list.

Didn`t notice that. I thought C# also had a function like that. Although arrays are resizable in C#(this time a link that is actually about C# and not JS). https://msdn.microsoft.com/en-us/library/bb348051%28v=vs.110%29.aspx

GPU: Gigabyte GTX 970 G1 Gaming CPU: i5-4570 RAM: 2x4gb Crucial Ballistix Sport 1600Mhz Motherboard: ASRock Z87 Extreme3 PSU: EVGA GS 650 CPU cooler: Be quiet! Shadow Rock 2 Case: Define R5 Storage: Crucial MX100 512GB
Link to comment
Share on other sites

Link to post
Share on other sites

Didn`t notice that. I thought C# also had a function like that. Although arrays are resizable in C#(this time a link that is actuallt about C# and not JS). https://msdn.microsoft.com/en-us/library/bb348051%28v=vs.110%29.aspx

Oh nice, I didn't knew that method - I'll try it. But still, lists are awesome.  :P

From salty to bath salty in 2.9 seconds

 

Link to comment
Share on other sites

Link to post
Share on other sites

I think no. He will have to use a list.

 

I think that's only for JavaScript. He'll have to use Insert or Add method for a list.

if i have an array that has some strings in it, can i make array=list (pseudo code)

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Didn`t notice that. I thought C# also had a function like that. Although arrays are resizable in C#(this time a link that is actually about C# and not JS). https://msdn.microsoft.com/en-us/library/bb348051%28v=vs.110%29.aspx

 

Oh nice, I didn't knew that method - I'll try it. But still, lists are awesome.  :P

 

Arrays are not resizable in C#. That method creates a new array with the new size and copies over the data from the old array.

 

List, which is a C# implementation of the dynamic array data structure, does this for you behind the scenes as you add items to it.

Link to comment
Share on other sites

Link to post
Share on other sites

Arrays are not resizable in C#. That method creates a new array with the new size and copies over the data from the old array.

 

List, which is a C# implementation of the dynamic array data structure, does this for you behind the scenes as you add items to it.

Lists in C# aren't linked lists?

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

if i have an array that has some strings in it, can i make array=list (pseudo code)

List<string> someList = new List<string>(someArray);

From salty to bath salty in 2.9 seconds

 

Link to comment
Share on other sites

Link to post
Share on other sites

Arrays are not resizable in C#. That method creates a new array with the new size and copies over the data from the old array.

 

List, which is a C# implementation of the dynamic array data structure, does this for you behind the scenes as you add items to it.

I know, but it still works the same as if you had a resizable array in C# most of the time.

GPU: Gigabyte GTX 970 G1 Gaming CPU: i5-4570 RAM: 2x4gb Crucial Ballistix Sport 1600Mhz Motherboard: ASRock Z87 Extreme3 PSU: EVGA GS 650 CPU cooler: Be quiet! Shadow Rock 2 Case: Define R5 Storage: Crucial MX100 512GB
Link to comment
Share on other sites

Link to post
Share on other sites

Lists in C# aren't linked lists?

 

C# has a separate class called LinkedList for that (it was mentioned in the link in my reply to you above).

Link to comment
Share on other sites

Link to post
Share on other sites

List<string> someList = new List<string>(someArray);

after this ill be allowed to do anything with my old arrays elements but with list functions?

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

after this ill be allowed to do anything with my old arrays elements but with list functions?

No, that way you make a list, which contains the elements of the array.

From salty to bath salty in 2.9 seconds

 

Link to comment
Share on other sites

Link to post
Share on other sites

No, that way you make a list, which contains the elements of the array.

maybe my question was incorrect, but i meant what you answered :D

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

maybe my question was incorrect, but i meant what you answered :D

 

Using a List is defeating the purpose of the exercise which is teaching you how to work with arrays. ;)

 

But hey, you're still learning. You're just learning how to use a List instead which is a very useful class to know how to use. I'd recommend learning how to do the exercise both ways.

Link to comment
Share on other sites

Link to post
Share on other sites

Using a List is defeating the purpose of the exercise which is teaching you how to work with arrays. ;)

 

But hey, you're still learning. You're just learning how to use a List instead which is a very useful class to know how to use. I'd recommend learning how to do the exercise both ways.

i just didn't receive any help on doing it with arrays

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

i just didn't receive any help on doing it with arrays

Check Nineshadow's pseudocode - it can give you a general understanding and you can build the program around it. :) 

 

The list way is much simpler, but your teacher won't be happy with it.

Example:

int[] arr = {1,2,3,4,5};List <int> list = new List<int>(arr);list.Insert(2, 7); //insert "7" at the second positionforeach (var item in list){    Console.Write(item + " ");}

From salty to bath salty in 2.9 seconds

 

Link to comment
Share on other sites

Link to post
Share on other sites

The following is made in C++. Don't know how it should work in C#.

 

This is an insert function :

void insert(int **v, int length, int pos, int value){    int *t = new int[length+1];    int *q = *v;    for(int i = 0; i < pos; i++)        *(t+i) = q[i];    *(t+pos) = value;    for(int i = pos; i < length; i++)        *(t+i+1) = q[i];    *v = t;}

Its input is represented of : a pointer to the pointer of the array (since we will be editing the array's pointer) , the length of the array, value and position of the number to be inserted.

We create a new array of size length+1 at a pointer, let's call it T.

Then, we create a new int pointer which points to the original array, let's call it Q.

We copy everything from [0,pos-1] of Q into our new array T at a corresponding location ( T = Q)

We copy value into T[pos].

Then, we copy all elements from [pos,length] from Q into T at [pos+1,length+1] ( T[i+1] = Q )

Next, we put (a pointer to the final array) into the value pointed by the first pointer of the double pointer.

 

This basically overwrites our original array with the new T array.

 

However, in order to use this function you need to use a dynamically allocated array.

An example of using this function :

#include <iostream>using namespace std;void insert(int **v, int length, int pos, int value){    int *t = new int[length+1];    int *q = *v;    for(int i = 0; i < pos; i++)        *(t+i) = q[i];    *(t+pos) = value;    for(int i = pos; i < length; i++)        *(t+i+1) = q[i];    *v = t;}int main(){    int *v = new int[4];    v[0]=1;    v[1]=2;    v[2]=4;    v[3]=5;    insert(&v, 4, 2, 3);    for( int i = 0; i < 5; i++)        cout << v[i] << ' ';    return 0;}

We create a new dinamically allocated array : [1,2,4,5].

We call the insert function to put 3 into the position 2 of the array.

When we write our array, we end up with : [1,2,3,4,5].

 

It's different than the method I mentioned with pseudocode.

That one would work like this :

#include <iostream>#include <fstream>using namespace std;ifstream in("test.in");#define MAX 1000int main(){    int length;    in >> length;    int v[MAX];    for(int i = 0; i < length;i++) in >> v[i];    int position, value;    in >> position >> value;    for(int temp = length+1; temp > position; temp--)    {        v[temp] = v[temp-1];    }    v[position] = value;    length++;    for(int i = 0; i < length; i++) cout << v[i];    return 0;}

For this input file :

41 2 4 52 3

It writes :

1 2 3 4 5

Just as it should.

It probably should work in C# as well, with a little changes.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

i just didn't receive any help on doing it with arrays

Can`t test this code right now because my visual studio license is expired and I`m to lazy to download VS express, but here`s what I`d do if it has to be as an array:

int[] a = {1, 2, 3, 4, 5};int insertObjectAtIndex = 2;int insertValue = 100;int[] b = new int[a.Length+1];for (int i=0;i<=a.Length;i++) {  if(i==insertObjectAtIndex){    b[i]=insertValue;    i++;  }  b[i]=a[i];} return b;

Obviously this isn`t a complete function, but you should get the idea.

GPU: Gigabyte GTX 970 G1 Gaming CPU: i5-4570 RAM: 2x4gb Crucial Ballistix Sport 1600Mhz Motherboard: ASRock Z87 Extreme3 PSU: EVGA GS 650 CPU cooler: Be quiet! Shadow Rock 2 Case: Define R5 Storage: Crucial MX100 512GB
Link to comment
Share on other sites

Link to post
Share on other sites

Can`t test this code right now because my visual studio license is expired and I`m to lazy to download VS express, but here`s what I`d do if it has to be as an array:

int[] a = {1, 2, 3, 4, 5};int insertObjectAtIndex = 2;int insertValue = 100;int[] b = new int[a.Length+1];for (int i=0;i<=a.Length;i++) {  if(i==insertObjectAtIndex){    b[i]=insertValue;    i++;  }  b[i]=a[i];} return b;

The problem with your code is that it doesn't make a correct correlation between the two arrays after the new element is inserted.

Let's take your own example.

Once i reaches 2, b = 100, so b[2]=100, then i gets incremented and b = a, so b[3] = a[3] = 4

We obviously missed a[2].

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

 

Check Nineshadow's pseudocode - it can give you a general understanding and you can build the program around it. :)

 

The list way is much simpler, but your teacher won't be happy with it.

Example:

int[] arr = {1,2,3,4,5};List <int> list = new List<int>(arr);list.Insert(2, 7); //insert "7" at the second positionforeach (var item in list){    Console.Write(item + " ");}

I hate it when teachers tell me that my solution is bad. Today I had to do this exersize in school: http://codingbat.com/prob/p130788

This was my solution:

public int luckySum(int a, int b, int c) {  return a==13?0:(b==13?a:(c==13?a+b:a+b+c));}

But he told me that it was badly readable and I should do it with "if" instructions, which would have taken up at least 5 times more space.

GPU: Gigabyte GTX 970 G1 Gaming CPU: i5-4570 RAM: 2x4gb Crucial Ballistix Sport 1600Mhz Motherboard: ASRock Z87 Extreme3 PSU: EVGA GS 650 CPU cooler: Be quiet! Shadow Rock 2 Case: Define R5 Storage: Crucial MX100 512GB
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×