Skip to main content

Sort an array by using given digit frequency

Sorting an array by using given digit frequency refers to rearranging the elements of an array in a specific order based on the frequency of a given digit k in each element of the array.


int k = 7;

[-12  15  30  8  171  7  -177  777]
  ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③

Explain
777 : 7 occurs 3 times
177 : 7 occurs 2 times
7 : 7 occurs 1 times
171 : 7 occurs 1 times

In general, sorting an array by using a given digit frequency involves counting the number of times the digit appears in each element, and then sorting the elements based on those counts. The specific order in which the elements are sorted will depend on the desired criteria (e.g., highest to lowest frequency, lowest to highest frequency, etc.).

import java.util.HashMap;
import java.util.ArrayList;
/*
    Java program for
    Sort an array by using given digit frequency
*/
public class Sorting
{

    public void printArray(int []arr, int n)
    {
        for (int i = 0; i < n ; ++i ) 
        {
            System.out.print("  "+arr[i]);    
        }

    }
    public int countDigit(int number, int k)
    {
        int n = number;
        if (n < 0)
        {
            // Convert negative number to positive number
            n = -n;
        }
        int count = 0;
        while (n != 0)
        {
            if(n % 10 == k)
            {
                count++;
            }
        
            // Remove last digit
            n = n / 10;
        }
        return count;
    }
    public void sortByDigitFrequency(int []arr, int n, int k)
    {
        if(k < 0 || k > 9)
        {
           
            // When k is not a valid single digit
            return ;
        }
        HashMap < Integer, ArrayList < Integer >> record = 
          new HashMap < Integer, ArrayList < Integer >> ();

        int frequency ;

        int index = 0;
        int max = 0;

        for (int i = 0; i < n ; ++i) 
        {
            
            frequency =  countDigit(arr[i],k);

            if(!record.containsKey(frequency))
            {
                record.put(frequency,new ArrayList<Integer>());
            }
            // Collect elements by frequency
            record.get(frequency).add(arr[i]);

            if(frequency > max)
            {
                max = frequency;
            }
        }

        frequency = 0;

        while(frequency <= max)
        {

            if(record.containsKey(frequency))
            {
                // Assign elements by frequency
                for ( int v : record.get(frequency) ) 
                {
                    arr[index] = v;

                    index++;    
                }
            }
            frequency ++;
        }

    }
    public static void main(String[] args)
    {

        Sorting task = new Sorting();

        int []arr = { 171, -12, -177, 15, 777, 30, 7 , 8 };

        // Get the number of elements
        int n = arr.length;

        // digit
        int k = 7;
        /*
            arr = [171, -12, -177, 15, 777, 30, 7 , 8]
            k = 7

                
                 [171, -12, -177, 15, 777, 30, 7 , 8]
                  │      │    │    │   │    │  │   │
                  │      │    │    │   │    │  │   │                  
                  │      │    │    │   │    │  │   │ 
                  ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
                ----------------------------------------
                        Occurrence of given K
                ---------------------------------------
                    

                [-12  15  30  8  171  7  -177  777]
                  ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
                --------------------------------------
                        Sort by Occurrence  
        */ 
        task.sortByDigitFrequency(arr,n,k); 

        // After sort
        // Display array elements
        task.printArray(arr,n);

    }
}

Output

  -12  15  30  8  171  7  -177  777
