Special Counters - c#

I`m trying to create a special counter in C# ... I mean the counter will be consisting of characters not numbers.
I have a char[] of size 3:
char[] str = new char[strSize];
int i = 0;
int tmpSize = strSize - 1;
int curr;
while(!isEqual(str,finalStr,strSize))
{
str[strSize] = element[i % element.Length];
i++;
if (str[strSize] == element[element.Length - 1])
{
int j = strSize - 1;
if (j > 0)
{
j--;
int tmpCntr = j+1;
curr = getCurrentID(str[tmpCntr]);
str[tmpCntr] = element[(curr + 1) % element.Length];
while (str[tmpCntr] == element[0] && (i % element.Length > 0) && tmpCntr < 0)
{
tmpCntr--;
curr = getCurrentID(str[tmpCntr]);
str[tmpCntr] = element[(curr + 1) % element.Length];
}
}
}
}
if the strSize < 3 the application works fine and gives accurate output. If the strSize >= 3, the application goes in infinite loop!
Need help.
if this is hard this way, I would need a way to create a numerical counter and I`ll work on it to suite my application.

You haven't shown what half of your methods or parameters are.
Personally I would take a different approach. I would use an iterator block to make it easy to return an IEnumerable<string>, and internally just keep an integer counter. Then you just need to write a method to convert a counter value and "alphabet of digits" into a string. Something like this:
public static IEnumerable<string> Counter(string digits, int digitCount)
{
long max = (long) Math.Pow(digits.Length, digitCount);
for (long i = 0; i < max; i++)
{
yield return ConvertToString(i, digits, digitCount);
}
}
Another alternative is to do the same thing with LINQ, if a range of int is enough:
public static IEnumerable<string> Counter(string digits, int digitCount)
{
int max = (int) Math.Pow(digits.Length, digitCount);
return Enumerable.Range(0, max)
.Select(i => ConvertToString(i, digits, digitCount));
}
In either case, you just iterate over the returned sequence to get appropriate counter values.
With those in place, you just need to implement ConvertToString - which would probably be something like this:
public static string ConvertToString(long value, string digits, int digitCount)
{
char[] chars = new char[digitCount];
for (int i = digitCount - 1 ; i >= 0; i--)
{
chars[i] = digits[(int)(value % digits.Length)];
value = value / digits.Length;
}
return new string(chars);
}
Here's a test program showing it all working:
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main()
{
// Show the first 10 values
foreach (string value in Counter("ABCD", 3).Take(10))
{
Console.WriteLine(value);
}
}
public static IEnumerable<string> Counter(string digits, int digitCount)
{
long max = (long) Math.Pow(digits.Length, digitCount);
for (long i = 0; i < max; i++)
{
yield return ConvertToString(i, digits, digitCount);
}
}
public static string ConvertToString(long value,
string digits,
int digitCount)
{
char[] chars = new char[digitCount];
for (int i = digitCount - 1 ; i >= 0; i--)
{
chars[i] = digits[(int)(value % digits.Length)];
value = value / digits.Length;
}
return new string(chars);
}
}
Output:
AAA
AAB
AAC
AAD
ABA
ABB
ABC
ABD
ACA
ACB

Related

I wrote a program to get the count of matching adjacent alphabets in a string

