Sorting 2D Points in an array...what am I missing? - arrays

So here is the deal: I got a code from my colleague who cant figure out the mistakes he made. He wanted to sort the array first by Y, then by X (if Y=Y). Can you help?
using System;
using System.Collections;
public class Point {
public int x;
public int y;
public Point(int x, int y) {
x = x;
y = y;
}
public string ToString() {
return x + "," + y;
}
}
public class PointList {
public static void Main(string [] args) {
ArrayList AL = new ArrayList();
Random R = new Random();
for (int i = 0; i < 10; i++) {
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}
public static void PrintValues( IEnumerable myList ) {
foreach ( Object obj in myList )
Console.WriteLine( "{0}", obj );
Console.WriteLine();
}
}
Any ideas?

You can try with:
AL.Sort(delegate(Point a, Point b) {
if (a.y < b.y ) return -1;
else if (a.y > b.y ) return 1;
else {
if ( a.x < b.x ) return -1;
else if ( a.x > b.x ) return 1;
else return 0;
}
});

You could implement ICompareable and add the following code:
public class Point : IComparable
public int CompareTo(object obj)
{
if (obj == null) return 1;
Point otherPoint = obj as Point;
if (otherPoint != null)
{
if(this.y == otherPoint.y)
{
return this.x.CompareTo(otherPoint.x);
}
return this.y.CompareTo(otherPoint.y);
}
else
throw new ArgumentException("Object is not a Point");
}

Related

Flink's AggregateFunction's getResult() can change Accumulator value?

Can the getResult() function change the value of the accumulator?It still takes effect value when accumulating.
The code is in below:
public class WeightedAverage implements AggregateFunction<Datum, AverageAccumulator, Double> {
public AverageAccumulator createAccumulator() {
return new AverageAccumulator();
}
public AverageAccumulator merge(AverageAccumulator a, AverageAccumulator b) {
a.count += b.count;
a.sum += b.sum;
return a;
}
public AverageAccumulator add(Datum value, AverageAccumulator acc) {
acc.count += value.getWeight();
acc.sum += value.getValue();
return acc;
}
public Double getResult(AverageAccumulator acc) {
int result = acc.sum / (double) acc.count;
acc.count = 0; //here
acc.sum = 0; //here
return result;
}
}
No, you cannot modify the accumulator during getResult.
Flink will create new accumulators as necessary (e.g., for each new window).

Combining two instantiate scripts (Unity 3D)

I need to combine the following scripts into one script containing two functions, one that instantiates the next prefab in the array and the other that instantiates the previous prefab in the array (it is a virtual tour app). Both should also destroy the current prefab. I could then call the functions via event triggers.
I have this code for the "next Prefab" script.
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
if (gameObject.tag == "ArrowNEXT")
{
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex++;
if (currentIndex > Spheres.Length - 1) currentIndex = 0;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
I need to combine it with the following:
using UnityEngine;
public class RayCastPrevFIX: MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
if (gameObject.tag == "ArrowPREV")
{
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex--;
if (currentIndex < 0) currentIndex = Spheres.Length - 1;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
}
How would I go about this? Any help is greatly appreciated.I have this so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereSwap : MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void Next()
{
Destroy(currentObject);
currentIndex++;
if (currentIndex > Spheres.Length - 1) currentIndex = 0;
currentObject = Instantiate(Spheres[currentIndex]);
}
void Previous()
{
Destroy(currentObject);
currentIndex--;
if (currentIndex < 0) currentIndex = Spheres.Length - 1;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
You're on the right path, but you could shorten the code as well as use one function for both cases to avoid boilerplate:
using UnityEngine;
public class SphereSwap : MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
const string ArrowPrevTag = "ArrowPREV";
const string ArrowNextTag = "ArrowNEXT";
private void HandleClick(bool next)
{
if(Spheres == null || Spheres.Length == 0)
{
Debug.Log($"Spheres list is empty, nothing to swap.");
return;
}
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
// destroy current sphere.
Destroy(currentObject);
// go next or previous.
currentIndex += next ? 1 : -1;
// circular clamp if overflow
if (currentIndex < 0)
currentIndex = Spheres.Length - 1;
else if (currentIndex >= Spheres.Length)
currentIndex = 0;
// finally do instantiate.
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
// 'CompareTag' is more efficient than gameobject.tag == "sometag"
if (gameObject.CompareTag(ArrowNextTag))
HandleClick(true);
else if (gameObject.CompareTag(ArrowPrevTag))
HandleClick(false);
}
}
}

WPF Listbox Collection custom sort

I have a listbox
DropPrice
MyPrice
Price1
Price2
I want to sort it like this
Price1
Price2
DropPrice
MyPrice
I mean, if there's an item that starts with the sequence "price", it gets priority, else the smallest string should get the priority.
My source code:
var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource));
var customSort = new PrioritySorting("price");
lcv.CustomSort = customSort;
internal class PrioritySorting : IComparer
{
private string _text;
public PrioritySorting(string text)
{
_text = text;
}
public int Compare(object x, object y)
{
//my sorting code here
}
}
How can i write compare method. I know, that it can return 1,0 or -1. How can i set priorities.
You just have to check if it starts with "price".
Note that I don't think that ToString() is appropriate; you should rather implement IComparer<T> and strongly type your objects in your listbox.
public int Compare(object x, object y)
{
// test for equality
if (x.ToString() == y.ToString())
{
return 0;
}
// if x is "price" but not y, x goes above
if (x.ToString().StartsWith("Price") && !y.ToString().StartsWith("Price"))
{
return -1;
}
// if y is "price" but not x, y goes above
if (!x.ToString().StartsWith("Price") && y.ToString().StartsWith("Price"))
{
return 1;
}
// otherwise, compare normally (this way PriceXXX are also compared among themselves)
return string.Compare(x.ToString(), y.ToString());
}
Here is sample code snippet for IComparer.
private class sortYearAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
car c1=(car)a;
car c2=(car)b;
if (c1.year > c2.year)
return 1;
if (c1.year < c2.year)
return -1;
else
return 0;
}
}
This is more specific to your Question
internal class PrioritySorting : IComparer
{
private string _text;
public PrioritySorting(string text)
{
_text = text;
}
public int Compare(object x, object y)
{
var str1 = x as string;
var str2 = y as string;
if (str1.StartsWith("price") )
{
if (str2.StartsWith("price"))
return 0;
return 1;
}
return -1;
}
}

