Sorting an array of String in BlackBerry - blackberry

I need to sort an array of String like the following, in ascending order.
String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};
How to do that? I need help.

This answer is based on Signare and HeartBeat's suggestion. Explore this link for details. Also this link, Sorting using java.util.Array might be helpful.
// Initialization of String array
String strs[] = {"One", "Two", "Threee", "Four", "Five", "Six", "Seven"};
// implementation of Comparator
Comparator strComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
// Sort
Arrays.sort(strs, strComparator);

Try this -
import java.util.*;
import java.io.*;
public class TestSort1 {
String [] words = { "RĂ©al", "Real", "Raoul", "Rico" };
public static void main(String args[]) throws Exception {
try {
Writer w = getWriter();
w.write("Before :\n");
for (String s : words) {
w.write(s + " ");
}
java.util.Arrays.sort(words);
w.write("\nAfter :\n");
for (String s : words) {
w.write(s + " ");
}
w.flush();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
// useful to output accentued characters to the console
public static Writer getWriter() throws UnsupportedEncodingException {
if (System.console() == null) {
Writer w =
new BufferedWriter
(new OutputStreamWriter(System.out, "Cp850"));
return w;
}
else {
return System.console().writer();
}
}
}

Here is my solution:-
String str[]={"ASE","LSM","BSE","LKCSE","DFM"};
for(int j = 0; j < str.length; j++){
for(int i = j + 1; i < str.length; i++) {
if(str[i].compareTo(str[j]) < 0) {
String t = str[j];
str[j] = str[i];
str[i] = t;
}
}
}

Related

Can I use class methods inside factory constructor via Dart

I have the below code that is creating the PriortyQueue structure using Dart. But since I cannot use heapify function inside the Constructor or factory constructor I cannot initialize PQ with an existing set of List. Can somebody guide me and show me how I can use heapify while creating PQ instance so I can initialize it with an existing List? Also If you have any other suggestions against doing something like this please also help me as well. thank you
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
// ignore: todo
//TODO: missing heapify
return PriorityQueue._(newArray);
}
void insert(T node) {
_tree.add(node);
_swim(_tree.length - 1);
}
T getTop() {
_swap(1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(1);
return top;
}
List<T> _heapify(List<T> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(sinkNodeIndex);
sinkNodeIndex--;
}
}
void _sink(int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
// index can be unreachable
T? leftChild =
leftChildIndex >= _tree.length ? null : _tree[leftChildIndex];
T? rightChild =
rightChildIndex >= _tree.length ? null : _tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((_tree[minNodeIndex] as T).compareTo(_tree[nodeIndex] as T) < 0) {
_swap(nodeIndex, minNodeIndex);
_sink(minNodeIndex);
}
}
void _swim(int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((_tree[nodeIndex] as T).compareTo(_tree[parentIndex] as T) < 0) {
_swap(nodeIndex, parentIndex);
_swim(parentIndex);
}
}
void _swap(int i, int j) {
T temp = _tree[i] as T;
_tree[i] = _tree[j];
_tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}
I would make all the helper functions. _heapify, _sink/_swim, even _swap, be static functions which take the list as argument.
Then you can use them from anywhere, including inside the factory constructor.
Alternatively, you can change the constructor to returning:
return PriorityQueue._(newArray).._heapify();
This creates the PriorityQueue object, and then calls the _heapify method on it, before returning the value.
(I'd also make _tree have type List<T> and not insert the extra null at the beginning. It's more efficient to add/subtract 1 from indices than it is to cast to T.)
I ended up doing like Irn's first suggestion. But when I do functions static they lost Type of the class so I needed to specify for each function. Also, making List<T?> instead of List ended up with me fighting against the compiler.
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
_heapify(newArray);
return PriorityQueue._(newArray);
}
bool get isNotEmpty {
return _tree.isNotEmpty;
}
void insert(T node) {
_tree.add(node);
_swim(_tree, _tree.length - 1);
}
void insertMultiple(List<T> array) {
for (var element in array) {
insert(element);
}
}
T? removeTop() {
if (_tree.length == 1) return null;
_swap(_tree, 1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(_tree, 1);
return top;
}
void removeAll() {
_tree = [null];
}
static void _heapify<T extends Comparable<T>>(List<T?> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(array, sinkNodeIndex);
sinkNodeIndex--;
}
}
static void _sink<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
T? leftChild = leftChildIndex >= tree.length ? null : tree[leftChildIndex];
T? rightChild =
rightChildIndex >= tree.length ? null : tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((tree[minNodeIndex] as T).compareTo(tree[nodeIndex] as T) < 0) {
_swap(tree, nodeIndex, minNodeIndex);
_sink(tree, minNodeIndex);
}
}
static void _swim<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((tree[nodeIndex] as T).compareTo(tree[parentIndex] as T) < 0) {
_swap(tree, nodeIndex, parentIndex);
_swim(tree, parentIndex);
}
}
static void _swap<T extends Comparable<T>>(List<T?> tree, int i, int j) {
T temp = tree[i] as T;
tree[i] = tree[j];
tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}

