Where did these numbers come from? - c#

So I have a code here and what I am tring to do is to get max and min value from string("1 2 3 4 5 6 66") and when I tried to make a char array from this string and get from it max and min I am getting 54 as a max and 32 as a min. HOW?
static void Main(string[] args)
{
HighAndLow("1 2 3 4 5 6 66");
}
public static string HighAndLow(string numbers)
{
char[] liczby = numbers.ToArray();
int max = liczby.Max();
int min = liczby.Min();
Console.WriteLine($"{max} {min}");
return $"{max} {min}";
}

You're getting the char codes, not the values.
Change
char[] liczby = numbers.ToArray();
to something like
char[] temp = numbers.Split(' ');
int[] liczby = temp.Select(c => int.parse(c)).ToArray();

Look here
https://www.asciitable.com/
You will see that the character 'c' is decimal 54
and that " " (space) has decimal value 32

using System;
using System.Collections.Generic;
using System.Linq;
namespace stack
{
internal class Program
{
static void Main(string[] args)
{
HighAndLow("1 2 3 4 5 6 66");
}
static string HighAndLow(string numbers)
{
if (numbers.Length > 0)
{
var listnumbers = numbers.Split(' ');
var max = int.MinValue;
var min = int.MaxValue;
foreach (var number in listnumbers)
{
var ent = int.Parse(number);
max = ent <= max ? max : ent;
min = ent >= min ? min : ent;
}
Console.WriteLine("max :"+max+" min: "+min);
return $"{max} {min}";
}
return "empty string";
}
}
}
or just replace :
char[] liczby = numbers.ToArray();
with :
var temp = numbers.Split(' ');
int[] liczby = temp.Select(c => int.Parse(c)).ToArray();

Related

How to separate not separated input C#

The program must sum the even and odd numbers and then multiply them.
The problem comes when I enter the numbers like this 12345.
The array takes the number like 1 element but in order to make my code work it must separate the input when I put it like this 12345.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab_Methods
{
class Program
{
static void Main(string[] args)
{
int[] number = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int even = 0;
int odd = 0;
for (int i = 0; i < number.Length; i++)
{
if (number[i] % 2 == 0)
{
even = even + number[i];
}
else
{
odd = odd + number[i];
}
}
Console.WriteLine(even * odd);
}
}
}
If you want to split on ' ' (space), your input should use delimiter: "1 2 3 4 5"
// Separated input like "1 2 3 45 6 789"
// we don't have to materialize into array
// let's be nice: allow tabulation as well as space,
// tolerate leading/trailing and double spaces: " 1 2 3 "
var numbers = Console
.ReadLine()
.Split(new char[] { ' ', '\t'}, StringSplitOptions.RemoveEmptyEntries) // let's be nice
.Select(item => int.Parse(item));
int even = 0;
int odd = 0;
foreach (var number in numbers) {
if (number % 2 != 0)
odd += number;
else
even += number;
}
Console.WriteLine(even * odd);
If you want to enumerate digits within single number (e.g. within "12345")
// Single number input like "12345678"
var numbers = Console
.ReadLine()
.Where(c => c >= '0' && c <= '9') // characters in '0'..'9' range
.Select(c => c - '0'); // corresponding ints
// Then as usual
int even = 0;
int odd = 0;
foreach (var number in numbers) {
if (number % 2 != 0)
odd += number;
else
even += number;
}
Console.WriteLine(even * odd);
This way you will be able to input numbers from 0 to 9 without having to care about the way they are written:
class Program
{
static void Main(string[] args)
{
int[] numbers = Console.ReadLine().Select(x => {
if(int.TryParse(x.ToString(), out int result))
{
return result;
}
else
{
return -1;
}
}).Where(x => x != -1).ToArray();
int even = 0;
int odd = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] % 2 == 0)
{
even = even + numbers[i];
}
else
{
odd = odd + numbers[i];
}
}
Console.WriteLine(even * odd);
}
}
Input:
12345
Output:
54
Input:
1 2 3 4 5
Output:
54
Input:
1,2,3,4,5
Output:
54
Input:
,1.2 34|5
Output:
54

I want split the number into hundreds, not thousands

