How do I get my code to work? - c#

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

Related

Sums not being calculated right

Hi i am trying to calculate the sums of the submatrix of order K from a matrix of order M, but I am getting wrong result from the sums matrix. In my head the logic makes sense, I don't know what the mistake is.
static void Main(string[] args)
{
Console.WriteLine("Shkruani te madhesine e matrices dhe madhesine e submatrices: ");
int M;
int K;
int sum = 0;
M = int.Parse(Console.ReadLine());
K = int.Parse(Console.ReadLine());
int[] sums = new int[M - K + 1];
int[] matrix = new int[M];
Console.WriteLine("Shkruani vlerat e matrices: ");
foreach (int i in matrix)
{
matrix[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i <= M - K; i++)
{
for (int j = 0; j < K; j++)
{
sum += matrix[i + j];
}
sums[i] = sum;
sum = 0;
}
for (int i = 0; i < (M - K + 1); i++)
{
Console.WriteLine(sums[i]);
}
Console.ReadKey();
}
Instead of using
foreach (int i in matrix)
{
matrix[i] = int.Parse(Console.ReadLine());
}
Use this:
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = int.Parse(Console.ReadLine());
}
Explanation:
Because For-Each loop works with value (iterate through value) instead of index (May be what you want) while for loop works with index (iterate through index).
Hope this helps.
Thank you.

Matrix smallest number

So this code should work, but i cant figure out the problem.
It worked me once before... But now i only get back 0 as a result.
I know it should be obvious but i cant see it.
namespace ConsoleApp5
{
class Program
{
private static void Main(string[] args)
{Console.WriteLine("The SmallestNumber in the given matrix is : {0}", SmallestNumber());
Console.ReadKey();
}
public static int SmallestNumber()
{
int n = 10;
int m = 10;
int[,] TempMatrix = new int[n, m];
Random r = new Random();
int smallest = TempMatrix[0,0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
TempMatrix[i, j] = r.Next(10, 3000);
if (smallest > TempMatrix[i,j])
{
smallest = TempMatrix[i, j];
}
Console.WriteLine(string.Format("{0}\t", TempMatrix[i, j]));
}
}
return smallest;
}
}
}
When you initialize smallest, TempMatrix[0,0] has the value 0. All the random numbers you generate are between 10 and 3000, so all the numbers in the matrix are greater than smallest, since it is 0.
Setting smallest initially to int.MaxValue should solve the problem.

How would you create n nested loops for math?

So, I am trying to wrap my head around understanding how you can use a variable to denote how many times a loop is nested.
Here is an example I write up to simulate the output of dimensions = 4:
static void Main(string[] args)
{
int dimensions = 4; // e.g. for (1, 2, 3, 4), dimensions = 4
Console.WriteLine($"{addNumbers(dimensions)}");
Console.ReadKey();
}
static long addNumbers(int dimensions)
{
long number = 0;
// hard coded to be dimensions = 4
for (int h = 0; h <= dimensions; h++)
for (int i = 0; i <= dimensions; i++)
for (int j = 0; j <= dimensions; j++)
for (int k = 0; k <= dimensions; k++)
number += h + i + j + k; // just some random math
return number;
}
This will present the expected output of:
5000
So to readdress the problem, how can I code to allow this for n dimensions? Thanks for your help!
For arbitrary n dimensions you can loop with a help of array int[] address which represents n dimensions:
static long addNumbers(int dimensions) {
int[] address = new int[dimensions];
// size of each dimension; not necessary equals to dimensions
// + 1 : in your code, int the loops you have i <= dimensions, j <= dimensions etc.
int size = dimensions + 1;
long number = 0;
do {
//TODO: some math here
// i == address[0]; j = address[1]; ... etc.
number += address.Sum();
// next address: adding 1 to array
for (int i = 0; i < address.Length; ++i) {
if (address[i] >= size - 1)
address[i] = 0;
else {
address[i] += 1;
break;
}
}
}
while (!address.All(index => index == 0)); // all 0 address - items're exhausted
return number;
}
Finally, let's add some Linq to look at the results:
int upTo = 5;
string report = string.Join(Environment.NewLine, Enumerable
.Range(1, upTo)
.Select(i => $"{i} -> {addNumbers(i),6}"));
Console.Write(report);
Outcome:
1 -> 1
2 -> 18
3 -> 288
4 -> 5000 // <- We've got it: 5000 for 4 dimensions
5 -> 97200

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 + " ");
}
}
}

Mergesort code not working [duplicate]

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

Categories

Resources