Print out a Single count value for multiple Array items - java

I have this really quick question, im guessing is just staring at me but im not being able to see it. I had to count the number of occurrences of a certain name in an array. I did that using a loop as i was not allowed to use classes, hashmap etc. So i have a 93 names, for example Jake occurs 5 times, i want the out to be:
Jack - 5
instead, my program displays
Jack - 5
Jack - 5
Jack - 5
Jack - 5
Jack - 5
I just want it to be printed once, here is my loop for it:
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
int count = 0;
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
System.out.println(n + " - " + count);
}
ideal output should be:
Jack - 5
i need to print asterisks as output, so i want it to say
Jack (5) *****
Each asterisk represents a occurrence, i know how to print them, and i have put it in my code but it displays
***** Jack(5)
I was wondering how i could i fix that, any ideas?

You're cycling through each name in the list and checking it each time. Consequently, you're checking the name Jack 5 times, so you get 5 outputs.
As for some reason you're not allowed to use HashMaps, this should solve it:
String name[] = new String[]{"jack", "jack", "jack", "james", "jack", "jack", "james"};
ArrayList<String> checkedNames = new ArrayList<String>();
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
if(!checkedNames.contains(n))
{
int count = 0;
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
checkedNames.add(n);
System.out.println(n + " - " + count);
}
}
Edit: As you can't use ArrayLists but can sort the array:
String name[] = new String[]{"jack", "jack", "jack", "jack", "jack", "james"};
String lastName = "";
Arrays.sort(name);
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
if(!lastName.equals(n))
{
int count = 0;
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
System.out.println(n + " - " + count);
}
lastName = n;
}
Second edit:
Firstly, Arrays is a class built into Java, just as String is:
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
Secondly, if you want it to print asterisks, then change the System.out.println line to this:
System.out.println(n + " (" + count + ")" + new String(new char[count]).replace("\0", "*"));

Please check next code:
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
int count = 0;
boolean flag = true;
for (int i = 0; i < counter; i++){
if (name[i].equals(n)) {
flag = false;
}
}
if (flag) {
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
System.out.println(n + " - " + count);
}
}
Here you checked if selected name not yet in the array (from 0 to counter) than you count how many times it keeps in array and display information.

Will you try having a different array (lets say encouteredNames) which will store those names whose number of occurrence you've already counted? And then execute only the 'counting' loop only when you've determined that the name to be searched has not been searched previously (or it is still not stored in the encounteredNames array).
I'm sure there are better implementations than this, but for the meantime:
String[] names = {"Jack", "James", "Charles", "Jack", "Jack", "James"};
String[] encounteredNames = new String[names.length];
int encounteredNamesCount = 0;
for (int counter = 0; counter < names.length; counter++) {
String name = (names[counter]);
boolean nameAlreadyEncountered = false;
for (int i = 0; i < encounteredNames.length && encounteredNames[i] != null; i++) {
if (encounteredNames[i] == name) {
nameAlreadyEncountered = true;
break;
}
}
if (!nameAlreadyEncountered) {
encounteredNames[encounteredNamesCount++] = name;
int count = 0;
for (int i = 0; i < names.length; i++){
if (names[i].equals(name)) {
count++;
}
}
System.out.println(name + " - " + count);
}
}

Related