// Include header file
#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;
/*
    C++ program for
    Sort an array by using given digit frequency
*/
class Sorting
{
	public: void printArray(int arr[], int n)
	{
		for (int i = 0; i < n; ++i)
		{
			cout << "  " << arr[i];
		}
	}
	int countDigit(int number, int k)
	{
		int n = number;
		if (n < 0)
		{
			// Convert negative number to positive number
			n = -n;
		}
		int count = 0;
		while (n != 0)
		{
			if (n % 10 == k)
			{
				count++;
			}
			// Remove last digit
			n = n / 10;
		}
		return count;
	}
	void sortByDigitFrequency(int arr[], int n, int k)
	{
		if (k < 0 || k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		unordered_map < int, vector < int > > record;
		int frequency;
		int index = 0;
		int max = 0;
		for (int i = 0; i < n; ++i)
		{
			frequency = this->countDigit(arr[i], k);
			// Collect elements by frequency
			record[frequency].push_back(arr[i]);
			if (frequency > max)
			{
				max = frequency;
			}
		}
		frequency = 0;
		while (frequency <= max)
		{
			if (record.find(frequency) != record.end())
			{
				// Assign elements by frequency
				for (auto &v: record[frequency])
				{
					arr[index] = v;
					index++;
				}
			}
			frequency++;
		}
	}
};
int main()
{
	Sorting *task = new Sorting();
	int arr[] = {
		171 , -12 , -177 , 15 , 777 , 30 , 7 , 8
	};
	// Get the number of elements
	int n = sizeof(arr) / sizeof(arr[0]);
	// digit
	int k = 7;
	/*
	    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	    k = 7
	        
	         [171, -12, -177, 15, 777, 30, 7 , 8]
	          │      │    │    │   │    │  │   │
	          │      │    │    │   │    │  │   │                  
	          │      │    │    │   │    │  │   │ 
	          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	        ----------------------------------------
	                Occurrence of given K
	        ---------------------------------------
	            
	        [-12  15  30  8  171  7  -177  777]
	          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	        --------------------------------------
	                Sort by Occurrence  
	*/
	task->sortByDigitFrequency(arr, n, k);
	// After sort
	// Display array elements
	task->printArray(arr, n);
	return 0;
}

Output

  -12  15  30  8  171  7  -177  777
// Include namespace system
using System;
using System.Collections.Generic;
/*
    Csharp program for
    Sort an array by using given digit frequency
*/
public class Sorting
{
	public void printArray(int[] arr, int n)
	{
		for (int i = 0; i < n; ++i)
		{
			Console.Write("  " + arr[i]);
		}
	}
	public int countDigit(int number, int k)
	{
		int n = number;
		if (n < 0)
		{
			// Convert negative number to positive number
			n = -n;
		}
		int count = 0;
		while (n != 0)
		{
			if (n % 10 == k)
			{
				count++;
			}
			// Remove last digit
			n = n / 10;
		}
		return count;
	}
	public void sortByDigitFrequency(int[] arr, int n, int k)
	{
		if (k < 0 || k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		Dictionary < int, List < int >> record = 
          new Dictionary < int, List < int >> ();
		int frequency;
		int index = 0;
		int max = 0;
		for (int i = 0; i < n; ++i)
		{
			frequency = this.countDigit(arr[i], k);
			if (!record.ContainsKey(frequency))
			{
				record.Add(frequency, new List < int > ());
			}
			// Collect elements by frequency
			record[frequency].Add(arr[i]);
			if (frequency > max)
			{
				max = frequency;
			}
		}
		frequency = 0;
		while (frequency <= max)
		{
			if (record.ContainsKey(frequency))
			{
				// Assign elements by frequency
				foreach(int v in record[frequency])
				{
					arr[index] = v;
					index++;
				}
			}
			frequency++;
		}
	}
	public static void Main(String[] args)
	{
		Sorting task = new Sorting();
		int[] arr = {
			171 , -12 , -177 , 15 , 777 , 30 , 7 , 8
		};
		// Get the number of elements
		int n = arr.Length;
		// digit
		int k = 7;
		/*
		    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
		    k = 7
		        
		         [171, -12, -177, 15, 777, 30, 7 , 8]
		          │      │    │    │   │    │  │   │
		          │      │    │    │   │    │  │   │                  
		          │      │    │    │   │    │  │   │ 
		          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
		        ----------------------------------------
		                Occurrence of given K
		        ---------------------------------------
		            
		        [-12  15  30  8  171  7  -177  777]
		          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
		        --------------------------------------
		                Sort by Occurrence  
		*/
		task.sortByDigitFrequency(arr, n, k);
		// After sort
		// Display array elements
		task.printArray(arr, n);
	}
}

Output

