So for an assignment in my class, we have a lab where we have to write code that will do three things:
generate an array of 50 random numbers from 0-9.
Return how many 8's appear in the array.
Return the number of runs in the array.
We were given a .java file to start out with that is this:
package ArrayOfInts;
public class ArrayOfInts {
private int [] intArray;
private int eights;
private int runs;
//Sets intArray to the parameter and initializes all other variables
public ArrayOfInts(int [] x){
}
//Returns how many 8's are in the array.
public int findTheEights(){
return eights;
}
//Returns the number of runs in the array.
public int countTheRuns(){
return runs;
}
}
The code I've written so far is this:
package ArrayOfInts;
public class ArrayOfIntsTester {
public static void main(String [] args){
int [] testArray = new int [50];
for(int i = 0; i < testArray.length; i++){
int x = (int)(Math.random()*9);
testArray[i]= x;
System.out.print(x + ", ");
}
System.out.println();
ArrayOfInts test = new ArrayOfInts(testArray);
System.out.println(test.findTheEights());
System.out.println(test.countTheRuns());
}
}
I honestly have no idea where to start with this. Help?? The code I've written generates the correct type of array, but I don't know how to count what I need to count for it.
For the eights: iterate over the array and do eights++ everytime you find an eight.
if (testArray[i] == 8){
eights++
}
Here is some pseudo code to help you count the eights:
numberOfEights = 0;
for each element in testArray{
if (element equals 8) {
numberOfEights = nnumberOfEight + 1
} else {
nothing to do
}
}
return numberOfEights
Try to turn this to java code.
For the other part, i don't understand what is your runs.
//To count number of eights, iterate through array with a counter and increment it when we see an 8
public ArrayOfInts(int [] x){
eights = 0; //reset our count
for (int currentInt : intArray)
{
if (currentInt == 8)
eights++;
}
//Process runs here
}
To count the number of eight just use another variable which is initialized to 0 , like this :-
int c=0;
for (i=0;i<testArray.length;i++)
{
if (testArray[i] == 8)
{
c++;
}
}
Now your c has the number of 8's present in your array you cant print its value.
--> If that's what you are trying to ask
first initialize the array in constructor
public ArrayOfInts(int [] x){
intArray=x;
}
initialize the eights to 0
private int eights=0;
then update your count method
public int findTheEights(){
for(int current:intArray)
{
if(current==8){ eights++;}
}
return eights;
}
In JavaScript you could do it like the following example.
Counting of eights can be done directly at the initializaion of the array.
And if I understand you right, you'd like to count the instances of the object with the countTheRuns(). That can be done with a class variable.
If you'd like to play with the code, you'll find it here at jsFiddle.
/*So for an assignment in my class, we have a lab where we have to write code that will do three things:
generate an array of 50 random numbers from 0-9.
Return how many 8's appear in the array.
Return the number of runs in the array.
*/
(function() {
var MAX_RANDOM = 50;
var NUM_RANGE = 9; // 0 to 9
function ArrayOfInts() {
this.eights = 0;
this.numbers = [];
this.init();
// class variabe run_counter
ArrayOfInts.run_counter = (ArrayOfInts.run_counter || 0) +1;
this.getNumbers = function() {
return this.numbers;
};
this.getEights = function() {
return this.eights;
};
}
ArrayOfInts.prototype.init = function() {
for (var i=0; i< MAX_RANDOM; i++) {
var randNum = Math.floor(Math.random()*(NUM_RANGE+1));
this.numbers.push(randNum);
if (randNum == 8) this.eights++;
}
};
// demo usage code ---------------------
var array = new ArrayOfInts();
var array2 = new ArrayOfInts();
document.getElementById('output').innerHTML = array.getNumbers();
console.log(array.getNumbers());
document.getElementById('output').innerHTML += '<br/>The array has the following no. of eights: ' + array.getEights();
document.getElementById('output').innerHTML += '<br/>The number generation ran ' + ArrayOfInts.run_counter + ' times.';
})();
<div id="output"></div>
Related
Learning about Arrays. I am not able to figure out why a new number is not added to the back of my existing array. I read in two textfiles in file_1.txt are the numbers '1 2 3' and in file_2.txt is the number '91'. Basically without the method of Void addBack() the program does what I expect, however by adding the method it seems not make a new Array. Even when I go over the elements[i] = elements[i-1] it won't print it as a whole. I am expecting to print for the first part
The numbers are: 1 2 3 and the second part The numbers are: 1 2 3 91.
public class ExampleLecture {
IntRow readIntRow(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.add(input.nextInt());
}
return result;
}
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while(input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
void print(IntRow row) {
for (int i = 0; i < row.numberOfElements; i++) {
System.out.printf("%d ", row.elements[i]);
}
System.out.printf("\n");
}
void start() {
Scanner in = UIAuxiliaryMethods.askUserForInput().getScanner();
Scanner in2 =UIAuxiliaryMethods.askUserForInput().getScanner();
IntRow row = readIntRow(in);
IntRow row2 = setBack(in2);
System.out.printf("the numbers are: ");
print (row);
System.out.printf("the new numbers are: ");
print (row2);
}
public static void main(String[] args) {
new ExampleLecture().start();
}
}
package examplelecture;
class IntRow {
static final int MAX_NUMBER_OF_ELEMENTS = 250;
int[] elements;
int numberOfElements;
IntRow() {
elements = new int[MAX_NUMBER_OF_ELEMENTS];
numberOfElements = 0;
}
void add(int number) {
elements[numberOfElements] = number;
numberOfElements += 1;
}
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
elements[i] = number;
}
}
}
You have 2 successive assignments which write to the same position:
elements[i] = elements[i-1];
elements[i] = number;
The value is alway overwritten with number, so the first statement has no effect.
Also in your addBack method your for cycle:
for (int i = numberOfElements; i>0; i--) {
What happens if numberOfElements is 0?
You call it addBack but it looks like a better name for the method is addFirst. Usually index 0 is considered the front, not the back.
First off, both the readIntRow() and setBack() methods create new IntRow objects row and row2. If you want the result to be appended to the first IntRow object created i.e. to row , you should call:
IntRow row = readIntRow(in);
IntRow row2 = row.setBack(in2);
and setBack() needs to be modified to:
IntRow setBack(Scanner input) {
while(input.hasNext()) {
this.add(input.nextInt());
System.out.println("here");
}
return this;
}
Note that in setBack(), if you are trying to append numbers to the end of the IntRow object, you should call add() instead of addBack() as above. If you are trying to add to the front, you should call addBack() [and it might be better to call it addFront() instead].
Also, in the implementation of addBack(), if you are trying to add to the front of the IntRow object, the element[i] = number operation should take place only once, after the loop. Otherwise all the values in indices <= numberOfElements would be overwritten with number.
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
}
elements[0] = number;
}
Admittedly it is not entirely clear what you are trying to accomplish. But you may have several problems. The first is as follows:
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
IntRow has nothing in it since it is new. So all you are doing is iterating over the new file which has just 91 in it. Remember, result has no items. So it won't even iterate once in addBack.
So just do the following:
Change your addBack method to just add the numbers. Why use a loop to cascade down the elements since you are doing this within the same instance of IntRow? Just add it on to the end using the numberofElements as the next index.
void addBack(int number) {
elements[numberOfElements++] = number;
}
If you want to copy the contents of one IntRow object to another you would need another method in the IntRow class. Something like:
public void copy(IntRow r) {
for (int i = 0; i < r.numerOfElements; i++) {
elements[i] = r.elements[i];
}
numerOfElements = r.numberOfElements;
}
And keeping with good design it might be better to return numberOfElements in a method such as public int size();
I have tried some solutions from the forum but did not worked for me, if the answer be specific in kotlin language then it will me more helpful for me.
You can try this out with recursion function that will only return unique random number in the range of 0 to 6.
private var randomNumber: Int = 0
private var integerList: MutableList<Int>? = null
private fun getRandomNumber(): Int {
val rand = Random()
randomNumber = rand.nextInt(7)
if (integerList!!.contains(randomNumber)) {
getRandomNumber()
} else {
integerList!!.add(randomNumber)
}
return randomNumber
}
As Andrew Thompson say here you can
Add each number in the range sequentially in a list
Shuffle it
Take the first 'n' numbers from the list
A simple implementation would be:
import java.util.ArrayList;
import java.util.Collections;
public class UniqueRandomNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<3; i++) {
System.out.println(list.get(i));
}
}
}
This would print 3 unique random numbers from 1 to 10
int[] Numbers;
int num = 0;
getRandomNum();
public void getRandomNum()
{
Random rand = new Random(10);
if(Numbers.contains(rand))
{
Log.i("console","Try Again");
}
else
{
num = rand;
Numbers.add(rand);
}
}
First of all I wouldn't recommend a function for that, rather use a class that encapsulates the logic which increases usability.
1st option
You can use the List function (yes, it's really a function here) to generate a list of all possible numbers, then shuffle it and after that iterate over it.
class UniqueRandomNumbers(lowerBound: Int, upperBound: Int) {
private val iterator = List(upperBound - lowerBound) {
lowerBound + it + 1
}.shuffled().iterator()
val next get() = if (iterator.hasNext()) iterator.next() else null
}
2nd option
Alternatively you could generate random numbers until you find one that has not been consumed before.
class UniqueRandomNumbers(val lowerBound: Int, val upperBound: Int) {
private val consumedNumbers = mutableSetOf<Int>()
val next: Int?
get() {
var newNumber: Int
if (consumedNumbers.size == (upperBound - lowerBound + 1)) {
return null
}
do {
newNumber = Random.nextInt(lowerBound, upperBound + 1)
} while (newNumber in consumedNumbers)
consumedNumbers += newNumber
return newNumber
}
}
Usage in both cases:
val numberProvider = UniqueRandomNumbers(0, 2)
// returns 0, 1, 2 or null if all numbers have been consumed
numberProvider.next
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[].
I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")
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;
}
}