Selection sort Max to end - selection-sort

This is my first question or time on this site so sorry if i do anything wrong. I have been trying to get this to work for my class. my eclipse has been broken for a little while so i have been coding blind as i cant find the end result or run and execute my programs. a classmate told me this question of mine was wrong but won't tell me what. it is supposed to be a selection sort that takes the greatest integers to the end then print after each pass. this looks right to me please help.
public class selectSort {
public static void Sort (){
int[] num= {5,20,8,6,7,1,3,11,15,9};
int i;
int n;
int temp;
for (i=num.length-1; i>0; i--){
int first=0;
for(n= 1; n >= i; n++){
if( num[n] > num[first])
first=n;
}
temp = num[first];
num[first] = num[i];
num[i] = temp;
System.out.println(num);
}}}

Related

Do while loop condition is unidentified and I'm not sure why

I'm working on a do-while loop for a function to find the difference between two string lengths in a vector. For some reason, the two variables "SentinelVar" and "difference" are marked as unidentified despite the fact that I declared them earlier in the loop. I don't see anything wrong with ; placement, so if anyone here would point out what is making them unidentified, that would be amazing! Below is my code, thank you for your time!
int findDifference(int position) {
string firststring = asterisks.at(position);
int firstlength = firststring.size();
int i = 1; // Used in loop
do {
int sentinelVar = 0;
string secondstring = asterisks.at(position + 1);
int secondlength = secondstring.size();
int difference = firstlength - secondlength;
if (difference > 0) {
sentinelVar = 1;
}
else {
i++;
}
} while (sentinelVar < 1 || i = asterisks.size()); // The sentinelVar here is undefined
return difference; // This is the one that's marked also undefined
}
I've made sure by copy-pasting that I didn't misspell any of the variables. I also made sure that my ; and syntax was in order, but couldn't find anything wrong.

Why is for loop only out putting first and last entries

This is what is being asked to do...
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
This is the code I have. It compiles and runs, but only outputs the first and last entries of the unique list. Any input greatly appreciated! Thanks in advance.
import java.util.Scanner;
public class DuplicateElimination{
// sets helper functions
public static boolean isIn(int x, int[]y)
{
boolean isIn = false;// sets boolean to false
for (int i=0; i<y.length; i++)// sets for loop to run for length of array
{
if(y[i]==x)
{
isIn = true;
}
}
return isIn;
}
public static int[] append(int x, int[] y)// going to change what has already been set. creates integer array
{
int len = y.length +1;// sets length
int[] a = new int[len];// initializes new array
for (int i=0; i<y.length; i++); // goes through length of y
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
}
public static void main(String[] args)// sets main
{
Scanner input = new Scanner (System.in);// sets scanner to read input info
int[]uniqueList = new int[1];
uniqueList[0] = 0;// sets unique list to 0
System.out.print("Enter an integer between 10 and 100:");// prompts input from user
int entered = input.nextInt();// inputs value from user
System.out.printf("This is the first time %d has been entered\n", entered);// adds first entered # to unique list
uniqueList[0] = entered;// adds entered value to unique list
for (int i=0; i<4; i++)// sets loop to find unique values
{
System.out.print("Enter an integer between 10 and 100:");// prompts use
entered = input.nextInt();// inputs value
if(isIn (entered, uniqueList) == false)// calls is in function
{
System.out.printf("This is the first time %d has been entered\n", entered);
uniqueList = append(entered, uniqueList);// puts entered values in unique values on list
}
}
System.out.println("The complete list of unique values entered is:");
for(int i =0; i< uniqueList.length; i++)// runs through list to check for unique #s
{
System.out.printf("Unique value %d: is %d\n", i + 1, uniqueList[i]);// outputs list
}
}// ends main
}// ends class
in the append part change your for loop to:
for (int i=0;i<y.length;i++)
a[i]=y[i];
it didn't work because of for (int i=0; i<y.length; i++); the semi-colon is hijacking your loop as for why the result is as it is, your
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
part is just copying the first element of y into a and then copying the new element in the last cel of a
import java.util.*;
class Example{
public static void main(String args[]){
int[] xr = new int[5];
Scanner input = new Scanner (System.in);
System.out.println("Input five different integers between 10 and 100 below");
L1: for (int i = 0; i < xr.length; i++){
System.out.print("\tInput number "+(i+1)+" : ");
xr[i] = input.nextInt();
for(;xr[i]<=10 || xr[i]>=100;){
i--;
System.out.println("\t Error : You entered number is not between 10 and 100.");
continue L1;
}
for (int x = 0; x < i; x++){
if(xr[x] == xr[i]){
i--;
System.out.println("\tError : You cannot use duplicate numbers.");
continue L1;
}
}
}
System.out.println(Arrays.toString(xr));
}
}

