Contenuto principale

Risultati per

The toughest problem in the Cody Contest 2025 is Clueless - Lord Ned in the Game Room. Thank you Matt Tearle for such as wonderful problem. We can approach this clueless(!) tough problem systematically.
Initialize knowledge Matrix
Based on the hints provided in the problem description, we can initialize a knowledge matrix of size n*3 by m+1. The rows of the knowledge matrix represent the different cards and the columns represent the players. In the knowledge matrix, the first n rows represent category 1 cards, the next n rows, category 2 and the next category 3. We can initialize this matrix with zeros. On the go, once we know that a player holds the card, we can make that entry as 1 and if a player doesn't have the card, we can make that entry as -1.
yourcards processing
These are cards received by us.
  1. In the knowledge matrix, mark the entries as 1 for the cards received. These entries will be the some elements along the column pnum of the knowledge matrix.
  2. Mark all other entries along the column pnum as -1, as we don't receive other cards.
  3. Mark all other entries along the rows corresponding to the received cards as -1, as other players cannot receive the cards that are with us.
commoncards processing
These are the common cards kept open.
  1. In the knowledge matrix, mark the entries as 1 for the common cards. These entries will be some elements along the column (m+1) of the knowledge matrix.
  2. Mark all other entries along the column (m+1) as -1, as other cards are not common.
  3. Mark all other entries along the rows corresponding to the common cards as -1, as other players cannot receive the cards that are common.
Result -1 processing
In the turns input matrix, the result (5th column) value -1 means, the corresponding player doesn't have the 3 cards asked.
  1. Find all the rows with result as -1.
  2. For those corresponding players (1st element in each row of turns matrix), mark -1 entries in the knowledge matrix for those 3 absent cards.
pnum turns processing
These are our turns, so we get definite answers for the asked cards. Make sure to traverse only the rows corresponding to our turn.
  1. The results with -1 are already processed in the previous step.
  2. The results other than -1 means, that particular card is present with the asked player. So mark the entry as 1 for the corresponding player in the knowledge matrix.
  3. Mark all other entries along the row corresponding to step 2 as -1, as other players cannot receive this card.
Result 0 processing
So far, in the yourcards processing, commoncards processing, result -1 processing and pnum turns processing, we had very straightforward definite knowledge about the presence/absence of the card with a player. This step onwards, the tricky part of the problem begins.
result 0 means, any one (or more) of the asked cards are present with the asked player. We don't know exactly which card.
  1. For the asked player, if we have a definite no answer (-1 value in the knowledge matrix) for any two of the three asked cards, then we are sure about the card that is present with the player.
  2. Mark the entry as 1 for the definitely known card for the corresponding player in the knowledge matrix.
  3. Mark all other entries along the row corresponding to step 2 as -1, as other players cannot receive this card.
Cards per Player processing
Based on the number of cards present in the yourcards, we know the ncards, the number of cards per player.
Check along each column of the knowledge matrix, that is for each player.
  1. If the number of ones (definitely present cards) is equal to ncards, we can make all other entries along the column as -1, as this player cannot have any other card.
  2. If the sum of number of ones (definitely present cards) and the number of zeros (unknown cards) is equal to ncards, we can (i) mark the zero entries as one, as the unknown cards have become definitely present cards, (ii) mark all other entries along the column as -1, as other players cannot have any other card.
Category-wise cards checking
For each category, we must get a definite card to be present in the envelope.
  1. In each category (For every group of n rows of knowledge matrix), check for a row with all -1s. That is a card which is definitely not present with any of the players. Then this card will surely be present in the envelope. Add it to the output.
  2. If we could not find an all -1 row, then in that category, check each row for a 1 to be present. Note down the rows which doesn't have a 1. Those cards' players are still unknown. If we have only one such row (unknown card), then it must be in the envelope, as from each category one card is present in the envelope. Add it to the output.
  3. For the card identified in Step 2, mark all the entries along that row in the knowledge matrix as -1, as this card doesn't belong to any player.
