Spoj task Bonus: ARRAYSUB - subarraysZadanie runtime error (NZEC) {c#} - c#

Good morning I ran into a problem because look at the Bonus task: ARRAYSUB - subarrays task
it gives me a runtime error (NZEC) although ideone is not showing any error https://ideone.com/1eiciI Thank you
using System;
using System.Linq;
namespace ConsoleApp17
{
internal class Program
{
private static void Main(string[] args)
{
int n = Convert.ToInt32((Console.ReadLine()));
int k;
int val = 0;
int[] arr = Console.ReadLine().Split().Select(int.Parse).ToArray();
k = Convert.ToInt32((Console.ReadLine()));
for (int i = 0; i < n - k + 1; i++)
{
val = arr[i];
for (int j = i; j < i + k; j++)
{
if (val < arr[j])
{
val = arr[j];
}
}
Console.Write(val + " ");
}
}
}
I try to solve task and get accpeted

That might help u
this type of error - when the program throws an exception. In this task, probably incorrectly loaded input or exceeding the range.
I propose:
int[] arr = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

Related

You can only display 60 characters per line

When running this program, my first line has 62 digits while the other lines only have 60. How can I place 2 spaces in front of the first line so each line of the array is no more then 60 characters? So basically it would look like ( with two spaces in the beginning)
9999999999999999999999999999999999999999999999999999999999
999999999999999999999999999999999999999999999999999999999999
999999999999999999999999999999999999999999999999999999999999
using System;
namespace BigFactorial
{
class Program
{
static int MAX = 5000;
//This is telling the program what to multiply.
private static void mult(int[] x, int n)
{
int y = 0, i, m;
for (i = 0; i < MAX; i++)
{
m = y + x[i] * n;
x[i] = m % 10000;
y = m / 10000;
}
}
//This is telling the program how to calculate factorial of n.
public static void Factorial(int[] a, int n)
{
a[0] = 1;
for (int i = n; i > 1; i--)
{
mult(a, i);
}
}
//This is displaing the factorial after the calculation.
public static void Display(int[] a)
{
int i;
for (i = MAX - 1; a[i] == 0; i--) ;
Console.Write(a[i]);
for (int j = i - 1, c = 1; j >= 0; j--, c++)
{
string s = "" + a[j];
Console.Write(s.PadLeft(4, '0'));
if (c % 15 == 0)
Console.WriteLine();
}
Console.WriteLine();
}
public static void Main(string[] args)
{
while (true)
{
//Telling user to enter a number.
Console.Write("Enter a number to factor or a negative number to quit: ");
int n = int.Parse(Console.ReadLine());
//Quit function
if (n < 0) break;
int[] arr = new int[MAX];
Factorial(arr, n);
Display(arr);
}
//100000 is the max number it can calculate
}
}
}
You have already demonstrated that you know how to use String.PadLeft(), so cache the strings that you are writing in memory so you can inspect them rather than writing directly out to the console.
using System.Linq;
using System.Text;
public static void Display(int[] a)
{
int i = 0;
// build the string in memory, so we can inspect the length of the lines
StringBuilder output = new StringBuilder();
output.Append(a[i]);
for (int j = i - 1, c = 1; j >= 0; j--, c++)
{
output.Append($"{a[j]}".PadLeft(4, '0'));
if (c % 15 == 0)
output.AppendLine();
}
// get the lines into an array so we can normalise the length,
// although we know the length today, calculating it expresses the intent better
var lines = output.ToString().Split(new string [] { Environment.NewLine }, StringSplitOptions.None);
var maxLength = lines.Max(x => x.Length);
// now write the output to the console
foreach(var line in lines)
Console.WriteLine(line.PadLeft(maxLength, ' '));
}
It is not necessary to use StringBuilder like this, you could have used a List<string> and that would simplify the code further. It is however useful to identify that code written targeting the Console can easily be refactored to write to memory via StringBuilder as the syntax is very similar.
You could also have used a StringWriter instance called Console and the syntax would be identical... But that was a step too far for a logic block as simple as this.

Memory error NZEC when using C# on HackerEarth

I am solving a question on HackerEarth. The test case passes successfully, but the rest of the cases show a NZEC error. I know NZEC stands for Non Zero Exit Code but I am not sure why this is happening here.
Any insight about why this happens and how I can optimize my code (preferably without changing the logic) will help.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int t = int.Parse(Console.ReadLine());
int[] arr = new int[3];
for(int m = 0; m < t; m++)
{
arr[m] = int.Parse(Console.ReadLine());
}
for (int n = 0; n < t; n++)
{
int i, j;
for (i = 0; i < arr[n]; i++)
{
for (j = 0; j < 2 * arr[n]; j++)
{
if (j <= i || j >= 2 * arr[n] - 1 - i)
{
Console.Write("*");
}
else
{
Console.Write("#");
}
}
Console.WriteLine("\n");
}
Console.WriteLine("\n");
}
}
}

Any idea why I'm getting a runtime error here?

Doing this problem on HackerRank and my O(n) solution is passing all the test cases besides the last three, which it is failing with a Runtime Error. Unfortunately, I have no way of seeing what the runtime error is. When I run the tests in Visual Studio I get no errors. Any idea what could be causing the problem?
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
public static void Swap(int[] A, int i1, int i2)
{
int temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
}
static void Main(String[] args)
{
int[] parameters = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int n = parameters[0];
int k = parameters[1];
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int[] pos = new int[n + 1]; // pos[m] is the index of the value m in arr
for(int i = 0; i < arr.Length; ++i)
{
pos[arr[i]] = i;
}
for(int i = 0; i < arr.Length && k > 0; ++i, --n)
{
if(arr[i] == n)
continue;
int j = pos[n];
Swap(pos, arr[i], n);
Swap(arr, i, j);
--k;
}
Console.WriteLine(string.Join(" ", arr));
}
}
below partial code is wrong, because user can enter three number such as 15, 20, 22, array.length is 15 but you want access to index 15, 20, 22...
if you want access to these indexes should set length of pos to max number.
for(int i = 0; i < arr.Length; ++i)
{
pos[arr[i]] = i;
}
edit1:
for more guide, please say line of code and message of run time error.

