logo
down
shadow

How to sort the coordinates of a hash set in C#


How to sort the coordinates of a hash set in C#

By : Erick Speck
Date : October 25 2020, 07:10 PM
it fixes the issue You can use custom comparer to achieve what you want, where you can define your own rules:
code :
var comparer = Comparer<Point>.Create((p1, p2) =>
{
    if (p1.y < p2.y)
    {
       return p1.x > p2.x ? 1 : -1;
    } 
    else
    {
       return p1.x < p2.x ? 1 : -1;
    }
});

hashset.OrderBy(p => p, comparer)


Share : facebook icon twitter icon
Sort hash in ruby return an array but when i convert in to hash it sort it exactly opposite to first one

Sort hash in ruby return an array but when i convert in to hash it sort it exactly opposite to first one


By : Srini Vasan
Date : March 29 2020, 07:55 AM
hope this fix your issue It appears that you are using a version of Ruby pre-1.9, where there is no concept of the elements of a Hash having an order.
If you really need ordered Hashes, and if you really can't upgrade to Ruby 1.9, then there are libraries available that implement ordered Hashes for older versions of Ruby. (E.g. Hashery, among many others.)
How to sort floating point coordinates with no elimination of coordinates?

How to sort floating point coordinates with no elimination of coordinates?


By : user3017232
Date : March 29 2020, 07:55 AM
I wish this helpful for you This is what i wrote and it worked for all the cases finally. Let me admit it can be improved for performance and this might be a quick and dirty way but this what i am using at the moment.
P.S: I also admit that "Convex Hull" or "Graham Scan" was never what i needed and has nothing to do with what was required. So technically it was a fault on my side. I needed to sort points with the closest point first as @Chris had suggested.
code :
public class ConvexHull6
{

    public class PointDistance
    {
        public double X { get; set; }
        public double Y { get; set; }
        public double distance { get; set; }
        public int index { get; set; }
    }
    public class StormPointsDistance
    {
        public StormPoints stormPoints { get; set; }
        public Double distance { get; set; }
    }
    public static List<PointD> ReOrderPointsByClosestPointFirst(List<PointD> points, bool islower = false)
    {
        var minX = points.Min(p => p.X);
        var maxX = points.Max(p => p.X);
        var minP = points.First(p => p.X == minX);
        var maxP = points.First(p => p.X == maxX);

        minP = points.First(p => p.X == minX);
        maxP = points.First(p => p.X == maxX);

        var pB = points.ToList();
        var len = pB.Count();
        //Temporary lists to hold data structures and points when performing the points sorting..
        var pDist = new List<PointDistance>();
        var distances = new List<Double>();
        int index = 0;
        //Sorted list to hold final points...
        var sorted = new List<PointD>();
        for (int i = 0; i < len; i++)
        {
            if (i > 0)
            {
                //Minimum point or "Point of Reference for comparison" is now the last point in the sorted list.
                minP = sorted[sorted.Count() - 1];
                //Clear the temporary lists used...
                pDist.Clear(); distances.Clear();
            }
            for (int j = 0; j < len - i; j++)
            {
                var distance = Math.Sqrt(Math.Pow(pB[j].X - minP.X, 2) + Math.Pow(pB[j].Y - minP.Y, 2));
                pDist.Add(new PointDistance() { X = pB[j].X, Y = pB[j].Y, distance = distance, index = index });
                distances.Add(distance);
            }
            //Order the data structure
            pDist = pDist.OrderBy(m => m.distance).ToList();
            //Convert to points list for use
            pB = pDist.Select(m => new PointD(m.X, m.Y)).ToList();
            //Get the first point and put it in the sorted list
            sorted.Add(pB[0]);
            //Remove the point from the pb list so that it is not considered again
            pB.RemoveAt(0);

            index++;
        }
        pDist = pDist.OrderBy(m => m.distance).ToList();
        distances = pDist.Select(m => m.distance).ToList();

        //The new code...
        points = sorted.ToList();

        //Get the minimum Point again as minP has been overwritten during the loop
        minX = points.Min(p => p.X);
        maxX = points.Max(p => p.X);
        minP = points.First(p => p.X == minX);
        maxP = points.First(p => p.X == maxX);
        //Check if minp does nott match the first point
        if ((minP != points[0] && maxP == points[0]) || (maxP != points[len - 1] && minP == points[len - 1]))
        {
            //Reverse only if the first point of array is not the minimum point
            points.Reverse();
        }
        return points;
    }

}
Sort coordinates (x,y) of a parabola y=ax^2+bx+c x=x1,x2,x3, x4. according to y coordinates

Sort coordinates (x,y) of a parabola y=ax^2+bx+c x=x1,x2,x3, x4. according to y coordinates


By : Salvatore Trimarchi
Date : March 29 2020, 07:55 AM
like below fixes the issue The farther an x value is from the parabola's apex x0, the higher is its y value when a is positive and the lower its y value when a is negative.
code :
    |x1 - x0| > |x2 - x0| && a > 0   --> y1 > y2
    |x1 - x0| > |x2 - x0| && a < 0   --> y1 < y2
    x0 = - b / (2*a)
    i = index(x: min(|x - x0|))
    l = i - 1
    r = i + 1
import bisect

