public int search(E target)
{
int p=0;
Node<E> current = top;
while(current!= null) {
if(current.getItem().equals(target)) {
p++;
current=null;
}
else {
current= current.getNext();
p++;
}
}
return p;
}
output
Searching for the 10 of hearts It was found at position 1
Searching for the 2 of hearts It was found at position 3
Searching for the 5 of diamonds It was found at position 6
Searching for the 1 of diamonds It was found at position 6
Searching for the 1 of diamonds It was found at position 0
my output works fine for first 3 cards but comes to an error when searching for cards not in the linked list i am trying to get it to return -1 if the card does not exist in the pile but the first 1 of diamonds should not be 6 it should be -1 the last two lines are checking two separate linkedlists for the value both should return -1 for not existing in pile . the second list does not anything inside at all.
Related
I am really new to Constraint Programming and I am trying to solve a problem where from a two dimensional array, consisting of numbers, I need to take the least amount of sub arrays (2D) as possible, covering as much of the original 2D array as possible, obeying the following rules:
Every sub array must be a rectangle part of the original
The sum of numbers in each sub array must not exceed a specific number
Every sub array must have at least 2 numbers in it
For example for the following matrix:
3 5 1 4
5 1 2 8
0 8 1 3
8 3 2 1
For a maximum sum of 10, a solution would be:
3 -not picked
{ 5 1 4 }
{ 5 1 }
{ 2 8 }
{ 0 8 }
{ 1 3
2 1 }
8 -not picked
Right now I am using the diffn() equivalent of or-tools (MakeNonOverlappingBoxesConstraint()) to create the rectangles that are gonna cover the original array.
My problem is how to get the rectangles created by diffn() and split the original matrix based on the position and size of each one, so I can apply the Sum constraint.
If there is another way of achieving the same constraints without using the diffn() then I would try it out, but I can't think any other way.
Thank you!
The way to get a value from an array based on an IntVar, inside the solver, is by using the MakeElement() function and in this case the 2d version of it.
That way you can get a specific value from the matrix but not a range based on two IntVars (for example x - dx of rectangles). To accomplish the range part you can use a loop and a ConditionalExpression() to figure out if the specified value is in range.
For example in a 1d array, in order to get elements from data, positions x to x + dx would be as follows
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IntVar x = solver.MakeIntVar(0, data.Length - 1);
IntVar dx = solver.MakeIntVar(1, data.Length);
solver.Add(x + dx <= data.Length);
IntVarVector range = new IntVarVector();
for (int i = 0; i < dx.Max(); i++)
{
range.Add(solver.MakeConditionalExpression((x + i < x + dx).Var() , solver.MakeElement(data, (x + i).Var()), 0).Var());
}
solver.Add(range.ToArray().Sum() <= 10);
In Case of the 2d array (as in the question) then you just iterate through both dimensions. The only difference is that the 2d version of MakeElement() accepts an IndexEvaluator2 item (LongLongToLong in C#) so you have to make your own class that inherits LongLongToLong and override the Run() function.
class DataValues: LongLongToLong
{
private int[,] _data;
private int _rows;
private int _cols;
public DataValues(int[,] data, int rows, int cols)
{
_rows = rows;
_cols = cols;
_data = data;
}
public override long Run(long arg0, long arg1)
{
if (arg0 >= _rows || arg1 >= _cols)
return 0;
return _data[arg0, arg1];
}
}
The only problem with this class is that it can ask for a value off the array, so we must handle it ourselves with if (arg0 >= _rows || arg1 >= _cols).
P.S. I dont know if this is the best method of accomplishing it, but it was the best I could think of, since I couldn't find anything similar online.
The question is:
Given a list of String, find a specific string in the list and return
its index in the ordered list of String sorted by mergesort. There are
two cases:
The string is in the list, return the index it should be in, in the ordered list.
The String is NOT in the list, return the index it is supposed to be in, in the ordered list.
Here is my my code, I assume that the given list is already ordered.
For 2nd case, how do I use mergesort to find the supposed index? I would appreciate some clues.
I was thinking to get a copy of the original list first, sort it, and get the index of the string in the copy list. Here I got stuck... do I use mergesort again to get the index of non-existing string in the copy list?
public static int BSearch(List<String> s, String a) {
int size = s.size();
int half = size / 2;
int index = 0;
// base case?
if (half == 0) {
if (s.get(half) == a) {
return index;
} else {
return index + 1;
}
}
// with String a
if (s.contains(a)) {
// on the right
if (s.indexOf(s) > half) {
List<String> rightHalf = s.subList(half + 1, size);
index += half;
return BSearch(rightHalf, a);
} else {
// one the left
List<String> leftHalf = s.subList(0, half - 1);
index += half;
return BSearch(leftHalf, a);
}
}
return index;
}
When I run this code, the index is not updated. I wonder what is wrong here. I only get 0 or 1 when I test the code even with the string in the list.
Your code only returns 0 or 1 because you don't keep track of your index for each recursive call, instead of resetting to 0 each time. Also, to find where the non-existent element should be, consider the list {0,2,3,5,6}. If we were to run a binary search to look for 4 here, it should stop at the index where element 5 is. Hope that's enough to get you started!
I want to split a large string file into large number of very small sub string and then store it so that i can use all sub string further in my program. what will be best way to do so.my program is in C# so Please provide solution only in C#.
Here is input File : https://he-s3.s3.amazonaws.com/media/hackathon/code-monk-hashing/problems/monk-in-the-land-of-pokemons/4326354c-2-input-4326316.txt?Signature=mtbhaQ2%2F6VRAH8A9OfZTSAX6oTQ%3D&Expires=1457955770&AWSAccessKeyId=AKIAJLE6MUHDYS3HN6YQ
all i want to get all number separated by white space in a collection.
is it possible that i can read all number separated by white space without saving them in collection?
Question:
Monk has to visit a land where strange creatures, known as Pokemons, roam around in the wild. Each Pokemon in the land will attack any visitor. They can only be pacified by feeding them their favorite food.
The Pokemon of type X eats one food item of type X.
Monk knows that he will encounter N ponds on the way. At each pond, he will find a food item and then encounter a Pokemon. The i'th pond has the food item of type Ai and the Pokemon of type Bi.
The monk can feed the item at the i'th pond to the Pokemon at the pond if the type matches. Monk may have to carry some food items with him before leaving so as to feed all the Pokemons. Help him find the number of items he must carry, to be to able to pass through the land safely.
Input:
The first line contains T, denoting the number of test cases. Then, T test cases follow.
The first line of each test case contains an integer N. Then, N lines follow.
Each line consists of 2 space-separated integers Ai and Bi.
Output: For each test case, print the answer in a new line.
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 105
1 ≤ Ai, Bi ≤ 106
Code:
using System;
using System.Numerics;
using System.Collections.Generic;
class MyClass
{
static void Main(string[] args)
{
int TestCaseNo = Int32.Parse(System.Console.ReadLine().Trim());
int TestCase;
for (int j = 0; j < TestCaseNo; j++)
{
LinkedList<int> numbers = new LinkedList<int>();
numbers.Clear();
int count = 0;
TestCase = Int32.Parse(System.Console.ReadLine().Trim());
for (int i = 0; i < TestCase; i++)
{
string line = System.Console.ReadLine().Trim();
string[] temp = line.Split(' ');
if (Int32.Parse(temp[0]) == Int32.Parse(temp[1]))
{ }
else
{
if (numbers.Contains(Int32.Parse(temp[1])))
{
numbers.Remove(Int32.Parse(temp[1]));
numbers.AddFirst(Int32.Parse(temp[0]));
}
else
{
numbers.AddFirst(Int32.Parse(temp[0]));
count++;
}
}
}
System.Console.WriteLine(count);
}
}
}
I found this interview question floating around, and after having given much thought to it, I couldn't really develop a sound algorithm for it.
Given a string of numbers in sequential order, find the missing number.The range of numbers is not given.
Sample Input:"9899100101103104105"
Answer:102
This is a simple problem.
Guess the number of digits for the first number
Read numbers from the string one by one. If the previous number you have read is x, the next number must be either x + 1 or x + 2. If it is x + 2, remember x + 1 as the missed number, continue until the end of the string anyway to verify that the initial guess was correct. If you read something else than x + 1 or x + 2, the initial guess was wrong and you need to restart with (next) guess.
With your example:
9899100101103104105
First guess length 1
read 9
the next number should be either 10 or 11. Read the next two digits, you get 89.
That is incorrect, so the initial guess was wrong.
Second guess length 2
read 98
the next number should be either 99 or 100. Read the next two digits for 99
the next number should be either 100 or 101. Read the next three digits for 100
... 101
... 103 (remember 102 as the missed number)
... 104
... 105
end of input
Guess of length 2 was verified as correct guess and 102 reported as missing number.
The only dififcult part, of course, is figuring out how many digits the numbers have. I see two approaches.
Try a certain number of digits for the first number, decide what the following number should therefore be (there'll be two options, depending on whether the missing number is the second one), and see if that matches the following string of digits. If so, continue on. If the string doesn't fit the pattern, try again with a different number of digits.
Look at the starting and ending portions of the string, and reason the number of digits based on that and the length of the string. This one's a little more handwavey.
digits=1
parse the string like the first number conatins digits digits only.
parse the next number and check if it is sequential correct related to the last parsed one
if it decreases, digit+=1, goto 1.
if it is 2 higher than the last parsed, you might found the gap, parse the rest, if parsing the restis not an increasing sequence, digit+=1, goto 2, otherwise you have found the gap.
if it is 1 higher than the last parsed number, goto 3.
digit+=1, goto 2. (I am not sure if this case can ever happen)
Example:
given: "131416".
1. digits=1
2. parse '1'
3. parse '3'
4. it does not decrease
5. possibly found the gap: parse the rest '1416' fails, because '1' != '4'
=> digit+=1 (digit=2) goto 2
2. parse '13'
3. parse '14'
4. it does not decrease
5. it is no 2 higher than the last parsed one (13)
6. it is 1 higher (14 = 13+1) => goto 3
3. parse '16'
4. it does not decrease
5. possibly found the gap: parse the rest '' passed because nothing more to parse,
=> found the gab: '15' is the missing number
Here is a working C# solution you can check in LINQPad:
void Main()
{
FindMissingNumberInString("9899100101103104105").Dump("Should be 102");
FindMissingNumberInString("78910121314").Dump("Should be 11");
FindMissingNumberInString("99899910011002").Dump("Should be 1000");
// will throw InvalidOperationException, we're missing both 1000 and 1002
FindMissingNumberInString("99899910011003");
}
public static int FindMissingNumberInString(string s)
{
for (int digits = 1; digits < 4; digits++)
{
int[] numbers = GetNumbersFromString(s, digits);
int result;
if (FindMissingNumber(numbers, out result))
return result;
}
throw new InvalidOperationException("Unable to determine the missing number fro '" + s + "'");
}
public static int[] GetNumbersFromString(string s, int digits)
{
var result = new List<int>();
int index = digits;
int number = int.Parse(s.Substring(0, digits));
result.Add(number);
while (index < s.Length)
{
string part;
number++;
digits = number.ToString().Length;
if (s.Length - index < digits)
part = s.Substring(index);
else
part = s.Substring(index, digits);
result.Add(int.Parse(part));
index += digits;
}
return result.ToArray();
}
public static bool FindMissingNumber(int[] numbers, out int missingNumber)
{
missingNumber = 0;
int? found = null;
for (int index = 1; index < numbers.Length; index++)
{
switch (numbers[index] - numbers[index - 1])
{
case 1:
// sequence continuing OK
break;
case 2:
// gap we expect to occur once
if (found == null)
found = numbers[index] - 1;
else
{
// occured twice
return false;
}
break;
default:
// not the right sequence
return false;
}
}
if (found.HasValue)
{
missingNumber = found.Value;
return true;
}
return false;
}
This can likely be vastly simplified but during exploratory coding I like to write out clear and easy to understand code rather than trying to write it in as few lines of code or as fast as possible.
I'm Creating a game similar to Gift Quest, Where I have to swap elements, Check for Vertical and Horizontal repeated elements then erase repeated ones (if 3 elements are same in a row or column, remove those and fill with new ones)
int [][] Board = new int[5][5];
I have an integer array as my board i have defined each gift with a specific integer value for example chocolates = 1, candy = 2 etc
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
Board[i][j] = rand.nextInt(5);
}
}
I finished the swap part also, Now I want to check the board if there are same element more than 3 times in a row and column.if it is then make that place in array blank. So i can fill it.
Can someone help me with the checking part ?
int counter = 0;
int currentTile = 0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(Board[i,j] == currentTile)
Counter++;
if(Counter == 3)
DoStuff(); //Yay 3 in a row!
currentTile = Board[i,j];
}
counter = 0;
}
And do the same thing, but swap the loops for the x axis