Finding the number of Polysyllables in java - arrays

Say I have a String array, I already counted the number of syllables in the array. How would I go about finding the number of Polysyllables in the array? I know I would have to count the number of words with syllables > 1, but I don't know how to go about doing that.

You need to keep track of the number of syllables in another data structure. You could use a simple int[] to do this, and it could be returned by the function that counts syllables, that you have already created.
String[] myStrings = {"One", "Syllable", "Dog", "Laptop"};
int[] mySyllables = countSyllables(myStrings);
//In the above case, mySyllables = {1, 3, 1, 2};
So once you have counted the number of syllables, and saved the values, you can iterate your mySyllables array, and whenever you encounter a value greater than 1, you know how many polysyllables you have.
int numPoly = 0;
for(int i=0;i<mySyllables.length;i++) {
if(mySyllables[i] > 1) numPoly++;
}
In the given sample case, the end result is numPoly == 2, being "Syllables" and "Laptop"

Related

Counting Sort issue in array

I am making an algorithm for counting sort. In first step i have initialized the second array with 0. Secondly i counted the frequency of elements in second for loop. In third loop i am trying to sort the array. The third loop does not run in code blocks. Also it's not giving me right sorted result.Any issue with third loop. As it changes array to 1-1-2-0-2-2-0-1-1 rather it should be 0-0-0-1-1-1-1-2-2-2
printf("Hello world!\n");
unsigned m=3;
unsigned n=10;
unsigned x;
unsigned k;
unsigned data[10] = {0, 2, 1, 1, 0, 2, 2, 0, 1, 1};
unsigned *count;
count =(unsigned *)malloc(sizeof(unsigned)*m);
int y=sizeof(data);
for(int i=0;i<m;i++)
{
count[i]=0;
}
for(int j=0;j<n;j++)
{
x=data[j];
count[x]++;
}
for(k=n-1;k>=0;k--)
{
data[count[data[k]]-1]=data[k];
count[data[k]]=count[data[k]]-1;
}
for(int i=0;i<n;i++)
{
printf("%d \n",data[i]);
}
return 0;
}
In this line
for(k=n-1;k>=0;k--)
k is unsigned so k >= 0 is always true. When an unsigned integer would go below zero, its value "wraps".
Also, your sorting loop does not sort anything. It can't because there are no comparisons. You may like to review your algorithm.
The problem (in addition to the loop condition error mentioned in another answer) is that this appears to be a combination of two incompatible counting sort approaches.
The "traverse the input array backwards, inserting each element into the appropriate place in the output array" approach requires a separate output array. Consider the simple case of sorting {2, 1}: if we copy the 1 into the appropriate slot in the same array, it becomes {1, 1}, which will end up being our final output. Instead, that 1 needs to be placed into the appropriate slot of a separate array so that we don't overwrite the 2.
Additionally, this approach requires us to make a second pass over the count array to change its semantic meaning from "count of elements with value n" to "index of first element with value > n". This is accomplished by adding the total so far to each element of count (so in your case, count would go from {3, 4, 3} to {3, 7, 10}). After this step, count[n] - 1 is the index in the output array at which the next n should be placed.
Given that you're sorting integers, a second (easier) approach is also possible: once you've finished your initial traversal of the input array, count holds all the information you need, so you can freely overwrite the input array. Just start at the beginning and insert count[0] 0s, count[1] 1s, etc. This approach doesn't require any postprocessing of count or any separate output array.

How do I generate random numbers from an array without repetition?