  -12  15  30  8  171  7  -177  777
package main
import "fmt"
/*
    Go program for
    Sort an array by using given digit frequency
*/

func printArray(arr[] int, n int) {
	for i := 0 ; i < n ; i++ {
		fmt.Print("  ", arr[i])
	}
}
func countDigit(number, k int) int {
	var n int = number
	if n < 0 {
		// Convert negative number to positive number
		n = -n
	}
	var count int = 0
	for (n != 0) {
		if n % 10 == k {
			count++
		}
		// Remove last digit
		n = n / 10
	}
	return count
}
func sortByDigitFrequency(arr[] int, n int, k int) {
	if k < 0 || k > 9 {
		// When k is not a valid single digit
		return
	}
	var record = make(map[int] []int )
	var frequency int
	var index int = 0
	var max int = 0
	for i := 0 ; i < n ; i++ {
		frequency = countDigit(arr[i], k)
		if _, found := record[frequency] ; !found {
			record[frequency] = make([]int,0)
		}
		// Collect elements by frequency
		record[frequency] = append(record[frequency], arr[i])
		if frequency > max {
			max = frequency
		}
	}
	frequency = 0
	for (frequency <= max) {
		if _, found := record[frequency] ; found {
			var value = record[frequency]
			// Assign elements by frequency
			for i := 0 ; i < len(value) ; i++ {
				arr[index] = value[i]
				index++
			}
		}
		frequency++
	}
}
func main() {

	var arr = [] int {171 , -12 , -177 , 15 , 777 , 30 , 7 , 8}
	// Get the number of elements
	var n int = len(arr)
	// digit
	var k int = 7
	/*
	    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	    k = 7
	        
	         [171, -12, -177, 15, 777, 30, 7 , 8]
	          │      │    │    │   │    │  │   │
	          │      │    │    │   │    │  │   │                  
	          │      │    │    │   │    │  │   │ 
	          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	        ----------------------------------------
	                Occurrence of given K
	        ---------------------------------------
	            
	        [-12  15  30  8  171  7  -177  777]
	          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	        --------------------------------------
	                Sort by Occurrence  
	*/
	sortByDigitFrequency(arr, n, k)
	// After sort
	// Display array elements
	printArray(arr, n)
}

Output

  -12  15  30  8  171  7  -177  777
<?php
/*
    Php program for
    Sort an array by using given digit frequency
*/
class Sorting
{
	public	function printArray($arr, $n)
	{
		for ($i = 0; $i < $n; ++$i)
		{
			echo("  ".$arr[$i]);
		}
	}
	public	function countDigit($number, $k)
	{
		$n = $number;
		if ($n < 0)
		{
			// Convert negative number to positive number
			$n = -$n;
		}
		$count = 0;
		while ($n != 0)
		{
			if ($n % 10 == $k)
			{
				$count++;
			}
			// Remove last digit
			$n = (int)($n / 10);
		}
		return $count;
	}
	public	function sortByDigitFrequency(&$arr, $n, $k)
	{
		if ($k < 0 || $k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		$record = array();
		$frequency;
		$index = 0;
		$max = 0;
		for ($i = 0; $i < $n; ++$i)
		{
			$frequency = $this->countDigit($arr[$i], $k);
			if (!array_key_exists($frequency, $record))
			{
				$record[$frequency] = array();
			}
			// Collect elements by frequency
			$record[$frequency][] = $arr[$i];
			if ($frequency > $max)
			{
				$max = $frequency;
			}
		}
		$frequency = 0;
		while ($frequency <= $max)
		{
			if (array_key_exists($frequency, $record))
			{
				// Assign elements by frequency
				foreach($record[$frequency] as $key => $value)
				{
					$arr[$index] = $value;
					$index++;
				}
			}
			$frequency++;
		}
	}
}

function main()
{
	$task = new Sorting();
	$arr = array(171, -12, -177, 15, 777, 30, 7, 8);
	// Get the number of elements
	$n = count($arr);
	// digit
	$k = 7;
	/*
	    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	    k = 7
	        
	         [171, -12, -177, 15, 777, 30, 7 , 8]
	          │      │    │    │   │    │  │   │
	          │      │    │    │   │    │  │   │                  
	          │      │    │    │   │    │  │   │ 
	          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	        ----------------------------------------
	                Occurrence of given K
	        ---------------------------------------
	            
	        [-12  15  30  8  171  7  -177  777]
	          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	        --------------------------------------
	                Sort by Occurrence  
	*/
	$task->sortByDigitFrequency($arr, $n, $k);
	// After sort
	// Display array elements
	$task->printArray($arr, $n);
}
main();

Output

