I have an array and have already sorted it. I want to be able to find which numbers repeat. Following that, I want to be able to count how many times these numbers repeat. For example in a list [1,2,3,3,4,4] 3 and 4 repeats and they both repeats twice. My following code is able to find which numbers repeats but unable to get my mind around on how to count the number of times they each repeat. And I am using ArrayList. Trying to skip that and keep everything to purely just arrays excluding hashmap too. Appreciate any help. Tnks.
public static void main(String[] args) {
int[] num = {1,2,3,3,4,4};
for(int x : num){
System.out.print(x + " ");
}
System.out.println("\n" + freq(num));
}
public static ArrayList<Integer> freq(int[] num){
ArrayList<Integer> list = new ArrayList<>();
for(int x=0; x < num.length-1; x++){
if(num[x] == num[x+1]){
if(!list.contains(num[x])){
list.add(num[x]);
}
}
}
return list;
}
Well, since your array is sorted,you could use another array where each index corresponds to the amount of hits for this number:
int[] count = new int[num[num.length - 1]];
Then you could increment the index of this counter for each match:
count[num[x] - 1] = count[num[x] - 1] + 1;
This would however not compact your representation, just bring it to another form. Since you do not know the result lenght before the computation, a more compact representation without lists or even better maps is however not possible since the size of an array must be known at creation. This solution will only work with numbers bigger than 0. For other ranges, you have to adjust the offset.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
int[] num = {1,2,3,3,4,4};
for(int x : num){
System.out.print(x + " ");
}
System.out.println("\n" + freq(num));
}
static class ValueCountPair {
public ValueCountPair( final int val )
{
value = val;
count = 2;
}
public int value;
public int count;
public String toString() {
return "[" + value + ": " + count + "]";
}
}
public static ArrayList<ValueCountPair> freq(final int[] num){
ArrayList<ValueCountPair> list = new ArrayList<ValueCountPair>();
ValueCountPair last = null;
for(int x=0; x < num.length-1; x++){
if(num[x] == num[x+1]){
if ( last == null || last.value != num[x+1] )
list.add( last = new ValueCountPair( num[x+1] ) );
else
++last.count;
}
}
return list;
}
}
Related
the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running
package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class bubbleSort {
public static void main(String[] args) {
int length = getLength();
List<Integer> randomList = createList(length);
System.out.println("The list before sorting:\n" + randomList);
List<Integer> newList = sortList(randomList, length);
System.out.println("The list after sorting:\n" + newList);
}
public static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
int length = Integer.parseInt(reader.nextLine());
return length;
}
public static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> randomList = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
return randomList;
}
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
}
}
}
return randomList;
}
}
Create a swap method to make it clearer (both for us and yourself):
private void swap(List<Integer> values, x, y) {
int temp = values.get(x);
values.set(x, values.get(y));
values.set(y, temp);
}
Other suggestions:
name your class BubbleSort rather than bubbleSort. Convention for class names is to start with uppercase.
don't pass the length as a second argument to your sort method. It's redundant and might become incorrect if someone sneakily adds an item to the list.
rename randomList to values or numbers or randomNumbers. No need to repeat the type in the variable name.
replace sorted == false with !sorted. This is the common and more readable notation
getLength and createList can be private
Consider using the main method to create an instance of your sorting class, with the list as a field. In that way the methods won't have to pass the list along to each other. Your code will be more readable and more object-oriented.
EDIT: you could take the separation even further and move all the static methods into a separate class called 'Application' or 'Main'. See edited code below:
Here's roughly how the code would look following my suggestions:
public class BubbleSort {
// a field
private List<Integer> numbers;
public BubbleSort(List<Integer> numbers) {
this.numbers = numbers;
}
public static List<Integer> sort() {
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int x = 0; x < length - 1; x++) {
if(numbers.get(x) > numbers.get(x + 1)) {
sorted = false;
swap(x, x + 1);
}
}
}
return numbers;
}
private void swap(x, y) {
int temp = numbers.get(x);
numbers.set(x, numbers.get(y));
numbers.set(y, temp);
}
}
The Application class. It's purpose is to get the length from the user, create test data and set up and call a BubbleSort instance:
public class Application {
public static void main(String[] args) {
int length = getLength();
List<Integer> unsorted = createList(length);
System.out.println("The list before sorting:\n" + unsorted);
// creating an instance of the BubbleSort class
BubbleSort bubbleSort = new BubbleSort(unsorted );
List<Integer> sorted = bubbleSort.sort();
System.out.println("The list after sorting:\n" + sorted);
}
private static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
return Integer.parseInt(reader.nextLine());
}
private static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> numbers = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
numbers.add(randomnumber);
}
return numbers;
}
BTW Good job splitting off those methods getLength and createList. That's the right idea.
you made a couple of mistakes
this:
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
should be:
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
full method:
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
}
}
}
return randomList;
}
I am doing a pretty basic assignment. "Use recursion to print the values of a list" and I came up with the code below, but as it passes the list EVERY time it calls itself I wondered if there is a better way. Any advice please?
public class RecurList {
public static void main(String[] args) {
int[] list = {8,7,9,10,56};
int ix = list.length;
int sumNow = ShowNext(ix, 0, list); // initial call -> sum is 0
System.out.println("Recursion total is " + sumNow);
}
public static int ShowNext(int inx, int sum, int[] lst) {
if (inx == 0) return sum;
int item = lst[inx - 1];
sum += item;
System.out.println("inx:" + inx + " item:" + item + " sum:" + sum);
return ShowNext(inx - 1, sum, lst);
}
}
Please read and follow Java Naming Conventions. Start your method names with a lowercase letter.
"Use recursion to print the values of a list"
You failed that assignment since you're using an array instead of a list.
it passes the list EVERY time it calls itself I wondered if there is a better way.
There are two solutions to this problem.
The more intentional approach is what #Prune suggested: shorten the list (which is an array in your case) by one element. The utility class Arrays has methods to do this.
The lesser "recursive" style is to make the array a class member and remove it from the methods parameter list:
public class RecurList {
static int[] list;
public static void main(String[] args) {
list = {8,7,9,10,56};
int ix = list.length;
int sumNow = ShowNext(ix, 0); // initial call -> sum is 0
System.out.println("Recursion total is " + sumNow);
}
public static int ShowNext(int inx, int sum) {
if (inx == 0) return sum;
int item = lst[inx - 1];
sum += item;
System.out.println("inx:" + inx + " item:" + item + " sum:" + sum);
return ShowNext(inx - 1, sum);
}
}
I am attempting to generate an ADDITIONAL single random number and create another method that will have three parameters = the integer array, the size of the array, and the value it will be searching for in the array. It will search through the array and count how many times the value was found.It will then either print out how many times the value was found or that the value was not found. I am a bit lost and this is what I have so far which generates the random array and prints it/ asking the user if they want to restart. Thanks in advance
My code:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
I should not be telling you the whole code, since this looks like a homework question.
So here are the hints:
Creating an additional random number - Not so difficult, as you have RND_GEN
int rn = RND_GEN.nextInt(10)+1; //exactly as you have been doing it.
Creating a method that takes three parameters.... Here is the method header:
void search(int[] array, int size, int val)
Body of the method? You have various search algorithms out there. Some of the most popular ones are:
linear search
binary search
So just go on, research, learn and do it yourself.
I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].