It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have the following to solve and I'm not sure how to approach this:
There are parking lots that are adjacent to each other and their placement resembles a straight line. Each parking lot has a value (profit) assigned to it. You can purchase as many lots as you want BUT they have to be adjacent to each other (in a contiguous set).
INPUT (THIS IS GIVEN/WHAT YOU WOULD TYPE IN):
Number of lots: 9
Value for each parking lot: ie: -5, 0, 7, -6, 4, 3, -5, 0, 2
Representation (for easier viewing)
Each box contains profit of a each lot:
OUTPUT:
Should be:
3 6 8
meaning:
3 - start lot #,
6 - ending lot #,
8 - total profit (7 - 6 + 4 + 3)
If there is more than one answer, program should write the one that contains the smallest number of parking lots. If there is still more than one possible answer, your program can write any of them.
Please help. thanks in advance.
EDIT:
I got it working:
/// <summary>
/// The problem 2.
/// </summary>
public class MySuperAwesomeClass
{
#region Constants and Fields
/// <summary>
/// The seq end.
/// </summary>
private static int seqEnd = -1;
/// <summary>
/// The seq start.
/// </summary>
private static int seqStart;
#endregion
// Quadratic maximum contiguous subsequence sum algorithm.
#region Public Methods and Operators
/// <summary>
/// The max sub sum 2.
/// </summary>
/// <param name="a">
/// The a.
/// </param>
/// <returns>
/// The max sub sum 2.
/// </returns>
public static int maxSumSub(int[] a)
{
int maxSum = 0;
for (int i = 0; i < a.Length; i++)
{
int thisSum = 0;
for (int j = i; j < a.Length; j++)
{
thisSum += a[j];
if (thisSum > maxSum)
{
maxSum = thisSum;
seqStart = i;
seqEnd = j;
}
}
}
return maxSum;
}
#endregion
#region Methods
/// <summary>
/// The main.
/// </summary>
private static void Main()
{
Console.WriteLine("Enter N:");
string stringInput = Console.ReadLine();
int[] a = new int[Convert.ToInt16(stringInput)];
Console.WriteLine("Enter profit values:");
for (int i = 0; i < Convert.ToInt16(stringInput); i++)
{
string value = Console.ReadLine();
a[i] = Convert.ToInt16(value);
}
int maxSum = maxSumSub(a);
Console.WriteLine(string.Format("{0} {1} {2}", seqStart, seqEnd, maxSum));
Console.ReadKey();
}
#endregion
}
Except I can't figure out this part:
If there is more than one answer, program should write the one that contains the smallest number of parking lots.
This is the classic Maximum subset sum problem. No code as this is homework, but here is the general solution. I'm sure you can find code online by searching the title if you still get stuck.
Make first/last index variables for the max subset. These will hold the parking spaces of our answer. 3 and 6 respectively in your example.
Make a sum variable for the sum of the max subset. This will hold the sum of our answer. 8 in your example.
Make another set of first/last/sum variables which we will be our "current" variables.
Start at the beginning of the parking spaces. Place the current first and current last variable at the start and update the sum.
Now you're going to loop through each parking space by moving the current last variable and updating the sum.
If the current sum is greater then the max-so-far sum, save all the current variables into the max-so-far variables.
If at any point our current sum dips into the negative or becomes zero, our subset is not helping us get a max anymore, so restart it by moving the current first to where current last is and resetting current sum to zero.
Once we get to the end return the max-so-far variables
Here's a hint for a way you can make the algorithm more efficient: look at how the totals from each end add up. For example, from what you provided, from the left side the totals would be -5, -5, 2, -4, 0, 3, -2, -2, 0, and from the right side they would be 2, 2, -3, 0, 4, -2, 5, 5, 0.
Related
Implement the NextBiggerThan method that returns the nearest largest integer consisting of the digits of the given positive integer number and null if no such number exists. The method should return -1, if there is no nearest largest number.
Use iteration and selection statements. Extract digits using the remainder operator %. Don't use strings, collections or arrays.
At first, I thought it would be enough to swap the last 2 digits of the number. But now I see that it is crucial to use selection and iteration. Unfortunately, I have no clue how to correctly implement them here.
using System.Collections.Generic;
using System;
namespace NextBiggerTask
{
public static class NumberExtension
{
/// <summary>
/// Finds the nearest largest integer consisting of the digits of the given positive integer number; return -1 if no such number exists.
/// </summary>
/// <param name="number">Source number.</param>
/// <returns>
/// The nearest largest integer consisting of the digits of the given positive integer; return -1 if no such number exists.
/// </returns>
/// <exception cref="ArgumentException">Thrown when source number is less than 0.</exception>
public static int NextBiggerThan(int number)
{
int lastdigit = number % 10;
int lastdigits = number % 100;
int prelastdigit = (lastdigits - lastdigit) / 10;
int nearestnumber = number - lastdigits;
nearestnumber += 10 * lastdigit + prelastdigit;
return nearestnumber;
}
}
}
Let D be a list of the digits, in order, of number.
Let i be the smallest value such that D[i..] is non-increasing. (If i is 0, then there is no next value.)
Let j be index of the smallest value in D[i..] that is larger than D[i-1]
Then your answer is D[..i-2]+D[j]+sorted_ascending(D[i..] with D[j] replaced by D[i-1])
Example:
number = 114232, so D=[1,1,4,2,3,2]
i is 4 (for [3,2])
j is also 4 (for the 3)
So the result is [1,1,4] + [3] + [2,2]
Foreword: Zeckendorf representation
This mathematical theorem states that for each number n, there are k addition operands all present in the Fibonacci sequence {0, 1, 1, 2, 3, 5 et al}. For example, we got 100. To find its Zeckendorf representation, we first must find the largest value smaller or equal to 100 present in the Fibonacci sequence. In this case, it's 89. 100-89 is 11. The same process repeated gives us 8, and then 3. Therefore 89+8+3 = 100. This works for all numbers. If you have a strong computer that doesn't overflow with large numbers, and if you have a programming language supervised for math that holds numbers with large values, you can calculate the Zeckendorf representation for almost any given number.
However since we're using C# that's tricky with types and how large the numbers are, we have to practice caution when dealing with Zeckendorf representation. I used long to hold my numbers, and I calculated 20th number of the Fibonacci sequence.
static void Fbonacci_Init(int roof)
{
for (int i = 1; i < roof; i++) //where roof = 20
{
Fibonacci.Add(Fibonacci[i - 1] + Fibonacci[i]);
}
}
I then created two public static lists as fields:
public static List<long> Fibonacci = new List<long>() { 0, 1 };
public static List<long> ZeckendorfRep = new List<long>();
And then created a function called FindLesser than finds the a value lesser or equal to long given argument and adds it to ZeckendorfRep:
static void FindLesser(long number)
{
for (int i = Fibonacci.Count - 1; i >= 0; i--)
{
if (Fibonacci[i] <= number)
{
ZeckendorfRep.Add(Fibonacci[i]);
break;
}
}
}
And function called Difference for recursion of both FindLesser() and itself:
static void Difference(long init)
{
FindLesser(init - ZeckendorfRep[0]);
long summation = ZeckendorfRep.Sum();
if (summation != init)
{
for (int i = 1; i < ZeckendorfRep.Count; i++)
{
long difference = ZeckendorfRep[i] - ZeckendorfRep[i - 1];
FindLesser(difference);
Difference(difference);
}
}
}
I then call each function with the argument long input which is Console.ReadLine().
Anyways, the code doesn't work properly. It only returns the first two operands of a given representation, for example, for 100, it only returns 89 and 8. What could be the problem?
I was asked a question to write a optimal program that would determine the total number of stops a elevator has taken to serve X number of people. Question description is as below.
There is a elevator in a building with M floors, this elevator can take a max of X people at a time or max of total weight Y. Given that a set of people has arrived and their weight and the floor they need to stop given how many stops has the elevator taken to serve all the people. Consider elevator serves in the first come first serve basis.
E.g. Let Array A be the weight of people to be considered
A[] = {60, 80, 40 }
Let Array B be the floors where person needs to be dropped respectively
B[] = {2, 3, 5}
Total building floors be 5,max allowed person in elevator be 2 at a time with max weight capacity being 200
For this example the elevator would take total of 5 stops floors ground, 2, 3,ground, 5 , ground
What would be the optimal code for this?
One of my solution is as below. Is there any other better solutions?
class Solution
{
/// <summary>
/// Return total stops used
/// </summary>
/// <param name="A">weight of people</param>
/// <param name="B">floors they need to get down</param>
/// <param name="M">total floors in the building</param>
/// <param name="X">Max people to carry at a time</param>
/// <param name="Y">max weight to carry at a time</param>
/// <returns></returns>
public int solution(int[] A, int[] B, int M, int X, int Y)
{
// write your code in C# 6.0 with .NET 4.5 (Mono)
int totalStops = 0;
long totalWeightPerRound = 0;
int maxPersonsCount = 0;
List<int> lstFloors = new List<int>();
int currPerson = 0;
bool startLift = false;
while (currPerson < A.Length)
{
if ((totalWeightPerRound + A[currPerson]) <= Y && (maxPersonsCount+1) <= X)
{
totalWeightPerRound += A[currPerson];
maxPersonsCount++;
lstFloors.Add(B[currPerson]);
if (currPerson == A.Length - 1)
startLift = true;
currPerson++;
}
else
{
startLift = true;
}
if (startLift)
{
totalStops += lstFloors.Distinct().Count() + 1;
lstFloors.Clear();
maxPersonsCount = 0;
totalWeightPerRound = 0;
startLift = false;
}
}
return totalStops;
}
}
Maybe a little off topic, but as someone said above, it`s a math not a programming question. To be on the safe side, you should construct a functional describing the cost function you want to minimize, add constraints to include boundary conditions and finally calculate the variation to get the extremum.
Putting it another way, it is a non trivial mathematical task and you should REALLY concentrate on getting the math right before even trying to write a line of code. To optimize means to get the optimal solution, not just some solution ;)
First of all, I'm not really sure if I have framed my question correctly, but what I'm looking for can be better explained by looking at the below visual representation:
I have a method which returns an int within the range of 0 and 360.
Now, for further manipulation, I would like to round? or get the closest match from the numbers which are offset by 30. So how can I achieve this. Also, is there a specific term for the function that I'm looking for?
You may also edit the question if you think it can be written better.
Best Regards,
Navik.
This should work for any list where the items are an equal distance apart (i.e. 30, 60, 90).
EDIT
I've updated the code to use AlexD's elegant solution so that it will work with lists of any 'step' value, and with any starting (or ending) value (i.e. it could start with a negative number, like: -20, -15, -10, -5, 0, 5, 10, 15, 20):
/// <summary>
/// Gets the value of the item in the list of
/// numbers that is closest to the given number
/// </summary>
/// <param name="number">Any number</param>
/// <param name="numbers">A list of numbers, sorted from lowest to highest,
/// where the difference between each item is the same</param>
/// <returns>The value of the list item closest to the given number</returns>
public static int GetClosestNumber(int number, List<int> numbers)
{
if (numbers == null) throw new ArgumentNullException("numbers");
if (numbers.Count == 0)
throw new
ArgumentException("There are no items to compare against.", "numbers");
if (numbers.Count == 1) return numbers[0]; // Short-circuit for single-item lists
var step = Math.Abs(numbers[1] - numbers[0]);
// Get closest number using a slight modification of AlexD's elegant solution
var closestNumber = (Math.Abs(number) + (step / 2)) / step *
step * (number < 0 ? -1 : 1);
// Ensure numbers is within min/max bounds of the list
return Math.Min(Math.Max(closestNumber, numbers[0]), numbers[numbers.Count - 1]);
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
public static class MyExtensions
{
/// <summary>
/// Finds the missing numbers in a list.
/// </summary>
/// <param name="list">List of numbers</param>
/// <returns>Missing numbers</returns>
public static IEnumerable<int> FindMissing(this List<int> list)
{
// Sorting the list
list.Sort();
// First number of the list
var firstNumber = list.First();
// Last number of the list
var lastNumber = list.Last();
// Range that contains all numbers in the interval
// [ firstNumber, lastNumber ]
var range = Enumerable.Range(firstNumber, lastNumber - firstNumber);
// Getting the set difference
var missingNumbers = range.Except(list);
return missingNumbers;
}
}
Now you can call the extension method in the following way:
class Program
{
static void Main(string[] args)
{
// List of numbers
List<int> daysOfMonth =
new List<int>() { 6, 2, 4, 1, 9, 7, 3, 10, 15, 19, 11, 18, 13, 22, 24, 20, 27, 31, 25, 28 };
Console.Write("\nList of days: ");
foreach(var num in daysOfMonth)
{
Console.Write("{0} ", num);
}
Console.Write("\n\nMissing days are: ");
// Calling the Extension Method in the List of type int
foreach(var number in daysOfMonth.FindMissing())
{
Console.Write("{0} ", number);
}
}
}
public static IEnumerable<int> FindMissing(List<int> list)
{
if (list.Count < 3) yield break;
List<int> listClone = new List<int>(list); //do not modify the original list
listClone.Sort();
for (int n = listClone[i] ; n < listClone[listClone.Count - 1]; n++)
if (!listClone.Contains(n))
yield return n;
}
And of course this may be optimized not to traverse the entire listClone every time
Actually, your own code is not doing what it is expected to do.
The method documentation pretends that FindMissing will find what numbers are missing from Min..Max range of a list. Instead, the method actually finds the missing numbers between the first and the last value in a list. In other words, in a given example, I expect the search to be done from 1 to 31. Instead, the method will search from 6 to 28.
Now, if you need to transform this into a non-LINQ method, try it step by step :
The method uses list.First() and list.Last(). You can have both values by using indexes and list.Count.
The method uses Enumerable.Range. The behavior is easily reproduced with a for loop.
The method uses IEnumerable.Except(). You can find the missing values yourself by looping through the list.