TapeEquilibrium: Single failed test case... where is the error? - c#

TLDR: Codility "Challenge" - my results: Where is the error?
Short Description (Full Description): Given an Array, split the array into two (Upper and lower parts) and give the minimum difference between two possible parts in absolute value.
My thought process is:
create an "Upper" and "Lower" bucket for sums.
In one pass of the array, we get a sum for the "Upper" bucket.
Then, one array value at a time, move the numbers into lower (Upper-n, Lower+n).
At each step, get the difference (Abs(Upper-lower))
Monitor lowest "Minimum"
Submitted Code:
public int solution(int[] A)
{
// Quick results:
if (A == null) return -1;
if (A.Length == 0) return -1; // Can't split
if (A.Length == 1) return -1; // Can't split
if (A.Length == 2) return Math.Abs(A[0] - A[1]); // Only one way to split
// Hold above/below/result...
long lower = 0;
long upper = 0;
var min = long.MaxValue;
// Pass#1: Sum All to get "Upper"
for (long i = 0; i < A.Length; i++) upper += A[i];
// Pass#2:
// foreach in array
// ... Shift number from upper to lower
// ... Calculate new difference/minimum
for (var i = 0; i < A.Length; i++)
{
lower += A[i];
upper -= A[i];
var diff = Math.Abs(upper - lower);
min = Math.Min(min, diff);
if (diff == 0) return 0;
}
return (int) min;
}
Out of 13 test cases, the only one that Codility fails me on is: "Small Numbers". it says "Wrong answer, expected 20 got 0". It doesn't show the test data it uses, so I'm left guessing as to "Why".
Where is my error? I think I've stared at it too much, but I can't seem to figure out what case would "break" my function.
Edit: Fixed translation. Submitted code to Codility uses a Foreach, and the code I have here is a For. Corrected the variables in the loop.

The problem is that you didn't take into account one of the rules: 0 < P < N.
Your second loop is assuming 0 < P <= N.
Assume this input:
10, 10, -20
Your code would return 0 but 40 would be correct.
Fix:
Change your second loop header to
for (var i = 0; i < A.Length - 1; i++)
Proof

Related

How to shuffle string characters to right and left until int.MaxValue?

My task is to make a organized shuffle, from source all odd numbers will go to left and even number will go to right.
I have done that much like this, and it is good for normal scenario:
public static string ShuffleChars(string source, int count)
{
if (string.IsNullOrWhiteSpace(source) || source.Length == 0)
{
throw new ArgumentException(null);
}
if (count < 0)
{
throw new ArgumentException(null);
}
for (int i = 0; i < count; i++)
{
source = string.Concat(source.Where((item, index) => index % 2 == 0)) +
string.Concat(source.Where((item, index) => index % 2 != 0));
}
return source;
}
Now the problem is, what if the count is int.MaxValue or a other huge number in millions, it will loop trough a lot. How can I optimize the code in terms of speed and resource consumption?
You should be able to determine by the string's length how many iterations it will take before it's back to it's original sort order. Then take the modulus of the iteration count and the input count, and only iterate that many times.
For example, a string that is three characters will be back to it's original sort order in 2 iterations. If the input count was to do 11 iterations, we know that 11 % 2 == 1, so we only need to iterate one time.
Once you determine a formula for how many iterations it takes to reach the original sort order for any length of string, you can always reduce the number of iterations to that number or less.
Coming up with a formula will be tricky, however. A string with 14 characters takes 12 iterations until it matches itself, but a string with 15 characters only takes 4 iterations.
Therefore, a shortcut might be to simply start iterating until we reach the original sort order (or the specified count, whichever comes first). If we reach the count first, then we return that answer. Otherwise, we can determine the answer from the idea in the first paragraph - take the modulus of the input count and the iteration count, and return that answer.
This would require that we store the values from our iterations (in a dictionary, for example) so we can retrieve a specific previous value.
For example:
public static string ShuffleChars(string source, int count)
{
string s = source;
var results = new Dictionary<int, string>();
for (int i = 0; i < count; i++)
{
s = string.Concat(s.Where((item, index) => index % 2 == 0)) +
string.Concat(s.Where((item, index) => index % 2 != 0));
// If we've repeated our original string, return the saved
// value of the input count modulus the current iteration
if (s == source)
{
return results[count % (i + 1) - 1];
}
// Otherwise, save the value for later
else
{
results[i] = s;
}
}
// If we get here it means we hit the requested count before
// ever returning to the original sort order of the input
return s;
}
Instead of creating new immutable strings on each loop, you could work with a mutable array of characters (char[]), and swap characters between places. This would be the most efficient in terms of memory consumption, but doing the swaps on a single array could be quite tricky. Using two arrays is much easier, because you can just copy characters from one array to the other, and at the end of each loop swap the two arrays.
One more optimization you could do is to work with the indices of the char array, instead of its values. I am not sure if this will make any difference in practice, since in modern 64 bit machines both char and int types occupy 8 bytes (AFAIK). It will surely make a difference on 32 bit machines though. Here is an implementation, with all these ideas put together:
public static string ShuffleChars(string source, int count)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
// Instantiate the two arrays
int[] indices = new int[source.Length];
int[] temp = new int[source.Length];
// Initialize the indices array with incremented numbers
for (int i = 0; i < indices.Length; i++)
indices[i] = i;
for (int k = 0; k < count; k++)
{
// Copy the odds to the temp array
for (int i = 0, j = 0; j < indices.Length; i += 1, j += 2)
temp[i] = indices[j];
// Copy the evens to the temp array
int lastEven = (indices.Length >> 1 << 1) - 1;
for (int i = indices.Length - 1, j = lastEven; j >= 0; i -= 1, j -= 2)
temp[i] = indices[j];
// Swap the two arrays, using value tuples
(indices, temp) = (temp, indices);
}
// Map the indices to characters from the source string
return String.Concat(indices.Select(i => source[i]));
}