When fromatting integer number (e.g. 1234567890) I want groups of size 2 (hundreds), not of size 3 (thousands). I have tried something like this
int number = 1234567890;
string value = string.Format("{0:#,###0}", number);
Desired value:
12,34,56,78,90
Actual value:
1,234,567,890
There can be many logic for doing this. I found following one.
I assume you have string.
static void Main(string[] args)
{
string numbers = "1234567890";
Console.WriteLine(string.Join(",", CustomSplit(numbers, 1)));
Console.WriteLine(string.Join(",", CustomSplit(numbers, 2)));
Console.WriteLine(string.Join(",", CustomSplit(numbers, 3)));
Console.ReadLine();
}
public static List<string> CustomSplit(string Input, int Length)
{
List<string> result = new List<string>();
string[] split = new string[Input.Length / Length + (Input.Length % Length == 0 ? 0 : 1)];
for (int i = 0; i < split.Length; i++)
{
result.Add( Input.Substring(i * Length, i * Length + Length > Input.Length ? 1 : Length));
}
return result;
}
OUTPUT
1,2,3,4,5,6,7,8,9,0
12,34,56,78,90
123,456,789,0
Try this:-
static void Main(string[] args)
{
NumberFormatInfo nfi = new CultureInfo("en-US").NumberFormat;
// Displays a value with the default separator (".").
Int64 myInt = 123456789012345;
Console.WriteLine(myInt.ToString("N", nfi));
// Displays the same value with different groupings.
int[] mySizes1 = { 2, 3, 4 };
int[] mySizes2 = { 2, 2 };
nfi.NumberGroupSizes = mySizes1;
Console.WriteLine(myInt.ToString("N", nfi));
nfi.NumberGroupSizes = mySizes2;
Console.WriteLine(myInt.ToString("N", nfi));
ReadLine();
}
for further info plz refer this link :- https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numbergroupsizes(v=vs.110).aspx

Put numbers from string into int array [duplicate]

This question already has answers here:
Convert string to int array using LINQ [duplicate]
(6 answers)
Closed 7 years ago.
I have lines (string type) of numbers like "23 78 53 4 94 32 148 31". I need to put them into int array. Here's the lame code I wrote, but it doesn't work properly:
int currentArrayValue=0;
int currentChar=0;
for (int i = 0; i < text1.Length; i++)
{
if (text1[i] != ' ')
{
currentChar++;
continue;
}
else
{
for (int k = 1; k <=currentChar; k++)
{
if (k == 1) Array[currentArrayValue] = text1[i - currentChar];
else if (k == 2) Array[currentArrayValue] = text1[i - currentChar] * 10;
else if (k == 3) Array[currentArrayValue] = text1[i - currentChar] * 100;
}
currentArrayValue++;
}
}
It can be a one-, two- or three-digit number.
There are several ways to achieve what you want as the other answers point out. If you want a bit of safety checking then I'd use TryParse:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var test = "1 2 3 x";
var values = test.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
var results = new List<int>();
foreach(var value in values)
{
int x;
if(Int32.TryParse(value, out x))
{
results.Add(x);
}
else
{
Console.WriteLine("{0} is not an integer", value);
}
}
}
}
So if you have a string as such and all the numbers are separated by spaces
string foo = "12 34 567 120 12";
All you have to do is use string.Split(' ') to break this string into an array then convert those values to int values.
int[] intArray = foo.Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
string input = "23 78 53 4 94 32 148 31";
var arr = Regex.Matches(input, #"\d+").Cast<Match>().Select(m => int.Parse(m.Value)).ToArray();
Use string.Split instead. You can split on each space and get an array. From there, parse each item to an int. You can actually do it all in one line with LINQ.
int[] myInts = text1.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => int.Parse(s)).ToArray();
Non-Linq answer
const string inputVal = "23 78 53 4 94 32 148 31";
string[] splitInput = inputVal.Split(' ');
int[] inputIntArray = new int[splitInput.Length];
int counter = 0;
foreach (string split in splitInput){
inputIntArray[counter++] = int.Parse(split);
}

Reverse binary representation of int (only significant bits)

I'm trying to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11 right?
Here's my code:
static void Main(string[] args)
{
Console.WriteLine("Enter a Number");
int numb = int.Parse(Console.ReadLine());
int reverse = 0;
while (numb > 0)
{
int rem = numb % 10;
reverse = (reverse * 10) + rem;
numb = numb / 10;
}
Console.WriteLine("Reverse number={0}", reverse);
Console.ReadLine();
}
By this code I only get the numbers to reverse (13 -> 31)...
The input should contain a single line with an integer N, 1≤N≤1000000000 and I want my output in one line with one integer, the number I want to get by reversing the binary representation of N.
Something like that
// 13 = 1101b
int value = 13;
// 11 = 1011b
int result = Convert.ToInt32(new String(
Convert.ToString(value, 2)
.Reverse()
.ToArray()), 2);
Explanation:
Convert.ToString(value, 2) returns value in binary representation ("1101")
Reverse().ToArray() - reverse the string ('1','0','1','1') as sequence of characters and converts to array char[].
new String(...) constructs string "1011" from array of char
finally, Convert.ToInt32(..., 2) convert binary representation back to int
You can use Convert.ToString and Convert.ToInt32 methods, where 2 means binary:
int numb = int.Parse(Console.ReadLine());
var reversedString = Convert.ToString(numb, 2).ReverseString();
var result = Convert.ToInt32(reversedString, 2);
...
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
A fun excercise would be doing this without using the string conversion.
I have very little experience with bit twiddling so there is probably a faster and better way of doing this, but this seems to work:
public static IEnumerable<bool> ToBinary(this int n)
{
for (int i = 0; i < 32; i++)
{
yield return (n & (1 << i)) != 0;
}
}
public static int ToInt(this IEnumerable<bool> b)
{
var n = 0;
var counter = 0;
foreach (var i in b.Trim().Take(32))
{
n = n | (i ? 1 : 0) << counter;
counter++
}
return n;
}
private static IEnumerable<bool> Trim(this IEnumerable<bool> list)
{
bool trim = true;
foreach (var i in list)
{
if (i)
{
trim = false;
}
if (!trim)
{
yield return i;
}
}
}
And now you'd call it like this:
var reversed = n.ToBinary().Reverse().ToInt();

