Array duplicate deletion in C# - c#

This is my code so far I have display all items in the array as the user enters and create an error message for duplicate numbers that deletes the duplicate and continues the loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace midterm
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("How many numbers will you enter?");
size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
int i;
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i != j)
{
if (numbers[j] == numbers[i])
{
int k = j;
while (k < size - 1)
{
numbers[k] = numbers[k + 1];
k++;
}
size--;
}
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < size; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}
}
Every time I go to change the for loops around or add an error message then the program stops deleting the duplicates I am really stumped on this one can someone lend me a hand.

Have a look at LINQ, it has some great functions that can be used for collection manipulation. In your situation I would do the following:
Distinct() here filters the array to only unique values.
int[] initialArray = new int[] { 1, 1, 2, 3, 4, 5 };
int[] noDuplicates = initialArray.Distinct().ToArray(); // [1,2,3,4,5]

I would recommend using a List instead of array. A List will allow you to keep adding entries to it without having to specify the size.
With the list, you can check if entry exists already before adding it, so you wont have to remove or delete

Easy way, use a HashSet
HashSet<int> mySet = new HashSet<int>();
//...
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (!mySet.Add(number))
{
Console.WriteLine("That was a duplicate. Try again");
i--;
}
}
If you must use arrays:
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
int numbers = Convert.ToInt32(Console.ReadLine());
if (ExistsInArray(number, numbers))
{
Console.WriteLine("That was a duplicate. Try again");
i--;
}
else
{
numbers[i] = number;
}
}
And then:
private static bool ExistsInArray(number, numbers)
{
// Your code to search numbers for number and return true if found
// Left as an exercise for the OP
}
One important note here is that it's a lot easier to check whether your array already contains the element you are trying to add than to remove it after the fact. If it already exists, just don't add it again.

Related

is there a way to have line amount higher than 6, when my array bound is set to 6?

I would like to print out more than six lines of six random numbers, but array bound is blocking me. I have set my array 'numbers' to six in order to always get just six random numbers, but now I dont know what to do to print out for example just ten lines of the numbers, because as I said - I can not due to six bounded array and I do not know how to deal with it. Can anyone help, please?
using System;
class Program
{
static void Main()
{
Draw();
Console.ReadKey();
}
static void Draw()
{
int choice;
Random randomNum = new Random();
int[] numbers = new int[6];
Console.Write("enter line amount: ");
choice = int.Parse(Console.ReadLine());
for (int i = 0; i < choice; i++)
{
Console.Write("\n");
for (int j = 0; j < numbers.Length; j++)
{
numbers[i] = randomNum.Next(1, 49);
Console.Write("{0} ", numbers[i]);
}
}
}
}
Hy!
In the 2nd for loop, write "j" instead of "i", because the 2nd for loop monitors the length of the array
Try this:
static void Main(string[] args)
{
Draw();
Console.ReadKey();
}
static void Draw()
{
int choice;
Random randomNum = new Random();
int[] numbers = new int[6];
Console.Write("enter line amount: ");
choice = int.Parse(Console.ReadLine());
for (int i = 0; i < choice; i++)
{
Console.Write("\n");
for (int j = 0; j < numbers.Length; j++)
{
numbers[j] = randomNum.Next(1, 49);
Console.Write("{0} ", numbers[j]);
}
}
}
Arrays in C# are of a fixed size, so I'd recommend using a dynamically-sized collection, such as a List<T> instead in your case.
There's a good introduction on how to use these on Microsoft's documentation here if you aren't familiar.

Finding sum a multi-dimensional array's reverse diagonal elements

this is my multi dimensional array.
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
And i want find sum of reverse diagonal elements (From:right top To:left bottom) (4 -> 7 -> 10 -> 13)
Here is my code, it gives an error but i still can't find why.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sketchboard
{
class Program
{
static int reversediagonaladder (int[,] a)
{
int sum = 0;
for(int row=a.GetLength(0) ; row>0 ; row--)
{
for(int column=a.GetLength(1) ; column>0 ; column--)
{
if (row == column)
sum += a[row , column];
}
}
Console.WriteLine($"{sum}");
return sum;
}
static void Main(string[] args)
{
int[,] a ={ {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16 } };
reversediagonaladder(a);
Console.ReadLine(); // added for hold console on screen
}
}
}
Your loop starts with a.GetLength(1) or a.GetLength(0) in both cases this will resolve to 4 but there is no index with 4 since indexes start with 0.
So index will be 0, 1, 2 or 3 which equals to a length of 4.
To fix your problem you need to substract 1 from the length.
Currently you are also skipping the index 0, I don't know why you are doing so, maybe it is an error aswell, to fix this you have to change the break condidtion of the for loop from > 0 to >= 0.
This should work
for (int row = a.GetLength(0) - 1; row >= 0; row--)
{
for (int column = a.GetLength(1) - 1; column >= 0; column--)
{
if (row == column)
sum += a[row , column];
}
}
Edit:
Here a version which actually does what the question claims it does, it also gets rid of the double for loop which should run more performant
var column = a.GetLength(1);
for (int row = 0; row < a.GetLength(0); row++)
{
column--;
var item = a[row, column];
sum += item;
}
Here you can see it in action:
https://dotnetfiddle.net/S5imGs
If you don't want to deal with the -1, use GetUpperBound instead.
Here's an example doing as Self suggested with just one for loop:
public static void Main(string[] args)
{
int[,] a ={ {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16} };
int sum = reversediagonaladder(a);
Console.WriteLine("sum = " + sum);
Console.WriteLine();
Console.WriteLine("Press Enter to Quit");
Console.ReadLine();
}
static int reversediagonaladder(int[,] a)
{
// code assumes a SQUARE matrix
int sum = 0;
for (int row=0, col=a.GetUpperBound(1); row<=a.GetUpperBound(0) && col>=0; row++, col--)
{
sum += a[row, col];
}
return sum;
}

Selection Sort Implementation

I'm not really sure what's wrong with the implementation I have. How would I fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelectionSort
{
class Program
{
static void algorithm(int[] to_sort)
{
int bufor;
for (int i = 0; i < to_sort.Length; i++)
{
for (int j = i + 1; j < to_sort.Length; j++)
{
if (to_sort[i] >= to_sort[j])
{
bufor = to_sort[i];
to_sort[i] = to_sort[j];
to_sort[j] = bufor;
}
}
}
}
static void Main(string[] args)
{
int[] to_sort = new int[100];
Console.WriteLine("");
for (int i = 1; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.WriteLine("");
algorithm(to_sort);
Console.WriteLine("\n");
Console.WriteLine("Sorted list:");
for (int i = 0; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.Read();
}
}
}
This produces the following output:
Original list: 00000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
Sorted list: 000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
It looks like my array (int[] to_sort) was empty, am I right? How can I get this:
Original list: 123456789....100
Sorted list: 123456789...100
Perhaps you originate from the C++ world where initializing an array does not mean the array is "cleaned" (the data that happened to be located at the allocated memory remains untouched), but in C# if you initialize an array like:
int[] to_sort = new int[100];
It means you construct an array where every element is set to default(T) with T the type. For an int that is 0 (for objects it is null, etc.). So you just constructed an array filled with zeros.
You can however for instance fill it with random numbers like:
Random rand = new Random();
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = rand.Next(0,1000);
}
EDIT
Based on your comment, you want to fill it with the positions, you can do this like:
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = i+1;
}
I think the easiest and shortest way you can initialize an array of sequential numbers is like this:
int[] to_sort = Enumerable.Range(1, 100).ToArray();
What you have will just allocate the array and fill it with the default value for int, which is 0:
int[] to_sort = new int[100];

Array Duplicate Elimination with c#?

I have a program here that need some improvements. This Program inputs 5 elements in an Array and Removes if any duplicates. It works but the problem is that it sets every duplicate to zero. I don't want to display zero. I want it completely destroyed and eliminated. I don't want that duplicate element to appear. This is what I have so Far! Could Use some help. Thank You.
// Gurpreet Singh
// Duplicate Program
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
number[j] = 0;
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < Array_Size; i++)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
Console.ReadLine();
}
}
The easiest way is to use Linq's Distinct method:
number = number.Distinct().ToArray();
This will return a new array without any duplicates.
The duplicate is displayed as zero, since you assign the value of the duplicate to be zero, in the line,
if(number[j]==number[i])
number[j]=0
to delete the element from the array, use the following code:
if(number[j]==number[i])
{
int k=j;
while(k<Array_Size-1)
{
number[k]=number[k+1];
k++;
}
Array_Size--;
}
the statement Array_Size--; is done so that the last element is not repeated twice
This is my complete code in which I put some double-for-loop statement to
prevent it from inserting the duplicated integers in an array.
Have a look.
class Program
{
static void Main(string[] args)
{
const int ARRAY_SIZE = 5;
int[] ArrayTable = new int[ARRAY_SIZE];
int Element=0;
int a;
for(a=0; a<ArrayTable.Length;a++)
{
Console.Write("Please Enter an integer (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
}
ArrayTable[a] = Element;
for (int b = 0; b < a; b++)
{
while (ArrayTable[a] == ArrayTable[b])
{
Console.Write("Integer Duplicated!\nTry again: ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
Console.WriteLine();
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
}
}
}
}
for (int c = 0; c < ArrayTable.Length; c++)
{
Console.Write("{0} ", ArrayTable[c]);
}
}

A logic issue regarding a very simple solution that performs the factorizing function

This solution factorizes a number (numInput), it works perfectly well except for a logic error I can't seem to find no matter how much I track the solution. The logic error causes the returned result to be 0 no matter the value initialized for numInput.
using System;
namespace factorizer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(factorialise());
Console.ReadKey();
}
private static int factorialise()
{
int numInput = int.Parse(Console.ReadLine());
int[] number = new int[numInput];
for (int i = 1; i < numInput; i++) //stores the (n-1)...(n-i) value for the number input'd in the array number[i]
{
number[i - 1] = numInput - i; //the element indicating the index number is 'i - 1' index values start from zero
}
for (int index = 0; index < number.Length; index++) //multiplies the element corresponding the index number with the number input'd
{
numInput = numInput * number[index];
}
return numInput;
}
}
}
Your last item in array stays uninitialized (i.e. equal to zero). Change items count:
int[] number = new int[numInput-1];
Also why not simply use for loop?
int result = 1;
for(int i = 1; i <= numInput; i++)
result *= i;
And another sample just for fun
Enumerable.Range(1, numInput).Aggregate(1, (a,i) => a * i)

Categories