Instantiating at random based on word - c++

I have a word = "CAT"
I have 26 alphabet prefabs A - Z - prefab array
I want to instantiate 6 prefabs from the prefab at random
so B,L,T,C,A,T - in any random order
but I need it to include the letters that makeup the word cat
My first thought was to use a dictionary/hashmap to map the word cat to the position in the array i.e C = [2] A = [0] T[]
but the hashmap/dictionary only takes a key value pair but I am providing it with more than one value the 3 letters needed
This is being programmed in unity so my prefabs are already in the letters array its just getting them to include my spelling.
public GameObject[] letters;
void Start() {
int x;
/* for loop execution */
for (x = 0; x < 5; x = x + 1)
{
CreateCubes();
}
}
public void CreateCubes()
{
GameObject obj = Instantiate(letters[Random.Range(0, 26)]);
obj.transform.position = new Vector3(
);

Assuming you have all prefabs in a GameObject[] array you could use this to auto-populate a dictionary
public GameObject[] prefabs = new GameObject[26];
private Dictionary<char, GameObject> CharToPrefab = new Dictionary<char, GameObject>(26);
private void Start()
{
for (var i = 0; i < 27; i++)
{
// add 0 to 26 to the start character A
// results in A-Z
CharToPrefab[(char)('A' + i)] = prefabs[i];
}
}
Than you can access a certain prefab by calling
CharToPrefab[character];
For generating the instances (simplest version without taking any doubles into account) you could do e.g.
public void RandomLetters(string word)
{
// 1. spawn the minimum required letters to build the word
foreach (var letter in word)
{
var obj = Instantiate(CharToPrefab[letter]);
// maybe use obj for something e.g. shuffel all instantiated objects positions
}
// 2. fill the rest with random letters
// assuming always same amount as word letters
var rand = new System.Random();
foreach (var letter in word)
{
// pics a number from 0 to 26
// and adds it to the char -> results in A-Z
var randomChar = (char)('A' + rand.Next(0, 27));
var obj = Instantiate(CharToPrefab[randomChar]);
// maybe use obj for something e.g. shuffel all instantiated objects positions
}
}

Related

Using DrJava, how do I shift the characters stored in a 2d array and store in a different location using a Caesar shift cipher

**After collecting a number between 1 and 4 from the user, I need to use a Caesar shift cipher to shift every letter in the array forward by the number the user provided. I decided to use if statements for every possible character that could be in the user's String input that would be stored as characters in my 2d array, but I am unsure as to how I write the code that will actually shift each letter.
**
import java.util.Scanner;
public class Csci1301_hw3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int value;
System.out.println("Enter your sentence: ");
String sentence=scan.nextLine();
int lengthofString=sentence.length();
char[][] myArray = new char[lengthofString][3];
for(int counter=0; counter <=sentence.length(); counter++)
myArray[counter][0]= sentence.charAt(counter);
System.out.println("Please enter an integer between 1 and 4 to encrypt your sentence: ");
value=scan.nextInt();
while(value < 1 || value > 4)
{
System.out.println("Please enter an integer between 1 and 4 to encrypt your sentence: ");
value=scan.nextInt();
}}
public static char caesarCipher(int counter, char[][] myArray, int value)
{
if(myArray[counter][0]=='A')
myArray[counter][1]='A'+value;
if(myArray[counter][0]=='B')
myArray[counter][1]='B'+value;
if(myArray[counter][0]=='C')
myArray[counter][1]='C'+value;
if(myArray[counter][0]=='D')
myArray[counter][1]='D'+value;
if(myArray[counter][0]=='E')
myArray[counter][1]='E'+value;
if(myArray[counter][0]=='F')
myArray[counter][1]='F'+value;
if(myArray[counter][0]=='G')
myArray[counter][1]='G'+value;
if(myArray[counter][0]=='H')
myArray[counter][1]='H'+value;
if(myArray[counter][0]=='I')
myArray[counter][1]='I'+value;
if(myArray[counter][0]=='J')
myArray[counter][1]='J'+value;
if(myArray[counter][0]=='K')
myArray[counter][1]='K'+value;
if(myArray[counter][0]=='L')
myArray[counter][1]='L'+value;
if(myArray[counter][0]=='M')
myArray[counter][1]='M'+value;
if(myArray[counter][0]=='N')
myArray[counter][1]='N'+value;
if(myArray[counter][0]=='O')
myArray[counter][1]='O'+value;
if(myArray[counter][0]=='P')
myArray[counter][1]='P'+value;
if(myArray[counter][0]=='Q')
myArray[counter][1]='Q'+value;
if(myArray[counter][0]=='R')
myArray[counter][1]='R'+value;
if(myArray[counter][0]=='S')
myArray[counter][1]='S'+value;
if(myArray[counter][0]=='T')
myArray[counter][1]='T'+value;
if(myArray[counter][0]=='U')
myArray[counter][1]='U'+value;
if(myArray[counter][0]=='V')
myArray[counter][1]='V'+value;
if(myArray[counter][0]=='W')
myArray[counter][1]='W'+value;
if(myArray[counter][0]=='X')
myArray[counter][1]='X'+value;
if(myArray[counter][0]=='Y')
myArray[counter][1]='Y'+value;
if(myArray[counter][0]=='Z')
myArray[counter][1]='Z'+value;
if(myArray[counter][0]=='a')
myArray[counter][1]='a'+value;
if(myArray[counter][0]=='b')
myArray[counter][1]='b'+value;
if(myArray[counter][0]=='c')
myArray[counter][1]='c'+value;
if(myArray[counter][0]=='d')
myArray[counter][1]='d'+value;
if(myArray[counter][0]=='e')
myArray[counter][1]='e'+value;
if(myArray[counter][0]=='f')
myArray[counter][1]='f'+value;
if(myArray[counter][0]=='g')
myArray[counter][1]='g'+value;
if(myArray[counter][0]=='h')
myArray[counter][1]='h'+value;
if(myArray[counter][0]=='i')
myArray[counter][1]='i'+value;
if(myArray[counter][0]=='j')
myArray[counter][1]='j'+value;
if(myArray[counter][0]=='k')
myArray[counter][1]='k'+value;
if(myArray[counter][0]=='l')
myArray[counter][1]='l'+value;
if(myArray[counter][0]=='m')
myArray[counter][1]='m'+value;
if(myArray[counter][0]=='n')
myArray[counter][1]='n'+value;
if(myArray[counter][0]=='o')
myArray[counter][1]='o'+value;
if(myArray[counter][0]=='p')
myArray[counter][1]='p'+value;
if(myArray[counter][0]=='q')
myArray[counter][1]='q'+value;
if(myArray[counter][0]=='r')
myArray[counter][1]='r'+value;
if(myArray[counter][0]=='s')
myArray[counter][1]='s'+value;
if(myArray[counter][0]=='t')
myArray[counter][1]='t'+value;
if(myArray[counter][0]=='u')
myArray[counter][1]='u'+value;
if(myArray[counter][0]=='v')
myArray[counter][1]='v'+value;
if(myArray[counter][0]=='w')
myArray[counter][1]='w'+value;
if(myArray[counter][0]=='x')
myArray[counter][1]='x'+value;
if(myArray[counter][0]=='y')
myArray[counter][1]='y'+value;
if(myArray[counter][0]=='z')
myArray[counter][1]='z'+value;
if(myArray[counter][0]=='0')
myArray[counter][1]='0'+value;
if(myArray[counter][0]=='1')
myArray[counter][1]='1'+value;
if(myArray[counter][0]=='2')
myArray[counter][1]='2'+value;
if(myArray[counter][0]=='3')
myArray[counter][1]='3'+value;
if(myArray[counter][0]=='4')
myArray[counter][1]='4'+value;
if(myArray[counter][0]=='5')
myArray[counter][1]='5'+value;
if(myArray[counter][0]=='6')
myArray[counter][1]='6'+value;
if(myArray[counter][0]=='7')
myArray[counter][1]='7'+value;
if(myArray[counter][0]=='8')
myArray[counter][1]='8'+value;
if(myArray[counter][0]=='9')
myArray[counter][1]='9'+value;
if(myArray[counter][0]==',')
myArray[counter][1]=','+value;
if(myArray[counter][0]=='.')
myArray[counter][1]='.'+value;
if(myArray[counter][0]=='!')
myArray[counter][1]='!'+value;
if(myArray[counter][0]=='?')
myArray[counter][1]='?'+value;
}}
Does this help? It uses a different approach, but it should be adaptable. It uses the ascii value of the char to shift by the desired amount and writes to a new array.
public class Main {
public static void main(String[] args) {
char[] inputString = "This is a test message".toLowerCase().toCharArray();
char[] output = new char[inputString.length];
int index = 0;
int amountToShift = 10;
for (char letter : inputString) {
// don't cipher spaces. You could add other letters if needed.
if (letter == ' ') {
output[index] = ' ';
} else {
int ascii = letter;
ascii = ascii + amountToShift;
// if you need to shift the letter past the end of the alphabet, loop round
if (ascii > 122) {
int tempAscii = (ascii - 97)%26;
ascii = tempAscii + 97;
}
output[index] = (char) ascii;
}
index++;
}
String result = String.valueOf(output);
System.out.println(result);
}}

