logo
down
shadow

How to sort an array based on the occurrences of the elements in a string in C#?


How to sort an array based on the occurrences of the elements in a string in C#?

By : vvarmo
Date : November 22 2020, 10:54 AM
this one helps. You can do this concisely with a Linq query (I've renamed your original array to countries):
code :
var result = countries.Select(country => new { country, 
                                               index = downloadString.IndexOf(country)})
                      .Where(pair => pair.index >= 0)
                      .OrderBy(pair => pair.index)
                      .Select(pair => pair.country)
                      .ToArray();


Share : facebook icon twitter icon
Sort array based on count of occurrences in ascending order

Sort array based on count of occurrences in ascending order


By : Lu Yu
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Here's one approach to start you off could be based on the idea of keeping a count of how many times each integer in the initial array has occurred in a map. Once all the numbers have been counted, sort the map by order of ascending value, and then print the output of the map:
code :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;

public class SortCount {
    public static void main(String[] args) {
        int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
        HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();

        for(int i = 0; i < nums.length; i++) {
            if(counts.containsKey(nums[
                Integer c = counts.get(nums[i]) + 1;
                counts.put(nums[i], c);
            }
            else {
                counts.put(nums[i],1);
            }
        }

        ValueComparator<Integer,Integer> bvc = new ValueComparator<Integer,Integer>(counts);
        TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(bvc);
        sortedMap.putAll(counts);

        ArrayList<Integer> output = new ArrayList<Integer>();
        for(Integer i : sortedMap.keySet()) {
            for(int c = 0; c < sortedMap.get(i); c++) {
                output.add(i);
            }
        }

        System.out.println(output.toString());
    }
}
import java.util.Comparator;
import java.util.Map;

public class ValueComparator<T1,T2 extends Comparable<T2>> implements Comparator<T1> {
    Map<T1,T2> base;
    public ValueComparator(Map<T1,T2> base) {
        this.base = base;
    }

    @Override
    public int compare(T1 k1, T1 k2) {
        T2 val1 = base.get(k1);
        T2 val2 = base.get(k2);

        return val1.compareTo(val2);
    }
}
Elasticsearch sort based on the number of occurrences a string appears in an array

Elasticsearch sort based on the number of occurrences a string appears in an array


By : K. Tanakazima
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further For those curious, I was not able to boost based on how many occurrences of the word happen in the array. I did however accomplished what I needed with the following:
code :
curl -X POST "http://localhost:9200/index/document/1" -d '{"id":1,"states_ties":["CA"],"state_abbreviation":"CA","worked_in_states":["CA"],"training_in_states":["CA"]}'
curl -X POST "http://localhost:9200/index/document/2" -d '{"id":2,"states_ties":["CA","NY"],"state_abbreviation":"FL","worked_in_states":["NY","CA"],"training_in_states":["NY","CA"]}'
curl -X POST "http://localhost:9200/index/document/3" -d '{"id":3,"states_ties":["CA","NY","FL"],"state_abbreviation":"NY","worked_in_states":["NY","CA"],"training_in_states":["NY","FL"]}'

curl -X GET 'http://localhost:9200/index/_search?per_page=10&pretty' -d '{
  "query": {
    "custom_filters_score": {
      "query": {
        "terms": {
          "states_ties": [
            "CA"
          ]
        }
      },
      "filters": [
        {
          "filter": {
            "term": {
              "state_abbreviation": "CA"
            }
          },
          "boost": 1.03
        },
        {
          "filter": {
            "terms": {
              "worked_in_states": [
                "CA"
              ]
            }
          },
          "boost": 1.02
        },
        {
          "filter": {
            "terms": {
              "training_in_states": [
                "CA"
              ]
            }
          },
          "boost": 1.01
        }
      ],
      "score_mode": "multiply"
    }
  },
  "sort": [
    {
      "_score": "desc"
    }
  ]
}'

results: id: score

1: 0.75584483
2: 0.73383
3: 0.7265643
Sort Array based on number of character occurrences

Sort Array based on number of character occurrences


By : JH4i
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I would create a class that implements the Comparator interface. In the compare method, detect the number of 5 characters there. If the number of 5 characters is equal, then use Integer.parseInt to get the numbers and compare them.
Make sure to return a number less than zero, 0, or greater than zero if the first string should compare less than, equal to, or greater than the second string respectively, to fulfill compare's contract.
how to sort a string array based on elements of another List

how to sort a string array based on elements of another List


By : charlie2ez
Date : March 29 2020, 07:55 AM
To fix this issue I've a string array - lets imagine something like; , I think you want to do something like this:
code :
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var values = new List<string>{"a","b","c","d","e","a","b","c","d","e","a","b","c","d","e"};
        var order = new List<string>{"a","b","c","d","e"};

        var sortedList = SortByList(values, order);

        foreach(var i in sortedList)
        {
            Console.WriteLine(i);
        }
    }
    public static List<string> SortByList(List<string> values, List<string> order){
        return values.OrderBy(x => order.IndexOf(x)).ToList();
    }
}
Find all occurrences of elements in an array in a string

Find all occurrences of elements in an array in a string


By : user2963549
Date : March 29 2020, 07:55 AM
Hope that helps you could use a pipe-delimited regex pattern with the keywords list like this:
code :
const subStrings = ["javascript", "php", "python"];
const regex = subStrings.join("|");


 db.find ({
   body: { $regex: regex, $options: 'i' }
});
Related Posts Related Posts :
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • Drop SQLite tables using list of tables names
  • Can I organize Git submodules in a flat hierarchy?
  • How to make a server reply after receiving a request/data
  • Stored Procedure works in DB but not in C# code
  • MVVM WPF Programmatically add Child Elements
  • NCrunch and PostSharp Logging clash
  • Increasing memory usage in socket client
  • Multiple DropDownList but same action
  • How to get application memory usage as shown in Task Manager?
  • Exposing interfaces instead of concrete classes
  • How to get only postal_code data from google api?
  • Is there a way to get rid of the (by dot42) using community licence?
  • Why must I implement a function for an interface in vb.net which apparently doesn't need to be implemented in C#
  • How to remove HTML tags from the gridview Row
  • Get public post from Facebook's Graph Search API 2.x with Facebook SDK for .NET
  • C# DLL Export to Inno-Setup - Error E0434F4D
  • syntax error insert into database
  • By-pass else block of int.TryParse in Lambda Syntax
  • Retrieve "property getter" from the property name
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org