Looping Over
In our so far steps, we could note that, the knowledge matrix got updated even after "Result 0 processing" step. This updation in the knowledge matrix may help the "Result 0 processing" step, if we perform it again. So, we can loop over the steps, "Result 0 processing", "Cards per Player processing" and "Category-wise cards checking" again. This ensures that, we will get the desired number of envelop cards (three in our case) as output.
Hoping to see, many of you to finish Cody Contest 2025 and make our team win the trophy.
The Cody Contest 2025 is underway, and it includes a super creative problem group which many of us have found fascinating. The central theme of the problems, expertly curated by @Matt Tearle, humorously revolves around the whims of the capricious dictator Lord Ned, as he goes out of his way to complicate the lives of his subjects and visitors alike. We cannot judge whether or not there's any truth to the rumors behind all the inside jokes, but it's obvious that the team had a lot of fun creating these; and we had even more fun solving them.
Today I want to showcase a way of graphically solving and visualizing one of those problems which I found very elegant, The Bridges of Nedsburg.
To briefly reiterate the problem, the number of islands and the arrangement of bridges of the city of Nedsburg are constantly changing. Lord Ned has decided to take advantage of this by charging visitors with an increasingly expensive n-bridge pass which allows them to cross up to n bridges in one journey. Given the Connectivity Matrix C, we are tasked with calculating the minimum n needed so that there is a path from every island to every other island in n steps or fewer.
Matt kindly provided us with some useful bit of math in the description detailing how to calculate the way to get from one island to another in an number of m steps. However, he has also hidden an alternative path to the solution in plain sight, in one of the graphs he provided. This involves the extremely useful and versatile object digraph, representing directed graphs, which have directional edges connecting the nodes. Here's some further great documentation and other cool resources on the topic for those who are interested in learning more about it:
Let's start using this object to explore a graphical solution to Lord Ned's conundrum. We will use the unit tests included in the problem to visualize the solution. We can retrieve the connectivity matrix for each case using the following function:
function C = getConnectivityMatrix(unit_test)
% Number of islands and bridge arrangement
switch unit_test
case 1
m = 3; idx = [3;4;8];
case 2
m = 3; idx = [3;4;7;8];
case 3
m = 4; idx = [2;7;8;10;13];
case 4
m = 4; idx = [4;5;7;8;9;14];
case 5
m = 5; idx = [5;8;11;12;14;18;22;23];
case 6
m = 5; idx = [2;5;8;14;20;21;24];
case 7
m = 6; idx = [3;4;7;11;18;23;24;26;30;32];
case 8
m = 6; idx = [3;11;12;13;18;19;28;32];
case 9
m = 7; idx = [3;4;6;8;13;14;20;21;23;31;36;47];
case 10
m = 7; idx = [4;11;13;14;19;22;23;26;28;30;34;35;37;38;45];
case 11
m = 8; idx = [2;4;5;6;8;12;13;17;27;39;44;48;54;58;60;62];
case 12
m = 8; idx = [3;9;12;20;24;29;30;31;33;44;48;50;53;54;58];
case 13
m = 9; idx = [8;9;10;14;15;22;25;26;29;33;36;42;44;47;48;50;53;54;55;67;80];
case 14
m = 9; idx = [8;10;22;32;37;40;43;45;47;53;56;57;62;64;69;70;73;77;79];
case 15
m = 10; idx = [2;5;8;13;16;20;24;27;28;36;43;49;53;62;71;75;77;83;86;87;95];
case 16
m = 10; idx = [4;9;14;21;22;35;37;38;44;47;50;51;53;55;59;61;63;66;69;76;77;84;85;86;90;97];
end
C = zeros(m);
C(idx) = 1;
end
The case in the example refers to unit test case 2.
unit_test = 2;
C = getConnectivityMatrix(unit_test);
disp(C)
0 1 1 0 0 1 1 0 0
We now calculate the digraph object D, and visualize it using its corresponding plot method:
D = digraph(C);
figure
p = plot(D,'LineWidth',1.5,'ArrowSize',10);
This is the same as the graph provided in the example. Another very useful method of digraph is shortestpath. This allows us to calculate the path and distance from one single node to another. For example:
% Path and distance from node 1 to node 2
[path12,dist12] = shortestpath(D,1,2);
fprintf('The shortest path from island %d to island %d is: %s. The minimum number of steps is: n = %d\n', 1, 2, join(string(path12), ' -> '),dist12)
The shortest path from island 1 to island 2 is: 1 -> 2. The minimum number of steps is: n = 1
% Path and distance from node 2 to node 1
[path21,dist21] = shortestpath(D,2,1);
fprintf('The shortest path from island %d to island %d is: %s. The minimum number of steps is: n = %d\n', 2, 1, join(string(path21), ' -> '),dist21)
The shortest path from island 2 to island 1 is: 2 -> 3 -> 1. The minimum number of steps is: n = 2
We can visualize these using the highlight method of the graph plot:
figure
p = plot(D,'LineWidth',1.5,'ArrowSize',10);
highlight(p,path12,'EdgeColor','r','NodeColor','r','LineWidth',2)
highlight(p,path21,'EdgeColor',[0 0.8 0],'LineWidth',2)
But that's not all! digraph can also provide us with a matrix of the distances d, i.e. the steps needed to travel from island i to island j, where i and j are the rows and columns of d respectively. This is accomplished by using its distances method. The distance matrix can be visualized as:
d = distances(D);
figure
% Using pcolor w/ appending matrix workaround for convenience
pcolor([d,d(:,end);d(end,:),d(end,end)])
% Alternatively you can use imagesc(d), but you'll have to recreate the grid manually
axis square
set(gca,'YDir','reverse','XTick',[],'YTick',[])
[X,Y] = meshgrid(1:height(d));
text(X(:)+0.5,Y(:)+0.5,string(d(:)),'FontSize',11)
colormap(interp1(linspace(0,1,4), [1 1 1; 0.7 0.9 1; 0.6 0.7 1; 1 0.3 0.3], linspace(0,1,8)))
clim([-0.5 7+0.5])
This confirms what we saw before, i.e. you need 1 step to go from island 1 to island 2, but 2 steps for vice versa. It also confirms that the minimum number of steps n that you need to buy the pass for is 2 (which also occurs for traveling from island 3 to island 2). As it's not the point of the post to give the full solution to the problem but rather present the graphical way of visualizing it I will not include the code of how to calculate this, but I'm sure that by now it's reduced to a trivial problem which you have already figured out how to solve.
That being said, now that we have the distance matrix, let's continue with the visualizations. First, let's plot the corresponding paths for each of these combinations:
figure
tiledlayout(size(C,1),size(C,2),'TileSpacing','tight','Padding','tight');
for i = 1:size(C,1)
for j = 1:size(C,2)
nexttile
p = plot(D,'ArrowSize',10);
highlight(p,shortestpath(D,i,j),'EdgeColor','r','NodeColor','r','LineWidth',2)
lims = axis;
text(lims(1)+diff(lims(1:2))*0.05,lims(3)+diff(lims(3:4))*0.9,sprintf('n = %d',d(i,j)))
end
end
This allows us to go from the distance matrix to visualizing the paths and number of steps for each corresponding case. Things are rather simple for this 3-island example case, but evil Lord Ned is just getting started. Let's now try to solve the problem for all provided unit test cases:
% Cell array of connectivity matrices
C = arrayfun(@getConnectivityMatrix,1:16,'UniformOutput',false);
% Cell array of corresponding digraph objects
D = cellfun(@digraph,C,'UniformOutput',false);
% Cell array of corresponding distance matrices
d = cellfun(@distances,D,'UniformOutput',false);
% id of solutions: Provided as is to avoid handing out the code to the full solution
id = [2, 2, 9, 3, 4, 6, 16, 4, 44, 43, 33, 34, 7, 18, 39, 2];
First, let's plot the distance matrix for each case:
figure
tiledlayout('flow','TileSpacing','compact','Padding','compact');
% Vary this to plot different combinations of cases
plot_cases = 1:numel(C);
for i = plot_cases
nexttile
pcolor([d{i},d{i}(:,end);d{i}(end,:),d{i}(end,end)])
axis square
set(gca,'YDir','reverse','XTick',[],'YTick',[])
title(sprintf('Case %d',i),'FontWeight','normal','FontSize',8)
end
c = colorbar('Ticks',0:7,'TickLength',0,'Limits',[-0.5 7+0.5],'FontSize',8);
c.Layout.Tile = 'East';
c.Label.String = 'Number of Steps';
c.Label.FontSize = 8;
colormap(interp1(linspace(0,1,4), [1 1 1; 0.7 0.9 1; 0.6 0.7 1; 1 0.3 0.3], linspace(0,1,8)))
clim(findobj(gcf,'type','axes'),[-0.5 7+0.5])
We immediately notice some inconsistencies, perhaps to be expected of the eccentric and cunning dictator. Things are pretty simple for the configurations with a small number of islands, but the minimum number of steps n can increase sharply and disproportionally to the additional number of islands. Cases 8 and 9 in particular have a particularly large n (relative to their grid dimensions), and case 14 has the largest n, almost double that of case 16 despite the fact that the latter has one extra island.
To visualize how this is possible, let's plot the path corresponding to the largest n for each case (though note that there might be multiple possible paths for each case):
figure
tiledlayout('flow','TileSpacing','tight','Padding','tight');
for i = plot_cases
nexttile
% Changing the layout to circular so we can better visualize the paths
p = plot(D{i},'ArrowSize',10,'Layout','Circle');
% Alternatively we could use the XData and YData properties if the positions of the islands were provided
axis([-1.5 1.5 -1.5 1.75])
[row,col] = ind2sub(size(d{i}),id(i));
highlight(p,shortestpath(D{i},row,col),'EdgeColor','r','NodeColor','r','LineWidth',2)
lims = axis;
text(lims(1)+diff(lims(1:2))*0.05,lims(3)+diff(lims(3:4))*0.9,sprintf('n = %d',d{i}(row,col)))
end
And busted! Unraveled! Exposed! Lord Ned has clearly been taking advantages of the tectonic forces by instructing his corrupt civil engineer lackeys to design the bridges to purposely force the visitors to go around in circles in order to drain them of their precious savings. In particular, for cases 8 and 9, he would have them go through every single island just to get from one island to another, whereas for case 14 they would have to visit 8 of the 9 islands just to get to their destination. If that's not diabolical then I don't know what is!
Ned jokes aside, I hope you enjoyed this contest just as much as I did, and that you found this article useful. I look forward to seeing more creative problems and solutions in the future.
goc3
goc3
Ultima attività il 10 Nov 2025 alle 17:38

