C# Array C with a formula - c#

im new to programming and I am stuck on a part of a question.
After i create two methods-one for inputing Array and one for summing the elements that are odd and can be dividible to 5.I have to do this to three arrays-A,B and C.I've done all of this,but this time i have to find the elements of C(again),but with this formula:
((An-Bn)(A1-B1),(An-1 - Bn-1)(A2-B2),....(A1-B1)(An-Bn))
or in other words:
((A[n]-B[n])(A[0]-B[0]),(A[n-1]-B[n-1])(A[2]-B[2]),....,(A[1]-B[1])(A[n]-B[n])
If someone can help me to figure this out.I've tried a couple of things and most of them give the "Index out of bounds".
Thank you in advance.
namespace MethodsArrays
{
class Program
{
//Tochka 1 a/ i b/
static void Array(int[] p)
{
for (int i = 0; i < p.Length; i++)
{
p[i] = int.Parse(Console.ReadLine());
}
}
static void Output(int [] p)
{
for (int i = 0; i < p.Length; i++)
{
Console.WriteLine();
Console.Write(p[i] + "");
Console.WriteLine();
}
}
static int Multiple(int[] p)
{
int br = 0;
for (int i = 0; i < p.Length; i++)
{
if (p[i] % 2 == 1 && p[i] % 5 == 0)
{
//for (int j = 0; j < p.Length;j++)
//{
br += p[i];
//}
}
}
return br;
}
//Tochka 2
public static void Main()
{
Console.WriteLine("Type the legth of the array.");
Console.WriteLine();
int n = int.Parse(Console.ReadLine());
Console.Write("n= "+ n);
Console.WriteLine();
int[] a = new int[n];
Array(a);
Console.Write("Array A: ");
Output(a);
Console.WriteLine();
Console.Write("Length of B = "+ n);
Console.WriteLine();
int[] b = new int[n];
Array(b);
Console.Write("Array B: ");
Output(b);
Console.WriteLine();
Console.Write("Length of C= " + n);
Console.WriteLine();
int[] c = new int[n];
Array(c);
Console.Write("Array C: ");
Output(c);
Console.WriteLine();
int br1 = Multiple(a); Console.WriteLine("br1=" + br1);
int br2 = Multiple(b); Console.WriteLine("br2=" + br2);
int br3 = Multiple(c); Console.WriteLine("br3=" + br3);
double srgeo = (br1 * br2 * br3);
double srg = Math.Pow(srgeo, (double)1 / 3);
Console.WriteLine("Srednogeometrichno= "+ srg);

There there are n elements in a and b then the i-th element of c is
c[i] = (a[n-i-1]-b[n-i-1])*(a[i]-b[i])
Or more specifically, try the method below for composing c
static int[] ComposeArray(int[] a, int[] b)
{
if (a.Length == b.Length)
{
int n = a.Length;
int[] c = new int[n];
for (int i = 0; i < n; i++)
{
c[i] = (a[n-i-1]-b[n-i-1])*(a[i]-b[i]);
}
return c;
}
throw new ArgumentException();
}
since no test data was given in the question, I made up some on my own:
static void Main(string[] args)
{
var a = Enumerable.Range(1, 5).Select((i) => i).ToArray();
// [1,2,3,4,5]
var b = Enumerable.Range(4, 5).Select((i) => i).ToArray();
// [4,5,6,7,8]
var c = ComposeArray(a, b);
// [9,9,9,9,9]
}

Related

Sorting Neighborhoods by Population Using Heap

I am trying to sort the neighborhoods by their populations. I used heap sorting algorithm in C#. I created an Array which keeps the population of the neighborhoods named "arr". And created an array which keeps the name of the hoods . It works good but how can I get output of sorting with name of the neighborhoods?
My code is here:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace HoodSorting
{
public class example
{
static void heapSort(int[] arr, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
static void heapify(int[] arr, int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
public static void Main()
{// arr REPRESENTS THE POUPLATION OF THE NEIGHBORHOODS
string[] neighborhoods = { "Bornova" ,"Westriver","Paradise","Goodman","McMountain","Rocker","Summerlin","Northcity","Greenhill","Sevenwaves"};
int[] arr = { 55, 25, 89, 34, 12, 19, 78, 95, 1, 100 };
int n = 10, i;
Console.WriteLine("Heap Sort");
Console.Write("Initial array is: ");
for (i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
heapSort(arr, 10);
Console.Write("\nSorted Array is: ");
for (i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
}
}
}
How can I get output like this:
Sorted Array is: Greenhill, McMountain,....,........, Northcity, Sevenwaves
Thanks a lot for the help
From an OOP perspective you would keep the two properties (name and population of a neighborhood) together in one object. Then when you sort the objects, you'll still have the associated data right there.
There are several ways to do this. For instance, you could create tuples.
Here is how that is applied to your code:
static void heapSort(Tuple<int, string>[] arr)
{
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--)
{
(arr[0], arr[i]) = (arr[i], arr[0]);
heapify(arr, i, 0);
}
}
static void heapify(Tuple<int, string>[] arr, int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left].Item1 > arr[largest].Item1)
largest = left;
if (right < n && arr[right].Item1 > arr[largest].Item1)
largest = right;
if (largest != i)
{
(arr[i], arr[largest]) = (arr[largest], arr[i]);
heapify(arr, n, largest);
}
}
public static void Main()
{
Tuple<int, string>[] arr = {
Tuple.Create(55, "Bornova"),
Tuple.Create(25, "Westriver"),
Tuple.Create(89, "Paradise"),
Tuple.Create(34, "Goodman"),
Tuple.Create(12, "McMountain"),
Tuple.Create(19, "Rocker"),
Tuple.Create(78, "Summerlin"),
Tuple.Create(95, "Northcity"),
Tuple.Create(1, "Greenhill"),
Tuple.Create(100, "Sevenwaves")
};
Console.WriteLine("Initial array is: ");
foreach (var pair in arr)
{
Console.Write(pair.Item2 + " ");
}
Console.WriteLine();
heapSort(arr);
Console.WriteLine("Sorted Array is: ");
foreach (var pair in arr)
{
Console.Write(pair.Item2 + " ");
}
Console.WriteLine();
}

Program that creates random numbers from 1 to n, without repeating, and stores them in array of size n

Well, I've been coding this program that has the objective to create random numbers, and then store them in an array (linhas[n]), but I don't want them to repeat.
I started by doing a for loop (int i = 0; i < n; i++) and inside it I wrote that a variable a (int a) was equal to a random number generated from the random function (r). Then I compared if a already existed in the array, using bool b = Array.Exists(linhas, elements => elements == a);, then wrote that if b was true it would decrease the i value by one, to repeat the same i loop, doing linhas[i] = a if b was false. Then it would write the elements of the array.
The problem that I'm getting is that when I open the program and write the value of n the program just doesn't do nothing, just a black screen. I already checked and if I put the value of n = 1, the program generates just one number, number 1. But if I put n = 2 it just stops.
If anyone understood what I said here and could help me, please just throw some tips!
The code here:
static void Main(string[] args)
{
int n;
Console.Write("Escreva o número de linhas a aparecer: ");
n = Convert.ToInt32(Console.ReadLine());
int[] linhas = new int[n];
var r = new Random();
for (int i = 0; i < n; i++)
{
int a = r.Next(1, n);
bool b = Array.Exists(linhas, elements => elements == a);
if (b == true)
{
i--;
}
else
{
linhas[i] = a;
}
}
Console.WriteLine("");
for (int i = 0; i < n; i++)
{
Console.WriteLine(linhas[i]);
}
Console.Read();
}
Random range is not valid. Your fault is r.Next(1, n) mean is [1;n). I fixed that r.Next(1, n+1).
Hope this helps. Bye!
using System;
using System.Linq;
class MyClass
{
static void Main(string[] args)
{
int n;
Console.Write("Escreva o número de linhas a aparecer: ");
n = Convert.ToInt32(Console.ReadLine());
int[] linhas = new int[n];
var r = new Random();
for (int i = 0; i < n;)
{
int a = r.Next(1, n + 1);
#region Using LINQ
//if (linhas.Contains(a))
//{
// continue;
//}
#endregion
#region Using Array Exists
bool b = Array.Exists(linhas, elements => elements == a);
if (b == true)
{
continue;
}
#endregion
else
{
linhas[i] = a;
i++;
}
}
Console.WriteLine("");
for (int i = 0; i < n; i++)
{
Console.WriteLine(linhas[i]);
}
}
}

Is there a way to throw an exception when string is typed in an arrayc#?

I am new in this fascinating world of programming. I have done this array, but when I type a non integer it crashes. I have tried many ways like int.Parse(console.readLine)), tryparse(text, out int) and ConvertTo32 ,However it continues saying that "Input string was not in correct format." Thanks
using System;
namespace BubbleSort
{
class Program
{
public static void HelpME(int[] a, int t)
{
for (int j = 0; j <= a.Length - 2; j++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
}
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
a[0 + x] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}
}
}
you should validate the user unput by using int.TryParse method. If the entered string can be converted to int then only it should be inserted into the array, otherwise the program should ignore that value.
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
int temp = 0;
string input = Console.ReadLine();
if(int.TryParse(input, out temp))
{
a[0 + x] = Convert.ToInt32(input);
}
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}

C# Adding big numbers using only strings?

I am trying to write a program that sums very big numbers (I am trying to solve a problem on projecteuler.net), so I cannot parse them into number types. So I was wondering if it is possible to sum such numbers using only strings or something like that?
Try using BigInteger instead. It effictively lets you use integers of arbitrary size.
kindly use BigInteger found in System.Numerics and use `
Add(BigInteger, BigInteger)
` please follow the below link for better understanding.
add two bigintegers
BigInteger Represents an arbitrarily large signed integer. microsoft documentation.
class Program
{
static void Main(string[] args)
{
string inputString = Console.ReadLine();
string[] linePart = inputString.Split(' ', ',', '\n'); // split as , and " " and new line
/* Console.WriteLine(linePart[1]);*/
string num0 = linePart[0];
string num1 = linePart[1];
int val0 = num0.Length;
int iv0 = val0;
int val1 = num1.Length;
int iv1 = val1;
/* Console.WriteLine(val0);
Console.WriteLine(val1)*/;
int arraySize;
if (val0 > val1)
{
arraySize = val0;
}
else { arraySize = val1; }
int[] arr0 = new int[arraySize];
int[] arr1 = new int[arraySize];
for (int i =0; i <iv0; i++)
{
arr0[i] = num0[val0-1]-48;
val0--;
}
for (int i = 0; i < iv1; i++)
{
arr1[i] = num1[val1-1]-48;
val1--;
}
/* for (int i = 0; i < arraySize; i++)
{
Console.Write(arr0[i]);
Console.Write(" ");
Console.Write(arr1[i]);
Console.WriteLine();
}*/
int tamp=0;
int rem=0;
int[] ans = new int[arraySize+1];
int ansloop = arraySize;
for(int i = 0; i <= arraySize; i++)
{
if (i != arraySize)
{
tamp = arr0[i] + arr1[i];
tamp = tamp + rem;
if (tamp >= 10)
{
tamp = tamp % 10;
rem = 1;
}
else { rem = 0; }
ans[ansloop] = tamp;
ansloop--;
}
else {
ans[ansloop] = rem;
}
}
for (int i = 0; i <= arraySize; i++)
{
Console.Write(ans[i]+" ");
}
}
}
}

Find ascending duplicate pairs in an array

Given an array A with zero index and N integers find equal elements with different positions in the array. Pair of indexes (P,Q) such that 0 <= P < Q < N such that A[P] = A[Q]. My algorithm is below but I am looking for a O(N*logN) solution.
public int solution(int[] A)
{
int N = A.Length;
int count = 0;
for (int j = 0; j < N; j++)
{
count += FindPairs(A[j], j, A);
}
return count;
}
public int FindPairs(int item, int ci, int[] A)
{
int len = A.Length;
int counter=0;
int k = ci+1;
while (k < len)
{
if (item == A[k])
counter++;
k++;
}
return counter;
}
From your code, it looks like the goal is to return the count of ascending duplicate pairs in A.
We observe that if there are m occurrences of the number x in A, then the number of ascending duplicate pairs of the value x is m choose 2, or m (m - 1) / 2.
So, we sum up m (m - 1) / 2 for each unique x, giving us the answer.
In pseudocode, this looks like:
count = new Dictionary();
foreach a in A {
count[a]++;
}
total = 0;
foreach key, value in count {
total += value * (value - 1) / 2;
}
return total;
This algorithm is O(N).
Recent interview question … here is what I did:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Codility
{
internal class Program
{
public struct Indice
{
public Indice(int p, int q)
{
P = p;
Q = q;
}
public int P;
public int Q;
public override string ToString()
{
return string.Format("({0}, {1})", P, Q);
}
}
private static void Main(string[] args)
{
// 0 1 2 3 4 5
int[] list = new int[] {3,3,3,3,3,3};
int answer = GetPairCount(list);
Console.WriteLine("answer = " + answer);
Console.ReadLine();
}
private static int GetPairCount(int[] A)
{
if (A.Length < 2) return 0;
Dictionary<int, Dictionary<Indice, Indice>> tracker = new Dictionary<int, Dictionary<Indice, Indice>>();
for (int i = 0; i < A.Length; i++)
{
int val = A[i];
if (!tracker.ContainsKey(val))
{
Dictionary<Indice, Indice> list = new Dictionary<Indice, Indice>();
Indice seed = new Indice(i, -1);
list.Add(seed, seed);
tracker.Add(val, list);
}
else
{
Dictionary<Indice, Indice> list = tracker[val];
foreach (KeyValuePair<Indice,Indice> item in list.ToList())
{
Indice left = new Indice(item.Value.P, i);
Indice right = new Indice(i, item.Value.Q);
if (!list.ContainsKey(left))
{
list.Add(left, left);
Console.WriteLine("left= " + left);
}
if (!list.ContainsKey(right))
{
list.Add(right, right);
Console.WriteLine("\t\tright= " + right);
}
}
}
}
return tracker.SelectMany(kvp => kvp.Value).Count(num => num.Value.Q > num.Value.P);
}
}
}
I think this is best version I got in c#.
static void Main(string[] args)
{
var a = new int[6] { 3, 5, 6, 3, 3, 5 };
//Push the indices into an array:
int[] indices = new int[a.Count()];
for (int p = 0; p < a.Count(); ++p) indices[p] = p;
//Sort the indices according to the value of the corresponding element in a:
Array.Sort(indices, (k, l) =>Compare(a[k], a[l]));
//Then just pull out blocks of indices with equal corresponding elements from indices:
int count = 0;
int i = 0;
while (i < indices.Count())
{
int start = i;
while (i < indices.Count() && a[indices[i]] == a[indices[start]])
{
++i;
}
int thisCount = i - start;
int numPairs = thisCount * (thisCount - 1) / 2;
count += numPairs;
}
Console.WriteLine(count);
Console.ReadKey();
}
//Compare function to return interger
private static int Compare(int v1, int v2)
{
if (v2 > v1)
return 1;
if (v1 == v2)
return 0;
else
return -1;
}
This approach has O(n log n) complexity overall, because of the sorting. The counting of the groups is linear.
Try this:
private static int GetIdenticalPairCount(int[] input)
{
int identicalPairCount = 0;
Dictionary<int, int> identicalCountMap = new Dictionary<int, int>();
foreach (int i in input)
{
if (identicalCountMap.ContainsKey(i))
{
identicalCountMap[i] = identicalCountMap[i] + 1;
if (identicalCountMap[i] > 1)
{
identicalPairCount += identicalCountMap[i];
}
else
{
identicalPairCount++;
}
}
else
{
identicalCountMap.Add(i, 0);
}
}
return identicalPairCount;
}
Test my version:
public int solution(int[] A)
{
int N = A.Length;
int count = 0;
for (int j = 0; j < N - 1; j++)
for (int i = j + 1; i < N; i++)
if (A[i] == A[j])
count++;
return count;
}

Categories

Resources