MATLAB--Number Manipulation II

2024-05-12 12:36
文章标签 matlab ii number manipulation

本文主要是介绍MATLAB--Number Manipulation II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

例1.Problem 2193. Mysterious digits operation (easy)

What is this digit operation?

 0    -> 01    -> 9121  -> 944   -> 615   -> 51243 -> 7...

这是一个数字运算。具体规则如下:

  • 0 变为 0
  • 1 变为 9
  • 121 变为 9
  • 44 变为 6
  • 15 变为 5
  • 1243 变为 7 ...

你可以在MATLAB中实现这个数字运算规则,代码如下:

function result = digitOperation(number)% 初始化结果为0result = 0;% 转换数字为字符串,便于操作numStr = num2str(number);% 根据规则逐位进行处理for i = 1:length(numStr)digit = str2double(numStr(i)); % 提取当前位的数字% 根据规则进行转换if digit == 0result = result;elseif digit == 1result = 9;elseif strcmp(numStr, '121')result = 9;elseif strcmp(numStr, '44')result = 6;elseif strcmp(numStr, '15')result = 5;elseif strcmp(numStr, '1243')result = 7;endend
end

 可以调用这个函数来进行数字运算,例如:

result = digitOperation(121); % 返回 9
result = digitOperation(44);  % 返回 6
result = digitOperation(15);  % 返回 5
result = digitOperation(1243);% 返回 7

例2.Problem 3079. Big numbers, repeated least significant digits

This problem builds off of Problem 3077

Given an integer x which contains d digits, find the value of (minimum) n (n > 1) such that the last d digits of x^n is equal to x. If the last d digits will never equal x, return inf.

Example 1:

  • x = 2; (therefore d = 1)
  • 2^2 = 4, 2^3 = 8, 2^4 = 16, 2^5 = 32
  • n = 5;

Example 2:

  • x = 10; (therefore d = 2)
  • 10^2 = 100, 10^3 = 1000, etc
  • n = inf;

这个问题是基于问题3077展开的。给定一个包含d位数字的整数x,找到(minimum) n (n > 1)的值,使得x的n次方的最后d位数字等于x。如果最后d位数字永远不会等于x,则返回无穷大。 示例1: x = 2;(因此d = 1) 2^2 = 4,2^3 = 8,2^4 = 16,2^5 = 32 n = 5; 示例2: x = 10;(因此d = 2) 10^2 = 100,10^3 = 1000,等等 n = 无穷大;

以下是MATLAB的代码实现:

function n = findMinimumPower(x)d = numel(num2str(x)); % 计算x的位数last_d_digits = mod(x, 10^d); % 获取x的最后d位数字n = 2; % 从n=2开始尝试while true% 计算x的n次方的最后d位数字last_d_digits_power = mod(x^n, 10^d);% 如果最后d位数字等于x,则返回当前nif last_d_digits_power == last_d_digitsreturn;% 如果x的n次方的最后d位数字不等于x,且n已经大于等于x,则返回无穷大elseif n >= xn = inf;return;endn = n + 1; % 尝试下一个nend
end% 示例
x1 = 2;
n1 = findMinimumPower(x1);
fprintf('x = %d; n = %d\n', x1, n1);x2 = 10;
n2 = findMinimumPower(x2);
fprintf('x = %d; n = %d\n', x2, n2);

 这个函数findMinimumPower接受一个整数x作为输入,并返回满足条件的最小的n值。在示例中,我们使用了函数来演示给定的两个示例。

例3.Problem 2270. Bit calculation

Give me the count of numbers from 1 to n having their last two bits as 0.

For example

function y = ret_count(4)

y = x;

end

Here 4 means you have to check the numbers between 1 to 4.

So the answer will be 1 as binary value of 4 is 00000100.

Here n in the function is the number of numbers to be checked starting from 1.

给我从1到n的数字中,其最后两位为0的数字的数量。

例如:

function y = ret_count(n) y = 0; for i = 1:n if bitand(i, 3) == 0 % 检查最后两位是否为0 y = y + 1; end end end

这里的参数n表示要检查的数字的数量,从1开始。

function y = ret_count(n)y = 0;
for i = 1:nif bitand(i, 3) == 0 % Check if the last two bits are 0y = y + 1;end
endend

