Results for
Hi Everyone!
As this is the most difficult question in problem group "Cody Contest 2025". To solve this problem, It is very important to understand all the hidden clues in the problem statement. Because everything is not directly visible.
For those who tried the problem, but were not able to solve. You might have missed any of the below hints -
- “The other players do not get to see which card has been shown, but they do know which three cards were asked for and that the player asked had one of them.” - Even when the card identity isn’t revealed (result = 0), you still gain partial knowledge — the asked player must have at least one of those three cards, meaning you can mark other players as not having all three simultaneously.
- "If it is your turn, you know the exact identity of that card" - You only know the exact shown card when result = 1, 2, or 3 — and it must be your turn. If someone else asked (even if you know result = 0), you don’t know which one was shown. So the meaning of result depends on whose turn it was, which is implicit — MATLAB code must assume that turns alternate 1→m→1, so your turn index is determined by (t-1) mod m + 1 == pnum.
- "Any leftover cards are placed face-up so that all players can see them" - These cards (commoncards) are not in anyone’s hand and cannot be in the envelope. So they’re not just visible — they’re logical constraints to eliminate from deduction.
- “It may be possible to determine the solution from less information than is given, but the information given will always be sufficient.”
- "Turn order is implied, not given explicitly" - Players take turns in order (1 to m, and back to 1).
On considering all the clues and constraints in the question, you will definitely be able to card for each category present in envelope.
I hope above clues will be useful for you.
Thank you, wishing you the success!
Regards,
Dev
Instead of growing arrays inside a loop, preallocate with zeros(), ones(), or nan(). It avoids memory fragmentation and speeds up Cody solutions.
A = zeros(1,1000);
Cody often hides subtle hints in example outputs — like data shape, rounding, or format. Matching those exactly saves you a lot of debugging time.
When solving Cody problems, sometimes your solution takes too long — especially if you’re recomputing large arrays or iterative sequences every time your function is called.
The Cody work area resets between separate runs of your code, but within one Cody test suite, your function may be called multiple times in a single session.
This is where persistent variables come in handy.
A persistent variable keeps its value between function calls, but only while MATLAB is still running your function suite.
This means:
- You can cache results to avoid recomputation.
- You can accumulate data across multiple calls.
- But it resets when Cody or MATLAB restarts.
Suppose you’re asked to find the n-th Fibonacci number efficiently — Cody may time out if you use recursion naively. Here’s how to use persistent to store computed values:
function f = fibPersistent(n)
import java.math.BigInteger
persistent F
if isempty(F)
F=[BigInteger('0'),BigInteger('1')];
for k=3:10000
F(k)=F(k-1).add(F(k-2));
end
end
% Extend the stored sequence only if needed
while length(F) <= n
F(end+1)=F(end).add(F(end-1));
end
f = char(F(n+1).toString); % since F(1) is really F(0)
end
%calling function 100 times
K=arrayfun(@(x)fibPersistent(x),randi(10000,1,100),'UniformOutput',false);
K(100)
The fzero function can handle extremely messy equations — even those mixing exponentials, trigonometric, and logarithmic terms — provided the function is continuous near the root and you give a reasonable starting point or interval.
It’s ideal for cases like:
- Solving energy balance equations
- Finding intersection points of nonlinear models
- Determining parameters from experimental data
Example: Solving for Equilibrium Temperature in a Heat Radiation-Conduction Model
Suppose a spacecraft component exchanges heat via conduction and radiation with its environment. At steady state, the power generated internally equals the heat lost:
Given constants:
= 25 W- k = 0.5 W/K
- ϵ = 0.8
- σ = 5.67e−8 W/m²K⁴
- A = 0.1 m²
= 250 K
Find the steady-state temperature, T.
% Given constants
Qgen = 25;
k = 0.5;
eps = 0.8;
sigma = 5.67e-8;
A = 0.1;
Tinf = 250;
% Define the energy balance equation (set equal to zero)
f = @(T) Qgen - (k*(T - Tinf) + eps*sigma*A*(T.^4 - Tinf^4));
% Plot for a sense of where the root lies before implementing
fplot(f, [250 300]); grid on
xlabel('Temperature (K)'); ylabel('f(T)')
title('Energy Balance: Root corresponds to steady-state temperature')
% Use fzero with an interval that brackets the root
T_eq = fzero(f, [250 300]);
fprintf('Steady-state temperature: %.2f K\n', T_eq);
Don’t miss out on two incredible keynotes that will shape the future of engineering and innovation:
1️⃣What’s New in MATLAB and Simulink in 2025
Get an inside look at the latest features designed to supercharge your workflows:
- A redesigned MATLAB desktop with customizable sidebars, light/dark themes, and new panels for coding tasks
- MATLAB Copilot – your AI-powered assistant for learning, idea generation, and productivity
- Simulink upgrades, including an enhanced quick insert tool, auto-straightening signal lines, and new methods for Python integration
- New options to deploy AI models on Qualcomm and Infineon hardware
2️⃣Accelerating Software-Defined Vehicles with Model-Based Design
See how MathWorks + NXP are transforming embedded system development for next-gen vehicles:
- Vehicle electrification example powered by MATLAB, Simulink, and NXP tools
- End-to-end workflow: modeling → validation → code generation → hardware deployment → real-time cloud monitoring
📅 When: November 13
💡Why Join? Stay ahead with cutting-edge tools, workflows, and insights from industry leaders.
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 there's any truth or not 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 to graphically solve and visualize 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 fact by charging visitors with an increasingly expensive n-bridge pass which allows them to cross up to n bridges in one journey. Provided 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 useleful 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. Some further useful documentation 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 or islands and 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 refets to unit test case 2.
unit_test = 2;
C = getConnectivityMatrix(unit_test);
disp(C)
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 you 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)
% 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)
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 method distances. The distance matrix can be vizualized 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');
set(gca,{'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
hold on
box on
set(gca,{'XTick','YTick'},{[],[]});
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))) % Or use from shortest path
end
end
This allows us to go from the distance matrix to vizualizing the paths and number of steps for each corresponding case. Things are rather simple for the this 3-island example case, but evil Lord Ned is just getting started. Let's now try to solve to 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
hold on
box on
axis tight square
pcolor([d{i},d{i}(:,end);d{i}(end,:),d{i}(end,end)]);
set(gca,'YDir','reverse');
set(gca,{'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 relatively large n (proportional 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
hold on
box on
set(gca,{'XTick','YTick'},{[],[]});
% 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)),'HorizontalAlignment','Left')
end
And busted! Lord Ned has been exposed to be taking advantages of the tectonic forces and has clearly instructed his corrupted civil engineer lackeys to design the bridges to purposely have the visitors 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 each single island just to get from a single 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.

