Unlikely argument type int for get(Object) on a Map<Character,Integer>Java(1200) - hashmap

longest= Math.max(longest,map.get(i)); [Error is being shown]
I understand Math.max and Longest is int AND map.get is Integer. I tried intValue() but its not working;
import java.util.HashMap;
public class longestSubstring {
public static void main(String[] args){
String str = "abcabcbb";
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
}
}
int longest = 0;
for(int i: map.keySet()){
longest= Math.max(longest,map.get(i)); // error here
}
System.out.println(longest);
}
}
Please help

import java.util.HashMap;
public class longestSubstring {
public static void main(String[] args){
String str = "abcabcbb";
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
}
}
int longest = 0;
for(Character c: map.keySet()){
longest= Math.max(longest,map.get(c));
}
System.out.println(longest);
}
}

Related

Error when running Apache Spark

I configure apache spark --one master node and two worker node
I running this jar file and dataset following command:
./bin/spark-submit --class dmlab.main.MainDriver --master local[2] PAMAE-Spark.jar USCensus1990.csv 10 4000 5 4 1
This is successfully in job 3. but, error in job 4 is starting.
Please kindly help me.
package dmlab.main;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.spark.SparkContext;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.rdd.RDD;
import org.apache.spark.storage.StorageLevel;
import dmlab.main.Algorithms;
import dmlab.main.FloatPoint;
import dmlab.main.PAMAE;
import scala.Tuple2;
import scala.Tuple2;
public final class PAMAE {
public static String eleDivider = ",";
public static JavaRDD<FloatPoint> readFile(JavaSparkContext sc, String
inputPath, int numOfCores)
{
JavaRDD<String> lines = sc.textFile(inputPath,numOfCores);
JavaRDD<FloatPoint> dataSet = lines.map(new
PAMAE.ParsePoint()).persist(StorageLevel.MEMORY_AND_DISK_SER());
return dataSet;
}
public static List<FloatPoint> PHASE_I(JavaSparkContext sc,
JavaRDD<FloatPoint> dataSet, int numOfClusters, int numOfSampledObjects, int
numOfSamples, int numOfCores)
{
List<FloatPoint> samples = dataSet.takeSample(true,
numOfSampledObjects*numOfClusters*10);
JavaRDD<FloatPoint> sampleSet = sc.parallelize(samples);
List<Tuple2<Integer, List<FloatPoint>>> candidateSet =
sampleSet.mapToPair(new PAMAE.Sampling(numOfClusters))
.groupByKey().mapValues(new PAMAE.PAM(numOfSampledObjects, numOfClusters))
.collect();
JavaRDD<Tuple2<Integer, List<FloatPoint>>> candidateSetRDD =
sc.parallelize(candidateSet).persist(StorageLevel.MEMORY_AND_DISK_SER());
List<Tuple2<Integer, Double>> costList = cluteringError(sc, dataSet,
candidateSetRDD);
List<Tuple2<Integer, List<FloatPoint>>> candidateList =
candidateSetRDD.collect();
int finalKey = -1;
double phaseIError = Double.MAX_VALUE;
for(int i=0; i<costList.size(); i++)
{
if(phaseIError > costList.get(i)._2())
{
phaseIError = costList.get(i)._2();
finalKey = costList.get(i)._1();
}
}
List<FloatPoint> bestSeed = null;
for(int i=0; i<candidateList.size(); i++)
{
if(candidateList.get(i)._1() == finalKey)
bestSeed = candidateList.get(i)._2();
}
System.out.println("PHASE I CLUSTERING ERROR : " + phaseIError+"\n");
candidateSetRDD.unpersist();
return bestSeed;
}
public static List<FloatPoint> PHASE_II(JavaSparkContext sc,
JavaRDD<FloatPoint> dataSet, List<FloatPoint> bestSeed, int numOfClusters,
int numOfSampledObjects, int numOfSamples, int numOfCores)
{
JavaRDD<FloatPoint> bestSeedRDD = sc.parallelize(bestSeed);
bestSeedRDD.persist(StorageLevel.MEMORY_AND_DISK_SER());
List<Tuple2<Integer, List<FloatPoint>>> temp = dataSet.mapToPair(new
PAMAE.AssignPoint(numOfCores))
.groupByKey().mapValues(new PAMAE.ModifiedWeiszfeld(bestSeedRDD)).collect();
ArrayList<FloatPoint> finalMedoids = new ArrayList<FloatPoint>();
for(int i=0; i<numOfClusters; i++)
{
int index = -1;
double minCost = Double.MAX_VALUE;
for(int j=0; j<numOfCores; j++)
{
if(minCost > temp.get(j)._2().get(i).getCost())
{ index = j;
minCost = temp.get(j)._2().get(i).getCost();}
}
finalMedoids.add(temp.get(index)._2().get(i));
temp.get(index)._2().get(i).toString());
}
bestSeedRDD.unpersist();
return finalMedoids;
}
public static List<Tuple2<Integer, Double>> cluteringError(JavaSparkContext
sc, JavaRDD<FloatPoint> dataSet, JavaRDD<Tuple2<Integer, List<FloatPoint>>>
medoids)
{
List<Tuple2<Integer, Double>> Error = dataSet.flatMapToPair(new
PAMAE.CostCaculator(medoids)).
reduceByKey(new
Function2<Double, Double, Double>() {
call(Double x, Double y) throws Exception {
return x+y;
}
}).collect();
return Error;
}
public static double FinalError(JavaSparkContext sc, JavaRDD<FloatPoint>
dataSet, List<FloatPoint> finalMedoids)
{
Tuple2<Integer,List<FloatPoint>> medoids = new Tuple2<Integer,
List<FloatPoint>>(1,finalMedoids);
List<Tuple2<Integer,List<FloatPoint>>> temp = new
ArrayList<Tuple2<Integer,List<FloatPoint>>>();
temp.add(medoids);
JavaRDD<Tuple2<Integer, List<FloatPoint>>> finalSetRDD =
sc.parallelize(temp).persist(StorageLevel.MEMORY_AND_DISK_SER());
List<Tuple2<Integer, Double>> finalError = cluteringError(sc, dataSet,
finalSetRDD);
return finalError.get(0)._2;
}
public static class ParsePoint implements Function<String, FloatPoint> {
#Override
public FloatPoint call(String line) {
String[] toks = line.toString().split(eleDivider);
FloatPoint pt = new FloatPoint(toks.length,-1);
for(int j=0; j<toks.length; j++)
pt.getValues()[j] = (Float.parseFloat(toks[j]));
return pt;
}
}
public static class Sampling implements PairFunction<FloatPoint, Integer,
FloatPoint> {
private int parallel = 0;
public Sampling(int parallel) {
// TODO Auto-generated constructor stub
this.parallel = parallel;
}
#Override
public Tuple2<Integer, FloatPoint> call(FloatPoint value) throws
Exception {
int key = (int)(Math.random()*parallel);
value.setKey(key);
return new Tuple2(key,value);
}
}
public static class PAM implements Function<Iterable<FloatPoint>,
List<FloatPoint>>{
private int sampleNumber = 0;
private int K = 0;
public PAM( int sampleNumber, int K) {
// TODO Auto-generated constructor stub
this.sampleNumber = sampleNumber;
this.K = K;
}
#Override
public List<FloatPoint> call(Iterable<FloatPoint> values) throws
Exception {
List<FloatPoint> sampledDataSet = new ArrayList<FloatPoint>();
for(FloatPoint pt : values)
sampledDataSet.add(pt);
HashSet<Integer> sampleIndex = new HashSet<Integer>();
int dataSize = sampledDataSet.size();
while(sampleIndex.size() != sampleNumber)
sampleIndex.add((int)(Math.random()*dataSize));
List<FloatPoint> samplePoints = new ArrayList<FloatPoint>();
for(Integer sample : sampleIndex)
samplePoints.add(sampledDataSet.get(sample));
sampledDataSet.clear();
float[][] preCalcResult = Algorithms.PreCalculate(samplePoints);
List<FloatPoint> sampleInit =
Algorithms.chooseInitialMedoids(samplePoints, K, preCalcResult, 0.5f);
Algorithms.PAM(samplePoints, sampleInit, preCalcResult);
return sampleInit;
}
}
public static class CostCaculator implements PairFlatMapFunction<FloatPoint,
Integer, Double>{
List<Tuple2<Integer, List<FloatPoint>>> Candidates;
public CostCaculator(JavaRDD<Tuple2<Integer, List<FloatPoint>>>
candidateSetRDD) {
Candidates = candidateSetRDD.collect();
}
#Override
public Iterable<Tuple2<Integer, Double>> call(FloatPoint pt)
throws Exception {
List<Tuple2<Integer, Double>> output = new ArrayList<Tuple2<Integer,
Double>>();
for(int i=0; i<Candidates.size(); i++)
{
int key = Candidates.get(i)._1();
List<FloatPoint> pts = Candidates.get(i)._2();
double min = Double.MAX_VALUE;
for(int j=0; j<pts.size(); j++)
{
double newCost = FunctionSet.distance(pt, pts.get(j));
if(min > newCost)
min = newCost;
}
output.add(new Tuple2<Integer, Double>(key, min));
}
return output;
}
}
public static class AssignPoint implements PairFunction<FloatPoint, Integer,
FloatPoint> {
private int coreNum=-1;
public AssignPoint(int coreNum) {
// TODO Auto-generated constructor stub
this.coreNum = coreNum;
}
#Override
public Tuple2<Integer, FloatPoint> call(FloatPoint value) throws
Exception {
int key = (int)(Math.random()*coreNum);
value.setKey(key);
return new Tuple2(key,value);
}
}
public static class ModifiedWeiszfeld implements
Function<Iterable<FloatPoint>, List<FloatPoint>>{
private List<FloatPoint> medoids = null;
public ModifiedWeiszfeld(JavaRDD<FloatPoint> bestSeed) {
this.medoids = bestSeed.collect();
}
#Override
public List<FloatPoint> call(Iterable<FloatPoint> values) throws
Exception {
List<FloatPoint> localDataSet = new ArrayList<FloatPoint>();
for(FloatPoint pt : values)
localDataSet.add(pt);
for(FloatPoint pt: medoids)
localDataSet.add(pt);
List<FloatPoint> finalMedoid = null;
finalMedoid = Algorithms.refinement(localDataSet, medoids, 0.01);
return finalMedoid;
}
}
}
i run this source code. this work has finished job 3. but , job 4 is starting .error is occuring.