For the same 1 of the test cases have passed while all the other had failed. The failed ones test cases were of very long strings. but could not understand where did I go wrong.
The number of test cases and string is been read in the main function, and string gets passed to this function.
public static int getMaxScore(string jewels)
{
string temp=jewels;
int count=0;
for(int i=0;i<temp.Length-1;i++)
{
for(int j=i;j<temp.Length-1;j++)
{
if(jewels[i]==jewels[j+1])
{
temp=jewels.Remove(i,2);
count++;
}
else
{
continue;
}
}
}
return count;
}
for the passed 1, there were 2 test cases. In that, one being jewels="abcddcbd" and the other being "abcd". Expected Output was 3 for the first string and 0 for the second. however, i got the expected output for this test case. but failed all other ones(those are very long strings)
jewels="edmamjboxwzfjsgnmycuutvkhzerdiabcvzlnoazreuavyemxqwgyzdvrzyohamwamziqvdduequyyspfipvigooyqmwllvp"
Can somebody help me in knowing what is wrong in my code or how can I obtain the result I want?
Thanks in Advance!!!
Sounds a Jewel Quest puzzle. Checking a string for adjacent equal characters, remove them and increase the counter by 1. Removing the two characters from the string could produce a new one with adjacent equal characters so it must be checked again from the beginning to remove them, increase the counter, and do it all over again until no more.
public static int getMaxScore(string jewels)
{
var count = 0;
var max = jewels.Length;
var i = 0;
var chars = jewels.ToList();
var adj = 2; //<- Change to increase the number of adjacent chars.
while (i < max)
{
if (chars.Count >= adj && i <= chars.Count - adj &&
chars.Skip(i).Take(adj).Distinct().Count() == 1)
{
count++;
chars.RemoveRange(i, adj);
max = chars.Count;
i = 0;
}
else
i++;
}
return count;
}
Testing:
void TheCaller()
{
Console.WriteLine(getMaxScore("abcddcbd"));
Console.WriteLine(getMaxScore("abcd"));
Console.WriteLine(getMaxScore("edmamjboxwzfjsgnmycuutvkhzerdiabcvzlnoazreuavyemxqwgyzdvrzyohamwamziqvdduequyyspfipvigooyqmwllvp"));
}
Writes 3, 0, and 5 respectively.
public static int CountThings(string s)
{
if(s.Length < 2) { return 0; }
int n = 0;
for (int i = 0; i < s.Length - 1; i++)
{
if (s[i] == s[i + 1])
{
int start = i;
int end = i + 1;
while (s[start] == s[end] && start >= 0 && end <= s.Length - 1)
{
n++;
start--;
end++;
}
}
}
return n;
}
For grits and shins, here's a compact recursive version:
static void Main(string[] args)
{
string jewels = "edmamjboxwzfjsgnmycuutvkhzerdiabcvzlnoazreuavyemxqwgyzdvrzyohamwamziqvdduequyyspfipvigooyqmwllvp";
int score = getMaxScore(new StringBuilder(jewels));
Console.WriteLine($"jewels = {jewels}");
Console.WriteLine($"score = {score}");
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}
static int getMaxScore(StringBuilder jewels)
{
for(int i=0; i<(jewels.Length-1); i++)
if (jewels[i]==jewels[i+1])
return 1 + getMaxScore(jewels.Remove(i, 2));
return 0;
}

How do I get rid of circular numbers in my list

