• 0

Algorithm Help


Question

Alright, I already passed a basic Algorithms course in school, but a friend who's taking it needs help with an exercise. I can't for the life of me figure out a simple way to do this... it is being made using a flowchart-generator, not a real programming language, so I can't access any advanced functions. This is the scenario:

You have to chose the cheapest, most efficient way to get somewhere. Now, assume the following price lists:

  • 1 KM: $12
  • 2 KM: $21
  • 3 KM: $31
  • 4 KM: $40
  • 5 KM: $49
  • 6 KM: $58
  • 7 KM: $69
  • 8 KM: $79
  • 9 KM: $90
  • 10KM: $101

So for example, the cheapest way to get a 15 KM trip would be to pay for a 3 KM trip and two 6 KM ones. What would the algorithm for this be like? I'm having a hard time with it..

Thanks in advance!

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/
Share on other sites

16 answers to this question

Recommended Posts

  • 0

There seems to be no rule between KM and $ on your price list, so you need to sort them by km/price ratio and always use combinations made of the cheapest trips, reverting to higher priced one when adding a cheaper one would get you too far.

Maybe it's more complex than that, though. :unsure:

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590153416
Share on other sites

  • 0

Well, the above logic run good

But I guess this will also do!!!

Hope you would appreciate :)

Try this

Step 1.

Factor your distance to travel into prime factors

Step 2.

Suppose, u want to travel 15kms then after factorizing you will able to get it as product of 3*5

i.e 5 times three, no as from your table of KM's to Cost i c that rate even km's is slightly less than the that of odd ones.

So form even numbers of the factorzing number as much as possible

for 15km's it would be (3+3)+(3+3) + 3

which would result into your required least cost!!! :)

Hope it helps, plz feel free to comment

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590154482
Share on other sites

  • 0
Seems easy enough. Here's how:

1. Calculate the cost/km for each km/$ pair, and sort them

2. Take the lowest cost/km and subtract as many kms as you can, keeping track.

3. Take the next lowest and repeat as per step 2

(Y)

:no:

Sorry, but my algorithm doesn't work, at least not in the general case.

Consider the following:

10km - $10 = $1/km

1km - $5 = $5/km

8km - 9$ = $1.125/km

Now say you want to go 16km. According to the algorithm I gave, you would take 1 - 10km and 6 - 1km, which would add up to $40. Now, you could take 2 - 8km which would give you $18.

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590159638
Share on other sites

  • 0

If you don't need the most efficient algorithm... and want to save yourself a headache...

Start by computing a possible path. Any one. That will cost a certain amount. Save that amount as the cheapest known path.

Now go through all possible combinations. This might be prohibitingly expensive, but you can break out of any calculation as soon as it exceeds the cheapest known path, and avoid equivalent permutations (2x8kms + 3x1km == 3x1km + 2x8kms). When a cheaper path is found, update your cheapest known path variable.

When all possibilities have been examined, you have the cheapest path!

Of course, given a long list of prices, this might take a while. For 10 prices, for instance, the worst case scenario will require to evaluate 92 378 possibilities, and that's if you avoid equivalent permutations. For 20 prices, worst case scenario is 68 923 264 410 possibilities avoiding equivalent permutations.

If you don't bother avoiding equivalent permutations (consider order important), then worst case scenario is n^n. :p

EDIT: actually the number of possiblities is MUCH lower if you only consider those that make up the required number of kilometers.

Edited by Dr_Asik
Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590161040
Share on other sites

  • 0

Maybe a possible way to start would be to assign each of the pricings a variable.

Read in the trip length and run it through a loop that would break it down starting with 10 and down to 1.

Probably would if/else using modulus (remainder) to make sure you get integer values. (If that even makes sense?)

Then obviously once you have the pricing choices, calculate out the total price using the variables.

My brain is drained from finals, so I don't know if any of that makes sense. Maybe you'll get some sort of idea from it.

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590161208
Share on other sites

  • 0
:p

EDIT: actually the number of possiblities is MUCH lower if you only consider those that make up the required number of kilometers.

Or it could be much higher if the list of prices stayed like the one the OP listed but the distance you want to cover is much higher (i.e. 5000 km).

In that regard, you could use the lowest price per kilometer fare until you are within the distance of the longest trip available.

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590164696
Share on other sites

  • 0

well, i found a good one that might work,

here it's simply

before startl, naming:

km = KM trip

cost(int km) //a method that calculate the least cost combination of trips

{

if ( km <=0 ) invalid trip

else if ( 1 <= km < 9 )

use the mentioned prices. i.e. 1 km => $12, 8 Km => $79

else //(km >= 9)

(km/5) * cost(km/2) + cost(cost%2)

}

notice that the km/2 and km%2 are integers i.e 9/2 = 4 and 9%2 = 1

I know this is NOT an algorithm exactly and not an complete code, it is in between and it must be done "Recursively"

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590196144
Share on other sites

  • 0
This is the unbounded knapsack problem (see http://en.wikipedia.org/wiki/Knapsack_problem). The greedy algorithm won't necessarily give you the optimal solution. You should take a look at a dynamic programming solution.

OMG! this is exactly what I did :-) even though I didn't know about that !!!

