Mergesort code not working [duplicate] - c#

This question already has answers here:
Merge Sort code is not working and showing exception
(3 answers)
Closed 8 years ago.
I am using C# to implement the code of mergesort();
Here is the code i wrote in main()
static void Main(string[] args)
{
int[] arr = { 5,9,2,-10,53,-64,10,22,15,-60,2,3};
Merge(arr,0,6,12);
}
And here is the Merge() function
public static void Merge(int[] arr,int p,int q,int r )
{
int n1 = q-p;
int n2 = r-q;
int[] L=new int[n1];
int[] R = new int[r-n2];
for (int i = 0; i < n1; i++)
L[i] = arr[i];
foreach (int x in L)
Console.WriteLine(x);
for (int i = 0; i < r-n2; i++)
R[i] = arr[q+i];
Console.WriteLine("New part");
foreach (int x in R)
Console.WriteLine(x);
int k=0, d=0;
for (int i = p; i < r; i++)
{
if (L[k] <= R[k])
{
arr[i] = L[k];
k++;
}
else
{
arr[i] = R[d];
d++;
}
}
}
The code is showing exception as index out of bound refering the line numbers containg int n1 = q-p; and Merge(arr,0,6,12);
Can anyone kindly help me

Length of R[] = r - n2 = 12 - (12 - 6) = 6.
In the last for loop you iterate while i < r, i.e. i < 12. This means that you might try to get indexes 0 - 11 from R[] in the else-statement. This gives you an exception.
for (int i = p; i < r; i++)
{
if (L[k] <= R[k])
{
arr[i] = L[k];
k++;
}
else
{
arr[i] = R[d];
d++;
}
}
The exception fires from arr[i] = R[d].
Edit: Are you sure about your definition of the length of R[]?
int n2 = r - q;
...
int[] R = new int[r-n2]; // this is the same as int[] R = new int[q].

Related

C# Array C with a formula

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]
}

Digit difference sort

So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}

Converting Codility solution to C# (Grocery-store, Hydrogenium 2013)

In order to learn and understand how Dijkstra's algorithm is used to solve the "Grocery Store" ([Hydrogenium 2013]: https://codility.com/programmers/challenges/hydrogenium2013) problem on codility, I'm trying to rewrite the #2, O(n^2) solution(https://codility.com/media/train/solution-grocery-store.pdf) in C#.
1) What language are those solutions written in?
2) What would be the C# equivalent to this bit of code?
G = [[]] *N
for i in xrange(M):
G[A[i]] = G[A[i]] + [(B[i], C[i])]
G[B[i]] = G[B[i]] + [(A[i], C[i])]
This is what I have so far
int[] G = new int[N];
for (int i = 0; i < M; i++)
{
G[A[i]] = G[A[i]];
G[B[i]] = G[B[i]];
}
Thanks in advance,
Gregory
Downloaded IDLE (a python IDE...kind of) and figured it out. It appears to be adding pairs to each array element. Here's the code I came up with if anyone else happens to stumble across the same problem.
private struct nodePair
{
public int node;
public int time;
public nodePair(int node, int time)
{
this.node = node;
this.time = time;
}
}
public int solution(int[] A, int[] B, int[] C, int[] D)
{
int M = A.Length;
int N = D.Length;
//build the graph
List<nodePair>[] G = new List<nodePair>[N];
for (int i = 0; i < N; i++)
{
G[i] = new List<nodePair>();
}
for (int i = 0; i < M; i++)
{
G[A[i]].Add(new nodePair(B[i], C[i]));
G[B[i]].Add(new nodePair(A[i], C[i]));
}
//initialize the distance table
int[] dist = new int[N];
for (int i = 0; i < N; i++)
{
dist[i] = int.MaxValue;
}
bool[] visited = new bool[N];
for (int i = 0; i < N; i++)
{
visited[i] = false;
}
//look for the minimum value
int ii = 0; ;
dist[0] = 0;
for (int k = 0; k < N; k++)
{
int s = int.MaxValue;
//find the minimum
for (int j = 0; j < N; j++)
{
if ((dist[j] < s) && (visited[j] == false))
{
s = dist[j];
ii = j;
}
}
visited[ii] = true;
if (s < D[ii])
{
return s;
}
List<nodePair> thisNodeLIst = G[ii];
foreach (nodePair oneNode in thisNodeLIst)
{
dist[oneNode.node] = Math.Min(dist[oneNode.node], s + oneNode.time);
}
}//for
return -1;
}
}