def parasort(a, b, c, x):
    """Return list sorted by y = a*x*x + b*x + c for sorted input x."""

    if not x:
        return x

    if a == 0:                          # degenerate case: line
        if b < 0: return x[::-1]
        return x[:]

    x0 = -0.5 * b / a                   # apex of parabola

    i = bisect.bisect_left(x, x0) + 1   # closest point via bin. search
    l = x[:i][::-1]                     # left array, reverted
    r = x[i:]                           # right array

    res = []

    while l and r:                      # merge l and r
        if x0 - l[0] > r[0] - x0:       # right item is smaller
            res += [r.pop(0)]
        else:                           # left item is smaller
            res += [l.pop(0)]

    res += l + r                        # append rest of arrays

    if a < 0: return res[::-1]        
    return res



a = 4
b = 0
c = 0
xx = parasort(a, b, c, [-3, 0, 1, 2])

for x in xx:
    print x, a*x*x + b*x + c
Sort a nested hash based on one of the values of the of the final hash

Sort a nested hash based on one of the values of the of the final hash


By : Vinod Muda
Date : March 29 2020, 07:55 AM
I wish this helpful for you Only arrays can store a set of values in a specific order
I think this is what you're looking for. For each value of $key1 it stores the sorted values of $key2 in an array and prints them
code :
use strict;
use warnings 'all';

my %hash = (
    name1 => {
        a => { line => 4, page => 112 },
        b => { line => 6, page => 134 },
        c => { line => 1, page => 112 },
    },
    name2 => {
        a => { line => 43, page => 112 },
        b => { line => 12, page => 134 },
        c => { line => 55, page => 112 },
    },
);

for my $key1 ( sort keys %hash ) {
    my $h2 = $hash{$key1};
    my @key2 = sort { $h2->{$a}{line} <=> $h2->{$b}{line} } keys %$h2;
    print "$key1: @key2\n";
}
name1: c a b
name2: b a c
Perl sort hash, how to sort by $hash{$key}->{secondkey}

Perl sort hash, how to sort by $hash{$key}->{secondkey}


By : D.M.J.
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You need to use cmp instead of <=> since you are comparing strings. The comments are correct and we need to take into consideration 10+ hours. You need to use sprintf to add leading zero when hours are less than 10 to have strings sorted correctly.
code :
foreach my $k (sort { sprintf("%05s", ($d{$a}->{t1})) cmp sprintf("%05s", ($d{$b}->{t1})) } keys %d) {
Related Posts Related Posts :
  • Moving picture box fast causes flickering C#
  • The remote server returned an error: (407) Proxy Authentication Required
  • XNA and Ninject: Syntax for dependency arguments?
  • How do I use C# and ADO.NET to query an Oracle table with a spatial column of type SDO_GEOMETRY?
  • Using C# to iterate form fields with same name
  • C# regex to validate "realistic" IP values
  • C# background worker and timer loop
  • How do I backup and restore the system clipboard in C#?
  • Colon ':' error - Not all named parameters have been set in Nhibernate?
  • Decoupling the view, presentation and ASP.NET Web Forms
  • Passing variables from a thread to another form using C#
  • How to get target path for UserName/My Pictures folder?
  • Blob Storage trigger is not getting fired upon uploading an image to the container, why?
  • How to solve encoding problem reading feed
  • how do you set Parallelizable Attribute in dotnet core for Nunit tests?
  • error MSB4226 MSBuild.Community.Tasks.Targets" was not found
  • Question about how to use strong typed dataset in N-tier application for .NET
  • MouseEnter and MouseLeave events from a Panel and its child controls
  • Moving a member of a List to the Front of the List
  • use inheritance to create a custom, type safe, null safe collection?
  • Problem saving excel file after inserting data
  • C# Setting Properties using Index
  • Placing & deleting element(s) from a object (stack)
  • Generic Singleton Façade design pattern
  • Having an outline for MouseOver for a WPF ListView
  • How to create resource manager in ASP.NET
  • Setting an XAML Window always on top (but no TopMost property)
  • Correctly use dependency injection
  • Managed code (C#) vs Matlabs and C++ for speed
  • Setting Cursor property has no effect
  • .net Attributes that handle exceptions - usage on a property accessor
  • Controlling images of nodes in a TreeView
  • How to return Task<IEnumerable<T>>?
  • Create a overlay screen while a game/program is running?
  • How to deal with JavaScript when trying to fetch web page in C#.NET/WPF?
  • how to read screen resolution - and change this resolution?
  • Converting C# void* to byte[]
  • C# Textbox validation should only accept integer values, but allows letters as well
  • format ugly c# source code
  • Why RSA encryption can return different results with C# and Java?
  • ASP.NET MVC 2 Localization/Globalization stored in the database?
  • LoaderLock was detected, and turning off the warning does not work
  • Problem with usercontrol scaling when added at run-time in .Net, WinForms
  • Good Silverlight Custom ItemsControl Tutorial
  • C# tabcontrol border controls
  • save images in webbrowser control without redownloading them from the internet
  • How can i restart MSDTC service on remote server from client machine
  • Fields of class, are they stored in the stack or heap?
  • setup format for columns of DataTable or GridView
  • c# - wmplib - playing 2 mp3 files but can get them in synic
  • How to delete a file from a SFTP server programmatically using SharpSSH?
  • .NET HttpListener Prefix issue with anything other than localhost
  • .NET: Type.Parse not working?
  • Inheritence in C# question - is overriding internal methods possible?
  • Prevent command window showing when NAnt compiling windows forms application
  • Need to pinvoke a .dll or something to change the mouse cursor in WPF
  • Store more than 24 hours in a DateTime
  • Custom code access permissions
  • How to convert SAML XML token string to either SecurityToken or ClaimsPrincipal instance?
  • DropDownList problem/doubt
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk