C# coding, I need to create several text files and populate it with unsorted lists of integers, then read it from the respective file into a list - sorting

ArrayList List;
String FileName;
static void Main(string[] args)
{
List<int> Integers = new List<int>();
Console.WriteLine("Please pick desired list size");
Console.WriteLine("Use the respective number (1)Small, (2)Medium, (3)Large, or (4)XLarge");
int size = int.Parse(Console.ReadLine());
Randomgen(List);
}
static void Randomgen(int Size, ArrayList List)
{
StreamWriter SW = new StreamWriter(FileName); ;
switch (Size)
{
case 1:
Random random = new Random();
for (int i = 0; i < 101; i++)
{
List.Add(new Integers(random.Next(1, int.MaxValue)));
}
break;
case 2:
Random randomM = new Random();
for (int i = 0; i < 2001; i++)
{
List.Add(new Integers(randomM.Next(1, int.MaxValue)));
}
break;
case 3:
Random randomL = new Random();
for (int i = 0; i < 20001; i++)
{
List.Add(new Integers(randomL.Next(1, int.MaxValue)));
}
break;
case 4:
Random randomXL = new Random();
for (int i = 0; i < 200001; i++)
{
List.Add(new Integers(randomXL.Next(1, int.MaxValue)));
}
break;
}
}
static void populateListFromFile(string FileName, ArrayList List)
{
StreamReader Input = new StreamReader(FileName);
while (!Input.EndOfStream)
{
List.Add(new Integers(int.Parse(Input.ReadLine())));
}
Console.WriteLine("File has been successfully imported");
}
}
****Im trying to create 1 of 4 different text files based of the user selection using the switch case, with an arraylist of unsorted integers and then I want to Streamread back into an arraylist usign my populate listfrom file method, so that I may proceed to sort them later using 3 other sorting methods. the whole point is to measure the efficiency of the algorithms over different amounts of data or list sizes. the main method is giving me trouble though. Most of my knowledge is self studied so please bare with me.

So what exactly is the problem you are facing, from what I can see, your Randomgen function accepts 2 parameters which is int Size and ArrayList List. However in your call to it in Main you are only providing it with 1 parameters Randomgen(List);, therefore the whole switch case inside of that function won't work.

Related

Generate an array of random numbers not present in a list dart

so i have a list of predefined numbers where each number consists of 6 numbers like this {1,2,3,4,5,6 ; 34,52,3,76,12,4 ; 53,1,4,76,23,5 ; .... }
each individual number in the group of numbers range from 1 to 99,
import 'dart:math';
main() {
var rng = new Random();
var l = new List.generate(12, (_) => rng.nextInt(100));
}
i want to generate an array of 6 different random numbers using dart in a way that it is not already present in the list of numbers i already have.
import 'dart:math';
void main() {
var listOfSets = List<Set<int>>();
final int nElementsWithMax = 99;
final int kTaken = 6;
final int requiredResults = 3;
for (int i = 0; i < requiredResults; i++) {
bool isInList = false;
Set<int> anewSet;
do {
anewSet = Set.of(listRandom(nElementsWithMax, kTaken));
isInList = listOfSets.firstWhere(
(setInList) => anewSet.intersection(setInList).length == anewSet.length,
orElse: () => null)
!= null;
} while (isInList);
listOfSets.add(anewSet);
}
print(listOfSets);
}
List<int> listRandom(int maxNumber, int numberOfGenerations) {
final random = Random();
var currentOptions = List<int>.generate(maxNumber, (i) => i);
var list = List.generate(numberOfGenerations, (_) {
final index = random.nextInt(currentOptions.length);
final result = currentOptions[index];
currentOptions.removeAt(index);
return result;
});
return list;
}
Keep in mind that you cannot exceed the combination limit defined here.
In your case, requiredResults cannot exceed (100!)/((6! * (100 - 6)!) ... some huge number

Iterate lists of different length using Java 8 streams

I am trying to iterate over three lists of different size but not getting the exact logic of how i can retrieve data from them and store in another list.
I was able to handle up to two list until I add some more filtration to the elements. For now I am using 3 for loops but i want to use Java 8 streams if possible. Can someone please suggest me the correct logic for the below iterations.
public class CustomDto {
public static void main(String... args) {
List<String> list1 = Arrays.asList("Hello", "World!");
List<String> list2 = Arrays.asList("Hi", "there");
List<String> list3 = Arrays.asList("Help Me");
Map<Integer, Object> map = new HashMap<>();
for (int i = 0; i < list1.size(); i++) {
List<String> list4 = new LinkedList();
for (int j = 0; j < list2.size(); j++) {
for (int k = 0; k < list3.size(); k++) {
if (!(list2.get(j).equals(list3.get(k))))
list4.add(list2.get(j));
}
if (j > list4.size() - 1) {
list4.add(null);
}
}
map.put(i, list4);
}
}
}
All i want to convert the above code into stream, in which i can iterate a list inside another list and can use the index of one another.
public static void main(String... args) {
List<String> list1 = Arrays.asList("Hello", "World!");
List<String> list2 = Arrays.asList("Hi", "there");
List<String> list3 = Arrays.asList("Help Me");
List<String> list4 = concat(list1, list2, list3); //you can add as many lists as you like here
System.out.println(list4);
}
private static List<String> concat(List<String>... lists) {
return Stream.of(lists)
.flatMap(List::stream)
.collect(Collectors.toList());
}
Output
[Hello, World!, Hi, there, Help Me]
Try this create a multiple dimension array out of List, from there you can use stream too
Customdto[][] listArray = new Customdto[][]{ l1.toArray(new Customdto[]{})
, l2.toArray(new Customdto[]{}), l3.toArray(new Customdto[]{})};
int size = listArray[0].length > listArray[1].length && listArray[0].length > listArray[2].length ?listArray[0].length
:(listArray[1].length > listArray[2].length ? listArray[1].length:listArray[2].length);
for(int i = 0; i <size;i++)
{
if(listArray[0].length >i && listArray[1].length >i && listArray[2].length >i &&
listArray[0][i].equals(listArray[1][i])
&& listArray[1][i].getCalendarDate().equals(listArray[2][i].getCalendarDate()))
{
l4.add(listArray[1][i]);
}else
{
l4.add(null);
}
}
Tried with Below Input
List<Customdto> l1 = new ArrayList<Customdto>();
List<Customdto> l2 = new ArrayList<Customdto>();
List<Customdto> l3 = new ArrayList<Customdto>();
List<Customdto> l4 = new ArrayList<Customdto>();
l1.add(new Customdto(1));
l1.add(new Customdto(2));
l1.add(new Customdto(3));
l1.add(new Customdto(4));
l2.add(new Customdto(1));
l2.add(new Customdto(2));
l2.add(new Customdto(3));
l3.add(new Customdto(1));
l3.add(new Customdto(2));
Output is
[Customdto [id=1], Customdto [id=2], null, null]

Two sum data structure problems

I built a data structure for two sum question. In this data structure I built add and find method.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example:
add(1); add(3); add(5);
find(4) // return true
find(7) // return false
the following is my code, so what is wrong with this code?
http://www.lintcode.com/en/problem/two-sum-data-structure-design/
this is the test website, some cases could not be passed
public class TwoSum {
private List<Integer> sets;
TwoSum() {
this.sets = new ArrayList<Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
// Write your code here
this.sets.add(number);
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
// Write your code here
Collections.sort(sets);
for (int i = 0; i < sets.size(); i++) {
if (sets.get(i) > value) break;
for (int j = i + 1; j < sets.size(); j++) {
if (sets.get(i) + sets.get(j) == value) {
return true;
}
}
}
return false;
}
}
There does not seem to be anything wrong with your code.
However a coding challenge could possibly require a more performant solution. (You check every item against every item, which would take O(N^2)).
The best solution to implement find, is using a HashMap, which would take O(N). It's explained more in detail here.

How to find a word from arrays of characters?

What is the best way to solve this:
I have a group of arrays with 3-4 characters inside each like so:
{p, {a, {t, {m,
q, b, u, n,
r, c v o
s } } }
}
I also have an array of dictionary words.
What is the best/fastest way to find if the array of characters can combine to form one of the dictionary words? For example, the above arrays could make the words:
"pat","rat","at","to","bum"(lol)but not "nub" or "mat"Should i loop through the dictionary to see if words can be made or get all the combinations from the letters then compare those to the dictionary
I had some Scrabble code laying around, so I was able to throw this together. The dictionary I used is sowpods (267751 words). The code below reads the dictionary as a text file with one uppercase word on each line.
The code is C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace SO_6022848
{
public struct Letter
{
public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static implicit operator Letter(char c)
{
return new Letter() { Index = Chars.IndexOf(c) };
}
public int Index;
public char ToChar()
{
return Chars[Index];
}
public override string ToString()
{
return Chars[Index].ToString();
}
}
public class Trie
{
public class Node
{
public string Word;
public bool IsTerminal { get { return Word != null; } }
public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
}
public Node Root = new Node();
public Trie(string[] words)
{
for (int w = 0; w < words.Length; w++)
{
var word = words[w];
var node = Root;
for (int len = 1; len <= word.Length; len++)
{
var letter = word[len - 1];
Node next;
if (!node.Edges.TryGetValue(letter, out next))
{
next = new Node();
if (len == word.Length)
{
next.Word = word;
}
node.Edges.Add(letter, next);
}
node = next;
}
}
}
}
class Program
{
static void GenWords(Trie.Node n, HashSet<Letter>[] sets, int currentArrayIndex, List<string> wordsFound)
{
if (currentArrayIndex < sets.Length)
{
foreach (var edge in n.Edges)
{
if (sets[currentArrayIndex].Contains(edge.Key))
{
if (edge.Value.IsTerminal)
{
wordsFound.Add(edge.Value.Word);
}
GenWords(edge.Value, sets, currentArrayIndex + 1, wordsFound);
}
}
}
}
static void Main(string[] args)
{
const int minArraySize = 3;
const int maxArraySize = 4;
const int setCount = 10;
const bool generateRandomInput = true;
var trie = new Trie(File.ReadAllLines("sowpods.txt"));
var watch = new Stopwatch();
var trials = 10000;
var wordCountSum = 0;
var rand = new Random(37);
for (int t = 0; t < trials; t++)
{
HashSet<Letter>[] sets;
if (generateRandomInput)
{
sets = new HashSet<Letter>[setCount];
for (int i = 0; i < setCount; i++)
{
sets[i] = new HashSet<Letter>();
var size = minArraySize + rand.Next(maxArraySize - minArraySize + 1);
while (sets[i].Count < size)
{
sets[i].Add(Letter.Chars[rand.Next(Letter.Chars.Length)]);
}
}
}
else
{
sets = new HashSet<Letter>[] {
new HashSet<Letter>(new Letter[] { 'P', 'Q', 'R', 'S' }),
new HashSet<Letter>(new Letter[] { 'A', 'B', 'C' }),
new HashSet<Letter>(new Letter[] { 'T', 'U', 'V' }),
new HashSet<Letter>(new Letter[] { 'M', 'N', 'O' }) };
}
watch.Start();
var wordsFound = new List<string>();
for (int i = 0; i < sets.Length - 1; i++)
{
GenWords(trie.Root, sets, i, wordsFound);
}
watch.Stop();
wordCountSum += wordsFound.Count;
if (!generateRandomInput && t == 0)
{
foreach (var word in wordsFound)
{
Console.WriteLine(word);
}
}
}
Console.WriteLine("Elapsed per trial = {0}", new TimeSpan(watch.Elapsed.Ticks / trials));
Console.WriteLine("Average word count per trial = {0:0.0}", (float)wordCountSum / trials);
}
}
}
Here is the output when using your test data:
PA
PAT
PAV
QAT
RAT
RATO
RAUN
SAT
SAU
SAV
SCUM
AT
AVO
BUM
BUN
CUM
TO
UM
UN
Elapsed per trial = 00:00:00.0000725
Average word count per trial = 19.0
And the output when using random data (does not print each word):
Elapsed per trial = 00:00:00.0002910
Average word count per trial = 62.2
EDIT: I made it much faster with two changes: Storing the word at each terminal node of the trie, so that it doesn't have to be rebuilt. And storing the input letters as an array of hash sets instead of an array of arrays, so that the Contains() call is fast.
There are probably many way of solving this.
What you are interested in is the number of each character you have available to form a word, and how many of each character is required for each dictionary word. The trick is how to efficiently look up this information in the dictionary.
Perhaps you can use a prefix tree (a trie), some kind of smart hash table, or similar.
Anyway, you will probably have to try out all your possibilities and check them against the dictionary. I.e., if you have three arrays of three values each, there will be 3^3+3^2+3^1=39 combinations to check out. If this process is too slow, then perhaps you could stick a Bloom filter in front of the dictionary, to quickly check if a word is definitely not in the dictionary.
EDIT: Anyway, isn't this essentially the same as Scrabble? Perhaps try Googling for "scrabble algorithm" will give you some good clues.
The reformulated question can be answered just by generating and testing. Since you have 4 letters and 10 arrays, you've only got about 1 million possible combinations (10 million if you allow a blank character). You'll need an efficient way to look them up, use a BDB or some sort of disk based hash.
The trie solution previously posted should work as well, you are just restricted more by what characters you can choose at each step of the search. It should be faster as well.
I just made a very large nested for loop like this:
for(NSString*s1 in [letterList objectAtIndex:0]{
for(NSString*s2 in [letterList objectAtIndex:1]{
8 more times...
}
}
Then I do a binary search on the combination to see if it is in the dictionary and add it to an array if it is

Adding dynamic values in an input box using watin for a web based application

I am working on a web based application which takes care of online orders placed by customers .
we are using watin for sanity.This is what my code reads
mybrowser.TextField(Find.ByName("searchBox")).Value = "milk";
mybrowser.Image(Find.ByName("search")).Click();
In the input field i want to add any string value(e.g meat/bakery) of X length
Please help
As I read your question you want to be able to generate and input a string of a specific, given length X. Here is some code I wrote a while ago for that.
public static string GetRandomString(int length)
{
StringBuilder randomString = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i < length; i++)
{
randomString.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * randomNumber.NextDouble() + 65))));
}
return randomString.ToString();
}
If you want to pick from a specific list of items I would use code like this
public static string GenerateRandomFood()
{
string[] foods = {"Bread", "Cheese", "Milk", };
// There are 3 food names
return foods[GetRandomInt(0, 2)];
}
Hope that is what you are after.

Resources