C
C#2y ago
wcasa

troubles with list length

class Solution
{
static void Main(string[] args)
{
string line = Console.ReadLine();
string[] temp = line.Split(' ');
List<int> nums = new List<int>(temp.Length);
for (int i = 0; i < temp.Length; i++)
{
nums[i] = Convert.ToInt32(temp[i]);
}
nums.Sort();
Console.WriteLine($"Наименьшее значение = {nums[0]}");
Console.WriteLine($"Наибольшее значение = {nums[nums.Count - 1]}");
}
}
class Solution
{
static void Main(string[] args)
{
string line = Console.ReadLine();
string[] temp = line.Split(' ');
List<int> nums = new List<int>(temp.Length);
for (int i = 0; i < temp.Length; i++)
{
nums[i] = Convert.ToInt32(temp[i]);
}
nums.Sort();
Console.WriteLine($"Наименьшее значение = {nums[0]}");
Console.WriteLine($"Наибольшее значение = {nums[nums.Count - 1]}");
}
}
38 Replies
wcasa
wcasa2y ago
i wanna get input from user which contains line of numbers, than convert those numbers into list<int>, sort it, so that i could find min and max value what is wrong with this?
Angius
Angius2y ago
You don't need to give the list an initial size And use .Add() to add elements to it
wcasa
wcasa2y ago
but why doesnt my method work?
MODiX
MODiX2y ago
Retax#0813
REPL Result: Failure
new List<int>(99)[0]
new List<int>(99)[0]
Exception: ArgumentOutOfRangeException
- Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
- Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
Compile: 410.056ms | Execution: 23.683ms | React with ❌ to remove this embed.
Angius
Angius2y ago
Because you set the size of the list But it doesn't actually have anything inside So you can't set those things
wcasa
wcasa2y ago
wai what
Angius
Angius2y ago
You say "there will be 70 boxes in the truck" But there are no boxes
Anton
Anton2y ago
the constructor sets the capacity, not the count
Angius
Angius2y ago
So you can't put a thing in the 7th box
wcasa
wcasa2y ago
that kinda sucks
Angius
Angius2y ago
No, why?
hime
hime2y ago
The initial capacity you set does not mean there are actually values (like say, 0) in there yet, the internal array is set to that size, but it doesn't let you access it directly unless you actually added it
wcasa
wcasa2y ago
i thought c# would fill it with 0s or nulls would be convinient
Angius
Angius2y ago
Makes things easier for you, though. No need for messing with the index and stuff
wcasa
wcasa2y ago
i thought it would be slightly slower than assigning with index
Angius
Angius2y ago
Not in any way that would matter
wcasa
wcasa2y ago
wait but why would you set size in the first place
hime
hime2y ago
Sure, if you are adding 1 million items/second it might be 10ms slower
Anton
Anton2y ago
var list = Enumerable.Repeat(default(Type), 99).ToList(); I'd probably use something like this
Angius
Angius2y ago
When the list reaches capacity and you add one more element, the list gets doubled in size That costs some performance
Anton
Anton2y ago
only as an optimization
Angius
Angius2y ago
Telling the list what size to expect causes it to not have to double the capacity It's a minor optimization
wcasa
wcasa2y ago
ohhh so, even if i create list of 70 numbers, list.add, than it will add into [0] index, not in [70]th index?
Anton
Anton2y ago
yes
Angius
Angius2y ago
Yeah
wcasa
wcasa2y ago
pretty cool than thanks!
Anton
Anton2y ago
and you can't change the count of a list without adding elements until that count reaches the value you need as far as I know
wcasa
wcasa2y ago
that makes sense
Angius
Angius2y ago
So you can rewrite
for (int i = 0; i < temp.Length; i++)
{
nums[i] = Convert.ToInt32(temp[i]);
}
for (int i = 0; i < temp.Length; i++)
{
nums[i] = Convert.ToInt32(temp[i]);
}
into just
foreach (var t in temp)
{
nums.Add(int.Parse(t));
}
foreach (var t in temp)
{
nums.Add(int.Parse(t));
}
Anton
Anton2y ago
this allocates more memory probably but yeah that method is as bad as adding 99 zeros in a loop but there's no other way you can do this with the default list implementation
wcasa
wcasa2y ago
btw, is there something better than this?
Angius
Angius2y ago
LINQ
var nums = temp.Select(int.Parse).ToList();
var nums = temp.Select(int.Parse).ToList();
wcasa
wcasa2y ago
instead of writing all of this
string line = Console.ReadLine();
string[] temp = line.Split(' ');
List<int> nums = new List<int>(temp.Length);
for (int i = 0; i < temp.Length; i++)
foreach (var t in temp)
{
nums.Add(int.Parse(t));
}
string line = Console.ReadLine();
string[] temp = line.Split(' ');
List<int> nums = new List<int>(temp.Length);
for (int i = 0; i < temp.Length; i++)
foreach (var t in temp)
{
nums.Add(int.Parse(t));
}
nah, i mean right from the string to list<int> nums
Angius
Angius2y ago
var nums = Console.ReadLine().Split(' ')
.Select(int.Parse)
.ToList();
var nums = Console.ReadLine().Split(' ')
.Select(int.Parse)
.ToList();
wcasa
wcasa2y ago
without spliting it into array -> converting to list
Angius
Angius2y ago
Ah You can only really take text as input So you will need to split it, and you will need to parse it
wcasa
wcasa2y ago
jesus that sucks so badly
Angius
Angius2y ago
Eh, you can always write some simple helper methods
public static class Input
{
public static bool TryGetInt(out int? number)
{
if (int.TryParse(Console.ReadLine(), out var num))
{
number = num;
return true;
}
number = null;
return false;
}
}
public static class Input
{
public static bool TryGetInt(out int? number)
{
if (int.TryParse(Console.ReadLine(), out var num))
{
number = num;
return true;
}
number = null;
return false;
}
}
if (Input.TryGetInt(out var num))
{
Console.WriteLine($"Your number is {num}");
}
else
{
Console.WriteLine("Not a number");
}
if (Input.TryGetInt(out var num))
{
Console.WriteLine($"Your number is {num}");
}
else
{
Console.WriteLine("Not a number");
}
Or some such
Want results from more Discord servers?
Add your server
More Posts
❔ When does the IDisposable objects gets automatically disposed ?```cs public bool Method() { bool result = false; using(var disposableClass = new DisposableClas❔ i need some help with this please the dash is not workingprivate bool canDash = true; private bool isDashing; private float dashingPower = 24f; p❔ How DI works?Been using dependency injection to share variables between classes a lot lately, and it got me wonde❔ How put specific UserControl to ContentControl baseing on DataContext.In https://www.codeproject.com/articles/1118762/generic-wpf-crud-control-getting-started project we ❔ How can I make an instantiated object move?I'm trying to make an object spawned with the instantiate function move, but I can't get it to work.❔ How to input a reference of a class into a function with an argument of an interface` I want to save the result of whatever StartFight does to fighter1 and fighter 2, specifically the ❔ File IO Question.Is there anyway to empty a json file? I know you can delete the file but is there anyway to empty al✅ Need assistance compiling an older dotnet appI'm attempting to compile the latest version of the "Loki" character editor Valheim for my kids and❔ Websocket connection fails, however a javascript websocket can connect to server fineI am using `System.Net.WebSockets` to create a websocket client to a websocket server I am running. ❔ Can not figure out a way to make my code repeat until you type a valid inputim having a hard time figuring out how to make my code repeat until you enter a number and if you en