How can define a 26x2 array and then use LINQ on its rows?

Grrrr I have C# and multidimensional arrays. For some reason, coming from a C/C++ background, they really annoy me.
So when I run
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for(int t = 0; t < T; ++t)
{
string str = Console.ReadLine();
if(str.Length % 2 == 1)
{
Console.WriteLine(-1);
continue;
}
int n = str.Length / 2;
// determine how many replacements s1 needs to be an anagram of s2
string s1 = str.Substring(0, n);
string s2 = str.Substring(n, n);
int[][] counter = new int[26][2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a][0] += 1;
counter[(int)s2[i] - ascii_a][1] += 1;
}
int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();
Console.WriteLine(count);
}
}
}
I get
solution.cs(22,42): error CS0029: Cannot implicitly convert type int'
toint[][]' Compilation failed: 1 error(s), 0 warnings
No idea why.
I can change it to
int[,] counter = new int[26,2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a, 0] += 1;
counter[(int)s2[i] - ascii_a, 1] += 1;
}
int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();
but then, of course, my LINQ statement breaks.
If you change
int[][] counter = new int[26][2];
to
int[][] counter = new int[26][];
for (int i = 0; i < counter.Length; i++)
counter[i] = new int[2];
code compiles. You can test the rest as you like. As you haven't provided necessary input in OP.
You can't define jagged array like that:
int[][] counter = new int[26][2];
I recommend reading on jagged arrays:
https://msdn.microsoft.com/en-us/library/2s05feca.aspx
https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
In your case I'd suggest using not jagged, but multi-dimentional array:
var counter = new int[26,2];
What you are using here is a jagged array, and you can't new one like that:
int[][] counter = new int[26][2];
You have to declare the inner array separately :
int[][] counter = new int[26][];
for (int i = 0; i < 26; i++)
{
counter[i] = new int[2];
}
Alternatively, as #IvanStoev suggested, you can also use a LINQ one liner:
var counter = Enumerable.Range(0, 26).Select(_ => new int[2]).ToArray();
You can also use a 2-dimensional array, such as this one :
// notice there is only one bracket
int[,] counter = new int[26,2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a, 0] += 1;
counter[(int)s2[i] - ascii_a, 1] += 1;
}
// and, you will need to update your query,
// as linq would implicitly flatten the array
var count = Enumerable.Range(0, 26)
.Select(x => counter[x, 0] - counter[x, 1])
.Sum();
I would suggest defining a Counter struct then use an array of those instead of a multi-dimensional array.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
struct Counter
{
public int c1;
public int c2;
}
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for (int t = 0; t < T; ++t)
{
string str = Console.ReadLine();
if (str.Length % 2 == 1)
{
Console.WriteLine(-1);
continue;
}
int n = str.Length / 2;
// determine how many replacements s1 needs to be an anagram of s2
string s1 = str.Substring(0, n);
string s2 = str.Substring(n, n);
Counter[] counter = new Counter[26];
int ascii_a = (int)'a';
for (int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a].c1 += 1;
counter[(int)s2[i] - ascii_a].c2 += 1;
}
int count = counter.Select((pair => Math.Abs(pair.c1 - pair.c2))).Sum();
Console.WriteLine(count);
}
}
}

Insertion sort algorithm c#

I am trying to implement the Insertion sort in one of my programs. What I have been trying to create is a sorting program (in both ascending or descending order) However I have tried with algorithms such as quicksort and merge-sort, I am really new to c# and coding. The problem I am facing here is the fact that my files includes both a string of code, as well as a double/integer (example: 75.350, 74.430, Thursday, Friday) and since this algorithm is designed for integers. Is there a way to convert it please?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StreamReader sh1Open = new StreamReader("c:..\\Files\\SH1_Open.txt");
string Sh1OpenString = sh1Open.ReadToEnd();
int[] x = { Convert.ToInt32(Sh1OpenString) };
int j;
int temp;
for (int i = 1; i < x.Length; i++)
{
j = i - 1;
while (j >= 0 && x[j]>x[j+1])
{
temp = x[j];
x[j] = x[j + 1];
x[j + 1] = temp;
j = j - 1;
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
Console.ReadKey();
}
}
}
The best way is probably using generic method with IComparable constraint.
T[] InsertionSort(T[] x) where T : IComparable<T>
{
for (int i = 0; i < x.Length-1; i++)
{
int j = i+1;
while (j>0)
{
if (x[j-1].CompareTo(x[j]) > 1)
{
T temp = x[j-1];
x[j - 1] = x[j];
x[j] = temp;
}
j--;
}
}
return x;
}
or using algorithm from http://www.codecodex.com/wiki/Insertion_sort
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j=j-1;
}
array[j + 1] = value;
}
}
Also, there is probably a bug in this line:
int[] x = { Convert.ToInt32(Sh1OpenString) };
because you're trying to convert whole file to one integer.
Since in C# the comparison operators are defined for strings you could just replace all relevant int variables with string variables. The algorithm should run the same (albeit a bit slower)

Categories

Resources