Powershell Combine Arrays with get-random - powershell

Hello Below is my momentary Code..
It takes seven random „meals“ out of an list and then orders them into a weekly list ordert in days.
# Food selector for the week!
#random Stuff mixed for every day.
Enum Food
{#Add Food here:
Tacos
Pizza
Quesedias
Lasagne
Älplermakkaronen
Apfelwähe
Apprikosenwähe
Rabarberwähe
Käsekuchen
Pasta
Ravioli
Empanadas
Hamburger
}
function Food {
$foodsOfWeek = [Enum]::GetValues([Food]) | Get-Random -Count 7
foreach ($day in [Enum]::GetValues([DayOfWeek])) {
([string]$day).Substring(0, 3) + ': ' + $foodsOfWeek[[DayOfWeek]::$day]
}
}
I am trying to make it so it can be combined with more arrays like this:
Enum Food
{#Add Food here:
Tacos
Pizza
Quesedias
Lasagne
Älplermakkaronen
Apfelwähe
Apprikosenwähe
Rabarberwähe
Käsekuchen
Pasta
Ravioli
Empanadas
Hamburger
}
Enum Food2
{#Add Fish Stuff here:
Whatever Fish I want^^ :)
}
#and an array for meat(like steak)
.....
#an array for som healthy food!
.....
function Food {
$foodsOfWeek = [Enum]::GetValues([Food]) | Get-Random -Count 7
foreach ($day in [Enum]::GetValues([DayOfWeek])) {
([string]$day).Substring(0, 3) + ': ' + $foodsOfWeek[[DayOfWeek]::$day]
}
}
So it does combine them and takes RANDOM out of them all but I can set criterias like it must have one at least from every "List".
Perfect would be:
Every week at least once —> Meat, Fish, Vegetables and then the rest is random from the first list...
I hope you guys can help me :)
Kind regards Alex

Albeit this may not be exactly what you are looking for, you could try the following:
{
# Food selector for the week!
#random Stuff mixed for every day.
Enum FastFood
{#Add Food here:
Tacos
Pizza
Quesedias
Lasagne
Älplermakkaronen
Apfelwähe
Apprikosenwähe
Rabarberwähe
Käsekuchen
Pasta
Ravioli
Empanadas
Hamburger
}
Enum Meat
{#Add Food here:
Steak
Chop
Beaf
Lamb
Pork
Chicken
}
function Food {
#either
$Foods = [Enum]::GetValues([FastFood]) + [Enum]::GetValues([Meat])
#or
$Foods = [Enum]::GetValues([FastFood])
$Foods += [Enum]::GetValues([Meat])
$foodsOfWeek = $Foods | Get-Random -Count 7
foreach ($day in [Enum]::GetValues([DayOfWeek])) {
([string]$day).Substring(0, 3) + ': ' + $foodsOfWeek[[DayOfWeek]::$day]
}
The $Foods variable of course is not an Enum type but an object collection, however you can then generate your random 'meal' of the day & have the option to extend the list as additional categories are added. To access a specific entry you can index as follows: $Foods[10]
The current variable contains 19 elements ($Foods.count)
Hope it helps,

Related

How to take Python Input with mistakes

I'm making a script where you guess a movie based off of a quote from it. What I'm wondering is how I make it so that I can take "Terminator" and "The Terminator" and allow spelling mistakes to still be correct.
I tried to look it up but found pretty much nothing.
#Guess that movie, gives a quote and you have to guess it for points, add a high score system.
from random import randint
points = 0
quote1 = randint(0,3)
quote2 = randint(0,3)
quote3 = randint(0,3)
quote4 = randint(0,3)
movieQuoteEasy = ["You're going to need a bigger boat.", "I'll be back.", "Here's Johnny!", "Say hello to my little friend!"]
movieQuoteMedi = ["Luca Brazi Sleeps with the fishes.", "Whatever doesn't kill you simply makes you... stranger.", "You talking to me?", "I love the smell of Napalm in the morning."]
movieQuoteHard = ["Rosebud...", "How am I funny to you? what makes me so funny.", "They call it a Royal with Cheese.", "Go ahead, make my day."]
movieQuoteExtr = ["I tried... at least I did that.", "Gentlemen, you can't fight here this is the way room!", "I'm having an old friend for Dinner.", "The greatest trick the devil pulled was convincing the world he didn't exist."]
movieAnswerEasy = ["Jaws", "The Terminator", "The Shining", "Scarface"]
movieAnswerMedi = ["The Godfather", "The Dark Knight", "Taxi Driver", "Apocalypse Now"]
movieAnswerHard = ["Casablanca", "Goodfellas", "Pulp Fiction", "Dirty Hary"]
movieAnswerExtr = ["One Flew Over the Cuckos Nest", 'Dr. Strangelove', "Silence of the Lambs", "The Usual Suspects"]
print("Welcome to Guess That Movie!")
input()
#Easy Question
print("Easy: " + movieQuoteEasy[quote1])
guess1 = input()
#Takes the value for use input and checks it against the correct answer.
if guess1 == movieAnswerEasy[quote1]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerEasy[quote1])
#Medium Question
print("Medium: " + movieQuoteMedi[quote2])
guess2 = input()
#Takes the value for use input and checks it against the correct answer.
if guess2 == movieAnswerMedi[quote2]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerMedi[quote1])
#Hard Question
print("Hard: " + movieQuoteHard[quote3])
guess3 = input()
#Takes the value for use input and checks it against the correct answer.
if guess3 == movieAnswerHard[quote3]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerHard[quote3])
#Extream Question
print("Insane: " + movieQuoteExtr[quote4])
guess4 = input()
# Takes the value for use input and checks it against the correct answer.
if guess4 == movieAnswerExtr[quote4]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerExtr[quote4])
print("\nGreat job, you have " + str(points) + " points.")
input()
exit()
I want to be able to take in 'The Terminator' and just 'terminator'
I know how to solve your problem. The first thing you can do is add .lower() to the end of your input. This will put all of the letters in the user's input in lower case. Like this: guess1 = input().lower. Now it doesn't matter if the user types in upper or lower case. Also; you should do this:
guess1 = input(">>> ").lower() #Allows the user to input lower case letters.
if "terminator" in guess1: #This is probably what you are looking for.
#If the program detects the keyword 'terminator'
#in your guess, then the if statement will execute.
#Whatever happens when the user is correct.
else:
#Whatever happens when the user is incorrect.
I hope I helped you!

