gpt4 book ai didi

java - 检查数组中模式的递归方法

转载 作者:太空宇宙 更新时间:2023-11-04 14:48:41 24 4
gpt4 key购买 nike

我正在尝试用 Java 编写一个递归方法,该方法将采用两个 int 数组,如果第一个数组表示第二个数组的模式,则返回 true/false,这样 - (模式数组接受 0, 1 或 2。0 代表一位或两位数字,1 代表一位数字,2 代表两位数字。所以如果我发送 {2, 3, 57} 和 {1, 0, 2} 它将返回 true。如果我输入 {2, 555, 57} 和 {1, 0, 2} 它将返回 false。另外,如果我输入 {2,3,573**,4,34,35}** 和 {1 , 0, 2} 我仍然需要得到 true,因为数组的一部分代表了模式。​​

我想出了这个:

private static boolean match(int [] a, int [] pattern, int i, int j, int c, int subArr)
{
if(a.length < pattern.length)
return false;
else if(pattern.length == 0)
return true;
else if(pattern.length == a.length && check(a, pattern, i, j))
return true;
else if(check(a, pattern, i++, j++))
{
return check(a, pattern, i, j);
}

else return false;
}


private static boolean check(int [] a, int [] pattern, int i, int j)
{
if(pattern[j] == 1 && (checkDigits(a[i]) == 1))
{
return true;
}
else if(pattern[j] == 2 && checkDigits(a[i]) == 2)
{
return true;
}
else if(pattern[j] == 0 &&(checkDigits(a[i]) == 1 || checkDigits(a[i]) == 2 )){
return true;
}
else return false;

}


private static int checkDigits(int k){
int length = (int)(Math.log10(k)+1);
return length;

}

match 方法正在执行所有检查。检查方法是检查模式,检查数字是位数。我的问题是 3 位数字。如果我举个例子 { 2, 123, 54 } 和 {1, 0, 2} 我得到 true 而不是 false。我相信问题出在检查方法中,但我找不到问题所在。

最佳答案

检查我现在写的这段代码,我在代码中添加了注释,如果你运行它。我在控制台上写了一些文字来向您解释它是如何工作的。所以最后当你想使用它时,只需删除 system.out.print

public class ArrayPattern {
static int numbers[] = {1,10,20,3,30};
static int pattern[] = {0,0,2,2};

public static void main(String[] args) {
System.out.println(isPattern(0, 0));
}

/**
* Recursive method that checks for the pattern. If it fails to match pattern starting from index i, it
* tries starting from index i+1
* */
public static boolean isPattern(int index, int consec){

// If all pattern values where matched consecutively
if(consec == pattern.length)
return true;

// If the numbers ended and the pattern wasn't found
if(index == numbers.length)
return false;

// If the current number matches the pattern, check the next number at index + 1
if(checkPattern(pattern[consec], numbers[index])){
System.out.println(pattern[consec] +" => "+ numbers[index]);
return isPattern(index+1, consec+1);
}

// If the pattern was not found, starting from a specific index. Start from the next index to check if the pattern can be found
System.out.println(String.format("\nFailed to match pattern, try starting from index: %d\n", (index - consec + 1)));
return isPattern(index - consec + 1, 0);
}

/**
* Just chesk the pattern:
* 0 => 1 or 2 digits.
* 1 => 1 digit.
* 2 => 2 digits
*/
public static boolean checkPattern(int pattern, int value){
String sValue = String.format("%d", value);
switch (pattern) {
case 0:
return sValue.length() <= 2;
default:
return sValue.length() == pattern;
}
}
}

关于java - 检查数组中模式的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24069013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com