Increasing sequence in one dimensional array

You're given an array of integers,in case if you see subsequence in which each following bigger than the previous on one(2 3 4 5) you have to rewrite this subsequence in the resulting array like this 2 - 5 and then the rest of the array. So in general what is expected when you have 1 2 3 5 8 10 11 12 13 14 15 the output should be something like 1-3 5 8 10-15.
I have my own idea but can't really implement it so all I managed to do is:
static void CompactArray(int[] arr)
{
int[] newArr = new int[arr.length];
int l = 0;
for (int i = 0,k=1; i <arr.length ; i+=k,k=1) {
if(arr[i+1]==arr[i]+1)
{
int j = i;
while (arr[j+1]==arr[j]+1)
{
j++;
k++;
}
if (k>1)
{
}
}
else if(k==1)
{
newArr[i] = arr[i];
}
}
In short here I walk through the array and checking if next element is sum of one and previous array element and if so I'm starting to walk as long as condition is true and after that i just rewriting elements under indices and then move to the next.
I expect that people will help me to develop my own solution by giving me suggestions instead of throwing their own based on the tools which language provides because I had that situation on the russian forum and it didn't help me, and also I hope that my explanation is clear because eng isn't my native language so sorry for possible mistakes.
If I understand the problem correctly, you just need to print the result on the screen, so I'd start with declaring the variable which will hold our result string.
var result = string.Empty
Not using other array to store the state will help us keep the code clean and much more readable.
Let's now focus on the main logic. We'd like to loop over the array.
for (int i = 0; i < array.Length; i++)
{
// Let's store the initial index of current iteration.
var beginningIndex = i;
// Jump to the next element, as long as:
// - it exists (i + 1 < array.Length)
// - and it is greater from current element by 1 (array[i] == array[i+1] - 1)
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
// If the current element is the same as the one we started with, add it to the result string.
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
// If it is different element, add the range from beginning element to the one we ended with.
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
All that's left is printing the result:
Console.WriteLine(result)
Combining it all together would make the whole function look like:
static void CompactArray(int[] array)
{
var result = string.Empty;
for (int i = 0; i < array.Length; i++)
{
var beginningIndex = i;
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
Console.WriteLine(result);
}

When arrays go awry?

I'm trying to learn C# by solving mathematical problems. For example, I'm working on finding the sum of factors of 3 or 5 in the first 1000 positive numbers. I have the basic shell of the code laid out, but it isn't behaving how I'm expecting it to.
Right now, instead of getting a single output of 23, I am instead getting 1,1,3,3,5,5,7,7,9,9. I imagine I messed up the truncate function somehow. Its a bloody mess, but its the only way I can think of checking for factors. Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
using System;
namespace Problem1
{
class Problem1
{
public static void Main()
{
//create a 1000 number array
int[] numberPool = new int[10];
//use for loop to assign the first 1000 positive numbers to the array
for (int i = 0; i < numberPool.Length; i++)
{
numberPool[i] = i + 1;
}
//check for factors of 3 or 5 using if/then statment
foreach (int i in numberPool)
if ((i / 3) == Math.Truncate((((decimal)(i / 3)))) || ((i / 5) == Math.Truncate(((decimal)(i / 5)))))
{
numberPool[i] = i;
}
else
{
numberPool[i] = 0;
}
//throw the 0s and factors together and get the sum!
int sum = 0;
for (int x = 0;x < numberPool.Length;x++)
{
sum = sum + numberPool[x];
}
Console.WriteLine(sum);
Console.ReadLine();
//uncomment above if running in vbs
}
}
}
The foreach loop has a few errors.
If you want to modify the array you are looping through use a for loop. Also, use modulus when checking remainders.
for (int i = 0; i < numberPool.Length; i++)
{
if (numberPool[i] % 3 == 0 || numberPool[i] % 5 == 0)
{
// Do nothing
}
else
{
numberPool[i] = 0;
}
}
Modulus (%) will give the remainder when dividing two integers.
Another useful shortcut, variable = variable + x can be replaced with variable += x
Please note that there are more concise ways of doing this but since you are learning the language I will leave that for you to find.
#kailanjian gave some great advice for you but here is another way your initial logic can be simplified for understanding:
//the sum of factors
int sum = 0;
//the maximum number we will test for
int maxNum = 1000;
//iterate from 1 to our max number
for (int i = 1; i <= maxNum; i++)
{
//the number is a factor of 3 or 5
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
//output our sum
Console.WriteLine(sum);
You also stated:
Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
Your program logic will execute in the order that you list it and won't move on to the next given command until it is complete with the last. So your sum output will only be printed once it has completed our for loop iteration.

Having the nth char based on a variable not working as expected

So I have pow - a list containing numbers. I have to examine other numbers like this: Get all the digits and sum the numbers from pow having the same index as the certain digit.
So if I check number 4552 I need to get pow[4]+pow[5]+pow[5]+pow[2]. Because I'm a noob I try to convert the number to string, get the characters with loop and then convert back to int to get the index. So the code is as follows for getting the sums between 4550 and 4559:
for (int i = 4550; i < 4560; i++)
{
int sum = 0;
for (int j = 0; j < i.ToString().Length; j++)
{
sum += pows[Convert.ToInt32(i.ToString()[j])]; //here is the error - index was out of range
//do something with sum (like store it in another list)
}
}
So what is wrong with that?
EDIT: To avoid confusion... pow has 10 elements, from indexes 0-9.
SOLUTION: The issue with my code was that I got the character code not the digit itself, thanks Steve Lillis. Though the solution provided by Dmitry Bychenko is far more superior to my attempt. Thank you all.
What you're looking for is similar to a digital root:
Modulus (% in C#) is easier and faster than conversion to string:
public static int DigitalRootIndex(IList<int> list, int value) {
if (value < 0)
value = -value;
int result = 0;
// for value == 4552
// result == list[4] + list[5] + list[5] + list[2]
while (value > 0) {
int index = value % 10;
result += list[index];
value /= 10;
}
return result;
}
...
int test = DigitalRootIndex(pow, 4552);
This bit of code gets a single character such as '4' which is character code 59:
c = i.ToString()[j]
Then this bit of code turns that char into an integer. It doesn't parse it like you're expecting, so the result for '4' is 59, not 4:
Convert.ToInt32(c)
Do this instead:
int.Parse(c.ToString())
Something like this (quick and dirty try)?
int currentDigit;
int sum;
for (int i = 4550; i < 4560; i++)
{
sum = 0;
currentDigit = i;
while (currentDigit > 0)
{
if (pow.Count > (currentDigit % 10))
{
sum += pow[((currentDigit % 10))];
}
}
}
Note that lists have zero based index so when you do pow[1], you are actually accessing second element in the list. Is that what you want?

How can i check the index length in long[] array?

For example i have a long[] x
And im doing:
for (int i=0; i<x.length;x--)
{
}
I know that in x for example i have 30 indexs cells.
How can i loop over the cells(indexs) in the x array and find on each cell the length of it and also to get/show the numbers in each cell.
If in x[0] there is 232
And in x[1] there is 21
And so on...
I want to display 232,21,....etc
And then i want to check that if x[i].length is above 0 do...
But there is no x[i].length
So how do i do it ?
I did:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
long count = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > 0)
{
MessageBox.Show(histogram[i].ToString());
break;
}
}
return result;
}
And its working but each time its showing me the number twice why the messagebox is working twice each time ?
If in the first array the number is 33454 then i see the messagebox once and then once again. Whats wrong here ? I want it to show me the number only once each time.
Its like repeating each number and show it once and then once again and only then moving to the next one.
EDIT **
Maybe the problem its showing the number twice each time have something to do with the scroll event im using ?
void trackBar1_Scroll(object sender, EventArgs e)
{
myTrackPanelss1.trackBar1.Minimum = 0;
myTrackPanelss1.trackBar1.Maximum = counter - 1;//list_of_histograms.Count-1;
long[] tt = list_of_histograms[myTrackPanelss1.trackBar1.Value];
histogramControl1.DrawHistogram(tt);
long res = GetTopLumAmount(tt, 1000);
long max = GetHistogramMaximum(tt);
if (res > -1)
label24.Text = (res / 1000.0).ToString();
setpicture(myTrackPanelss1.trackBar1.Value);
this.pictureBox1.Refresh();
}
For some reason its getting to the scroll and do everything here again. Twice in a row.
What can be the problem ?
A long[] basically holds a number of long values. Doing x[i].length is invalid, because a long does not have a property length. What is it that you are trying to achieve?
long[] x = {1,2,3} ;
x.length; //this is valid because you are querying the length / count of the array
x[0].length; //this is invalid because 1 does not have a property length
EDIT
Your loop counter will be the index. So,
for (int i =0; i < x.Length; i++)
{
//check for maximum, when you find it
Console.WriteLine("The maximum value is " + x[i]);
Console.WriteLine("The maximum value is present at index " + i);
}
As Michael says, you can find the length of the array via x.Length. In C#, x.Length (where x is an array) will return a 32-bit integer that represents the total number of elements across all dimensions. You only have a 1D array here, so that should be sufficient for what you're trying to achieve.
If you're also after the value stored in the array, the value is called as:
x[i];
So, in an example:
for ( int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
... would display the value in the array in your console.
Is that what you were asking?
Here is how to do something based on the values in the array.:
for (int i=0; i < x.Length; i++)
{
// print the number to the screen.
Console.WriteLine(x[i]);
if (x[i] > 0) {
// do something else.
}
}
I'm not sure what you meant by x--, but that's probably wrong from your description.
You could cast it to a string and get the length property.
x[i].ToString().Length
Although if you want to check if the length is above zero, then surely just the presence of a value proves this?
Your function has a terrible problem:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
long count = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > 0)
{
MessageBox.Show(histogram[i].ToString());
break;
}
}
return result;
}
This way, you check the values in your array.
When i=0, it checks x[i]. So, 33454 (the value you gave in x[0]) is greater than 0, it shows the number and "break;", so it stops the "for" and do what's next: it returns the result variable that is never modified.
So variables result and count are useless in your code.
Rewrite with something that way for getting the maximum in your array:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > result)
{
MessageBox.Show(string.Format("{0} is greater than {1}", histogram[i], result);
result = histogram[i];
}
}
return result;
}

Categories