If you have solved a Cody problem before, you have likely seen the Scratch Pad text field below the Solution text field. It provides a quick way to get feedback on your solution before submitting it. Since submitting a solution takes you to a new page, any time a wrong solution is submitted, you have to navigate back to the problem page to try it again.
Instead, I use the Scratch Pad to test my solution repeatedly before submitting. That way, I get to a working solution faster without having to potentially go back and forth many times between the problem page and the wrong-solution page.
Here is my approach:
  1. Write a tentative solution.
  2. Copy a test case from the test suite into the Scratch Pad.
  3. Click the Run Function button—this is immediately below the Scratch Pad and above the Output panel and Submit buttons.
  4. If the solution does not work, modify the solution code, sometimes putting in disp() lines and/or removing semicolons to trace what the code is doing. Repeat until the solution passes.
  5. If the solution does work, repeat steps 2 through 4.
  6. Once there are no more test cases to copy and paste, clean up the code, if necessary (delete disp lines, reinstate all semicolons to suppress output). Click the Run Function button once more, just to make sure I did not break the solution while cleaning it up. Then, click the Submit button.
For problems with large test suites, you may find it useful to copy and paste in multiple test cases per iteration.
Hopefully you find this useful.
Nicolas Douillet
Nicolas Douillet
Ultima attività il 25 Ott 2025 alle 13:09