Putting array with unknown variables into another array

The purpose of this code is is to define the root of the sum of the squares.
I cant figure out how to put i into j. Please help.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int input, som, i=0;
int j = 0;
double answer;
Boolean gaDoor= true;
int [] array = new int [24];
while (gaDoor)
{
Console.Write("Specify a positive integer");
input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
gaDoor = false;
}
else
{
if (input >= 0)
{
array[i] = input;
i++;
}
else
{
Console.WriteLine("Specify a positive integer ");
}
}
}
while (j<i)
{
sum = array [j] ^ 2;
answer = Math.Sqrt(sum);
Console.Write(answer);
}
Console.ReadKey();
}
}
}
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] invoer = new int[24];
double[] resultaat = new double[24];
double totaal = 0;
double wortel = 0;
int commando = 0;
int teller = -1;
try {
// Keep going until a negative integer is entered (or a 0)
while ((commando = Convert.ToInt32 (Console.ReadLine ())) > 0) {
teller++;
invoer [teller] = commando;
}
} catch (FormatException) {
// Not a number at all.
}
teller = -1;
foreach (int i in invoer) {
teller++;
resultaat [teller] = Math.Pow (invoer [teller], 2);
totaal += resultaat [teller];
if (invoer [teller] > 0) {
Console.WriteLine ("Invoer: {0}, Resultaat: {1}", invoer [teller], resultaat [teller]);
}
}
wortel = Math.Sqrt (totaal);
Console.WriteLine ("Totaal: {0}, Wortel: {1}", totaal, wortel);
}
}
}