Implementing stacks, ques using linked lists. Difference between "=" operator and setlink() function

This is my code
import java.util.*;
class node{
public int data;
public node link;
public node()
{
data = 0;
link = null;
}
public node(int d, node l)
{
data = d;
link = l;
}
void setlink(node n)
{
link = n;
}
void setdata(int dat)
{
data = dat;
}
int showdata()
{
return data;
}
node showlink()
{
return link;
}
}
class stack{
node top;
int size;
stack()
{
top = null;
size = 0;
}
void push()
{
node npt = new node();
size++;
System.out.println("Enter the value you want to enter :");
Scanner sc = new Scanner(System.in);
int val;
val = sc.nextInt();
npt.setdata(val);
if( top == null )
{
top = npt;
}
else
{
npt.setlink(top);
top = npt;
}
}
void pop()
{
node npt = top;
top = npt.showlink();
size--;
}
void showstack()
{
node nptr = top;
int i = 1;
while( nptr != null )
{
System.out.println("Data at position "+ i + " is : " + nptr.showdata());
i++;
nptr = nptr.showlink();
}
}
}
class stacked{
public static void main(String args[])
{
stack obj = new stack();
int temp = 0;
while( temp != 1 )
{
System.out.println("-- Enter 1 to exit -- 2 to push -- 3 to pop -- 4 to show Stack --");
Scanner sc = new Scanner(System.in);
temp = sc.nextInt();
if(temp == 1)
{
break;
}
switch(temp)
{
case 2: obj.push();
break;
case 3: obj.pop();
break;
case 4: obj.showstack();
break;
}
temp++;
}
}
}
My question is in the function void push() in class stack what is the difference between "=" operator and setlink() function.
I mean why cannot we write npt = top; instead of npt.setlink(top); ?
What does "=" do and how is the referencing done?
Thanks

Why is javac telling me illegal start of expression?

Here's my code, i do not know what I'm doing wrong seriously. I tried many different things like taking the public modifier away from get. but I still get the same thing. This program is supposed to print out the Nth number line in the pascal triangle do to that I am using recursion a little bit.
import java.util.*;
public class Triangle{
private int lineNumber, count;
private int[] num;
public Triangle(){
lineNumber = 1;
}
public Triangle(int n){
set(n);
}
public void set(int n){
if(n < 1){
lineNumber = 1;
}
else{
lineNumber = n;
}
public int get()//Triangle.java:26: error: ';' expected //
{
return lineNumber;
}
private void pascal(int[] row){ //Triangle.java:30: error: illegal start of expression
if(count >= lineNumber){
return;
}
num = new int[row.length + 1];
num[0] = 1;
for(int i = 1; i < row.length; i++){
num[i] = row[i - 1] + row[i];
}
num[row.length] = 1;
count ++;
pascal(num);
return;
}
public int[] output(){
count = 1;
num = new int[count];
num[0] = 1;
pascal(num);
return num;
}
public static void main(String[] args){
int i,userNum;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a number to get the nth line of"+
" Pascal's Triangle." );
userNum = input.nextInt();
PascalTriangle triangle = new Triangle(userNum);
int[] result = triangle.output();
System.out.println("\n Line " + triangle.get() + " of "
+ "Pascal's Triangle is ");
for(i = 0; i < result.length; i++){
System.out.println(result[i] + " ");
}
}
}
}
You need one more closing bracket after the else statement in the set() method.Try to add the closing } before
else{
lineNumber = n;
}
}
public int get()//Triangle.java:26: error: ';' expected //

Why does this priority queue implementation only print one value repeatedly?

This program should print out the values in order ascending order. But it only displays 957.0 repeatedly. How do I display the numbers in order?
import java.io.*;
import java.util.*;
class PriorityQ {
public int maxSize;
public double[] queArray;
public int nItems;
//------
public PriorityQ(int s){
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
//-----
public void insert(double item){
int j;
if(nItems == 0){
queArray[nItems++] = item;
}
else{
for(j = nItems-1; j >= 0; j--){
if(item > queArray[j]){
queArray[j + 1] = item;
}
else{
break;
}
}
queArray[j + 1] = item;
nItems++;
}
}
//-----
public double remove(){
return queArray[--nItems];
}
//-----
public double peekMin(){
return queArray[nItems - 1];
}
//-----
public boolean isEmpty(){
return(nItems == 0);
}
//-----
public boolean isFull(){
return(nItems == maxSize);
}
}
//-----
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(546);
thePQ.insert(687);
thePQ.insert(36);
thePQ.insert(98);
thePQ.insert(957);
while(!thePQ.isEmpty()){
double item = thePQ.remove();
System.out.print(item + " ");
}
System.out.println("");
}
}
You should save yourself the effort and use a priority queue with the generic type Double. If you wanted descending order you could even use a comparator that orders the highest value before the lowest, but you asked for ascending.
Your problem is that your array does contain many copies of 957.
This is because of this line in your code:
if(item > queArray[j]){
queArray[j + 1] = item;
}
Try:
import java.io.*;
import java.util.*;
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQueue<Double> thePQ = new PriorityQueue<Double>(5);
thePQ.add(546);
thePQ.add(687);
thePQ.add(36);
thePQ.add(98);
thePQ.add(957);
while(thePQ.size() > 0){
double item = thePQ.poll();
System.out.print(item + " ");
}
System.out.println("");
}
}
Or I can fix your code to print out the queue in descending order leaving it to you to then make it print out in ascending order, the block I pointed to before should read like this instead:
if(item < queArray[j]){
queArray[j + 1] = queArray[j];
}

Windows Phone character-encoding