I know similar question have been asked before but bear with me.
I have an array:
int [] arr = {1,2,3,4,5,6,7,8,9};
I want numbers to be generated randomly 10 times. Something like this:
4,6,8,2,4,9,3,8,7
Although some numbers are repeated, no number is generated more than once in a row. So not like this:
7,3,1,8,8,2,4,9,5,6
As you can see, the number 8 was repeated immediately after it was generated. This is not the desired effect.
So basically, I'm ok with a number being repeated as long as it doesn't appear more than once in a row.
Generate a random number.
Compare it to the last number you generated
If it is the same; discard it
If it is different, add it to the array
Return to step 1 until you have enough numbers
generate a random index into the array.
repeat until it's different from the last index used.
pull the value corresponding to that index out of the array.
repeat from beginning until you have as many numbers as you need.
While the answers posted are not bad and would work well, someone might be not pleased with the solution as it is possible (tough incredibly unlikely) for it to hang if you generate long enough sequence of same numbers.
Algorithm that deals with this "problem", while preserving distribution of numbers would be:
Pick a random number from the original array, let's call it n, and output it.
Make array of all elements but n
Generate random index from the shorter array. Swap the element on the index with n. Output n.
Repeat last step until enough numbers is outputed.
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] result = new int[10];
int previousChoice = -1;
int i = 0;
while (i < 10) {
int randomIndex = (int) (Math.random() * arr.length);
if (arr[randomIndex] != previousChoice) {
result[i] = arr[randomIndex];
i++;
}
}
The solutions given so far all involve non-constant work per generation; if you repeatedly generate indices and test for repetition, you could conceivably generate the same index many times before finally getting a new index. (An exception is Kiraa's answer, but that one involves high constant overhead to make copies of partial arrays)
The best solution here (assuming you want unique indices, not unique values, and/or that the source array has unique values) is to cycle the indices so you always generate a new index in (low) constant time.
Basically, you'd have a with loop like this (using Python for language mostly for brevity):
# randrange(x, y) generates an int in range x to y-1 inclusive
from random import randrange
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []
selectidx = 0
randstart = 0
for _ in range(10): # Runs loop body 10 times
# Generate offset from last selected index (randstart is initially 0
# allowing any index to be selected; on subsequent loops, it's 1, preventing
# repeated selection of last index
offset = randrange(randstart, len(arr))
randstart = 1
# Add offset to last selected index and wrap so we cycle around the array
selectidx = (selectidx + offset) % len(arr)
# Append element at newly selected index
result.append(arr[selectidx])
This way, each generation step is guaranteed to require no more than one new random number, with the only constant additional work being a single addition and remainder operation.

Finding count of distinct elements in every k subarray

How to solve this question efficiently?
Given an array of size n and an integer k we need to return the sum of count of all distinct numbers in a window of size k. The window slides forward.
e.g. arr[] = {1,2,1,3,4,2,3};
Let k = 4.
The first window is {1,2,1,3}, count of distinct numbers is 2….(1 is repeated)
The second window is {2,1,3,4} count of distinct numbers is 4
The third window is {1,3,4,2} count of distinct numbers is 4
The fourth window is {3,4,2,3} count of distinct numbers is 2
You should keep track of
a map that counts frequencies of elements in your window
a current sum.
The map with frequencies can also be an array if the possible elements are from a limited set.
Then when your window slides to the right...
increase the frequency of the new number by 1.
if that frequency is now 1, add it to the current sum.
decrease the frequency of the old number by 1.
if that frequency is now 0, subtract it from the current sum.
Actually, I am the asker of the question, I am not answering the question, but i just wanted to comment on the answers, but I can't since I have very less reputation.
I think that for {1, 2, 1, 3} and k = 4, the given algorithms produce count = 3, but according to the question, the count should be 2 (since 1 is repeated)
You can use a hash table H to keep track of the window as you iterate over the array. You also keep an additional field for each entry in the hash table that tracks how many times that element occurs in your window.
You start by adding the first k elements of arr to H. Then you iterate through the rest of arr and you decrease the counter field of the element that just leaves the windows and increase the counter field of the element that enters the window.
At any point (including the initial insertion into H), if a counter field turns 1, you increase the number of distinct elements you have in your window. This can happen while the last but one occurrence of an element leaves the window or while a first occurrence enters it. If a counter field turns to any other value but 1, you decrease the number of distinct elements you have in the window.
This is a linear solution in the number of elements in arr. Hashing integers can be done like this, but depending on the language you use to implement your solution you might not really need to hash them yourself. In case the range in which the elements of arr reside in is small enough, you can use a simple array instead of the hash table, as the other contributors suggested.
This is how I solved the problem
private static int[] getSolve(int[] A, int B) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < B; i++) {
map.put(A[i], map.getOrDefault(A[i], 0) + 1);
}
List<Integer> res = new ArrayList<>();
res.add(map.size());
//4, 1, 3, 1, 5, 2, 5, 6, 7
//3, 1, 5, 2, 5, 6 count = 5
for (int i = B; i < A.length; i++) {
if (map.containsKey(A[i - B]) && map.get(A[i - B]) == 1) {
map.remove(A[i - B]);
}
if (map.containsKey(A[i - B])) {
map.put(A[i - B], map.get(A[i - B]) - 1);
}
map.put(A[i], map.getOrDefault(A[i], 0) + 1);
System.out.println(map.toString());
res.add(map.size());
}
return res.stream().mapToInt(i -> i).toArray();
}