We can define A(j,Y) recursively as follows:

A(0, Y) = 0 
A(j, 0) = 0 
A(j, Y) = A(j − 1, Y)  if wj &gt; Y 
A(j, Y) = max { A(j − 1, Y),  pj + A(j − 1, Y − wj) }  if wj ≤ Y. 
The solution can then be found by calculating A(n, W). To do this efficiently we can use a table to store previous computations. This solution will therefore run in O(nW) time and O(nW) space, though with some slight modifications we can reduce the space complexity to O(W).

Good luck guys

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590204434
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft finally admits its default Windows 11 25H2, 24H2 action broke key legacy component by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. So far the company has acknowledged two known issues that have popped up after the release which include bugged-out Office apps as well as the Recycle Bin; though there could be more at play too. Speaking of bugs and issues, Microsoft seems to have finally acknowledged a problem that probably has been around for close to a year. That's because back in July of 2025 the company made a default change to the latest Windows 11 versions, wherein it switched to JScript9Legacy on Windows 11 24H2 and later releases. Hence following the release of version 25H2 in October 2025, JScript9Legacy also remained default-enabled. As a result there has been a compatibility issue ever since then. For those wondering, by switching to JScript9Legacy Microsoft intended to improve the security of modern Windows PCs by reducing vulnerabilities tied to legacy scripting like cross-site scripting (XSS), among others. XSS exploits can allow cyber-attackers to attach malicious code onto legitimate websites and use them to execute the code when a potential victim loads such a website. Hence the new JScript9Legacy engine enforced stricter execution policies and improved object handling, which should help mitigate such attacks. Microsoft today has published a new support article detailing the problem. Neowin spotted it while browsing. The company says that JScript global definitions and execution context may fail to persist across scripts, potentially breaking older dependent apps and web-based components that relied on this legacy behavior. In the article Microsoft has confirmed that the issue stems from its move away from the older jscript9.dll engine in favor of jscript9legacy.dll. As mentioned above, while the newer engine was designed to address vulnerabilities and strengthen security it also changes how JScript handles execution context. As a result functions and definitions loaded by one script could no longer remain available to subsequent scripts once execution ended. The company notes that some applications worked correctly on earlier Windows versions because the older JScript engine automatically retained global definitions and execution state between scripts. Under the newer model though that behavior is disabled by default causing certain legacy workloads and polyfill-dependent scripts to fail. Microsoft says it addressed the problem via the KB5077241 update though the fix had not been enabled automatically in the following updates. As such admins must explicitly turn on persistent JScript execution context using a Registry setting that the tech giant shared today. The configuration can be applied to individual processes or system-wide through the FEATURE_ENABLE_PERSISTENCE registry key. The steps have been outlined below: Run the following command to create the feature control registry key: reg add "HKLM\Software\Policies\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PERSISTENCE" Under this key, create a new DWORD (32-bit) value. Configure the value as follows: To enable persistence for specific processes only: Set the value to 1 for each target process name. To enable persistence for all processes: Add * as the key name and set its value to 1. You can find the official support article here on Microsoft's website.
    • The possibility that milk gathers back into a glass implies that gravity can be 'reversed'.
    • VidCoder 12.20 by Razvan Serea  VidCoder is a DVD/Blu-ray ripping and video transcoding application for Windows. It uses HandBrake as its encoding engine. Calling directly into the HandBrake library gives it a more rich UI than the official HandBrake Windows GUI. VidCoder can rip DVDs but does not defeat the CSS encryption found in most commercial DVDs. You’ll need the NET 8 Desktop Runtime. If you don’t have it, VidCoder will prompt you to download and install it. The Portable version is self-contained and does not require any .NET Runtime to be installed. You do not need to install HandBrake for VidCoder to work. Feature list: Multi-threaded MP4, MKV containers Completely integrated encoding pipeline: everything is in one process and no huge intermediate temporary files H.264, H.265, MPEG-4, MPEG-2, VP8, Theora video Hardware-accelerated encoding with AMD VCE, Nvidia NVENC and Intel QuickSync AAC, MP3, Vorbis, AC3, FLAC audio encoding and AAC/AC3/MP3/DTS/DTS-HD passthrough Target bitrate, size or quality for video 2-pass encoding Decomb, detelecine, deinterlace, rotate, reflect, chroma smooth, colorspace filters Powerful batch encoding with simultaneous encodes Customizable Pickers to automatically pick audio and subtitle tracks, destination, titles and more Instant source previews Creates small encoded preview clips Pause, resume encoding VidCoder 12.20 changes: Updated HandBrake core to 1.11.2. Download: VidCoder 12.20 | 47.0 MB (Open Source) Download: Portable VidCoder 12.19 | 89.3 MB Link: VidCoder Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Jordan Smith earned a badge
      Week One Done
    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      590
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      76
    4. 4
      Michael Scrip
      73
    5. 5
      Steven P.
      66
  • Tell a friend

    Love Neowin? Tell a friend!