I know that when you're referencing an array it starts from 0, but does array.length start from 0 or does it start from 1?
Because if I specify an array size to be 10, I reference it 0-9, does this mean array.length is 0-9?
I'm asking because I'm using array.length as the maximum size of a randomly generated number but I'm doing it like this
randomArrayPointer = randomIntNum( 0 , ( posPercents.Length - 1 ) ); //generates a random number that fits the arrays range
if( randomArrayPointer < posPercents.Length ) //ensures the integer is less than the length of the array
{
return ( posPercents [ randomArrayPointer ] );
}
else
{
return ( posPercents [ 0 ] );
}
Here is my method randomIntNumber (I +1 to the maximum because when specifying 1 to 10 as the inputs for Random() it will give me a number between 0-9)
public static int randomIntNum( int min , int max )
{
if( max != 1 & ( max != ( min + 1 ) ) ) //if max isn't 1 and max isn't the minimum + 1
{
max = max - 1; //remove 1, this corrects the random generator so that the parameters sent don't need adjusting
}
int newInt;
newInt = rnd.Next( min , max );
return ( newInt );
}
Edit:
This is my method now, thanks everyone.
public static double randomPercentChange( Boolean? positive )
{
if( positive == true )
{
return ( posPercents [ rnd.Next( posPercents.Length ) ] );
}
else if( positive == false )
{
return ( negPercents [ rnd.Next( negPercents.Length ) ] );
}
else if( positive == null )
{
return ( 1 );
}
return 1;
}
EDIT 2: 4 years on I am sorely embarrassed by this question, but it is a great reference point for progress
If your array is empty, it contains 0 elements and has length 0.
If your array has 1 element in 0 index, then its length is equal to 1.
If your array has 2 elements in 0 and 1 indexes, then its length is equal 2.
and so on...
Array.Length refers to the size of the array, i.e how many elements it can hold. Arrays are 0 based when indexing them, so an example iteration would look like...
for(var i = 0; i < myArray.Length; i++)
{
var elm = myArray[i];
//do something with the element
}
I suppose your question is, "why is the last value in your array at index posPercents.Length - 1 instead of posPercents.Length?"
Since arrays are zero based, posPercents.Length = 10, but the last value is not at index 10. It is at index 9, hence its index is posPercents.Length - 1.
Related
Given an ordered list of integers, L = { 1, 2, 3, 4 }
and a permutation size of k,
I need to generate all 'ordered' permutations of length k having the first sequence = L[0].
With the example above, this should yield the following results:
k = 1
= { 1 }
k = 2
= { 1, 2 }, { 1, 3 }, { 1, 4 }
k = 3
= { 1, 2, 3 }, { 1, 2, 4}, { 1, 3, 4}
k = 4
= { 1, 2, 3, 4 }
This is what I came up with:
Assign permutations = Generate all possible permutations of L[1...n-1].
permutations.EliminateIfNotInOrder().
Prepend L[0] with each sequence in permutations.
Is there any better way to generate all ordered permutations in the first place, without needing the second-step of elimination?
Assuming that by "in order" you mean matching the order in the initial list:
public static IEnumerable<T> Yield<T>( T value )
{
yield return value;
}
public static IEnumerable<IEnumerable<T>> GetOrderedPermutations<T>( IEnumerable<T> source, int k )
{
if( k == 0 ) return new[] { Enumerable.Empty<T>() };
int length = source.Count();
if( k == length ) return new[] { source };
if( k > length ) return Enumerable.Empty<IEnumerable<T>>();
return GetOrderedHelper<T>( source, k, length );
}
private static IEnumerable<IEnumerable<T>> GetOrderedHelper<T>( IEnumerable<T> source, int k, int length )
{
if( k == 0 )
{
yield return Enumerable.Empty<T>();
yield break;
}
int i = 0;
foreach( var item in source )
{
if( i + k > length ) yield break;
var permutations = GetOrderedHelper<T>( source.Skip( i + 1 ), k - 1, length - i );
i++;
foreach( var subPerm in permutations )
{
yield return Yield( item ).Concat( subPerm );
}
}
}
This can still be made more efficient (by removing the recursion). But this is the most straight-forward algorithm I could come up with. In your case, since you always want the first element to appear, you can run the algorithm by chopping off the first element and just put it back on later:
var permutations = GetOrderedPermutations( source.Skip( 1 ), k - 1 )
.Select( p => Yield( source.First() ).Concat( p ) );
The idea behind this algorithm is fairly simple: All permutations are found by picking the first item in the permutation and just prepending it to all permutations of length k - 1 made out of the remainder of the list.
If you want to remove the recursion, there's a way of looking at it iteratively:
If you want a permutation of length k, initialize k pointers pointing to the first k elements of the source. These pointers point to the elements of the current permutation. To get the next permutation, increment the last pointer. If the last pointer goes past the end of the source, increment the previous pointer and set the last pointer to one past it. In code:
public static IEnumerable<IEnumerable<T>> GetOrderedPermutations<T>( IList<T> source, int k )
{
if( k == 0 ) yield return Enumerable.Empty<T>();
if( k == source.Count ) yield return source;
if( k > source.Count ) yield break;
var pointers = Enumerable.Range( 0, k ).ToArray();
// The first element of our permutation can only be in the first
// Count - k + 1 elements. If it moves past here, we can't have
// anymore permutations because there aren't enough items in the list.
while( pointers[0] <= source.Count - k )
{
yield return pointers.Select( p => source[p] );
// Increment the last pointer
pointers[k - 1]++;
// The i variable will keep track of which pointer
// we need to increment. Start it at the second to
// last (since this is the one that we're going to
// increment if the last pointer is past the end).
int i = k - 2;
while( pointers[k - 1] >= source.Count && i >= 0 )
{
// Okay, the last pointer was past the end, increment
pointers[i]++;
// Reset all the pointers after pointer i
for( int j = i + 1; j < k; ++j )
{
pointers[j] = pointers[j - 1] + 1;
}
// If the last pointer is still past the end, we'll
// catch it on the next go-around of this loop.
// Decrement i so we move the previous pointer next time.
--i;
}
}
}
I have a function (f) the takes a number of items (n) and a number of columns (c) and returns the optimal layout as an array of items per column. I define optimal as being as square as possible. So f(4,4) would return [4,4,4,4], f(17,4) would return [5,4,4,4], and f(1,4) would return [1,0,0,0]. My function works correctly in all my tests, but I am looking to alter it. My desire to do this is not because I am looking increase performance. I just want to do this, because I am experimenting and want to learn different techniques.
Here is the code:
public static int[] f(int n, int c){
int[] a = new int[c];
if(c>0 && n>=0){
int opt = (n-(n%c))/c;
n = n - (opt*c);
for(int i = 0;i<a.Length;i++){
a[i] = opt;
if(n>0){
a[i]++;
n--;
}
}
}
return a;
}
The function works by first determining the optimal number of items per col:
int opt = (n-(n%c))/c;
So f(17,4) would yield 4, f(19,4) would also yield 4, and f(3,4) would yield 0. Then the reminder is calculated:
n = n - (opt*c);
I then loop through the array (of length c) and assign a[i] equal to the optimal value. Finally, if the reminder is greater than 0 I add 1 to a[i]. This equally distributes the reminder across the array. This is the part I would like to alter.
Instead of checking if(n>0) and adding 1 to the array is there a formula I could use that might look like:
a[i] = opt + n*?????;
So n*??? would always equal 1 if n is greater than 0 and 0 if n is 0 or less?
The simple answer to your question is to use an expression with the conditional operator:
a[i] = opt + (n > 0 ? 1 : 0);
(n > 0 ? 1 : 0) will be 1 if n is greater than 0, and 0 otherwise.
On that note, there is a clearer and more concise way to implement your algorithm.
Determine the total number of items that can be distributed evenly between the slots (call this average). This has the value n / c (using integer division).
Determine the remainder that would be left after those are evenly distributed (call this remainder). This has the value n % c.
Put the value average + 1 in the first remainder slots, and put average in the rest.
The implementation for this would be:
public static int[] Distribute(int total, int buckets)
{
if (total < 0) { throw new ArgumentException("cannot be less than 0", "total"); }
if (buckets < 1) { throw new ArgumentException("cannot be less than 1", "buckets"); }
var average = total / buckets;
var remainder = total % buckets;
var array = new int[buckets];
for (var i = 0; i < buckets; i++)
{
array[i] = average + (i < remainder ? 1 : 0);
}
return array;
}
And the obligatory Linq version:
public static int[] DistributeLinq(int total, int buckets)
{
if (total < 0) { throw new ArgumentException("cannot be less than 0", "total"); }
if (buckets < 1) { throw new ArgumentException("cannot be less than 1", "buckets"); }
var average = total / buckets;
var remainder = total % buckets;
return Enumerable.Range(1, buckets)
.Select(v => average + (v <= remainder ? 1 : 0))
.ToArray();
}
If you want to use a formula:
Math.Max(n - Math.Abs(n - 1), 0)
should do the trick.
Your code should look like:
a[i] = opt + Math.Max(n - Math.Abs(n - 1), 0)
Another option for a formula would be
Math.Max(Math.Sign(n), 0)
If you are looking for a mathematical formula, I'm not sure you're going to find it as the function is discontinuous at n = 0.
How about a simple function which outputs int on a bool expression?
int IsPositive(int number)
{
//if number is > 0 return integer one (1), else return integer zero (0)
return number > 0 ? 1 : 0;
}
You can then use this in your code as such:
a[i] = opt + IsPositive(n);
//opt + 1 if n > 0, opt + 0 if n <= 0
Update: per your comment, you can just move the evaluation inline:
a[i] = opt + (n > 0 ? 1 : 0);
As an aside: you should make #BradleyDotNET's comment one of your programming mottos.
Hi i have this solution for PermCheck codility. Here is the link which includes the question: https://codility.com/demo/results/demo73YNCU-8FK/
I got 100% for it but i got a time complexity of O(N * log(N)) or O(N).
How could i make this code O(N)? Could you also give a brief description of what makes code O(N)? Thankyou.
Code here for shortcut:
Array.Sort(A);
if(A[0] == 1 && A.Length == 1) return 1;
if(A[0] != 1) return 0;
int n = 0;
for(int i = 0; i < A.Length; i++)
{
if(i < A.Length - 1)
{
if(A[i+1] == A[i] + 1)
{
n += 1;
}
else
{
return 0;
}
}
}
return 1;
Create a bool array which has the same size as the input, N, and leave all elements as the default false value. Loop through every element X of the input. If X is greater than N then return false. If array[N-1] is true, return false. Otherwise set array[N-1] to true. Repeat. This is O(N).
Explanation: First, if you have a permutation, then you need elements 1..N, but if any element is larger than N, then surely some elements are missing. Second, if an element occurs twice, it's a problem, that's why we create the bool array to remember already seen elements.
My python solution (doesn't need additional libraries, looks pythonic and not difficult to understand by others):
def solution(A): return 1 if len(set(A)) == len(A) == sorted(A)[-1] else 0
It can be simplified to:
def solution(A):
if len(set(A)) == len(A):
if len(A) == sorted(A)[-1]:
return 1
return 0
I checked two moments:
1: Length of set from array (set can't have duplicates) is equals to length of initial array
Arrays passed (no duplicates):
[1, 3, 2, 4], [4, 3, 2, 5]
Arrays failed:
[1, 1, 2, 4], [5, 6, 6, 1]
2: Length of initial array is equals to last element in sorted array
Arrays passed:
[1, 2, 3, 4]: Length is equal to last element => return 1
Arrays failed:
[2, 3, 4, 5]: Length is not equal to last element => return 0
This code doesn't work if A contains 0 or negative elements, but according to task details: each element of array A is an integer within the range [1..1,000,000,000].
Codility shows 100% and O(N) or O(N * log(N))
Tried to make it O(N) (suggested by fejesjoco):
def solution(A):
array_length = len(A)
seen_values = [False] * array_length
for x in A:
if x > array_length:
return 0
else:
if seen_values[x - 1]:
return 0
else:
seen_values[x - 1] = True
return 1
Codility result 100% Detected time complexity: O(N) or O(N * log(N))
Both codes shows equal result and time complexity. Maybe codility can't evaluate it right?
Here is my 100/100 answer:
same Idea as #fejesjoco
https://codility.com/demo/results/demoNR485D-33P/
You can change int to long to get performance.
public int solution(int[] A)
{
// idea: add to set,dictionary. Count the size and compare to N.
// dedupe data when needed.
var set = new HashSet<int>();
var max = int.MinValue;
foreach (var item in A)
{
if (set.Contains(item)) return 0;
set.Add(item);
if (item > max) max = item;
}
return set.Count == max ? 1 : 0;
}
This is my solution that scored 100% in correctness and performance.
def solution(A):
arraylength = len(A)
if (arraylength > 100000):
raise ValueError("Out of bound range")
arr = sorted(A)
for i in range(arraylength):
if (arr[i] != i+1):
return 0
return 1
I know that this questions is asked long time ago but it is still active in codility.
Possible solution:
public int solution(int[] A)
{
return (Enumerable.Range(1, A.Length).Except(A).Count() == 0) ? 1 : 0;
}
Following the suggestion by fejesjoco,
Boolean[] bln = new Boolean[A.Length];
for (int i = 0; i < A.Length; i++)
{
if (A[i] > A.Length) // more than array length
return 0;
if (bln[A[i]-1]) // same value twice
return 0;
bln[A[i]-1] = true;
}
return 1;
This was my solution, it scored 100%. Do not forget to add "using System.Linq".
int distinctLength = A.Distinct().ToArray().Length;
// The array length should equal to the distinct array length which is also the maximum value in array A.
if (A.Length == distinctLength && distinctLength == A.Max()) { return 1; }
return 0;
Swift Solution 100%
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
let sorted = A.sorted()
for (index, value) in sorted.enumerated() {
if index+1 != value {
return 0
}
}
return 1
}
I'm trying to write a class in C# that converts a big number (string format) to any number system, I found this code at How to convert a gi-normous integer (in string format) to hex format? (C#)
var s = "843370923007003347112437570992242323";
var result = new List<byte>();
result.Add( 0 );
foreach ( char c in s )
{
int val = (int)( c - '0' );
for ( int i = 0 ; i < result.Count ; i++ )
{
int digit = result[i] * 10 + val;
result[i] = (byte)( digit & 0x0F );
val = digit >> 4;
}
if ( val != 0 )
result.Add( (byte)val );
}
var hex = "";
foreach ( byte b in result )
hex = "0123456789ABCDEF"[ b ] + hex;
This code also works for any numeric system (2^n base) with a few modifications to the code.
The problem is that I do not understand the logic of the algorithm (the for statement).
Can someone please explain this part of the code:
for ( int i = 0 ; i < result.Count ; i++ )
{
int digit = result[i] * 10 + val;
result[i] = (byte)( digit & 0x0F );
val = digit >> 4;
}
if ( val != 0 )
result.Add( (byte)val );
In order to make this code to convert, for example, a string decimal to a string base64, I need to change the mask so it can calculate six bits, instead of just four for the hex system, and then right-shift digit by 6 to add the remaining to the next byte.
result[i] = (byte)( digit & 0x03F );
val = digit >> 6; // 2^6 = 64
and finally just change the look-up table to print the result
hex =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" [ b ] + hex;
It is this line in the for-loop the one I don't totally understand
int digit = result[i] * 10 + val;
What is this line, along with the loop, doing on each iteration to every byte of result? and most importantly, why?
Perhaps the code is easier to understand if you compare the algorithm to the simpler version where the integer can be represented in an int. Then result would be a 32 bit integer which you would initialize to 0 and for each digit you would multiply the existing value of result with 10 and add the next digit:
int result = 0;
foreach ( char c in s ) {
int val = (int)( c - '0' );
result = 10*result + val;
}
For big integers you need a byte array to represent the integer and the loop that you want to understand is a way to multiply the value in the byte array of unknown length with 10 while also adding the digit value. Because multiplying by 10 is not a simple bit shift you need that extra code.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to check if a number is a power of 2
I want to determine if a number is in
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
...
I tried this:
public static void Main(string[] args)
{
int result = 1;
for (int i = 0; i < 15; i++)
{
//Console.WriteLine(result);
Console.WriteLine(result % 2);
result *= 2;
}
}
As you can see it returns
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...
How should I efficiently make the above print to be 0 for all of them including 1?
The following expression should be true if i is in your sequence.
(i & (i-1)) == 0)
http://rextester.com/JRH41036
How about something like this?
bool IsInBinarySequence( int number ){
var numbertocheck = 1;
do{
if( number == numbertocheck ) return true;
numbertocheck *= 2;
}while( numbertocheck <= number );
return false;
}
This has no specific limit on the number to check, but makes sure it stops checking if the number to check grows larger than the actual number we're trying to decide if is in the binary sequence.
Since the first time result is odd, you will get 1, since right after that you multiply it by 2, you will always get 0.
You need to print result if you want to get the list of powers of 2.
Console.WriteLine(result);
A primitive way to do that will be:
public static void Main(string[] args)
{
int result = 1;
int numToCheck = 141234;
boolean found = false;
for (int i = 0; i < 15; i++)
{
if (numToCheck == result) {
found = true;
break;
}
result *= 2;
}
if(found) Console.WriteLine("Awesome");
}
You can determine if a number is a power of 2 (including 2^0) by using the following method:
public bool IsPowerOfTwo(int x) {
return (x > 0) && ((x & (x - 1)) == 0)
}
Over here you can read why and how this works.
It's a bit of a hack, but this works ...
static void Main()
{
for (int i = 0; i < 40; i++)
{
var str = Convert.ToString(i, 2);
var bitCount = str.Count(c => c == '1');
Console.ForegroundColor = bitCount == 1 ? ConsoleColor.White : ConsoleColor.DarkGray;
Console.WriteLine(i + ": " + (bitCount == 1));
}
}
it seems you're actually asking if only one bit in the binary representation of the number is a 1
What you is not a test whether the number is in the sequence BUT it is a generator for such numbers... only the print part is containing some sort of a test...
Try this code for a test:
public static void Main(string[] args)
{
int result = 0;
int numToTest = 0;
if ( int.TryParse (args[0], out numToTest) )
{
result = ((from c in Convert.ToString (numToTest, 2) where c == '1' select c).Count() == 1 ) ? 1 : 0;
}
Console.WriteLine(result);
}
The above code takes a commandline argument and tests it for being in the binary sequence according to the criterion you posted... if so it prints 1, otherwise it prints 0.
Thats correct. 1 0 0 0 0 0 is the correct sequence.
Result is 1 in the first loop. 1 % 2 is 1.
Then result *= 2 gives result the value 2. In the next loop run 2 % 2 = 0. Then result *= 2 is 4. 4%2 is 0. 4 *= 2 is 8. 8 %2 is 0. Since result is always multiplied with 2 it keeps to be in the powers of 2 row and thus als MOD operations with 2 result to 0. So all is fine with that code.
your code will print only Binary sequences. as you are applying MOD 2 . so either you will get 0 or 1 . so it will be print in Binary Sequence.
Boolean result = false;
Int32 numberToTest = 64;
Int32 limit = 15;
for (int i = 0; i < limit && !result; i++)
{
if (Math.Pow(2, i).Equals(numberToTest))
{
result = true;
}
}
Console.WriteLine(String.Format("Number {0} {1} a power of 2.", numberToTest, result ? "is" : "is not"));