  -12  15  30  8  171  7  -177  777
/*
    Node JS program for
    Sort an array by using given digit frequency
*/
class Sorting
{
	printArray(arr, n)
	{
		for (var i = 0; i < n; ++i)
		{
			process.stdout.write("  " + arr[i]);
		}
	}
	countDigit(number, k)
	{
		var n = number;
		if (n < 0)
		{
			// Convert negative number to positive number
			n = -n;
		}
		var count = 0;
		while (n != 0)
		{
			if (n % 10 == k)
			{
				count++;
			}
			// Remove last digit
			n = parseInt(n / 10);
		}
		return count;
	}
	sortByDigitFrequency(arr, n, k)
	{
		if (k < 0 || k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		var record = new Map();
		var index = 0;
		var max = 0;
      	var frequency = 0;
		for (var i = 0; i < n; ++i)
		{
			frequency = this.countDigit(arr[i], k);
			if (!record.has(frequency))
			{
				record.set(frequency, []);
			}
			// Collect elements by frequency
			record.get(frequency).push(arr[i]);
			if (frequency > max)
			{
				max = frequency;
			}
		}
		frequency = 0;
		while (frequency <= max)
		{
			if (record.has(frequency))
			{
              	let value = record.get(frequency);
              	
				// Assign elements by frequency
				for (var i = 0; i < value.length; ++ i)
				{
					arr[index] = value[i];
					index++;
				}
			}
			frequency++;
		}
	}
}

function main()
{
	var task = new Sorting();
	var arr = [171, -12, -177, 15, 777, 30, 7, 8];
	// Get the number of elements
	var n = arr.length;
	// digit
	var k = 7;
	/*
	    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	    k = 7
	        
	         [171, -12, -177, 15, 777, 30, 7 , 8]
	          │      │    │    │   │    │  │   │
	          │      │    │    │   │    │  │   │                  
	          │      │    │    │   │    │  │   │ 
	          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	        ----------------------------------------
	                Occurrence of given K
	        ---------------------------------------
	            
	        [-12  15  30  8  171  7  -177  777]
	          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	        --------------------------------------
	                Sort by Occurrence  
	*/
	task.sortByDigitFrequency(arr, n, k);
	// After sort
	// Display array elements
	task.printArray(arr, n);
}
main();

Output

  -12  15  30  8  171  7  -177  777
#    Python 3 program for
#    Sort an array by using given digit frequency
class Sorting :
	def printArray(self, arr, n) :
		i = 0
		while (i < n) :
			print("  ", arr[i], end = "")
			i += 1
		
	
	def countDigit(self, number, k) :
		n = number
		if (n < 0) :
			#  Convert negative number to positive number
			n = -n
		
		count = 0
		while (n != 0) :
			if (n % 10 == k) :
				count += 1
			
			#  Remove last digit
			n = int(n / 10)
		
		return count
	
