This code basically takes a string array goes through it one at a time and displays a tally of each elements occurrence.
problem is that element number 3 ("One") is repeated at the end and im not sure why, so the out put i would get is:
Current Output:
One 2
Two 1
Three 1
One 2
Code:
public static void main(String[] args) {
String [] myStrings = {"One", "Two", "Three", "One"};
StringCount(myStrings);
}
public static void StringCount(String [] Array)
{
int size = Array.length;
for (int i = 0; i < size; i++)
{
int count = 0;
String element = Array[i];
for (int j = 0; j < size; j++)
{
if (Array[j].equals(element)){
count ++;
}
}
System.out.println(Array[i] + " " + count);
}
}
Expected Output:
One 2
Two 1
Three 1
First, you get four printed lines because you call the output method inside a loop that runs exactly four times:
for (int i = 0; i < size; i++) // size is 4
{
...
System.out.println(Array[i] + " " + count);
}
As you want to count the occurrences of all distinct strings, you want to map those strings to their count. The problem is that you can't know the exact number of distinct strings beforehand. So you have to build up such a map and loop again over its elements (in a second step):
Map<String, Integer> counts = new HashMap<>();
/* setup map */
for (int i = 0; i < size; i++) {
String element = Array[i];
/* special case for having an element the first time: */
if (!counts.containsKey(element)) {
counts.put(element, Integer.valueOf(0));
}
/* increase the count for the element and store it back in map */
int oldCount = counts.get(element).intValue();
counts.put(element, Integer.valueOf(oldCount+1));
}
/* print out values */
for(String element : counts.keySet()) {
System.out.println(element + " " + counts.get(element));
}
Use a Set to avoid duplicates like below:
public static void StringCount(String [] Array)
{
int size = Array.length;
Set<String> existingElement = new HashSet<>();
for (int i = 0; i < size; i++)
{
int count = 0;
String element = Array[i];
for (int j = 0; j < size; j++)
{
if (Array[j].equals(element)){
count ++;
}
}
// This will print the result if and only if the element has not
// already been added into the Set
if (existingElement.add(Array[i])) {
System.out.println(Array[i] + " " + count);
}
}
}
Output:
One 2
Two 1
Three 1
Because you check every element and you have One two times, so it will be checked twice! you need to have a set of checked elements so when you check element you put it in set, and then before checking next element you check if it is in set, if it is, then skip it.
Related
So right now I am trying to code a function that will remove the highest value in an unsorted array.
Currently the code looks like this:
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
}
/*int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}*/
}
tailIndex = tailIndex - 1;
}
Here I have my attempt at this:
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
The program runs no bother but still deletes the first item in the array instead of the highest number. This code was given my my college lecturer for a different solution but unfortunately it doesn't work here.
Would this solution work with enough altercations? Or is there another solution I should try?
Thanks.
The code snippet in the question can be updated to below code, while keeping the same data structure i.e. queue and this updated code has 3 steps - finding the index of largest element, shifting the elements to overwrite the largest element and finally set the tailIndex to one less i.e. decrease the size of the queue.
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
int largeIndex = 0;
for (int i = 0; i < tailIndex; i++) {
if (((PriorityItem<T>) storage[i]).getPriority() > priority) {
priority = ((PriorityItem<T>) storage[i]).getPriority();
largeIndex = i ;
}
}
for(int i = largeIndex; i < (tailIndex - 1) ; i++)
storage[i] = storage[i + 1];
}
tailIndex = tailIndex - 1;
}
Hope it helps.
Step 1
Find the highest index.
int[] array;
int highIndex = 0;
for (int i = 1; i < highIndex.size(); i++)
if (array[highIndex] < array[highIndex])
highIndex = i;
Step 2
Create new array with new int[array.size() - 1]
Step 3
Move all values of array into new array (except the highest one).
My hint: When its possible, then use a List. It reduces your complexity.
You can find the largest Number and it's index then copy each number to its preceding number. After that, you have two options:
Either add Length - 1 each time you iterate the array.
Or copy the previous array and don't include removed number in it.
Working Code:
import java.util.Arrays;
public class stackLargest
{
public static void main(String[] args)
{
int[] unsortedArray = {1,54,21,63,85,0,14,78,65,21,47,96,54,52};
int largestNumber = unsortedArray[0];
int removeIndex = 0;
// getting the largest number and its index
for(int i =0; i<unsortedArray.length;i++)
{
if(unsortedArray[i] > largestNumber)
{
largestNumber = unsortedArray[i];
removeIndex = i;
}
}
//removing the largest number
for(int i = removeIndex; i < unsortedArray.length -1; i++)
unsortedArray[i] = unsortedArray[i + 1];
// now you have two options either you can iterate one less than the array's size
// as we have deleted one element
// or you can copy the array to a new array and dont have to add " length - 1" when iterating through the array
// I am doing both at once, what you lke you can do
int[] removedArray = new int[unsortedArray.length-1];
for(int i =0; i<unsortedArray.length-1;i++)
{
System.out.printf(unsortedArray[i] + " ");
removedArray[i] = unsortedArray[i];
}
}
}
Note: Use List whenever possible, it will not only reduce complexity, but, comes with a very rich methods that will help you a big deal.
I have to write a program to accept a String as input, and as output I'll have to print each and every alphabetical letter, and how many times each occurred in the user input. There are some constraints:
I cannot use built-in functions and collection
The printed result should be sorted by occurrence-value.
For example, with this input:
abbbccccdddddzz
I would expect this output:
a-1,z-2,b-3,c-4,d-5
This is what I have so far:
public static void isCountChar(String s) {
char c1[] = s.toCharArray();
int c3[] = new int[26];
for (int i = 0; i < c1.length; i++) {
char c = s.charAt(i);
c3[c - 'a']++;
}
for (int j = 0; j < c3.length; j++) {
if (c3[j] != 0) {
char c = (char) (j + 'a');
System.out.println("character is:" + c + " " + "count is: " + c3[j]);
}
}
}
But I don't know how to sort.
First of all a tip for your next question: The things you've stated in your comments would fit better as an edit to your question. Try to clearly state what the current result is, and what the expected result should be.
That being said, it was an interesting problem, because of the two constraints.
First of all you weren't allowed to use libraries or collections. If this wasn't a constraint I would have suggested a HashMap with character as keys, and int as values, and then the sorting would be easy.
Second constraint was to order by value. Most people here suggested a sorting like BubbleSort which I agree with, but it wouldn't work with your current code because it would sort by alphabetic character instead of output value.
With these two constraints it is probably best to fake key-value pairing yourself by making both an keys-array and values-array, and sort them both at the same time (with something like a BubbleSort-algorithm). Here is the code:
private static final int ALPHABET_SIZE = 26;
public static void isCountChar(String s)
{
// Convert input String to char-array (and uppercase to lowercase)
char[] array = s.toLowerCase().toCharArray();
// Fill the keys-array with the alphabet
char[] keys = new char[ALPHABET_SIZE];
for (int i = 0; i < ALPHABET_SIZE; i++)
{
keys[i] = (char)('a' + i);
}
// Count how much each char occurs in the input String
int[] values = new int[ALPHABET_SIZE];
for (char c : array)
{
values[c - 'a']++;
}
// Sort both the keys and values so the indexes stay the same
bubbleSort(keys, values);
// Print the output:
for (int j = 0; j < ALPHABET_SIZE; j++)
{
if (values[j] != 0)
{
System.out.println("character is: " + keys[j] + "; count is: " + values[j]);
}
}
}
private static void bubbleSort(char[] keys, int[] values)
{
// BUBBLESORT (copied from http://www.java-examples.com/java-bubble-sort-example and modified)
int n = values.length;
for(int i = 0; i < n; i++){
for(int j = 1; j < (n - i); j++){
if(values[j-1] > values[j]){
// Swap the elements:
int tempValue = values[j - 1];
values[j - 1] = values[j];
values[j] = tempValue;
char tempKey = keys[j - 1];
keys[j - 1] = keys[j];
keys[j] = tempKey;
}
}
}
}
Example usage:
public static void main (String[] args) throws java.lang.Exception
{
isCountChar("TestString");
}
Output:
character is: e; count is: 1
character is: g; count is: 1
character is: i; count is: 1
character is: n; count is: 1
character is: r; count is: 1
character is: s; count is: 2
character is: t; count is: 3
Here is a working ideone to see the input and output.
some sort: easy if not easiest to understand an coding
You loop from the first element to the end -1 : element K
compare element K and element K+1: if element K>element K+1, invert them
continue loop
if you made one change redo that !
I'm trying to count the integers of an array and store the count of those integers in another array.
The code counts the occurrence of an integer but continues to count the rest of the different integers with out resting the count. The code stores only the count of the first integer occurrence without an issue.
My problem is the count doesn't reset when the loop hits the next integer and continues to count from the last integers count and displays that.
How can I improve my code to find the integer occurrences of each individual integer?
public count() {
int k[] = {1,1,2,2};
int t[] = {0,0,0,0,0};
int count = 0;
System.out.println("reset count: "+count);
for (int f = 0; f<k.length; f++) {
for (int i =1; i < k.length-1; i++) {
for (int g = 0; g < t.length; g++ ) {
if (k[f] == i) {
count++;
System.out.println("Integer = "+i);
System.out.println("count: "+count);
t[g] = count;
}
i++;
}
}
}
System.out.println();
for (int o = 0; o < t.length; o++) {
System.out.println("Stored int counts t" + o + " = " + t[o]);
}
}
If you know what is the biggest possible element in k (lets suppose 100), then you can solve it linearly:
int[] t = new int[101]; //subject of change
for (int i : k) {
t[i]++;
}
Here, you'll increase the value of the i-th element of k when the currently processed element from k has value of i.
Otherwise, if you don't know the biggest possible element of k (and respectively, you won't know how to initialize the t array), you can use a Map:
Map<Integer, Integer> map = new TreeMap<>();
for (int i : k) {
if (map.containsKey(i)) {
int value = map.get(i);
map.put(i, ++value);
} else {
map.put(i, 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int i = entry.getKey();
int n = entry.getValue();
System.out.println("The number " + i + " was found " + n + " times.");
}
You can use the HashMap to keep unique values as key, and in iterations check if that key already exists, if it does then increment its value else move on.
Hope this will help.
Stackoverflow.
I'm trying to add 4 of each words in my ArrayList into the ArrayList itself. I have in my ArrayList two Strings. One is "java" and the other one is "Program". I'm trying to write a program that adds a total of 4 words of each word. Ex: I'm trying to add 4 x java and 4 x program.
Here's what I've got so far. I have no idea, what I'm doing wrong.
Any help or hints would be much appreciated.
/*
* Write a method called quadList that takes an ArrayList of strings as a parameter
* and replaces every string with four of that same string.
* For example, if the list stores the values ["java", "program"]
* before the method is called,it should store the values
* ["java ", " java ", " java ", " java ", "program", "program", "program", "program"]
* after the method finishes executing.
*/
import java.util.ArrayList;
public class Ex10_4_quadList {
public static void main(String[] args) {
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Java");
arrList.add("Program");
System.out.println("Before: " + arrList);
quadList(arrList);
System.out.println("after " + arrList);
}
private static void quadList(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < 4; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
}
Here's the fixed code:
public class Ex10_4_quadList {
public static void main(String[] args) {
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Java");
arrList.add("Program");
System.out.println("Before: " + arrList);
quadList(arrList);
Collections.sort(arrList);
System.out.println("after " + arrList);
}
private static void quadList(ArrayList<String> list) {
int initial = list.size();
for (int i = 0; i < initial; i++) {
for (int j = 0; j < 3; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
}
Ideally instead of iterating with an index you would use the foreach style of loop. However this means that you can't alter the list as you iterate. So you will need to add the members to a new list and then add all of them afterwards:
List<String> duplicates = new ArrayList<>();
for (String member: list) {
for (int i = 0; i < 4; i++) {
duplicates.add(member);
}
}
list.addAll(duplicates);
There are a number of shortcuts you can use if you are using Java 8 and, therefore, have access to streams:
list.addAll(list.stream()
.flatMap(m -> Stream.generate(() -> m).limit(4))
.collect(Collectors.toList());
This code says for each member of the list turn it into 4 copies of the item then collect all those as a list and add them to the original list.
Try:
private static void quadList(ArrayList<String> list) {
int listSize = list.size();
for (int i = 0; i < listSize; i++) {
for (int j = 0; j < 4; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
The problem with the code is that the list.size() is evaluated on every iteration. Since the inner loop is increasing the list size faster than the outer loop can iterate over it, the code effectively loops infinitely until JVM runs out of memory.
First of all, I have seen a similar question relating to C++, but I didn't quite understand it - plus my question is about Java.
Basically I have coded two methods that can use SelectionSort and BubbleSort on an array parsed in. While I believe I have the methods working correctly (I have run tests and they all have sorted the numbers in ascending order), I am not sure if I am counting the number of comparisons and number swaps correctly. If someone is able to test my code below and offer some feedback, I will be very grateful.
Note: I can zip up my Java project files and send them to anyone if needed.
BubbleSort method:
public String bubbleSort(int[] numbers)
{
System.out.println("******|Bubble Sort|******");
StringBuilder originalArray = new StringBuilder();
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
int temp; // temporary variable
//Set boolean variable to true,
//to allow the first pass.
boolean pass = true;
int comparisons = 0;
int swaps = 0;
//While a pass can be made,
while(pass)
{
//Set the boolean value to false,
//indicating a number swap could
//be made.
pass = false;
for(int i = 0; i < numbers.length - 1; i++)
{
//increment the number of comparisons by 1.
comparisons++;
if(numbers[i] > numbers[i+1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = temp;
//increment the amount of swaps made by 1,
//to put numbers in correct order.
swaps++;
pass = true;
}
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
SelectionSort method
public String selectionSort(int[] numbers)
{
System.out.println("******|Selection Sort|******");
StringBuilder originalArray = new StringBuilder();
int comparisons = 0;
int swaps = 0;
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
//Declare variable to hold first element
int first;
//declare temporary variable, to be used in
//swapping integers.
int temp;
for(int x = numbers.length - 1; x > 0; x--)
{
first = 0;
comparisons++;
for(int y = 1; y <= x; y++)
{
//comparisons++;
if(numbers[y] > numbers[first])
{
first = y;
//comparisons++;
swaps++;
}
temp = numbers[first];
numbers[first] = numbers[x];
numbers[x] = temp;
//swaps++;
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
For BUBBLE SORT:
Key comparisons -> (n*(n-1))/2
Item assignments (swaps) -> 3*(n-1)
For SELECTION SORT:
Key comparisons -> (n*(n-1))/2 (same as bubble)
Item assignments (swaps) -> (n*(n-1))/4
(Note that n is the number of your array size)