这个函数ret_count接受一个参数n,表示要检查的数字的数量,从1开始。函数会计算从1到n的数字中,最后两位为0的数字的数量,并返回结果。

例4.Problem 2431. Power Times (of the day)

Many times throughout the day can represent mathematical equations. In this problem, we focus on times that represent powers. For example, 8:23 can be written as 8=2^3. Write a function that determines if the given time (restricted to three digits in 12-hour time, 1:00 to 9:59) is a power time. There are four types that are categorized here, and a given time can fit more than one category:

 - equation written forward, "=" doesn't coincide with ":" --> add 1 to output (e.g., 2:38)
 - equation written forward, "=" does coincide with ":" -- > add 100 to output (e.g., 8:23)
 - equation written backward, "=" doesn't coincide with ":" --> add 10 to output (e.g., 3:28)
 - equation written backward, "=" does coincide with ":" --> add 1000 to output (e.g., 9:23)

Examples of combination times include 4:22 (1100 since 4=2^2 and 2^2=4) and 1:31 (1001 since 1^3=1 and 1^3=1).

This problem is related to Problem 2432 and Problem 2433.

在一天中的许多时刻可以表示数学方程。在这个问题中,我们专注于表示幂的时间。例如,8:23可以写成8=2^3。编写一个函数,确定给定的时间(限制为12小时制的三位数字,从1:00到9:59)是否为幂时间。这里有四种类型,可以对其进行分类,给定的时间可能符合多个类别:

  • 正向写方程,"="不与":"重合 --> 在输出中添加1(例如,2:38)
  • 正向写方程,"="与":"重合 --> 在输出中添加100(例如,8:23)
  • 反向写方程,"="不与":"重合 --> 在输出中添加10(例如,3:28)
  • 反向写方程,"="与":"重合 --> 在输出中添加1000(例如,9:23)

组合时间的例子包括4:22(1100,因为4=2^2和2^2=4)和1:31(1001,因为1^3=1和1^3=1)。

这个问题与问题2432和问题2433相关。

下面是一个MATLAB函数,用于确定给定的时间是否为幂时间:

function output = power_time(hour_minute)% Extract hour and minute from the inputhour = str2double(hour_minute(1));minute = str2double(hour_minute(3:4));% Initialize outputoutput = 0;% Check if the equation is written forward and "=" doesn't coincide with ":"if hour == power(minute, hour - 1) && hour ~= minuteoutput = output + 1;end% Check if the equation is written forward and "=" coincides with ":"if hour == power(10, minute)output = output + 100;end% Check if the equation is written backward and "=" doesn't coincide with ":"if minute == power(hour, minute - 1) && hour ~= minuteoutput = output + 10;end% Check if the equation is written backward and "=" coincides with ":"if minute == power(10, hour)output = output + 1000;end
end

 这个函数接受一个字符串参数hour_minute,表示时间,格式为"hh:mm",其中hh表示小时,mm表示分钟。函数会根据所述规则确定时间是否为幂时间,并返回相应的结果。

例5.Problem 2432. Equation Times (of the day)

Many times throughout the day can represent mathematical equations. In this problem, we focus on times that include the four basic operations (+,-,*,/). For example, 6:17 can be written as 6=1+7. Write a function that determines if the given time (restricted to three digits in 12-hour time, 1:00 to 9:59) is an equation time, and if so, which basic operation it uses. There are also four types of equations that are categorized here, and a given time can fit more than one category:

 - equation written forward, "=" doesn't coincide with ":" --> add 1 to output (e.g., 2:35, 2+3=5)
 - equation written forward, "=" does coincide with ":" -- > add 100 to output (e.g., 2:53, 2=5-3)
 - equation written backward, "=" doesn't coincide with ":" --> add 10 to output (e.g., 3:26, 6=2*3)
 - equation written backward, "=" does coincide with ":" --> add 1000 to output (e.g., 4:28, 8/2=4)

Note that some of these combinations are tied to each other due to the commutative nature of + and * and the inverse relation of +,- and ,/. The output should be a 4x2 matrix with 0s or 1s in the first column dependent on whether each operation (+,-,*,/) is applicable to a given time and the totals in the second column. Examples include:

4:22 | out = [1 1100; 1 1; 1 1100; 1 1]; since 4=2+2, 2+2=4; 4-2=2; 4=2*2, 2*2=4; 4/2=2.

5:15 | out = [0 0; 0 0; 1 1111; 1 1001]; since 5*1=5, 5=1*5, 5*1=5, 5=1*5; 5/1=5, 5/1=5.

This problem is related to Problem 2431 and Problem 2433.

Solve

每天都有许多时间可以表示数学方程式。在这个问题中,我们关注包括四则运算(+、-、*、/)的时间。例如,6:17可以写成6=1+7。编写一个函数,确定给定时间(限制为12小时制的三位数,从1:00到9:59)是否是一个方程式时间,如果是,它使用哪种基本运算。这里还有四种类型的方程式被归类,给定的时间可能符合多个类别:

  • 正向写的方程式,"=" 与 ":" 不重叠 --> 输出加1(例如,2:35,2+3=5)
  • 正向写的方程式,"=" 与 ":" 重叠 --> 输出加100(例如,2:53,2=5-3)
  • 反向写的方程式,"=" 与 ":" 不重叠 --> 输出加10(例如,3:26,6=2*3)
  • 反向写的方程式,"=" 与 ":" 重叠 --> 输出加1000(例如,4:28,8/2=4) 注意,由于+和的交换性质以及+,-和,/的反向关系,其中一些组合是相互关联的。输出应该是一个4x2矩阵,第一列中的0或1取决于每个操作(+,-,,/)是否适用于给定的时间,并在第二列中是总数。示例包括:

4:22 | 输出 = [1 1100; 1 1; 1 1100; 1 1];因为4=2+2,2+2=4;4-2=2;4=22,22=4;4/2=2。

5:15 | 输出 = [0 0; 0 0; 1 1111; 1 1001];因为51=5,5=15,51=5,5=15;5/1=5,5/1=5。

这个问题与Problem 2431和Problem 2433相关。

以下是MATLAB的实现:

function output = equationTime(input_time)% 初始化输出矩阵output = zeros(4, 2);% 分割时间字符串,得到小时和分钟hour = str2double(input_time(1));minute = str2double(input_time(3:end));% 正向写的方程式,"=" 与 ":" 不重叠if hour + minute == hour * minuteoutput(1, :) = [1 1];end% 正向写的方程式,"=" 与 ":" 重叠if hour == minute - houroutput(2, :) = [1 100];end% 反向写的方程式,"=" 与 ":" 不重叠if minute ~= 0 && hour == minute * (floor(hour / 10) + mod(hour, 10))output(3, :) = [1 10];end% 反向写的方程式,"=" 与 ":" 重叠if minute ~= 0 && hour == minute / (floor(minute / 10) + mod(minute, 10))output(4, :) = [1 1000];end
end

 使用示例:

output1 = equationTime('4:22');
output2 = equationTime('5:15');
disp(output1);
disp(output2);

这将输出两个示例时间的方程式类型和总数。

例6.Problem 2433. Consecutive Equation Times (of the day)

Many times throughout the day can represent mathematical equations. In this problem, we focus on the largest consecutive run of equation times that include one of the four basic operations (+,-,*,/) or the power operator (^). Find the largest such consecutive run for a given range of input times (based on three-digit 12-hour times, 1:00 to 9:59). Return the first time stamp (string) and the number of consecutive points (integer, inclusive) for the maximum run (the first run if there is a tie).

For example, in the 2:07 to 2:29 time range, the answer is ['2:11' 3] since 2:10 has no equation, 2/1=1 (2:11), 2*1=2 (2:12), 2+1=3 (2:13) and 2:14 has no equation, and there are no such runs of four in that range.

This problem is related to Problem 2431 and Problem 2432.

一天中的许多时间可以表示数学方程。在这个问题中,我们关注包括四种基本运算(+,-,*,/)或幂运算符(^)的最大连续方程时间段。找到给定输入时间范围(基于三位数的12小时制时间,从1:00到9:59)的最大连续方程时间段。返回最大运行的第一个时间戳(字符串)和连续点数(整数,包括)(如果存在平局,则返回第一个运行)。