	def sortByDigitFrequency(self, arr, n, k) :
		if (k < 0 or k > 9) :
			#  When k is not a valid single digit
			return
		
		record = dict()
		index = 0
		max = 0
		i = 0
		while (i < n) :
			frequency = self.countDigit(arr[i], k)
			if (not(frequency in record.keys())) :
				record[frequency] = []
			
			#  Collect elements by frequency
			record.get(frequency).append(arr[i])
			if (frequency > max) :
				max = frequency
			
			i += 1
		
		frequency = 0
		while (frequency <= max) :
			if ((frequency in record.keys())) :
				for v in record.get(frequency):
					arr[index] = v
					index += 1
				
			
			frequency += 1
		
	

def main() :
	task = Sorting()
	arr = [171, -12, -177, 15, 777, 30, 7, 8]
	#  Get the number of elements
	n = len(arr)
	#  digit
	k = 7
	#    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	#    k = 7
	#         [171, -12, -177, 15, 777, 30, 7 , 8]
	#          │      │    │    │   │    │  │   │
	#          │      │    │    │   │    │  │   │                  
	#          │      │    │    │   │    │  │   │ 
	#          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	#        ----------------------------------------
	#                Occurrence of given K
	#        ---------------------------------------
	#        [-12  15  30  8  171  7  -177  777]
	#          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	#        --------------------------------------
	#                Sort by Occurrence  
	task.sortByDigitFrequency(arr, n, k)
	#  After sort
	#  Display list elements
	task.printArray(arr, n)

if __name__ == "__main__": main()

Output

   -12   15   30   8   171   7   -177   777
#    Ruby program for
#    Sort an array by using given digit frequency
class Sorting 
	def printArray(arr, n) 
		i = 0
		while (i < n) 
			print("  ", arr[i])
			i += 1
		end

	end

	def countDigit(number, k) 
		n = number
		if (n < 0) 
			#  Convert negative number to positive number
			n = -n
		end

		count = 0
		while (n != 0) 
			if (n % 10 == k) 
				count += 1
			end

			#  Remove last digit
			n = n / 10
		end

		return count
	end

	def sortByDigitFrequency(arr, n, k) 
		if (k < 0 || k > 9) 
			#  When k is not a valid single digit
			return
		end

		record = Hash.new()
		index = 0
		max = 0
		i = 0
		while (i < n) 
			frequency = self.countDigit(arr[i], k)
			if (!record.key?(frequency)) 
				record[frequency] = []
			end

			#  Collect elements by frequency
			record[frequency].push(arr[i])
			if (frequency > max) 
				max = frequency
			end

			i += 1
		end

		frequency = 0
		while (frequency <= max) 
			if (record.key?(frequency)) 
                v = record[frequency]
            	i = 0
				#  Assign elements by frequency
				while (i < v.size()) 
					arr[index] = v[i]
					index += 1
					i += 1
				end

			end

			frequency += 1
		end

	end

end

def main() 
	task = Sorting.new()
	arr = [171, -12, -177, 15, 777, 30, 7, 8]
	#  Get the number of elements
	n = arr.length
	#  digit
	k = 7
	#    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	#    k = 7
	#         [171, -12, -177, 15, 777, 30, 7 , 8]
	#          │      │    │    │   │    │  │   │
	#          │      │    │    │   │    │  │   │                  
	#          │      │    │    │   │    │  │   │ 
	#          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	#        ----------------------------------------
	#                Occurrence of given K
	#        ---------------------------------------
	#        [-12  15  30  8  171  7  -177  777]
	#          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	#        --------------------------------------
	#                Sort by Occurrence  
	task.sortByDigitFrequency(arr, n, k)
	#  After sort
	#  Display array elements
	task.printArray(arr, n)
end

main()

Output

  -12  15  30  8  171  7  -177  777
import scala.collection.mutable._;
/*
    Scala program for
    Sort an array by using given digit frequency
*/
class Sorting()
{
	def printArray(arr: Array[Int], n: Int): Unit = {
		var i: Int = 0;
		while (i < n)
		{
			print("  " + arr(i));
			i += 1;
		}
	}
	def countDigit(number: Int, k: Int): Int = {
		var n: Int = number;
		if (n < 0)
		{
			// Convert negative number to positive number
			n = -n;
		}
		var count: Int = 0;
		while (n != 0)
		{
			if (n % 10 == k)
			{
				count += 1;
			}
			// Remove last digit
			n = n / 10;
		}
		return count;
	}
	def sortByDigitFrequency(arr: Array[Int], n: Int, k: Int): Unit = {
		if (k < 0 || k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		var record: HashMap[Int, ArrayBuffer[Int]] = 
          new HashMap[Int, ArrayBuffer[Int]]();
		var frequency: Int = 0;
		var index: Int = 0;
		var max: Int = 0;
		var i: Int = 0;
		while (i < n)
		{
			frequency = countDigit(arr(i), k);
			if (!record.contains(frequency))
			{
				record.addOne(frequency, new ArrayBuffer[Int]());
			}
			// Collect elements by frequency
			record.get(frequency).get += arr(i);
			if (frequency > max)
			{
				max = frequency;
			}
			i += 1;
		}
		frequency = 0;
		while (frequency <= max)
		{
			if (record.contains(frequency))
			{
				// Assign elements by frequency
				for ((value) <- record.get(frequency).get)
				{
					arr(index) = value;
					index += 1;
				}
			}
			frequency += 1;
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Sorting = new Sorting();
		var arr: Array[Int] = Array(171, -12, -177, 15, 777, 30, 7, 8);
		// Get the number of elements
		var n: Int = arr.length;
		// digit
		var k: Int = 7;
		/*
		    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
		    k = 7
		        
		         [171, -12, -177, 15, 777, 30, 7 , 8]
		          │      │    │    │   │    │  │   │
		          │      │    │    │   │    │  │   │                  
		          │      │    │    │   │    │  │   │ 
		          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
		        ----------------------------------------
		                Occurrence of given K
		        ---------------------------------------
		            
		        [-12  15  30  8  171  7  -177  777]
		          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
		        --------------------------------------
		                Sort by Occurrence  
		*/
		task.sortByDigitFrequency(arr, n, k);
		// After sort
		// Display array elements
		task.printArray(arr, n);
	}
}

Output

  -12  15  30  8  171  7  -177  777
import Foundation;
/*
    Swift 4 program for
    Sort an array by using given digit frequency
*/
class Sorting
{
	func printArray(_ arr: [Int], _ n: Int)
	{
		var i: Int = 0;
		while (i < n)
		{
			print("  ", arr[i], terminator: "");
			i += 1;
		}
	}
	func countDigit(_ number: Int, _ k: Int) -> Int
	{
		var n: Int = number;
		if (n < 0)
		{
			// Convert negative number to positive number
			n = -n;
		}
		var count: Int = 0;
		while (n  != 0)
		{
			if (n % 10 == k)
			{
				count += 1;
			}
			// Remove last digit
			n = n / 10;
		}
		return count;
	}
	func sortByDigitFrequency(_ arr: inout[Int], _ n: Int, _ k: Int)
	{
		if (k < 0 || k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		var record = [Int : [Int] ]();
		var frequency: Int;
		var index: Int = 0;
		var max: Int = 0;
		var i: Int = 0;
		while (i < n)
		{
			frequency = self.countDigit(arr[i], k);
			if (!record.keys.contains(frequency))
			{
				record[frequency] = [Int]();
			}
			// Collect elements by frequency
			record[frequency]!.append(arr[i]);
			if (frequency > max)
			{
				max = frequency;
			}
			i += 1;
		}
		frequency = 0;
		while (frequency <= max)
		{
			if (record.keys.contains(frequency))
			{
              	let value: [Int] = record[frequency]!;
                i = 0;
				// Assign elements by frequency
				while (i < value.count)
				{
					arr[index] = value[i];
					index += 1;
                  	i += 1;
				}
			}
			frequency += 1;
		}
	}
}
func main()
{
	let task: Sorting = Sorting();
	var arr: [Int] = [171, -12, -177, 15, 777, 30, 7, 8];
	// Get the number of elements
	let n: Int = arr.count;
	// digit
	let k: Int = 7;
	/*
	    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	    k = 7
	        
	         [171, -12, -177, 15, 777, 30, 7 , 8]
	          │      │    │    │   │    │  │   │
	          │      │    │    │   │    │  │   │                  
	          │      │    │    │   │    │  │   │ 
	          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	        ----------------------------------------
	                Occurrence of given K
	        ---------------------------------------
	            
	        [-12  15  30  8  171  7  -177  777]
	          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	        --------------------------------------
	                Sort by Occurrence  
	*/
	task.sortByDigitFrequency(&arr, n, k);
	// After sort
	// Display array elements
	task.printArray(arr, n);
}
main();

Output

   -12   15   30   8   171   7   -177   777
/*
    Kotlin program for
    Sort an array by using given digit frequency
*/
class Sorting
{
	fun printArray(arr: Array < Int > , n: Int): Unit
	{
		var i: Int = 0;
		while (i < n)
		{
			print("  " + arr[i]);
			i += 1;
		}
	}
	fun countDigit(number: Int, k: Int): Int
	{
		var n: Int = number;
		if (n < 0)
		{
			// Convert negative number to positive number
			n = -n;
		}
		var count: Int = 0;
		while (n != 0)
		{
			if (n % 10 == k)
			{
				count += 1;
			}
			// Remove last digit
			n = n / 10;
		}
		return count;
	}
	fun sortByDigitFrequency(arr: Array < Int > , n: Int, k: Int): Unit
	{
		if (k < 0 || k > 9)
		{
			// When k is not a valid single digit
			return;
		}
		var record = HashMap < Int,MutableList< Int >> ();
		var frequency: Int;
		var index: Int = 0;
		var max: Int = 0;
		var i: Int = 0;
		while (i < n)
		{
			frequency = this.countDigit(arr[i], k);
			if (!record.containsKey(frequency))
			{
				record.put(frequency, mutableListOf < Int > ());
			}
			// Collect elements by frequency
			record.getValue(frequency).add(arr[i]);
			if (frequency > max)
			{
				max = frequency;
			}
			i += 1;
		}
		frequency = 0;
		while (frequency <= max)
		{
			if (record.containsKey(frequency))
			{
				// Assign elements by frequency
				for (v in record.getValue(frequency))
				{
					arr[index] = v;
					index += 1;
				}
			}
			frequency += 1;
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val task: Sorting = Sorting();
	val arr: Array < Int > = arrayOf(171, -12, -177, 15, 777, 30, 7, 8);
	// Get the number of elements
	val n: Int = arr.count();
	// digit
	val k: Int = 7;
	/*
	    arr = [171, -12, -177, 15, 777, 30, 7 , 8]
	    k = 7
	        
	         [171, -12, -177, 15, 777, 30, 7 , 8]
	          │      │    │    │   │    │  │   │
	          │      │    │    │   │    │  │   │                  
	          │      │    │    │   │    │  │   │ 
	          ①     ⓪    ②   ⓪  ③   ⓪  ①  ⓪
	        ----------------------------------------
	                Occurrence of given K
	        ---------------------------------------
	            
	        [-12  15  30  8  171  7  -177  777]
	          ⓪   ⓪  ⓪  ⓪  ①  ①   ②   ③
	        --------------------------------------
	                Sort by Occurrence  
	*/
	task.sortByDigitFrequency(arr, n, k);
	// After sort
	// Display array elements
	task.printArray(arr, n);
}

Output

  -12  15  30  8  171  7  -177  777




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment