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.
Related
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();
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 + " ");
}
}
}
This question already has an answer here:
Creating all possible arrays without nested for loops [closed]
(1 answer)
Closed 6 years ago.
I posted this similar, previous question, but I was not very clear.
I have the following code:
int N=4;
int[] myArray = new int[N];
for (int i1 = 1; i1 < N; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < N; i2++)
myArray[1]=i2;
for (int i3 = 1; i3 < N; i3++)
myArray[2]=i3;
for (int i4 = 1; i4 < N; i4++)
{
myArray[3]=i4;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
This outputs the following:
1111
1112
1113
1121
1122
1123
1131
....
3332
3333
Is there a simple way to change this nested for loop to recursion? I am not very skilled at programming, so the simpler, the better. I am not worried about how efficient the code is.
I, effectively, would like to be able to change the int N in my code to different numbers, without having to add or remove anything from my code.
EDIT
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
int class_length = 4;
int[] toric_class = Enumerable.Repeat(1, class_length).ToArray();
Recursion(toric_class, class_length, 1, 3);
Console.Read();
}
static void Recursion(int[] toric_class, int length, int number, int spot)
{
if (number < 4)
{
toric_class[spot] = number;
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
Recursion(toric_class, length, number + 1, spot);
}
}
}
}
This only outputs
1111
1112
1113
I am unsure of where to go from here.
public static void Set(int[] array, int index, int N)
{
if (index == N)
{
foreach (var item in array)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
return;
}
for (int i = 1; i < N; i++)
{
array[index] = i;
Set(array, index + 1, N);
}
}
And call it this way:
int N = 4;
int[] myArray = new int[N];
Set(myArray, 0, N);
If you want just to simplify and generalize the solition, you don't want any recursion:
// N - length of the array
// K - kind of radix; items of the array will be in [1..K] range
private static IEnumerable<int[]> Generator(int N = 4, int K = 3) {
int[] items = Enumerable
.Repeat(1, N)
.ToArray();
do {
yield return items.ToArray(); // .ToArray() : let's return a copy of the array
for (int i = N - 1; i >= 0; --i)
if (items[i] < K) {
items[i] += 1;
break;
}
else
items[i] = 1;
}
while (!items.All(item => item == 1));
}
Test
string test = string.Join(Environment.NewLine, Generator(4)
.Select(items => string.Concat(items)));
Console.Write(test);
Outcome:
1111
1112
1113
1121
1122
...
3321
3322
3323
3331
3332
3333
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);
}
}
}
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];
}