Need help on solving this Arrays problem using java - arrays

Make an array of integer (score) with 10 members. Randomize the
content with value between 0-100. For each of the member of array,
visualize the value using “-” for each ten. For example: score[0] = 55 will be visualized as “-----" (Using Java).
public class w9lab1 {
public static void main(String args[]) {
double[] temperature = new double[7];
for (int i = 0; i < 7; i++) {
temperature[i] = Math.random()*100;
}
for (int i = 0; i < 7; i++) {
System.out.println(temperature[i]);
}
double totalTemperature = 0;
for (int i = 0; i < 7 ; i++) {
totalTemperature += temperature[i];
}
double maxTemperature = temperature[0];
for (int i = 1; i < 7; i++){
if (temperature[i] > maxTemperature){
maxTemperature = temperature[i];
}
}
System.out.println("Temperatur maximum adalah " + maxTemperature);
}
}

import java.util.Random;
import java.util.Arrays;
public class w9lab1 {
public static void main(String[] args) {
Random random = new Random();
int[] score = new int[10];
for (int i = 0; i < score.length; i++) {
score[i] = random.nextInt(101);
for (int n = 1; n <= score[i] / 10; n++)
System.out.print('-');
System.out.println();
}
System.out.println(Arrays.toString(score));
}
}

Related

How to call runningSum function and print it?

package Package;
import java.util.Arrays;
class Cars {
public int[] runningSum(int[] nums) {
int sum = 0;
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sum = sum+nums[0];
res[i]=sum;
}
return res;
}
public static void main(String[] args) {
int[] a = {1,2,3,4};
Cars arr = new Cars();
System.out.println(arr.runningSum(a));
}
}
//output i'm getting is [I#e580929]
//output i want is [1,3,6,10]
Am not sure what you are trying to do by sum = sum+nums[0]; after the loop. But the solution below works!
public int[] runningSum(int[] nums) {
int sum = 0;
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
res[i] = sum;
}
return res;
}
}

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);
}
}
}

flipped 2D array not filling properly

My 2D array will not fill properly I want the original array to stay unmodified, which it does, but then the next array to be flipped. For example 111, 222, 333 should be 333, 222, 111. If anyone could help it would be appreciated.
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int rows = 0, cols = 0;
System.out.println("Please enter the size or your rows first and then columns:");
Scanner input = new Scanner (System.in);
rows = input.nextInt();
cols = input.nextInt();
int [][] my2DArray = new int [rows][cols];
System.out.print("Now fill the array with the numbers you would like: ");
for(int i = 0; i < my2DArray.length; i++)
{
for(int j = 0; j < my2DArray[i].length; j++)
{
my2DArray[i][j] = input.nextInt();
}
System.out.println("");
}
System.out.println("Here is the origional unmodified array.");
for(int i = 0; i < my2DArray.length; i++)
{
for(int j = 0; j < my2DArray[i].length; j++)
{
System.out.print(my2DArray[i][j] + " ");
}
System.out.println("");
}
flipMy2DArray(my2DArray);
}
public static int[][] flipMy2DArray(int[][] inMy2DArray)
{
int [][] flipMy2DArray = new int [inMy2DArray.length][inMy2DArray.length];
for(int row = flipMy2DArray.length-1; row > 0; row--)
{
for(int cols = 0; cols < flipMy2DArray[row].length; cols++)
{
flipMy2DArray[row][cols] = inMy2DArray[row][cols];
}
System.out.println("");
}
for(int row = 0; row < flipMy2DArray.length; row ++)
{
for(int cols = 0; cols < flipMy2DArray[row].length; cols++)
{
System.out.print(flipMy2DArray[row][cols]+ " ");
}
System.out.println("");
}
return flipMy2DArray;
}
}

Resources