Okay, I know that this code is crude, and all around a messy, but I am no programmer, so bear with me. I have this code that lists a bunch of numbers, but I want it to not list any circular copies of the numbers.
For example, if the number 111262 is on my list, I don't want 112621, 126211, 262111, 621112, or 211126 to be listed.
Sorry, that number cannot be on the list.
For a true example, if the number 111252 is on my list, I don't want 112521, 125211, 252111, 521112, or 211125 to be listed.
Any help is appreciated!
namespace Toric_Classes
{
class Program
{
static void Main(string[] args)
{
int number_of_perms=0;
bool badsubsum1;
bool badsubsum2;
int subsum1 = 0;
int subsum2 = 0;
int sum = 0;
int class_length=6;
int[] toric_class=new int[class_length];
// The nested for loops scroll through every possible number of length class_length, where each digit can have a value of 1,2,..., or class_length-1
// Each number is looked at as an array, and is not stored anywhere, only printed if it satisfies certain conditions
for(int i1=1; i1<class_length; i1++)
{
toric_class[0] = i1;
for (int i2 = 1; i2 < class_length; i2++)
{
toric_class[1] = i2;
for (int i3 = 1; i3 < class_length; i3++)
{
toric_class[2] = i3;
for (int i4 = 1; i4 < class_length; i4++)
{
toric_class[3] = i4;
for (int i5 = 1; i5 < class_length; i5++)
{
toric_class[4] = i5;
for (int i6 = 1; i6 < class_length; i6++)
{
badsubsum1 = false;
badsubsum2 = false;
toric_class[5] = i6;
// Find the value of the sum of the digits of our array.
// We only want numbers that have a total digit sum being a multiple of class_length
for (int k = 0; k < class_length; k++)
{
sum += toric_class[k];
}
// The follwong two nested loops find the value of every contiguous subsum of our number, but not the total subsum.
// We *do not* want any subsum to be a multiple of class_length.
// That is, if our number is, say, 121342, we want to find 1+2, 1+2+1, 1+2+1+3, 1+2+1+3+4, 2+1, 2+1+3, 2+1+3+4, 2+1+3+4+2, 1+3, 1+3+4, 1+3+4+2, 3+4, 3+4+2, and 4+2
// The following checks 1+2, 1+2+1, 1+2+1+3, 1+2+1+3+4, 2+1, 2+1+3, 2+1+3+4, 1+3, 1+3+4, and 3+4
for (int i = 0; i < class_length - 1; i++)
{
for (int j = i + 1; j < class_length - 1; j++)
{
for (int k = i; k < j; k++)
{
subsum1 += toric_class[k];
}
if (subsum1 % class_length == 0)
{
badsubsum1 = true;
break;
}
subsum1 = 0;
}
}
// The following checks 2+1, 2+1+3, 2+1+3+4, 2+1+3+4+2, 1+3, 1+3+4, 1+3+4+2, 3+4, 3+4+2, and 4+2
for (int i = 1; i < class_length; i++)
{
for (int j = i + 1; j < class_length; j++)
{
for (int k = i; k < j; k++)
{
subsum2 += toric_class[k];
}
if (subsum2 % class_length == 0)
{
badsubsum2 = true;
break;
}
subsum2 = 0;
}
}
// We only want numbers that satisfies the following conditions
if (sum % class_length == 0 && badsubsum1 == false && badsubsum2 == false)
{
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
number_of_perms++;
}
sum = 0;
subsum1 = 0;
subsum2 = 0;
}
}
}
}
}
}
Console.WriteLine("Number of Permuatations: "+number_of_perms);
Console.Read();
}
}
}
EDIT
To clarify, I am creating a list of all numbers with length n that satisfy certain conditions. Consider the number d1d2...dn, where each di is a digit of our number. Each di may have value 1,2,...,n. Our number is in the list if it satisfies the following
The sum of all the digits is a multiple of n, that is,
d1+d2+...+dn = 0 mod n
Every contiguous subsum of the digits is not a multiple of n, aside from the total sum, that is, if i !=1 and j != n, then
di+d(i+1)+...+dj != 0 mod n
I should mention again that a "number" does not strictly use the numbers 0-9 in its digits. It may take any value between 1 and n. In my code, I am using the case where n=6.
The code works by creating an array of length class_length (in the code above, I use class_length=6). We first have 6 nested for loops that simply assign values to the array toric_class. The first for assigns toric_class[0], the second for assigns toric_class[1], and so on. In the first go around, we are generating the array 111111, then 111112, up to 111115, then 111121, etc. So essentially, we are looking at all heximal numbers that do not include 0. Once we reach our sixth value in our array, we check the array toric_class and check its values to ensure that it satisfies the above conditions. If it does, we simply print the array in a line, and move on.
Here is my easy and inefficient way that should work with minimal changes to your code. It requires shared string list var strList = new List<string>(); to store the used numbers. Then this part:
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
number_of_perms++;
becomes something like this:
string strItem = " " + string.Join(" ", toric_class) + " "; // Example: int[] {1, 12, 123} becomes " 1 12 123 "
if (!strList.Any(str => str.Contains(strItem))) // Example: if " 1 12 123 1 12 123 " contains " 1 12 123 "
{
Console.WriteLine(strItem);
strItem += strItem.Substring(1); // double the string, but keep only one space between them
strList.Add(strItem);
}
number_of_perms++; // not sure if this should be in the if statement
The idea is that for example the string " 1 1 1 2 5 2 1 1 1 2 5 2 " contains all circular copies of the numbers {1, 1, 1, 2, 5, 2}. I used string as a lazy way to check if array contains sub-array, but you can use similar approach to store copy of the used numbers in a list of arrays new List<int[]>() and check if any of the arrays in the list is circular copy of the current array, or even better HashSet<int[]>() approach similar to #slavanap's answer.
The first version of my answer was the easiest, but it works only with array of single digit items.
List is almost the same as array (new List<string>() instead of new string[]), but makes it much easier and efficient to add items to it. For example {1,2}.Add(3) becomes {1,2,3}.
str => str.Contains(strItem) is shortcut for a function that accepts parameter str and returns the result of str.Contains(strItem). That "function" is then passed to the .Any LINQ extension, so
strList.Any(str => str.Contains(strItem))
is shortcut for something like this:
foreach(string str in strList)
{
if (str.Contains(strItem))
{
return true;
}
}
return false;
The following method:
private static List<int> GetCircularEquivalents(int value)
{
var circularList = new List<int>();
var valueString = value.ToString();
var length = valueString.Length - 1;
for (var i = 0; i < length; i++)
{
valueString = valueString.Substring(1, length) + valueString.Substring(0, 1);
circularList.Add(int.Parse(valueString));
}
return circularList;
}
will return a list of the circular numbers derived from the input value. Using your example, this method can be called like this:
var circularList = GetCircularEquivalents(111262);
var dirtyList = new List<int> { 1, 112621, 2, 126211, 3, 262111, 4, 621112, 5, 211126, 6 };
var cleanList = dirtyList.Except(circularList).ToList();
which would result in a cleanList made up of the numbers 1 through 6, i.e. the dirtyList with all the circular numbers derived from 111262 removed.
That's where OOP really benefits. Comments inlined.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3 {
struct MyInt : IEquatable<MyInt> {
private int _value;
public MyInt(int value) {
_value = value;
}
// make it look like int
static public implicit operator MyInt(int value) {
return new MyInt(value);
}
public static explicit operator int(MyInt instance) {
return instance._value;
}
// main difference in these 3 methods
private int GetDigitsNum() {
int temp, res;
for (res = 0, temp = Math.Abs(_value); temp > 0; ++res, temp /= 10);
return res;
}
public bool Equals(MyInt other) {
int digits = other.GetDigitsNum();
if (digits != this.GetDigitsNum())
return false;
int temp = other._value;
// prepare mul used in shifts
int mul = 1;
for (int i = 0; i < digits - 1; ++i)
mul *= 10;
// compare
for (int i = 0; i < digits; ++i) {
if (temp == _value)
return true;
// ROR
int t = temp % 10;
temp = temp / 10 + t * mul;
}
return false;
}
public override int GetHashCode() {
// hash code must be equal for "equal" items,
// that's why use a sum of digits.
int sum = 0;
for (int temp = _value; temp > 0; temp /= 10)
sum += temp % 10;
return sum;
}
// be consistent
public override bool Equals(object obj) {
return (obj is MyInt) ? Equals((MyInt)obj) : false;
}
public override string ToString() {
return _value.ToString();
}
}
class Program {
static void Main(string[] args) {
List<MyInt> list = new List<MyInt> { 112621, 126211, 262111, 621112, 211126 };
// make a set of unique items from list
HashSet<MyInt> set = new HashSet<MyInt>(list);
// print that set
foreach(int item in set)
Console.WriteLine(item);
}
}
}
Output:
112621

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;
}

Find the missing integer in Codility

I need to "Find the minimal positive integer not occurring in a given sequence. "
A[0] = 1
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2, the function should return 5.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
I wrote the code in codility, but for many cases it did not worked and the performance test gives 0 %. Please help me out, where I am wrong.
class Solution {
public int solution(int[] A) {
if(A.Length ==0) return -1;
int value = A[0];
int min = A.Min();
int max = A.Max();
for (int j = min+1; j < max; j++)
{
if (!A.Contains(j))
{
value = j;
if(value > 0)
{
break;
}
}
}
if(value > 0)
{
return value;
}
else return 1;
}
}
The codility gives error with all except the example, positive and negative only values.
Edit: Added detail to answer your actual question more directly.
"Please help me out, where I am wrong."
In terms of correctness: Consider A = {7,2,5,6,3}. The correct output, given the contents of A, is 1, but our algorithm would fail to detect this since A.Min() would return 2 and we would start looping from 3 onward. In this case, we would return 4 instead; since it's the next missing value.
Same goes for something like A = {14,15,13}. The minimal missing positive integer here is again 1 and, since all the values from 13-15 are present, the value variable will retain its initial value of value=A[0] which would be 14.
In terms of performance: Consider what A.Min(), A.Max() and A.Contains() are doing behind the scenes; each one of these is looping through A in its entirety and in the case of Contains, we are calling it repeatedly for every value between the Min() and the lowest positive integer we can find. This will take us far beyond the specified O(N) performance that Codility is looking for.
By contrast, here's the simplest version I can think of that should score 100% on Codility. Notice that we only loop through A once and that we take advantage of a Dictionary which lets us use ContainsKey; a much faster method that does not require looping through the whole collection to find a value.
using System;
using System.Collections.Generic;
class Solution {
public int solution(int[] A) {
// the minimum possible answer is 1
int result = 1;
// let's keep track of what we find
Dictionary<int,bool> found = new Dictionary<int,bool>();
// loop through the given array
for(int i=0;i<A.Length;i++) {
// if we have a positive integer that we haven't found before
if(A[i] > 0 && !found.ContainsKey(A[i])) {
// record the fact that we found it
found.Add(A[i], true);
}
}
// crawl through what we found starting at 1
while(found.ContainsKey(result)) {
// look for the next number
result++;
}
// return the smallest positive number that we couldn't find.
return result;
}
}
The simplest solution that scored perfect score was:
public int solution(int[] A)
{
int flag = 1;
A = A.OrderBy(x => x).ToArray();
for (int i = 0; i < A.Length; i++)
{
if (A[i] <= 0)
continue;
else if (A[i] == flag)
{
flag++;
}
}
return flag;
}
Fastest C# solution so far for [-1,000,000...1,000,000].
public int solution(int[] array)
{
HashSet<int> found = new HashSet<int>();
for (int i = 0; i < array.Length; i++)
{
if (array[i] > 0)
{
found.Add(array[i]);
}
}
int result = 1;
while (found.Contains(result))
{
result++;
}
return result;
}
A tiny version of another 100% with C#
using System.Linq;
class Solution
{
public int solution(int[] A)
{
// write your code in C# 6.0 with .NET 4.5 (Mono)
var i = 0;
return A.Where(a => a > 0).Distinct().OrderBy(a => a).Any(a => a != (i = i + 1)) ? i : i + 1;
}
}
A simple solution that scored 100% with C#
int Solution(int[] A)
{
var A2 = Enumerable.Range(1, A.Length + 1);
return A2.Except(A).First();
}
public class Solution {
public int solution( int[] A ) {
return Arrays.stream( A )
.filter( n -> n > 0 )
.sorted()
.reduce( 0, ( a, b ) -> ( ( b - a ) > 1 ) ? a : b ) + 1;
}
}
It seemed easiest to just filter out the negative numbers. Then sort the stream. And then reduce it to come to an answer. It's a bit of a functional approach, but it got a 100/100 test score.
Got an 100% score with this solution:
https://app.codility.com/demo/results/trainingUFKJSB-T8P/
public int MissingInteger(int[] A)
{
A = A.Where(a => a > 0).Distinct().OrderBy(c => c).ToArray();
if (A.Length== 0)
{
return 1;
}
for (int i = 0; i < A.Length; i++)
{
//Console.WriteLine(i + "=>" + A[i]);
if (i + 1 != A[i])
{
return i + 1;
}
}
return A.Max() + 1;
}
JavaScript solution using Hash Table with O(n) time complexity.
function solution(A) {
let hashTable = {}
for (let item of A) {
hashTable[item] = true
}
let answer = 1
while(true) {
if(!hashTable[answer]) {
return answer
}
answer++
}
}
The Simplest solution for C# would be:
int value = 1;
int min = A.Min();
int max = A.Max();
if (A.Length == 0) return value = 1;
if (min < 0 && max < 0) return value = 1;
List<int> range = Enumerable.Range(1, max).ToList();
List<int> current = A.ToList();
List<int> valid = range.Except(current).ToList();
if (valid.Count() == 0)
{
max++;
return value = max;
}
else
{
return value = valid.Min();
}
Considering that the array should start from 1 or if it needs to start from the minimum value than the Enumerable.range should start from Min
MissingInteger solution in C
int solution(int A[], int N) {
int i=0,r[N];
memset(r,0,(sizeof(r)));
for(i=0;i<N;i++)
{
if(( A[i] > 0) && (A[i] <= N)) r[A[i]-1]=A[i];
}
for(i=0;i<N;i++)
{
if( r[i] != (i+1)) return (i+1);
}
return (N+1);
}
My solution for it:
public static int solution()
{
var A = new[] { -1000000, 1000000 }; // You can try with different integers
A = A.OrderBy(i => i).ToArray(); // We sort the array first
if (A.Length == 1) // if there is only one item in the array
{
if (A[0]<0 || A[0] > 1)
return 1;
if (A[0] == 1)
return 2;
}
else // if there are more than one item in the array
{
for (var i = 0; i < A.Length - 1; i++)
{
if (A[i] >= 1000000) continue; // if it's bigger than 1M
if (A[i] < 0 || (A[i] + 1) >= (A[i + 1])) continue; //if it's smaller than 0, if the next integer is bigger or equal to next integer in the sequence continue searching.
if (1 < A[0]) return 1;
return A[i] + 1;
}
}
if (1 < A[0] || A[A.Length - 1] + 1 == 0 || A[A.Length - 1] + 1 > 1000000)
return 1;
return A[A.Length-1] +1;
}
class Solution {
public int solution(int[] A) {
int size=A.length;
int small,big,temp;
for (int i=0;i<size;i++){
for(int j=0;j<size;j++){
if(A[i]<A[j]){
temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
}
int z=1;
for(int i=0;i<size;i++){
if(z==A[i]){
z++;
}
//System.out.println(a[i]);
}
return z;
}
enter code here
}
In C# you can solve the problem by making use of built in library functions. How ever the performance is low for very large integers
public int solution(int[] A)
{
var numbers = Enumerable.Range(1, Math.Abs(A.Max())+1).ToArray();
return numbers.Except(A).ToArray()[0];
}
Let me know if you find a better solution performance wise
C# - MissingInteger
Find the smallest missing integer between 1 - 1000.000.
Assumptions of the OP take place
TaskScore/Correctness/Performance: 100%
using System;
using System.Linq;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
var A = new int[] { -122, -5, 1, 2, 3, 4, 5, 6, 7 }; // 8
var B = new int[] { 1, 3, 6, 4, 1, 2 }; // 5
var C = new int[] { -1, -3 }; // 1
var D = new int[] { -3 }; // 1
var E = new int[] { 1 }; // 2
var F = new int[] { 1000000 }; // 1
var x = new int[][] { A, B, C, D, E, F };
x.ToList().ForEach((arr) =>
{
var s = new Solution();
Console.WriteLine(s.solution(arr));
});
Console.ReadLine();
}
}
// ANSWER/SOLUTION
class Solution
{
public int solution(int[] A)
{
// clean up array for negatives and duplicates, do sort
A = A.Where(entry => entry > 0).Distinct().OrderBy(it => it).ToArray();
int lowest = 1, aLength = A.Length, highestIndex = aLength - 1;
for (int i = 0; i < aLength; i++)
{
var currInt = A[i];
if (currInt > lowest) return lowest;
if (i == highestIndex) return ++lowest;
lowest++;
}
return 1;
}
}
}
Got 100% - C# Efficient Solution
public int solution (int [] A){
int len = A.Length;
HashSet<int> realSet = new HashSet<int>();
HashSet<int> perfectSet = new HashSet<int>();
int i = 0;
while ( i < len)
{
realSet.Add(A[i]); //convert array to set to get rid of duplicates, order int's
perfectSet.Add(i + 1); //create perfect set so can find missing int
i++;
}
perfectSet.Add(i + 1);
if (realSet.All(item => item < 0))
return 1;
int notContains =
perfectSet.Except(realSet).Where(item=>item!=0).FirstOrDefault();
return notContains;
}
class Solution {
public int solution(int[] a) {
int smallestPositive = 1;
while(a.Contains(smallestPositive)) {
smallestPositive++;
}
return smallestPositive;
}
}
Well, this is a new winner now. At least on C# and my laptop. It's 1.5-2 times faster than the previous champion and 3-10 times faster, than most of the other solutions. The feature (or a bug?) of this solution is that it uses only basic data types. Also 100/100 on Codility.
public int Solution(int[] A)
{
bool[] B = new bool[(A.Length + 1)];
for (int i = 0; i < A.Length; i++)
{
if ((A[i] > 0) && (A[i] <= A.Length))
B[A[i]] = true;
}
for (int i = 1; i < B.Length; i++)
{
if (!B[i])
return i;
}
return A.Length + 1;
}
Simple C++ solution. No additional memory need, time execution order O(N*log(N)):
int solution(vector<int> &A) {
sort (A.begin(), A.end());
int prev = 0; // the biggest integer greater than 0 found until now
for( auto it = std::begin(A); it != std::end(A); it++ ) {
if( *it > prev+1 ) break;// gap found
if( *it > 0 ) prev = *it; // ignore integers smaller than 1
}
return prev+1;
}
int[] A = {1, 3, 6, 4, 1, 2};
Set<Integer> integers = new TreeSet<>();
for (int i = 0; i < A.length; i++) {
if (A[i] > 0) {
integers.add(A[i]);
}
}
Integer[] arr = integers.toArray(new Integer[0]);
final int[] result = {Integer.MAX_VALUE};
final int[] prev = {0};
final int[] curr2 = {1};
integers.stream().forEach(integer -> {
if (prev[0] + curr2[0] == integer) {
prev[0] = integer;
} else {
result[0] = prev[0] + curr2[0];
}
});
if (Integer.MAX_VALUE == result[0]) result[0] = arr[arr.length-1] + 1;
System.out.println(result[0]);
I was surprised but this was a good lesson. LINQ IS SLOW. my answer below got me 11%
public int solution (int [] A){
if (Array.FindAll(A, x => x >= 0).Length == 0) {
return 1;
} else {
var lowestValue = A.Where(x => Array.IndexOf(A, (x+1)) == -1).Min();
return lowestValue + 1;
}
}
I think I kinda look at this a bit differently but gets a 100% evaluation. Also, I used no library:
public static int Solution(int[] A)
{
var arrPos = new int[1_000_001];
for (int i = 0; i < A.Length; i++)
{
if (A[i] >= 0)
arrPos[A[i]] = 1;
}
for (int i = 1; i < arrPos.Length; i++)
{
if (arrPos[i] == 0)
return i;
}
return 1;
}
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> elements = new TreeSet<Integer>();
long lookFor = 1;
for (int i = 0; i < A.length; i++) {
elements.add(A[i]);
}
for (Integer integer : elements) {
if (integer == lookFor)
lookFor += 1;
}
return (int) lookFor;
}
I tried to use recursion in C# instead of sorting, because I thought it would show more coding skill to do it that way, but on the scaling tests it didn't preform well on large performance tests. Suppose it's best to just do the easy way.
class Solution {
public int lowest=1;
public int solution(int[] A) {
// write your code in C# 6.0 with .NET 4.5 (Mono)
if (A.Length < 1)
return 1;
for (int i=0; i < A.Length; i++){
if (A[i]==lowest){
lowest++;
solution(A);
}
}
return lowest;
}
}
Here is my solution in javascript
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
let result = 1;
let haveFound = {}
let len = A.length
for (let i=0;i<len;i++) {
haveFound[`${A[i]}`] = true
}
while(haveFound[`${result}`]) {
result++
}
return result
}
class Solution {
public int solution(int[] A) {
var sortedList = A.Where(x => x > 0).Distinct().OrderBy(x => x).ToArray();
var output = 1;
for (int i = 0; i < sortedList.Length; i++)
{
if (sortedList[i] != output)
{
return output;
}
output++;
}
return output;
}
}
You should just use a HashSet as its look up time is also constant instead of a dictionary. The code is less and cleaner.
public int solution (int [] A){
int answer = 1;
var set = new HashSet<int>(A);
while (set.Contains(answer)){
answer++;
}
return answer;
}
This snippet should work correctly.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int result = 1;
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(2);
lst.Add(3);
lst.Add(18);
lst.Add(4);
lst.Add(1000);
lst.Add(-1);
lst.Add(-1000);
lst.Sort();
foreach(int curVal in lst)
{
if(curVal <=0)
result=1;
else if(!lst.Contains(curVal+1))
{
result = curVal + 1 ;
}
Console.WriteLine(result);
}
}
}

Integer to Integer Array C# [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 1 year ago.
I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way :
My solution was :
public static int[] intToArray(int num){
String holder = num.ToString();
int[] numbers = new int[Holder.ToString().Length];
for(int i=0;i<numbers.length;i++){
numbers[i] = Convert.toInt32(holder.CharAt(i));
}
return numbers;
}
A simple solution using LINQ
int[] result = yourInt.ToString().Select(o=> Convert.ToInt32(o) - 48 ).ToArray()
I believe this will be better than converting back and forth. As opposed to JBSnorro´s answer I reverse after converting to an array and therefore avoid IEnumerable´s which I think will contribute to a little bit faster code. This method work for non negative numbers, so 0 will return new int[1] { 0 }.
If it should work for negative numbers, you could do a n = Math.Abs(n) but I don't think that makes sense.
Furthermore, if it should be more performant, I could create the final array to begin with by making a binary-search like combination of if-statements to determine the number of digits.
public static int[] digitArr(int n)
{
if (n == 0) return new int[1] { 0 };
var digits = new List<int>();
for (; n != 0; n /= 10)
digits.Add(n % 10);
var arr = digits.ToArray();
Array.Reverse(arr);
return arr;
}
Update 2018:
public static int numDigits(int n) {
if (n < 0) {
n = (n == Int32.MinValue) ? Int32.MaxValue : -n;
}
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
return 10;
}
public static int[] digitArr2(int n)
{
var result = new int[numDigits(n)];
for (int i = result.Length - 1; i >= 0; i--) {
result[i] = n % 10;
n /= 10;
}
return result;
}
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x);
but if you want to convert it to 1,2,3,4,5:
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x - 48);
I'd do it like this:
var result = new List<int>();
while (num != 0) {
result.Insert(0, num % 10);
num = num / 10;
}
return result.ToArray();
Slightly less performant but possibly more elegant is:
return num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();
Note that these both return 1,2,3,4,5,6 rather than 49,50,51,52,53,54 (i.e. the byte codes for the characters '1','2','3','4','5','6') as your code does. I assume this is the actual intent?
Using conversion from int to string and back probably isn't that fast. I would use the following
public static int[] ToDigitArray(int i)
{
List<int> result = new List<int>();
while (i != 0)
{
result.Add(i % 10);
i /= 10;
}
return result.Reverse().ToArray();
}
I do have to note that this only works for strictly positive integers.
EDIT:
I came up with an alternative. If performance really is an issue, this will probably be faster, although you can only be sure by checking it yourself for your specific usage and application.
public static int[] ToDigitArray(int n)
{
int[] result = new int[GetDigitArrayLength(n)];
for (int i = 0; i < result.Length; i++)
{
result[result.Length - i - 1] = n % 10;
n /= 10;
}
return result;
}
private static int GetDigitArrayLength(int n)
{
if (n == 0)
return 1;
return 1 + (int)Math.Log10(n);
}
This works when n is nonnegative.
Thanks to ASCII character table. The simple answer using LINQ above yields answer + 48.
Either
int[] result = youtInt.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();
or
int[] result = youtInt.ToString().Select(o => int.Parse(o.ToString())).ToArray();
can be used
You can do that without converting it to a string and back:
public static int[] intToArray(int num) {
List<int> numbers = new List<int>();
do {
numbers.Insert(0, num % 10);
num /= 10;
} while (num > 0);
return numbers.ToArray();
}
It only works for positive values, of course, but your original code also have that limitation.
I would convert it in the below manner
if (num == 0) return new int[1] { 0 };
var digits = new List<int>();
while (num > 0)
{
digits.Add(num % 10);
num /= 10;
}
var arr = digits.ToArray().Reverse().ToArray();
string DecimalToBase(int iDec, int numbase)
{
string strBin = "";
int[] result = new int[32];
int MaxBit = 32;
for(; iDec > 0; iDec/=numbase)
{
int rem = iDec % numbase;
result[--MaxBit] = rem;
}
for (int i=0;i<result.Length;i++)
if ((int)result.GetValue(i) >= base10)
strBin += cHexa[(int)result.GetValue(i)%base10];
else
strBin += result.GetValue(i);
strBin = strBin.TrimStart(new char[] {'0'});
return strBin;
}
int BaseToDecimal(string sBase, int numbase)
{
int dec = 0;
int b;
int iProduct=1;
string sHexa = "";
if (numbase > base10)
for (int i=0;i<cHexa.Length;i++)
sHexa += cHexa.GetValue(i).ToString();
for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
{
string sValue = sBase[i].ToString();
if (sValue.IndexOfAny(cHexa) >=0)
b=iHexaNumeric[sHexa.IndexOf(sBase[i])];
else
b= (int) sBase[i] - asciiDiff;
dec += (b * iProduct);
}
return dec;
}
i had similar requirement .. i took from many good ideas, and added a couple missing pieces .. where many folks weren’t handling zero or negative values. this is what i came up with:
public static int[] DigitsFromInteger(int n)
{
int _n = Math.Abs(n);
int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
int[] digits = new int[length];
for (int i = 0; i < length; i++)
{
digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
_n /= 10;
}
return digits;
}
i think this is pretty clean .. although, it is true we're doing a conditional check and several extraneous calculations with each iteration .. while i think they’re nominal in this case, you could optimize a step further this way:
public static int[] DigitsFromInteger(int n)
{
int _n = Math.Abs(n);
int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
int[] digits = new int[length];
for (int i = 0; i < length; i++)
{
//digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
digits[(length - i) - 1] = _n % 10;
_n /= 10;
}
if (n < 0)
digits[0] *= -1;
return digits;
}
A slightly more concise way to do MarkXA's one-line version:
int[] result = n.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();
GetNumericValue returns the visible number in your char as a double, so if your string is "12345", it will return the doubles 1,2,3,4,5, which can each be cast to an int. Note that using Convert.ToInt32 on a char in C# returns the ASCII code, so you would get 49,50,51,52,53. This can understandably lead to a mistake.
Here is a Good Solution for Convert Your Integer into Array i.e:
int a= 5478 into int[]
There is no issue if You Have a String and You want to convert a String into integer Array for example
string str=4561; //Convert into
array[0]=4;
array[1]=5;
array[2]=6;
array[3]=7;
Note: The Number of zero (0) in devider are Equal to the Length of input and Set Your Array Length According to Your input length
Now Check the Coding:
string str=4587;
int value = Convert.ToInt32(str);
int[] arr = new int[4];
int devider = 10000;
for (int i = 0; i < str.Length; i++)
{
int m = 0;
devider /= 10;
arr[i] = value / devider;
m = value / devider;
value -= (m * devider);
}
private static int[] ConvertIntToArray(int variable)
{
string converter = "" + variable;
int[] convertedArray = new int[converter.Length];
for (int i=0; i < convertedArray.Length;i++) //it can be also converter.Length
{
convertedArray[i] = int.Parse(converter.Substring(i, 1));
}
return convertedArray;
}
We get int via using method. Then, convert it to string immediately (123456->"123456"). We have a string called converter and carry to int value. Our string have a string.Length, especially same length of int so, we create an array called convertedArray that we have the length, that is converter(string) length. Then, we get in the loop where we are convert the string to int one by one via using string.Substring(i,1), and assign the value convertedArray[i]. Then, return the convertedArray.At the main or any method you can easily call the method.
public static int[] intToArray(int num)
{
num = Math.Abs(num);
int length = num.ToString().Length;
int[] arr = new int[length];
do
{
arr[--length] = num % 10;
num /= 10;
} while (num != 0);
return arr;
}
Dividing by system base (decimal in this case) removes the right most digit, and we get that digit by remainder operator. We keep repeating until we end up with a zero. Each time a digit is removed it will be stored in an array starting from the end of the array and backward to avoid the need of revering the array at the end. The Math.Abs() function is to handle the negative input, also the array is instantiated with the same size as input length.
Integer or Long to Integer Array C#
Convert it to char array and subtract 48.
public static int[] IntToArray(int value, int length)
{
char[] charArray = new char[length];
charArray = value.ToString().ToCharArray();
int[] intArray = new int[length];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = charArray[i] - 48;
}
return intArray;
}
public static int[] LongToIntArray(long value, int length)
{
char[] charArray = new char[length];
charArray = value.ToString().ToCharArray();
int[] intArray = new int[length];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = charArray[i] - 48;
}
return intArray;
}

Categories