Split string by "],["

I know one back slash / can be used to escape some special characters like (, . and double back slash // can be used to escape special characters in a string directly.
I want to split:
"[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]"
by ],[ between each sub array.
What should I do if I want to get all the sub arrays by splitting them to be "[[0,0,1,0,0", "0,0,0,0,0","0,0,0,1,0","1,1,0,1,1", "0,0,0,0,0]]" first.
If you have better idea on how to convert them directly into sub arrays including numbers only like "0,0,1,0,0", "0,0,0,0,0","0,0,0,1,0","1,1,0,1,1", "0,0,0,0,0" that will be even better.
Since both [ and ] at special characters in regex you need to escape them.
you can try with below:
str.split("\\],\\[");
Test code:
String str="[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]";
String[] strs = str.split("\\],\\[");
for(String s:strs){
System.out.println(s);
}
Output result:
[[0,0,1,0,0
0,0,0,0,0
0,0,0,1,0
1,1,0,1,1
0,0,0,0,0]]
If you want to remove the duplicate [[ and ]],just add below codes before split:
str = str.substring(2);
str = str.substring(0, str.length()-2);
Updated answer,if you want to eliminate all the brackets in between and at both ends by regex,you write regex like \[?\[((\d,)+\d) then fetch the first group of each match record data, below is the code:
String str = "[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]";
String regex = "\\[?\\[((\\d,)+\\d)";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
The output is
0,0,1,0,0
0,0,0,0,0
0,0,0,1,0
1,1,0,1,1
0,0,0,0,0
Your input is valid JSON, so I suggest using a JSON parser.
The code would look like this:
import javax.json.*;
JsonReader jsonReader = Json.createReader(new StringReader("[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]"));
JsonArray array = jsonReader.readArray();
jsonReader.close();
System.out.println("Array #2: " + array.getJsonArray(1)); // should give [0,0,0,0,0]
System.out.println("Array #3, 4th value: " + array.getJsonArray(2).getInt(3)); // should give 1
If you want the String to convert into a 2d-Array, you can use below functions that takes the String and returns the 2d-Array of ints:
private static int[][] getMatrixFromString(String arrayStrinng) {
String arrayString = arrayStrinng.substring(1, arrayStrinng.length() - 1);
String[] splitMajor = arrayString.split("],");
int rowCount = splitMajor.length, colCount = 0;
int[][] matrix = new int[rowCount][];
for (int row = 0; row < splitMajor.length; row++) {
String[] splitMinor = splitMajor[row].split(",");
if (colCount == 0) {
colCount = splitMinor.length;
matrix = new int[rowCount][colCount];
}
for (int i = 0; i < colCount; i++) {
if (splitMinor[i].startsWith("["))
splitMinor[i] = splitMinor[i].substring(1);
if (splitMinor[i].endsWith("]"))
splitMinor[i] = splitMinor[i].substring(0, splitMinor[i].length() - 1);
matrix[row][i] = Integer.parseInt(splitMinor[i]);
}
}
return matrix;
}

Getting rid of unused pointers in a pointers array : C++ Builder

I have a Part class. And I created an array of pointers of type Part.
const int SZ = 50;
Part *myPart[SZ];
I then made a new instance of type Part inside the Part array at a random position between 0 and 50. A new instance is created every time a Button is pressed.
int x = (rand() * SZ)/RAND_MAX + 0;
myPart[x] = new Part(x);
I then put the result inside a List Box. This is executed when a second Button is pressed.
String str = "";
ListBox1->Clear();
for(int x = 0; x < SZ; x++)
{
if(myPart[x])
{
str = IntToStr(myPart[x]->getId()) + ", ";
str += myPart[x]->getStatus() + ", " + myPart[x]->getShelf() + ", ";
str += IntToStr(myPart[x]->getQuantity());
ListBox1->Items->Add(str);
}
else
{
ListBox1->Items->Add("- - - - - - - - -");
}
}
The result will appear at different places (index positions) in the List Box.
Say I pressed the randomizing button 5 times, and thus have 5 results at different random positions in the list box, how do I "push" the 5 results to the top of the stack and get rid of the 45 remaining, unused pointers?

C# Loop through a collection and assign each object to a variable

I am sure this is quite simple but I cannot seem to get this right.
I have a built up a ICollection of Users. This collection could have 1 or many.
I now want to loop through this collection and assign a variable to each user that I can then use to fill in a spread sheet.
At present I have this code :
string username = null;
foreach (var user in dailyReport)
{
username = user.UserName;
}
Cell cell= worksheet.Cells["B5"];
cell.PutValue(username);
Now obviously this just puts the last user of the collection into cell B5!
How do I collect all user.UserNames so I can place them in B5, B6, B7 and so on????
To get a list of the user names:
List<string> userNames = dailyReport.Select( x=> x.UserName).ToList();
Alternatively you can just do the assignment in the loop directly:
int index = 5;
foreach (var user in dailyReport)
{
Cell cell= worksheet.Cells["B"+ index.ToString()];
cell.PutValue(user.UserName);
index++;
}
You need to put the value inside the foreach loop. The specific thing you are asking for--getting a different variable for every value in the collection--is not possible, and isn't what you want anyway.
string column = "B"; // or whatever your column is
int row = 1; // or whatever your starting value is
foreach (var user in dailyReport)
{
string username = user.UserName;
string cellAddress = String.Format("{0}{1}", column, row);
Cell cell = worksheet.Cells[cellAddress];
cell.PutValue(username);
row++; // make sure to increment the row, or every username goes in the same cell
}
int i = 5;
foreach (var user in dailyReport)
{
worksheet.Cells["B" + (i++).ToString()].PutValue(user.UserName);
}

Switch every pair of words in a string (“ab cd ef gh ijk” becomes “cd ab gh ef ijk”) in c/c++

Switch every pair of words in a string (“ab cd ef gh ijk” becomes “cd ab gh ef ijk”) in c++ without any library function.
int main(){
char s[]="h1 h2 h3 h4";//sample input
switch_pair(s);
std::cout<<s;
return 0;
}
char * switch_pair(char *s){
char * pos = s;
char * ptr = s;
int sp = 0;//counts number of space
while(*pos){
if(*pos==' ' && ++sp==2){ //if we hit a space and it is second space then we've a pair
revStr_iter(ptr,pos-1);//reverse the pair so 'h1 h2' -> '2h 1h'
sp=0;//set no. of space to zero to hunt new pairs
ptr=pos+1;//reset ptr to nxt word after the pair i.e. h3'
}
pos++;
}
if(sp==1) //tackle the case where input is 'h1 h2' as only 1 space is there
revStr_iter(ptr,pos-1);
revWord(s); //this will reverse each individual word....i hoped so :'(
return s;
}
char* revStr_iter(char* l,char * r){//trivial reverse string algo
char * p = l;
while(l<r){
char c = *l;
*l = *r;
*r = c;
l++;
r--;
}
return p;
}
char* revWord(char* s){//this is the villain....need to fix it...Grrrr
char* pos = s;
char* w1 = s;
while(*pos){
if(*pos==' '){//reverses each word before space
revStr_iter(w1,pos-1);
w1=pos+1;
}
pos++;
}
return s;
}
Input - h1 h2 h3 h4
expected - h2 h1 h4 h3
actual - h2 h1 h3 4h
can any noble geek soul help plz :(((
IMO, what you're working on so far looks/seems a lot more like C code than C++ code. I think I'd start from something like:
break the input into word objects
swap pairs of word objects
re-construct string of rearranged words
For that, I'd probably define a really minimal string class. Just about all it needs (for now) is the ability to create a string given a pointer to char and a length (or something on that order), and the ability to assign (or swap) strings.
I'd also define a tokenizer. I'm not sure if it should really be a function or a class, but for the moment, let's jut say "function". All it does is look at a string and find the beginning and end of a word, yielding something like a pointer to the beginning, and the length of the word.
Finally, you need/want an array to hold the words. For a first-step, you could just use a normal array, then later when/if you want to have the array automatically expand as needed, you can write a small class to handle it.
int Groups = 1; // Count 1 for the first group of letters
for ( int Loop1 = 0; Loop1 < strlen(String); Loop1++)
if (String[Loop1] == ' ') // Any extra groups are delimited by space
Groups += 1;
int* GroupPositions = new int[Groups]; // Stores the positions
for ( int Loop2 = 0, Position = 0; Loop2 < strlen(String); Loop2++)
{
if (String[Loop2] != ' ' && (String[Loop2-1] == ' ' || Loop2-1 < 0))
{
GroupPositions[Position] = Loop2; // Store position of the first letter
Position += 1; // Increment the next position of interest
}
}
If you can't use strlen, write a function that counts any letters until it encounters a null terminator '\0'.