containsKey is returning true while expecting false

import java.util.HashMap;
public class Chapter1_Problem_1_1 {
public static void main(String[] args) {
String str = "bacdee";
int j = 0;
for(int i=0; i< str.length(); i++) {
char ch = str.charAt(i);
String s = new String(new char[] {ch});
HashMap<String, Integer> map = new HashMap<String, Integer>();
if (map.containsKey(s)) {
System.out.println("false");
} else {
map.put(s, j++);
System.out.println("true:: " + s);
}
}
}
}
In the above code, I am getting containskey as true for the last char "e" not sure why, it should be false; any ideas why this is happening?

how to generate sequence number using c# in window application

private string GenerateID()
{
}
private void auto()
{
AdmissionNo.Text = "A-" + GenerateID();
}
with prefix of A like below
A-0001
A-0002 and so on .
You can use below code.
private string GenerateId()
{
int lastAddedId = 8; // get this value from database
string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
return demo;
// it will return 0009
}
private void Auto()
{
AdmissionNo.Text = "A-" + GenerateId();
// here it will set the text as "A-0009"
}
Look at this
public class Program
{
private static int _globalSequence;
static void Main(string[] args)
{
_globalSequence = 0;
for (int i = 0; i < 10; i++)
{
Randomize(i);
Console.WriteLine("----------------------------------------->");
}
Console.ReadLine();
}
static void Randomize(int seed)
{
Random r = new Random();
if (_globalSequence == 0) _globalSequence = r.Next();
Console.WriteLine("Random: {0}", _globalSequence);
int localSequence = Interlocked.Increment(ref _globalSequence);
Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
}
}
Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:
public sealed class Sequence
{
private int value = 0;
public Sequence(string prefix)
{
this.Prefix = prefix;
}
public string Prefix { get; }
public int GetNextValue()
{
return System.Threading.Interlocked.Increment(ref this.value);
}
public string GetNextNumber()
{
return $"{this.Prefix}{this.GetNextValue():0000}";
}
}
This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.