Null Pointer Exception using Object Arrays

I am planning to make an airline system. I have initialized the array using initSeats but it still throws back the NPE error. It happens when i call the seatChecker() from bookMenu.
public void initSeats(){
for(int b = 0; b < seatList.length; b++)
{
initC.setName("null");
initC.setEmail("null");
initC.setCreditNo(0);
initC.setAddress("null");
initC.setPassportNo("null");
seatList[b] = new Seat('A', 0, "null", 0.0, "Available", initC);
}
for(int d = 0; d <= 24; d++)
{
seatList[d].setSeatLetter('A');
seatList[d].setSeatNo(d);
}
for(int n = 25; n <= 48; n++)
{
seatList[n].setSeatLetter('B');
seatList[n].setSeatNo(n);
}
for(int m = 49; m <= 72; m++)
{
seatList[m].setSeatLetter('C');
seatList[m].setSeatNo(m);
}
for(int t = 73; t <= 96; t++)
{
seatList[t].setSeatLetter('D');
seatList[t].setSeatNo(t);
}
for(int q = 97; q <= 120; q++)
{
seatList[q].setSeatLetter('E');
seatList[q].setSeatNo(q);
}
for(int v = 121; v < 144; v++)
{
seatList[v].setSeatLetter('F');
seatList[v].setSeatNo(v);
}
for(int x = 0; x <= 48; x++)
{
seatList[x].setSection("Front");
seatList[x].setPrice(500);
}
for(int j = 49; j <= 96; j++)
{
seatList[j].setSection("Middle");
seatList[j].setPrice(250);
}
for(int u = 97; u < 144; u++)
{
seatList[u].setSection("Back");
seatList[u].setPrice(100);
}
}
public void seatChecker(int index)
{
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available")){
System.out.println("Seat is Available.");
}else{
System.out.println("Seat is not Available. Please Pick Another Seat.");
bookMenu();
}
}
public void bookMenu()
{
int choice1 = 0;
int index;
System.out.println("Where do you want to be seated?");
System.out.println("[1] Front");
System.out.println("[2] Middle");
System.out.println("[3] Back");
choice1 = sc.nextInt();
sc.nextLine();
if(choice1 == 1){
System.out.print("Choose a seat number (0 - 48): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 2){
System.out.println("Choose a seat number (49 - 96): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 3){
System.out.println("Choose a seat number (97 - 144): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else
{
System.out.println("Invalid Choice. Going back to Menu.");
MainMenu();
}
}
Null Pointer Exception Code
Exception in thread "main" java.lang.NullPointerException
at pkg.Airlines.AirlineUI.seatChecker(AirlineUI.java:132)
Seat Class
public class Seat{
private char seatLetter;
private int seatNo;
private String section;
private double price;
private String status;
private Customer customerDetails;
public Seat(char seatLetter, int seatNo, String section, double price, String status, Customer details)
{
this.seatLetter = seatLetter;
this.seatNo = seatNo;
this.section = section;
this.price = price;
this.status = status;
this.customerDetails = details;
}
public Customer getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(Customer customerDetails) {
this.customerDetails = customerDetails;
}
public char getSeatLetter() {
return seatLetter;
}
public void setSeatLetter(char seatLetter) {
this.seatLetter = seatLetter;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Probably the problems are this two line :
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available"))
First thing could be seatList[index] is not initialized . Once you declare an array of references as :
Seat[] array = new Seat[10];
The array contains 10 null references for Seat object . You need to instantiate them before using them :
Seat[0] = new Seat();
Second potential problem will be, this check :
if(status.equalsIgnoreCase("Available"))
Replace it to :
if("Available".equalsIgnoreCase(status))
to avoid any NullPointerException in case status is null.
P.S. Please show us the Seat class to understand your problem better.
Well is quite simple resolve a Null Pointer Exception.
Probably in one of the index of seatList there isn't a value.

Resources