In this post I will show you the solution to the Task 2 of this week’s Weekly Challenge 233. This time I was using the help of ChatGPT, which offered a very nice solution.
Task 2: Frequency Sort
You are given an array of integers.
Write a script to sort the given array in increasing order based on the frequency of the values. If multiple values have the same frequency then sort them in decreasing order.
Example 1
Input: @ints = (1,1,2,2,2,3)
Ouput: (3,1,1,2,2,2)
'3' has a frequency of 1
'1' has a frequency of 2
'2' has a frequency of 3
Example 2
Input: @ints = (2,3,1,3,2)
Ouput: (1,3,3,2,2)
'2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
Example 3
Input: @ints = (-1,1,-6,4,5,-6,1,4,1)
Ouput: (5,-1,4,4,-6,-6,1,1,1)
I asked ChatGPT the following: ‘Create a program. Here is the description of the task.’ To make sure the result is in the Raku programming language, I also added the following instruction in my local settings so that it knows which programming language I prefer by default.
The solution generated by ChatGPT was quite good with a small mistake.
ChatGPT: Sure, here’s a Raku program that implements the described sorting algorithm for the given task:
sub frequency-sort(@arr) { my %freq; %freq{$_}++ for @arr; my @sorted = @arr.sort: { %freq{$^b} <=> %freq{$^a} || $^b <=> $^a }; return @sorted; } my @ints = (1, 1, 2, 2, 2, 3); my @sorted = frequency-sort(@ints); say "Input: @ints"; say "Output: @sorted";
First, Raku would not interpolate arrays, so say "Input: @ints"
prints the string literary: Input: @ints
. Second, in the sorting rule, sorting by frequency must be ascending rather than descending, so we need to switch the placeholder variables $^b
and $^a
.
In the rest, ChatGPT did a good work. It computed the frequency using a loop, and I especially liked how it addressed the requirement to sort by two dimensions.
Here is the full program with the above-mentioned corrections:
sub frequency-sort(@arr) { my %freq; %freq{$_}++ for @arr; my @sorted = @arr.sort: { %freq{$^a} <=> %freq{$^b} || $^b <=> $^a }; return @sorted; } my @tests = (1, 1, 2, 2, 2, 3), (2, 3, 1, 3, 2), (-1, 1, -6, 4, 5, -6, 1, 4, 1); say frequency-sort($_) for @tests;
This program prints the following output for the given test cases:
$ raku ch-2.raku [3 1 1 2 2 2] [1 3 3 2 2] [5 -1 4 4 -6 -6 1 1 1]
Just wondering: is it necessary to put the Raku language requirement in the “Custom Instructions” settings? Could you have instead asked “Create a Raku program. Here is the description of the task.’?
Of course, you can add this to the request directly in the chat. I just made it simpler for me to avoid repeating this when I play with other tasks. On the other side, it breaks all other non-programming questions 🙂