Hi cody fellows,
I already solved more than 500 problems -months ago, last july if I remember well- and get this scholar badge, but then it suddenly disappeared a few weeks later. I then solved a few more problems and it reappeared.
Now I observed it disappeared once more a few days ago.
Have you also noticed this erratic behavior of the scholar badge ? Is it normal and / or intentional ? If not, how to explain it ? (deleted problems ?)
Cheers,
Nicolas
For some time now, this has been bugging me - so I thought to gather some more feedback/information/opinions on this.
What would you classify Recursion? As a loop or as a vectorized section of code?
For context, this query occured to me while creating Cody problems involving strict (so to speak) vectorization - (Everyone is more than welcome to check my recent Cody questions).
To make problems interesting and/or difficult, I (and other posters) ban functions and functionalities - such as for loops, while loops, if-else statements, arrayfun() and the rest of the fun() family functions. However, some of the solutions including the reference solution I came up with for my latest problem, contained recursion.
I am rather divided on how to categorize it. What do you think?
Hey cody fellows :-) !
I recently created two problem groups, but as you can see I struggle to set their cover images :
What is weird given :
  • I already did it successfully twice in the past for my previous groups ;
  • If you take one problem specifically, Problem 60984. Mesh the icosahedron for instance, you can normally see the icon of the cover image in the top right hand corner, can't you ?
  • I always manage to set cover images to my contributions (mostly in the filexchange).
