Reputation: 39
These are a couple homework questions on arrays I am having problems with, so no answers, just hints please.
With this one my problem is how to iterate through an array in chunks instead of individual values.
So far what I have is:
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);
}
This just populates the array with random numbers and lists the index number. How do I iterate through the array in chuncks of 3 numbers next to each other.
My problem here is how to count how many times a single letter shows up in all the arrays.
Upvotes: 0
Views: 167
Reputation: 9041
You'll need an array of 20 elements, a random generator to populate your array with random numbers, then a for loop with an if statment to determine which three consecutive elements have the largest sum
You'll need an array of 10 elements, a string that has every letter of the alphabet, a random generator to populate your array with random letters from the alphabet, a Map of Maps that will hold your random strings as the key of the outer map with the inner map will have the letters of the string as the key and their count as the value.
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("");
}
}
Results:
Upvotes: 1
Reputation: 616
Prob 1: What you can do is make another method that accepts the array and returns the first index of three consecutive indexes.
int compute(int[] array)
{
int temp=0;
int index;
for(int i=0; i<=17; i++)
{
if( array[i]+array[i+1]+array [i+2]>temp)
{
temp= array[i]+array[i+1]+array [i+2];
index=i;
}
}
return index;
// you can now use this index and compute
// next two indexes
}
Upvotes: 1
Reputation: 1132
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);
}
Output: 5+2+9=16
Above program is for problem 1;
Upvotes: 1
Reputation:
For problem 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");
}
}
Output: w 4 times
u 1 times
d 1 times
e 3 times
s 1 times
c 4 times
a 2 times
h 3 times
i 1 times
I have tried for one please try the same with multiple strings
Upvotes: 3
Reputation: 308
Here are some hints:
Problem 1
loop over the array starting with position 1 and going to position 18 with counter p
for each position sum up the values at p
,p-1
and p+1
. If that value is greater than the last value computed, store the index.
Problem 2 Use a hashmap with the key type Character and value type Integer. For each letter of each string in the array, check if it is in the hashmap, if it is not, put an entry in the hashmap and set its value to 1. This is essentially making a histogram of the characters.
Upvotes: 4