Hackerrank Challenge - Completed but don't understand optimal solution - c#

So I've completed the challenge that has the following link:
https://www.hackerrank.com/challenges/crush/problem
With the following code in C#:
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Solution {
// Complete the arrayManipulation function below.
static long arrayManipulation(int n, int[][] queries) {
long[] arr = new long[n];
long count = 0;
long largestValue = long.MinValue;
for (int i = 0; i < queries.Length; ++i)
{
long startIndex = queries[i][0];
long endIndex = queries[i][1];
long numberToAdd = queries[i][2];
for (long j = startIndex - 1; j <= endIndex - 1; ++j)
{
arr[j] += numberToAdd;
}
}
return arr.Max();
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(#System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string[] nm = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nm[0]);
int m = Convert.ToInt32(nm[1]);
int[][] queries = new int[m][];
for (int i = 0; i < m; i++) {
queries[i] = Array.ConvertAll(Console.ReadLine().Split(' '), queriesTemp => Convert.ToInt32(queriesTemp));
}
long result = arrayManipulation(n, queries);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
However, it fails on some test cases as it is not running at its optimal speed. I have read the explanation of how to make it better, but I'm not understanding it. It talks about adding -k to i+1 and prefix sums and... to be honest I feel like a floundering fish with this one. I don't know if someone could potentially help explain or simply the explanation?
The optimal description says:

Related

VB.net C# number and letter generator

I been having issues creating a number and letter generator, it should look like this: 9WJLNN8MNDVJCFLQJ4W93YH6ZM:ZWN6QV9ZXG9YCMWAXXWP492DS9
26 letters and numbers randomly colon and same thing after colon, but I keep getting errors but heres my code from what I got so far
Right now I cant even get the numbers and letters together to make it work, im just so confused on what to do. If anyone can help me out that would be amazing. I've been working on this for a few days now.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml;
namespace Testing23891721983712983981
{
class Program
{
static void Main(string[] args)
{
{
Random rand = new Random();
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
numbers[i] = rand.Next(1000, 10000);
}
string prefix = string.Join("-", numbers);
for (int i = 0; i < 100; i++)
{
int threeDigits = rand.Next(100, 1000);
RandomGenerator generator = new RandomGenerator();
string str = generator.RandomString(26, false);
Console.WriteLine(threeDigits, str);
Console.ReadKey();
}
}
}
public class RandomGenerator
{
// Generate a random number between two numbers
public int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
// Generate a random string with a given size
public string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
// Generate a random password
public string RandomPassword()
{
StringBuilder builder = new StringBuilder();
builder.Append(RandomString(4, true));
builder.Append(RandomNumber(1000, 9999));
builder.Append(RandomString(2, false));
return builder.ToString();
}
}
}
}
use Guid class to generate random numbers with string and then use substring on it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
{
Random rand = new Random();
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
numbers[i] = rand.Next(1000, 10000);
}
string prefix = string.Join("-", numbers);
string strguid = "";
for (int i = 0; i < 2; i++)
{
Guid guid = Guid.NewGuid();
if (strguid != "")
{
strguid = strguid + ":" + guid.ToString().Replace("-", "").Substring(0, 26).ToUpper();
}
else
{
strguid = guid.ToString().Replace("-", "").Substring(0, 26).ToUpper();
}
}
Console.WriteLine(strguid);
Console.ReadKey();
}
}
}
}

How can I pair the contents of this array without repeating itself?

I am trying to make a Secret Santa code, so that upon running the program, it will take all names from the array and pair them.
I've tried numerous ways of doing this but it just ends up repeating an entry already in the output. fOr example:
Fred and Sarah
Yusef and Kyle
Sarah and Fred
Sarah has come up twice which is not good.
Here's the starting code, of course I first randomise the array, but have no clue what to do after that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp27
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
String[] students = {"Fred","Mary","Yusef","Kyle","Sophie", "Lydia", "Max", "Donald","Yasmin","Archie"};
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
}
}
}
Any ideas, can anyone help?
I have also tried this which I thought would work but it returns an error of the index being out of bounds of array
static void Main(string[] args)
{
Random random = new Random();
String[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie" };
int count = 0;
for (int i = 0; i < 5; i++)
{
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
Console.Write("{0} and {1}", shuffleStudents[count], shuffleStudents[count+1]);
for (int j = 0; j < 5; j++)
{
count++;
}
}
Console.Read();
}
}
}
You can try to shuffle them, then print the result. Here's the code I did:
using System;
using System.Linq;
namespace _05_01_19_5am
{
class Program
{
public static void Main()
{
Random random = new Random();
String[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie" };
var shuffleThem = students.OrderBy(s => Guid.NewGuid()).ToArray();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(shuffleThem[i] + " + " + shuffleThem[i+5]);
}
}
}
}
Fiddled around a bit more and found the solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp27
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
string[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie"};
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
Console.WriteLine("Your pairs for Secret Santa has been completed!");
int count = 0;
for (int j = 0; j < 5; j++)
{
Console.Write("{0} and {1} \n", shuffleStudents[count], shuffleStudents[count+1]);
for (int i = 0; i < 2; i++)
{
count++;
}
}
Console.Read();
}
}
}

How to generate the numeric value which is not exist in given numeric array?

I have this method to generate new numeric value but it takes a long time to complete the function.
How to generate random number in fast approch?
public int GeneratenewID(int[] OptionId)
{
Random ran = new Random();
int SearchId = ran.Next(1, OptionId.Length*2);
if (!OptionId.Contains(SearchId))
{
return SearchId;
}
else
{
return GeneratenewID(OptionId);
}
}
this is going to work for sure so try:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int [] OptionId=new int[]
{
0, 1,4,7,3,1,37,9
};
Program p = new Program();
int a= p. GeneratenewID(OptionId);
}
public int GeneratenewID(int[] OptionId)
{
Random ran = new Random(1);
int number = 0;
for (int j = 0; j < OptionId.Length ; j++)
{
number = ran.Next(OptionId.Length);
if (!OptionId.Contains(number))
break;
else
j--;
}
return number;
}
}
}

Getting index is outside bounds of the array

Could someone explain why do I get this out of bounds?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testing
{
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
double[] numbers = new double[] { };
for(int i = 0; i < n; i++)
{
var input = double.Parse(Console.ReadLine());
numbers[i] = input;
}
Console.WriteLine(numbers);
}
}
}
You haven't set the array size
double[] numbers = new double[n]
An array is fixed in length upon initialization. Yours has size 0.
double[] numbers = new double[] { }; // { } is the same as 'initialize with 0 elements or no content'
You need to use a List instead of an Array.
List<double> numbers = new List<double>();
for(int i = 0; i < n; i++)
{
var input = double.Parse(Console.ReadLine());
numbers.Add(input);
}

While cycle and inputs

I have code like this, how can i add 4 more inputs? (5 in total) and program would return the square of them(num*num, dont know how i should be in english, maybe correct?) Thank you very much for your time!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number to get square");
int num = Convert.ToInt16(Console.ReadLine());
int ruut = num * num;
while (num!=1000)
{
Console.WriteLine(ruut);
break;
}
Console.ReadLine();
}
}
}
`
use a for loop and an array. Here's an example in the simplest code possible:
int[] num = new int[5];
for(int i = 0; i < 5; i++)
{
num[i] = Convert.ToInt16(Console.ReadLine());
}
for(int i = 0; i < 5; i++)
{
Console.WriteLine(num[i] * num[i]);
}

Categories

Resources