I already tried several image formats, included .png 4/3 ratio, but still the cover images don't set.
Could you please help me to correctly set my cover images ?
Thank you.
Nicolas
I've been trying this problem a lot of time and i don't understand why my solution doesnt't work.
In 4 tests i get the error Assertion failed but when i run the code myself i get the diag and antidiag correctly.
function [diag_elements, antidg_elements] = your_fcn_name(x)
[m, n] = size(x);
% Inicializar los vectores de la diagonal y la anti-diagonal
diag_elements = zeros(1, min(m, n));
antidg_elements = zeros(1, min(m, n));
% Extraer los elementos de la diagonal
for i = 1:min(m, n)
diag_elements(i) = x(i, i);
end
% Extraer los elementos de la anti-diagonal
for i = 1:min(m, n)
antidg_elements(i) = x(m-i+1, i);
end
end
goc3
goc3
Ultima attività il 3 Dic 2024

I was browsing the MathWorks website and decided to check the Cody leaderboard. To my surprise, William has now solved 5,000 problems. At the moment, there are 5,227 problems on Cody, so William has solved over 95%. The next competitor is over 500 problems behind. His score is also clearly the highest, approaching 60,000.
Please take a moment to congratulate @William.
"What are your favorite features or functionalities in MATLAB, and how have they positively impacted your projects or research? Any tips or tricks to share?
Many MATLAB enthusiasts come Cody to sharpen their skills, face new challenges, and engage in friendly competition. We firmly believe that learning from peers is one of the most effective ways to grow.
With this in mind, the Cody team is thrilled to unveil a new feature aimed at enriching your learning journey: the Cody Discussion Channel. This space is designed for sharing expertise, acquiring new skills, and fostering connections within our community.
On the Cody homepage, you'll now notice a Discussions section, prominently displaying the four most recent posts. For those eager to contribute, we encourage you to familiarize yourself with our posting guidelines before creating a new post. This will help maintain a constructive and valuable exchange of ideas for everyone involved.
Together, let's create an environment where every member feels empowered to share, learn, and connect.
goc3
goc3
Ultima attività il 7 Giu 2024

There are a host of problems on Cody that require manipulation of the digits of a number. Examples include summing the digits of a number, separating the number into its powers, and adding very large numbers together.
If you haven't come across this trick yet, you might want to write it down (or save it electronically):
digits = num2str(4207) - '0'
That code results in the following:
digits =
4 2 0 7
Now, summing the digits of the number is easy:
sum(digits)
ans =
13
Hello and a warm welcome to everyone! We're excited to have you in the Cody Discussion Channel. To ensure the best possible experience for everyone, it's important to understand the types of content that are most suitable for this channel.
Content that belongs in the Cody Discussion Channel:
  • Tips & tricks: Discuss strategies for solving Cody problems that you've found effective.
  • Ideas or suggestions for improvement: Have thoughts on how to make Cody better? We'd love to hear them.
  • Issues: Encountering difficulties or bugs with Cody? Let us know so we can address them.
  • Requests for guidance: Stuck on a Cody problem? Ask for advice or hints, but make sure to show your efforts in attempting to solve the problem first.
  • General discussions: Anything else related to Cody that doesn't fit into the above categories.
Content that does not belong in the Cody Discussion Channel:
  • Comments on specific Cody problems: Examples include unclear problem descriptions or incorrect testing suites.
  • Comments on specific Cody solutions: For example, you find a solution creative or helpful.
