Program should give to a word special numerical value (but…) - c#

There's a program I wrote in C, it works perfectly. When I tried to translate it into the language C# it was not compiling. The problem was that C# doesn't know the meaning of scanf ("%19s" , string1); like in C.
I changed scanf to:
string read;
do
{
read = Console.ReadLine();
}
while (read.Length <= 19);
it couldn't work properly. then i tried: to change it into:
string string1Input = Console.ReadLine();
It was working better but if statements were not checked because I was getting all "sum"-s equaled to 0.
This is the program written translated into C#:
public static class GlobalMembersAnbanisRicxvitiMnishvneloba
{
static int Main()
{
string string1 = new string(new char[20]);
sbyte a = (sbyte)'a';
sbyte b = (sbyte)'b';
sbyte g = (sbyte)'g';
sbyte X = (sbyte)'X';
sbyte i = (sbyte)'i';
sbyte H = (sbyte)'H';
sbyte V = (sbyte)'V';
etc..
int rigi;
int sum = 0;
int sum2 = 0;
int sum3 = 0;
Console.Write(" my word is:\n");
string string1Input = Console.ReadLine();
for (rigi = 0; string1[rigi] != '\0'; rigi++)
{
if (string1[rigi] == a)
{
sum3 = sum3 + 1;
sum2 = sum2 + 1;
sum = sum + 1;
}
else
if (string1[rigi] == b)
{
sum3 = sum3 + 3;
sum2 = sum2 + 2;
sum = sum + 2;
}
etc...
} /* end for*/
if (string1[rigi-1]==i)
{
sum=sum-10; sum2=sum2-10; sum3=sum3-55;
}
Console.Write("sum is:");
Console.Write("{0:D}\n", sum);
Console.Write("sum2 is:");
Console.Write("{0:D}\n", sum2);
Console.Write("sum");
Console.Write("{0:D}\n", sum3);
return 0;
}
}
The idea of the prog is:
Program gives a numerical meaning to each of the letter of a word we type and adds this numbers to each other.
Question II: how to make
if (string1[rigi-1]==i)
{
sum=sum-10; sum2=sum2-10; sum3=sum3-55;
}
work?

There is no end caracter string in C#, like in C. In fact, string in C, and string in C# are two totally different things, and are not used the same way.
So for loop over a string, the good way is to use a foreach loop.
Change
for (rigi = 0; string1[rigi] != '\0'; rigi++)
By
foreach(var oneCaracter in string1Input)
Then string1[rigi] must become oneCaracter
And sbyte must become char
Sample correction:
char a = 'a';
int sum = 0;
int sum2 = 0;
int sum3 = 0;
string string1Input = Console.ReadLine();
foreach(char oneCaracter in string1Input)
{
if (oneCaracter == a)
{
sum3 = sum3 + 1;
sum2 = sum2 + 1;
sum = sum + 1;
}
}
if (string1Input[string1Input.Length - 1] == i)
{
sum = sum - 10; sum2 = sum2-10; sum3 = sum3-55;
}

Related

Convert oct to dex integer

Incorrectly converts a number
In the program you need to convert from octal number system to decimal
"a" is a integer class field that uses the GetDex() method
Construct - this.a = a;
public int GetDex()
{
int res = 0;
int exp = 1;
for (int i = Convert.ToString(a).Length - 1; i >= 0; i--)
{
res += exp * Convert.ToInt32(Convert.ToString(a)[i]);
exp *= 8;
}
return res;
}
The problem is in the
Convert.ToInt32(Convert.ToString(a)[i])
fragment. You actually add ascii codes, not digits. To get digit integer 5 from character '5' just subtract '0':
(Convert.ToString(a)[i] - '0')
Your code corrected:
public int GetDex()
{
int res = 0;
int exp = 1;
for (int i = Convert.ToString(a).Length - 1; i >= 0; i--)
{
//DONE: you should add digits, not ascii codes: - '0'
res += exp * (Convert.ToString(a)[i] - '0');
exp *= 8;
}
return res;
}
You can put it compact with a help of Linq:
public int GetDex() => a
.ToString()
.Aggregate(0, (s, i) => s * 8 + i - '0');

Find the largest palindrome made from the product of two 3-digit numbers C#

I tried to solve projecteuler 4th project with C# but I don't receive the correct answer, I get 90909. Can someone spot my mistake?
The problem goes like this:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
namespace Largest_palindrome_product{
class Program
{
static void Main(string[] args)
{
string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
int result = 0;
string rev= "hello";
string palindrome = "hello";
string bingo = "hello";
int j = 1;
for (int i = 1; i< 1000; i++)
{
for (int y = 1; y< 1000; y++)
{
result = i * y;
bingo = result.ToString();
rev = Reverse(bingo);
j = int.Parse(bingo);
}
if (rev == bingo)
{
palindrome = bingo;
}
}
Console.Write(palindrome);
Console.Read();
}
}
}
I think what has caused so much confusion is the use of String this just complicates thing having to convert them back and forth.
Your program works fine (if the if is moved as per John's comment) if only you'd checked the new number was larger!
here is my take on it:
// stolen from https://www.geeksforgeeks.org/reverse-digits-integer-overflow-handled/
int Reverse(int num)
{
int rev_num = 0;
while (num > 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
int result = 0;
int palindrome = 0;
int j = 1;
for (int i = 999; i > 0; i--)
{
for (int y = 999; y > 0; y--)
{
result = i * y;
if (result == Reverse(result))
{
if (result > palindrome)
{
palindrome = result;
}
}
}
}
Console.Write(palindrome);
Console.Read();

c#: Project Euler 8. Have some troubles in program

I'm writing a program to solve problem 8 in project Euler, which finds the thirteen adjacent digits in the 1000-digit number that have the greatest product. Firstly, i determine that the 1000-digit number is a string. Then i create a split method that breaks up this string into smaller chars, and converts it to int number. (i use ulong type instead of int)
static ulong split(char input)
{
ulong number = ulong.Parse(Convert.ToString(input));
return number;
}
then i create a method that has ability to check whether what is the biggest product. convert it into int type, find the product of thirteen adjacent digits.
static ulong check(string string1)
{
ulong product = 1;
ulong max = 0;
ulong[] array = new ulong[50];
char[] h1 = string1.ToCharArray();
for (int i = 0; i < string1.Length; i++)
array[i] = split(h1[i]);
for (int i = 0; i < array.Length - 12; i++)
{
for (int j = 0; j < 13; j++)
{
product *= array[i + j]
if (product > max)
max = product;
}
product = 1;
}
return max;
In the main method. i write some code to input the 1000-digit number and write the answer.
string input = #"73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450";
input = input.Replace(" ", "");
input = input.Replace("/r/n", "");
Console.Write(check(input));
Console.ReadKey();
But the program has trouble in the split method. can you explain for me, please ? :(
here is all my program.
string input = #"73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450";
input = input.Replace(" ", "");
input = input.Replace("/r/n", "");
Console.Write(check(input));
Console.ReadKey();
}
static ulong split(char input)
{
ulong number = ulong.Parse(Convert.ToString(input));
return number;
}
static ulong check(string string1)
{
ulong product = 1;
ulong max = 0;
ulong[] array = new ulong[50];
char[] h1 = string1.ToCharArray();
for (int i = 0; i < string1.Length; i++)
array[i] = split(h1[i]);
Console.WriteLine();
for (int i = 0; i < array.Length - 12; i++)
{
for (int j = 0; j < 13; j++)
{
product *= array[i + j];
if (product > max)
{
max = product;
Console.Write(array[i + j] + " ");
}
}
product = 1;
}
return max;
}

Function Anagram

An anagram is a word formed from another by rearranging its letters, using all the original letters exactly once; for example, orchestra can be rearranged into carthorse.
I want to write a function to return all anagrams of a given word (including the word itself) in any order.
For example GetAllAnagrams("abba") should return a collection containing "aabb", "abab", "abba", "baab", "baba", "bbaa".
Any help would be appreciated.
Here is a working function, making use of a GetPermutations() extension found elsewhere on stack overflow
public static List<string> GetAnagrams(string word)
{
HashSet<string> anagrams = new HashSet<string>();
char[] characters = word.ToCharArray();
foreach (IEnumerable<char> permutation in characters.GetPermutations())
{
anagrams.Add(new String(permutation.ToArray()));
}
return anagrams.OrderBy(x => x).ToList();
}
Here is the GetPermutations() extension and it's other necessary extensions:
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> enumerable)
{
var array = enumerable as T[] ?? enumerable.ToArray();
var factorials = Enumerable.Range(0, array.Length + 1)
.Select(Factorial)
.ToArray();
for (var i = 0L; i < factorials[array.Length]; i++)
{
var sequence = GenerateSequence(i, array.Length - 1, factorials);
yield return GeneratePermutation(array, sequence);
}
}
private static IEnumerable<T> GeneratePermutation<T>(T[] array, IReadOnlyList<int> sequence)
{
var clone = (T[])array.Clone();
for (int i = 0; i < clone.Length - 1; i++)
{
Swap(ref clone[i], ref clone[i + sequence[i]]);
}
return clone;
}
private static int[] GenerateSequence(long number, int size, IReadOnlyList<long> factorials)
{
var sequence = new int[size];
for (var j = 0; j < sequence.Length; j++)
{
var facto = factorials[sequence.Length - j];
sequence[j] = (int)(number / facto);
number = (int)(number % facto);
}
return sequence;
}
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
private static long Factorial(int n)
{
long result = n;
for (int i = 1; i < n; i++)
{
result = result * i;
}
return result;
}
}
Here is a screenshot of the result:
And, finally, a github repository of the complete Visual Studio solution: Github
import java.util.Scanner;
import java.lang.String;
public class KrishaAnagram
{
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
String s1, s2;
int sum1, sum2;
sum1 = sum2 = 0;
System.out.print("Enter fisrt string: ");
s1 = Scan.next();
System.out.print("Enter Second string: ");
s2 = Scan.next();
if (s1.length() != s2.length()) {
System.out.println("NOT ANAGRAM");
} else {
for (int i = 0; i < s1.length(); i++) {
char ch1 = s1.charAt(i);
char ch2 = s2.charAt(i);
sum1 += (int) ch1;
sum2 += (int) ch2;
}
if (sum1 == sum2)
System.out.println("IT IS AN ANAGRAM : s1 = " + sum1 + "s1 = " + sum2);
else
System.out.println("IT IS NOT AN ANAGRAM : s1 = " + sum1 + "s1 = " + sum2);;
}
}
}
//This is My way of solving anagram in java,Hope it helps.

Reorder digits in integer using C#

I want to ask how I can reorder the digits in an Int32 so they result in the biggest possible number.
Here is an example which visualizes what I am trying to do:
2927466 -> 9766422
12492771 -> 97742211
I want to perform the ordering of the digits without using the System.Linq namespace and without converting the integer into a string value.
This is what I got so far:
public static int ReorderInt32Digits(int v)
{
int n = Math.Abs(v);
int l = ((int)Math.Log10(n > 0 ? n : 1)) + 1;
int[] d = new int[l];
for (int i = 0; i < l; i++)
{
d[(l - i) - 1] = n % 10;
n /= 10;
}
if (v < 0)
d[0] *= -1;
Array.Sort(d);
Array.Reverse(d);
int h = 0;
for (int i = 0; i < d.Length; i++)
{
int index = d.Length - i - 1;
h += ((int)Math.Pow(10, index)) * d[i];
}
return h;
}
This algorithm works flawlessly but I think it is not very efficient.
I would like to know if there is a way to do the same thing more efficiently and how I could improve my algorithm.
You can use this code:
var digit = 2927466;
String.Join("", digit.ToString().ToCharArray().OrderBy(x => x));
Or
var res = String.Join("", digit.ToString().ToCharArray().OrderByDescending(x => x) );
Not that my answer may or may not be more "efficient", but when I read your code you calculated how many digits there are in your number so you can determine how large to make your array, and then you calculated how to turn your array back into a sorted integer.
It would seem to me that you would want to write your own code that did the sorting part without using built in functionality, which is what my sample does. Plus, I've added the ability to sort in ascending or descending order, which is easy to add in your code too.
UPDATED
The original algorithm sorted the digits, now it sorts the digits so that the end result is the largest or smallest depending on the second parameter passed in. However, when dealing with a negative number the second parameter is treated as opposite.
using System;
public class Program
{
public static void Main()
{
int number1 = 2927466;
int number2 = 12492771;
int number3 = -39284925;
Console.WriteLine(OrderDigits(number1, false));
Console.WriteLine(OrderDigits(number2, true));
Console.WriteLine(OrderDigits(number3, false));
}
private static int OrderDigits(int number, bool asc)
{
// Extract each digit into an array
int[] digits = new int[(int)Math.Floor(Math.Log10(Math.Abs(number)) + 1)];
for (int i = 0; i < digits.Length; i++)
{
digits[i] = number % 10;
number /= 10;
}
// Order the digits
for (int i = 0; i < digits.Length; i++)
{
for (int j = i + 1; j < digits.Length; j++)
{
if ((!asc && digits[j] > digits[i]) ||
(asc && digits[j] < digits[i]))
{
int temp = digits[i];
digits[i] = digits[j];
digits[j] = temp;
}
}
}
// Turn the array of digits back into an integer
int result = 0;
for (int i = digits.Length - 1; i >= 0; i--)
{
result += digits[i] * (int)Math.Pow(10, digits.Length - 1 - i);
}
return result;
}
}
Results:
9766422
11224779
-22345899
See working example here... https://dotnetfiddle.net/RWA4XV
public static int ReorderInt32Digits(int v)
{
var nums = Math.Abs(v).ToString().ToCharArray();
Array.Sort(nums);
bool neg = (v < 0);
if(!neg)
{
Array.Reverse(nums);
}
return int.Parse(new string(nums)) * (neg ? -1 : 1);
}
This code fragment below extracts the digits from variable v. You can modify it to store the digits in an array and sort/reverse.
int v = 2345;
while (v > 0) {
int digit = v % 10;
v = v / 10;
Console.WriteLine(digit);
}
You can use similar logic to reconstruct the number from (sorted) digits: Multiply by 10 and add next digit.
I'm posting this second answer because I think I got the most efficient algorithm of all (thanks for the help Atul) :)
void Main()
{
Console.WriteLine (ReorderInt32Digits2(2927466));
Console.WriteLine (ReorderInt32Digits2(12492771));
Console.WriteLine (ReorderInt32Digits2(-1024));
}
public static int ReorderInt32Digits2(int v)
{
bool neg = (v < 0);
int mult = neg ? -1 : 1;
int result = 0;
var counts = GetDigitCounts(v);
for (int i = 0; i < 10; i++)
{
int idx = neg ? 9 - i : i;
for (int j = 0; j < counts[idx]; j++)
{
result += idx * mult;
mult *= 10;
}
}
return result;
}
// From Atul Sikaria's answer
public static int[] GetDigitCounts(int n)
{
int v = Math.Abs(n);
var result = new int[10];
while (v > 0) {
int digit = v % 10;
v = v / 10;
result[digit]++;
}
return result;
}

Categories