Array index out of bounds in sieve of eratosthenes - arrays

I am having trouble with ArrayIndexOutOfBounds.
I am new to coding and I don't fully understand this problem and I am unable to fix it. Any help is appreciated.
public class Primes {
public static void main(String[] args) {
final int SIZE = 10000;
boolean[] numberIsPrime = new boolean[SIZE];
int rowCounter = 0;
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
for( int index = 2; index <= SIZE; index++) {
if( numberIsPrime[index] = true){
for( int i = index; i <= SIZE; i++){
numberIsPrime[index * i] = false;
}
}
}
for( int index = 1; index <= SIZE; index++){
if( numberIsPrime[index] = true){
System.out.println(index + " ");
rowCounter++;
if( rowCounter == 10){
System.out.println();
}
}
}
}
}

You should tag the question with the language you're using, but I'm gonna assume it's Java. The problem is
boolean[] numberIsPrime = new boolean[SIZE];
...
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
The first line declares numberIsPrime as an array of size 10000. That means you can access numberIsPrime[0], numberIsPrime[1], ... numberIsPrime[9999]. You can't access numberIsPrime[10000].

Related

Reverse an Array without using reverse Function and other array the same array to be reverse all elements in the same array. size fix

// I am tring but cant do it
int[] arr = {1,3,4,2,5,6};
int n = arr.length,x = 0;
for (int i = 0 ; i < n; i++ ) {
x++;
System.out.println(arr[i]);
}
//try this:
public class reverseArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = new int[] { 1,3,4,2,5,6 };
System.out.print("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
// method #1: by using extra array
System.out.println();
System.out.print("Reversed array method 1: ");
int j = 0;
int revArr[] = new int[] { arr.length };
for (int i = arr.length - 1; i >= 0; i--) {
revArr[j] = arr[i];
System.out.print(revArr[j] + " ");
}
// method #2: without using extra array
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
System.out.println();
System.out.print("Reversed array method 2: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

number of subarray with average greater than average of the rest of the elements of array

We are given a array of size < 2000
and A[i]< 10^6.I know the bruteforce approach.Can we do better i.e in linear time ?
I am checking each subarray and comparing its average with the other elements.
public class FindingSubArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
double avg1 = getAverage(i,j,arr);
double avg2 = getAverageOfRest(i,j,arr);
//System.out.println(avg1+" "+avg2);
if(avg1 > avg2) {
a.add(i+1);
b.add(j+1);
}
}
}
System.out.println(a.size());
for(int i=0;i<a.size();i++){
System.out.println(a.get(i)+" "+b.get(i));
}
}
private static double getAverageOfRest(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for(int k=0;k<i;k++) {
result += arr[k] ;
count ++;
}
for(int k=j+1;k<arr.length;k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
private static double getAverage(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for (int k = i; k <= j; k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
}

Selection Sort for strings and integers at the same time

Here is the task I have been set with:
Create a text file named Names_ages.txt with the following content:
Jones 14
Abrams 15
Smith 19
Jones 9
Alexander 22
Smith 20
Smith 17
Tippurt 42
Jones 2
Herkman 12
Jones 11
Each line is a person’s last name followed by a space and then his age. We want to sort these names alphabetically and in the case of duplicate names, sort by age in an ascending fashion. A properly sorted list will appear as follows:
Abrams, 15
Alexander, 22
Herkman, 12
Jones, 2
Jones, 9
Jones, 11
Jones, 14
Smith, 17
Smith, 19
Smith, 20
Tippurt, 42
Here are my (working) selection sort methods for Strings and ints respectively:
private static void sort(String[] a) {
String min;
int minIndex;
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
// find minimum
for (int j = i + 1; j < a.length; j++) {
// salient feature
if (a[j].charAt(0) < min.charAt(0)) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; // swap
a[i] = min;
}
}
private static void sort(int[] a) {
int min, minIndex;
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
// find minimum
for (int j = i + 1; j < a.length; j++) {
// salient feature
if (a[j] < min) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; // swap
a[i] = min;
}
}
I can sort the names in the text file and then the numbers after, but the ages end up corresponding with incorrect people. Here is my class with the main method:
Scanner scanner = new Scanner(new File("/Users/Krish/IdeaProjects/Lessons/src/Lesson40/MultipleKey/NamesAges.txt"));
String text[] = new String[100];
int index = 0;
while (scanner.hasNext()) {
text[index++] = scanner.nextLine();
}
scanner.close();
String name;
String[] names = new String[index];
int age;
int[] ages = new int[index];
for (int i = 0; i < index; i++) {
Scanner line = new Scanner(text[i]);
name = line.next();
names[i] = name;
age = line.nextInt();
ages[i] = age;
}
sort(names);
sort(ages);
for (int i = 0; i < index; i++) {
System.out.println(names[i] + ", " + ages[i]);
}
Any help is appreciated, thanks.
Create a POJO class Person implementing Comparable<Person>
After parsing, store Person instances in a collection, say List<Person>
Sort the collection
-
public class PersonTest {
static class Person implements Comparable<Person> {
private static final Comparator<Person> COMPARATOR = Comparator
.comparing(Person::getName)
.thenComparingInt(Person::getAge);
final String name;
final int age;
public static Person parse(String rec) {
final String[] parts = rec.split(" ");
return new Person(parts[0], Integer.valueOf(parts[1]));
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
#Override
public int compareTo(Person o) {
return COMPARATOR.compare(this, o);
}
}
#Test
public void testSorting() throws Exception {
final Person[] sortedPersons = Files.lines(Paths.get("/path/to/file.txt"))
.map(Person::parse)
.sorted() // sort it here
.toArray(Person[]::new);
// or instead, sort it here with your custom algorithm
// using Person.COMPARATOR for comparison
}
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("/Users/Krish/IdeaProjects/Lessons/src/Lesson40/MultipleKey/NamesAges"));
String[] text = new String[100];
int index = -1;
while (scanner.hasNext()) {
text[++index] = scanner.nextLine();
}
scanner.close();
Scanner line;
String[] name = new String[100];
int[] age = new int[100];
for (int i = 0; i <= index; i++) {
line = new Scanner(text[i]);
name[i] = line.next();
age[i] = line.nextInt();
}
String minName;
int minAge;
int minIndex;
for (int i = 0; i <= index; i++) {
minName = name[i];
minAge = age[i];
minIndex = i;
for (int j = i + 1; j <= index; j++) {
if (name[j].compareTo(minName) == 0) {
if (age[j] < minAge) {
minName = name[j];
minAge = age[j];
minIndex = j;
}
} else if (name[j].compareTo(minName) < 0) {
minName = name[j];
minAge = age[j];
minIndex = j;
}
}
name[minIndex] = name[i];
name[i] = minName;
age[minIndex] = age[i];
age[i] = minAge;
}
for (int j = 0; j <= index; j++) {
System.out.println(name[j] + ", " + age[j]);
}
}

gridview dataitem to decimal array

enter code hereHello I try to convert the dataitem into decimal array, here is my code;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (; i < 9; )
{
if (!DBNull.Value.Equals(DataBinder.Eval(e.Row.DataItem, headerNames[i])))
TotalSales += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, headerNames[i]));
totals(e.Row.DataItem);
}
}
}
public static decimal[] totals(object arr)
{
decimal[] res = arr as decimal[];
decimal[] sRes = res.OfType<decimal>().ToArray();
return sRes;
}
I can see that the dataitem successfully assigned to arr.
However the line
decimal[] res = arr as decimal[]; does not assign the arr to res, so the next line gives me an error complaining the value cannot be null.
Can you please help?
While I was waiting for an answer here, I tried and came up with a code that calculates totals in GridView_DataBound event, please comment if there is anything can be better and how to not show the total (0.0) under the columns that do not have decimal values (i.e. string)
public static void gridViewTotals1(object sender , EventArgs e)
{
var grdview = (GridView)sender;
decimal[,] rowAndColumns = new decimal[grdview.Rows.Count, grdview.Columns.Count];
decimal n;
decimal[] totalSalesArray = new decimal[grdview.Columns.Count];
for (int i = 0; i < grdview.Columns.Count; i++)
{
for (int j = 0; j < grdview.Rows.Count; j++)
if (decimal.TryParse(grdview.Rows[j].Cells[i].Text, out n))
{
rowAndColumns[j, i] = Convert.ToDecimal(grdview.Rows[j].Cells[i].Text);
}
}
GridViewRow footerRow = grdview.FooterRow;
for (int k = 0; k < grdview.Columns.Count; k++)
{
decimal totalSales = 0;
for (int l = 0; l < grdview.Rows.Count; l++)
{
totalSales += rowAndColumns[l, k];
totalSalesArray[k] = totalSales;
footerRow.Cells[k].Text = String.Format("{0:N2}", totalSales);
}
}
}

I need to determine if a random number is unique

I need to write a function that receives the number generated in fillArray and determine if it has already been generated. I need to return a true or false thus determining if the random number must be put into the array.
Here's what I am working on. Thanks for any help. I've searched for anything similar but unfortunately cannot find anything.
public class RandomGenerator {
int Arr[] = new int[6];
int size;
public void fillArray() {
int randNum = (int) (Math.random() * 49) + 1;
for (int i = 0; i < size; i++) {
Arr[i] = randNum;
alreadyThere(randNum);
}
size++;
}
public int alreadyThere(int randNum) {
int find = randNum;
boolean found = false;
int i = 0;
while (!found && i < size) {
if (Arr[i] == find) {
found = true;
}
i++;
}
if (!found) {
}
return randNum;
}

Resources