Merge Sort code is not working and showing exception

public static void Merge(int[] arr,int p,int q,int r )
{
int n1 = q-p;
int n2 = r-q;
int[] L=new int[n1];
int[] R = new int[r-n2];
for (int i = 0; i < n1; i++)
L[i] = arr[i];
foreach (int x in L)
Console.WriteLine(x);
for (int i = 0; i < n2; i++)
R[i] = arr[q+i];
Console.WriteLine("New part");
foreach (int x in R)
Console.WriteLine(x);
int k=0, d=0;
for (int i = p; i < r; i++)
{
if (L[k] <= R[k])
{
arr[i] = L[k];
k++;
}
else
{
arr[i] = R[d];
d++;
}
}
}
The above code shows exception(index out of bound when I call from main() method using Merge(arr,0,0,12). Where arr is an int array of length 12.
You get an Index out of bounds exception in this part:
for (int i = 0; i < n2; i++)
R[i] = arr[q+i];
Your R-array is of size 0, while n2 is defined as 12 with the given arguments.
You array L is declared of size q-p, which are both 0
Both you L and R array are defined as too small
Initialize them like this instead:
int[] L = new int[arr.Length];
int[] R = new int[arr.Length];

How do I get my code to work?

I have a one assignment
I have to make one dimension array with 20 numbers - first 10 numbers are from 1 do 10. others 10 numbers I have to get in method called Dopolni - where I have to sum together array with one another like - p11 = p0+p1, p12 = p1+p2, p14 = p2+p3 and so on - I dont know how to arrange it to get those other 10 numbers - help please
my code till now is
static void Dopolni(int[] p)
{
for (int i = 11; i < 20; i++)
{
p[i] = p[i] + 1;
}
}
static void Main(string[] args)
{
int[] p = new int[20];
for (int i = 1; i < 20; i++)
{
if (i <= 10)
{
p[i] += i;
}
Console.WriteLine("{0}", p[i]);
}
Dopolni(p);
Console.WriteLine(p);
Console.ReadKey(true);
}
All numbers I have to write out in main window. Hope someone can help out
The indices of the first 10 numbers range from 0 to 9, the others from 10 to 19. But since you always sum two consecutive numbers, you will only get 9 sums! In order to get 10 sums, you could start by summing 0 with p[0]:
int previous = 0;
for (int i = 0; i < 10; i++) {
p[i + 10] = previous + p[i];
previous = p[i];
}
public static void Main()
{
int[] p = new int[20];
for (int i = 0; i < 10; i++)
{
p[i] = i + 1;
ยจ
Console.WriteLine(p[i]);
}
Dopolni(p);
}
static void Dopolni(int[] p)
{
for (int i = 10; i < 20; i++)
{
p[i] = p[i - 10] + p[i - 9];
Console.WriteLine(p[i]);
}
}
This looks like trouble:
int[] p = new int[20];
Console.WriteLine(p);
What you want is to loop through p and print each element, not rely on the array implementation of ToString().
Try:
foreach (var n in p)
Console.WriteLine(n);
Do you need to have it in a function? Its really quite simple...
Notice I use 'out int[]', thats what your missing in your code. Out specifies you want in/out param, not just in ;)
static void Main()
{
int[] p = new int[20];
// First 10 numbers
for (int i = 0; i < 10; i++)
p[i] = i + 1;
Dolpini(out p);
foreach (int m in p)
Console.WriteLine(m);
}
static void Dolpini(out int[] numbers)
{
// Next 10 numbers
for (int k = 10; k < 20; k++)
p[k] = p[k-10] + p[k-9];
}

Categories

Resources