I try this:
public static int sum(List<int> list)
{
int sum = 0;
foreach (var item in list)
{
sum = item + sum;
}
return sum;
}
public static int sumAbsolute(List<int> list)
{
foreach (var item in list)
{
Math.Abs(item);
}
return sum(list);
}
and the in the main function:
static void Main(string[] args)
{
var list = new List<int>() {
-1,-2,-3
};
Console.WriteLine(sumAbsolute(list));
Console.ReadKey();
}
But the output is -6 and not 6.
So why doesn't my code work?
In short: because Math.Abs(item) returns an int that you dont use:
If you really want to replace all ints in the list, you could do:
for(int i = 0; i < list.Length; i++)
{
list[i] = Math.Abs(list[i]);
}
or with LINQ, this also doesn't need to modify the list:
public static int SumAbsolute(IEnumerable<int> list)
{
return list.Select(Math.Abs).Sum();
}
Related
i'm trying to solve project euler's third problem but it seems that the compiler skips a for loop so it makes my code totally useless
note : the idea didn't show any syntax error
here's the code :
class Program
{
static void Main(string[] args)
{
const long n = 600851475143;
List<long> factors = new List<long>();
factors = getFactors(Math.Sqrt(n));
long max = 0;
for (int i = 0; i<factors.Count ;i++)//this loop in particular , it doesn't print the "testing.."
{
Console.WriteLine("test....");
if(isPrime(getFactors(factors[i])))
{
max = factors[i];
}
}
Console.ReadKey();
}
static List<long> getFactors(double number)
{
List<long> list = new List<long>();
for(int i = 2;i<=number;i++)
{
if(number%i ==0)
{
list.Add(i);
}
}
return list;
}
static bool isPrime(List<long> list)
{
if(list.Count == 2)
{
return true;
}
else
{
return false;
}
}
}
static List<long> getFactors(double number)
{
List<long> list = new List<long>();
for (int i = 2; i <= number; i++)
{
if (Math.Floor(number % i) == 0)
{
list.Add(i);
}
}
return list;
}
number is a fraction, it will never == 0 unless its cast to an int
I have here this code to create ID Randome when calling and then add to the ArrayList, but I want to check if I already have same ID to dont added to ArrayList I have used BinarySearch to check Result
but it look there Something wrong
public delegate void DESetUp();
public static DESetUp IdSetUP = delegate ()
{
ArrayList valID = new ArrayList();
Func<int> getID = () => new Random().Next(1, 5);
int Result = getID();
if (Result == valID.BinarySearch(Result))
{
valID.Add(Result);
Console.WriteLine("AddSuccessful");
}
else
{
Console.WriteLine("AddFailed");
}
foreach (var item in valID)
{
Console.WriteLine("your id is : {0}", item);
}
};
Thank you
try this:
use List instead of ArrayList:
Always you need to sort the values with BinarySearch
List<int> valID = new List<int>();
Func<int> getID = () => new Random().Next(1, 10);
int Result = getID();
// here need to sort the list
valID.Sort();
if (valID.BinarySearch(Result) < 0) // if the position of value is lles than zero the value does not exists
{
valID.Add(Result);
Console.WriteLine("AddSuccessful");
}
else
{
Console.WriteLine("AddFailed");
}
i have reached a great result
i have assisted delegate List
public class MainClass
{
//assist delegate List<int>
public delegate void DESetUp(List<int> DLint);
//assist delegate List<int>
public static DESetUp IdSetUP = delegate (List<int> valID)
{
Func<int> getID = () => new Random().Next(1, 3);
int Result = getID();
// here need to sort the list
valID.Sort();
if (valID.BinarySearch(Result) < 0) // if the position of value is lles than zero the value does not exists
{
valID.Add(Result);
Console.WriteLine("AddSuccessful");
}
else
{
Console.WriteLine("AddFailed");
}
foreach (int item in valID)
{
Console.WriteLine(item);
}
};
static void Main(string[] args)
{
//assist List<int> ID
List<int> ID = new List<int>();
//ADD delegate + List<int> + IdSetUP
IdSetUP(ID);
IdSetUP(ID);
IdSetUP(ID);
IdSetUP(ID);
}
}
thank you all
I making a application with compression mechanism and need my own Dictionary. Every cicle in my app, It adds new element into a myDictionary and update(add a char to some previous elements in myDictionary ). I was doing it with normal list and Quicksort function, but it was really slow. I'm searching for some new methods how to do this but SortedList, Dictionary or LookUp doesnt seems like what I looking for. Is it better to make my own SortedList or is too hard/complex to manage?
Some of the code:
public class MyDictionary
{
private List<string> Contexts;
private List<string> Contents;
private int Count; //words count
//Konstruktor
public MyDictionary()
{
Count = 0;
Contexts = new List<string>();
Contents = new List<string>();
}
region Public Functions
public void AddChar(char ch, int contentSize)
{
for (int i = 0; i < Count; i++)
{
if (Contents[i].Length < contentSize)
{
Contents[i] = Contents[i] + ch;
}
}
}
public void Add(string context, string content)
{
Contexts.Add(Reverse(context)); //otočený kontext
Contents.Add(content);
Count++;
}
public void update()
{
quicksort(Contexts, Contents, 0, Count-1);
}
private void quicksort(List<String> context, List<String> content, int left, int right)
{
int i = left, j = right;
string pivot = context[(left + right) / 2];
while (i <= j)
{
while (context[i].CompareTo(pivot) < 0)
{
i++;
}
while (context[j].CompareTo(pivot) > 0)
{
j--;
}
if (i <= j)
{
swap(i,j);
i++;
j--;
}
}
// Recursive calls
if (left < j)
{
quicksort(context, content, left, j);
}
if (i < right)
{
quicksort(context, content, i, right);
}
}
private static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
Here is a class that acts like a SortedDictionary, but can hold multiple values with the same key. You may need to flesh it out a little bit, with methods like Remove, and adding support for your own IComparer<TKey> if you need them. LINQPad file
public class SortedMultiValue<TKey, TValue> : IEnumerable<TValue>
{
private SortedDictionary<TKey, List<TValue>> _data;
public SortedMultiValue()
{
_data = new SortedDictionary<TKey, System.Collections.Generic.List<TValue>>();
}
public void Clear()
{
_data.Clear();
}
public void Add(TKey key, TValue value)
{
if (!_data.TryGetValue(key, out List<TValue> items))
{
items = new List<TValue>();
_data.Add(key, items);
}
items.Add(value);
}
public IEnumerable<TValue> Get(TKey key)
{
if (_data.TryGetValue(key, out List<TValue> items))
{
return items;
}
throw new KeyNotFoundException();
}
public IEnumerator<TValue> GetEnumerator()
{
return CreateEnumerable().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return CreateEnumerable().GetEnumerator();
}
IEnumerable<TValue> CreateEnumerable()
{
foreach (IEnumerable<TValue> values in _data.Values)
{
foreach (TValue value in values)
{
yield return value;
}
}
}
}
You can use it like this:
var data = new SortedMultiValue<string, string>();
data.Add("Dog", "Buddy");
data.Add("Dog", "Mr. Peanutbutter");
data.Add("cat", "Charlie");
data.Add("cat", "Sam");
data.Add("cat", "Leo");
foreach (string item in data)
{
Console.WriteLine(item);
}
Console.WriteLine();
foreach (string item in data.Get("cat"))
{
Console.WriteLine(item);
}
Console.WriteLine();
foreach (string item in data.Get("Dog"))
{
Console.WriteLine(item);
}
It produces this as the output (notice that the first group of names is sorted by the key they were inserted with):
Charlie
Sam
Leo
Buddy
Mr. Peanutbutter
Charlie
Sam
Leo
Buddy
Mr. Peanutbutter
I need an int array, from an int value.
The int value 123456 converts to int[] {1,2,3,4,5,6}.
Is there any better solution than this:
using System.Diagnostics;
namespace test
{
#if DEBUG
[DebuggerDisplay("{GetDebuggerDisplay()}")]
#endif
public class IntArray
{
#if DEBUG
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
private int _value;
#if DEBUG
[DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)]
#endif
private int[] _valueArray;
public IntArray(int intValue)
{
Value = intValue;
}
public int Value
{
get { return _value; }
set
{
_value = value;
_valueArray = null;
_valueArray = CreateIntArray(value);
}
}
public int[] Array
{
get { return _valueArray; }
}
private string GetDebuggerDisplay()
{
return string.Format("Value = {0}", Value);
}
private static int[] CreateIntArray(int value)
{
string s = value.ToString();
var intArray = new int[s.Length];
for (int i = 0; i < s.Length; i++)
intArray[i] = int.Parse(s[i].ToString());
return intArray;
}
}
}
Any help and criticism would be appreciated.
You can do as following using Linq. This is only the making of the array from the int value.
var arrayOfInts = myint.ToString().Select(i => int.Parse(i.ToString())).ToArray();
EDIT :
This can also be made as a extension method on int if you want to use this often.
public static class IntExtensions
{
public static int[] ToArray(this int i)
{
return i.ToString().Select(c => int.Parse(c.ToString())).ToArray();
}
}
Then you can use this extension by doing this :
var myArray = 123456.ToArray();
You may convert to int to String, later you can use LINQ to Convert each character to integer and then return an array of integers using .ToArray()
int a = 123456;
string tempA = a.ToString();
int[] temp = tempA.Select(r => Convert.ToInt32(r.ToString())).ToArray();
EDIT:
As per Styxxy comment:
int a = 123456;
int[] array = new int[a.ToString().Length];
int i = array.Length - 1;
while (a > 0)
{
array[i--] = a % 10;
a = a / 10;
}
Another approach:
public static int[] GetInts(this int value)
{
if (value == 0)
return new int[] { 0 };
else
{
int val = value;
List<int> values = new List<int>();
while (Math.Abs(val) >= 1)
{
values.Add(Math.Abs(val % 10));
val = val / 10;
}
values.Reverse();
return values.ToArray();
}
}
and use it:
int value = 123456;
int[] values = value.GetInts();
Edit: improved to work with negative numbers and zero
var res = 123456.ToString().Select(c => Int32.Parse(c.ToString())).ToArray();
Another way using char.GetNumericValue:
int[] ints = 123456.ToString().Select(c => (int)char.GetNumericValue(c)).ToArray();
or without Linq:
var chars = 123456.ToString();
int[] ints = new int[chars.Length];
for (int i = 0; i < chars.Length; i++)
ints[i] = (int)char.GetNumericValue(chars[i]);
As said in the comments, it is better to use basic arithmetic operations, rather than converting to a string, looping through a string and parsing strings to integers.
Here is an example (I made an extension method for an integer):
static class IntegerExtensions
{
public static int[] ToCypherArray(this int value)
{
var cyphers = new List<int>();
do
{
cyphers.Add(value % 10);
value = value / 10;
} while (value != 0);
cyphers.Reverse();
return cyphers.ToArray();
}
}
class Program
{
static void Main(string[] args)
{
int myNumber = 123456789;
int[] cypherArray = myNumber.ToCypherArray();
Array.ForEach(cypherArray, (i) => Console.WriteLine(i));
Console.ReadLine();
}
}
How to create dynamic incrementing variable using "for" loop in C#? like this:
track_1, track_2, track_3, track_4. so on.
You can't create dynamically-named variables. All you can do - it to create some collection or array, and operate with it.
I think the best class for you is generic List<>:
List<String> listWithDynamic = new List<String>();
for (int i = 1; i < limit; i +=1)
{
listWithDynamic.Add(string.Format("track_{0}", i));
...
}
Assuming you want strings:
for (int i = 1; i < limit; i +=1)
{
string track = string.Format("track_{0}", i);
...
}
But when you already have variables called track_1, track_2, track_3, track_4 you will need an array or List:
var tracks = new TrackType[] { track_1, track_2, track_3, track_4 } ;
for (int i = 0; i < tracks.length; i++)
{
var track = tracks[i]; // tracks[0] == track_1
...
}
Obvious Solution
for (var i = 0; i < 10; i++)
{
var track = string.Format("track_{0}", i);
}
Linq-Based Solution
foreach (var track in Enumerable.Range(0, 100).Select(x => string.Format("track_{0}", x)))
{
}
Operator-Based Solution This is somewhat hacky, but fun none-the-less.
for (var i = new Frob(0, "track_{0}"); i < 100; i++)
{
Console.WriteLine(i.ValueDescription);
}
struct Frob
{
public int Value { get; private set; }
public string ValueDescription { get; private set; }
private string _format;
public Frob(int value, string format)
: this()
{
Value = value;
ValueDescription = string.Format(format, value);
_format = format;
}
public static Frob operator ++(Frob value)
{
return new Frob(value.Value + 1, value._format);
}
public static Frob operator --(Frob value)
{
return new Frob(value.Value - 1, value._format);
}
public static implicit operator int(Frob value)
{
return value.Value;
}
public static implicit operator string(Frob value)
{
return value.ValueDescription;
}
public override bool Equals(object obj)
{
if (obj is Frob)
{
return ((Frob)obj).Value == Value;
}
else if (obj is string)
{
return ((string)obj) == ValueDescription;
}
else if (obj is int)
{
return ((int)obj) == Value;
}
else
{
return base.Equals(obj);
}
}
public override int GetHashCode()
{
return Value;
}
public override string ToString()
{
return ValueDescription;
}
}
don't know if I get your question, but I will try:
for(var i = 1; i < yourExclusiveUpperbound; i++)
{
var track = String.Format("$track_{0}", i);
// use track
}
or with some LINQ-Magic:
foreach(var track in Enumerate.Range(1, count)
.Select(i => String.Format("$track_{0}", i)))
{
// use track
}
Do as follow:
for (int i = 0; i < lenght; i ++)
{
any work do in loop
}
No, we can't create dynamically named variables in a loop. But, there are other elegant ways to address the problem instead of creating dynamically named variables.
One could be, create an array or list before the loop and store values in array / list items in the loop. You can access the array / list later anywhere in your code. If you know which variable you want to use (track_1, track_2, ...), you can simply access it from the array / list (tracks[1], tracks[2], ...).
List<String> tracks = new List<String>();
for (int i = 1; i < limit; i++)
{
Track track = new Track();
tracks.Add(track);
...
}