It’s exciting to dive into a new dataset full of unfamiliar variables but it can also be overwhelming if you’re not sure where to start. Recently, I discovered some new interactive features in MATLAB live scripts that make it much easier to get an overview of your data. With just a few clicks, you can display sparklines and summary statistics using table variables, sort and filter variables, and even have MATLAB generate the corresponding code for reproducibility.
The Graphics and App Building blog published an article that walks through these features showing how to explore, clean, and analyze data—all without writing any code.
If you’re interested in streamlining your exploratory data analysis or want to see what’s new in live scripts, you might find it helpful:
If you’ve tried these features or have your own tips for quick data exploration in MATLAB, I’d love to hear your thoughts!
Submit your questions about this work in the comment section below.
In the FAQs, I saw the procedure to download the "mobile background", is the the same thing as an award? If yes, good, else how can we get an award and what are the available ones?
iaabdulhameed@knu.ac.kr
Glad to have watched the session, especially the part when the speaker, Arthur gave an answer to my question on "speech recognition use case" in Avionics.
isequal() is your best friend for Cody! It compares arrays perfectly without rounding errors — much safer than == for matrix outputs.
When Cody hides test cases, test your function with random small inputs first. If it works for many edge cases, it will almost always pass the grader.
I am Prof Ansar Interested in coding challenge taker inmatlab
I set my 3D matrix up with the players in the 3rd dimension. I set up the matrix with: 1) player does not hold the card (-1), player holds the card (1), and unknown holding the card (0). I moved through the turns (-1 and 1) that are fixed first. Then cycled through the conditional turns (0) while checking the cards of each player using the hints provided until it was solved. The key for me in solving several of the tests (11, 17, and 19) was looking at the 1's and 0's being held by each player.
sum(cardState==1,3);%any zeros in this 2D matrix indicate possible cards in the solution
sum(cardState==0,3)>0;%the ones in this 2D matrix indicate the only unknown positions
sum(cardState==1,3)|sum(cardState==0,3)>0;%oring the two together could provide valuable information
Some MATLAB Cody problems prohibit loops (for, while) or conditionals (if, switch, while), forcing creative solutions.
One elegant trick is to use nested functions and recursion to achieve the same logic — while staying within the rules.
Example: Recursive Summation Without Loops or Conditionals
Suppose loops and conditionals are banned, but you need to compute the sum of numbers from 1 to n. This is a simple example and obvisously n*(n+1)/2 would be preferred.
function s = sumRecursive(n)
zero=@(x)0;
s = helper(n); % call nested recursive function
function out = helper(k)
L={zero,@helper};
out = k+L{(k>0)+1}(k-1);
end
end
sumRecursive(10)
- The helper function calls itself until the base case is reached.
- Logical indexing into a cell array (k>0) act as an 'if' replacement.
- MATLAB allows nested functions to share variables and functions (zero), so you can keep state across calls.
Tips:
- Replace 'if' with logical indexing into a cell array.
- Replace for/while with recursion.
- Nested functions are local and can access outer variables, avoiding global state.
What a fantastic start to Cody Contest 2025! In just 2 days, over 300 players joined the fun, and we already have our first contest group finishers. A big shoutout to the first finisher from each team:
- Team Creative Coders: @Mehdi Dehghan
- Team Cool Coders: @Pawel
- Team Relentless Coders: @David Hill
- 🏆 First finisher overall: Mehdi Dehghan
Other group finishers: @Bin Jiang (Relentless), @Mazhar (Creative), @Vasilis Bellos (Creative), @Stefan Abendroth (Creative), @Armando Longobardi (Cool), @Cephas (Cool)
Kudos to all group finishers! 🎉
Reminder to finishers: The goal of Cody Contest is learning together. Share hints (not full solutions) to help your teammates complete the problem group. The winning team will be the one with the most group finishers — teamwork matters!
To all players: Don’t be shy about asking for help! When you do, show your work — include your code, error messages, and any details needed for others to reproduce your results.
Keep solving, keep sharing, and most importantly — have fun!
I realized that using vectorized logic instead of nested loops makes Cody problems run much faster and cleaner. Functions like any(), all(), and logical indexing can replace multiple for-loops easily !
Many MATLAB Cody problems involve recognizing integer sequences.
If a sequence looks familiar but you can’t quite place it, the On-Line Encyclopedia of Integer Sequences (OEIS) can be your best friend.
OEIS will often identify the sequence, provide a formula, recurrence relation, or even direct MATLAB-compatible pseudocode.
Example: Recognizing a Cody Sequence
Suppose you encounter this sequence in a Cody problem:
1, 1, 2, 3, 5, 8, 13, 21, ...
Entering it on OEIS yields A000045 – The Fibonacci Numbers, defined by:
F(n) = F(n-1) + F(n-2), with F(1)=1, F(2)=1
You can then directly implement it in MATLAB:
function F = fibSeq(n)
F = zeros(1,n);
F(1:2) = 1;
for k = 3:n
F(k) = F(k-1) + F(k-2);
end
end
fibSeq(15)