How can I display the largest amount in my 2D array?

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
public class labb8 {
public static void main(String[] args) {
Random rnd = new Random();
int[][] sales = new int[5][7];
int[] total = new int[sales.length];
ArrayList<String> unpopularSoftware = new ArrayList<String>();
String[] locations = {"Houston", "Dallas", "Hunts", "San Ant", "Austin"};
System.out.println("Location\t| Software Sales\t\t| Total Sales");
System.out.println("--------------------------------------------------");
for (int i = 0; i < sales.length; i++) {
for (int j = 0; j < sales[i].length; j++) {
sales[i][j] = rnd.nextInt(25);
total[i] += sales[i][j];
}
System.out.print(locations[i] + "\t\t|");
System.out.print(" " + Arrays.toString(sales[i]));
System.out.println("\t| " + total[i]);
}
int unpopularModelCounter;
for (int j = 0; j < sales[0].length; j++) {
unpopularModelCounter = 0;
for (int i = 0; i < sales.length; i++) {
if (sales[i][j] != 0) {
unpopularModelCounter++;
}
}
if (unpopularModelCounter <= 3) {
unpopularSoftware.add("Software " + (j + 1));
}
}
System.out.println("Unpopular Software: " + unpopularSoftware);
System.out.println("Location with most sold licenses: ");
}
}
Above is the code and it gives me the results I'm looking for; however, I'd like to know some methods on how can I print out the name of the location that has the most sold software? What I've tried is putting System.out.println(total[i]); under System.out.println("\t| " + total[i]); but that just displayed all the totals, which is what I figured would happen. I've also tried putting System.out.println(total[i]); where the other output lines are at the bottom(which is where I want it), but the code can't find [i], which made me believe that I might have to create some methods; so, again, I'm asking for some course of advice on how to print out the name of the city with the largest amount sold in terms of my code.
If you want the name of the city the the highest total, you need to look through the total array for the largest total and, while doing that, keep track of both the largest total you've seen so far and the index at which you saw that largest total.
Something like this should do the job nicely:
// Our initial guess is that `total[0]` is the maximum sales total.
int maxSales = total[0];
int maxI = 0;
for (int i = 1; i < total.length; ++i) {
if (totals[i] > maxSales) {
maxSales = total[i];
maxI = i;
}
}
System.out.println(locations[maxI] + " has the most sales: " + maxSales);
Maybe try adding this to the end of the code.
int max = 0; // stores the maximum value
for (int i = 0; i < total.length; i++) {
max = Math.max(max, total[i]);
}
System.out.println(max);
This should print the greatest value of the total array. I like your code!

Remove a duplicate word sentence in an array

Given a problem that determines the output of the word, length of each word, and the number of times the word repeats, I have the following code capable to determine the word and length of each word below:
String sentence;
String charSentence;
String[] wordOutput;
private void analyzeWords(String s) {
String[] words = sentence.split(" ");
wordOutput = new String[words.length];
int[] repeats = new int[words.length];
// Increment a single repeat
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
// Increment when repeated.
for (int j = i + 1; j < words.length - 1; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
repeats[i]++;
}
}
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
}
When I run the program, I get the following output:
Equal 5 2
Equal 5 1 <- This is a duplicate word and should not be here when it repeats.
Does anyone know where my problem is? Is it something relating that deals with my repeats array?
The first problem is that in the inner for loop you are looping from i+1 to length-1. You need to loop till length. Second you will need to determine if there are any occurrences of the word in the String, and if so use a continue statement. You can do:
outer:
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
for(int index = i-1; index >= 0; index--) {
if(words[i].equals(words[index])) {
continue outer;
}
}
...
}
However the problem with this is that there will be null values at the end of the list, as you specify an Array with the same length as the number of words. To solve this you can do:
wordOutput = Arrays.stream(wordOutput).filter(e-> e!= null).toArray(String[]::new);
Which will filter out the null values
Output:
(With the input String: "This is a String is a with a lot lot of this repeats repeats")
This 4 2
is 2 2
a 1 3
String 6 1
with 4 1
lot 3 2
of 2 1
this 4 1
repeats 7 2
Instead of incrementing count at all index store the count only in last occurence of word, in other case, have the count value of 0. at the end traverse the count array, if its greater than zero, print the value and its count
private void analyzeWords(String s) {
String[] words = sentence.split(" ");
wordOutput = new String[words.length];
int[] repeats = new int[words.length];
for (int i = 0; i < words.length; i++) {
int count =1;
int index = i;
for (int j = i + 1; j < words.length - 1; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
count++;
index = j;
}
}
if(repeats[index]==0){
repeats[index]=count; // update repeat array only for last occurence of word
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[index];
}
}
First, as GBlodgett mention you should check all left words for repeats, your current solution skips last word. Update second loop termination condition to j < words.length.
Second, if you want to print duplicates only once you need a condition in your solution. One of the example:
boolean[] duplicates = new boolean[words.length];
// Increment a single repeat
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
// Check for duplicates,
// If the word was not marked as duplicate
if (!duplicates[i]) {
// Increment when repeated.
for (int j = i + 1; j < words.length; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
repeats[i]++;
duplicates[j] = true;
}
}
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
}
}
There is a Java 8+ solution, for example:
Map<String, Long> m = Arrays.stream(s.split(" ")).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map will have pairs of word and it occurrences.

Trying to find common elements between the rows in a single 2D array