My code is Encoding.GetEncoding("iso-8859-9"); in my Windows Phone project. But "iso-8859-9" is not supported on Windows Phone. How can I fix this problem?
http://www.hardcodet.net/2010/03/silverlight-text-encoding-class-generator
I also found this link but I don't know how to use it.
To use the program, just type the encoding name and it will generate the class like so:
Then make a file for the class somewhere (Copypaste the code generated from the program) and start using it:
//Instead of
Encoding enc = Encoding.GetEncoding("iso-8859-9");
//do this
Encoding enc = new ISO88599Encoding();
//Proceed exactly the same
The code generated is too long to copypaste here but hopefully you manage with these instructions.
Here is a piece of code that is Windows Phone 7.1 (and Silverlight I think) compatible that redefines an ISO-8859-9 (or Latin9) encoding. The code also redefines the ISO-8859-1 (or Latin1) and Windows-1252 for convenience. It could also be used to define the other ISO Latin encoding family:
public class Latin9Encoding : LatinEncoding
{
public Latin9Encoding()
: base(CharMap)
{
}
static Latin9Encoding()
{
CharMap = new Dictionary<byte, char>();
CharMap.Add(0xD0, '\u011E');
CharMap.Add(0xDD, '\u0130');
CharMap.Add(0xDE, '\u015E');
CharMap.Add(0xF0, '\u011F');
CharMap.Add(0xFD, '\u0131');
CharMap.Add(0xFE, '\u015F');
}
public static Dictionary<byte, char> CharMap;
public override string WebName
{
get
{
return "iso-8859-9";
}
}
}
public class Windows1252Encoding : LatinEncoding
{
public Windows1252Encoding()
: base(CharMap)
{
}
static Windows1252Encoding()
{
CharMap = new Dictionary<byte, char>();
CharMap.Add(0x80, '\u20AC');
CharMap.Add(0x82, '\u201A');
CharMap.Add(0x83, '\u0192');
CharMap.Add(0x84, '\u201E');
CharMap.Add(0x85, '\u2026');
CharMap.Add(0x86, '\u2020');
CharMap.Add(0x87, '\u2021');
CharMap.Add(0x88, '\u02C6');
CharMap.Add(0x89, '\u2030');
CharMap.Add(0x8A, '\u0160');
CharMap.Add(0x8B, '\u2039');
CharMap.Add(0x8C, '\u0152');
CharMap.Add(0x8E, '\u017D');
CharMap.Add(0x91, '\u2018');
CharMap.Add(0x92, '\u2019');
CharMap.Add(0x93, '\u201C');
CharMap.Add(0x94, '\u201D');
CharMap.Add(0x95, '\u2022');
CharMap.Add(0x96, '\u2013');
CharMap.Add(0x97, '\u2014');
CharMap.Add(0x98, '\u02DC');
CharMap.Add(0x99, '\u2122');
CharMap.Add(0x9A, '\u0161');
CharMap.Add(0x9B, '\u203A');
CharMap.Add(0x9C, '\u0153');
CharMap.Add(0x9E, '\u017E');
CharMap.Add(0x9F, '\u0178');
}
public static Dictionary<byte, char> CharMap;
public override string WebName
{
get
{
return "Windows-1252";
}
}
}
public class Latin1Encoding : LatinEncoding
{
public Latin1Encoding()
: base(null)
{
}
public override string WebName
{
get
{
return "iso-8859-1";
}
}
}
public abstract class LatinEncoding : Encoding
{
protected LatinEncoding(Dictionary<byte, char> map)
{
FallbackByte = (byte)'?';
if (map != null)
{
Map = map;
ReverseMap = new Dictionary<char, byte>(map.Count);
foreach (var entry in map)
{
ReverseMap[entry.Value] = entry.Key;
}
}
}
public byte FallbackByte { get; set; }
public Dictionary<byte, char> Map { get; private set; }
public Dictionary<char, byte> ReverseMap { get; private set; }
public override int GetByteCount(char[] chars, int index, int count)
{
return count;
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (chars == null)
throw new ArgumentNullException("bytes");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
if (bytes == null)
throw new ArgumentNullException("bytes");
if (byteIndex < 0)
throw new ArgumentOutOfRangeException("byteIndex");
if ((charIndex + charCount) > chars.Length)
throw new ArgumentOutOfRangeException("charCount");
if ((byteIndex + charCount) > bytes.Length)
throw new ArgumentOutOfRangeException("charCount");
for (int i = 0; i < charCount; i++)
{
char c = chars[charIndex + i];
if (ReverseMap != null)
{
byte b;
if (ReverseMap.TryGetValue(c, out b))
{
bytes[byteIndex + i] = b;
continue;
}
}
bytes[byteIndex + i] = c > 255 ? FallbackByte : (byte)c;
}
return charCount;
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return count;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (chars == null)
throw new ArgumentNullException("chars");
if (byteIndex < 0)
throw new ArgumentOutOfRangeException("byteIndex");
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if ((byteIndex + byteCount) > bytes.Length)
throw new ArgumentOutOfRangeException("byteCount");
if ((charIndex + byteCount) > chars.Length)
throw new ArgumentOutOfRangeException("byteCount");
for (int i = 0; i < byteCount; i++)
{
if (Map != null)
{
char c;
if (Map.TryGetValue(bytes[byteIndex + i], out c))
{
chars[charIndex + i] = c;
continue;
}
}
chars[charIndex + i] = (char)bytes[byteIndex + i];
}
return byteCount;
}
public override int GetMaxByteCount(int charCount)
{
return charCount;
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount;
}
}

Resources