• 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

    • Same Internet Archive seemed to grab the new version https://web.archive.org/web/20...d/Setup_MakeMKV_v1.18.4.exe Here's the link to an additional file it periodically downloads https://web.archive.org/web/20260213092148/https://www.makemkv.com/sdf.bin I think update's keys, etc. To manually trigger this update, put the sdf.bin file in the root of where the program is installed. When you launch the program it will pick up the file and import it. Typically put it here: C:\Program Files (x86)\MakeMKV\sdf.bin
    • Windows 11 KB5094126, KB5093998 bugging out Office apps but it may not be Microsoft's fault 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. Although the tech giant did not acknowledge any major problems, some users online reported various issues ranging from OneDrive and Dropbox access problems, BitLocker recovery lockouts, to blue screens and BSODs. You can read about them in this dedicated piece. While there is still no confirmation about those problems from Microsoft the company has admitted to another bug which we did not report on. The tech giant has confirmed it has received reports of an issue in which certain third-party applications may be unable to launch Microsoft Office apps or open Office documents after installing the Patch Tuesday. This affects both Windows 11 as well as Windows 10. The company says the problem impacts a subset of applications that rely on OLE (Object Linking and Embedding) automation to communicate with Microsoft Office programs. According to Microsoft, affected scenarios involve third-party software attempting to open Office applications or documents from within their own interface. In such cases, the Office program may fail to launch altogether, or the requested document may not open. Oddly there may not be any error message, which probably makes the issue difficult to diagnose. The bug affects several Office products, including Word, Excel, PowerPoint, Access, and other apps in the Microsoft Office suite when they are launched through the affected software. These include tax and accounting software such as CCH Engagement and Workpaper Manager, dental practice management solutions like Dentrix and Softdent, as well as the popular research and reference management tool Zotero. Microsoft adds that other applications using similar Office integration methods could also experience the same problematic behavior. To understand the issue it is important to look at OLE, the Microsoft technology involved. OLE allows different applications to work together and share data, while its Automation feature lets one program control another. Thus this enables third-party software to launch Microsoft Office apps, open documents, and perform tasks automatically without requiring users to switch between programs. Because many accounting, healthcare, research, and business applications rely on OLE automation to interact with Word, Excel, PowerPoint, and other Office apps, any disruption can break those workflows. As a result, affected software may be unable to open Office documents or launch Office applications even though the programs themselves continue to work normally. At the moment the company has not provided a permanent fix though it has confirmed that engineers are actively working on a resolution, which will be delivered through a future Windows update. As such additional details will be shared once more information becomes available. In the meantime, Microsoft recommends a simple workaround for affected users whic is to open the Office application or document directly rather than launching it through the third-party program. For enterprise customers and organizations managing larger deployments, Microsoft says an additional mitigation is available. Admins experiencing the problem on their managed devices are advised to contact Microsoft Support for business to obtain and apply the workaround.
    • It saddens me when cars are such dull colours now. Mine is bright metallic blue and I absolutely adore it for standing out in contrast to that depressing backdrop of traffic.
    • Sparkle 2.20.0 by Razvan Serea Sparkle is a free, open-source Windows optimization tool designed to make your PC faster, cleaner, and more private. With Sparkle, you can easily debloat Windows by removing unnecessary apps and services, disable Microsoft tracking to enhance privacy, and apply performance tweaks to boost speed. Its cleaner removes junk and temporary files, while every change is safe and fully reversible. Sparkle also features a modern, user-friendly interface with automatic updates, making system maintenance simple. Explore over 39 tweaks, from disabling telemetry and hibernation to optimizing network and game settings, all aimed at customizing and enhancing your Windows experience. Sparkle supports Windows 10 and 11. Sparkle 2.20.0 changelog: Debloat Tweak has animated border New homepage loading UI New Tweak Modal (Markdown Supported) Refactored GPU Detection Added Tests with vitest Added foobar2000 to apps Added Localsend to apps Updated Modal Styles Added styles for disabled inputs Added Animated Border to debloat-windows tweak Bumped dependencies Refactor System info logic for speed Tweak info modals now support Markdown Added Clear System info cache to settings Redesigned Home Page Loading UI Changed Some Icons around the app Download: Sparkle 2.20.0 | Portable | ~100.0 MB (Open Source) Links: Sparkle Website | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • lol it was a typo, fixed! haha imagine an actual 4TB Gen4 NVMe for $40 in 2026
  • Recent Achievements

    • Reacting Well
      Dys Topia earned a badge
      Reacting Well
    • Conversation Starter
      NovaEdgeX earned a badge
      Conversation Starter
    • One Year In
      Console General earned a badge
      One Year In
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      517
    2. 2
      +Edouard
      184
    3. 3
      PsYcHoKiLLa
      106
    4. 4
      Steven P.
      88
    5. 5
      ATLien_0
      68
  • Tell a friend

    Love Neowin? Tell a friend!