I have a 2 dimensional String array and I am trying to find if the rows have common elements between them and what that element is. It should look at the element that is in (0,0) and compare it to the element that is in (1,0), (1,1), (1,2) and so on. I am trying to use nested for loops but I can't seem to get it right. Could someone tell me what is wrong with my code and how I should fix it?
for(int i = 0; i < times.length; i++ ){
for(int j = 0; j < times[i].length; j++ ){
if(i+1 < times.length)
if(times[i][j].equals(times[i+1][j])){
System.out.println(times[i][j + " = " + times[i+1][j])
}
}
}
I will try to keep this as intuitive and easy to understand as possible. The bounds for the first row is [0, times.length - 2]. That way, the bounds for the second row will be [1, times.length - 1].
For each element in first row, I will check every element in the second row. The following code demonstrates that.
for(int row = 0 ; row < times.length - 1 ; row++) {
for(int colFirst = 0 ; colFirst < times(row).length ; colFirst++) {
for(int colSecond = 0 ; colSecond < times(row + 1).length ; colSecond++) {
if(times[row][colFirst].equals(times[row+1][colSecond]))
System.out.println(times[i][j + " = " + times[i+1][j]);
}
}
}
You want something like this:
String[][] times = new String[][] {
{ "aaa", "bbb", "ccc" },
{ "bbb", "dfdf", "ddd" },
{ "dfdfff", "ddd" }
};
for (int i = 0; i < times.length - 1; i++)
{
for (int j = 0; j < times[i].length; j++)
{
String currStringPrevRow = times[i][j];
String [] nextRow = times[i + 1];
for (String s : nextRow)
{
if (s.equals(currStringPrevRow))
{
System.out.println(s + " in row [" + i + "] is equal to " + s + " is row " + (i+1));
}
}
}
}

Printing array elements with a for loop

This is a challenge question from my online textbook I can only get the numbers to prin forward... :(
Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline.
Ex: If courseGrades = {7, 9, 11, 10}, print:
7 9 11 10
10 11 9 7
Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.
Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]).
import java.util.Scanner;
public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;
/* Your solution goes here */
for(i=0; i<NUM_VALS; i++){
System.out.print(courseGrades[i] + " ");
}
for(i=NUM_VALS -1; i>3; i++){
System.out.print(courseGrades[i]+ " ");
}
return;
}
}
This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
for (i = 0; i < NUM_VALS; i++) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for (i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
Your two loops almost were correct. Try using this code:
for (int i=0; i < NUM_VALS; i++) {
// this if statement avoids printing a trailing space at the end.
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i]);
}
for (int i=NUM_VALS-1; i >= 0; i--) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i] + " ");
}
To print backwards you want:
for(i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");
I also have been working on the this textbook question. The issue with the above code is that i has already been assigned, so trying using int in the for loop will cause an error. Below is the code I used to successfully achieve the desired outcome.
for ( i = 0 ; i <NUM_VALS; ++i) {
if (i > 0) {
System.out.print("");
}
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for ( i = NUM_VALS -1; i >=0; --i) {
if (i > 0) {
System.out.print("");
}
System.out.print( courseGrades[i] + " ");
}
System.out.println();

Java - Adjacent comparing and calculating frequency of words [duplicate]

This question already has answers here:
Calculating frequency of each word in a sentence in java
(20 answers)
Closed 9 years ago.
I have a already sorted string array named arr and Supposing I enter the sentence
hello how hello to how me in
Desired Output is
hello 2
how 2
me 1
in 1
to 1
Here's how I am trying to count it
int counter = 1;
for(j1 = 0; j1 < arr.length; j1++){
if(j1 + 1 < arr.length){
if(arr[j1].equals(arr[j1 + 1])){
counter++;
} else {
System.out.println(arr[j1] + " " + counter);
counter = 1;
}
}
}
but this is not working , please help?
The problem is the line:
if(j1 + 1 < arr.length) {...}
You are not iterating over the whole array; the last element is left uncounted.
Without explaining to much, this could be a quick fix:
public static void main(String[] args) {
String[] arr = { "hello", "how", "hello", "to", "how", "me", "in" };
Arrays.sort(arr);
int counter = 1;
for (int j1 = 0; j1 < arr.length; j1++) {
int j2 = j1 + 1;
String next = (j2 < arr.length) ? arr[j2] : null;
if (arr[j1].equals(next)) {
counter++;
} else {
System.out.println(arr[j1] + " " + counter);
counter = 1;
}
}
}

Categories

Resources