Finding the highest pair in int array [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a dice game, where I need to find the highest pair of 5 dices and get the total of it.
I have made this code so far which counts the numbers into pairs. Now I want to find the highest pair.
Code:
int Pair[];
Pair = new int[7] {0, 0, 0, 0, 0, 0, 0} //Seven pairs because i dont want to use Pair[0]
int TT[];
TT = new int[5] { 1, 6, 3, 1, 3 }; //five dice
int t = 1;
for(int i = 0; i < 5; i++)
{
if ( TT[i] == t)
{
Pair[t] = Pair[t] + 1;
t = t + 1;
}
}

If I understand your problem correctly, I think you are overcomplicating it. If you think about it, what you want are the two highest numbers from an arry. Simply sort it, and reverse it, and take the two first numbers.
class Program
{
static void Main(string[] args)
{
int[] Dice = new int[5] { 1, 6, 3, 1, 3 };
Array.Sort(Dice);
Array.Reverse(Dice);
Console.WriteLine("The largest pair is ({0}, {1})", Dice[0], Dice[1]);
}
}
The other possibility for the largets pair (as mentioned in a comment) is that you want to find the highest number in the list that occurs twice. You can do this by sorting the Array, reversing it, so you read from the highest number. Then incrementally check if the current number matches the next number, and if this is the case, you found the highest pair.
class Program
{
static void Main(string[] args)
{
int[] Dice = new int[5] { 1, 6, 3, 1, 3 };
Array.Sort(Dice);
Array.Reverse(Dice);
for (int i = 1; i < Dice.Length; i++)
{
if (Dice[i] == Dice[i - 1])
{
Console.WriteLine("The largest pair is ({0}, {1})", Dice[i], Dice[i-1]);
break;
}
}
}
}

Related

For loop with ref array in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
how does this loop work that i get the result of 11, 2, 13, 4, 15?
What i mean is to explain how one number enters the for loop and what happens
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5 };
fun1(ref arr);
Console.ReadLine();
}
static void fun1 (ref int[] array)
{
for (int i = 0; i < array.Length; i = i + 2)
{
array[i] = array[i] + 10;
}
Console.WriteLine(string.Join(",", array));
}
}
You loop statement
for (int i = 0; i < array.Length; i = i + 2)
Assuming array's length is 5, your loop variable i starts from 0. It them gets incremented by 2 every iteration. This is because you have defined the expression i = i+2. So i go from 0 -> 2 -> 4, when it gets to 6, it doesn't enter the loop.
Thus, you only access the odd elements of the array