Pass in a long number and return an array of all the digits and the count of each digit

For instance, if the input is set to 1234, the program will return 11213141 because digit 1 occurs once, digit 2 occurs once ... so on and so forth.
Another example: 142225 => 11234151
My program works fine with small input but if the input has 10 digits or more, the result would make no sense. Please help.
class Example
{
// Get sorted(ascending) list for each digit in num
public static List<int> GetList(long num)
{
List<int> listOfInts = new List<int>();
while (num > 0)
{
int remainder = (int) num % 10;
listOfInts.Add(remainder);
num = num / 10;
}
listOfInts.Sort();
return listOfInts;
}
// Get minimum digit in the list
public static int getMinimumInt(List<int> l)
{
int min = 10;
foreach (int s in l)
{
if (s <= min)
{
min = s;
}
}
return min;
}
// Get count of the minimum digit specified
public static int getCount(int i,List<int> l)
{
int count = 0;
foreach (int s in l)
{
if (s == i)
{
count++;
}
}
return count;
}
public static void Main()
{
long input = 1234567891020; // Arbituary input
// initialize
List<int> outputList=new List<int>(); // List that would be eventually outputted
List<int> listOfInt = new List<int>();
listOfInt = GetList(input);
//Loop end till no element left in listOfInt
while ((listOfInt.ToArray()).Length!=0)
{
int item = getMinimumInt(listOfInt);
int count = getCount(item, listOfInt);
outputList.Add(item); // Add the item to be counted
outputList.Add(count); // Add count of the item
listOfInt.RemoveRange(0, count); // Remove digits that have been counted
}
// Output the list
foreach (int i in outputList)
{
Console.Write(i);
}
Console.WriteLine();
Console.ReadLine();
}
}
}
In your GetList() function, you are casting your 10+ digit long to an integer:
int remainder = (int) num % 10;
Attempting to place a 10+ digit number into an int means you are running up against the highest value of 32-bit integers, which is 2,147,483,647. That would explain why your results seem strange.
Use a long instead. If that isn't enough you can try System.Numerics.BigInteger, which will allow you to add more digits to it until you run out of memory.
You can use this LINQ approach, it doesn't care about numbers, just chars:
string output = String.Concat(input
.GroupBy(c => c)
.Select(g => String.Format("{0}{1}", g.Key, g.Count())));
If you want the result as long use long.TryParse(output, out longvariable).
int sourceVal = 12341231;
string sourceStr = sourceVal.ToString();
List<char> uniqueChars = null;
#if LINQ
uniqueChars = sourceStr.ToCharArray().Distinct().ToList();
#else
uniqueChars = new List<char>();
foreach (char c in sourceStr)
if (!uniqueChars.Contains(c))
uniqueChars.Add(c);
#endif
string result = "";
foreach (var wantedChar in uniqueChars)
#if LINQ
result += wantedChar.ToString() + (sourceStr.Count(f => f == wantedChar)).ToString();
#else
result += wantedChar.ToString() + (sourceStr.Split(wantedChar).Length - 1).ToString();
#endif
Console.WriteLine("Result = " + result);
This was my code to keep it as similar to yours. If you want to limit the count, use a modulus on the end (% 10) to keep the count to a single digit.
Having now seen the other Linq answer, I think that is a lot neater. Given that your maximum answer would be something like 192,939,495,969,798,999 if sorted in character order ascending, you would need a long not an int to store that.
Just change
int remainder = (int) num % 10;
to
int remainder = (int)(num % 10);
The first one is casting num to int then doing the mod 10. This will result in overflow when num is larger than int.MaxValue, typically a negative number. The second does the mod 10 first then the cast, which is safe as the mod will result in a value that can easily fit into an int.

Categories

Resources