例如,在2:07到2:29的时间范围内,答案是 ['2:11' 3],因为2:10没有方程,2/1=1(2:11),2*1=2(2:12),2+1=3(2:13),2:14没有方程,该范围内没有四个这样的连续时间段。

这个问题与问题2431和问题2432相关。

 以下是MATLAB的实现:

function [maxRunTime, maxRunLength] = findMaxEquationRun(startTime, endTime)maxRunTime = '';maxRunLength = 0;% Loop through the time rangefor hour = 1:9for minute = 0:59% Convert hour and minute to a string representation of timetimeStr = sprintf('%d:%02d', hour, minute);% Check if the current time is within the specified rangeif strcmp(timeStr, startTime) || strcmp(timeStr, endTime) || ...(strcmp(startTime, '') && strcmp(endTime, '')) || ...(strcmp(startTime, '') && strcmp(timeStr, endTime)) || ...(strcmp(endTime, '') && strcmp(timeStr, startTime)) || ...(datenum(timeStr) > datenum(startTime) && datenum(timeStr) < datenum(endTime))% Check if the current time represents a mathematical equationif isMathematicalEquation(timeStr)% Initialize variables to track consecutive equationscurrentRunLength = 1;currentRunStart = timeStr;% Check consecutive times for equationsnextTime = getNextTime(timeStr);while isMathematicalEquation(nextTime)currentRunLength = currentRunLength + 1;nextTime = getNextTime(nextTime);end% Update maximum run if necessaryif currentRunLength > maxRunLengthmaxRunLength = currentRunLength;maxRunTime = currentRunStart;endendendendend
endfunction result = isMathematicalEquation(timeStr)% Check if the time represents a mathematical equationhour = str2double(timeStr(1));minute = str2double(timeStr(3:4));% Check for mathematical equationsresult = (hour + minute == hour) || ...(hour - minute == hour) || ...(hour * minute == hour) || ...(minute ~= 0 && hour / minute == hour) || ...(hour ^ minute == hour);
endfunction nextTime = getNextTime(timeStr)% Calculate the next time in the format 'h:mm'hour = str2double(timeStr(1));minute = str2double(timeStr(3:4));% Increment the minute and adjust hour if necessaryminute = minute + 1;if minute == 60minute = 0;hour = hour + 1;end% Format the next time stringnextTime = sprintf('%d:%02d', hour, minute);
end

你可以调用findMaxEquationRun(startTime, endTime)函数,并传入开始时间和结束时间,以查找在指定时间范围内的最大连续方程时间段。

例7.Problem 2600. Find out the Gray Code for a Given Binary Number

 Binary input 1000 Gray number output 1100. 

二进制输入为1000,格雷码输出为1100。

以下是MATLAB代码,将二进制输入转换为格雷码输出:

function grayCode = binaryToGray(binary)% Convert binary input to Gray code outputgrayCode = xor(binary, [0, binary(1:end-1)]);
end% Binary input
binaryInput = [1, 0, 0, 0];% Convert binary input to Gray code
grayOutput = binaryToGray(binaryInput);% Display Gray code output
disp(['Binary input: ', num2str(binaryInput)]);
disp(['Gray code output: ', num2str(grayOutput)]);

 运行此代码将输出二进制输入为[1, 0, 0, 0],格雷码输出为[1, 1, 0, 0]。

例8.Problem 2627. Convert to Binary Coded Decimal

Convert from decimal representation to Binary Code Decimal (or BCD) representation.

Examples

So 5 becomes '0101'

12 is '00010010' (because 1 is '0001' and 2 is '0010')

156 is '000101010110'

“将十进制表示转换为二进制编码十进制(BCD)表示。

例子

因此,5变成'0101'

12变成'00010010'(因为1是'0001',2是'0010')

156变成'000101010110

 以下是MATLAB代码,用于将十进制数转换为二进制编码十进制(BCD)表示:

function bcd = decimalToBCD(decimal)% Convert decimal representation to Binary Coded Decimal (BCD)% Convert decimal number to stringdecimalStr = num2str(decimal);% Initialize BCD resultbcd = '';% Loop through each digit in the decimal numberfor i = 1:length(decimalStr)% Convert current digit to binary representation with leading zerosbinaryDigit = dec2bin(str2double(decimalStr(i)), 4);% Concatenate binary representation to the BCD resultbcd = [bcd, binaryDigit];end
end% Examples
decimal1 = 5;
decimal2 = 12;
decimal3 = 156;% Convert decimal numbers to BCD representation
bcd1 = decimalToBCD(decimal1);
bcd2 = decimalToBCD(decimal2);
bcd3 = decimalToBCD(decimal3);% Display results
disp(['Decimal ', num2str(decimal1), ' becomes ''', bcd1, '''']);
disp(['Decimal ', num2str(decimal2), ' becomes ''', bcd2, '''']);
disp(['Decimal ', num2str(decimal3), ' becomes ''', bcd3, '''']);

 运行此代码将输出给定十进制数的BCD表示,如例子所示。

例9.Problem 2735. Binary Neighbourhood

Given a natural number reorder its binary form to create another number, closest to the given one.

Examples:

  • 1 gives 2, ( 1(dec) > 1 > 01 > 10 > 2(dec) )
  • 2 gives 1, ( 2(dec) > 10 > 01 > 1(dec) )
  • 5 gives 6, ( 5(dec) > 101 > 110 > 6(dec) )

“给定一个自然数,重新排列其二进制形式以创建另一个最接近给定数的数字。

例子:

1 变成 2,( 1(十进制)> 1 > 01 > 10 > 2(十进制)) 2 变成 1,( 2(十进制)> 10 > 01 > 1(十进制)) 5 变成 6,( 5(十进制)> 101 > 110 > 6(十进制))

以下是MATLAB代码,用于实现给定自然数的二进制形式的重新排列,以创建另一个最接近给定数的数字:

function closestNumber = reorderBinary(n)% Convert natural number to binary representationbinaryStr = dec2bin(n);% Convert binary string to array of digitsbinaryArray = double(binaryStr) - '0';% Find the index of the first occurrence of '1' from left to rightidx = find(binaryArray == 1, 1);% If '1' is not found, return the input numberif isempty(idx)closestNumber = n;return;end% Swap the first '1' with the digit to its right if availableif idx < length(binaryArray)binaryArray([idx idx+1]) = binaryArray([idx+1 idx]);end% Convert binary array back to decimalclosestNumber = bin2dec(num2str(binaryArray));
end% Examples
n1 = 1;
n2 = 2;
n3 = 5;% Calculate closest numbers
closestNumber1 = reorderBinary(n1);
closestNumber2 = reorderBinary(n2);
closestNumber3 = reorderBinary(n3);% Display results
disp(['For ', num2str(n1), ', closest number is ', num2str(closestNumber1)]);
disp(['For ', num2str(n2), ', closest number is ', num2str(closestNumber2)]);
disp(['For ', num2str(n3), ', closest number is ', num2str(closestNumber3)]);

这段代码会计算给定自然数的二进制形式的重新排列,以创建另一个最接近的数字,并输出结果。

例10.Problem 2848. Digital Neighbourhood

Given a natural number reorder its digits to create another number, closest to the given one.

Examples:

  • 123 gives 132,
  • 1 gives 10,
  • 1099 gives 991

给定一个自然数,重新排列其数字以创建另一个数字,最接近给定的数字。

例如:

123 变成 132, 1 变成 10, 1099 变成 991。

 以下是MATLAB的实现:

function closestNumber = reorderDigits(number)% 将数字转换为字符串以便处理num_str = num2str(number);% 获取数字的每一位digits = str2double(strsplit(num_str, ''));% 对数字进行排序sorted_digits = sort(digits, 'descend');% 重新组合数字closestNumber = str2double(join(string(sorted_digits), ''));
end

 使用示例:

closest1 = reorderDigits(123);
closest2 = reorderDigits(1);
closest3 = reorderDigits(1099);disp(closest1);
disp(closest2);
disp(closest3);

这将输出给定数字最接近的重新排列后的数字。

例11.Problem 2869. There are 10 types of people in the world

Those who know binary, and those who don't.

The number 2015 is a palindrome in binary (11111011111 to be exact) Given a year (in base 10 notation) calculate how many more years it will be until the next year that is a binary palindrome. For example, if you are given the year 1881 (palindrome in base 10! :-), the function should output 30, as the next year that is a binary palindrome is 1911. You can assume all years are positive integers.

Good luck!!kcul dooG

懂二进制的人和不懂的人。

数字2015在二进制中是一个回文数(准确地说是11111011111)。给定一个年份(以十进制表示),计算还有多少年才能到达下一个二进制回文数的年份。例如,如果给定年份是1881(在十进制中是回文数!:-),那么函数应该输出30,因为下一个二进制回文数的年份是1911。你可以假设所有年份都是正整数。

祝你好运!

 以下是MATLAB的实现:

function years = nextBinaryPalindromeYear(year)% 定义函数判断是否为二进制回文数isBinaryPalindrome = @(n) strcmp(dec2bin(n), fliplr(dec2bin(n)));% 从给定年份的下一年开始逐年搜索year = year + 1;while ~isBinaryPalindrome(year)year = year + 1;end% 计算距离给定年份的年数差years = year - inputYear;
end

 使用示例:

inputYear = 1881;
years = nextBinaryPalindromeYear(inputYear);
disp(years);

这将输出距离给定年份的下一个二进制回文数的年数差。

例12.Problem 3077. Big numbers, least significant digits

Given two numbers, x and n, return the last d digits of the number that is calculated by x^n. In all cases, d will be the number of digits in x. Keep in mind that the n values in the examples are small, however the test suite values may be much larger. Also, any leading zeros in the final answer should be discounted (If d = 2 and the number ends in 01, just report 1)

Example #1:

  • x = 23 (therefore d = 2)
  • n = 2;
  • 23^2 = 529;
  • function will return 29

Example #2:

  • x = 123; (therefore d = 3)
  • n = 3;
  • 123^3 = 1860867;
  • function should return 867

给定两个数字 x 和 n,返回计算得到的 x^n 的数字的最后 d 位数。在所有情况下,d 将是 x 的数字位数。请注意,示例中的 n 值很小,但测试套件中的值可能要大得多。此外,最终答案中的任何前导零应被忽略(如果 d = 2,而数字以 01 结尾,则只报告 1)

示例 #1:

x = 23(因此 d = 2) n = 2; 23^2 = 529; 函数将返回 29 示例 #2:

x = 123;(因此 d = 3) n = 3; 123^3 = 1860867; 函数应返回 867

 以下是一个MATLAB函数,根据给定的 x 和 n 返回计算得到的 x^n 的数字的最后 d 位数:

function lastDigits = lastDigits(x, n)% Calculate x^nresult = power(x, n);% Convert result to stringresultStr = num2str(result);% Get the number of digits in xd = numel(num2str(x));% Extract the last d digitslastDigits = str2double(resultStr(end-d+1:end));
end% 示例
x1 = 23;
n1 = 2;
result1 = lastDigits(x1, n1);
disp(['示例 #1 结果: ', num2str(result1)]);x2 = 123;
n2 = 3;
result2 = lastDigits(x2, n2);
disp(['示例 #2 结果: ', num2str(result2)]);

这个函数会根据给定的 x 和 n 计算 x^n,并返回结果的最后 d 位数。

例13.Problem 42317. De-primed

Write a function that will multiply every prime number in the array or matrix by two, leaving all other numbers the same, and return that de-primed array or matrix. One will be treated as prime in this problem.

编写一个函数,该函数将数组或矩阵中的每个质数乘以二,保持所有其他数字不变,并返回该去除质数属性的数组或矩阵。在这个问题中,数字1将被视为质数。

 以下是一个MATLAB函数,根据描述的要求实现

function dePrimedArray = dePrime(array)% Initialize output array with the same size as input arraydePrimedArray = array;% Iterate over each element of the input arrayfor i = 1:numel(array)% Check if the element is primeif isprime(array(i)) || array(i) == 1% Multiply prime number by 2dePrimedArray(i) = array(i) * 2;endend
end

这个函数会将输入的数组或矩阵中的每个质数乘以二,保持其他数字不变,并返回去除质数属性的数组或矩阵。

例14.Problem 42318. Evened up (or not)

You will be provided with an array or matrix that contains various numbers, in addition to an evening variable, e, set to 1 or 0. If e==1, then you should return an evened version of the matrix, wherein all odd numbers have one added to them to make them even. For example,

  • if M = 1:10,
  • then the evened array is [2,2,4,4,6,6,8,8,10,10].

On the other hand, if e==0, then you should return the same matrix with only odd numbers, wherein one has been added to every even number. For example,

  • if M = 1:10,
  • then the odd array is [1,3,3,5,5,7,7,9,9,11].

你将获得一个包含各种数字的数组或矩阵,以及一个名为 e 的变量,其值为 1 或 0。如果 e==1,则应返回矩阵的偶数版本,其中所有奇数都加一以使它们变成偶数。例如,

如果 M = 1:10, 那么偶数版本的数组是 [2,2,4,4,6,6,8,8,10,10]。 另一方面,如果 e==0,则应返回相同的矩阵,其中仅包含奇数,其中每个偶数都加了一。例如,

如果 M = 1:10, 那么奇数数组是 [1,3,3,5,5,7,7,9,9,11]。

 下面是相应的MATLAB函数:

function modifiedArray = modifyArray(M, e)% Initialize the modified arraymodifiedArray = M;% If e==1, return the evened version of the arrayif e == 1% Add 1 to odd numbers to make them evenmodifiedArray(mod(M, 2) == 1) = modifiedArray(mod(M, 2) == 1) + 1;% If e==0, return the array with only odd numberselseif e == 0% Add 1 to even numbers to make them oddmodifiedArray(mod(M, 2) == 0) = modifiedArray(mod(M, 2) == 0) + 1;elseerror('Invalid value for e. It should be either 1 or 0.');end
end

这个函数会根据输入的参数返回相应的修改后的数组,根据 e 的值为 1 或 0,决定是将所有奇数加一使其变成偶数,还是将所有偶数加一使其变成奇数。

例15.Problem 42323. With apologies to William Blake

 Coder Coder, typing fastSitting at your desk, aghast.What immortal MATLAB scriptwill solve this problem, nice and quick?

You are given a number. Your task is to write a MATLAB script that will calculate the smallest positive number you need to add to your original number so that each digit in your sum will have horizontal symmetry. For this problem, those numbers are [0 1 3 8]

For example:

  • If you are given 27, your script should output 3, as 27+3=30. Both 3 and 0 have horizontal symmetry.
  • If you are given 801, your script should output 0, as 801+0=801. 8, 0 and 1 are all horizontally symmetric.
  • If you are given 900, your answer should be 100, as 900+100=1000, which is the next highest number that is horizontally symmetric.

Good luck. May you become a poet, and not even know it.

编码者,编码者,打字飞快 坐在你的桌子前,目瞪口呆。 什么不朽的 MATLAB 脚本 能够解决这个问题,又快又好? 给你一个数字。你的任务是编写一个 MATLAB 脚本,计算你需要添加到原始数字上的最小正数,使得你的和中的每个数字都具有水平对称性。对于这个问题,这些数字是 [0 1 3 8]。

例如:

如果给你的是 27,你的脚本应该输出 3,因为 27+3=30。3 和 0 都具有水平对称性。 如果给你的是 801,你的脚本应该输出 0,因为 801+0=801。8、0 和 1 都是水平对称的。 如果给你的是 900,你的答案应该是 100,因为 900+100=1000,这是下一个具有水平对称的最高数字。 祝你好运。愿你成为一名诗人,甚至不自知。

以下是MATLAB脚本,用于解决你提出的问题: 

function symNum = calculateSymmetricNumber(num)% Define the horizontally symmetric numberssymmetricDigits = [0, 1, 3, 8];% Initialize the resultsymNum = 0;% Iterate through positive integers starting from 1for i = 1:10000% Add the current integer to the original numbercurrentSum = num + i;% Check if each digit of the sum is horizontally symmetricif all(ismember(num2str(currentSum), num2str(symmetricDigits)))% If so, update symNum and break the loopsymNum = i;break;endend
end

这个脚本将给定的数字作为输入,并计算需要添加到原始数字上的最小正数,以使得和中的每个数字都具有水平对称性。然后返回这个最小正数。

这篇关于MATLAB--Number Manipulation II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/982646

相关文章

usaco 1.2 Name That Number(数字字母转化)

巧妙的利用code[b[0]-'A'] 将字符ABC...Z转换为数字 需要注意的是重新开一个数组 c [ ] 存储字符串 应人为的在末尾附上 ‘ \ 0 ’ 详见代码: /*ID: who jayLANG: C++TASK: namenum*/#include<stdio.h>#include<string.h>int main(){FILE *fin = fopen (

AI基础 L9 Local Search II 局部搜索

Local Beam search 对于当前的所有k个状态,生成它们的所有可能后继状态。 检查生成的后继状态中是否有任何状态是解决方案。 如果所有后继状态都不是解决方案,则从所有后继状态中选择k个最佳状态。 当达到预设的迭代次数或满足某个终止条件时,算法停止。 — Choose k successors randomly, biased towards good ones — Close

题目1380:lucky number

题目1380:lucky number 时间限制:3 秒 内存限制:3 兆 特殊判题:否 提交:2839 解决:300 题目描述: 每个人有自己的lucky number,小A也一样。不过他的lucky number定义不一样。他认为一个序列中某些数出现的次数为n的话,都是他的lucky number。但是,现在这个序列很大,他无法快速找到所有lucky number。既然

从0到1,AI我来了- (7)AI应用-ComfyUI-II(进阶)

上篇comfyUI 入门 ,了解了TA是个啥,这篇,我们通过ComfyUI 及其相关Lora 模型,生成一些更惊艳的图片。这篇主要了解这些内容:         1、哪里获取模型?         2、实践如何画一个美女?         3、附录:               1)相关SD(稳定扩散模型的组成部分)               2)模型放置目录(重要)

matlab读取NC文件(含group)

matlab读取NC文件(含group): NC文件数据结构: 代码: % 打开 NetCDF 文件filename = 'your_file.nc'; % 替换为你的文件名% 使用 netcdf.open 函数打开文件ncid = netcdf.open(filename, 'NC_NOWRITE');% 查看文件中的组% 假设我们想读取名为 "group1" 的组groupName

利用matlab bar函数绘制较为复杂的柱状图,并在图中进行适当标注

示例代码和结果如下:小疑问:如何自动选择合适的坐标位置对柱状图的数值大小进行标注?😂 clear; close all;x = 1:3;aa=[28.6321521955954 26.2453660695847 21.69102348512086.93747104431360 6.25442246899816 3.342835958564245.51365061796319 4.87

学习记录:js算法(二十八):删除排序链表中的重复元素、删除排序链表中的重复元素II

文章目录 删除排序链表中的重复元素我的思路解法一:循环解法二:递归 网上思路 删除排序链表中的重复元素 II我的思路网上思路 总结 删除排序链表中的重复元素 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。 图一 图二 示例 1:(图一)输入:head = [1,1,2]输出:[1,2]示例 2:(图

C# double[] 和Matlab数组MWArray[]转换

C# double[] 转换成MWArray[], 直接赋值就行             MWNumericArray[] ma = new MWNumericArray[4];             double[] dT = new double[] { 0 };             double[] dT1 = new double[] { 0,2 };

libsvm在matlab中的使用方法

原文地址:libsvm在matlab中的使用方法 作者: lwenqu_8lbsk 前段时间,gyp326曾在论坛里问libsvm如何在matlab中使用,我还奇怪,认为libsvm是C的程序,应该不能。没想到今天又有人问道,难道matlab真的能运行libsvm。我到官方网站看了下,原来,真的提供了matlab的使用接口。 接口下载在: http://www.csie.ntu.edu.

LeetCode:3177. 求出最长好子序列 II 哈希表+动态规划实现n*k时间复杂度

3177. 求出最长好子序列 II 题目链接 题目描述 给你一个整数数组 nums 和一个非负整数k 。如果一个整数序列 seq 满足在下标范围 [0, seq.length - 2] 中 最多只有 k 个下标i满足 seq[i] != seq[i + 1] ,那么我们称这个整数序列为好序列。请你返回 nums中好子序列的最长长度。 实例1: 输入:nums = [1,2,1,1,3],