Creating an average array

part of an assignment that I'm working on is having me pass an array through a method that calculates the averages of the elements in the last array 5 numbers at a time.
For example, say Array1 consists of {1, 2, 3, 4, 5, 6}
The method would calculate the average of {1, 2, 3, 4, 5} and then {2, 3, 4, 5, 6}
The method would then take those averages and put them into a new array and pass that array back into the main.
I'm just not sure where to start. The most I can think of logically is that I'm going to need to use nested loops.
And yes, this is my first year in programming.
Welcome to Stack Overflow, Tony! Here at Stack Overflow, we really encourage users to provide some proof of effort or research, keep this in mind in future posts :)Let's think about this problem logically. We want to start by getting the average of the array from array[0] to array[n-2] (You use n-2, because index n-1 is actually holding the value '6').
For the second part. start at array[1] and go to array[n-1] Once we know this, we can take the average and return it.There is no need for nested loops here, remember this concept while programming and many tears will be saved: Keep it simple
Here is a similar question that was posted: How to minpulate arrays and find the average
Here is a solution that I came up with. When you are in the design stage of your program, you want to think about how you can make your code reusable. There may be a time when you'll have a complex program and many parts will need to perform the same operation with different data. This is known as code re-usability and mastering it will make your life easier.
public static void main(String[] args) {
int [] arr = new int [] {1, 2, 3, 4, 5, 6}; //Stores the numbers we need to average
//We get the Lower-Average by starting at index 0, going to index n-2
System.out.println ("Lower-Average: " + average(0, arr.length - 2, arr));
//We get the Upper-Average by starting at index 1, going to index n-1
System.out.println ("Upper-Average: " + average(1, arr.length - 1, arr));
}
/*
* This method accepts a start index, end index, and an array to operate on
* The average is calculated iteratively and returned based on number of elements provided
*/
public static double average (int startIndex, int endIndex, int [] array) {
double avg = 0; //Stores the average
int counter; //Used to hold number of elements iterated through
for (counter = startIndex; counter <= endIndex; counter++) {
avg += array[counter]; //Summation for the average
}
return avg = avg / counter; //Calculate the average and return it to caller
}
Output:
Lower-Average: 3.0
Upper-Average: 3.3333333333333335

Find if one integer array is a permutation of other

Given two integer arrays of size N, design an algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
I can think of two ways:
Sort them and compare : O(N.log N + N)
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0. This is O(N). I am not sure if this method will eliminate false positives completely. Thoughts. Better algorithms?
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0.
This doesn't work. Example:
a = [1,6] length(a) = 2, sum(a) = 7, xor(a) = 7
b = [3,4] length(b) = 2, sum(b) = 7, xor(b) = 7
Others have already suggested HashMap for an O(n) solution.
Here's an O(n) solution in C# using a Dictionary<T, int>:
bool IsPermutation<T>(IList<T> values1, IList<T> values2)
{
if (values1.Count != values2.Count)
{
return false;
}
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (T t in values1)
{
int count;
counts.TryGetValue(t, out count);
counts[t] = count + 1;
}
foreach (T t in values2)
{
int count;
if (!counts.TryGetValue(t, out count) || count == 0)
{
return false;
}
counts[t] = count - 1;
}
return true;
}
In Python you could use the Counter class:
>>> a = [1, 4, 9, 4, 6]
>>> b = [4, 6, 1, 4, 9]
>>> c = [4, 1, 9, 1, 6]
>>> d = [1, 4, 6, 9, 4]
>>> from collections import Counter
>>> Counter(a) == Counter(b)
True
>>> Counter(c) == Counter(d)
False
The best solution is probably a counting one using a map whose keys are the values in your two arrays.
Go through one array creating/incrementing the appropriate map location and go through the other one creating/decrementing the appropriate map location.
If the resulting map consists entirely of zeros, your arrays are equal.
This is O(N), and I don't think you can do better.
I suspect this is approximately what Mark Byers was going for in his answer.
If a space complexity of O(n) is not a problem, you can do it in O(n), by first storing in a hash map the number of occurrences for each value in the first array, and then running a second pass on the second array and check that every element exists in the map, decrementing the number the occurrences for each element.
Sort the contents of both arrays numerically, and then compare each nth item.
You could also take each item in array1, and then check if it is present in array2. Keep a count of how many matches you find. At the end, the number of matches should equal the length of the arrays.

Resources