Missing number -n to n [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
There is a number N (i.e., N = 3).
I create an array from -N to N (i.e. {-3, -2, -1, 0, 1, 2, 3})
I randomly remove a number from the array (i.e. {-3, -2, 0, 1, 2, 3}, removed -1)
I shuffle the Array (i.e. {-2, 0, 2, 3, -3, 1})
Write a function
public int FindMissing(int[] arr)
That takes the shuffled Array from the initial steps and identifies and returns the array's missing number.
I've done it like this, but I think I did it wrong:
public partial class findMissingNumber
{
public static int FindMissing(int[] arr, int N)
{
int summ = (N - 1) * N / 2;
int sumarr = 1;
for (int i = 1; i < arr.Length; i++)
{
sumarr += arr[i];
}
return summ - sumarr;
}
public static void Main()
{
Console.WriteLine(FindMissing(new int[] { -2, 0, 2, 3, -3, 1 }, 3));
Console.ReadLine();
}
}
The sum of all the numbers in an array [-N, N] is 0.
If an element is missing it'll be 0 minus the missing number.
If 1 is missing, sum = 0 - 1, therefore the missing number is -sum. Except when 0 is missing.
With LINQ is very easy:
using System.Linq;
class findMissingNumber
{
public static int FindMissing(int[] arr)
{
return (arr.Contains(0)) ? -arr.Sum() : 0;
}
public static void Main()
{
Console.WriteLine(FindMissing(new int[] { -2, 2, 1, 3, -3, -1 }));
}
}
Of course if you know that the array will always miss a number you don't even need to check if 0 is missing and it all boils down to -arr.Sum()
Without LINQ is a little longer, but works in the same way:
public static int FindMissing(int[] arr)
{
int sum = 0;
if (Array.FindIndex(arr, x => x == 0) < 0)
return 0;
Array.ForEach(arr, x => sum += x);
return -sum;
}
Again, if you know that an element will alwas be missing, you can avoid looking for zero
I used lambdas, but you can write your predicate as you like https://zetcode.com/csharp/predicate/

List items calculation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have a list / array of integers, i.e:
{1, 2, 3, 4}
Is there a way to get every single possible combination of additions and add them to another list / array?
Like this:
1+2, 1+3, 1+4,
2+3, 2+4,
3+4,
1+2+3, 1+2+4, 1+3+4,
2+3+4,
1+2+3+4
So the end-result would be (without duplicates):
{3, 4, 5, 6, 7, 8, 9, 10}
With more specific to int list you can do that
static List<int> GetCombination(List<int> list, List<int> combinations, int sumNum, bool addNumberToResult = false)
{
if (list.Count == 0) {
return combinations;
}
int tmp;
for (int i = 0; i <= list.Count - 1; i++) {
tmp = sumNum + list[i];
if(addNumberToResult){
combinations.Add(tmp);
}
List<int> tmp_list = new List<int>(list);
tmp_list.RemoveAt(i);
GetCombination(tmp_list,combinations,tmp, true);
}
return combinations;
}
and to call it simply do
List<int> numbers = new List<int>(){1,2,3,4,5};
List<int> possibleCombination = GetCombination(numbers, new List<int>(), 0);
and to remove duplicate
possibleCombination.Distinct()
If you want it orderer you can call
possibleCombination.Distinct().OrderBy(itm => itm)
or
possibleCombination.Distinct().OrderByDescending(itm => itm)
C# fiddle
Edit : As Pierre rightly pointed out, the code did not stick to the question, I corrected accordingly, adding an parameters for adding or not the numbers to the result list.
Based on this great answer here is a version that will allow you to eliminate the "small subset"(*)
public static List<List<T>> GetCombination<T>(List<T> inputList, int minimumItems = 1)
{
int count = (int)Math.Pow(2, inputList.Count) - 1;
List<List<T>> result = new List<List<T>>(count + 1);
if (minimumItems == 0)
result.Add(new List<T>());
for (int i = 1; i <= count; i++)
{
List<T> combinason = new List<T>(inputList.Count);
for (int j = 0; j < inputList.Count; j++)
{
if ((i >> j & 1) == 1)
combinason.Add(inputList[j]);
}
if (combinason.Count >= minimumItems)
result.Add(combinason);
}
return result;
}
Result:
>> { {1,2}, {1,3}, {2,3}, {1,2,3}, {1,4}, {2,4},
>> {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4} }
From here a simple .Sum() on the subset:
Subsets.ForEach( s => result.Add(s.Sum()) );
As you wanted to clear every duplicate in the list:
DoublonList.Distinct();
C# fiddle
ps: (*) Can't find the word in english for groupe of only one element

In c#, how can i rotate a list a specific amount of places?

I wrote a code to rotate a list a specific amount of places, the code I have below works but i would like to know if there is a more efficient way to do this.
public void Test8(List<int> items, int places)
{
int nums;
for (int i = 0; i < places; i++)
{
nums = items[items.Count() - 1];
items.RemoveAt(items.Count - 1);
items.Insert(0, nums);
}
}
This is a classic computer science problem. One technique that's slightly faster is to reverse the entire array, then reverse the two chunks of the array:
// If we want to shift two places, start with an array
[1, 2, 3, 4, 5, 6, 7, 8]
// Then reverse the entire array
[8, 7, 6, 5, 4, 3, 2, 1]
// Then reverse the first n elements, two in our case
[7, 8, 6, 5, 4, 3, 2, 1]
^^^^
// Then reverse the remaining items
[7, 8, 1, 2, 3, 4, 5, 6]
^^^^^^^^^^^^^^^^
Or, as code:
static void Reverse(List<int> items, int posFrom, int posTo)
{
// Helper to reverse a sub portion of an array in place
while (posFrom < posTo)
{
// Swap the first and last items
int temp = items[posFrom];
items[posFrom] = items[posTo];
items[posTo] = temp;
// Shrink down to the next pair of items
--posTo;
++posFrom;
}
}
static void Test8(List<int> items, int places)
{
// Sanity, if we try to rotate more than there are
// items in the array, it just loops around
places %= items.Count;
// Reverse the entire array
Reverse(items, 0, items.Count - 1);
// Reverse the first group of items
Reverse(items, 0, places - 1);
// Reverse the second group of items
Reverse(items, places, items.Count - 1);
}
This is O(n) time, irregardless of the shift size.
It can be faster if you implement it using Circular Array QUEUE (which theoritically have better memory management than the list). This does not need physically rotating the existing data, so it should be faster than your original code.
BTW, you can read other references in StackOverflow to enrich your knowledge, for ex:
Easiest way to Rotate a List in c#
Performance differences... so dramatic?
You are inserting and removing list elements. There is some overhead associated with that. A list can be accessed by index. You can therefore loop through the list, moving elements to the position they should be in. You will need to use a temporary integer variable to avoid overwriting any list data.
Also good to check and make sure the rotation isn't nonsensical, i.e. rotating a list of length 3 right 5K by removing and adding items 5K times doesn't make sense, you can do that by doing something like places%=items.Count; before you start rotating.
Here is a similar question:
C# Collection - Order by an element (Rotate)
Also, try this:
static void Main(string[] args)
{
var items = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var rotatedItems = Rotate(items, 4);
// rotated is now {5, 6, 7, 8, 9, 1, 2, 3, 4}
Console.WriteLine(string.Join(", ", rotatedItems));
Console.Read();
}
public static IEnumerable<int> Rotate(IEnumerable<int> items, int places)
{
return items.Skip(places).Concat(items.Take(places));
}
You can write a user defined extension of List<int> that does the rotation by using List<T>.Reverse().
I took the basic idea from the C++ Standard Template Library which basically uses Reverse in three steps:
Reverse(first, mid)
Reverse(mid, last)
Reverse(first, last)
As far as I know, this is the most efficient and fastest way. I tested with 1 billion elements and the rotation Rotate(0, 50000, 800000) takes 0.00097 seconds.
(By the way: adding 1 billion ints to the List already takes 7.3 seconds)
Here's the extension you can use:
public static class Extensions
{
public static void Rotate(this List<int> me, int first, int mid, int last)
{
//indexes are zero based!
if (first >= mid || mid >= lastIndex)
return;
me.Reverse(first, mid - first + 1);
me.Reverse(mid + 1, last - mid);
me.Reverse(first, last - first + 1);
}
}
The usage is like:
static void Main(string[] args)
{
List<int> iList = new List<int>{0,1,2,3,4,5,6,7,8,9};
Console.WriteLine("Before rotate:");
foreach (var item in iList)
{
Console.Write(item + " ");
}
Console.WriteLine();
int firstIndex = 0, midIndex = 3, lastIndex = 5;
iList.Rotate(firstIndex, midIndex, lastIndex);
Console.WriteLine($"After rotate {firstIndex}, {midIndex}, {lastIndex}:");
foreach (var item in iList)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
Circular Right-Shift Array with specified number of times in ArrayList.
Specified Range of array elements and circular shift.
become faster code as compare with array implementation
Code
using System;
using System.Collections;
public class Program
{
// Circular Array repeting logic in ArrayList
public static ArrayList CircularshiftArry(ArrayList a, int circularrep)
{
int I = 1;
while (I <= circularrep)
{
int n = a.Count;
a.Insert(0, a[n - I]);
I++;
}
return a;
}
public static void Main()
{
Console.WriteLine("ENTER HOW MANY CIRCULAR REPETATION YOU WANT");
int circularrep = int.Parse(Console.ReadLine());
ArrayList a = new ArrayList();
Console.WriteLine("HOW MANY ARRAY ELEMENTS YOU WANT TO ENTER");
int num = int.Parse(Console.ReadLine());
for (int i = 0; i < num; i++)
{
Console.WriteLine("ENTER ARRAY ELEMENTS:{0}", i);
int p = int.Parse(Console.ReadLine());
a.Add(p);
}
Console.WriteLine("\n");
Console.WriteLine("The enterd array is :");
for (int i = 0; i < num; i++)
{
Console.Write("{0}\t", a[i]);
}
ArrayList b = CircularshiftArry(a, circularrep);
Console.WriteLine("\n");
int N = b.Count;
Console.WriteLine("The {0}times circular shifted array is :", circularrep);
for (int i = 0; i < N - circularrep; i++)
{
Console.Write("{0}\t", b[i]);
}
Console.ReadLine();
}
}
This is the output in console window

Convert string to char error message [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Cannot convert string to char error message. I am trying to be able to write a program that will, for example, allow the user to input 1800HIETHC and it will give them back all digits.
I am already stuck.... Any help or advise on what to do?
static void Main(string[] args)
{
char number = ' ';
int numb = 0;
Console.WriteLine("Please enter the telephone number...");
number = Console.ReadLine();
while (number <= 10)
{
if (number == 'A')
{
numb = 2;
}
}
Console.WriteLine(numb);
}
}
}
Console.ReadLine gives you a string
a string is, among other things, a collection of chars
try this
string number = "";
int numb = 0;
Console.WriteLine("Please enter the telephone number...");
number = Console.ReadLine();
for(int i=0; i<number.Count; i++)
{
if (number[i] == 'A')
{
//...
}
}
Console.ReadLine() returns a string not a character. So you cannot assign it to the variable number.
Once you have assigned it to a string you can get characters out of the string by doing myString[0]
If I understand you correctly,
string number = "1800HIETHC"; //Console.ReadLine() reads whole line, not a single char.
int[] nums = Digits(number);
static int[] Digits(string number)
{
return number.Where(char.IsLetterOrDigit).Select(ToNum).ToArray();
}
static int ToNum(char c)
{
int[] nums = { 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9 };
if (char.IsDigit(c)) return c - '0';
c = char.ToUpper(c);
return nums[c - 'A'];
}

Categories

Resources