Algorithm for Hyper String

I want to know about the algorithm to solve HyperString Problem.
You can find the description at https://www.hackerrank.com/challenges/hyper-strings.
Can it be solved by dynamic programming?
Any help would be highly apreciated.
public class HyperString {
//Abubaker Tagelsir
private static int n,m,sum=1;
private static void temp(String u,String []d)
{
for(int i=0 ; i<d.length;i++)
{
if((u.length()+d[i].length())<=m)
{
sum++;
temp(u+d[i],d);
}
}
}
private static int Input3(String [] d)
{
sum +=d.length;
for(int i=0;i<d.length;i++){
for(int j=0;j<d.length;j++)
{
if((d[i].length()+d[j].length())<=m)
{
sum++;
temp(d[i]+d[j],d);
}
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String h = sc.nextLine();
StringTokenizer tz = new StringTokenizer(h);
String h1 = tz.nextToken();
n = Integer.parseInt(h1);
String h2 = tz.nextToken();
m = Integer.parseInt(h2);
//Input2();
String [] d = new String[n];
for(int i=0;i<n;i++)
{
d[i] = sc.nextLine();
}
System.out.println(Input3(d));
}
}

Trying to create a package for my java application

I am in the process of putting together a simple RPG game engine in java. At this point everything works fine while all my classes are in one directory. Basically, I know I am going to end up with a heap of files and wish to organise them into a package structure. I followed the directions at http://www.jarticles.com/package/package_eng.html but can't seem to make the magic happen. The two classes posted are the least dependent of the lot and I figure if I can get these working then the rest shouldn't be a drama. For the record I am using openJDK in Leeenux (remix of Ubuntu netbook Remix)
First class
package adventure.engine;
import java.util.*;
public class Inventory
{
ArrayList itemList = new ArrayList();
public Inventory()
{
}
public void addItem()
{
}
public void removeItem()
{
}
}
And the second:
package adventure.engine;
import adventure.engine.*;
public class PlayerCharacter
{
private String name = "Player";
private String race;
private String plrClass;
private int level;
private int xp;
private int levelXp;
private Inventory inventory = new Inventory();
//---------
//Abilities
//---------
private static final String[] abilitiesList = {"Strength",
"Dexterity",
"Constitution",
"Intelligence",
"Wisdom",
"Charisma"};
private int[] abilitiesValues = new int[abilitiesList.length];
//------
//Skills
//------
private static final String[] skillsList = {"Acrobatics" , "Insight",
"Arcana" , "Intimidate",
"Athletics" , "Nature",
"Bluff" , "Perception",
"Diplomacy" , "Religion",
"Dungeoneering" , "Stealth",
"Endurance" , "Streetwise",
"Heal" , "Thievery",
"History"};
private int[] skillsValues = new int[skillsList.length];
//***********
//Constructor
//***********
public PlayerCharacter()
{
level = 1;
xp = 0;
levelXp = 1000;
setAbility("Strength", 8);
setAbility("Dexterity", 10);
setAbility("Constitution", 10);
setAbility("Intelligence", 10);
setAbility("Wisdom", 10);
setAbility("Charisma", 10);
} //public PlayerSheet()
//*************
//Class Methods
//*************
public void addXp(int val)
{
xp += val;
if (xp >= levelXp)
{
level++;
xp -= levelXp;
//levelXp += ;
}
} //public void addXp(int val)
public void updateSkills()
{
}
//Mutators
public void setName(String n)
{
name = n;
}
public void setLevel(int l)
{
level = l;
}
public void setRace(String r)
{
race = r;
}
public void setXP(int x)
{
xp = x;
}
public void setClass(String c)
{
plrClass = c;
}
//set ability value by name
public void setAbility(String a, int val)
{
for(int i = 0; i < abilitiesList.length; i++)
{
if(abilitiesList[i].compareTo(a) == 0)
{
abilitiesValues[i] = val;
}
}
}
//set ability by index
public void setAbility(int index, int val)
{
abilitiesValues[index] = val;
}
//set skill by name
public void setSkill(String name, int val)
{
for(int i = 0; i < skillsList.length; i++)
{
if(skillsList[i].compareTo(name) == 0)
{
skillsValues[i] = val;
}
}
}
//set skill by index
public void setSkill(int index, int val)
{
skillsValues[index] = val;
}
//Accessors
public static String[] getAbilityList()
{
return abilitiesList;
}
public static String[] getSkillsList()
{
return skillsList;
}
//retrieve an ability value by name
public int getAbility(String a)
{
int val = 0;
for(int i = 0; i < abilitiesList.length; i++)
{
if(abilitiesList[i].compareTo(a) == 0)
{
val = abilitiesValues[i];
break;
}
}
return val;
}
//retrieve an ability value by index number
public int getAbility(int i)
{
return abilitiesValues[i];
}
public int getSkill(String s)
{
int val = 0;
for(int i = 0; i < skillsList.length; i++)
{
if(skillsList[i].compareTo(s) == 0)
{
val = skillsValues[i];
break;
}
}
return val;
}
public int getSkill(int i)
{
return skillsValues[i];
}
public String getName()
{
return name;
}
public String getRace()
{
return race;
}
public String getPlrClass()
{
return plrClass;
}
public int getLevel()
{
return level;
}
public int getXP()
{
return xp;
}
public int getLevelXP()
{
return levelXp;
}
} //public class PlayerCharacter
Classes reside in /home/user/Java/adventure/engine
Output from echo $classpath is /home/james/Java:/.:
when I attempt to compile the second class I get the following error:
PlayerCharacter.java:18: cannot find symbol
symbol : class Inventory
location: class adventure.engine.PlayerCharacter
private Inventory inventory = new Inventory();
^
PlayerCharacter.java:18: cannot find symbol
symbol : class Inventory
location: class adventure.engine.PlayerCharacter
private Inventory inventory = new Inventory();
Any feedback on this would be greatly appreciated.How to solve this?
Two things.
1) You might not have compiled Inventory
2) PlayerCharacter and Inventory are in same package. So there is no need to import.
You should be compiling them as
javac adventure/engine/Inventory.java
javac adventure/engine/PlayerCharacter.java

Resources