Declare a here-string containing variables outside of a loop

I would like to declare a here-string outside of a loop use that string in the loop where the variables get resolved.
My ideal scenario would look like below. This doesn't work as Powershell evaluates the string one time before entering the loop instead of each time inside the loop kind of obvious but bitten by it nevertheless.
$number = "Number $($_)"
1..2 | % { $number }
I know I can use one of these solutions
1..2 | % { "Number $($_)" }
$number = "Number {0}"
1..2 | % { $number -f $_ }
$number = "Number <replace>"
1..2 | % { $number -replace "<replace>", "$_" }
but they have drawbacks I'd like to avoid
Due to the size of the string, declaring it inside the loop obfuscates the logic of the loop making the code less readable.
The formatting solution is too easy to get wrong when many variables are involved.
In the replace solution it's easier to match what get's replaced by what variable but I would have to chain many replace commands.
Edit
Rereading my own question makes it obvious that the actual use case is missing from the question.
Note that ultimately I ended up choosing the formatting option
Following would declare the template with some variables that need replacing in a loop
$sqltemplate = #"
SELECT aud.dpt_mov_hex||aud.dpt_ref||aud.can_typ||TO_CHAR(aud.dte_aud-1,'YYYYMMDD')||'000001' transaction_id,
acc.dos_nbr contract_id, acc.pay_acc_nbr account_id,
CASE WHEN NULL IS NULL THEN unt.nam_unt ELSE unt.nam_unt||'<'||NULL ||'>' END product_id,
aud.dpt_ref, aud.dpt_mov_hex, aud.dpt_mov_dte uitwerkingsdatum,
CASE WHEN can_typ = 0 THEN 'VZ'||aud.dpt_mov_ven_typ ELSE 'VZ'||aud.dpt_mov_ven_typ||'-CR' END transactietype,
aud.dpt_mov_amt_eur bedrag_in_eur, aud.dte_cnv, aud.dpt_mov_fix_eur, aud.dpt_mov_con_inc, aud.dpt_mov_amt_sgn bedrag_teken,
aud.dpt_mov_amt_unt bedrag_in_units, aud.dpt_mov_amt_rte, aud.dpt_mov_amt_val_pre, aud.dpt_mov_amt_val_aft,
aud.dpt_mov_amt_ioc, aud.dte_exe verwerkingsdatum, aud.exe_mng, aud.cmt, aud.trn_nbr, aud.dte_aud datum_aanlevering, aud.can_typ
FROM lfe_dpt_mov_aud aud, vnv_isr_pay_acc acc, vnv_bel_unt unt
WHERE aud.dte_aud >= TO_DATE('$((Get-Date).ToString('dd.MM.yyyy'))', 'DD.MM.YYYY')
AND aud.dpt_ref = '{0}'
AND acc.pay_acc_nbr = '{1}'
AND unt.inv_unt = '{2}'
UNION
SELECT aud.dpt_mov_hex||aud.dpt_ref||aud.can_typ||TO_CHAR(aud.dte_aud-1,'YYYYMMDD')||'000001' transaction_id,
acc.dos_nbr contract_id, acc.pay_acc_nbr account_id,
CASE WHEN itr_rte IS NULL THEN unt.nam_unt ELSE unt.nam_unt||'<'||itr_rte ||'>' END product_id,
aud.dpt_ref, aud.dpt_mov_hex, aud.dpt_mov_dte uitwerkingsdatum,
CASE WHEN can_typ = 0 THEN 'VZ'||aud.dpt_mov_ven_typ ELSE 'VZ'||aud.dpt_mov_ven_typ||'-CR' END transactietype,
aud.dpt_mov_amt_eur bedrag_in_eur, aud.dte_cnv, aud.dpt_mov_fix_eur, aud.dpt_mov_con_inc, aud.dpt_mov_amt_sgn bedrag_teken,
aud.dpt_mov_amt_unt bedrag_in_units, aud.dpt_mov_amt_rte, aud.dpt_mov_amt_val_pre, aud.dpt_mov_amt_val_aft,
aud.dpt_mov_amt_ioc, aud.dte_exe verwerkingsdatum, aud.exe_mng, aud.cmt, aud.trn_nbr, aud.dte_aud datum_aanlevering, aud.can_typ
FROM lfe_dpt_mov_aud aud, vnv_dpt dpt, vnv_isr_pay_acc acc, vnv_bel_unt unt
WHERE aud.dpt_ref = dpt.dpt_ref
AND dpt.pay_acc = acc.pay_acc_nbr
AND dpt.inv_unt = unt.inv_unt
AND aud.dte_aud >= TO_DATE('$((Get-Date).ToString('dd.MM.yyyy'))', 'DD.MM.YYYY')
AND acc.pay_acc_nbr = '{1}'
AND unt.inv_unt = '{2}'
UNION
"#
and this template would get used in a statement such as this
$rolledbackMatchs is an array of custom object containing the three properties: dtp_ref, pay_acc_nbr and inv_unt.
$rolledbackMatches | ForEach-Object { $sqltemplate -f $_.dpt_ref, $_.pay_acc_nbr, $_.inv_unt }
Couple of approaches come to mind:
dot source here-string assignment from a separate file:
# loop.variables.ps1
$myVar = #"
Stuff going on with $_ in here
"#
and then in the loop itself:
1..2 | % { . .\loop.variables.ps1; <# do stuff with $myVar here #> }
Manually invoke string expansion:
$hereString = #'
Stuff (not yet) going on with $_ in here
'#
1..2 | % { $myVar = $ExecutionContext.InvokeCommand.ExpandString($hereString) }
Wrap it in a scriptblock
(as suggested by PetSerAl)
$stringBlock = {
#"
Stuff going on with $_ in here
"#
}
1..2 | % { $myVar = &$stringBlock}
I'm struggling to understand what you're trying to achieve here.
For a start you never define a here-string you just define $number as a string
A here-string would look like this
$number = #"
Number 4
"#
if all you're trying to do is push a number into a string try this
foreach ($number in (1..3)){
"Number $number"
}
which is close to your desired option and less ambiguous

Split an array based on value

This is my first question here, so sorry if I make any mistakes posting this.
I'm trying to split an array based on its values. Basically I want to create two arrays whose values are as close to the average as possible. I managed to do this with this code:
function Sum($v) {
[Linq.Enumerable]::Sum([int64[]]$v)
}
$arr = 0..9 | % {get-random -min 1 -max 10}
"ARRAY:" + $arr
"SUM: " + (sum $arr)
"AVG: " + (sum $arr)/2
# start of the code that matters
$wavg = (sum $arr)/2
foreach ($i in (0..($arr.Count-1))) {
$wavg -= $arr[$i]
if ($wavg -le 0) {
$i-=(-$wavg -gt $arr[$i]/2);break
}
}
"SPLIT INDEX: " + $i
"ARR1: " + $arr[0..$i] + " (" + $(sum $arr[0..$i]) + ")"
"ARR2: " + $arr[($i+1)..$arr.Count] + " (" + $(sum $arr[($i+1)..$arr.Count]) + ")"
The reason my foreach is structured this way is because in my actual code the values are in an index hash and are accessed as $index[$arr[$i]].
This means that the resulting two arrays could be of unequal size (it would be easy if I could just split the array in half). Sample output of my code to demonstrate this:
ARRAY: 5 3 6 3 2 3 6 3 1 3
SUM: 35
AVG: 17.5
SPLIT INDEX: 3
ARR1: 5 3 6 3 (17)
ARR2: 2 3 6 3 1 3 (18)
The code works as is, but I feel it could be done in a more elegant and speedier way. Because I need to execute this code a few thousand times in my script I want it to be as fast as possible.

Powershell script assign food to numbers and list them

The script should allocate and list the numbers of the particular foods.
So i want a Script that makes a "Plan" of the Food i'm gonna eat this week.
i have a counter that can "choose from 200 meals".
So what i need is that it is like this:
number* = Tacos
number* = Pizza
...continuing like this
I don't have a clue how to do this... i hope you can help me!
here is my code untill now.
# Food selector for the week!
#random Stuff mixed for every day.
function Random-Food{
Param(
[array]$InputList
)
return $InputList | Get-Random -Count 7
$InputList.Count;
}
$a = 1..200
Write-Output (Random-Food -InputList $a)
In a separate file, create an enumeration (for readability):
Enum Food
{
Tacos
Pizza
...
}
In your script, dot-source this file so you have it available: . 'C:\myenum.ps1'
Then in your function:
function Get-Food {
[Enum]::GetValues([Food]) | Get-Random -Count 7
}
This will return 7 random foods from your list. As an added bonus, you can assign a number to each food and get that reference as well. (Tacos = 5 and access it like [Food]::Tacos which can be treated as a string or integer)
To include the day:
function Get-Food {
$foodsOfWeek = [Enum]::GetValues([Food]) | Get-Random -Count 7
foreach ($day in [Enum]::GetValues([DayOfWeek])) {
([string]$day).Substring(0, 3) + ': ' + $foodsOfWeek[$day]
}
}
An explanation:
The function will grab all the values (Tacos, Pizza, etc.) from your custom [Food] enumeration and then randomly select 7 of those to put into an array that we store into $foodsOfWeek.
At that point, we need to loop through the days of the week (system built-in enumeration [DayOfWeek]). We type-cast to a string so we can call the .Substring() method to grab the first 3 characters and append a : for formatting.
Finally, we access the $foodOfWeek array using the [DayOfWeek] enumeration since days correlate to the numbers 0-6 (the size of our array).
(DayOfWeek.Sunday == 0) && (DayOfWeek.Sunday == "Sunday")) == true
To learn PowerShell, try this: Windows PowerShell 3.0 Step by Step - Pearsoncmg.com
Freebie follows. Written and tested on A Win 7 machine with PowerShell 4. I included a few foods. All you have to do is add items to the $foodList.
Sample output follows the code
cls
#define an array of strings and load it with food words
$foodList = #("Apples","Bananas", "Cherries","Grapes","Mangoes","Melons","Oranges","Peaches","Pears","Pineapples","Strawberries","Tomatoes")
#define an array of days
$dow = #("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
#loop 7 times, once per day and generate a random number between 0 and the number of food items - 1
for ($i = 0; $i -lt 7; $i++)
{
$foodItemIndex = Get-Random -Minimum 0 -Maximum ($foodList.Count - 1)
write-host ($dow[$i] + ": " + $foodList[$foodItemIndex])
}
Here's one way to do it:
$foodChoices = "Pizza","Taco","Dim Sum","Burger","Salad","Soup","Sandwich","Curry"
$foodChoices[(Get-Random -InputObject (0..($foodChoices.Count - 1)) -Count 7)] |
ForEach-Object {$daysOfWeek = [enum]::GetNames([DayOfWeek]); $day=0}{
[PsCustomObject]#{
Day=$daysOfWeek[$day++]
Food=$_
}
}
Output will look something like this:
Day Food
--- ----
Sunday Burger
Monday Sandwich
Tuesday Salad
Wednesday Taco
Thursday Soup
Friday Dim Sum
Saturday Curry
Just add more items to $foodChoices and you're good to go ...

Splitting String using Multiple Entries from a List

I have following list of splitters:
val splitd = list(" or ", " and ", " up to ")
and the following string:
val st = "You should eat 2 kg apples a week or 2 bananas everyday; up to a month you should eat 5g of ginger everyday"
I want following output:
val entry = List("You should eat 2 kg apples a week", "2 bananas everyday;", "a month you should eat 5g of ginger everyday")
If there is no entry in "splitd" matching the content in "st" then full string "st" should be returned. Thanks in advance for your help.
Dear #Shadowlands and #marstran, need your help again.
Check this out:
splitd.foldLeft(List(st)) {
case (acc, spl) => acc.flatMap(item => item.split(spl).toList)
}