迭代数组

时间:2015-04-30 03:09:30

标签: java arrays

这些是关于阵列的一些功课问题,我遇到了问题,所以没有答案,请提示。

  1. 编写一个程序,生成一个包含20个随机整数的数组,值为1-100,然后计算数组中哪三个连续元素的总和最大。
  2. 有了这个,我的问题是如何以块的形式迭代数组而不是单个值。

    到目前为止我所拥有的是:

    public class Arrays
    {
        public static void main (String[] args)
        {
            int[] randNum = new int[21];
            for (int i = 1; i < randNum.length; i++)
            {
                randNum[i] = (int) (Math.random() * 100) + 1;
                System.out.print(randNum[i] + ", ");
            }
    
                System.out.println();
                int index = 0;
                for(int x : randNum)
                    System.out.println((index++) + ": " + x);
    }
    

    这只是用随机数填充数组并列出索引号。如何在3个数字的chuncks中迭代遍历数组。

    1. 编写一个程序,生成一组包含10个小写字母的随机字符串,字符串长度在5到50之间随机。然后计算字符串中每个字母的出现次数并打印出这些字母。最后,它将打印字符串的平均长度
    2. 我的问题是如何计算单个字母出现在所有数组中的次数。

4 个答案:

答案 0 :(得分:4)

以下是一些提示:

问题1

从位置1开始循环遍历数组,并使用计数器p转到第18位 对于每个职位,总结pp-1p+1处的值。如果该值大于计算的最后一个值,则存储索引。

问题2 使用键类型为Character且值类型为Integer的hashmap。对于数组中每个字符串的每个字母,检查它是否在hashmap中,如果不是,则在hashmap中放入一个条目并将其值设置为1.这实质上是对字符进行直方图。

答案 1 :(得分:3)

问题2

 public static void main(String[] args) {
    // TODO Auto-generated method stub
   String inp="hsaadhiewhuwccwecwec";
    HashMap<Character, Integer> countcharact=new HashMap<>();
    int j=0;
    for(int i=0;i<inp.length();i++){
        if(countcharact.containsKey(inp.charAt(i))==true){
            j=countcharact.get(inp.charAt(i));
            countcharact.put(inp.charAt(i),j+1);

        }
        else
            countcharact.put(inp.charAt(i), 1);
    }

    Set<Character> s=countcharact.keySet();
    for(Character c:s){
        System.out.println(c+" "+countcharact.get(c)+" times");
    }

}

输出: w 4次

你1次

d 1次

e 3次

s 1次

c 4次

2次

h 3次

我1次

我试过一个请尝试使用多个字符串

答案 2 :(得分:1)

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] input={1,2,4,5,2,9,2};
    int p=0,maximum=0,start=0;;
    while(p<input.length-3){
        if(input[p]+input[p+1]+input[p+2]>maximum){
            start=p;
            maximum=input[p]+input[p+1]+input[p+2];
        }
        p++;
    }

    for(int i=start;i<start+3;i++)
        System.out.print(input[i]+"+");

    System.out.print("="+maximum);

}

输出: 5 + 2 + 9 = 16

以上程序适用于问题1;

答案 3 :(得分:1)

问题1

你需要一个包含20个元素的数组,一个随机生成器用随机数填充你的数组,然后是一个带有if语句的for循环来确定哪三个连续元素的总和最大

问题2

你需要一个包含10个元素的数组,一个包含字母表中每个字母的字符串,一个用字母表中的随机字母填充数组的随机生成器,一个将随机字符串作为键的地图映射内部地图的外部地图将使用字符串的字母作为键,并将其计数作为值。

public static void main(String[] args) throws Exception {
    problem1();
    problem2();
}

private static void problem1() {
    Random r = new Random(System.currentTimeMillis());

    int[] randomNumbers = new int[20];
    // Populate your array with random numbers;
    for (int i = 0 ; i < randomNumbers.length; i++) {
        // This will generate numbers from 1 - 100
        randomNumbers[i] = r.nextInt(100) + 1;
    }

    int[] consecutiveElements = null;
    int largestSum = 0;

    // -3 because we're looking 3 elements at a time and we don't want to go outside the bounds of the array
    for (int i = 0; i < randomNumbers.length - 3; i++) {
        int sum = randomNumbers[i] + randomNumbers[i + 1] + randomNumbers[i + 2];
        if (sum > largestSum) {
            largestSum = sum;
            consecutiveElements = new int[] { randomNumbers[i], randomNumbers[i + 1], randomNumbers[i + 2] };
        }
    }

    System.out.println("Problem 1:");
    System.out.println("Random numbers: " + Arrays.toString(randomNumbers));
    System.out.println("Largest consecutive elements for sum: " + Arrays.toString(consecutiveElements));
    System.out.println("Sum: " + largestSum);
}

private static void problem2() {
    Random r = new Random(System.currentTimeMillis());
    String[] randomStrings = new String[10];

    String alphabet = "abcdefghijklmnopqrstuvwxyz";

    // Populate your strings with random letters
    for (int i = 0; i < randomStrings.length; i++) {
        randomStrings[i] = "";
        // To get a number from 5 - 50;
        int randomLength = r.nextInt(46) + 5;
        for (int j = 0; j < randomLength; j++) {
            randomStrings[i] += alphabet.charAt(r.nextInt(26)); 
        }
    }

    // Count occurrences of letters in each string and sum up the string lengths
    int stringLengthSum = 0;
    // Map of Maps...  Outer map is keyed by the random strings with an inner map of the characters and their occurrences as the value
    // Inner map is keyed by the letters in the random string with their occurrences as the value
    Map<String, Map<String, Integer>> occurrences = new HashMap<>();
    for (int stringIndex = 0; stringIndex < randomStrings.length; stringIndex++) {
        // Calculate the sum of the string lengths
        stringLengthSum += randomStrings[stringIndex].length();

        // Count letter occurrences in each string
        occurrences.put(randomStrings[stringIndex], new HashMap<>());
        for (int characterIndex = 0; characterIndex < randomStrings[stringIndex].length(); characterIndex++) {
            String letter = String.valueOf(randomStrings[stringIndex].charAt(characterIndex));
            if (!occurrences.get(randomStrings[stringIndex]).containsKey(letter)) {
                occurrences.get(randomStrings[stringIndex]).put(letter, 1);
            } else {
                int currentOccurrenceCount = occurrences.get(randomStrings[stringIndex]).get(letter);
                occurrences.get(randomStrings[stringIndex]).put(letter, currentOccurrenceCount + 1);
            }
        } // End for (int characterIndex = 0; characterIndex < randomStrings[stringIndex].length(); characterIndex++)
    } // End for (int stringIndex = 0; stringIndex < randomStrings.length; stringIndex++)

    // Calculate the average string length
    double stringLengthAverage = stringLengthSum / randomStrings.length;

    System.out.println("");
    System.out.println("Problem 2:");
    // Print average string length
    System.out.println("Average string length: " + stringLengthAverage);
    // Print out random strings and their letter occurences
    for (Map.Entry<String, Map<String, Integer>> entry : occurrences.entrySet()) {
        System.out.println(entry.getKey());
        for (Map.Entry<String, Integer> letterEntryCount : entry.getValue().entrySet()) {
            System.out.print(letterEntryCount.getKey() + ": " + letterEntryCount.getValue() + "   ");
        }
        System.out.println("");
    }
}

结果:

enter image description here