how to return a structure (defined in .h file) from a function in another cpp file?

I ran into this issue and I cannot handle it. Any suggestion is appreciated.
I have a structure defined in a header file as follows:
Results.h
#ifndef RESULTS_H
#define RESULTS_H
struct Results
{
double dOptSizeMWh;
double dOrigSOCFinal;
double dManiSOCFinal;
};
#endif
and a general definition of "Deterministic" function in Deterministic.h:
#ifndef DETERMINISTIC_H
#define DETERMINISTIC_H
Results Deterministic(int,int,int,double,double); //Deterministic(int nNoMonth, int nNOWind, int nWindLength, double dPreviousSizeMWh, double dPreviousSOC)
#endif;
This function is implemented in Deterministic.cpp:
#include "Results.h"
Results Deterministic(int nNoMonth, int nNOWind, int nWindLength, double dPreviousSizeMWh, double dPreviousSOC)
{
// returns number of rows and columns of the array created
struct Results sRes;
sRes.dOptSizeMWh = -1.0; // for the optimal size of battery in MWh
sRes.dOrigSOCFinal = -1.0; // for the SOC at the end of the window
sRes.dManiSOCFinal = -1.0; // this is set to 0.0 if final SOC is slightly below 0
//...........................////
// OTHER Calculation .......////
//...........................////
return sRes;
}
Finally, I have a main file which I call Deterministic function and I use Results structure, main.cpp:
#include <Results.h>
#include <Deterministic.h>
using namespace std;
int main ()
{
int nNoMonth = 1; // the month that we want to use in the input
int nWindLength = 1; // length of window, hour
int nNODays = 1; // number of days that we want to repeat optimization
struct Results dValues;
double **mRes = new double*[nNODays * 24 / nWindLength];
for (int i = 0; i < nNODays * 24 / nWindLength; ++i) mRes[i] = new double[3];
for (int i = 0; i < nNODays * 24 / nWindLength; i++)
{
if (i == 0)
{
dValues = Deterministic(nNoMonth, i, nWindLength, 0.0, 0.0);
}else
{
temp0 = *(*(mRes+i-1)); double temp1 = *(*(mRes+i-1)+1); double temp2 = *(*(mRes+i-1)+2);
if (temp2 == -1.0) {dValues = Deterministic(nNoMonth, i, nWindLength, temp0, temp1);}
else {dValues = Deterministic(nNoMonth, i, nWindLength, *(*(mRes+i-1)), *(*(mRes+i-1)));}
}
*(*(mRes+i)) = dValues.dOptSizeMWh;
*(*(mRes+i)+1) = dValues.dOrigSOCFinal;
*(*(mRes+i)+2) = dValues.dManiSOCFinal;
}
these are only a small portion of the codes in Deterministic.cpp and main.cpp which defines the problem. First loop goes well (i.e., i=0) without any problem, but it fails in the second loop and beyond with this error: "R6010 - abort() has been called"
This error comes up in the main.cpp where I call Deterministic function in the if statement.
I have no problem compiling and running the posted code (other than the missing double in front of the declaration of temp). Without knowing what Deterministic() is actually doing, it's a bit hard to guess what the problem is (divide by zero? playing a Justin Bieber mp3?). It shouldn't have anything to do with returning a structure from a function defined in another file (translation units are a fundamental feature of the language). To find the root cause, single-step through the (complete) Deterministic() using your debugger.

Rating the quality of string matches

What would be the best way to compare a pattern with a set of strings, one by one, while rating the amount with which the pattern matches each string? In my limited experience with regex, matching strings with patterns using regex seems to be a pretty binary operation...no matter how complicated the pattern is, in the end, it either matches or it doesn't. I am looking for greater capabilities, beyond just matching. Is there a good technique or algorithm that relates to this?
Here's an example:
Lets say I have a pattern foo bar and I want to find the string that most closely matches it out of the following strings:
foo for
foo bax
foo buo
fxx bar
Now, none of these actually match the pattern, but which non-match is the closest to being a match? In this case, foo bax would be the best choice, since it matches 6 out of the 7 characters.
Apologies if this is a duplicate question, I didn't really know what exactly to search for when I looked to see if this question already exists.
This one works, I checked with Wikipedia example distance between "kitten" and "sitting" is 3
public class LevenshteinDistance {
public static final String TEST_STRING = "foo bar";
public static void main(String ...args){
LevenshteinDistance test = new LevenshteinDistance();
List<String> testList = new ArrayList<String>();
testList.add("foo for");
testList.add("foo bax");
testList.add("foo buo");
testList.add("fxx bar");
for (String string : testList) {
System.out.println("Levenshtein Distance for " + string + " is " + test.getLevenshteinDistance(TEST_STRING, string));
}
}
public int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
That's an interesting question! The first thing that came to mind is that the way regular expressions are matched is by building a DFA. If you had direct access to the DFA that was built for a given regex (or just built it yourself!) you could run the input measure the distance from the last state you transitioned to and an accept state, using a shortest path as a measure of how close it was to being accepted, but I'm not aware of any libraries that would let you do that easily and even this measure probably wouldn't exactly map onto your intuition in a number of cases.

shuffle card deck issues in language agnostic [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.
Problem 1 :
Product of everything except current
Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]
For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.
IMPORTANT: Your algorithm must run in linear time.
Problem 2 : ( the topic was in one of Jeff posts )
Shuffle card deck evenly
Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).
Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()
What is the complexity of your algorithm (as a function of the number n of cards in the deck)?
Explain how you would test that the cards are evenly shuffled by your method (black box testing).
P.S. I had two hours to code the solutions
First question:
int countZeroes (int[] vec) {
int ret = 0;
foreach(int i in vec) if (i == 0) ret++;
return ret;
}
int[] mysticCalc(int[] values, int[] indexes) {
int zeroes = countZeroes(values);
int[] retval = new int[values.length];
int product = 1;
if (zeroes >= 2) { // 2 or more zeroes, all results will be 0
for (int i = 0; i > values.length; i++) {
retval[i] = 0;
}
return retval;
}
foreach (int i in values) {
if (i != 0) product *= i; // we have at most 1 zero, dont include in product;
}
int indexcounter = 0;
foreach(int idx in indexes) {
if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0
retval[indexcounter] = 0;
}
else if (zeroes == 1) { // One zero on this index. result is product
retval[indexcounter] = product;
}
else { // No zeros. Return product/value at index
retval[indexcounter] = product / values[idx];
}
indexcouter++;
}
return retval;
}
Worst case this program will step through 3 vectors once.
For the first one, first calculate the product of entire contents of input, and then for every element of index, divide the calculated product by input[index[i]], to fill in your result array.
Of course I have to assume that the input has no zeros.
Tnilsson, great solution ( because I've done it the exact same way :P ).
I don't see any other way to do it in linear time. Does anybody ? Because the recruiting manager told me, that this solution was not strong enough.
Are we missing some super complex, do everything in one return line, solution ?
A linear-time solution in C#3 for the first problem is:-
IEnumerable<int> ProductExcept(List<int> l, List<int> indexes) {
if (l.Count(i => i == 0) == 1) {
int singleZeroProd = l.Aggregate(1, (x, y) => y != 0 ? x * y : x);
return from i in indexes select l[i] == 0 ? singleZeroProd : 0;
} else {
int prod = l.Aggregate(1, (x, y) => x * y);
return from i in indexes select prod == 0 ? 0 : prod / l[i];
}
}
Edit: Took into account a single zero!! My last solution took me 2 minutes while I was at work so I don't feel so bad :-)
Product of everything except current in C
void product_except_current(int input[], int index[], int out[],
int len) {
int prod = 1, nzeros = 0, izero = -1;
for (int i = 0; i < len; ++i)
if ((out[i] = input[index[i]]) != 0)
// compute product of non-zero elements
prod *= out[i]; // ignore possible overflow problem
else {
if (++nzeros == 2)
// if number of zeros greater than 1 then out[i] = 0 for all i
break;
izero = i; // save index of zero-valued element
}
//
for (int i = 0; i < len; ++i)
out[i] = nzeros ? 0 : prod / out[i];
if (nzeros == 1)
out[izero] = prod; // the only non-zero-valued element
}
Here's the answer to the second one in C# with a test method. Shuffle looks O(n) to me.
Edit: Having looked at the Fisher-Yates shuffle, I discovered that I'd re-invented that algorithm without knowing about it :-) it is obvious, however. I implemented the Durstenfeld approach which takes us from O(n^2) -> O(n), really clever!
public enum CardValue { A, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, J, Q, K }
public enum Suit { Spades, Hearts, Diamonds, Clubs }
public class Card {
public Card(CardValue value, Suit suit) {
Value = value;
Suit = suit;
}
public CardValue Value { get; private set; }
public Suit Suit { get; private set; }
}
public class Deck : IEnumerable<Card> {
public Deck() {
initialiseDeck();
Shuffle();
}
private Card[] cards = new Card[52];
private void initialiseDeck() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 13; ++j) {
cards[i * 13 + j] = new Card((CardValue)j, (Suit)i);
}
}
}
public void Shuffle() {
Random random = new Random();
for (int i = 0; i < 52; ++i) {
int j = random.Next(51 - i);
// Swap the cards.
Card temp = cards[51 - i];
cards[51 - i] = cards[j];
cards[j] = temp;
}
}
public IEnumerator<Card> GetEnumerator() {
foreach (Card c in cards) yield return c;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
foreach (Card c in cards) yield return c;
}
}
class Program {
static void Main(string[] args) {
foreach (Card c in new Deck()) {
Console.WriteLine("{0} of {1}", c.Value, c.Suit);
}
Console.ReadKey(true);
}
}
In Haskell:
import Array
problem1 input index = [(left!i) * (right!(i+1)) | i <- index]
where left = scanWith scanl
right = scanWith scanr
scanWith scan = listArray (0, length input) (scan (*) 1 input)
Vaibhav, unfortunately we have to assume, that there could be a 0 in the input table.
Second problem.
public static void shuffle (int[] array)
{
Random rng = new Random(); // i.e., java.util.Random.
int n = array.length; // The number of items left to shuffle (loop invariant).
while (n > 1)
{
int k = rng.nextInt(n); // 0 <= k < n.
n--; // n is now the last pertinent index;
int temp = array[n]; // swap array[n] with array[k] (does nothing if k == n).
array[n] = array[k];
array[k] = temp;
}
}
This is a copy/paste from the wikipedia article about the Fisher-Yates shuffle. O(n) complexity
Tnilsson, I agree that YXJuLnphcnQ solution is arguably faster, but the idee is the same. I forgot to add, that the language is optional in the first problem, as well as int the second.
You're right, that calculationg zeroes, and the product int the same loop is better. Maybe that was the thing.
Tnilsson, I've also uset the Fisher-Yates shuffle :). I'm very interested dough, about the testing part :)
Trilsson made a separate topic about the testing part of the question
How to test randomness (case in point - Shuffling)
very good idea Trilsson:)
YXJuLnphcnQ, that's the way I did it too. It's the most obvious.
But the fact is, that if you write an algorithm, that just shuffles all the cards in the collection one position to the right every time you call sort() it would pass the test, even though the output is not random.
Shuffle card deck evenly in C++
#include <algorithm>
class Deck {
// each card is 8-bit: 4-bit for suit, 4-bit for value
// suits and values are extracted using bit-magic
char cards[52];
public:
// ...
void shuffle() {
std::random_shuffle(cards, cards + 52);
}
// ...
};
Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html
Testing:
// ...
int main() {
typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
Map freqs;
Deck d;
const size_t ntests = 100000;
// compute frequencies of events: card at position
for (size_t i = 0; i < ntests; ++i) {
d.shuffle();
size_t pos = 0;
for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
++freqs[std::make_pair(pos, *j)];
}
// if Deck.shuffle() is correct then all frequencies must be similar
for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
std::cout << "pos=" << j->first.first << " card=" << j->first.second
<< " freq=" << j->second << std::endl;
}
As usual, one test is not sufficient.