Please direct such comments to the Comments section on the problem or solution page itself.
We hope the Cody discussion channel becomes a vibrant space for sharing expertise, learning new skills, and connecting with others.
sky
sky
Ultima attività il 18 Gen 2024

I'm having problem in its test 6 ... passing 5/6 what would be the real issue..
am wring Transformation matrix correct.. as question said SSW should be 202.5 degree...
so what is the issue..
This video discusses the "Cody" bridge, which is a pedestrian bridge over a canal that has been designed to move up and out of the way when ships need to travel through. The mathematics of the bridge movement are discussed and diagrammed. It is unique and educational.
Thats the task:
Given a square cell array:
x = {'01', '56'; '234', '789'};
return a single character array:
y = '0123456789'
I wrote a code that passes Test 1 and 2 and one that passes Test 3 but I'm searching a condition so that the code for Test 3 runs when the cell array only contains letters and the one for Test 1 and 2 in every other case. Can somebody help me?
This is my code:
y = []
[a,b]=size(x)
%%TEST 3
delimiter=zeros(1,a)
delimiter(end)=1
delimiter=repmat(delimiter,1,b)
delimiter(end)=''
delimiter=string(delimiter)
y=[]
for i=1:a*b
y = string([y x(i)])
end
y=join(y,delimiter)
y=erase(y,'0')
y=regexprep(y,'1',' ')
%%TEST 1+2
for i=1:a*b
y = string([y x(i)])
y=join(y)
end
y=erase(y,' ' )
That's the question: Given four different positive numbers, a, b, c and d, provided in increasing order: a < b < c < d, find if any three of them comprise sides of a right-angled triangle. Return true if they do, otherwise return false .
I wrote this code but it doesn't pass test 7. I don't really understand why it isn't working. Can somebody help me?
function flag = isTherePythagoreanTriple(a, b, c, d)
a2=a^2
b2=b^2
c2=c^2
d2=d^2
format shortG
if a2+b2==c2
flag=true
else if a2+b2==d2
flag=true
else if a2+c2==d2
flag=true
else if c2+b2==d2
flag=true
else flag=false
end
end
end
end
end
That's the question:
The file cars.mat contains a table named cars with variables Model, MPG, Horsepower, Weight, and Acceleration for several classic cars.
Load the MAT-file. Given an integer N, calculate the output variable mpg.
Output mpg should contain the MPG of the top N lightest cars (by Weight) in a column vector.
I wrote this code and the resulting column vector has the right values but it doesn't pass the tests. What's wrong?
function mpg = sort_cars(N)
load cars.mat
sorted=sortrows(cars,4)
mpg = sorted(1:N,2)
end
I recently have found that I am no longer able to give my difficulty rating for questions on Cody after sucessfully completing a question. This is obviously not a big deal, I was just wondering if this was an issue on my end or if there was some change that I was not aware of.
The option to rate does not pop up after solving a problem, and the rating in general does not even show up anymore when answering questions (though it is visible from problem groups).
MATLAB users come to Cody to learn MATLAB and the best way to learn is to learn from other community users. However, when you tried to see all solutions, you saw a message that you had to solve a new problem to unlock all the solutions or submit a solution of a smaller size. This is very confusing and we have been hearing this pain point from users.
Today, the Cody team is pleased to announce that players are able to see all solutions to a problem once they solve it correctly.
After solving a problem, you will see a button that says ‘View Community’s Solutions’, which will bring you to the list of all solutions.
Note that this is our first step in facilitating the learning aspect of Cody. We are actively working on improving the solutions list, so your input is valuable to us. Please let us know your comments or suggestions.
When solving problems over on Cody, I can almost always view all solutions to a problem after submitting a correct solution of my own. Very rarely, however, this is not the case, and I instead get the following message:
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.
You may solve another problem from Community group to unlock all the solutions to this problem.
If this happens, then again, I can almost always rectify this by submitting a (correct) solution to a different problem (I take it that the Community group is the implicit group of all problems on Cody --- is it?). But sometimes that, too, fails.
So my question is, why? What are the criteria that determine when all solutions are, in fact, unlocked?
(There is a related question here, but I feel the posted answer does not answer the question.)